okami.mom/strata

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

Niko1221Merge f-027-gh-eng: GitHub engine items for 0.2.76ca60e9a0

main
9.6 KiB207 linesraw
1"""serve/lifeline.py: a process Strata starts ends when the process that started it ends, however that ends.
2
3    python -m unittest serve.test_lifeline
4
5Each case runs a small "server" process (a fresh interpreter) that starts a sleeping child through
6`lifeline.popen`, then ends that server the hard way (kill -9 / TerminateProcess), and checks that the child
7is gone. The mechanism under test is Windows' job object, Linux's PR_SET_PDEATHSIG, or the portable watcher
8(forced with STRATA_LIFELINE=watcher so it is proven on every POSIX box, not only on macOS).
9"""
10import json
11import os
12import signal
13import subprocess
14import sys
15import tempfile
16import textwrap
17import time
18import unittest
19from pathlib import Path
20
21ROOT = Path(__file__).resolve().parents[1]
22POSIX = os.name == "posix"
23
24SERVER = textwrap.dedent("""
25    import os, sys, time, threading, subprocess
26    sys.path.insert(0, {root!r})
27    from serve import lifeline
28    mode = sys.argv[1]
29    sleeper = [sys.executable, "-c", "import time; time.sleep(600)"]
30    out = {{"mechanism": lifeline.mechanism()}}
31    if mode == "thread":                       # started on a request thread that ends at once
32        box = []
33        t = threading.Thread(target=lambda: box.append(lifeline.popen(sleeper, "engine")))
34        t.start(); t.join()
35        child = box[0]
36    else:
37        child = lifeline.popen(sleeper, "engine")
38    out["child"] = child.pid
39    out["server"] = os.getpid()
40    print(__import__("json").dumps(out), flush=True)
41    if mode == "exit":                         # ends normally, the child still running
42        sys.exit(0)
43    time.sleep(600)
44""")
45
46
47def alive(pid: int) -> bool:
48    from strata_control import procs
49    return procs.start_token(pid) is not None
50
51
52class Lifeline(unittest.TestCase):
53    def setUp(self):
54        self.temp = tempfile.TemporaryDirectory(prefix="strata-lifeline-")
55        self.addCleanup(self.temp.cleanup)
56        self.env = {**os.environ, "LOCALAPPDATA": self.temp.name, "XDG_STATE_HOME": self.temp.name,
57                    "PYTHONPATH": str(ROOT)}
58        self.script = Path(self.temp.name) / "server.py"
59        self.script.write_text(SERVER.format(root=str(ROOT)), encoding="utf-8")
60        self.spawned = []
61        self.addCleanup(self._reap)
62
63    def _reap(self):
64        for pid in self.spawned:
65            if alive(pid):
66                try:
67                    os.kill(pid, signal.SIGTERM)
68                except OSError:
69                    pass
70
71    def launch(self, mode, **env):
72        proc = subprocess.Popen([sys.executable, str(self.script), mode], stdout=subprocess.PIPE, text=True,
73                                env={**self.env, **env})
74        info = json.loads(proc.stdout.readline())
75        self.spawned.append(info["child"])
76        self.addCleanup(lambda: proc.poll() is None and proc.kill())
77        return proc, info
78
79    def wait_gone(self, pid, seconds=15):
80        deadline = time.monotonic() + seconds
81        while time.monotonic() < deadline:
82            if not alive(pid):
83                return True
84            time.sleep(0.1)
85        return not alive(pid)
86
87    def hard_kill(self, proc):
88        if POSIX:
89            os.kill(proc.pid, signal.SIGKILL)
90        else:
91            proc.kill()
92        proc.wait(timeout=10)
93
94    def _killed_parent_takes_the_child(self, **env):
95        proc, info = self.launch("sleep", **env)
96        self.assertTrue(alive(info["child"]))
97        self.hard_kill(proc)
98        self.assertTrue(self.wait_gone(info["child"]), f"the child outlived a killed server ({info['mechanism']})")
99        return info["mechanism"]
100
101    def test_a_child_ends_when_its_server_is_killed(self):
102        self.assertIn(self._killed_parent_takes_the_child(), ("job", "pdeathsig", "watcher"))
103
104    @unittest.skipUnless(POSIX, "the portable watcher is the POSIX path")
105    def test_the_portable_watcher_ends_the_child_when_the_server_is_killed(self):
106        self.assertEqual(self._killed_parent_takes_the_child(STRATA_LIFELINE="watcher"), "watcher")
107
108    @unittest.skipUnless(POSIX, "the portable watcher is the POSIX path")
109    def test_the_watcher_token_does_not_change_with_the_child_state(self):
110        """The watcher's token has to be the child's START TIME, and nothing that moves while it runs.
111
112        The token used to come from `ps -o lstart=,stat=`, so it carried the state character as well.  A child
113        is R (running) for the first milliseconds of its life and then settles to S (sleeping); the token is
114        taken right after `popen`, so the watcher then compared 'S' against its 'R' token, decided the child
115        was not the one it had been told about, and exited WITHOUT signalling it.  That is the "child outlived
116        a killed server" failure, and it appeared or vanished depending on which state the spawn was sampled
117        in - which is why it read as a flake.  Sampled while the child spins (R) and again while it sleeps
118        (S), the token must be the same either way.
119        """
120        from serve import lifeline
121        from unittest import mock
122        # in-process popen() means procs.write_record() would use the REAL per-user state dir; setUp's env only
123        # reaches subprocesses. Keep this test's launch record in the temp dir like the other cases.
124        with mock.patch.dict(os.environ, {"XDG_STATE_HOME": self.temp.name, "LOCALAPPDATA": self.temp.name}):
125            child = lifeline.popen([sys.executable, "-c",
126                                    "import time\nend = time.time() + 1.5\nwhile time.time() < end:\n    pass\n"
127                                    "time.sleep(30)"], "engine")
128        self.spawned.append(child.pid)
129        self.addCleanup(lambda: child.poll() is None and child.kill())
130
131        def state():
132            """The child's state character, read independently of the code under test ('R' running, 'S' asleep)."""
133            out = subprocess.run(["ps", "-o", "stat=", "-p", str(child.pid)], capture_output=True, text=True).stdout
134            return out.strip()[:1]
135
136        while_spinning = lifeline._start_token(child.pid)
137        spinning_state = state()
138        time.sleep(2.0)                                        # asleep by now
139        while_sleeping = lifeline._start_token(child.pid)
140        sleeping_state = state()
141        self.assertEqual((spinning_state, sleeping_state), ("R", "S"),
142                         "the child did not go from running to sleeping, so this proves nothing about the token")
143        self.assertTrue(while_spinning and while_sleeping, (while_spinning, while_sleeping))
144        self.assertEqual(while_spinning, while_sleeping,
145                         "the token moved with the child's state, so the watcher would skip the kill")
146
147    @unittest.skipUnless(sys.platform.startswith("linux"), "PR_SET_PDEATHSIG is Linux")
148    def test_a_child_started_on_a_request_thread_outlives_that_thread_but_not_the_server(self):
149        proc, info = self.launch("thread")
150        self.assertEqual(info["mechanism"], "pdeathsig")
151        time.sleep(1.0)
152        self.assertTrue(alive(info["child"]), "the request thread ended and took the child with it")
153        self.hard_kill(proc)
154        self.assertTrue(self.wait_gone(info["child"]))
155
156    def test_a_server_that_exits_normally_leaves_nothing_behind(self):
157        proc, info = self.launch("exit")
158        proc.wait(timeout=15)
159        self.assertTrue(self.wait_gone(info["child"]), "end_children at exit must stop what is still running")
160
161    def test_the_child_is_recorded_while_it_runs_and_forgotten_after(self):
162        from strata_control import procs
163        proc, info = self.launch("sleep")
164        base = Path(self.temp.name) / "Strata" / "procs" if not POSIX else Path(self.temp.name) / "strata" / "procs"
165        record = base / f"{info['child']}.json"
166        deadline = time.monotonic() + 5
167        while not record.exists() and time.monotonic() < deadline:
168            time.sleep(0.05)
169        data = json.loads(record.read_text(encoding="utf-8"))
170        self.assertEqual((data["pid"], data["role"], data["parent"]["pid"]), (info["child"], "engine", info["server"]))
171        self.assertEqual(data["token"], procs.start_token(info["child"]))
172        self.hard_kill(proc)
173        self.assertTrue(self.wait_gone(info["child"]))
174
175
176if __name__ == "__main__":
177    unittest.main()
178
179
180STUBBORN = (
181    "import signal, sys, time\n"
182    "if hasattr(signal, 'SIGTERM'): signal.signal(signal.SIGTERM, signal.SIG_IGN)\n"
183    "print('READY 4096 stop', flush=True)\n"
184    "time.sleep(600)\n"          # never reads QUIT, never answers STOP, ignores SIGTERM
185)
186
187
188class HardFallback(unittest.TestCase):
189    """The clean stop has a deadline: an engine that ignores STOP, QUIT and SIGTERM is killed, and close() returns."""
190
191    def test_an_engine_that_ignores_everything_is_killed(self):
192        from unittest import mock
193        from serve import server
194        engine = server.StrataEngine("missing-executable", [], lazy=True)
195        engine.proc = subprocess.Popen([sys.executable, "-c", STUBBORN], stdin=subprocess.PIPE, stdout=subprocess.PIPE,
196                                       text=True, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
197        engine.proc.stdout.readline()
198        victim = engine.proc
199        t0 = time.monotonic()
200        with mock.patch.object(server, "ENGINE_QUIT_WAIT_S", 1), mock.patch.object(server, "ENGINE_TERM_WAIT_S", 1), \
201                mock.patch.object(server, "ENGINE_KILL_WAIT_S", 10):
202            engine.close()
203        self.assertLess(time.monotonic() - t0, 12)
204        self.assertIsNotNone(victim.poll(), "the engine is still running after close()")
205        self.assertIsNone(engine.proc)
206        if os.name == "posix":
207            self.assertEqual(victim.returncode, -signal.SIGKILL, "it ignored SIGTERM, so only the kill ended it")