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
6.7 KiB162 linesraw
1"""The RAM this process gets on Linux, read the way the engine reads it.
2
3Inside a container /proc/meminfo shows the host's memory; the container's cgroup limit is the RAM there is. The limit is
4the smallest of cgroup v2 memory.max and memory.high from the process's group up to the mount root (cut at the deepest
5level that is visible: a container without its own cgroup namespace sees its host path, but only its own subtree), or of
6cgroup v1 memory.limit_in_bytes when there are no v2 memory files.
7
8Under a limit below MemTotal the available figure is the limit less the group's usage, with clean file cache on the
9active and inactive lists counted as free again (memory.stat: active_file + inactive_file, bounded by the usage, less
10dirty and writeback pages; shmem and locked pages are on other lists), as the engine's memory guard counts it. Without
11a limit, or with a limit at or above MemTotal, both figures are /proc/meminfo's, as before.
12"""
13from __future__ import annotations
14
15import os
16
17SELF_CGROUP = "/proc/self/cgroup"
18CGROUP_ROOT = "/sys/fs/cgroup"
19MEMINFO = "/proc/meminfo"
20
21
22def _levels(root: str, group: str) -> list[str]:
23    """The cgroup directories from the mount `root` down to `group` ("/a/b"), cut at the first one that is not there."""
24    levels = [root]
25    at = root
26    for part in [p for p in group.split("/") if p]:
27        if part in (".", ".."):
28            return []
29        at = os.path.join(at, part)
30        if not os.path.isdir(at):
31            break
32        levels.append(at)
33    return levels if os.path.isdir(root) else []
34
35
36def _number(path: str, v1: bool = False) -> int | None:
37    """A cgroup number file: its value, or None for "max", an absent or unreadable file, or v1's "unlimited"."""
38    try:
39        with open(path) as stream:
40            text = stream.read().strip()
41    except OSError:
42        return None
43    if not text.isdigit():
44        return None
45    value = int(text)
46    if v1 and value >= 1 << 62:
47        return None
48    return value
49
50
51def limited_levels(self_cgroup: str = SELF_CGROUP, root: str = CGROUP_ROOT) -> list[tuple[int, str, bool]]:
52    """(limit in bytes, the level's directory, is cgroup v1) for every level of this process's cgroup that sets one."""
53    try:
54        with open(self_cgroup) as stream:
55            lines = stream.read().splitlines()
56    except OSError:
57        lines = ["0::/"]
58    v2_group = v1_group = None
59    for line in lines:
60        parts = line.split(":", 2)
61        if len(parts) != 3:
62            continue
63        if parts[0] == "0" and parts[1] == "":
64            v2_group = parts[2]
65        elif "memory" in parts[1].split(","):
66            v1_group = parts[2]
67    out: list[tuple[int, str, bool]] = []
68    v2_files = False
69    if v2_group is not None:
70        for level in _levels(root, v2_group):
71            if not os.path.exists(os.path.join(level, "memory.current")):
72                continue
73            v2_files = True
74            values = [v for v in (_number(os.path.join(level, n)) for n in ("memory.max", "memory.high")) if v is not None]
75            if values:
76                out.append((min(values), level, False))
77    if not v2_files and v1_group is not None:
78        for level in _levels(os.path.join(root, "memory"), v1_group):
79            value = _number(os.path.join(level, "memory.limit_in_bytes"), v1=True)
80            if value is not None:
81                out.append((value, level, True))
82    return out
83
84
85def memory_limit(self_cgroup: str = SELF_CGROUP, root: str = CGROUP_ROOT) -> int | None:
86    """The smallest memory limit (bytes) on this process's cgroup and its ancestors; None when no level sets one."""
87    limits = [limit for limit, _, _ in limited_levels(self_cgroup, root)]
88    return min(limits) if limits else None
89
90
91def clean_file_cache(stat_text: str, usage: int, v1: bool = False) -> int:
92    """Clean file cache on the active and inactive lists (bytes), bounded by the usage, from a memory.stat text.
93    0 when inactive_file is missing or unreadable; an active_file that cannot be read adds nothing."""
94    prefix = "total_" if v1 else ""
95    keys = {"inactive": prefix + "inactive_file", "active": prefix + "active_file",
96            "dirty": "total_dirty" if v1 else "file_dirty", "writeback": "total_writeback" if v1 else "file_writeback"}
97    seen: dict[str, int] = {}
98    active_bad = False
99    for line in stat_text.splitlines():
100        fields = line.split()
101        if len(fields) != 2:
102            continue
103        key, value = fields
104        name = next((k for k, v in keys.items() if v == key), None)
105        if name is None:
106            continue
107        ok = value.isdigit()
108        if name == "inactive":
109            if not ok or "inactive" in seen:
110                return 0
111        elif name == "active":
112            if not ok or "active" in seen:
113                active_bad = True
114                continue
115        elif not ok:
116            return 0
117        seen[name] = int(value)
118    if "inactive" not in seen:
119        return 0
120    cached = seen["inactive"] + (seen["active"] if "active" in seen and not active_bad else 0)
121    credit = min(cached, usage)
122    for name in ("dirty", "writeback"):
123        credit = max(credit - seen.get(name, 0), 0)
124    return credit
125
126
127def _level_room(limit: int, level: str, v1: bool) -> int:
128    usage = _number(os.path.join(level, "memory.usage_in_bytes" if v1 else "memory.current"))
129    if usage is None:
130        return limit
131    try:
132        with open(os.path.join(level, "memory.stat")) as stream:
133            stat_text = stream.read()
134    except OSError:
135        stat_text = ""
136    used = usage - clean_file_cache(stat_text, usage, v1)
137    return limit - used if used < limit else 0
138
139
140def ram_bytes(meminfo: str = MEMINFO, self_cgroup: str = SELF_CGROUP, root: str = CGROUP_ROOT) -> tuple[int | None, int | None]:
141    """(total, available) bytes of RAM for this process on Linux; None for a figure /proc/meminfo does not give (and
142    both None where there is no /proc/meminfo)."""
143    info: dict[str, int] = {}
144    try:
145        with open(meminfo, encoding="ascii") as stream:
146            for line in stream:
147                key, _, rest = line.partition(":")
148                if key in ("MemTotal", "MemAvailable"):
149                    info[key] = int(rest.split()[0]) * 1024
150    except (OSError, ValueError, IndexError):
151        return None, None
152    total, available = info.get("MemTotal"), info.get("MemAvailable")
153    if total is None:
154        return None, available
155    mem_total = total
156    for limit, level, v1 in limited_levels(self_cgroup, root):
157        if limit >= mem_total:          # not a container's limit: /proc/meminfo's figures stand
158            continue
159        total = min(total, limit)
160        if available is not None:
161            available = min(available, _level_room(limit, level, v1))
162    return total, available