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
8.0 KiB167 linesraw
1"""The RAM figure the Terminal's tools read (strata_control/cgroup_memory.py; split_engine.ram_gib, tune_machine.memory,
2and setup's ram_gb through the same limit reader): inside a container the cgroup limit, outside it /proc/meminfo exactly
3as before.  Fake /proc and cgroup trees in a temporary folder; no container needed.
4"""
5import os
6import tempfile
7import unittest
8from pathlib import Path
9from unittest import mock
10
11from strata_control import cgroup_memory as C
12from strata_control import split_engine, tune_machine
13
14GIB = 1 << 30
15MIB = 1 << 20
16HOST_KB = 527_799_316            # a 503 GiB host, as /proc/meminfo shows it inside the rented container
17HOST_AVAIL_KB = 500_000_000
18POD_LIMIT = 61_998_571_520       # that container's memory.max: 57.74 GiB
19
20
21def stat(inactive=0, active=0, dirty=0, writeback=0, shmem=0, v1=False):
22    p = "total_" if v1 else ""
23    d, w = ("total_dirty", "total_writeback") if v1 else ("file_dirty", "file_writeback")
24    return (f"{p}anon 1000\n{p}file {inactive + active + shmem}\n{p}shmem {shmem}\n{p}inactive_anon {shmem}\n"
25            f"{p}active_file {active}\n{p}inactive_file {inactive}\n{d} {dirty}\n{w} {writeback}\n")
26
27
28class Tree:
29    def __init__(self, total_kb=HOST_KB, avail_kb=HOST_AVAIL_KB):
30        self.tmp = tempfile.TemporaryDirectory()
31        self.dir = Path(self.tmp.name)
32        (self.dir / "cg").mkdir()
33        self.put("meminfo", f"MemTotal:       {total_kb} kB\nMemFree:        1000 kB\nMemAvailable:   {avail_kb} kB")
34
35    def put(self, rel, text):
36        p = self.dir / rel
37        p.parent.mkdir(parents=True, exist_ok=True)
38        p.write_text(f"{text}\n")
39
40    def group(self, rel, limit=None, current=0, high=None, stat_text="", v1=False):
41        base = f"cg/memory/{rel}" if v1 else f"cg/{rel}"
42        if v1:
43            self.put(f"{base}/memory.limit_in_bytes", limit if limit is not None else 9223372036854771712)
44            self.put(f"{base}/memory.usage_in_bytes", current)
45        else:
46            self.put(f"{base}/memory.max", limit if limit is not None else "max")
47            self.put(f"{base}/memory.high", high if high is not None else "max")
48            self.put(f"{base}/memory.current", current)
49        self.put(f"{base}/memory.stat", stat_text)
50
51    def ram(self):
52        return C.ram_bytes(str(self.dir / "meminfo"), str(self.dir / "self_cgroup"), str(self.dir / "cg"))
53
54    def close(self):
55        self.tmp.cleanup()
56
57
58class RamBytes(unittest.TestCase):
59    def setUp(self):
60        self.t = Tree()
61
62    def tearDown(self):
63        self.t.close()
64
65    def test_v2_container_limit(self):
66        # the pod: 20 GiB used, of which 8 GiB clean file cache (5 active, 3 inactive) and 1 GiB of it dirty
67        self.t.put("self_cgroup", "0::/")
68        self.t.group(".", limit=POD_LIMIT, current=20 * GIB, stat_text=stat(inactive=3 * GIB, active=5 * GIB, dirty=GIB))
69        total, avail = self.t.ram()
70        self.assertEqual(total, POD_LIMIT)
71        self.assertEqual(avail, POD_LIMIT - (20 * GIB - 7 * GIB))
72
73    def test_shmem_is_not_credited(self):
74        self.t.put("self_cgroup", "0::/")
75        self.t.group(".", limit=24 * GIB, current=10 * GIB, stat_text=stat(inactive=2 * GIB, shmem=3 * GIB))
76        self.assertEqual(self.t.ram(), (24 * GIB, 24 * GIB - 8 * GIB))
77
78    def test_memory_high_counts_as_the_limit(self):
79        self.t.put("self_cgroup", "0::/")
80        self.t.group(".", limit=40 * GIB, high=30 * GIB, current=10 * GIB, stat_text=stat())
81        self.assertEqual(self.t.ram(), (30 * GIB, 20 * GIB))
82
83    def test_v1_container_limit(self):
84        self.t.put("self_cgroup", "4:memory:/docker/abc\n1:cpu,cpuacct:/docker/abc")
85        self.t.group("docker/abc", limit=32 * GIB, current=12 * GIB, stat_text=stat(inactive=GIB, active=GIB, v1=True), v1=True)
86        self.t.group("docker", v1=True)
87        self.t.group(".", v1=True)
88        self.assertEqual(self.t.ram(), (32 * GIB, 32 * GIB - 10 * GIB))
89
90    def test_limit_on_a_parent_level(self):
91        # the process's own group has no limit; its parent's 24 GiB is the one that holds (and its usage counts)
92        self.t.put("self_cgroup", "0::/box/job")
93        self.t.group(".")
94        self.t.group("box", limit=24 * GIB, current=18 * GIB, stat_text=stat(active=2 * GIB))
95        self.t.group("box/job", current=6 * GIB, stat_text=stat(active=GIB))
96        self.assertEqual(self.t.ram(), (24 * GIB, 24 * GIB - 16 * GIB))
97
98    def test_the_tighter_of_two_levels(self):
99        self.t.put("self_cgroup", "0::/box/job")
100        self.t.group(".")
101        self.t.group("box", limit=40 * GIB, current=36 * GIB, stat_text=stat())
102        self.t.group("box/job", limit=30 * GIB, current=10 * GIB, stat_text=stat())
103        self.assertEqual(self.t.ram(), (30 * GIB, 4 * GIB))
104
105    def test_no_limit_is_meminfo_exactly(self):
106        self.t.put("self_cgroup", "0::/user.slice/u.scope")
107        self.t.group(".")
108        self.t.group("user.slice", current=50 * GIB, stat_text=stat())
109        self.t.group("user.slice/u.scope", current=GIB, stat_text=stat())
110        self.assertEqual(self.t.ram(), (HOST_KB * 1024, HOST_AVAIL_KB * 1024))
111
112    def test_limit_at_or_above_memtotal_is_meminfo_exactly(self):
113        for limit in (HOST_KB * 1024, HOST_KB * 1024 + GIB):
114            self.t.put("self_cgroup", "0::/")
115            self.t.group(".", limit=limit, current=400 * GIB, stat_text=stat())
116            self.assertEqual(self.t.ram(), (HOST_KB * 1024, HOST_AVAIL_KB * 1024), limit)
117
118    def test_no_cgroup_files_is_meminfo_exactly(self):
119        self.t.put("self_cgroup", "0::/")
120        self.assertEqual(self.t.ram(), (HOST_KB * 1024, HOST_AVAIL_KB * 1024))
121
122    def test_container_free_never_above_the_hosts(self):
123        t = Tree(avail_kb=4 * MIB)            # the host has 4 GiB available; the container's room is larger
124        try:
125            t.put("self_cgroup", "0::/")
126            t.group(".", limit=24 * GIB, current=GIB, stat_text=stat())
127            self.assertEqual(t.ram(), (24 * GIB, 4 * GIB))
128        finally:
129            t.close()
130
131    def test_no_meminfo(self):
132        self.assertEqual(C.ram_bytes(str(self.t.dir / "none"), str(self.t.dir / "self_cgroup"), str(self.t.dir / "cg")),
133                         (None, None))
134
135    def test_limit_reader_matches_ram(self):
136        self.t.put("self_cgroup", "0::/box")
137        self.t.group(".")
138        self.t.group("box", limit=24 * GIB, current=GIB, stat_text=stat())
139        self.assertEqual(C.memory_limit(str(self.t.dir / "self_cgroup"), str(self.t.dir / "cg")), 24 * GIB)
140
141
142class Callers(unittest.TestCase):
143    """split_engine.ram_gib and tune_machine.memory give the helper's figures, in their units; outside a container the
144    same numbers as their earlier /proc/meminfo arithmetic."""
145
146    def test_split_engine_ram_gib(self):
147        with mock.patch.object(C, "ram_bytes", lambda: (POD_LIMIT, 13 * GIB)):
148            self.assertEqual(split_engine.ram_gib(), (POD_LIMIT / GIB, 13.0))
149        with mock.patch.object(C, "ram_bytes", lambda: (HOST_KB * 1024, HOST_AVAIL_KB * 1024)):
150            self.assertEqual(split_engine.ram_gib(), (HOST_KB / (1 << 20), HOST_AVAIL_KB / (1 << 20)))
151        with mock.patch.object(C, "ram_bytes", lambda: (None, None)):
152            self.assertEqual(split_engine.ram_gib(), (0.0, 0.0))
153
154    @unittest.skipIf(os.name == "nt", "the Linux branch of tune_machine.memory")
155    def test_tune_machine_memory(self):
156        with mock.patch.object(tune_machine.sys, "platform", "linux"), \
157                mock.patch.object(C, "ram_bytes", lambda: (HOST_KB * 1024, HOST_AVAIL_KB * 1024)):
158            self.assertEqual(tune_machine.memory(), {"total_mib": HOST_KB // 1024, "available_mib": HOST_AVAIL_KB // 1024})
159        with mock.patch.object(tune_machine.sys, "platform", "linux"), \
160                mock.patch.object(C, "ram_bytes", lambda: (POD_LIMIT, 13 * GIB)):
161            self.assertEqual(tune_machine.memory(), {"total_mib": POD_LIMIT // MIB, "available_mib": 13 * 1024})
162        with mock.patch.object(tune_machine.sys, "platform", "linux"), mock.patch.object(C, "ram_bytes", lambda: (None, None)):
163            self.assertEqual(tune_machine.memory(), {"total_mib": None, "available_mib": None})
164
165
166if __name__ == "__main__":
167    unittest.main()