okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
2e0f28e7d
main
1"""Record Windows host memory and physical-disk counters during a local experiment.""" 2from __future__import annotations 3 4import argparse 5import ctypes 6from ctypes import wintypes 7import json 8from pathlib import Path 9import time 10 11import psutil 12 13 14class PerformanceInformation (ctypes .Structure ): 15_fields_ = [("cb" ,wintypes .DWORD )]+ [ 16 (name ,ctypes .c_size_t )for name in ( 17"CommitTotal" ,"CommitLimit" ,"CommitPeak" ,"PhysicalTotal" , 18"PhysicalAvailable" ,"SystemCache" ,"KernelTotal" ,"KernelPaged" , 19"KernelNonpaged" ,"PageSize" , 20 ) 21 ]+ [(name ,wintypes .DWORD )for name in ( 22"HandleCount" ,"ProcessCount" ,"ThreadCount" , 23 )] 24 25 26performance = ctypes .WinDLL ("psapi" ,use_last_error = True ).GetPerformanceInfo 27performance .argtypes = [ctypes .POINTER (PerformanceInformation ),wintypes .DWORD ] 28performance .restype = wintypes .BOOL 29 30 31class ProcessMemoryCounters (ctypes .Structure ): 32_fields_ = [("cb" ,wintypes .DWORD ), ("page_fault_count" ,wintypes .DWORD )]+ [ 33 (name ,ctypes .c_size_t )for name in ( 34"peak_working_set_bytes" ,"working_set_bytes" ,"peak_paged_pool_bytes" , 35"paged_pool_bytes" ,"peak_nonpaged_pool_bytes" ,"nonpaged_pool_bytes" , 36"commit_bytes" ,"peak_commit_bytes" ,"private_commit_bytes" , 37"private_working_set_bytes" , 38 ) 39 ]+ [("shared_commit_bytes" ,ctypes .c_ulonglong )] 40 41 42kernel = ctypes .WinDLL ("kernel32" ,use_last_error = True ) 43kernel .OpenProcess .argtypes = [wintypes .DWORD ,wintypes .BOOL ,wintypes .DWORD ] 44kernel .OpenProcess .restype = wintypes .HANDLE 45kernel .CloseHandle .argtypes = [wintypes .HANDLE ] 46kernel .CloseHandle .restype = wintypes .BOOL 47process_memory = ctypes .WinDLL ("psapi" ,use_last_error = True ).GetProcessMemoryInfo 48process_memory .argtypes = [wintypes .HANDLE ,ctypes .POINTER (ProcessMemoryCounters ),wintypes .DWORD ] 49process_memory .restype = wintypes .BOOL 50 51 52def extended_memory (process ): 53handle = kernel .OpenProcess (0x1000 ,False ,process .pid )# PROCESS_QUERY_LIMITED_INFORMATION 54if not handle : 55if not process .is_running (): 56raise psutil .NoSuchProcess (process .pid ) 57raise ctypes .WinError (ctypes .get_last_error ()) 58try : 59info = ProcessMemoryCounters () 60info .cb = ctypes .sizeof (info ) 61if not process_memory (handle ,ctypes .byref (info ),info .cb ): 62raise ctypes .WinError (ctypes .get_last_error ()) 63return {name :getattr (info ,name )for name ,_ in info ._fields_ if name != "cb" } 64finally : 65kernel .CloseHandle (handle ) 66 67 68def sample (server ): 69info = PerformanceInformation () 70info .cb = ctypes .sizeof (info ) 71if not performance (ctypes .byref (info ),info .cb ): 72raise ctypes .WinError (ctypes .get_last_error ()) 73processes = [] 74if server is not None : 75try : 76descendants = [server ,* server .children (recursive = True )] 77except psutil .NoSuchProcess : 78descendants = [] 79for process in descendants : 80try : 81with process .oneshot (): 82processes .append ({ 83"pid" :process .pid , 84"name" :process .name (), 85"memory" :process .memory_info ()._asdict (), 86"windows_memory" :extended_memory (process ), 87"cpu_seconds" :process .cpu_times ()._asdict (), 88"io_counters" :process .io_counters ()._asdict (), 89 }) 90except psutil .NoSuchProcess : 91continue 92battery = psutil .sensors_battery () 93return { 94"epoch_s" :time .time (), 95"memory" :psutil .virtual_memory ()._asdict (), 96"pagefile" :psutil .swap_memory ()._asdict (), 97"commit_bytes" :info .CommitTotal * info .PageSize , 98"commit_limit_bytes" :info .CommitLimit * info .PageSize , 99"commit_peak_bytes" :info .CommitPeak * info .PageSize , 100"system_cache_bytes" :info .SystemCache * info .PageSize , 101"physical_disks" : { 102name :counters ._asdict () 103for name ,counters in psutil .disk_io_counters (perdisk = True ).items () 104 }, 105"ac_power" :battery .power_plugged if battery is not None else None , 106"processes" :processes , 107 } 108 109 110def main (): 111parser = argparse .ArgumentParser (description = __doc__ ) 112parser .add_argument ("--server-pid" ,type = int ) 113parser .add_argument ("--out" ,type = Path ,required = True ) 114parser .add_argument ("--stop-file" ,type = Path ,required = True ) 115parser .add_argument ("--interval" ,type = float ,default = 1.0 ) 116parser .add_argument ("--samples" ,type = int ,help = "Optional bounded diagnostic run" ) 117args = parser .parse_args () 118if args .interval <= 0 or (args .samples is not None and args .samples < 1 ): 119parser .error ("Interval and sample limit must be positive" ) 120if args .stop_file .exists (): 121parser .error ("The stop file already exists; choose a new experiment path" ) 122server = psutil .Process (args .server_pid )if args .server_pid is not None else None 123args .out .parent .mkdir (parents = True ,exist_ok = True ) 124with args .out .open ("x" ,encoding = "utf-8" )as output : 125count = 0 126while not args .stop_file .exists (): 127started = time .monotonic () 128output .write (json .dumps (sample (server ))+ "\n" ) 129output .flush () 130count += 1 131if args .samples is not None and count >= args .samples : 132break 133if server is not None and not server .is_running (): 134break 135time .sleep (max (0 ,args .interval - (time .monotonic ()- started ))) 136 137 138if __name__ == "__main__" : 139main ()