okami.mom/strata

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

Niko1221merge f-split into f-split-s6326e39118

main
2.6 KiB70 linesraw
1"""Parent-loss guard and graceful-stop channel for a server launched by the local runtime host.
2
3The inherited pipe has exactly one writer, held by the host.  EOF therefore
4means the host exited, including after SIGKILL.
5
6POSIX: the server has its own process group so its engine subprocesses receive
7the emergency stop as well.  Windows: the host passes the pipe as the server's
8standard input (``--owner-fd 0``) and ends the server's whole process tree
9through a kill-on-close job object if it dies; the pipe is also how the host
10asks the server to drain and exit (it closes its end), because Windows has no
11SIGTERM to send.  EOF is turned into a Ctrl+C in the main thread, which is the
12path the server already drains and stops cleanly on.
13"""
14
15from __future__ import annotations
16
17import os
18import signal
19import stat
20import threading
21import time
22
23
24def _stop_gracefully() -> None:
25    import _thread
26    _thread.interrupt_main()
27
28
29def start(fd: int, on_loss=None, grace: float = 60.0) -> None:
30    if os.name == "nt":
31        if fd < 0 or not stat.S_ISFIFO(os.fstat(fd).st_mode):
32            raise ValueError("--owner-fd must be an inherited pipe")
33
34        def watch_windows() -> None:
35            try:
36                while os.read(fd, 1):
37                    pass
38            except OSError:
39                pass
40            (on_loss or _stop_gracefully)()
41
42        threading.Thread(target=watch_windows, name="strata-owner-guard", daemon=True).start()
43        return
44    if os.name != "posix" or fd < 0 or os.getpgrp() != os.getpid():
45        raise ValueError("--owner-fd requires a dedicated POSIX server process group")
46    if not stat.S_ISFIFO(os.fstat(fd).st_mode):
47        raise ValueError("--owner-fd must be an inherited pipe")
48
49    def watch() -> None:
50        try:
51            while os.read(fd, 1):
52                pass
53        except OSError:
54            pass                       # a broken guard must never authorize another process to manage us
55        finally:
56            os.close(fd)
57        # This is an emergency path.  Signal the whole dedicated group so an engine already spawned during model
58        # loading cannot be orphaned.  SIGTERM is the clean stop (the server drains and closes its engine); if the
59        # group is still there after `grace` seconds, SIGKILL ends whatever is left.
60        pgid = os.getpgrp()
61        try:
62            os.killpg(pgid, signal.SIGTERM)
63            deadline = time.monotonic() + grace
64            while time.monotonic() < deadline:
65                time.sleep(0.5)
66            os.killpg(pgid, signal.SIGKILL)
67        except OSError:
68            pass
69
70    threading.Thread(target=watch, name="strata-owner-guard", daemon=True).start()