okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1"""Which processes Strata started, and how to tell one of them from a stranger. 2 3Every engine, image encoder and server that Strata starts leaves a small private record: its PID, the time it 4started, its command line, and the same two things for the process that started it. When that parent is gone and 5the child is still running, the child is a leftover. A leftover is ended only when ALL of these still hold at the 6moment of the signal: 7 8* the process at that PID started at the recorded time (a later process that reused the number does not match); 9* its command line is the recorded one (PID reuse plus the same start time is not possible, but this is also what 10makes an unrelated program impossible to hit by a corrupted record); 11* the recorded parent is not running as that same process. 12 13A PID that is only a number is never signalled. If the identity of a process cannot be read (no command line on 14this platform and no psutil), it is left alone and reported. 15 16Also here: the one-time check for engines left by earlier Strata versions, which wrote no record: an orphan of 17exactly the engine executable that is about to be started, running ``--serve`` with no live parent. 18""" 19 20from __future__import annotations 21 22from strata_control .private_files import private_mkdir as _private_mkdir 23import json 24import os 25import signal 26import subprocess 27import sys 28import time 29from dataclasses import dataclass 30from pathlib import Path 31 32from strata_control import paths 33from strata_control import atomic as _atomic_mod 34 35WINDOWS = os .name == "nt" 36SCHEMA = 1 37INIT_NAMES = {"systemd" ,"init" ,"launchd" ,"upstart" }# parents that adopt orphans 38 39try :# psutil ships in every Strata runtime (requirements.txt, the Control lock files) 40import psutil 41except ImportError :# pragma: no cover - the Linux /proc fallback below still identifies processes 42psutil = None 43 44 45# ---------------------------------------------------------------------------------------------- identity 46 47def start_token (pid :int )-> str | None : 48"""A string that is the same for the lifetime of one process and different for a later process with the same 49PID. None when there is no such process or its start cannot be read.""" 50if type (pid )is not int or pid <= 0 : 51return None 52if sys .platform .startswith ("linux" ): 53try : 54raw = Path (f"/proc/ { pid } /stat" ).read_text (encoding = "utf-8" ,errors = "replace" ) 55fields = raw [raw .rindex (")" )+ 2 :].split () 56if fields [0 ]== "Z" :# a zombie has exited; only its parent has not collected it 57return None 58return "l:" + fields [19 ]# starttime, clock ticks since boot (field 22) 59except (OSError ,ValueError ,IndexError ): 60return None 61if WINDOWS : 62from strata_control import winproc 63started = winproc .process_started (pid ) 64return None if started is None else f"w: { started } " 65if psutil is not None : 66try : 67p = psutil .Process (pid ) 68if p .status ()== psutil .STATUS_ZOMBIE : 69return None 70return f"p: { p . create_time ():.3f } " 71except (psutil .Error ,OSError ): 72return None 73try : 74out = subprocess .run (["ps" ,"-o" ,"lstart=,stat=" ,"-p" ,str (pid )],capture_output = True ,text = True , 75timeout = 5 ).stdout .strip () 76except (OSError ,subprocess .SubprocessError ): 77return None 78return None if not out or out .endswith ("Z" )else "s:" + out .rsplit (None ,1 )[0 ] 79 80 81def started_epoch (pid :int )-> float | None : 82"""When the process at `pid` was created, in seconds since 1970, or None when there is no such process or the time cannot be read. 83A number recorded in an old file can belong to a later process; a creation time after the file was written proves it does.""" 84if type (pid )is not int or pid <= 0 : 85return None 86if psutil is not None : 87try : 88return float (psutil .Process (pid ).create_time ()) 89except (psutil .Error ,OSError ): 90return None 91if WINDOWS : 92from strata_control import winproc 93ticks = winproc .process_started (pid ) 94return None if ticks is None else (ticks - 116444736000000000 )/ 1e7 # 100 ns ticks since 1601 95if sys .platform .startswith ("linux" ): 96token = start_token (pid ) 97try : 98boot = next (int (line .split ()[1 ])for line in Path ("/proc/stat" ).read_text ().splitlines ()if line .startswith ("btime " )) 99return boot + int (token [2 :])/ os .sysconf ("SC_CLK_TCK" )if token else None 100except (OSError ,ValueError ,StopIteration ): 101return None 102return None 103 104 105def command_line (pid :int )-> list [str ]| None : 106"""The process's argv, or None when it cannot be read (then it is never treated as a match).""" 107if sys .platform .startswith ("linux" ): 108try : 109raw = Path (f"/proc/ { pid } /cmdline" ).read_bytes () 110return [part .decode ("utf-8" ,"replace" )for part in raw .split (b"\0" )if part ]or None 111except OSError : 112return None 113if psutil is not None : 114try : 115return list (psutil .Process (pid ).cmdline ())or None 116except (psutil .Error ,OSError ): 117return None 118if not WINDOWS : 119try : 120out = subprocess .run (["ps" ,"-o" ,"command=" ,"-p" ,str (pid )],capture_output = True ,text = True , 121timeout = 5 ).stdout .strip () 122except (OSError ,subprocess .SubprocessError ): 123return None 124return out .split ()or None 125return None 126 127 128def parent_of (pid :int )-> int | None : 129if sys .platform .startswith ("linux" ): 130try : 131raw = Path (f"/proc/ { pid } /stat" ).read_text (encoding = "utf-8" ,errors = "replace" ) 132return int (raw [raw .rindex (")" )+ 2 :].split ()[1 ]) 133except (OSError ,ValueError ,IndexError ): 134return None 135if psutil is not None : 136try : 137return psutil .Process (pid ).ppid () 138except (psutil .Error ,OSError ): 139return None 140return None 141 142 143def exe_path (pid :int )-> str | None : 144if sys .platform .startswith ("linux" ): 145try : 146return os .readlink (f"/proc/ { pid } /exe" ) 147except OSError : 148return None 149if psutil is not None : 150try : 151return psutil .Process (pid ).exe ()or None 152except (psutil .Error ,OSError ): 153return None 154return None 155 156 157def same_file (a :str | None ,b :str | None )-> bool : 158if not a or not b : 159return False 160try : 161return os .path .samefile (a ,b ) 162except OSError : 163return os .path .normcase (os .path .abspath (a ))== os .path .normcase (os .path .abspath (b )) 164 165 166@dataclass( frozen = True ) 167class Ident : 168pid :int 169token :str 170cmd :tuple [str , ...] 171 172 173def identify (pid :int )-> Ident | None : 174"""The live process at `pid`, with the facts a record is later compared with.""" 175token = start_token (pid ) 176cmd = command_line (pid ) 177if token is None or not cmd : 178return None 179return Ident (pid ,token ,tuple (cmd )) 180 181 182def is_same (pid :int ,token :str ,cmd :list [str ]| tuple [str , ...]| None )-> bool : 183"""True only when the process now at `pid` started at `token` and runs exactly `cmd`.""" 184if start_token (pid )!= token : 185return False 186now = command_line (pid ) 187return bool (now )and list (now )== list (cmd or []) 188 189 190# ---------------------------------------------------------------------------------------------- records 191 192def procs_dir (create :bool = True )-> Path : 193"""The owner-private folder of launch records (beside runtime/, under the per-user state).""" 194base = paths .state_base ()/ "procs" 195if create and not base .exists (): 196_private_mkdir (base ,parents = True ,exist_ok = True ) 197if WINDOWS : 198from strata_control import private_files 199private_files .restrict_to_current_user (base ,directory = True ) 200return base 201 202 203def write_record (pid :int ,role :str ,* ,profile :str | None = None ,cmd :list [str ]| None = None , 204parent_pid :int | None = None )-> str | None : 205"""Record that this process started `pid`; returns the process's start token (None: nothing was written). 206Best effort: a record that cannot be written never stops a launch.""" 207try : 208token = start_token (pid ) 209command = list (cmd )if cmd else command_line (pid ) 210parent_pid = os .getpid ()if parent_pid is None else parent_pid 211parent_token = start_token (parent_pid ) 212if token is None or not command or parent_token is None : 213return None 214record = {"schema" :SCHEMA ,"pid" :pid ,"token" :token ,"cmd" :command ,"role" :role , 215"profile" :profile ,"parent" : {"pid" :parent_pid ,"token" :parent_token }, 216"written_at" :time .time ()} 217path = procs_dir ()/ f" { pid } .json" 218tmp = path .with_suffix (f". { os . getpid () } .tmp" ) 219tmp .write_text (json .dumps (record ),encoding = "utf-8" ) 220_atomic_mod .replace (tmp ,path ) 221return token 222except (OSError ,ValueError ): 223return None 224 225 226def drop_record (pid :int ,token :str | None = None )-> None : 227"""Delete the record of `pid`; with `token`, only if it is the record of that process (not of a later one).""" 228path = procs_dir (create = False )/ f" { pid } .json" 229try : 230if token is not None : 231record = _load (path ) 232if record is None or record ["token" ]!= token : 233return 234path .unlink (missing_ok = True ) 235except OSError : 236pass 237 238 239def _load (path :Path )-> dict | None : 240try : 241if path .stat ().st_size > 16 * 1024 : 242return None 243record = json .loads (path .read_text (encoding = "utf-8" )) 244except (OSError ,ValueError ): 245return None 246ok = (isinstance (record ,dict )and record .get ("schema" )== SCHEMA and type (record .get ("pid" ))is int and 247isinstance (record .get ("token" ),str )and isinstance (record .get ("cmd" ),list )and 248all (isinstance (part ,str )for part in record ["cmd" ])and isinstance (record .get ("parent" ),dict )and 249type (record ["parent" ].get ("pid" ))is int and isinstance (record ["parent" ].get ("token" ),str )) 250return record if ok else None 251 252 253def records (profile :str | None = None )-> list [dict ]: 254base = procs_dir (create = False ) 255if not base .is_dir (): 256return [] 257found = [] 258for path in sorted (base .glob ("*.json" )): 259record = _load (path ) 260if record is None : 261continue 262if profile is None or record .get ("profile" )== profile : 263found .append (record ) 264return found 265 266 267# ---------------------------------------------------------------------------------------------- leftovers 268 269def leftovers (profile :str | None = None ,* ,forget_stale :bool = True )-> tuple [list [dict ],list [dict ]]: 270"""(to_end, unverifiable). `to_end`: recorded processes that still run as exactly what was recorded whose 271parent is no longer that process. Records of processes that have gone, or whose PID now belongs to something 272else, are deleted (when `forget_stale`); the stranger is not touched. `unverifiable`: still running but their 273command line cannot be read here, so they are reported and left alone.""" 274to_end ,unverifiable = [], [] 275for record in records (profile ): 276pid = record ["pid" ] 277token = start_token (pid ) 278if token is None or token != record ["token" ]: 279if forget_stale : 280drop_record (pid ) 281continue 282parent = record ["parent" ] 283if start_token (parent ["pid" ])== parent ["token" ]: 284continue # its starter is still there: not a leftover 285if is_same (pid ,record ["token" ],record ["cmd" ]): 286to_end .append (record ) 287elif command_line (pid )is None : 288unverifiable .append (record ) 289elif forget_stale : 290drop_record (pid )# same start time, different command line: not ours 291return to_end ,unverifiable 292 293 294def _signal_verified (record :dict ,sig :int )-> bool : 295"""Signal the recorded process, but only if it is still the recorded process at this instant.""" 296if not is_same (record ["pid" ],record ["token" ],record ["cmd" ]): 297return False 298try : 299os .kill (record ["pid" ],sig ) 300except (ProcessLookupError ,PermissionError ): 301return False 302return True 303 304 305def end_one (record :dict ,* ,grace :float = 8.0 ,settle :float = 10.0 ,say = None )-> str : 306"""End one verified leftover: a polite signal where the OS has one, then a kill after `grace` seconds, then up to 307`settle` seconds for it to be gone (#4051: an engine holding tens of GB of pinned memory can take longer than the 30810 s that were enough for a small process; `say` is told every ~10 s while it is waited for). 309Returns 'gone' (already not running), 'ended' or 'stuck'.""" 310pid = record ["pid" ] 311if not is_same (pid ,record ["token" ],record ["cmd" ]): 312drop_record (pid ) 313return "gone" 314# once signalled, the start token alone says it still runs: an exiting process has an empty command line on Linux 315def running (): 316return start_token (pid )== record ["token" ] 317if not WINDOWS : 318_signal_verified (record ,signal .SIGTERM ) 319deadline = time .monotonic ()+ grace 320while time .monotonic ()< deadline and running (): 321time .sleep (0.1 ) 322if is_same (pid ,record ["token" ],record ["cmd" ]): 323_signal_verified (record ,signal .SIGKILL ) 324else : 325if is_same (pid ,record ["token" ],record ["cmd" ]): 326subprocess .run (["taskkill" ,"/F" ,"/PID" ,str (pid )],capture_output = True )# one PID, verified just above 327started = time .monotonic () 328deadline = started + settle 329told = 0 330while time .monotonic ()< deadline and running (): 331time .sleep (0.1 ) 332waited = int ((time .monotonic ()- started )// 10 ) 333if say is not None and waited > told : 334told = waited 335say (f"[strata] still waiting for process { pid } to give its memory back ( { told * 10 } s)" ) 336if running (): 337return "stuck" 338drop_record (pid ) 339return "ended" 340 341 342def end_leftovers (profile :str | None = None ,* ,grace :float = 8.0 ,settle :float = 10.0 ,say = None )-> dict : 343"""End every verified leftover (children first: a record whose parent is itself a leftover goes last).""" 344to_end ,unverifiable = leftovers (profile ) 345children_first = sorted (to_end ,key = lambda r :r ["written_at" ],reverse = True ) 346result = {"ended" : [],"gone" : [],"stuck" : [],"unverifiable" : [ 347 {"pid" :r ["pid" ],"role" :r .get ("role" )}for r in unverifiable ]} 348for record in children_first : 349outcome = end_one (record ,grace = grace ,settle = settle ,say = say ) 350result [outcome ].append ({"pid" :record ["pid" ],"role" :record .get ("role" ),"profile" :record .get ("profile" )}) 351if say is not None and outcome != "gone" : 352say (f"[strata] leftover { record . get ( 'role' , 'process' ) } { record [ 'pid' ] } { outcome } " ) 353return result 354 355 356# ---------------------------------------------------------------------------- engines older versions left 357 358def _short_name (path :str )-> str | None : 359"""The 8.3 name Windows gives the file at `path` (None where there is none or it cannot be read).""" 360try : 361import ctypes 362buf = ctypes .create_unicode_buffer (32768 ) 363n = ctypes .windll .kernel32 .GetShortPathNameW (str (path ),buf ,len (buf )) 364return os .path .basename (buf .value )if 0 < n < len (buf )else None 365except (AttributeError ,OSError ,ValueError ): 366return None 367 368 369def _name_may_be (name :str ,base :str ,short :str | None )-> bool : 370"""Could a process whose image name is `name` be the engine file `base`? Loose on purpose (same_file decides): the same name in 371any case, the file's own 8.3 name, or any 8.3-looking name (STEM~N.EXT) whose stem starts the engine's name.""" 372n = name .lower () 373if n == base or (short is not None and n == short ): 374return True 375stem = n .split ("~" ,1 )[0 ]if "~" in n else "" 376return bool (stem )and base .replace (" " ,"" ).startswith (stem ) 377 378 379def _engine_candidates (engine_exe :str ): 380"""psutil processes (with info pid, ppid, cmdline, create_time) that could be `engine_exe`. 381 382Windows: reading a command line costs 30-150 ms for each protected process that refuses it (svchost, lsass ...): over 250 processes 383that was 4-9 s at every server start. So the names come first (cheap) and only a process whose image name can be the engine's 384file is read in full; a process whose name cannot be read is read in full as before. Elsewhere every process is read, as before 385(a Linux name is the 15-character comm and can be a link's name).""" 386full = ["pid" ,"ppid" ,"cmdline" ,"create_time" ] 387if not WINDOWS : 388yield from psutil .process_iter (full ) 389return 390import ntpath # Windows path rules (os.path there; named so the tests can run elsewhere) 391base = ntpath .basename (str (engine_exe )).lower () 392short = (_short_name (engine_exe )or "" ).lower ()or None 393for p in psutil .process_iter (["pid" ,"name" ]): 394name = p .info .get ("name" ) 395if name and not _name_may_be (name ,base ,short ): 396continue 397try : 398p .info = p .as_dict (attrs = full ) 399except (psutil .Error ,OSError ): 400continue 401yield p 402 403 404def orphans_of (engine_exe :str )-> list [Ident ]: 405"""Processes that are exactly this engine executable, running ``--serve``, whose parent no longer exists. 406 407Earlier Strata versions wrote no record. Such an engine is not a service anybody started on purpose: the 408server that owned it is gone, and it holds the GPU. Only the executable that is about to be started is 409matched, never another installation's, and a process whose parent is alive is never an orphan.""" 410if psutil is None or not engine_exe : 411return [] 412mine = {os .getpid ()} 413try : 414# pid 1 and a subreaper such as `systemd --user` (an ancestor of every desktop terminal) adopt orphans: they are not starters 415mine .update (q .pid for q in psutil .Process ().parents ()if q .pid != 1 and q .name ().lower ()not in INIT_NAMES ) 416except psutil .Error : 417pass 418found = [] 419for p in _engine_candidates (engine_exe ): 420try : 421cmd = p .info .get ("cmdline" )or [] 422if "--serve" not in cmd or p .pid in mine : 423continue 424if not same_file (p .exe (),engine_exe ): 425continue 426parent = p .info .get ("ppid" ) 427if parent in mine : 428continue # started by this server (or by a process above it) 429if parent and parent != 1 : 430try : 431q = psutil .Process (parent ) 432adopted = q .name ().lower ()in INIT_NAMES # an init that adopts orphans did not start it 433if not adopted and q .create_time ()<= p .info ["create_time" ]+ 1.0 and q .status ()!= psutil .STATUS_ZOMBIE : 434continue # a live parent started it: not an orphan 435except psutil .NoSuchProcess : 436pass 437ident = identify (p .pid ) 438if ident is not None : 439found .append (ident ) 440except (psutil .Error ,OSError ): 441continue 442return found 443 444 445def end_orphans (engine_exe :str ,* ,grace :float = 8.0 ,settle :float = 10.0 ,say = None )-> list [dict ]: 446"""End the orphans of `engine_exe` (see `orphans_of`), re-verified one by one.""" 447ended = [] 448for ident in orphans_of (engine_exe ): 449record = {"pid" :ident .pid ,"token" :ident .token ,"cmd" :list (ident .cmd ),"role" :"engine" ,"written_at" :0 } 450outcome = end_one (record ,grace = grace ,settle = settle ,say = say ) 451ended .append ({"pid" :ident .pid ,"outcome" :outcome }) 452if say is not None and outcome != "gone" : 453say (f"[strata] an engine left behind by an earlier run (pid { ident . pid } ) { outcome } " ) 454return ended