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.6 KiB154 linesraw
1"""serve/winjob.py: a contained child - and whatever it starts - ends when the process that contained it ends, even
2when that process is killed outright (the console window closed, Task Manager), with no cleanup of its own.
3
4    python -m unittest serve.test_winjob      (Windows only; skipped elsewhere)
5
6The test holds a handle to the child and to the grandchild (kernel32, from the standard library) instead of asking `tasklist` whether a PID is
7listed: a handle names one process object, so a PID that Windows hands out again to some other program cannot pass for the child, and when a
8process is still there after the wait the failure says which process it is (image name, creation time, seconds since the kill).
9"""
10import os
11import subprocess
12import sys
13import time
14import unittest
15from datetime import datetime
16from pathlib import Path
17
18ROOT = Path(__file__).resolve().parent.parent
19sys.path.insert(0, str(ROOT))
20
21# stands in for the server: contains a child that starts a grandchild, prints both pids, then waits to be killed
22PARENT = f"""
23import subprocess, sys, time
24sys.path.insert(0, {str(ROOT)!r})
25from serve.winjob import contain
26code = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); "
27        "print(g.pid, flush=True); time.sleep(120)")
28child = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True)
29ok = contain(child)
30print(ok, child.pid, child.stdout.readline().strip(), flush=True)
31time.sleep(120)
32"""
33
34_PROCESS_TERMINATE, _PROCESS_QUERY_LIMITED_INFORMATION, _SYNCHRONIZE = 0x0001, 0x1000, 0x00100000
35_WAIT_OBJECT_0 = 0
36_FILETIME_UNIX_EPOCH_S = 11644473600          # seconds from 1601-01-01 (FILETIME) to 1970-01-01
37
38if os.name == "nt":
39    import ctypes
40    from ctypes import wintypes
41
42    _k32 = ctypes.WinDLL("kernel32", use_last_error=True)
43    _k32.OpenProcess.restype = wintypes.HANDLE
44    _k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
45    _k32.CloseHandle.argtypes = (wintypes.HANDLE,)
46    _k32.WaitForSingleObject.restype = wintypes.DWORD
47    _k32.WaitForSingleObject.argtypes = (wintypes.HANDLE, wintypes.DWORD)
48    _k32.TerminateProcess.argtypes = (wintypes.HANDLE, wintypes.UINT)
49    _k32.GetProcessTimes.argtypes = (wintypes.HANDLE,) + (ctypes.POINTER(wintypes.FILETIME),) * 4
50    _k32.QueryFullProcessImageNameW.argtypes = (wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR, ctypes.POINTER(wintypes.DWORD))
51
52
53def _identity(handle) -> tuple[str, float]:
54    """(image file name, creation time as seconds since 1970) of the process behind an open handle."""
55    created, a, b, c = (wintypes.FILETIME() for _ in range(4))
56    if not _k32.GetProcessTimes(handle, ctypes.byref(created), ctypes.byref(a), ctypes.byref(b), ctypes.byref(c)):
57        raise ctypes.WinError(ctypes.get_last_error())
58    text, size = ctypes.create_unicode_buffer(1024), wintypes.DWORD(1024)
59    name = Path(text.value).name if _k32.QueryFullProcessImageNameW(handle, 0, text, ctypes.byref(size)) else "?"
60    return name, ((created.dwHighDateTime << 32) | created.dwLowDateTime) / 1e7 - _FILETIME_UNIX_EPOCH_S
61
62
63def _when(seconds: float) -> str:
64    return datetime.fromtimestamp(seconds).strftime("%H:%M:%S.%f")[:-3]
65
66
67class Held:
68    """A process held by a handle. The handle keeps the process object (and so its identity) alive; `exited()` asks that object, never the PID."""
69
70    def __init__(self, pid: int, label: str):
71        self.pid, self.label = pid, label
72        self.handle = _k32.OpenProcess(_SYNCHRONIZE | _PROCESS_QUERY_LIMITED_INFORMATION | _PROCESS_TERMINATE, False, pid)
73        if not self.handle:
74            raise ctypes.WinError(ctypes.get_last_error())
75        self.image, self.created = _identity(self.handle)
76
77    def exited(self) -> bool:
78        return _k32.WaitForSingleObject(self.handle, 0) == _WAIT_OBJECT_0
79
80    def holder_of_the_pid_now(self) -> str:
81        """What a fresh OpenProcess by PID finds: image name and creation time, and whether it is the process held here."""
82        handle = _k32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, self.pid)
83        if not handle:
84            return "no process has the PID"
85        try:
86            image, created = _identity(handle)
87        finally:
88            _k32.CloseHandle(handle)
89        same = abs(created - self.created) < 0.001           # the creation time is what tells two processes with one PID apart (an exited process has no image name to ask for)
90        return "%s created %s (%s)" % (image if image != "?" else "an exited process", _when(created), "the same process" if same else "NOT the process held")
91
92    def explain(self, since_kill: float) -> str:
93        listed = subprocess.run(["tasklist", "/FI", f"PID eq {self.pid}", "/NH"], capture_output=True, text=True).stdout.strip().replace("\n", " | ")
94        return ("%s outlived the server: pid %d is %s, created %s; %.1f s after the kill it is still running; the PID is held now by: %s; tasklist: %s"
95                % (self.label, self.pid, self.image, _when(self.created), since_kill, self.holder_of_the_pid_now(), listed or "-"))
96
97    def end(self) -> None:
98        if self.handle:
99            if not self.exited():                     # on a failure, don't leave them sleeping (this very process, by handle)
100                _k32.TerminateProcess(self.handle, 1)
101            _k32.CloseHandle(self.handle)
102            self.handle = None
103
104
105@unittest.skipUnless(os.name == "nt", "job objects are Windows-only")
106class TestWinJob(unittest.TestCase):
107    def test_children_end_with_a_killed_server(self):
108        # a venv's python.exe is a launcher that runs the real interpreter as its child: kill() must reach the latter
109        python = getattr(sys, "_base_executable", None) or sys.executable
110        parent = subprocess.Popen([python, "-c", PARENT], stdout=subprocess.PIPE, text=True)
111        child = grandchild = None
112        try:
113            ok, child_pid, grandchild_pid = parent.stdout.readline().split()
114            child, grandchild = Held(int(child_pid), "the child"), Held(int(grandchild_pid), "the grandchild")
115            self.assertEqual(ok, "True")
116            self.assertFalse(child.exited() or grandchild.exited())
117            parent.kill()                       # TerminateProcess: no atexit, no finally - like closing the window
118            t_kill = time.monotonic()
119            parent.wait(10)
120            deadline = time.monotonic() + 10
121            while not (child.exited() and grandchild.exited()) and time.monotonic() < deadline:
122                time.sleep(0.05)
123            for held in (child, grandchild):
124                if not held.exited():
125                    self.fail(held.explain(time.monotonic() - t_kill))
126        finally:
127            if parent.poll() is None:
128                parent.kill()
129            for held in (child, grandchild):
130                if held is not None:
131                    held.end()
132
133    def test_elsewhere_or_without_a_process_it_is_a_no_op(self):
134        from serve.winjob import contain
135        self.assertFalse(contain(None))
136
137
138if __name__ == "__main__":
139    unittest.main()
140
141
142@unittest.skipUnless(os.name == "nt", "power throttling is a Windows setting")
143class TestNoThrottle(unittest.TestCase):
144    def test_a_contained_child_is_opted_out_of_power_throttling(self):
145        # #691: contain() also sets ProcessPowerThrottling (EcoQoS off), so a minimized server window does not move the
146        # engine to the E-cores
147        from serve import winjob
148        child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"])
149        try:
150            self.assertTrue(winjob.no_throttle(int(child._handle)))
151            self.assertTrue(winjob.contain(child))
152        finally:
153            child.kill()
154            child.wait(10)