okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""#4260: `strata bench run --profile` ends the engine it started, with the program it started, and says so only when something is left. 2 3The engine tree is the server (`strata serve`), the engine it starts and whatever those start. On Windows the tree is put in a job object this run owns, 4so a per-process `taskkill` that is refused ("Access is denied" on a tree this very user started) no longer leaves it running; on Linux and macOS it is the 5process group. An unrelated process with the same program name is never touched. 6 7python -m pytest tests/terminal/test_bench_stop.py 8""" 9import os 10import subprocess 11import sys 12import tempfile 13import time 14import unittest 15from pathlib import Path 16from unittest import mock 17 18from strata_cli import bench_standard 19 20WINDOWS = os .name == "nt" 21PARENT = ("import subprocess, sys, time\n" 22"kid = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)'])\n" 23"open(sys.argv[1], 'w').write(str(kid.pid))\n" 24"time.sleep(120)\n" ) 25 26 27def alive (pid :int )-> bool : 28if WINDOWS : 29from strata_control import winproc 30return winproc .pid_alive (pid ,None ) 31try : 32os .kill (pid ,0 ) 33except ProcessLookupError : 34return False 35except PermissionError : 36return True 37# a zombie answers signal 0; only its parent has not collected it 38try : 39return Path (f"/proc/ { pid } /stat" ).read_text ().rsplit (")" ,1 )[1 ].split ()[0 ]!= "Z" 40except OSError : 41# collected between the signal and the read (1 in 15 on a loaded p2006): gone, unless signal 0 still finds it (no /proc) 42try : 43os .kill (pid ,0 ) 44except ProcessLookupError : 45return False 46except PermissionError : 47return True 48return not Path ("/proc" ).is_dir () 49 50 51def describe (pid :int )-> str : 52"""What is left of a process, for a failure message: state, parent, start time and command line, read from /proc.""" 53try : 54fields = Path (f"/proc/ { pid } /stat" ).read_text ().rsplit (")" ,1 )[1 ].split ()# fields[0] is the state (field 3 of the file), fields[1] the parent, fields[19] the start (field 22) 55boot = next (int (line .split ()[1 ])for line in Path ("/proc/stat" ).read_text ().splitlines ()if line .startswith ("btime" )) 56started = time .strftime ("%H:%M:%S" ,time .localtime (boot + int (fields [19 ])/ os .sysconf ("SC_CLK_TCK" ))) 57command = Path (f"/proc/ { pid } /cmdline" ).read_bytes ().replace (b"\0" ,b" " ).decode (errors = "replace" ).strip ()[:160 ] 58return "pid %d state %s, parent %s, started %s, command line %r" % (pid ,fields [0 ],fields [1 ],started ,command ) 59except (OSError ,IndexError ,ValueError ,StopIteration ,AttributeError ): 60return "pid %d: nothing readable in /proc (gone, or no /proc on this system)" % pid 61 62 63class StopEngine (unittest .TestCase ): 64def setUp (self ): 65self .temp = tempfile .TemporaryDirectory (prefix = "strata-benchstop-" ) 66self .addCleanup (self .temp .cleanup ) 67self .pidfile = Path (self .temp .name )/ "kid.pid" 68self .procs = [] 69self .addCleanup (self ._reap ) 70 71def _reap (self ): 72for pid in getattr (self ,"pids" , []): 73try : 74if alive (pid ): 75os .kill (pid ,9 ) 76except OSError : 77pass 78for proc in self .procs : 79if proc .poll ()is None : 80proc .kill () 81try : 82proc .wait (10 ) 83except subprocess .TimeoutExpired : 84pass 85for proc in self .procs : 86handle = getattr (proc ,"_strata_log" ,None ) 87if handle is not None and not handle .closed : 88handle .close () 89time .sleep (0.5 ) 90 91def _start_tree (self ): 92"""What start_engine does: a child of this run, in its own group (POSIX) or process group + job (Windows), with a child of its own.""" 93kwargs = {"creationflags" :getattr (subprocess ,"CREATE_NEW_PROCESS_GROUP" ,0 )}if WINDOWS else {"start_new_session" :True } 94handle = open (Path (self .temp .name )/ "engine.log" ,"wb" ) 95proc = subprocess .Popen ([sys .executable ,"-c" ,PARENT ,str (self .pidfile )],stdout = handle ,stderr = subprocess .STDOUT ,** kwargs ) 96proc ._strata_log = handle 97self .procs .append (proc ) 98if WINDOWS : 99from serve import winjob 100proc ._strata_job = winjob .contain (proc ) 101# wait for the whole pid, not only the file: under load the file can exist, still empty, for longer than a fixed pause 102deadline ,kid = time .monotonic ()+ 60 ,None 103while kid is None and time .monotonic ()< deadline : 104try : 105kid = int (self .pidfile .read_text ().strip ()) 106except (OSError ,ValueError ): 107time .sleep (0.05 ) 108self .assertIsNotNone (kid ,"the stand-in engine did not start its own child within 60 s" ) 109self .pids = [proc .pid ,kid ] 110return proc ,kid 111 112def test_the_child_and_its_child_both_end (self ): 113proc ,kid = self ._start_tree () 114outsider = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(120)" ])# same program, not ours 115self .procs .append (outsider ) 116self .assertTrue (alive (kid )) 117self .assertIsNone (bench_standard .stop_engine (proc )) 118t_stop = time .monotonic () 119deadline = t_stop + 30 # a loaded box can take seconds to deliver and reap 120while alive (kid )and time .monotonic ()< deadline : 121time .sleep (0.1 ) 122# three checks; a failure says which one it is and, for what survived, what it is (state, parent, start, command line) 123if alive (proc .pid ): 124self .fail ("check 1 of 3: the engine's server survived: " + describe (proc .pid )) 125if alive (kid ): 126self .fail ("check 2 of 3: what the engine's server started survived (%.1f s after stop_engine returned): %s" % (time .monotonic ()- t_stop ,describe (kid ))) 127if outsider .poll ()is not None : 128self .fail ("check 3 of 3: a process of the same program that this run did not start was ended (exit code %s)" % outsider .poll ()) 129 130@ unittest . skipUnless ( WINDOWS , "Windows: a refused taskkill" ) 131def test_a_refused_taskkill_does_not_leave_the_tree_running (self ): 132proc ,kid = self ._start_tree () 133refused = subprocess .CompletedProcess (["taskkill" ],128 ,b"" ,b"ERROR: The process could not be terminated.\r\nReason: Access is denied.\r\n" ) 134with mock .patch .object (bench_standard .subprocess ,"run" ,return_value = refused ): 135problem = bench_standard .stop_engine (proc ) 136self .assertIsNone (problem ,"the tree is gone, so there is nothing to report" ) 137deadline = time .monotonic ()+ 10 138while alive (kid )and time .monotonic ()< deadline : 139time .sleep (0.1 ) 140self .assertFalse (alive (kid )) 141 142@ unittest . skipUnless ( WINDOWS , "Windows: every way of ending it refused" ) 143def test_a_tree_that_cannot_be_ended_is_still_reported (self ): 144proc ,kid = self ._start_tree () 145refused = subprocess .CompletedProcess (["taskkill" ],128 ,b"" ,b"Access is denied." ) 146with mock .patch .object (bench_standard .subprocess ,"run" ,return_value = refused ), \ 147mock .patch ("serve.winjob.terminate" ,return_value = False ),mock .patch .object (proc ,"kill" ,side_effect = OSError ("denied" )): 148problem = bench_standard .stop_engine (proc ) 149self .assertIn ("still running" ,problem or "" ) 150 151def test_a_process_that_already_ended_is_nothing_to_stop (self ): 152proc = subprocess .Popen ([sys .executable ,"-c" ,"pass" ]) 153proc .wait (20 ) 154proc ._strata_log = open (os .devnull ,"wb" ) 155self .assertIsNone (bench_standard .stop_engine (proc )) 156 157 158if __name__ == "__main__" : 159unittest .main ()