okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1"""Leftover detection: a process is ended only when it is exactly what Strata recorded and its starter is gone.""" 2 3import json 4import os 5import subprocess 6import sys 7import tempfile 8import time 9import unittest 10from pathlib import Path 11from unittest import mock 12 13from strata_control import procs 14 15SLEEP = [sys .executable ,"-c" ,"import time; time.sleep(120)" ] 16NO_WINDOW = getattr (subprocess ,"CREATE_NO_WINDOW" ,0 ) 17 18 19class Procs (unittest .TestCase ): 20def setUp (self ): 21self .temp = tempfile .TemporaryDirectory (prefix = "strata-procs-" ) 22self .addCleanup (self .temp .cleanup ) 23patcher = mock .patch .dict (os .environ , {"LOCALAPPDATA" :self .temp .name ,"XDG_STATE_HOME" :self .temp .name }) 24patcher .start () 25self .addCleanup (patcher .stop ) 26self .started = [] 27self .addCleanup (self ._kill_all ) 28 29def _kill_all (self ): 30for proc in self .started : 31if proc .poll ()is None : 32proc .kill () 33proc .wait (timeout = 10 ) 34 35def sleeper (self ): 36proc = subprocess .Popen (SLEEP ,creationflags = NO_WINDOW ) 37self .started .append (proc ) 38deadline = time .monotonic ()+ 10 39while procs .identify (proc .pid )is None and time .monotonic ()< deadline : 40time .sleep (0.05 ) 41return proc 42 43def recorded_pair (self ): 44"""(starter, child, record): a recorded child of a starter that is then ended.""" 45starter ,child = self .sleeper (),self .sleeper () 46self .assertIsNotNone (procs .write_record (child .pid ,"engine" ,profile = "app-1" ,parent_pid = starter .pid )) 47return starter ,child 48 49def gone (self ,proc ,seconds = 15 ): 50try : 51proc .wait (timeout = seconds ) 52return True 53except subprocess .TimeoutExpired : 54return False 55 56def test_a_child_whose_starter_is_gone_is_a_leftover_and_is_ended (self ): 57starter ,child = self .recorded_pair () 58self .assertEqual (procs .leftovers ()[0 ], [],"its starter is alive: not a leftover" ) 59starter .kill ();starter .wait (timeout = 10 ) 60found ,unverifiable = procs .leftovers () 61self .assertEqual ([r ["pid" ]for r in found ], [child .pid ]) 62self .assertEqual (unverifiable , []) 63result = procs .end_leftovers (grace = 2 ) 64self .assertEqual ([r ["pid" ]for r in result ["ended" ]], [child .pid ]) 65self .assertTrue (self .gone (child )) 66self .assertEqual (procs .records (), [],"the record goes with the process" ) 67 68def test_a_child_with_a_live_starter_is_never_touched (self ): 69starter ,child = self .recorded_pair () 70result = procs .end_leftovers (grace = 1 ) 71self .assertEqual ((result ["ended" ],result ["stuck" ]), ([], [])) 72self .assertIsNone (child .poll ()) 73 74def test_a_reused_pid_is_not_the_recorded_process (self ): 75starter ,child = self .recorded_pair () 76path = procs .procs_dir ()/ f" { child . pid } .json" 77record = json .loads (path .read_text (encoding = "utf-8" )) 78record ["token" ]= "x:not-this-process" # what a later process with the same number looks like 79path .write_text (json .dumps (record ),encoding = "utf-8" ) 80starter .kill ();starter .wait (timeout = 10 ) 81result = procs .end_leftovers (grace = 1 ) 82self .assertEqual ((result ["ended" ],result ["stuck" ]), ([], [])) 83self .assertIsNone (child .poll (),"a stranger with the recorded PID must be left alone" ) 84self .assertEqual (procs .records (), [],"the stale record is dropped" ) 85 86def test_the_same_start_time_with_another_command_line_is_not_ended (self ): 87starter ,child = self .recorded_pair () 88path = procs .procs_dir ()/ f" { child . pid } .json" 89record = json .loads (path .read_text (encoding = "utf-8" )) 90record ["cmd" ]= [sys .executable ,"-c" ,"something else" ] 91path .write_text (json .dumps (record ),encoding = "utf-8" ) 92starter .kill ();starter .wait (timeout = 10 ) 93result = procs .end_leftovers (grace = 1 ) 94self .assertEqual ((result ["ended" ],result ["stuck" ]), ([], [])) 95self .assertIsNone (child .poll ()) 96 97def test_a_profile_filter_only_ends_that_profiles_leftovers (self ): 98starter ,child = self .recorded_pair () 99other_starter ,other = self .sleeper (),self .sleeper () 100procs .write_record (other .pid ,"engine" ,profile = "app-2" ,parent_pid = other_starter .pid ) 101starter .kill ();other_starter .kill () 102starter .wait (timeout = 10 );other_starter .wait (timeout = 10 ) 103result = procs .end_leftovers (profile = "app-1" ,grace = 2 ) 104self .assertEqual ([r ["pid" ]for r in result ["ended" ]], [child .pid ]) 105self .assertIsNone (other .poll (),"another profile's leftover is not part of this stop" ) 106 107def test_garbage_in_the_records_folder_is_ignored (self ): 108base = procs .procs_dir () 109 (base / "1.json" ).write_text ("{not json" ,encoding = "utf-8" ) 110 (base / "2.json" ).write_text (json .dumps ({"schema" :1 ,"pid" :"no" }),encoding = "utf-8" ) 111 (base / "3.json" ).write_text ("x" * 40000 ,encoding = "utf-8" ) 112self .assertEqual (procs .records (), []) 113self .assertEqual (procs .end_leftovers ()["ended" ], []) 114 115def test_an_engine_orphan_of_this_executable_is_found_and_a_live_one_is_not (self ): 116# an "engine": this interpreter running --serve; its starter is gone after the middle process exits 117code = ("import subprocess,sys; p=subprocess.Popen([sys.executable,'-c','import time; time.sleep(120)','--serve']," 118"stdin=subprocess.DEVNULL,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL," 119"creationflags=%d); print(p.pid, flush=True)" % NO_WINDOW ) 120middle = subprocess .run ([sys .executable ,"-c" ,code ],capture_output = True ,text = True ,timeout = 30 ) 121orphan_pid = int (middle .stdout .split ()[0 ]) 122self .addCleanup (lambda :procs .start_token (orphan_pid )and os .kill (orphan_pid ,9 )) 123deadline = time .monotonic ()+ 10 124while procs .identify (orphan_pid )is None and time .monotonic ()< deadline : 125time .sleep (0.05 ) 126live = subprocess .Popen ([* SLEEP ,"--serve" ],creationflags = NO_WINDOW ) 127self .started .append (live ) 128deadline = time .monotonic ()+ 10 129while procs .identify (live .pid )is None and time .monotonic ()< deadline : 130time .sleep (0.05 ) 131found = [i .pid for i in procs .orphans_of (sys .executable )] 132self .assertIn (orphan_pid ,found ) 133self .assertNotIn (live .pid ,found ,"this test process started it: a live parent" ) 134self .assertEqual (procs .orphans_of (str (Path (sys .executable ).with_name ("not-the-engine" ))), []) 135ended = procs .end_orphans (sys .executable ,grace = 2 ) 136self .assertIn (orphan_pid , [e ["pid" ]for e in ended ]) 137self .assertIsNone (live .poll ()) 138self .assertIsNone (procs .start_token (orphan_pid )) 139 140class SubreaperOrphans (unittest .TestCase ): 141"""An engine adopted by `systemd --user` is an orphan (#3254), and a dying process is waited for by its start token.""" 142 143class Gone (Exception ): 144pass 145 146def fake_psutil (self ,ancestors ,parent_name ): 147class Err (Exception ): 148pass 149 150class NoSuch (Err ): 151pass 152 153def proc (pid ,name ,ppid = 1 ): 154info = {"pid" :pid ,"ppid" :ppid ,"cmdline" : ["engine" ,"--serve" ],"create_time" :100.0 } 155return mock .Mock (pid = pid ,** {"name.return_value" :name ,"exe.return_value" :"/x/engine" ,"info" :info , 156"as_dict.return_value" :info }) 157 158me = mock .Mock (** {"parents.return_value" : [proc (p ,n )for p ,n in ancestors ]}) 159engine = proc (7000 ,"engine" ,ppid = 5000 ) 160parent = proc (5000 ,parent_name ) 161parent .create_time .return_value = 50.0 162parent .status .return_value = "running" 163fake = mock .Mock (Error = Err ,NoSuchProcess = NoSuch ,STATUS_ZOMBIE = "zombie" ) 164fake .Process .side_effect = lambda pid = None :me if pid is None else parent 165fake .process_iter .return_value = [engine ] 166return fake 167 168def found (self ,ancestors ,parent_name ): 169fake = self .fake_psutil (ancestors ,parent_name ) 170with mock .patch .object (procs ,"psutil" ,fake ),mock .patch .object (procs ,"same_file" ,return_value = True ), \ 171mock .patch .object (procs ,"identify" ,side_effect = lambda pid : ("ident" ,pid )): 172return procs .orphans_of ("/x/engine" ) 173 174def test_an_engine_adopted_by_systemd_user_is_an_orphan_even_when_it_is_an_ancestor_of_the_terminal (self ): 175# systemd --user (pid 5000) is an ancestor of every desktop terminal and adopts what loses its parent 176self .assertEqual (self .found ([(5000 ,"systemd" ), (6000 ,"bash" )],"systemd" ), [("ident" ,7000 )]) 177 178def test_an_engine_whose_parent_is_a_real_ancestor_is_not_an_orphan (self ): 179# started by this server's own shell: not touched 180self .assertEqual (self .found ([(5000 ,"bash" ), (6000 ,"tmux" )],"bash" ), []) 181 182def test_ending_waits_on_the_start_token_not_on_an_empty_command_line (self ): 183record = {"pid" :4242 ,"token" :"t1" ,"cmd" : ["engine" ,"--serve" ]} 184answers = ["t1" ,"t1" ]# still exiting twice, then gone 185def token (pid ): 186return answers .pop (0 )if answers else None 187with mock .patch .object (procs ,"WINDOWS" ,False ),mock .patch .object (procs ,"is_same" ,side_effect = [True ,False ,False ])as same , \ 188mock .patch .object (procs ,"_signal_verified" ),mock .patch .object (procs ,"start_token" ,side_effect = token ), \ 189mock .patch .object (procs ,"drop_record" ),mock .patch .object (procs .time ,"sleep" ): 190self .assertEqual (procs .end_one (record ,grace = 5 ),"ended" ) 191self .assertGreaterEqual (same .call_count ,1 ) 192 193def slow_exit (self ,exits_after ,** kw ): 194"""end_one of a process that is still there `exits_after` virtual seconds after the kill (a fake clock).""" 195record = {"pid" :4243 ,"token" :"t1" ,"cmd" : ["engine" ,"--serve" ]} 196now = [0.0 ] 197said = [] 198 199def sleep (s ): 200now [0 ]+= s 201 202def token (pid ): 203return "t1" if now [0 ]< exits_after else None 204with mock .patch .object (procs ,"WINDOWS" ,False ),mock .patch .object (procs ,"is_same" ,side_effect = lambda * a :token (0 )is not None ), \ 205mock .patch .object (procs ,"_signal_verified" ),mock .patch .object (procs ,"start_token" ,side_effect = token ), \ 206mock .patch .object (procs ,"drop_record" ),mock .patch .object (procs .signal ,"SIGKILL" ,9 ,create = True ), \ 207mock .patch .object (procs .time ,"sleep" ,side_effect = sleep ), \ 208mock .patch .object (procs .time ,"monotonic" ,side_effect = lambda :now [0 ]): 209return procs .end_one (record ,say = said .append ,** kw ),said 210 211def test_an_engine_that_needs_longer_than_ten_seconds_to_give_its_memory_back_is_waited_for (self ): 212# #4051: 50 GiB of pinned memory is released by the kernel after the signal; the next engine started beside it 213outcome ,_ = self .slow_exit (25.0 )# the old limit: 8 s grace + 10 s 214self .assertEqual (outcome ,"stuck" ) 215outcome ,said = self .slow_exit (40.0 ,settle = 120.0 ) 216self .assertEqual (outcome ,"ended" ) 217self .assertTrue (said and "still waiting for process 4243" in said [0 ],said ) 218self .assertEqual (self .slow_exit (40.0 ,settle = 10.0 )[0 ],"stuck" ) 219 220 221class WindowsOrphanScan (unittest .TestCase ): 222"""orphans_of on Windows reads names first and a command line only where the name can be the engine's file: 257 processes took 2234-9 s at every server start when every command line was read (30-150 ms for each protected process that refuses it).""" 224 225ENGINE = r"C:\Strata\engine\strata-vision-hip.exe" 226OTHER = r"C:\Old\engine\strata-vision-hip.exe" 227 228def table (self ): 229e ,o = self .ENGINE ,self .OTHER 230# pid: (name or an exception, exe, cmdline or an exception) 231return { 232101 : ("strata-vision-hip.exe" ,e , [e ,"--serve" ]),# an orphan 233102 : ("STRATA-VISION-HIP.EXE" ,e , [e ,"--serve" ]),# upper case 234103 : ("STRATA~1.EXE" ,e , [e ,"--serve" ]),# started through its 8.3 path 235104 : (PermissionError ,e , [e ,"--serve" ]),# the name cannot be read: read in full 236105 : ("svchost.exe" ,r"C:\Windows\System32\svchost.exe" ,PermissionError ), 237106 : ("lsass.exe" ,r"C:\Windows\System32\lsass.exe" ,PermissionError ), 238107 : ("strata-vision-hip.exe" ,o , [o ,"--serve" ]),# another installation's engine 239108 : ("strata-vision-hip.exe" ,e , [e ]),# not serving 240109 : ("chrome.exe" ,r"C:\Chrome\chrome.exe" , ["chrome.exe" ,"--serve" ]), 241 } 242 243def fake_psutil (self ,table ,asked ): 244class Err (Exception ): 245pass 246 247class NoSuch (Err ): 248pass 249 250class Denied (Err ): 251pass 252 253def read (pid ,attr ): 254name ,exe ,cmd = table [pid ] 255value = {"pid" :pid ,"ppid" :4242 ,"create_time" :100.0 ,"name" :name ,"cmdline" :cmd }[attr ] 256if attr == "cmdline" : 257asked .append (pid ) 258if isinstance (value ,type )and issubclass (value ,Exception ): 259raise Denied () 260return value 261 262def as_dict (pid ,attrs ): 263out = {} 264for a in attrs : 265try : 266out [a ]= read (pid ,a ) 267except Denied : 268out [a ]= None # as psutil: a refused value is None 269return out 270 271def proc (pid ,attrs ): 272p = mock .Mock (pid = pid ,info = as_dict (pid ,attrs )) 273p .as_dict .side_effect = lambda attrs = None :as_dict (pid ,attrs ) 274p .exe .side_effect = lambda :table [pid ][1 ] 275return p 276 277def process (pid = None ): 278if pid is None : 279return mock .Mock (** {"parents.return_value" : []}) 280raise NoSuch ()# every parent (4242) is gone: an orphan 281 282fake = mock .Mock (Error = Err ,NoSuchProcess = NoSuch ,STATUS_ZOMBIE = "zombie" ) 283fake .Process .side_effect = process 284fake .process_iter .side_effect = lambda attrs : [proc (pid ,attrs )for pid in table ] 285return fake 286 287def scan (self ,windows ,table = None ): 288table = table or self .table () 289asked = [] 290same = lambda a ,b :bool (a )and bool (b )and a .lower ()== b .lower ()# noqa: E731 291with mock .patch .object (procs ,"psutil" ,self .fake_psutil (table ,asked )),mock .patch .object (procs ,"WINDOWS" ,windows ), \ 292mock .patch .object (procs ,"same_file" ,side_effect = same ),mock .patch .object (procs ,"_short_name" ,return_value = None ), \ 293mock .patch .object (procs ,"identify" ,side_effect = lambda pid : ("ident" ,pid )): 294found = sorted (i [1 ]for i in procs .orphans_of (self .ENGINE )) 295return found ,asked 296 297def test_the_same_orphans_as_reading_every_process (self ): 298new ,_ = self .scan (windows = True ) 299old ,_ = self .scan (windows = False )# the full read, as before (and as Linux and macOS still do) 300self .assertEqual (new ,old ) 301self .assertEqual (new , [101 ,102 ,103 ,104 ]) 302 303def test_a_process_that_cannot_be_the_engine_is_never_asked_for_its_command_line (self ): 304_ ,asked = self .scan (windows = True ) 305self .assertEqual (sorted (asked ), [101 ,102 ,103 ,104 ,107 ,108 ]) 306_ ,asked_before = self .scan (windows = False ) 307self .assertEqual (sorted (asked_before ),sorted (self .table ())) 308 309def test_the_files_own_short_name_matches (self ): 310self .assertTrue (procs ._name_may_be ("SVIHIP~2.EXE" ,"strata-vision-hip.exe" ,"svihip~2.exe" )) 311self .assertTrue (procs ._name_may_be ("STRATA~3.EXE" ,"strata-vision-hip.exe" ,None )) 312self .assertFalse (procs ._name_may_be ("svchost.exe" ,"strata-vision-hip.exe" ,None )) 313self .assertFalse (procs ._name_may_be ("OTHER~1.EXE" ,"strata-vision-hip.exe" ,None )) 314 315def test_a_hard_link_under_another_name_is_left_to_the_full_read_only_off_windows (self ): 316# The full read matches any name that is the same file (os.path.samefile); the name filter does not. Strata never links an 317# engine under another name (setup's links are model files under their own name), so this is a hand-made case. 318e = self .ENGINE 319table = {201 : ("my-engine.exe" ,e , [e ,"--serve" ])} 320self .assertEqual (self .scan (windows = False ,table = table )[0 ], [201 ]) 321self .assertEqual (self .scan (windows = True ,table = table )[0 ], []) 322 323 324if __name__ == "__main__" : 325unittest .main ()