okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-container-mem-core: memory checks that read a container's limit correctly6b63729a9

main
17.3 KiB394 linesraw
1#include "strata/core/conversation_memory.hpp"
2
3#include <algorithm>
4#include <atomic>
5#include <cstdio>
6#include <cstdlib>
7#include <charconv>
8#include <filesystem>
9#include <fstream>
10#include <limits>
11#include <sstream>
12#include <string>
13#include <system_error>
14#include <vector>
15
16#if defined(_WIN32)
17#ifndef NOMINMAX
18#define NOMINMAX
19#endif
20#include <windows.h>
21#elif defined(__APPLE__)
22#include <mach/mach.h>
23#include <sys/sysctl.h>
24#endif
25
26namespace strata::core {
27
28namespace fs = std::filesystem;
29
30CacheCredit cache_credit_from_stat(const std::string& stat, uint64_t current, bool v1) {
31    const char* inactive_key = v1 ? "total_inactive_file" : "inactive_file";
32    const char* active_key = v1 ? "total_active_file" : "active_file";
33    const char* dirty_key = v1 ? "total_dirty" : "file_dirty";
34    const char* writeback_key = v1 ? "total_writeback" : "file_writeback";
35    std::optional<uint64_t> inactive, active;
36    bool active_bad = false;
37    uint64_t dirty = 0, writeback = 0;
38    std::istringstream in(stat);
39    std::string line;
40    while (std::getline(in, line)) {
41        std::istringstream fields(line);
42        std::string key, value, extra;
43        if (!(fields >> key >> value) || (fields >> extra)) continue;
44        uint64_t* target = key == dirty_key ? &dirty : key == writeback_key ? &writeback : nullptr;
45        uint64_t n = 0;
46        const auto parsed = std::from_chars(value.data(), value.data() + value.size(), n);
47        const bool ok = parsed.ec == std::errc{} && parsed.ptr == value.data() + value.size();
48        if (key == inactive_key) { if (!ok || inactive) return {}; inactive = n; }
49        else if (key == active_key) { if (!ok || active) active_bad = true; else active = n; }
50        else if (target != nullptr) { if (!ok) return {}; *target = n; }
51    }
52    if (!inactive) return {};
53    auto clean = [&](uint64_t cached) {
54        uint64_t credit = std::min(cached, current);
55        credit = dirty >= credit ? 0 : credit - dirty;
56        credit = writeback >= credit ? 0 : credit - writeback;
57        return credit;
58    };
59    CacheCredit c;
60    c.inactive = clean(*inactive);
61    // an active_file that is missing or cannot be read adds nothing: the lists figure is then the inactive one
62    const uint64_t both = active && !active_bad ? (*active > UINT64_MAX - *inactive ? UINT64_MAX : *inactive + *active) : *inactive;
63    c.lists = clean(both);
64    return c;
65}
66
67bool mem_credit_inactive_only(const char* env_value) {
68    return env_value != nullptr && env_value[0] == '1';
69}
70
71uint64_t cache_credit_for_limit(const CacheCredit& credit, uint64_t limit, std::optional<uint64_t> mem_total, bool inactive_only,
72                                std::optional<uint64_t> own_mapped) {
73    if (inactive_only || !mem_total || limit >= *mem_total || !own_mapped) return credit.inactive;
74    return credit.lists > *own_mapped ? credit.lists - *own_mapped : 0;
75}
76
77ArenaCgroupRoom arena_cgroup_room(uint64_t limit, uint64_t current, const std::string& stat_text, std::optional<uint64_t> mem_total,
78                                  bool inactive_only) {
79    ArenaCgroupRoom r;
80    if (inactive_only || !mem_total || limit >= *mem_total) return r;
81    r.applies = true;
82    uint64_t credit = cache_credit_from_stat(stat_text, current, false).lists;   // <= current
83    credit -= std::min(credit / 2, limit / 64);
84    r.credit = credit;
85    const uint64_t used = current - credit;
86    r.room = used < limit ? limit - used : 0;
87    return r;
88}
89
90namespace {
91std::atomic<uint64_t> g_locked_own_file_bytes{0};
92}
93
94void set_locked_own_file_bytes(uint64_t bytes) { g_locked_own_file_bytes.store(bytes, std::memory_order_relaxed); }
95uint64_t locked_own_file_bytes() { return g_locked_own_file_bytes.load(std::memory_order_relaxed); }
96
97std::optional<uint64_t> own_evictable_mapped_bytes(const std::string& status_text, uint64_t locked_file_bytes) {
98    std::istringstream in(status_text);
99    std::string line;
100    std::optional<uint64_t> rss;
101    while (std::getline(in, line)) {
102        std::istringstream fields(line);
103        std::string key, value, unit, extra;
104        if (!(fields >> key) || key != "RssFile:") continue;
105        if (rss || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {};
106        uint64_t kb = 0;
107        const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb);
108        if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() || kb > UINT64_MAX / 1024) return {};
109        rss = kb * 1024;
110    }
111    if (!rss) return {};
112    return *rss > locked_file_bytes ? *rss - locked_file_bytes : 0;
113}
114
115namespace {
116
117std::atomic<uint64_t> g_memory_limit_bytes{0};
118
119// "<key> <n> kB", exactly once, nothing else on the line; the value in bytes.  Anything else is unknown.
120std::optional<uint64_t> meminfo_kb_bytes(std::istream& meminfo, const char* wanted) {
121    std::optional<uint64_t> result;
122    std::string line;
123    while (std::getline(meminfo, line)) {
124        std::istringstream fields(line);
125        std::string key, value, unit, extra;
126        if (!(fields >> key) || key != wanted) continue;
127        if (result || !(fields >> value >> unit) || unit != "kB" || (fields >> extra)) return {};
128        uint64_t kb = 0;
129        const auto parsed = std::from_chars(value.data(), value.data() + value.size(), kb);
130        if (parsed.ec != std::errc{} || parsed.ptr != value.data() + value.size() ||
131            kb > std::numeric_limits<uint64_t>::max() / 1024) return {};
132        result = kb * 1024;
133    }
134    if (meminfo.bad() || (meminfo.fail() && !meminfo.eof())) return {};
135    return result;
136}
137
138// One cgroup control file: absent (no such file), a number, "max", or unusable (unreadable, empty, not a number).
139struct Value {
140    enum Kind { absent, bad, max, number } kind = absent;
141    uint64_t n = 0;
142};
143
144Value read_value(const fs::path& path) {
145    std::error_code ec;
146    const bool there = fs::exists(path, ec);
147    if (ec) return {Value::bad, 0};
148    if (!there) return {};
149    std::ifstream file(path);
150    if (!file) return {Value::bad, 0};
151    char buf[64];
152    file.read(buf, sizeof buf);
153    if (file.bad()) return {Value::bad, 0};
154    size_t len = (size_t) file.gcount();
155    if (len == sizeof buf) return {Value::bad, 0};
156    while (len > 0 && (buf[len - 1] == '\n' || buf[len - 1] == '\r' || buf[len - 1] == ' ' || buf[len - 1] == '\t')) --len;
157    if (len == 0) return {Value::bad, 0};
158    if (len == 3 && std::string(buf, 3) == "max") return {Value::max, 0};
159    Value v{Value::number, 0};
160    const auto parsed = std::from_chars(buf, buf + len, v.n);
161    if (parsed.ec != std::errc{} || parsed.ptr != buf + len) return {Value::bad, 0};
162    return v;
163}
164
165// The reclaimable file cache of one group, from its memory.stat, in the two forms the guard uses
166// (cache_credit_from_stat in the header has the rules).  A memory.stat that is missing gives no credit - not an
167// unknown sample.
168CacheCredit reclaimable_cache(const fs::path& dir, uint64_t current, bool v1) {
169    std::ifstream stat(dir / "memory.stat");
170    if (!stat) return {};
171    std::ostringstream text;
172    text << stat.rdbuf();
173    return cache_credit_from_stat(text.str(), current, v1);
174}
175
176// What the cgroup files say: every finite limit with the usage charged against it (and the cache credits of that
177// group), and the usage and credit of the topmost visible group (the root of this namespace - what a container's own
178// limit is measured over).
179struct CgroupScan {
180    struct Limit { uint64_t limit, current; CacheCredit credit; };
181    std::vector<Limit> limits;
182    std::optional<uint64_t> root_current;
183    uint64_t root_credit = 0;
184    bool any_files = false;
185};
186
187// `dirs` runs from the top visible group down to the process's own.  False when a file that is there cannot be used.
188bool scan_levels(const std::vector<fs::path>& dirs, const char* const* limit_names, size_t n_limits,
189                 const char* current_name, bool v1, CgroupScan& out) {
190    for (size_t i = 0; i < dirs.size(); ++i) {
191        const Value current = read_value(dirs[i] / current_name);
192        std::vector<Value> limits;
193        for (size_t k = 0; k < n_limits; ++k) limits.push_back(read_value(dirs[i] / limit_names[k]));
194        bool unusable = current.kind == Value::bad || current.kind == Value::max;
195        bool finite_limit = false;
196        for (const Value& v : limits) {
197            unusable = unusable || v.kind == Value::bad;
198            finite_limit = finite_limit || v.kind == Value::number;
199        }
200        if (unusable) return false;
201        if (current.kind == Value::absent) {
202            if (finite_limit) return false;   // a limit with no usage beside it: the room cannot be told
203            continue;                          // no memory controller at this level (e.g. the host's root group)
204        }
205        out.any_files = true;
206        const CacheCredit credit = reclaimable_cache(dirs[i], current.n, v1);
207        if (i == 0) { out.root_current = current.n; out.root_credit = credit.inactive; }
208        for (const Value& v : limits) {
209            if (v.kind != Value::number) continue;
210            if (v1 && v.n >= (1ull << 62)) continue;   // v1's "unlimited" is a number near 2^63
211            out.limits.push_back({v.n, current.n, credit});
212        }
213    }
214    return true;
215}
216
217// "/a/b/c" -> root, root/a, root/a/b, root/a/b/c, cut at the first one that is not a directory here: a container
218// without its own cgroup namespace sees its group's host path in /proc/self/cgroup, but only its own subtree under
219// the mount, so the deepest one that exists (at worst the mount itself) is the nearest group we can read.
220bool group_dirs(const fs::path& root, const std::string& group, std::vector<fs::path>& dirs) {
221    dirs.clear();
222    std::vector<std::string> names;
223    std::istringstream parts(group);
224    for (std::string part; std::getline(parts, part, '/');) {
225        if (part.empty()) continue;
226        if (part == "." || part == "..") return false;   // never walk out of the mount, nor trust a path that tries
227        names.push_back(part);
228    }
229    std::error_code ec;
230    if (!fs::is_directory(root, ec)) return true;   // nothing mounted: no cgroup terms
231    dirs.push_back(root);
232    fs::path at = root;
233    for (const std::string& part : names) {
234        at /= part;
235        if (!fs::is_directory(at, ec)) break;
236        dirs.push_back(at);
237    }
238    return true;
239}
240
241bool scan_cgroups(const MemoryProbePaths& paths, CgroupScan& out) {
242    std::optional<std::string> v2_group, v1_group;
243    std::ifstream groups(paths.self_cgroup);
244    if (!groups) {
245        v2_group = "/";   // no /proc/self/cgroup: the mount's own top group is still readable
246    } else {
247        std::string line;
248        while (std::getline(groups, line)) {
249            const size_t c1 = line.find(':'), c2 = c1 == std::string::npos ? c1 : line.find(':', c1 + 1);
250            if (c2 == std::string::npos) continue;
251            const std::string controllers = line.substr(c1 + 1, c2 - c1 - 1), group = line.substr(c2 + 1);
252            if (line.compare(0, c1, "0") == 0 && controllers.empty()) { v2_group = group; continue; }
253            std::istringstream names(controllers);
254            for (std::string name; std::getline(names, name, ',');)
255                if (name == "memory") v1_group = group;
256        }
257    }
258    std::vector<fs::path> dirs;
259    if (v2_group) {
260        if (!group_dirs(paths.cgroup_root, *v2_group, dirs)) return false;
261        static const char* const names[] = {"memory.max", "memory.high"};
262        if (!scan_levels(dirs, names, 2, "memory.current", false, out)) return false;
263    }
264    if (!out.any_files && v1_group) {   // cgroup v1: the memory controller's own tree
265        if (!group_dirs(fs::path(paths.cgroup_root) / "memory", *v1_group, dirs)) return false;
266        static const char* const names[] = {"memory.limit_in_bytes"};
267        if (!scan_levels(dirs, names, 1, "memory.usage_in_bytes", true, out)) return false;
268    }
269    return true;
270}
271
272std::optional<HostMemoryReading> combine(std::optional<uint64_t> available, std::optional<uint64_t> total,
273                                         const CgroupScan& cg, uint64_t explicit_limit, bool inactive_only,
274                                         std::optional<uint64_t> own_mapped) {
275    if (!available) return {};
276    HostMemoryReading r;
277    r.mem_available = *available;
278    r.available = *available;
279    r.source = MemorySource::meminfo;
280    r.limit = total.value_or(0);
281    r.current = total && *total >= *available ? *total - *available : 0;
282    for (const CgroupScan::Limit& l : cg.limits) {
283        const uint64_t credit = cache_credit_for_limit(l.credit, l.limit, total, inactive_only, own_mapped);
284        const uint64_t used = l.current - credit;   // credit <= current
285        const uint64_t room = l.limit > used ? l.limit - used : 0;
286        if (room < r.available) {
287            r.available = room;
288            r.source = MemorySource::cgroup;
289            r.limit = l.limit;
290            r.current = l.current;
291            r.credit = credit;
292        }
293    }
294    if (explicit_limit != 0) {
295        uint64_t used = 0, credit = 0;
296        if (cg.root_current) { used = *cg.root_current; credit = cg.root_credit; }
297        else if (total && *total >= *available) used = *total - *available;
298        else return {};
299        const uint64_t net = used - credit;
300        const uint64_t room = explicit_limit > net ? explicit_limit - net : 0;
301        if (room <= r.available) {   // a tie goes to the operator's number: it is the one that names the real cap
302            r.available = room;
303            r.source = MemorySource::flag;
304            r.limit = explicit_limit;
305            r.current = used;
306            r.credit = credit;
307        }
308    }
309    return r;
310}
311
312} // namespace
313
314const char* memory_source_name(MemorySource source) {
315    switch (source) {
316    case MemorySource::flag: return "flag";
317    case MemorySource::cgroup: return "cgroup";
318    default: return "meminfo";
319    }
320}
321
322std::optional<uint64_t> conversation_mem_available(std::istream& meminfo) {
323    return meminfo_kb_bytes(meminfo, "MemAvailable:");
324}
325
326void set_memory_limit_bytes(uint64_t bytes) { g_memory_limit_bytes.store(bytes, std::memory_order_relaxed); }
327uint64_t memory_limit_bytes() { return g_memory_limit_bytes.load(std::memory_order_relaxed); }
328
329std::optional<HostMemoryReading> sample_host_memory(const MemoryProbePaths& paths, uint64_t explicit_limit) {
330    std::ifstream avail_file(paths.meminfo);
331    if (!avail_file) return {};
332    const std::optional<uint64_t> available = conversation_mem_available(avail_file);
333    if (!available) return {};
334    std::ifstream total_file(paths.meminfo);
335    std::optional<uint64_t> total;
336    if (total_file) total = meminfo_kb_bytes(total_file, "MemTotal:");
337    CgroupScan cg;
338    if (!scan_cgroups(paths, cg)) {
339        // Without an operator cap the cgroup files are only an extra: the guard falls back to MemAvailable alone (what
340        // 0.1.41 used), once-warned.  With a cap the usage cannot be told, so the sample stays unknown.
341        if (explicit_limit != 0) return {};
342        static std::atomic<bool> warned{false};
343        if (!warned.exchange(true))
344            std::fprintf(stderr, "[strata] memory guard: the cgroup memory files could not be read or parsed, using "
345                                 "MemAvailable; set --memory-limit-mib to the container's limit\n");
346        cg = CgroupScan{};
347    }
348    std::optional<uint64_t> own_mapped;
349    if (!cg.limits.empty()) {   // only a limit can use it
350        std::ifstream status(paths.self_status);
351        if (status) {
352            std::ostringstream text;
353            text << status.rdbuf();
354            own_mapped = own_evictable_mapped_bytes(text.str(), locked_own_file_bytes());
355        }
356    }
357    return combine(available, total, cg, explicit_limit, mem_credit_inactive_only(std::getenv("STRATA_MEM_CREDIT_INACTIVE")), own_mapped);
358}
359
360std::optional<HostMemoryReading> sample_host_memory() {
361#if defined(_WIN32)
362    MEMORYSTATUSEX status{};
363    status.dwLength = sizeof status;
364    // #1607: the commit limit (RAM + page file) refuses an allocation while physical RAM is still free
365    if (!GlobalMemoryStatusEx(&status)) return {};
366    return combine(std::min<uint64_t>(status.ullAvailPhys, status.ullAvailPageFile), status.ullTotalPhys, CgroupScan{}, memory_limit_bytes(), true, std::nullopt);
367#elif defined(__linux__)
368    return sample_host_memory(MemoryProbePaths{}, memory_limit_bytes());
369#elif defined(__APPLE__)
370    // The rule of metal/src/engine/arena_budget.h's arena_avail(): free + purgeable pages, plus the inactive and speculative
371    // ones only up to the file-backed page count (other programs' inactive anonymous memory is what compresses or swaps).
372    vm_statistics64_data_t vs{};
373    mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
374    if (host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t) &vs, &count) != KERN_SUCCESS) return {};
375    uint64_t total = 0;
376    size_t len = sizeof total;
377    if (sysctlbyname("hw.memsize", &total, &len, nullptr, 0) != 0 || total == 0) return {};
378    const uint64_t pg = (uint64_t) vm_page_size;
379    const uint64_t available = ((uint64_t) vs.free_count + vs.purgeable_count) * pg +
380                               std::min<uint64_t>(((uint64_t) vs.inactive_count + vs.speculative_count) * pg,
381                                                  (uint64_t) vs.external_page_count * pg);
382    return combine(available, total, CgroupScan{}, memory_limit_bytes(), true, std::nullopt);
383#else
384    return {};
385#endif
386}
387
388std::optional<uint64_t> available_host_bytes() {
389    const auto reading = sample_host_memory();
390    if (!reading) return {};
391    return reading->available;
392}
393
394} // namespace strata::core