okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
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 8THREAD that forked the child, not to the process, so every start goes through one long-lived "anchor" thread; 9a 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 11sees EOF and ends the child, after checking it is still the same process (PID, start time). A child that 12ended 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 : 39try : 40import 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 ) 43except (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 52def __init__ (self )-> None : 53self ._jobs :queue .Queue = queue .Queue () 54self ._thread = threading .Thread (target = self ._run ,name = "strata-lifeline-anchor" ,daemon = True ) 55self ._thread .start () 56 57def _run (self )-> None : 58while True : 59fn ,future = self ._jobs .get () 60try : 61future .set_result (fn ()) 62except BaseException as exc :# noqa: BLE001 - handed to the caller 63future .set_exception (exc ) 64 65def call (self ,fn ): 66if threading .current_thread ()is self ._thread : 67return fn () 68future :concurrent .futures .Future = concurrent .futures .Future () 69self ._jobs .put ((fn ,future )) 70return future .result () 71 72 73_anchor :_Anchor | None = None 74_anchor_lock = threading .Lock () 75 76 77def _the_anchor ()-> _Anchor : 78global _anchor 79with _anchor_lock : 80if _anchor is None : 81_anchor = _Anchor () 82return _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.""" 87def run ()-> None : 88_libc .prctl (PR_SET_PDEATHSIG ,int (signal .SIGKILL ),0 ,0 ,0 ) 89if os .getppid ()!= parent :# the parent died between fork and prctl 90os .kill (os .getpid (),signal .SIGKILL ) 91if then is not None : 92then () 93return 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): 102signal.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. 107try: 108with open("/proc/%d/stat" % p, "rb") as f: # closed explicitly: start_of runs up to 42 times per child 109raw = f.read().decode("utf-8", "replace") 110fields = raw[raw.rindex(")") + 2:].split() 111if fields[0] == "Z": # exited; only its parent has not collected it 112return None 113return "l:" + fields[19] 114except Exception: 115pass 116if os.path.exists("/proc/self/stat"): # Linux, and that PID has no /proc entry any more 117return None 118try: 119out = subprocess.run(["ps", "-o", "lstart=", "-p", str(p)], capture_output=True, text=True, timeout=5).stdout.strip() 120except Exception: 121return None 122return None if not out else "p:" + out 123os.set_blocking(0, True) 124data = b"" 125while True: 126chunk = os.read(0, 16) 127if not chunk: 128break 129data += chunk 130if b"x" in data: # released: the child is gone or was ended on purpose 131sys.exit(0) 132if token and start_of(pid) == token: 133try: 134os.kill(pid, signal.SIGTERM) 135except OSError: 136sys.exit(0) 137for _ in range(40): 138time.sleep(0.25) 139if start_of(pid) != token: 140sys.exit(0) 141if start_of(pid) == token: 142try: 143os.kill(pid, signal.SIGKILL) 144except OSError: 145pass 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 155Identity is the start time alone. The previous version ran `ps -o lstart=,stat=` and kept the whole 156line, 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 158the token from start time, saw "different process", and exited without ending the child, which is 159exactly the flake `serve/test_lifeline.py` reported as "the child outlived a killed server". 160""" 161if sys .platform .startswith ("linux" ): 162try : 163fields = Path (f"/proc/ { pid } /stat" ).read_text (encoding = "utf-8" ,errors = "replace" ) 164rest = fields [fields .rindex (")" )+ 2 :].split () 165return "" if rest [0 ]== "Z" else "l:" + rest [19 ]# starttime, clock ticks since boot 166except (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. 171if os .path .exists ("/proc/self/stat" ): 172return "" 173try : 174out = subprocess .run (["ps" ,"-o" ,"lstart=" ,"-p" ,str (pid )],capture_output = True ,text = True , 175timeout = 5 ).stdout .strip () 176except (OSError ,subprocess .SubprocessError ): 177return "" 178return "" if not out else "p:" + out 179 180 181def _watch (child :subprocess .Popen )-> None : 182if not isinstance (child ,_REAL_POPEN )or getattr (child ,"pid" ,None )is None : 183return 184try : 185watcher = subprocess .Popen ([sys .executable ,"-S" ,"-c" ,_WATCHER ,str (child .pid ),_start_token (child .pid )], 186stdin = subprocess .PIPE ,stdout = subprocess .DEVNULL ,stderr = subprocess .DEVNULL , 187close_fds = True ,start_new_session = True ) 188except OSError : 189return 190with _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.""" 196if child is None : 197return 198with _watchers_lock : 199watcher = _watchers .pop (child .pid ,None ) 200if watcher is None : 201return 202try : 203watcher .stdin .write (b"x" ) 204watcher .stdin .close () 205except (OSError ,ValueError ): 206pass 207try : 208watcher .wait (timeout = 5 ) 209except subprocess .TimeoutExpired : 210watcher .kill () 211 212 213# ---------------------------------------------------------------------------------------------------- popen 214 215def mechanism ()-> str : 216"""Which guarantee a start gets on this platform: job, pdeathsig, watcher.""" 217if os .name == "nt" : 218return "job" 219if LINUX and _libc is not None and MODE != "watcher" : 220return "pdeathsig" 221return "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 230exception or a signal that unwinds main() before its own cleanup still leaves nothing behind (the engine and 231the others have already been closed on every normal path, so this finds nothing then).""" 232with _children_lock : 233alive = [c for c in _children if c .poll ()is None ] 234for child in alive : 235try : 236child .terminate () 237except OSError : 238pass 239deadline = time .monotonic ()+ grace 240for child in alive : 241try : 242child .wait (timeout = max (0.0 ,deadline - time .monotonic ())) 243except (subprocess .TimeoutExpired ,OSError ): 244try : 245child .kill () 246except OSError : 247pass 248 249 250atexit .register (end_children ) 251 252 253def _after_exit (child :subprocess .Popen ,token :str | None )-> None : 254child .wait () 255with _children_lock : 256_children .discard (child ) 257release (child ) 258if token is not None : 259procs .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 ): 266def run ()-> None : 267os .setpgid (0 ,0 ) 268if then is not None : 269then () 270return 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 276An engine or image encoder is also taken out of the terminal's reach (its own process group on POSIX, a new 277process group on Windows): Ctrl+C, a closing terminal or a console Break go to the server only, which then ends 278the engine the clean way (STOP, QUIT, wait) instead of the engine dying under a request that could have been 279finished or cancelled. What ties the engine's life to ours is the guarantee below, not the shared terminal. 280 281It also leaves a record (strata_control/procs.py) so that, if everything here dies anyway, the next start can 282find this process by PID, start time and command line and end it.""" 283how = mechanism () 284isolate = role in ISOLATED_ROLES 285if isolate and os .name == "nt" : 286kw ["creationflags" ]= kw .get ("creationflags" ,0 )| subprocess .CREATE_NEW_PROCESS_GROUP 287if isolate and os .name != "nt" and "start_new_session" not in kw : 288kw ["preexec_fn" ]= _own_group (kw .pop ("preexec_fn" ,None )) 289if how == "pdeathsig" : 290parent ,then = os .getpid (),kw .pop ("preexec_fn" ,None ) 291kw ["preexec_fn" ]= _die_with_parent (parent ,then ) 292child = _the_anchor ().call (lambda :subprocess .Popen (args ,** kw )) 293elif how == "job" : 294child = winjob .start_contained (args ,** kw )# in the job before it runs, so nothing it starts slips out 295else : 296child = subprocess .Popen (args ,** kw ) 297_watch (child ) 298if isinstance (child ,_REAL_POPEN ): 299with _children_lock : 300_children .add (child ) 301try : 302token = procs .write_record (child .pid ,role ,profile = os .environ .get ("STRATA_RUNTIME_PROFILE" )or None ) 303threading .Thread (target = _after_exit ,args = (child ,token ),name = "strata-lifeline-reaper" ,daemon = True ).start () 304except Exception :# noqa: BLE001 - a record is a safety net, never a reason to fail a start 305pass 306return 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 318was ignored at start, which is what `nohup` does on purpose). 319SIGINT 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 321the system ends the process a few seconds after the handler returns, so the handler waits for `finished` (up to 3224.5 s) and then returns; whatever is still running is ended by the job object. 323Must be called from the main thread.""" 324def in_main (reason :str ): 325def handler (signum ,frame ): 326request_stop (reason ) 327return handler 328for name ,reason in (("SIGTERM" ,"sigterm" ), ("SIGHUP" ,"sighup" ), ("SIGBREAK" ,"sigbreak" )): 329sig = getattr (signal ,name ,None ) 330if sig is None : 331continue 332try : 333# `nohup strata serve ... &` asks to outlive its terminal: a hangup that is ignored at start stays ignored 334if name == "SIGHUP" and signal .getsignal (sig )== signal .SIG_IGN : 335continue 336signal .signal (sig ,in_main (reason )) 337except (ValueError ,OSError ):# not the main thread 338pass 339if os .name != "nt" : 340return 341import ctypes 342from ctypes import wintypes 343events = {2 :"console-close" ,5 :"logoff" ,6 :"shutdown" } 344prototype = ctypes .WINFUNCTYPE (wintypes .BOOL ,wintypes .DWORD ) 345 346def on_console_event (event :int )-> bool : 347reason = events .get (event ) 348if reason is None : 349return False # Ctrl+C and Ctrl+Break: Python's own handling 350request_stop (reason ) 351if finished is not None : 352finished .wait (4.5 ) 353return True 354 355global _console_handler 356_console_handler = prototype (on_console_event ) 357ctypes .windll .kernel32 .SetConsoleCtrlHandler (_console_handler ,True )