okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
6ca60e9a0
main
1"""serve/lifeline.py: a process Strata starts ends when the process that started it ends, however that ends. 2 3python -m unittest serve.test_lifeline 4 5Each case runs a small "server" process (a fresh interpreter) that starts a sleeping child through 6`lifeline.popen`, then ends that server the hard way (kill -9 / TerminateProcess), and checks that the child 7is gone. The mechanism under test is Windows' job object, Linux's PR_SET_PDEATHSIG, or the portable watcher 8(forced with STRATA_LIFELINE=watcher so it is proven on every POSIX box, not only on macOS). 9""" 10import json 11import os 12import signal 13import subprocess 14import sys 15import tempfile 16import textwrap 17import time 18import unittest 19from pathlib import Path 20 21ROOT = Path (__file__ ).resolve ().parents [1 ] 22POSIX = os .name == "posix" 23 24SERVER = textwrap .dedent (""" 25import os, sys, time, threading, subprocess 26sys.path.insert(0, {root!r}) 27from serve import lifeline 28mode = sys.argv[1] 29sleeper = [sys.executable, "-c", "import time; time.sleep(600)"] 30out = {{"mechanism": lifeline.mechanism()}} 31if mode == "thread": # started on a request thread that ends at once 32box = [] 33t = threading.Thread(target=lambda: box.append(lifeline.popen(sleeper, "engine"))) 34t.start(); t.join() 35child = box[0] 36else: 37child = lifeline.popen(sleeper, "engine") 38out["child"] = child.pid 39out["server"] = os.getpid() 40print(__import__("json").dumps(out), flush=True) 41if mode == "exit": # ends normally, the child still running 42sys.exit(0) 43time.sleep(600) 44""" ) 45 46 47def alive (pid :int )-> bool : 48from strata_control import procs 49return procs .start_token (pid )is not None 50 51 52class Lifeline (unittest .TestCase ): 53def setUp (self ): 54self .temp = tempfile .TemporaryDirectory (prefix = "strata-lifeline-" ) 55self .addCleanup (self .temp .cleanup ) 56self .env = {** os .environ ,"LOCALAPPDATA" :self .temp .name ,"XDG_STATE_HOME" :self .temp .name , 57"PYTHONPATH" :str (ROOT )} 58self .script = Path (self .temp .name )/ "server.py" 59self .script .write_text (SERVER .format (root = str (ROOT )),encoding = "utf-8" ) 60self .spawned = [] 61self .addCleanup (self ._reap ) 62 63def _reap (self ): 64for pid in self .spawned : 65if alive (pid ): 66try : 67os .kill (pid ,signal .SIGTERM ) 68except OSError : 69pass 70 71def launch (self ,mode ,** env ): 72proc = subprocess .Popen ([sys .executable ,str (self .script ),mode ],stdout = subprocess .PIPE ,text = True , 73env = {** self .env ,** env }) 74info = json .loads (proc .stdout .readline ()) 75self .spawned .append (info ["child" ]) 76self .addCleanup (lambda :proc .poll ()is None and proc .kill ()) 77return proc ,info 78 79def wait_gone (self ,pid ,seconds = 15 ): 80deadline = time .monotonic ()+ seconds 81while time .monotonic ()< deadline : 82if not alive (pid ): 83return True 84time .sleep (0.1 ) 85return not alive (pid ) 86 87def hard_kill (self ,proc ): 88if POSIX : 89os .kill (proc .pid ,signal .SIGKILL ) 90else : 91proc .kill () 92proc .wait (timeout = 10 ) 93 94def _killed_parent_takes_the_child (self ,** env ): 95proc ,info = self .launch ("sleep" ,** env ) 96self .assertTrue (alive (info ["child" ])) 97self .hard_kill (proc ) 98self .assertTrue (self .wait_gone (info ["child" ]),f"the child outlived a killed server ( { info [ 'mechanism' ] } )" ) 99return info ["mechanism" ] 100 101def test_a_child_ends_when_its_server_is_killed (self ): 102self .assertIn (self ._killed_parent_takes_the_child (), ("job" ,"pdeathsig" ,"watcher" )) 103 104@ unittest . skipUnless ( POSIX , "the portable watcher is the POSIX path" ) 105def test_the_portable_watcher_ends_the_child_when_the_server_is_killed (self ): 106self .assertEqual (self ._killed_parent_takes_the_child (STRATA_LIFELINE = "watcher" ),"watcher" ) 107 108@ unittest . skipUnless ( POSIX , "the portable watcher is the POSIX path" ) 109def test_the_watcher_token_does_not_change_with_the_child_state (self ): 110"""The watcher's token has to be the child's START TIME, and nothing that moves while it runs. 111 112The token used to come from `ps -o lstart=,stat=`, so it carried the state character as well. A child 113is R (running) for the first milliseconds of its life and then settles to S (sleeping); the token is 114taken right after `popen`, so the watcher then compared 'S' against its 'R' token, decided the child 115was not the one it had been told about, and exited WITHOUT signalling it. That is the "child outlived 116a killed server" failure, and it appeared or vanished depending on which state the spawn was sampled 117in - which is why it read as a flake. Sampled while the child spins (R) and again while it sleeps 118(S), the token must be the same either way. 119""" 120from serve import lifeline 121from unittest import mock 122# in-process popen() means procs.write_record() would use the REAL per-user state dir; setUp's env only 123# reaches subprocesses. Keep this test's launch record in the temp dir like the other cases. 124with mock .patch .dict (os .environ , {"XDG_STATE_HOME" :self .temp .name ,"LOCALAPPDATA" :self .temp .name }): 125child = lifeline .popen ([sys .executable ,"-c" , 126"import time\nend = time.time() + 1.5\nwhile time.time() < end:\n pass\n" 127"time.sleep(30)" ],"engine" ) 128self .spawned .append (child .pid ) 129self .addCleanup (lambda :child .poll ()is None and child .kill ()) 130 131def state (): 132"""The child's state character, read independently of the code under test ('R' running, 'S' asleep).""" 133out = subprocess .run (["ps" ,"-o" ,"stat=" ,"-p" ,str (child .pid )],capture_output = True ,text = True ).stdout 134return out .strip ()[:1 ] 135 136while_spinning = lifeline ._start_token (child .pid ) 137spinning_state = state () 138time .sleep (2.0 )# asleep by now 139while_sleeping = lifeline ._start_token (child .pid ) 140sleeping_state = state () 141self .assertEqual ((spinning_state ,sleeping_state ), ("R" ,"S" ), 142"the child did not go from running to sleeping, so this proves nothing about the token" ) 143self .assertTrue (while_spinning and while_sleeping , (while_spinning ,while_sleeping )) 144self .assertEqual (while_spinning ,while_sleeping , 145"the token moved with the child's state, so the watcher would skip the kill" ) 146 147@ unittest . skipUnless ( sys . platform . startswith ( "linux" ), "PR_SET_PDEATHSIG is Linux" ) 148def test_a_child_started_on_a_request_thread_outlives_that_thread_but_not_the_server (self ): 149proc ,info = self .launch ("thread" ) 150self .assertEqual (info ["mechanism" ],"pdeathsig" ) 151time .sleep (1.0 ) 152self .assertTrue (alive (info ["child" ]),"the request thread ended and took the child with it" ) 153self .hard_kill (proc ) 154self .assertTrue (self .wait_gone (info ["child" ])) 155 156def test_a_server_that_exits_normally_leaves_nothing_behind (self ): 157proc ,info = self .launch ("exit" ) 158proc .wait (timeout = 15 ) 159self .assertTrue (self .wait_gone (info ["child" ]),"end_children at exit must stop what is still running" ) 160 161def test_the_child_is_recorded_while_it_runs_and_forgotten_after (self ): 162from strata_control import procs 163proc ,info = self .launch ("sleep" ) 164base = Path (self .temp .name )/ "Strata" / "procs" if not POSIX else Path (self .temp .name )/ "strata" / "procs" 165record = base / f" { info [ 'child' ] } .json" 166deadline = time .monotonic ()+ 5 167while not record .exists ()and time .monotonic ()< deadline : 168time .sleep (0.05 ) 169data = json .loads (record .read_text (encoding = "utf-8" )) 170self .assertEqual ((data ["pid" ],data ["role" ],data ["parent" ]["pid" ]), (info ["child" ],"engine" ,info ["server" ])) 171self .assertEqual (data ["token" ],procs .start_token (info ["child" ])) 172self .hard_kill (proc ) 173self .assertTrue (self .wait_gone (info ["child" ])) 174 175 176if __name__ == "__main__" : 177unittest .main () 178 179 180STUBBORN = ( 181"import signal, sys, time\n" 182"if hasattr(signal, 'SIGTERM'): signal.signal(signal.SIGTERM, signal.SIG_IGN)\n" 183"print('READY 4096 stop', flush=True)\n" 184"time.sleep(600)\n" # never reads QUIT, never answers STOP, ignores SIGTERM 185) 186 187 188class HardFallback (unittest .TestCase ): 189"""The clean stop has a deadline: an engine that ignores STOP, QUIT and SIGTERM is killed, and close() returns.""" 190 191def test_an_engine_that_ignores_everything_is_killed (self ): 192from unittest import mock 193from serve import server 194engine = server .StrataEngine ("missing-executable" , [],lazy = True ) 195engine .proc = subprocess .Popen ([sys .executable ,"-c" ,STUBBORN ],stdin = subprocess .PIPE ,stdout = subprocess .PIPE , 196text = True ,creationflags = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 )) 197engine .proc .stdout .readline () 198victim = engine .proc 199t0 = time .monotonic () 200with mock .patch .object (server ,"ENGINE_QUIT_WAIT_S" ,1 ),mock .patch .object (server ,"ENGINE_TERM_WAIT_S" ,1 ), \ 201mock .patch .object (server ,"ENGINE_KILL_WAIT_S" ,10 ): 202engine .close () 203self .assertLess (time .monotonic ()- t0 ,12 ) 204self .assertIsNotNone (victim .poll (),"the engine is still running after close()" ) 205self .assertIsNone (engine .proc ) 206if os .name == "posix" : 207self .assertEqual (victim .returncode ,- signal .SIGKILL ,"it ignored SIGTERM, so only the kill ended it" )