okami.mom/strata

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

Niko1221Merge main 7726f80cb (local, 11-10 14:08) into f-own-int714ff8242

main
16.2 KiB325 linesraw
1"""Leftover detection: a process is ended only when it is exactly what Strata recorded and its starter is gone."""
2
3import json
4import os
5import subprocess
6import sys
7import tempfile
8import time
9import unittest
10from pathlib import Path
11from unittest import mock
12
13from strata_control import procs
14
15SLEEP = [sys.executable, "-c", "import time; time.sleep(120)"]
16NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
17
18
19class Procs(unittest.TestCase):
20    def setUp(self):
21        self.temp = tempfile.TemporaryDirectory(prefix="strata-procs-")
22        self.addCleanup(self.temp.cleanup)
23        patcher = mock.patch.dict(os.environ, {"LOCALAPPDATA": self.temp.name, "XDG_STATE_HOME": self.temp.name})
24        patcher.start()
25        self.addCleanup(patcher.stop)
26        self.started = []
27        self.addCleanup(self._kill_all)
28
29    def _kill_all(self):
30        for proc in self.started:
31            if proc.poll() is None:
32                proc.kill()
33            proc.wait(timeout=10)
34
35    def sleeper(self):
36        proc = subprocess.Popen(SLEEP, creationflags=NO_WINDOW)
37        self.started.append(proc)
38        deadline = time.monotonic() + 10
39        while procs.identify(proc.pid) is None and time.monotonic() < deadline:
40            time.sleep(0.05)
41        return proc
42
43    def recorded_pair(self):
44        """(starter, child, record): a recorded child of a starter that is then ended."""
45        starter, child = self.sleeper(), self.sleeper()
46        self.assertIsNotNone(procs.write_record(child.pid, "engine", profile="app-1", parent_pid=starter.pid))
47        return starter, child
48
49    def gone(self, proc, seconds=15):
50        try:
51            proc.wait(timeout=seconds)
52            return True
53        except subprocess.TimeoutExpired:
54            return False
55
56    def test_a_child_whose_starter_is_gone_is_a_leftover_and_is_ended(self):
57        starter, child = self.recorded_pair()
58        self.assertEqual(procs.leftovers()[0], [], "its starter is alive: not a leftover")
59        starter.kill(); starter.wait(timeout=10)
60        found, unverifiable = procs.leftovers()
61        self.assertEqual([r["pid"] for r in found], [child.pid])
62        self.assertEqual(unverifiable, [])
63        result = procs.end_leftovers(grace=2)
64        self.assertEqual([r["pid"] for r in result["ended"]], [child.pid])
65        self.assertTrue(self.gone(child))
66        self.assertEqual(procs.records(), [], "the record goes with the process")
67
68    def test_a_child_with_a_live_starter_is_never_touched(self):
69        starter, child = self.recorded_pair()
70        result = procs.end_leftovers(grace=1)
71        self.assertEqual((result["ended"], result["stuck"]), ([], []))
72        self.assertIsNone(child.poll())
73
74    def test_a_reused_pid_is_not_the_recorded_process(self):
75        starter, child = self.recorded_pair()
76        path = procs.procs_dir() / f"{child.pid}.json"
77        record = json.loads(path.read_text(encoding="utf-8"))
78        record["token"] = "x:not-this-process"                  # what a later process with the same number looks like
79        path.write_text(json.dumps(record), encoding="utf-8")
80        starter.kill(); starter.wait(timeout=10)
81        result = procs.end_leftovers(grace=1)
82        self.assertEqual((result["ended"], result["stuck"]), ([], []))
83        self.assertIsNone(child.poll(), "a stranger with the recorded PID must be left alone")
84        self.assertEqual(procs.records(), [], "the stale record is dropped")
85
86    def test_the_same_start_time_with_another_command_line_is_not_ended(self):
87        starter, child = self.recorded_pair()
88        path = procs.procs_dir() / f"{child.pid}.json"
89        record = json.loads(path.read_text(encoding="utf-8"))
90        record["cmd"] = [sys.executable, "-c", "something else"]
91        path.write_text(json.dumps(record), encoding="utf-8")
92        starter.kill(); starter.wait(timeout=10)
93        result = procs.end_leftovers(grace=1)
94        self.assertEqual((result["ended"], result["stuck"]), ([], []))
95        self.assertIsNone(child.poll())
96
97    def test_a_profile_filter_only_ends_that_profiles_leftovers(self):
98        starter, child = self.recorded_pair()
99        other_starter, other = self.sleeper(), self.sleeper()
100        procs.write_record(other.pid, "engine", profile="app-2", parent_pid=other_starter.pid)
101        starter.kill(); other_starter.kill()
102        starter.wait(timeout=10); other_starter.wait(timeout=10)
103        result = procs.end_leftovers(profile="app-1", grace=2)
104        self.assertEqual([r["pid"] for r in result["ended"]], [child.pid])
105        self.assertIsNone(other.poll(), "another profile's leftover is not part of this stop")
106
107    def test_garbage_in_the_records_folder_is_ignored(self):
108        base = procs.procs_dir()
109        (base / "1.json").write_text("{not json", encoding="utf-8")
110        (base / "2.json").write_text(json.dumps({"schema": 1, "pid": "no"}), encoding="utf-8")
111        (base / "3.json").write_text("x" * 40000, encoding="utf-8")
112        self.assertEqual(procs.records(), [])
113        self.assertEqual(procs.end_leftovers()["ended"], [])
114
115    def test_an_engine_orphan_of_this_executable_is_found_and_a_live_one_is_not(self):
116        # an "engine": this interpreter running --serve; its starter is gone after the middle process exits
117        code = ("import subprocess,sys; p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(120)','--serve'],"
118                "stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,"
119                "creationflags=%d); print(p.pid, flush=True)" % NO_WINDOW)
120        middle = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, timeout=30)
121        orphan_pid = int(middle.stdout.split()[0])
122        self.addCleanup(lambda: procs.start_token(orphan_pid) and os.kill(orphan_pid, 9))
123        deadline = time.monotonic() + 10
124        while procs.identify(orphan_pid) is None and time.monotonic() < deadline:
125            time.sleep(0.05)
126        live = subprocess.Popen([*SLEEP, "--serve"], creationflags=NO_WINDOW)
127        self.started.append(live)
128        deadline = time.monotonic() + 10
129        while procs.identify(live.pid) is None and time.monotonic() < deadline:
130            time.sleep(0.05)
131        found = [i.pid for i in procs.orphans_of(sys.executable)]
132        self.assertIn(orphan_pid, found)
133        self.assertNotIn(live.pid, found, "this test process started it: a live parent")
134        self.assertEqual(procs.orphans_of(str(Path(sys.executable).with_name("not-the-engine"))), [])
135        ended = procs.end_orphans(sys.executable, grace=2)
136        self.assertIn(orphan_pid, [e["pid"] for e in ended])
137        self.assertIsNone(live.poll())
138        self.assertIsNone(procs.start_token(orphan_pid))
139
140class SubreaperOrphans(unittest.TestCase):
141    """An engine adopted by `systemd --user` is an orphan (#3254), and a dying process is waited for by its start token."""
142
143    class Gone(Exception):
144        pass
145
146    def fake_psutil(self, ancestors, parent_name):
147        class Err(Exception):
148            pass
149
150        class NoSuch(Err):
151            pass
152
153        def proc(pid, name, ppid=1):
154            info = {"pid": pid, "ppid": ppid, "cmdline": ["engine", "--serve"], "create_time": 100.0}
155            return mock.Mock(pid=pid, **{"name.return_value": name, "exe.return_value": "/x/engine", "info": info,
156                                         "as_dict.return_value": info})
157
158        me = mock.Mock(**{"parents.return_value": [proc(p, n) for p, n in ancestors]})
159        engine = proc(7000, "engine", ppid=5000)
160        parent = proc(5000, parent_name)
161        parent.create_time.return_value = 50.0
162        parent.status.return_value = "running"
163        fake = mock.Mock(Error=Err, NoSuchProcess=NoSuch, STATUS_ZOMBIE="zombie")
164        fake.Process.side_effect = lambda pid=None: me if pid is None else parent
165        fake.process_iter.return_value = [engine]
166        return fake
167
168    def found(self, ancestors, parent_name):
169        fake = self.fake_psutil(ancestors, parent_name)
170        with mock.patch.object(procs, "psutil", fake), mock.patch.object(procs, "same_file", return_value=True), \
171                mock.patch.object(procs, "identify", side_effect=lambda pid: ("ident", pid)):
172            return procs.orphans_of("/x/engine")
173
174    def test_an_engine_adopted_by_systemd_user_is_an_orphan_even_when_it_is_an_ancestor_of_the_terminal(self):
175        # systemd --user (pid 5000) is an ancestor of every desktop terminal and adopts what loses its parent
176        self.assertEqual(self.found([(5000, "systemd"), (6000, "bash")], "systemd"), [("ident", 7000)])
177
178    def test_an_engine_whose_parent_is_a_real_ancestor_is_not_an_orphan(self):
179        # started by this server's own shell: not touched
180        self.assertEqual(self.found([(5000, "bash"), (6000, "tmux")], "bash"), [])
181
182    def test_ending_waits_on_the_start_token_not_on_an_empty_command_line(self):
183        record = {"pid": 4242, "token": "t1", "cmd": ["engine", "--serve"]}
184        answers = ["t1", "t1"]                                   # still exiting twice, then gone
185        def token(pid):
186            return answers.pop(0) if answers else None
187        with mock.patch.object(procs, "WINDOWS", False), mock.patch.object(procs, "is_same", side_effect=[True, False, False]) as same, \
188                mock.patch.object(procs, "_signal_verified"), mock.patch.object(procs, "start_token", side_effect=token), \
189                mock.patch.object(procs, "drop_record"), mock.patch.object(procs.time, "sleep"):
190            self.assertEqual(procs.end_one(record, grace=5), "ended")
191        self.assertGreaterEqual(same.call_count, 1)
192
193    def slow_exit(self, exits_after, **kw):
194        """end_one of a process that is still there `exits_after` virtual seconds after the kill (a fake clock)."""
195        record = {"pid": 4243, "token": "t1", "cmd": ["engine", "--serve"]}
196        now = [0.0]
197        said = []
198
199        def sleep(s):
200            now[0] += s
201
202        def token(pid):
203            return "t1" if now[0] < exits_after else None
204        with mock.patch.object(procs, "WINDOWS", False), mock.patch.object(procs, "is_same", side_effect=lambda *a: token(0) is not None), \
205                mock.patch.object(procs, "_signal_verified"), mock.patch.object(procs, "start_token", side_effect=token), \
206                mock.patch.object(procs, "drop_record"), mock.patch.object(procs.signal, "SIGKILL", 9, create=True), \
207                mock.patch.object(procs.time, "sleep", side_effect=sleep), \
208                mock.patch.object(procs.time, "monotonic", side_effect=lambda: now[0]):
209            return procs.end_one(record, say=said.append, **kw), said
210
211    def test_an_engine_that_needs_longer_than_ten_seconds_to_give_its_memory_back_is_waited_for(self):
212        # #4051: 50 GiB of pinned memory is released by the kernel after the signal; the next engine started beside it
213        outcome, _ = self.slow_exit(25.0)                              # the old limit: 8 s grace + 10 s
214        self.assertEqual(outcome, "stuck")
215        outcome, said = self.slow_exit(40.0, settle=120.0)
216        self.assertEqual(outcome, "ended")
217        self.assertTrue(said and "still waiting for process 4243" in said[0], said)
218        self.assertEqual(self.slow_exit(40.0, settle=10.0)[0], "stuck")
219
220
221class WindowsOrphanScan(unittest.TestCase):
222    """orphans_of on Windows reads names first and a command line only where the name can be the engine's file: 257 processes took
223    4-9 s at every server start when every command line was read (30-150 ms for each protected process that refuses it)."""
224
225    ENGINE = r"C:\Strata\engine\strata-vision-hip.exe"
226    OTHER = r"C:\Old\engine\strata-vision-hip.exe"
227
228    def table(self):
229        e, o = self.ENGINE, self.OTHER
230        # pid: (name or an exception, exe, cmdline or an exception)
231        return {
232            101: ("strata-vision-hip.exe", e, [e, "--serve"]),        # an orphan
233            102: ("STRATA-VISION-HIP.EXE", e, [e, "--serve"]),        # upper case
234            103: ("STRATA~1.EXE", e, [e, "--serve"]),                 # started through its 8.3 path
235            104: (PermissionError, e, [e, "--serve"]),                # the name cannot be read: read in full
236            105: ("svchost.exe", r"C:\Windows\System32\svchost.exe", PermissionError),
237            106: ("lsass.exe", r"C:\Windows\System32\lsass.exe", PermissionError),
238            107: ("strata-vision-hip.exe", o, [o, "--serve"]),        # another installation's engine
239            108: ("strata-vision-hip.exe", e, [e]),                   # not serving
240            109: ("chrome.exe", r"C:\Chrome\chrome.exe", ["chrome.exe", "--serve"]),
241        }
242
243    def fake_psutil(self, table, asked):
244        class Err(Exception):
245            pass
246
247        class NoSuch(Err):
248            pass
249
250        class Denied(Err):
251            pass
252
253        def read(pid, attr):
254            name, exe, cmd = table[pid]
255            value = {"pid": pid, "ppid": 4242, "create_time": 100.0, "name": name, "cmdline": cmd}[attr]
256            if attr == "cmdline":
257                asked.append(pid)
258            if isinstance(value, type) and issubclass(value, Exception):
259                raise Denied()
260            return value
261
262        def as_dict(pid, attrs):
263            out = {}
264            for a in attrs:
265                try:
266                    out[a] = read(pid, a)
267                except Denied:
268                    out[a] = None                                    # as psutil: a refused value is None
269            return out
270
271        def proc(pid, attrs):
272            p = mock.Mock(pid=pid, info=as_dict(pid, attrs))
273            p.as_dict.side_effect = lambda attrs=None: as_dict(pid, attrs)
274            p.exe.side_effect = lambda: table[pid][1]
275            return p
276
277        def process(pid=None):
278            if pid is None:
279                return mock.Mock(**{"parents.return_value": []})
280            raise NoSuch()                                           # every parent (4242) is gone: an orphan
281
282        fake = mock.Mock(Error=Err, NoSuchProcess=NoSuch, STATUS_ZOMBIE="zombie")
283        fake.Process.side_effect = process
284        fake.process_iter.side_effect = lambda attrs: [proc(pid, attrs) for pid in table]
285        return fake
286
287    def scan(self, windows, table=None):
288        table = table or self.table()
289        asked = []
290        same = lambda a, b: bool(a) and bool(b) and a.lower() == b.lower()   # noqa: E731
291        with mock.patch.object(procs, "psutil", self.fake_psutil(table, asked)), mock.patch.object(procs, "WINDOWS", windows), \
292                mock.patch.object(procs, "same_file", side_effect=same), mock.patch.object(procs, "_short_name", return_value=None), \
293                mock.patch.object(procs, "identify", side_effect=lambda pid: ("ident", pid)):
294            found = sorted(i[1] for i in procs.orphans_of(self.ENGINE))
295        return found, asked
296
297    def test_the_same_orphans_as_reading_every_process(self):
298        new, _ = self.scan(windows=True)
299        old, _ = self.scan(windows=False)                            # the full read, as before (and as Linux and macOS still do)
300        self.assertEqual(new, old)
301        self.assertEqual(new, [101, 102, 103, 104])
302
303    def test_a_process_that_cannot_be_the_engine_is_never_asked_for_its_command_line(self):
304        _, asked = self.scan(windows=True)
305        self.assertEqual(sorted(asked), [101, 102, 103, 104, 107, 108])
306        _, asked_before = self.scan(windows=False)
307        self.assertEqual(sorted(asked_before), sorted(self.table()))
308
309    def test_the_files_own_short_name_matches(self):
310        self.assertTrue(procs._name_may_be("SVIHIP~2.EXE", "strata-vision-hip.exe", "svihip~2.exe"))
311        self.assertTrue(procs._name_may_be("STRATA~3.EXE", "strata-vision-hip.exe", None))
312        self.assertFalse(procs._name_may_be("svchost.exe", "strata-vision-hip.exe", None))
313        self.assertFalse(procs._name_may_be("OTHER~1.EXE", "strata-vision-hip.exe", None))
314
315    def test_a_hard_link_under_another_name_is_left_to_the_full_read_only_off_windows(self):
316        # The full read matches any name that is the same file (os.path.samefile); the name filter does not. Strata never links an
317        # engine under another name (setup's links are model files under their own name), so this is a hand-made case.
318        e = self.ENGINE
319        table = {201: ("my-engine.exe", e, [e, "--serve"])}
320        self.assertEqual(self.scan(windows=False, table=table)[0], [201])
321        self.assertEqual(self.scan(windows=True, table=table)[0], [])
322
323
324if __name__ == "__main__":
325    unittest.main()