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
14.4 KiB357 linesraw
1"""serve/lifeline.py - a process Strata starts ends when the process that started it ends, however that ends.
2
3The graceful path is the server's own (QUIT to the engine, drain, exit). This module is the guarantee behind it
4for the cases where nothing gets to run: kill -9, a crash, the console window closed, logoff, power-off.
5
6* Windows: the child joins a kill-on-close job object whose only handle is ours (serve/winjob.py).
7* Linux: ``PR_SET_PDEATHSIG`` = SIGKILL, set in the child before it execs. The kernel ties the signal to the
8  THREAD that forked the child, not to the process, so every start goes through one long-lived "anchor" thread;
9  a request thread that starts an engine and then finishes would otherwise take the engine with it.
10* macOS (no such call): a small watcher process holds a pipe to us. When we die the pipe closes, the watcher
11  sees EOF and ends the child, after checking it is still the same process (PID, start time). A child that
12  ended on its own, or was ended by us, is released first, so the watcher never signals a reused PID.
13
14``popen`` is ``subprocess.Popen`` plus the guarantee. ``release`` is called once the child has been reaped.
15"""
16from __future__ import annotations
17
18import atexit
19import concurrent.futures
20import os
21import queue
22import signal
23import subprocess
24import sys
25import threading
26import time
27
28from pathlib import Path
29
30from serve import winjob
31from strata_control import procs
32
33_REAL_POPEN = subprocess.Popen                  # tests replace subprocess.Popen; isinstance needs the class
34LINUX = sys.platform.startswith("linux")
35MODE = (os.environ.get("STRATA_LIFELINE") or "").strip().lower()        # "watcher" forces the portable path (tests)
36
37_libc = None
38if LINUX:
39    try:
40        import ctypes
41        _libc = ctypes.CDLL(None, use_errno=True)
42        _libc.prctl.argtypes = (ctypes.c_int, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong, ctypes.c_ulong)
43    except (OSError, AttributeError):
44        _libc = None
45
46PR_SET_PDEATHSIG = 1
47
48
49class _Anchor:
50    """One thread that lives as long as the process and performs every Popen, so PDEATHSIG's "parent" is it."""
51
52    def __init__(self) -> None:
53        self._jobs: queue.Queue = queue.Queue()
54        self._thread = threading.Thread(target=self._run, name="strata-lifeline-anchor", daemon=True)
55        self._thread.start()
56
57    def _run(self) -> None:
58        while True:
59            fn, future = self._jobs.get()
60            try:
61                future.set_result(fn())
62            except BaseException as exc:  # noqa: BLE001 - handed to the caller
63                future.set_exception(exc)
64
65    def call(self, fn):
66        if threading.current_thread() is self._thread:
67            return fn()
68        future: concurrent.futures.Future = concurrent.futures.Future()
69        self._jobs.put((fn, future))
70        return future.result()
71
72
73_anchor: _Anchor | None = None
74_anchor_lock = threading.Lock()
75
76
77def _the_anchor() -> _Anchor:
78    global _anchor
79    with _anchor_lock:
80        if _anchor is None:
81            _anchor = _Anchor()
82        return _anchor
83
84
85def _die_with_parent(parent: int, then=None):
86    """The preexec function of a child: SIGKILL when the starting thread ends; and if it ended already, now."""
87    def run() -> None:
88        _libc.prctl(PR_SET_PDEATHSIG, int(signal.SIGKILL), 0, 0, 0)
89        if os.getppid() != parent:                 # the parent died between fork and prctl
90            os.kill(os.getpid(), signal.SIGKILL)
91        if then is not None:
92            then()
93    return run
94
95
96# ---------------------------------------------------------------------------------------- the portable watcher
97
98_WATCHER = r'''
99import os, signal, subprocess, sys, time
100pid, token = int(sys.argv[1]), sys.argv[2]
101for s in (signal.SIGINT, signal.SIGHUP, signal.SIGTERM):
102    signal.signal(s, signal.SIG_IGN)               # it ends with its pipe, not with the terminal
103def start_of(p):
104    # Start time ONLY. `ps`'s stat column changes while a process runs (R while it starts, S while it
105    # sleeps), so including it made this token disagree with the one taken at start and the watcher
106    # spared the child it was meant to end.
107    try:
108        with open("/proc/%d/stat" % p, "rb") as f:   # closed explicitly: start_of runs up to 42 times per child
109            raw = f.read().decode("utf-8", "replace")
110        fields = raw[raw.rindex(")") + 2:].split()
111        if fields[0] == "Z":                       # exited; only its parent has not collected it
112            return None
113        return "l:" + fields[19]
114    except Exception:
115        pass
116    if os.path.exists("/proc/self/stat"):          # Linux, and that PID has no /proc entry any more
117        return None
118    try:
119        out = subprocess.run(["ps", "-o", "lstart=", "-p", str(p)], capture_output=True, text=True, timeout=5).stdout.strip()
120    except Exception:
121        return None
122    return None if not out else "p:" + out
123os.set_blocking(0, True)
124data = b""
125while True:
126    chunk = os.read(0, 16)
127    if not chunk:
128        break
129    data += chunk
130    if b"x" in data:                                # released: the child is gone or was ended on purpose
131        sys.exit(0)
132if token and start_of(pid) == token:
133    try:
134        os.kill(pid, signal.SIGTERM)
135    except OSError:
136        sys.exit(0)
137    for _ in range(40):
138        time.sleep(0.25)
139        if start_of(pid) != token:
140            sys.exit(0)
141    if start_of(pid) == token:
142        try:
143            os.kill(pid, signal.SIGKILL)
144        except OSError:
145            pass
146'''
147
148_watchers: dict[int, subprocess.Popen] = {}
149_watchers_lock = threading.Lock()
150
151
152def _start_token(pid: int) -> str:
153    """The same string for the life of one process, different for a later process with that PID.
154
155    Identity is the start time alone. The previous version ran `ps -o lstart=,stat=` and kept the whole
156    line, so the token changed whenever the process changed state - measured here: one child reported
157    '... R' once and '... S' eleven times inside 150 ms. The watcher then compared its own reading with
158    the token from start time, saw "different process", and exited without ending the child, which is
159    exactly the flake `serve/test_lifeline.py` reported as "the child outlived a killed server".
160    """
161    if sys.platform.startswith("linux"):
162        try:
163            fields = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8", errors="replace")
164            rest = fields[fields.rindex(")") + 2:].split()
165            return "" if rest[0] == "Z" else "l:" + rest[19]      # starttime, clock ticks since boot
166        except (OSError, ValueError, IndexError):
167            # procfs IS there and the entry is not readable: the process is gone (or is not ours), and there is
168            # nothing to fall back to. Without procfs at all, fall through to `ps` - otherwise this side would
169            # return "" while the watcher's start_of() returns "p:...", the two can never match, and the child
170            # outlives the server: exactly the failure this change removes, restored for that environment.
171            if os.path.exists("/proc/self/stat"):
172                return ""
173    try:
174        out = subprocess.run(["ps", "-o", "lstart=", "-p", str(pid)], capture_output=True, text=True,
175                             timeout=5).stdout.strip()
176    except (OSError, subprocess.SubprocessError):
177        return ""
178    return "" if not out else "p:" + out
179
180
181def _watch(child: subprocess.Popen) -> None:
182    if not isinstance(child, _REAL_POPEN) or getattr(child, "pid", None) is None:
183        return
184    try:
185        watcher = subprocess.Popen([sys.executable, "-S", "-c", _WATCHER, str(child.pid), _start_token(child.pid)],
186                                   stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
187                                   close_fds=True, start_new_session=True)
188    except OSError:
189        return
190    with _watchers_lock:
191        _watchers[child.pid] = watcher
192
193
194def release(child: subprocess.Popen | None) -> None:
195    """The child has been reaped (or ended on purpose): stop watching it. Harmless where nothing is watching."""
196    if child is None:
197        return
198    with _watchers_lock:
199        watcher = _watchers.pop(child.pid, None)
200    if watcher is None:
201        return
202    try:
203        watcher.stdin.write(b"x")
204        watcher.stdin.close()
205    except (OSError, ValueError):
206        pass
207    try:
208        watcher.wait(timeout=5)
209    except subprocess.TimeoutExpired:
210        watcher.kill()
211
212
213# ---------------------------------------------------------------------------------------------------- popen
214
215def mechanism() -> str:
216    """Which guarantee a start gets on this platform: job, pdeathsig, watcher."""
217    if os.name == "nt":
218        return "job"
219    if LINUX and _libc is not None and MODE != "watcher":
220        return "pdeathsig"
221    return "watcher"
222
223
224_children: set = set()
225_children_lock = threading.Lock()
226
227
228def end_children(grace: float = 3.0) -> None:
229    """Whatever this process started and has not ended yet: terminate, then kill. Runs at interpreter exit, so an
230    exception or a signal that unwinds main() before its own cleanup still leaves nothing behind (the engine and
231    the others have already been closed on every normal path, so this finds nothing then)."""
232    with _children_lock:
233        alive = [c for c in _children if c.poll() is None]
234    for child in alive:
235        try:
236            child.terminate()
237        except OSError:
238            pass
239    deadline = time.monotonic() + grace
240    for child in alive:
241        try:
242            child.wait(timeout=max(0.0, deadline - time.monotonic()))
243        except (subprocess.TimeoutExpired, OSError):
244            try:
245                child.kill()
246            except OSError:
247                pass
248
249
250atexit.register(end_children)
251
252
253def _after_exit(child: subprocess.Popen, token: str | None) -> None:
254    child.wait()
255    with _children_lock:
256        _children.discard(child)
257    release(child)
258    if token is not None:
259        procs.drop_record(child.pid, token)
260
261
262ISOLATED_ROLES = ("engine", "vision")      # speak a stdin protocol with us: the server alone decides when they stop
263
264
265def _own_group(then=None):
266    def run() -> None:
267        os.setpgid(0, 0)
268        if then is not None:
269            then()
270    return run
271
272
273def popen(args, role: str = "engine", **kw) -> subprocess.Popen:
274    """``subprocess.Popen(args, **kw)`` for a process that must not outlive us.
275
276    An engine or image encoder is also taken out of the terminal's reach (its own process group on POSIX, a new
277    process group on Windows): Ctrl+C, a closing terminal or a console Break go to the server only, which then ends
278    the engine the clean way (STOP, QUIT, wait) instead of the engine dying under a request that could have been
279    finished or cancelled. What ties the engine's life to ours is the guarantee below, not the shared terminal.
280
281    It also leaves a record (strata_control/procs.py) so that, if everything here dies anyway, the next start can
282    find this process by PID, start time and command line and end it."""
283    how = mechanism()
284    isolate = role in ISOLATED_ROLES
285    if isolate and os.name == "nt":
286        kw["creationflags"] = kw.get("creationflags", 0) | subprocess.CREATE_NEW_PROCESS_GROUP
287    if isolate and os.name != "nt" and "start_new_session" not in kw:
288        kw["preexec_fn"] = _own_group(kw.pop("preexec_fn", None))
289    if how == "pdeathsig":
290        parent, then = os.getpid(), kw.pop("preexec_fn", None)
291        kw["preexec_fn"] = _die_with_parent(parent, then)
292        child = _the_anchor().call(lambda: subprocess.Popen(args, **kw))
293    elif how == "job":
294        child = winjob.start_contained(args, **kw)   # in the job before it runs, so nothing it starts slips out
295    else:
296        child = subprocess.Popen(args, **kw)
297        _watch(child)
298    if isinstance(child, _REAL_POPEN):
299        with _children_lock:
300            _children.add(child)
301    try:
302        token = procs.write_record(child.pid, role, profile=os.environ.get("STRATA_RUNTIME_PROFILE") or None)
303        threading.Thread(target=_after_exit, args=(child, token), name="strata-lifeline-reaper", daemon=True).start()
304    except Exception:  # noqa: BLE001 - a record is a safety net, never a reason to fail a start
305        pass
306    return child
307
308
309# ------------------------------------------------------------------------------------------- stop signals
310
311_console_handler = None            # the ctypes callback must stay referenced for the life of the process
312
313
314def install_stop_handlers(request_stop, finished: threading.Event | None = None) -> None:
315    """Make every ordinary way a server is asked to end take the clean path (`request_stop(reason)`).
316
317    * POSIX: SIGTERM (docker stop, systemd, `kill`), SIGHUP (the terminal closed, the ssh connection dropped; not when it
318      was ignored at start, which is what `nohup` does on purpose).
319      SIGINT keeps Python's own handler (Ctrl+C, and a second Ctrl+C to stop waiting).
320    * Windows: SIGBREAK, and the console's close, logoff and shutdown events. Those arrive on a thread of their own and
321      the system ends the process a few seconds after the handler returns, so the handler waits for `finished` (up to
322      4.5 s) and then returns; whatever is still running is ended by the job object.
323    Must be called from the main thread."""
324    def in_main(reason: str):
325        def handler(signum, frame):
326            request_stop(reason)
327        return handler
328    for name, reason in (("SIGTERM", "sigterm"), ("SIGHUP", "sighup"), ("SIGBREAK", "sigbreak")):
329        sig = getattr(signal, name, None)
330        if sig is None:
331            continue
332        try:
333            # `nohup strata serve ... &` asks to outlive its terminal: a hangup that is ignored at start stays ignored
334            if name == "SIGHUP" and signal.getsignal(sig) == signal.SIG_IGN:
335                continue
336            signal.signal(sig, in_main(reason))
337        except (ValueError, OSError):                       # not the main thread
338            pass
339    if os.name != "nt":
340        return
341    import ctypes
342    from ctypes import wintypes
343    events = {2: "console-close", 5: "logoff", 6: "shutdown"}
344    prototype = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)
345
346    def on_console_event(event: int) -> bool:
347        reason = events.get(event)
348        if reason is None:
349            return False                                    # Ctrl+C and Ctrl+Break: Python's own handling
350        request_stop(reason)
351        if finished is not None:
352            finished.wait(4.5)
353        return True
354
355    global _console_handler
356    _console_handler = prototype(on_console_event)
357    ctypes.windll.kernel32.SetConsoleCtrlHandler(_console_handler, True)