"""浸泡测试 / 长时间运行的资源监测:内存、句柄(fd)、线程、CPU、IO,并给出泄漏判据。 用法:: # 1) 自己拉起被测进程并监测(跑够帧数或到时限自动收尾) python scripts/soak_watch.py -- python/build/portcv_run -c configs/edge-cpp.json \\ --backend edge --edge-demo ground --no-plc --max-frames 20000 # 2) 监测已经在跑的进程(现场排查:systemd 拉起的那一个) python scripts/soak_watch.py --pid 12345 --minutes 30 输出(默认写到 ``runs/``):: soak_<时间戳>.csv 每次采样一行 soak_<时间戳>.txt 人读摘要 + 泄漏判定 soak_<时间戳>.stdout.log 被测进程日志(由本脚本拉起时) 判据(保守,避免把分配器预热误判成泄漏): * 前 ``--warmup`` 秒(默认 60)为预热期,不计入趋势; * 对预热后的 RSS / 句柄做最小二乘斜率:RSS < ``--rss-slope`` MB/min 且 句柄净增 < 10 个 → 判"无泄漏迹象"; * 预热后仍逐分钟单调上升(≥90% 的分钟在涨)→ 提示"疑似泄漏"。 只用标准库:Windows 走 ctypes(psapi/kernel32 + Toolhelp32), Linux(现场板卡)读 /proc//{status,fd,task,stat,io}。 """ from __future__ import annotations import argparse import csv import ctypes import datetime as _dt import os import re import subprocess import sys import time REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) class _MemCounters(ctypes.Structure): _fields_ = [ ("cb", ctypes.c_ulong), ("PageFaultCount", ctypes.c_ulong), ("PeakWorkingSetSize", ctypes.c_size_t), ("WorkingSetSize", ctypes.c_size_t), ("QuotaPeakPagedPoolUsage", ctypes.c_size_t), ("QuotaPagedPoolUsage", ctypes.c_size_t), ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t), ("QuotaNonPagedPoolUsage", ctypes.c_size_t), ("PagefileUsage", ctypes.c_size_t), ("PeakPagefileUsage", ctypes.c_size_t), ] class _IoCounters(ctypes.Structure): _fields_ = [ ("ReadOperationCount", ctypes.c_ulonglong), ("WriteOperationCount", ctypes.c_ulonglong), ("OtherOperationCount", ctypes.c_ulonglong), ("ReadTransferCount", ctypes.c_ulonglong), ("WriteTransferCount", ctypes.c_ulonglong), ("OtherTransferCount", ctypes.c_ulonglong), ] class _ThreadEntry(ctypes.Structure): _fields_ = [ ("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32ThreadID", ctypes.c_ulong), ("th32OwnerProcessID", ctypes.c_ulong), ("tpBasePri", ctypes.c_long), ("tpDeltaPri", ctypes.c_long), ("dwFlags", ctypes.c_ulong), ] class WinSampler: """Windows:PSAPI + kernel32,零第三方依赖。""" QUERY = 0x0400 | 0x0010 # PROCESS_QUERY_INFORMATION | PROCESS_VM_READ SNAP_THREAD = 0x00000004 STILL_ACTIVE = 259 def __init__(self) -> None: self.k32 = ctypes.WinDLL("kernel32", use_last_error=True) self.psapi = ctypes.WinDLL("psapi", use_last_error=True) def open(self, pid: int) -> int: handle = self.k32.OpenProcess(self.QUERY, False, pid) if not handle: handle = self.k32.OpenProcess(0x1000 | 0x0010, False, pid) return int(handle) def close(self, handle: int) -> None: if handle: self.k32.CloseHandle(handle) def alive(self, handle: int) -> bool: code = ctypes.c_ulong(0) if not self.k32.GetExitCodeProcess(handle, ctypes.byref(code)): return False return code.value == self.STILL_ACTIVE def count_threads(self, pid: int): snapshot = self.k32.CreateToolhelp32Snapshot(self.SNAP_THREAD, 0) if snapshot == -1: return None try: entry = _ThreadEntry() entry.dwSize = ctypes.sizeof(entry) if not self.k32.Thread32First(snapshot, ctypes.byref(entry)): return None count = 0 while True: if entry.th32OwnerProcessID == pid: count += 1 if not self.k32.Thread32Next(snapshot, ctypes.byref(entry)): break return count finally: self.k32.CloseHandle(snapshot) def sample(self, pid: int, handle: int) -> dict: out: dict = {"threads": self.count_threads(pid)} mem = _MemCounters() mem.cb = ctypes.sizeof(mem) if self.psapi.GetProcessMemoryInfo(handle, ctypes.byref(mem), mem.cb): out["rss_mb"] = mem.WorkingSetSize / 1048576.0 out["peak_rss_mb"] = mem.PeakWorkingSetSize / 1048576.0 out["private_mb"] = mem.PagefileUsage / 1048576.0 out["paged_pool_mb"] = mem.QuotaPagedPoolUsage / 1048576.0 out["nonpaged_pool_mb"] = mem.QuotaNonPagedPoolUsage / 1048576.0 handles = ctypes.c_ulong(0) if self.k32.GetProcessHandleCount(handle, ctypes.byref(handles)): out["handles"] = int(handles.value) created = ctypes.c_ulonglong(0) exited = ctypes.c_ulonglong(0) kernel = ctypes.c_ulonglong(0) user = ctypes.c_ulonglong(0) if self.k32.GetProcessTimes( handle, ctypes.byref(created), ctypes.byref(exited), ctypes.byref(kernel), ctypes.byref(user), ): out["cpu_s"] = (kernel.value + user.value) / 1e7 io = _IoCounters() if self.k32.GetProcessIoCounters(handle, ctypes.byref(io)): out["io_read_mb"] = io.ReadTransferCount / 1048576.0 out["io_write_mb"] = io.WriteTransferCount / 1048576.0 return out def parse_proc_status(text: str) -> dict: """解析 ``/proc//status``(抽成纯函数,好单测,也不用上板)。 * ``rss_mb`` ← ``VmRSS``(常驻) * ``peak_rss_mb`` ← ``VmHWM``(峰值常驻,内核已记) * ``private_mb`` ← **``RssAnon``**(匿名常驻 ≈ 私有提交);**不能用 ``VmSize``**—— Python 进程的虚拟地址空间动辄 1.5 GB(cv2/numpy 的映射),拿它当"私有提交"会让 摘要里出现"私有 1530 MB"这种一看就假、但会被人当真的数字(2026-11-16 板端踩过) * ``threads`` ← ``Threads`` """ out: dict = {} for line in text.splitlines(): if line.startswith("VmRSS:"): out["rss_mb"] = float(line.split()[1]) / 1024.0 elif line.startswith("VmHWM:"): out["peak_rss_mb"] = float(line.split()[1]) / 1024.0 elif line.startswith("RssAnon:"): out["private_mb"] = float(line.split()[1]) / 1024.0 elif line.startswith("Threads:"): out["threads"] = int(line.split()[1]) return out class ProcSampler: """Linux(现场板卡):/proc/;句柄数 = /proc//fd 条目数。""" def open(self, pid: int) -> int: # 与 WinSampler 同接口 return pid def close(self, handle: int) -> None: return None def alive(self, handle: int) -> bool: return os.path.exists("/proc/%d" % handle) def sample(self, pid: int, handle: int) -> dict: out: dict = {} try: with open("/proc/%d/status" % pid, encoding="utf-8") as fh: out.update(parse_proc_status(fh.read())) except OSError: return out for path, key in (("/proc/%d/fd" % pid, "handles"), ("/proc/%d/task" % pid, "task_count")): try: out[key] = len(os.listdir(path)) except OSError: pass try: with open("/proc/%d/stat" % pid, encoding="utf-8") as fh: parts = fh.read().split() out["cpu_s"] = (int(parts[13]) + int(parts[14])) / float(os.sysconf("SC_CLK_TCK")) except (OSError, IndexError, ValueError): pass try: with open("/proc/%d/io" % pid, encoding="utf-8") as fh: for line in fh: if line.startswith("read_bytes:"): out["io_read_mb"] = int(line.split()[1]) / 1048576.0 elif line.startswith("write_bytes:"): out["io_write_mb"] = int(line.split()[1]) / 1048576.0 except (OSError, ValueError): pass return out def make_sampler(): return WinSampler() if os.name == "nt" else ProcSampler() def slope_per_min(samples: list) -> float: """最小二乘斜率,单位 /分钟(样本 = [(t_s, y), ...])。""" n = len(samples) if n < 3: return 0.0 mean_x = sum(x for x, _ in samples) / n mean_y = sum(y for _, y in samples) / n den = sum((x - mean_x) ** 2 for x, _ in samples) if den <= 0.0: return 0.0 return sum((x - mean_x) * (y - mean_y) for x, y in samples) / den * 60.0 def rise_ratio(samples: list) -> float: """逐分钟比较,上升的分钟占比(1.0 = 每分钟都在涨)。""" by_minute: dict = {} for t, y in samples: by_minute[int(t // 60)] = y minutes = sorted(by_minute) if len(minutes) < 2: return 0.0 rises = sum(1 for a, b in zip(minutes, minutes[1:]) if by_minute[b] > by_minute[a]) return rises / float(len(minutes) - 1) _RE_CXX_FRAMES = re.compile(r"已发布\s+(\d+)\s*帧") _RE_FPS_X10 = re.compile(r"fps_x10=(\d+)") # Python 侧的单行摘要(portcv/service/runner.py::status_line): # state=2(no_container,0.42) seq=88 fps=15.0 lat=63ms npr=97% frames=441 pub=441 chg=0 err=0 _RE_PY_STATUS = re.compile( r"\bseq=(\d+)\s+fps=([0-9.]+)\s+lat=([0-9.]+)ms\b" r".*?\bframes=(\d+)\s+pub=(\d+)\s+chg=(\d+)\s+err=(\d+)") _RE_WARN = re.compile(r"\[warn\]|\|\s*WARNING\b") def read_log_progress(path: str) -> dict: """抓被测进程日志里的进度:发布帧数 / 实测 fps / [warn] 行数 / 最后一行。 同一个脚本要能同时盯 C++ 与 Python 两个版本,两种日志格式都认: * C++ ``portcv_run``:``[stat] 已发布 50 帧,本轮 15.0 fps(滑窗 15.0 fps)…fps_x10=150`` * Python ``portcv run``:``16:17:55 | INFO | portcv.runner | state=… seq=88 fps=15.0 lat=63ms npr=97% frames=441 pub=441 chg=0 err=0`` 匹配用**子串搜索**而不是 ``startswith``:经 systemd / journald / ``tee`` 转发后 行首会多出时间戳前缀(2026-11-16 板端实测踩过:带前缀时 ``frames`` 恒为 ``None``, 进度停滞判据等于失效)。``frames`` 统一取"已发布"口径(Python 取 ``pub=``)。 """ out = {"frames": None, "fps": None, "warn_lines": 0, "errors": None, "last": "", "bytes": 0} if not path or not os.path.exists(path): return out out["bytes"] = os.path.getsize(path) try: with open(path, encoding="utf-8", errors="replace") as fh: text = fh.read() except OSError: return out for line in text.splitlines(): frames = _RE_CXX_FRAMES.search(line) fps = _RE_FPS_X10.search(line) py = _RE_PY_STATUS.search(line) if frames or fps or py: out["last"] = line.strip() if frames: out["frames"] = int(frames.group(1)) if fps: # C++ 退出统计里的"发布 fps_x10=" out["fps"] = int(fps.group(1)) / 10.0 if py: out["fps"] = float(py.group(2)) out["frames"] = int(py.group(5)) # pub = 已发布到 PLC 的帧数 out["errors"] = int(py.group(7)) out["warn_lines"] = len(_RE_WARN.findall(text)) return out def thread_leak(rows: list) -> str: """线程泄漏判定:**只吃预热后的窗口**。 t=0 那次采样常常撞在子进程刚 exec 的瞬间(``Threads: 1``、RSS 0),拿它当"首值"会把 "线程从 1 长到 24 就稳定"误判成泄漏(2026-11-16 板端 30 min 浸泡就是这么假阳性的)。 """ values = [r["threads"] for r in rows if r.get("threads")] if len(values) < 2: return "" if values[-1] > values[0] and max(values) - min(values) > 2: return "线程数 %d → %d → 疑似线程泄漏" % (values[0], values[-1]) return "" def main(argv=None) -> int: parser = argparse.ArgumentParser(description="浸泡测试 / 资源监测(内存·句柄·线程·CPU·IO)") parser.add_argument("--pid", type=int, default=0, help="监测已在运行的进程;不给则用 `-- cmd ...` 自己拉起") parser.add_argument("--interval", type=float, default=2.0, help="采样间隔秒(默认 2)") parser.add_argument("--minutes", type=float, default=0.0, help="最长监测时长(0 = 跟随被测进程/帧数)") parser.add_argument("--warmup", type=float, default=60.0, help="预热期秒数(默认 60,不计入趋势;分配器预热别当泄漏)") parser.add_argument("--rss-slope", type=float, default=1.0, help="RSS 斜率阈值 MB/min") parser.add_argument("--handle-slope", type=float, default=1.0, help="句柄斜率阈值 个/min") parser.add_argument("--outdir", default=os.path.join(REPO, "runs"), help="输出目录") parser.add_argument("--replay", default=None, help="事后重算:读入已有的 soak_*.csv,用当前判据重新出结论(不上板、不采样)") parser.add_argument("cmd", nargs=argparse.REMAINDER, help="`-- 被测程序 参数...`") args = parser.parse_args(argv) cmd = [a for a in args.cmd if a != "--"] os.makedirs(args.outdir, exist_ok=True) stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S") if args.replay: rows = _read_soak_csv(args.replay) if not rows: print("CSV 里没有采样行:%s" % args.replay, file=sys.stderr) return 2 base = os.path.splitext(args.replay)[0] deltas = sorted(b["t_s"] - a["t_s"] for a, b in zip(rows, rows[1:])) if deltas: # 摘要里的"间隔"按 CSV 实际采样间隔算 args.interval = round(deltas[len(deltas) // 2], 1) print("重算 %s(%d 行;预热 %.0fs 不计入趋势)" % (args.replay, len(rows), args.warmup)) return analyze(rows, args, [], base + ".stdout.log", args.replay, base + ".replay.txt") csv_path = os.path.join(args.outdir, "soak_%s.csv" % stamp) txt_path = os.path.join(args.outdir, "soak_%s.txt" % stamp) sampler = make_sampler() child = None log_path = "" if args.pid: pid = args.pid else: if not cmd: print("要么给 --pid,要么在 `--` 后给被测命令", file=sys.stderr) return 2 log_path = os.path.join(args.outdir, "soak_%s.stdout.log" % stamp) log_fh = open(log_path, "wb") env = dict(os.environ) # 若被测程序是 sanitizer 构建:把报告落到日志里,别让它只打到控制台 env.setdefault("ASAN_OPTIONS", "detect_leaks=0:print_stacktrace=1:abort_on_error=0") env.setdefault("UBSAN_OPTIONS", "print_stacktrace=1") child = subprocess.Popen(cmd, cwd=REPO, stdout=log_fh, stderr=subprocess.STDOUT, env=env) pid = child.pid handle = sampler.open(pid) if not handle: print("无法打开进程 %d(权限或已退出)" % pid, file=sys.stderr) return 2 rows: list = [] t0 = time.time() print("监测 pid=%d 采样间隔=%.1fs 输出=%s" % (pid, args.interval, csv_path)) try: while True: now = time.time() sample = sampler.sample(pid, handle) alive = sampler.alive(handle) progress = read_log_progress(log_path) row = { "t_s": round(now - t0, 3), "wall": _dt.datetime.now().strftime("%H:%M:%S"), "rss_mb": round(sample.get("rss_mb", 0.0), 2), "private_mb": round(sample.get("private_mb", 0.0), 2), "peak_rss_mb": round(sample.get("peak_rss_mb", 0.0), 2), "paged_pool_mb": round(sample.get("paged_pool_mb", 0.0), 3), "nonpaged_pool_mb": round(sample.get("nonpaged_pool_mb", 0.0), 3), "handles": sample.get("handles"), "threads": sample.get("threads"), "cpu_s": round(sample.get("cpu_s", 0.0), 2), "io_read_mb": round(sample.get("io_read_mb", 0.0), 3), "io_write_mb": round(sample.get("io_write_mb", 0.0), 3), "frames": progress["frames"], "fps": progress["fps"], "warn_lines": progress["warn_lines"], "alive": int(alive), } rows.append(row) print(" t=%6.1fs rss=%8.2fMB priv=%8.2fMB handles=%s threads=%s cpu=%6.1fs " "frames=%s fps=%s warn=%s" % (row["t_s"], row["rss_mb"], row["private_mb"], row["handles"], row["threads"], row["cpu_s"], row["frames"], row["fps"], row["warn_lines"])) sys.stdout.flush() if child is not None and child.poll() is not None and not alive: print("被测进程已退出,rc=%s" % child.returncode) break if args.minutes > 0 and (now - t0) >= args.minutes * 60.0: print("到达 --minutes 上限,收尾(本脚本拉起的进程会被终止)") break time.sleep(args.interval) except KeyboardInterrupt: print("收到中断,收尾") finally: sampler.close(handle) if child is not None and child.poll() is None: child.terminate() try: child.wait(timeout=15) except subprocess.TimeoutExpired: child.kill() if log_path: # 不关会在长跑结束时留 ResourceWarning try: log_fh.close() except Exception: # noqa: BLE001 - 收尾路径不抛 pass if not rows: print("没有采样数据", file=sys.stderr) return 2 with open(csv_path, "w", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows) return analyze(rows, args, cmd, log_path, csv_path, txt_path, child.returncode if child is not None else None) def _read_soak_csv(path: str) -> list: """把 ``soak_*.csv`` 读回成采样行(``--replay`` 用;缺列按 None/0 兜底)。""" rows: list = [] with open(path, newline="", encoding="utf-8") as fh: for raw in csv.DictReader(fh): def num(key): value = raw.get(key) return None if value in (None, "", "None") else float(value) threads = num("threads") handles = num("handles") rows.append({ "t_s": float(raw.get("t_s") or 0.0), "rss_mb": num("rss_mb") or 0.0, "private_mb": num("private_mb") or 0.0, "handles": None if handles is None else int(handles), "threads": None if threads is None else int(threads), "cpu_s": num("cpu_s") or 0.0, "io_read_mb": num("io_read_mb") or 0.0, "io_write_mb": num("io_write_mb") or 0.0, "frames": None if num("frames") is None else int(num("frames")), "fps": num("fps"), "warn_lines": int(num("warn_lines") or 0), }) return rows def analyze(rows: list, args, cmd, log_path: str, csv_path: str, txt_path: str, child_rc=None) -> int: """判定 + 摘要(采样循环与 ``--replay`` 共用;``child_rc`` 非 0 时数据不作数)。""" # ---------------- 判定 ---------------- post = [r for r in rows if r["t_s"] >= args.warmup] or rows[len(rows) // 2:] rss_series = [(r["t_s"], r["rss_mb"]) for r in post] priv_series = [(r["t_s"], r["private_mb"]) for r in post] handle_series = [(r["t_s"], float(r["handles"])) for r in post if r["handles"] is not None] rss_slope = slope_per_min(rss_series) priv_slope = slope_per_min(priv_series) handle_slope = slope_per_min(handle_series) handle_net = (handle_series[-1][1] - handle_series[0][1]) if len(handle_series) > 1 else 0.0 rss_rise = rise_ratio(rss_series) handle_rise = rise_ratio(handle_series) thread_values = [r["threads"] for r in rows if r["threads"]] last = rows[-1] first = post[0] if post else rows[0] # 首值取预热后:避开 exec 瞬间的 0 MB / 1 线程 verdict = [] ok = True # 先判"这份数据算不算数":进程异常退出 / 有效样本太少时,任何"无泄漏"结论都是假的 if child_rc not in (0, None): verdict.append("被测进程异常退出 rc=%s → 本次数据不作数(先看它的日志)" % child_rc) ok = False if len(post) < 5: verdict.append("预热后有效样本仅 %d 个(< 5)→ 不足以判定泄漏" % len(post)) ok = False if rss_slope > args.rss_slope: verdict.append("RSS 持续上升 %.2f MB/min(阈值 %.2f)→ 疑似内存泄漏" % (rss_slope, args.rss_slope)) ok = False if handle_slope > args.handle_slope or handle_net > 10: verdict.append("句柄净增 %.0f 个(%.2f 个/min)→ 疑似句柄/描述符泄漏" % (handle_net, handle_slope)) ok = False leaked_threads = thread_leak(post) if leaked_threads: verdict.append(leaked_threads) ok = False if rss_rise >= 0.9 and rss_slope > 0: verdict.append("预热后 %.0f%% 的分钟 RSS 都在涨 → 值得人看一眼" % (rss_rise * 100)) ok = False if last["warn_lines"] > max(20, len(rows)): verdict.append("[warn] 行数 %d 偏高 → 检查日志是否刷屏(现场会塞满磁盘)" % last["warn_lines"]) ok = False if not verdict: verdict.append("无明显泄漏迹象(RSS %.2f MB/min、句柄 %.2f 个/min,均在阈值内)" % (rss_slope, handle_slope)) summary = [ "浸泡测试 / 资源监测摘要", " 被测: %s" % (cmd if cmd else "pid=%d(外部进程)" % args.pid), " 样本: %d 个 / %.1f 分钟(间隔 %.1fs;预热 %.0fs 不计入趋势)" % (len(rows), (rows[-1]["t_s"] - rows[0]["t_s"]) / 60.0, args.interval, args.warmup), " RSS: 预热后首 %.2f → 末 %.2f MB(峰 %.2f),趋势 %+.2f MB/min" % (first["rss_mb"], last["rss_mb"], max(r["rss_mb"] for r in rows), rss_slope), " 私有提交: 预热后首 %.2f → 末 %.2f MB,趋势 %+.2f MB/min" % (first["private_mb"], last["private_mb"], priv_slope), " 句柄: 预热后首 %s → 末 %s(净 %+.0f,趋势 %+.2f 个/min;逐分钟上升比例 %.0f%%)" % (first["handles"], last["handles"], handle_net, handle_slope, handle_rise * 100), " 线程: 预热后首 %s → 末 %s(全程峰值 %s)" % (first["threads"], last["threads"], max(r["threads"] or 0 for r in rows) or None), " CPU: %.1f s(累计) IO: 读 %.2f MB / 写 %.2f MB" % (last["cpu_s"], last["io_read_mb"], last["io_write_mb"]), " 进度: 发布帧数=%s 实测 fps=%s [warn] 行=%d" % (last["frames"], last["fps"], last["warn_lines"]), " 日志: %s" % (log_path or "(外部进程,未由本脚本拉起)"), " 结论: " + ";".join(verdict), " 明细: %s" % csv_path, ] text = "\n".join(summary) + "\n" with open(txt_path, "w", encoding="utf-8") as fh: fh.write(text) print(text) print("退出码 %d(0 = 无泄漏迹象,1 = 需人工确认)" % (0 if ok else 1)) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())