okami.mom/strata

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

Niko1221Merge main 6c642df75 into f-own-int (round 16: network waits, robustness, Windows kill-on-close job start, GitHub and transfer fixes)cd9745050

main
7.8 KiB159 linesraw
1"""#4260: `strata bench run --profile` ends the engine it started, with the program it started, and says so only when something is left.
2
3The engine tree is the server (`strata serve`), the engine it starts and whatever those start. On Windows the tree is put in a job object this run owns,
4so a per-process `taskkill` that is refused ("Access is denied" on a tree this very user started) no longer leaves it running; on Linux and macOS it is the
5process group. An unrelated process with the same program name is never touched.
6
7    python -m pytest tests/terminal/test_bench_stop.py
8"""
9import os
10import subprocess
11import sys
12import tempfile
13import time
14import unittest
15from pathlib import Path
16from unittest import mock
17
18from strata_cli import bench_standard
19
20WINDOWS = os.name == "nt"
21PARENT = ("import subprocess, sys, time\n"
22          "kid = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'])\n"
23          "open(sys.argv[1], 'w').write(str(kid.pid))\n"
24          "time.sleep(120)\n")
25
26
27def alive(pid: int) -> bool:
28    if WINDOWS:
29        from strata_control import winproc
30        return winproc.pid_alive(pid, None)
31    try:
32        os.kill(pid, 0)
33    except ProcessLookupError:
34        return False
35    except PermissionError:
36        return True
37    # a zombie answers signal 0; only its parent has not collected it
38    try:
39        return Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[0] != "Z"
40    except OSError:
41        # collected between the signal and the read (1 in 15 on a loaded p2006): gone, unless signal 0 still finds it (no /proc)
42        try:
43            os.kill(pid, 0)
44        except ProcessLookupError:
45            return False
46        except PermissionError:
47            return True
48        return not Path("/proc").is_dir()
49
50
51def describe(pid: int) -> str:
52    """What is left of a process, for a failure message: state, parent, start time and command line, read from /proc."""
53    try:
54        fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()      # fields[0] is the state (field 3 of the file), fields[1] the parent, fields[19] the start (field 22)
55        boot = next(int(line.split()[1]) for line in Path("/proc/stat").read_text().splitlines() if line.startswith("btime"))
56        started = time.strftime("%H:%M:%S", time.localtime(boot + int(fields[19]) / os.sysconf("SC_CLK_TCK")))
57        command = Path(f"/proc/{pid}/cmdline").read_bytes().replace(b"\0", b" ").decode(errors="replace").strip()[:160]
58        return "pid %d state %s, parent %s, started %s, command line %r" % (pid, fields[0], fields[1], started, command)
59    except (OSError, IndexError, ValueError, StopIteration, AttributeError):
60        return "pid %d: nothing readable in /proc (gone, or no /proc on this system)" % pid
61
62
63class StopEngine(unittest.TestCase):
64    def setUp(self):
65        self.temp = tempfile.TemporaryDirectory(prefix="strata-benchstop-")
66        self.addCleanup(self.temp.cleanup)
67        self.pidfile = Path(self.temp.name) / "kid.pid"
68        self.procs = []
69        self.addCleanup(self._reap)
70
71    def _reap(self):
72        for pid in getattr(self, "pids", []):
73            try:
74                if alive(pid):
75                    os.kill(pid, 9)
76            except OSError:
77                pass
78        for proc in self.procs:
79            if proc.poll() is None:
80                proc.kill()
81            try:
82                proc.wait(10)
83            except subprocess.TimeoutExpired:
84                pass
85        for proc in self.procs:
86            handle = getattr(proc, "_strata_log", None)
87            if handle is not None and not handle.closed:
88                handle.close()
89        time.sleep(0.5)
90
91    def _start_tree(self):
92        """What start_engine does: a child of this run, in its own group (POSIX) or process group + job (Windows), with a child of its own."""
93        kwargs = {"creationflags": getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)} if WINDOWS else {"start_new_session": True}
94        handle = open(Path(self.temp.name) / "engine.log", "wb")
95        proc = subprocess.Popen([sys.executable, "-c", PARENT, str(self.pidfile)], stdout=handle, stderr=subprocess.STDOUT, **kwargs)
96        proc._strata_log = handle
97        self.procs.append(proc)
98        if WINDOWS:
99            from serve import winjob
100            proc._strata_job = winjob.contain(proc)
101        # wait for the whole pid, not only the file: under load the file can exist, still empty, for longer than a fixed pause
102        deadline, kid = time.monotonic() + 60, None
103        while kid is None and time.monotonic() < deadline:
104            try:
105                kid = int(self.pidfile.read_text().strip())
106            except (OSError, ValueError):
107                time.sleep(0.05)
108        self.assertIsNotNone(kid, "the stand-in engine did not start its own child within 60 s")
109        self.pids = [proc.pid, kid]
110        return proc, kid
111
112    def test_the_child_and_its_child_both_end(self):
113        proc, kid = self._start_tree()
114        outsider = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])      # same program, not ours
115        self.procs.append(outsider)
116        self.assertTrue(alive(kid))
117        self.assertIsNone(bench_standard.stop_engine(proc))
118        t_stop = time.monotonic()
119        deadline = t_stop + 30                                            # a loaded box can take seconds to deliver and reap
120        while alive(kid) and time.monotonic() < deadline:
121            time.sleep(0.1)
122        # three checks; a failure says which one it is and, for what survived, what it is (state, parent, start, command line)
123        if alive(proc.pid):
124            self.fail("check 1 of 3: the engine's server survived: " + describe(proc.pid))
125        if alive(kid):
126            self.fail("check 2 of 3: what the engine's server started survived (%.1f s after stop_engine returned): %s" % (time.monotonic() - t_stop, describe(kid)))
127        if outsider.poll() is not None:
128            self.fail("check 3 of 3: a process of the same program that this run did not start was ended (exit code %s)" % outsider.poll())
129
130    @unittest.skipUnless(WINDOWS, "Windows: a refused taskkill")
131    def test_a_refused_taskkill_does_not_leave_the_tree_running(self):
132        proc, kid = self._start_tree()
133        refused = subprocess.CompletedProcess(["taskkill"], 128, b"", b"ERROR: The process could not be terminated.\r\nReason: Access is denied.\r\n")
134        with mock.patch.object(bench_standard.subprocess, "run", return_value=refused):
135            problem = bench_standard.stop_engine(proc)
136        self.assertIsNone(problem, "the tree is gone, so there is nothing to report")
137        deadline = time.monotonic() + 10
138        while alive(kid) and time.monotonic() < deadline:
139            time.sleep(0.1)
140        self.assertFalse(alive(kid))
141
142    @unittest.skipUnless(WINDOWS, "Windows: every way of ending it refused")
143    def test_a_tree_that_cannot_be_ended_is_still_reported(self):
144        proc, kid = self._start_tree()
145        refused = subprocess.CompletedProcess(["taskkill"], 128, b"", b"Access is denied.")
146        with mock.patch.object(bench_standard.subprocess, "run", return_value=refused), \
147                mock.patch("serve.winjob.terminate", return_value=False), mock.patch.object(proc, "kill", side_effect=OSError("denied")):
148            problem = bench_standard.stop_engine(proc)
149        self.assertIn("still running", problem or "")
150
151    def test_a_process_that_already_ended_is_nothing_to_stop(self):
152        proc = subprocess.Popen([sys.executable, "-c", "pass"])
153        proc.wait(20)
154        proc._strata_log = open(os.devnull, "wb")
155        self.assertIsNone(bench_standard.stop_engine(proc))
156
157
158if __name__ == "__main__":
159    unittest.main()