okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-140' into f-140-j2e0f28e7d

main
5.5 KiB139 linesraw
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):
53    handle = kernel.OpenProcess(0x1000, False, process.pid)  # PROCESS_QUERY_LIMITED_INFORMATION
54    if not handle:
55        if not process.is_running():
56            raise psutil.NoSuchProcess(process.pid)
57        raise ctypes.WinError(ctypes.get_last_error())
58    try:
59        info = ProcessMemoryCounters()
60        info.cb = ctypes.sizeof(info)
61        if not process_memory(handle, ctypes.byref(info), info.cb):
62            raise ctypes.WinError(ctypes.get_last_error())
63        return {name: getattr(info, name) for name, _ in info._fields_ if name != "cb"}
64    finally:
65        kernel.CloseHandle(handle)
66
67
68def sample(server):
69    info = PerformanceInformation()
70    info.cb = ctypes.sizeof(info)
71    if not performance(ctypes.byref(info), info.cb):
72        raise ctypes.WinError(ctypes.get_last_error())
73    processes = []
74    if server is not None:
75        try:
76            descendants = [server, *server.children(recursive=True)]
77        except psutil.NoSuchProcess:
78            descendants = []
79        for process in descendants:
80            try:
81                with process.oneshot():
82                    processes.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                    })
90            except psutil.NoSuchProcess:
91                continue
92    battery = psutil.sensors_battery()
93    return {
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": {
102            name: counters._asdict()
103            for 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():
111    parser = argparse.ArgumentParser(description=__doc__)
112    parser.add_argument("--server-pid", type=int)
113    parser.add_argument("--out", type=Path, required=True)
114    parser.add_argument("--stop-file", type=Path, required=True)
115    parser.add_argument("--interval", type=float, default=1.0)
116    parser.add_argument("--samples", type=int, help="Optional bounded diagnostic run")
117    args = parser.parse_args()
118    if args.interval <= 0 or (args.samples is not None and args.samples < 1):
119        parser.error("Interval and sample limit must be positive")
120    if args.stop_file.exists():
121        parser.error("The stop file already exists; choose a new experiment path")
122    server = psutil.Process(args.server_pid) if args.server_pid is not None else None
123    args.out.parent.mkdir(parents=True, exist_ok=True)
124    with args.out.open("x", encoding="utf-8") as output:
125        count = 0
126        while not args.stop_file.exists():
127            started = time.monotonic()
128            output.write(json.dumps(sample(server)) + "\n")
129            output.flush()
130            count += 1
131            if args.samples is not None and count >= args.samples:
132                break
133            if server is not None and not server.is_running():
134                break
135            time.sleep(max(0, args.interval - (time.monotonic() - started)))
136
137
138if __name__ == "__main__":
139    main()