okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
cd9745050
main
1"""serve/winjob.py: a contained child - and whatever it starts - ends when the process that contained it ends, even 2when that process is killed outright (the console window closed, Task Manager), with no cleanup of its own. 3 4python -m unittest serve.test_winjob (Windows only; skipped elsewhere) 5 6The test holds a handle to the child and to the grandchild (kernel32, from the standard library) instead of asking `tasklist` whether a PID is 7listed: a handle names one process object, so a PID that Windows hands out again to some other program cannot pass for the child, and when a 8process is still there after the wait the failure says which process it is (image name, creation time, seconds since the kill). 9""" 10import os 11import subprocess 12import sys 13import time 14import unittest 15from datetime import datetime 16from pathlib import Path 17 18ROOT = Path (__file__ ).resolve ().parent .parent 19sys .path .insert (0 ,str (ROOT )) 20 21# stands in for the server: contains a child that starts a grandchild, prints both pids, then waits to be killed 22PARENT = f""" 23import subprocess, sys, time 24sys.path.insert(0, { str ( ROOT )!r } ) 25from serve.winjob import contain 26code = ("import subprocess, sys, time; g = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(120)']); " 27"print(g.pid, flush=True); time.sleep(120)") 28child = subprocess.Popen([sys.executable, "-c", code], stdout=subprocess.PIPE, text=True) 29ok = contain(child) 30print(ok, child.pid, child.stdout.readline().strip(), flush=True) 31time.sleep(120) 32""" 33 34_PROCESS_TERMINATE ,_PROCESS_QUERY_LIMITED_INFORMATION ,_SYNCHRONIZE = 0x0001 ,0x1000 ,0x00100000 35_WAIT_OBJECT_0 = 0 36_FILETIME_UNIX_EPOCH_S = 11644473600 # seconds from 1601-01-01 (FILETIME) to 1970-01-01 37 38if os .name == "nt" : 39import ctypes 40from ctypes import wintypes 41 42_k32 = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 43_k32 .OpenProcess .restype = wintypes .HANDLE 44_k32 .OpenProcess .argtypes = (wintypes .DWORD ,wintypes .BOOL ,wintypes .DWORD ) 45_k32 .CloseHandle .argtypes = (wintypes .HANDLE ,) 46_k32 .WaitForSingleObject .restype = wintypes .DWORD 47_k32 .WaitForSingleObject .argtypes = (wintypes .HANDLE ,wintypes .DWORD ) 48_k32 .TerminateProcess .argtypes = (wintypes .HANDLE ,wintypes .UINT ) 49_k32 .GetProcessTimes .argtypes = (wintypes .HANDLE ,)+ (ctypes .POINTER (wintypes .FILETIME ),)* 4 50_k32 .QueryFullProcessImageNameW .argtypes = (wintypes .HANDLE ,wintypes .DWORD ,wintypes .LPWSTR ,ctypes .POINTER (wintypes .DWORD )) 51 52 53def _identity (handle )-> tuple [str ,float ]: 54"""(image file name, creation time as seconds since 1970) of the process behind an open handle.""" 55created ,a ,b ,c = (wintypes .FILETIME ()for _ in range (4 )) 56if not _k32 .GetProcessTimes (handle ,ctypes .byref (created ),ctypes .byref (a ),ctypes .byref (b ),ctypes .byref (c )): 57raise ctypes .WinError (ctypes .get_last_error ()) 58text ,size = ctypes .create_unicode_buffer (1024 ),wintypes .DWORD (1024 ) 59name = Path (text .value ).name if _k32 .QueryFullProcessImageNameW (handle ,0 ,text ,ctypes .byref (size ))else "?" 60return name , ((created .dwHighDateTime << 32 )| created .dwLowDateTime )/ 1e7 - _FILETIME_UNIX_EPOCH_S 61 62 63def _when (seconds :float )-> str : 64return datetime .fromtimestamp (seconds ).strftime ("%H:%M:%S.%f" )[:- 3 ] 65 66 67class Held : 68"""A process held by a handle. The handle keeps the process object (and so its identity) alive; `exited()` asks that object, never the PID.""" 69 70def __init__ (self ,pid :int ,label :str ): 71self .pid ,self .label = pid ,label 72self .handle = _k32 .OpenProcess (_SYNCHRONIZE | _PROCESS_QUERY_LIMITED_INFORMATION | _PROCESS_TERMINATE ,False ,pid ) 73if not self .handle : 74raise ctypes .WinError (ctypes .get_last_error ()) 75self .image ,self .created = _identity (self .handle ) 76 77def exited (self )-> bool : 78return _k32 .WaitForSingleObject (self .handle ,0 )== _WAIT_OBJECT_0 79 80def holder_of_the_pid_now (self )-> str : 81"""What a fresh OpenProcess by PID finds: image name and creation time, and whether it is the process held here.""" 82handle = _k32 .OpenProcess (_PROCESS_QUERY_LIMITED_INFORMATION ,False ,self .pid ) 83if not handle : 84return "no process has the PID" 85try : 86image ,created = _identity (handle ) 87finally : 88_k32 .CloseHandle (handle ) 89same = abs (created - self .created )< 0.001 # the creation time is what tells two processes with one PID apart (an exited process has no image name to ask for) 90return "%s created %s (%s)" % (image if image != "?" else "an exited process" ,_when (created ),"the same process" if same else "NOT the process held" ) 91 92def explain (self ,since_kill :float )-> str : 93listed = subprocess .run (["tasklist" ,"/FI" ,f"PID eq { self . pid } " ,"/NH" ],capture_output = True ,text = True ).stdout .strip ().replace ("\n" ," | " ) 94return ("%s outlived the server: pid %d is %s, created %s; %.1f s after the kill it is still running; the PID is held now by: %s; tasklist: %s" 95% (self .label ,self .pid ,self .image ,_when (self .created ),since_kill ,self .holder_of_the_pid_now (),listed or "-" )) 96 97def end (self )-> None : 98if self .handle : 99if not self .exited ():# on a failure, don't leave them sleeping (this very process, by handle) 100_k32 .TerminateProcess (self .handle ,1 ) 101_k32 .CloseHandle (self .handle ) 102self .handle = None 103 104 105@ unittest . skipUnless ( os . name == "nt" , "job objects are Windows-only" ) 106class TestWinJob (unittest .TestCase ): 107def test_children_end_with_a_killed_server (self ): 108# a venv's python.exe is a launcher that runs the real interpreter as its child: kill() must reach the latter 109python = getattr (sys ,"_base_executable" ,None )or sys .executable 110parent = subprocess .Popen ([python ,"-c" ,PARENT ],stdout = subprocess .PIPE ,text = True ) 111child = grandchild = None 112try : 113ok ,child_pid ,grandchild_pid = parent .stdout .readline ().split () 114child ,grandchild = Held (int (child_pid ),"the child" ),Held (int (grandchild_pid ),"the grandchild" ) 115self .assertEqual (ok ,"True" ) 116self .assertFalse (child .exited ()or grandchild .exited ()) 117parent .kill ()# TerminateProcess: no atexit, no finally - like closing the window 118t_kill = time .monotonic () 119parent .wait (10 ) 120deadline = time .monotonic ()+ 10 121while not (child .exited ()and grandchild .exited ())and time .monotonic ()< deadline : 122time .sleep (0.05 ) 123for held in (child ,grandchild ): 124if not held .exited (): 125self .fail (held .explain (time .monotonic ()- t_kill )) 126finally : 127if parent .poll ()is None : 128parent .kill () 129for held in (child ,grandchild ): 130if held is not None : 131held .end () 132 133def test_elsewhere_or_without_a_process_it_is_a_no_op (self ): 134from serve .winjob import contain 135self .assertFalse (contain (None )) 136 137 138if __name__ == "__main__" : 139unittest .main () 140 141 142@ unittest . skipUnless ( os . name == "nt" , "power throttling is a Windows setting" ) 143class TestNoThrottle (unittest .TestCase ): 144def test_a_contained_child_is_opted_out_of_power_throttling (self ): 145# #691: contain() also sets ProcessPowerThrottling (EcoQoS off), so a minimized server window does not move the 146# engine to the E-cores 147from serve import winjob 148child = subprocess .Popen ([sys .executable ,"-c" ,"import time; time.sleep(30)" ]) 149try : 150self .assertTrue (winjob .no_throttle (int (child ._handle ))) 151self .assertTrue (winjob .contain (child )) 152finally : 153child .kill () 154child .wait (10 )