soak_watch.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. """浸泡测试 / 长时间运行的资源监测:内存、句柄(fd)、线程、CPU、IO,并给出泄漏判据。
  2. 用法::
  3. # 1) 自己拉起被测进程并监测(跑够帧数或到时限自动收尾)
  4. python scripts/soak_watch.py -- python/build/portcv_run -c configs/edge-cpp.json \\
  5. --backend edge --edge-demo ground --no-plc --max-frames 20000
  6. # 2) 监测已经在跑的进程(现场排查:systemd 拉起的那一个)
  7. python scripts/soak_watch.py --pid 12345 --minutes 30
  8. 输出(默认写到 ``runs/``)::
  9. soak_<时间戳>.csv 每次采样一行
  10. soak_<时间戳>.txt 人读摘要 + 泄漏判定
  11. soak_<时间戳>.stdout.log 被测进程日志(由本脚本拉起时)
  12. 判据(保守,避免把分配器预热误判成泄漏):
  13. * 前 ``--warmup`` 秒(默认 60)为预热期,不计入趋势;
  14. * 对预热后的 RSS / 句柄做最小二乘斜率:RSS < ``--rss-slope`` MB/min 且
  15. 句柄净增 < 10 个 → 判"无泄漏迹象";
  16. * 预热后仍逐分钟单调上升(≥90% 的分钟在涨)→ 提示"疑似泄漏"。
  17. 只用标准库:Windows 走 ctypes(psapi/kernel32 + Toolhelp32),
  18. Linux(现场板卡)读 /proc/<pid>/{status,fd,task,stat,io}。
  19. """
  20. from __future__ import annotations
  21. import argparse
  22. import csv
  23. import ctypes
  24. import datetime as _dt
  25. import os
  26. import re
  27. import subprocess
  28. import sys
  29. import time
  30. REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  31. class _MemCounters(ctypes.Structure):
  32. _fields_ = [
  33. ("cb", ctypes.c_ulong),
  34. ("PageFaultCount", ctypes.c_ulong),
  35. ("PeakWorkingSetSize", ctypes.c_size_t),
  36. ("WorkingSetSize", ctypes.c_size_t),
  37. ("QuotaPeakPagedPoolUsage", ctypes.c_size_t),
  38. ("QuotaPagedPoolUsage", ctypes.c_size_t),
  39. ("QuotaPeakNonPagedPoolUsage", ctypes.c_size_t),
  40. ("QuotaNonPagedPoolUsage", ctypes.c_size_t),
  41. ("PagefileUsage", ctypes.c_size_t),
  42. ("PeakPagefileUsage", ctypes.c_size_t),
  43. ]
  44. class _IoCounters(ctypes.Structure):
  45. _fields_ = [
  46. ("ReadOperationCount", ctypes.c_ulonglong),
  47. ("WriteOperationCount", ctypes.c_ulonglong),
  48. ("OtherOperationCount", ctypes.c_ulonglong),
  49. ("ReadTransferCount", ctypes.c_ulonglong),
  50. ("WriteTransferCount", ctypes.c_ulonglong),
  51. ("OtherTransferCount", ctypes.c_ulonglong),
  52. ]
  53. class _ThreadEntry(ctypes.Structure):
  54. _fields_ = [
  55. ("dwSize", ctypes.c_ulong),
  56. ("cntUsage", ctypes.c_ulong),
  57. ("th32ThreadID", ctypes.c_ulong),
  58. ("th32OwnerProcessID", ctypes.c_ulong),
  59. ("tpBasePri", ctypes.c_long),
  60. ("tpDeltaPri", ctypes.c_long),
  61. ("dwFlags", ctypes.c_ulong),
  62. ]
  63. class WinSampler:
  64. """Windows:PSAPI + kernel32,零第三方依赖。"""
  65. QUERY = 0x0400 | 0x0010 # PROCESS_QUERY_INFORMATION | PROCESS_VM_READ
  66. SNAP_THREAD = 0x00000004
  67. STILL_ACTIVE = 259
  68. def __init__(self) -> None:
  69. self.k32 = ctypes.WinDLL("kernel32", use_last_error=True)
  70. self.psapi = ctypes.WinDLL("psapi", use_last_error=True)
  71. def open(self, pid: int) -> int:
  72. handle = self.k32.OpenProcess(self.QUERY, False, pid)
  73. if not handle:
  74. handle = self.k32.OpenProcess(0x1000 | 0x0010, False, pid)
  75. return int(handle)
  76. def close(self, handle: int) -> None:
  77. if handle:
  78. self.k32.CloseHandle(handle)
  79. def alive(self, handle: int) -> bool:
  80. code = ctypes.c_ulong(0)
  81. if not self.k32.GetExitCodeProcess(handle, ctypes.byref(code)):
  82. return False
  83. return code.value == self.STILL_ACTIVE
  84. def count_threads(self, pid: int):
  85. snapshot = self.k32.CreateToolhelp32Snapshot(self.SNAP_THREAD, 0)
  86. if snapshot == -1:
  87. return None
  88. try:
  89. entry = _ThreadEntry()
  90. entry.dwSize = ctypes.sizeof(entry)
  91. if not self.k32.Thread32First(snapshot, ctypes.byref(entry)):
  92. return None
  93. count = 0
  94. while True:
  95. if entry.th32OwnerProcessID == pid:
  96. count += 1
  97. if not self.k32.Thread32Next(snapshot, ctypes.byref(entry)):
  98. break
  99. return count
  100. finally:
  101. self.k32.CloseHandle(snapshot)
  102. def sample(self, pid: int, handle: int) -> dict:
  103. out: dict = {"threads": self.count_threads(pid)}
  104. mem = _MemCounters()
  105. mem.cb = ctypes.sizeof(mem)
  106. if self.psapi.GetProcessMemoryInfo(handle, ctypes.byref(mem), mem.cb):
  107. out["rss_mb"] = mem.WorkingSetSize / 1048576.0
  108. out["peak_rss_mb"] = mem.PeakWorkingSetSize / 1048576.0
  109. out["private_mb"] = mem.PagefileUsage / 1048576.0
  110. out["paged_pool_mb"] = mem.QuotaPagedPoolUsage / 1048576.0
  111. out["nonpaged_pool_mb"] = mem.QuotaNonPagedPoolUsage / 1048576.0
  112. handles = ctypes.c_ulong(0)
  113. if self.k32.GetProcessHandleCount(handle, ctypes.byref(handles)):
  114. out["handles"] = int(handles.value)
  115. created = ctypes.c_ulonglong(0)
  116. exited = ctypes.c_ulonglong(0)
  117. kernel = ctypes.c_ulonglong(0)
  118. user = ctypes.c_ulonglong(0)
  119. if self.k32.GetProcessTimes(
  120. handle, ctypes.byref(created), ctypes.byref(exited),
  121. ctypes.byref(kernel), ctypes.byref(user),
  122. ):
  123. out["cpu_s"] = (kernel.value + user.value) / 1e7
  124. io = _IoCounters()
  125. if self.k32.GetProcessIoCounters(handle, ctypes.byref(io)):
  126. out["io_read_mb"] = io.ReadTransferCount / 1048576.0
  127. out["io_write_mb"] = io.WriteTransferCount / 1048576.0
  128. return out
  129. def parse_proc_status(text: str) -> dict:
  130. """解析 ``/proc/<pid>/status``(抽成纯函数,好单测,也不用上板)。
  131. * ``rss_mb`` ← ``VmRSS``(常驻)
  132. * ``peak_rss_mb`` ← ``VmHWM``(峰值常驻,内核已记)
  133. * ``private_mb`` ← **``RssAnon``**(匿名常驻 ≈ 私有提交);**不能用 ``VmSize``**——
  134. Python 进程的虚拟地址空间动辄 1.5 GB(cv2/numpy 的映射),拿它当"私有提交"会让
  135. 摘要里出现"私有 1530 MB"这种一看就假、但会被人当真的数字(2026-11-16 板端踩过)
  136. * ``threads`` ← ``Threads``
  137. """
  138. out: dict = {}
  139. for line in text.splitlines():
  140. if line.startswith("VmRSS:"):
  141. out["rss_mb"] = float(line.split()[1]) / 1024.0
  142. elif line.startswith("VmHWM:"):
  143. out["peak_rss_mb"] = float(line.split()[1]) / 1024.0
  144. elif line.startswith("RssAnon:"):
  145. out["private_mb"] = float(line.split()[1]) / 1024.0
  146. elif line.startswith("Threads:"):
  147. out["threads"] = int(line.split()[1])
  148. return out
  149. class ProcSampler:
  150. """Linux(现场板卡):/proc/<pid>;句柄数 = /proc/<pid>/fd 条目数。"""
  151. def open(self, pid: int) -> int: # 与 WinSampler 同接口
  152. return pid
  153. def close(self, handle: int) -> None:
  154. return None
  155. def alive(self, handle: int) -> bool:
  156. return os.path.exists("/proc/%d" % handle)
  157. def sample(self, pid: int, handle: int) -> dict:
  158. out: dict = {}
  159. try:
  160. with open("/proc/%d/status" % pid, encoding="utf-8") as fh:
  161. out.update(parse_proc_status(fh.read()))
  162. except OSError:
  163. return out
  164. for path, key in (("/proc/%d/fd" % pid, "handles"), ("/proc/%d/task" % pid, "task_count")):
  165. try:
  166. out[key] = len(os.listdir(path))
  167. except OSError:
  168. pass
  169. try:
  170. with open("/proc/%d/stat" % pid, encoding="utf-8") as fh:
  171. parts = fh.read().split()
  172. out["cpu_s"] = (int(parts[13]) + int(parts[14])) / float(os.sysconf("SC_CLK_TCK"))
  173. except (OSError, IndexError, ValueError):
  174. pass
  175. try:
  176. with open("/proc/%d/io" % pid, encoding="utf-8") as fh:
  177. for line in fh:
  178. if line.startswith("read_bytes:"):
  179. out["io_read_mb"] = int(line.split()[1]) / 1048576.0
  180. elif line.startswith("write_bytes:"):
  181. out["io_write_mb"] = int(line.split()[1]) / 1048576.0
  182. except (OSError, ValueError):
  183. pass
  184. return out
  185. def make_sampler():
  186. return WinSampler() if os.name == "nt" else ProcSampler()
  187. def slope_per_min(samples: list) -> float:
  188. """最小二乘斜率,单位 /分钟(样本 = [(t_s, y), ...])。"""
  189. n = len(samples)
  190. if n < 3:
  191. return 0.0
  192. mean_x = sum(x for x, _ in samples) / n
  193. mean_y = sum(y for _, y in samples) / n
  194. den = sum((x - mean_x) ** 2 for x, _ in samples)
  195. if den <= 0.0:
  196. return 0.0
  197. return sum((x - mean_x) * (y - mean_y) for x, y in samples) / den * 60.0
  198. def rise_ratio(samples: list) -> float:
  199. """逐分钟比较,上升的分钟占比(1.0 = 每分钟都在涨)。"""
  200. by_minute: dict = {}
  201. for t, y in samples:
  202. by_minute[int(t // 60)] = y
  203. minutes = sorted(by_minute)
  204. if len(minutes) < 2:
  205. return 0.0
  206. rises = sum(1 for a, b in zip(minutes, minutes[1:]) if by_minute[b] > by_minute[a])
  207. return rises / float(len(minutes) - 1)
  208. _RE_CXX_FRAMES = re.compile(r"已发布\s+(\d+)\s*帧")
  209. _RE_FPS_X10 = re.compile(r"fps_x10=(\d+)")
  210. # Python 侧的单行摘要(portcv/service/runner.py::status_line):
  211. # state=2(no_container,0.42) seq=88 fps=15.0 lat=63ms npr=97% frames=441 pub=441 chg=0 err=0
  212. _RE_PY_STATUS = re.compile(
  213. r"\bseq=(\d+)\s+fps=([0-9.]+)\s+lat=([0-9.]+)ms\b"
  214. r".*?\bframes=(\d+)\s+pub=(\d+)\s+chg=(\d+)\s+err=(\d+)")
  215. _RE_WARN = re.compile(r"\[warn\]|\|\s*WARNING\b")
  216. def read_log_progress(path: str) -> dict:
  217. """抓被测进程日志里的进度:发布帧数 / 实测 fps / [warn] 行数 / 最后一行。
  218. 同一个脚本要能同时盯 C++ 与 Python 两个版本,两种日志格式都认:
  219. * C++ ``portcv_run``:``[stat] 已发布 50 帧,本轮 15.0 fps(滑窗 15.0 fps)…fps_x10=150``
  220. * Python ``portcv run``:``16:17:55 | INFO | portcv.runner | state=… seq=88 fps=15.0
  221. lat=63ms npr=97% frames=441 pub=441 chg=0 err=0``
  222. 匹配用**子串搜索**而不是 ``startswith``:经 systemd / journald / ``tee`` 转发后
  223. 行首会多出时间戳前缀(2026-11-16 板端实测踩过:带前缀时 ``frames`` 恒为 ``None``,
  224. 进度停滞判据等于失效)。``frames`` 统一取"已发布"口径(Python 取 ``pub=``)。
  225. """
  226. out = {"frames": None, "fps": None, "warn_lines": 0, "errors": None, "last": "", "bytes": 0}
  227. if not path or not os.path.exists(path):
  228. return out
  229. out["bytes"] = os.path.getsize(path)
  230. try:
  231. with open(path, encoding="utf-8", errors="replace") as fh:
  232. text = fh.read()
  233. except OSError:
  234. return out
  235. for line in text.splitlines():
  236. frames = _RE_CXX_FRAMES.search(line)
  237. fps = _RE_FPS_X10.search(line)
  238. py = _RE_PY_STATUS.search(line)
  239. if frames or fps or py:
  240. out["last"] = line.strip()
  241. if frames:
  242. out["frames"] = int(frames.group(1))
  243. if fps: # C++ 退出统计里的"发布 fps_x10="
  244. out["fps"] = int(fps.group(1)) / 10.0
  245. if py:
  246. out["fps"] = float(py.group(2))
  247. out["frames"] = int(py.group(5)) # pub = 已发布到 PLC 的帧数
  248. out["errors"] = int(py.group(7))
  249. out["warn_lines"] = len(_RE_WARN.findall(text))
  250. return out
  251. def thread_leak(rows: list) -> str:
  252. """线程泄漏判定:**只吃预热后的窗口**。
  253. t=0 那次采样常常撞在子进程刚 exec 的瞬间(``Threads: 1``、RSS 0),拿它当"首值"会把
  254. "线程从 1 长到 24 就稳定"误判成泄漏(2026-11-16 板端 30 min 浸泡就是这么假阳性的)。
  255. """
  256. values = [r["threads"] for r in rows if r.get("threads")]
  257. if len(values) < 2:
  258. return ""
  259. if values[-1] > values[0] and max(values) - min(values) > 2:
  260. return "线程数 %d → %d → 疑似线程泄漏" % (values[0], values[-1])
  261. return ""
  262. def main(argv=None) -> int:
  263. parser = argparse.ArgumentParser(description="浸泡测试 / 资源监测(内存·句柄·线程·CPU·IO)")
  264. parser.add_argument("--pid", type=int, default=0,
  265. help="监测已在运行的进程;不给则用 `-- cmd ...` 自己拉起")
  266. parser.add_argument("--interval", type=float, default=2.0, help="采样间隔秒(默认 2)")
  267. parser.add_argument("--minutes", type=float, default=0.0,
  268. help="最长监测时长(0 = 跟随被测进程/帧数)")
  269. parser.add_argument("--warmup", type=float, default=60.0,
  270. help="预热期秒数(默认 60,不计入趋势;分配器预热别当泄漏)")
  271. parser.add_argument("--rss-slope", type=float, default=1.0, help="RSS 斜率阈值 MB/min")
  272. parser.add_argument("--handle-slope", type=float, default=1.0, help="句柄斜率阈值 个/min")
  273. parser.add_argument("--outdir", default=os.path.join(REPO, "runs"), help="输出目录")
  274. parser.add_argument("--replay", default=None,
  275. help="事后重算:读入已有的 soak_*.csv,用当前判据重新出结论(不上板、不采样)")
  276. parser.add_argument("cmd", nargs=argparse.REMAINDER, help="`-- 被测程序 参数...`")
  277. args = parser.parse_args(argv)
  278. cmd = [a for a in args.cmd if a != "--"]
  279. os.makedirs(args.outdir, exist_ok=True)
  280. stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S")
  281. if args.replay:
  282. rows = _read_soak_csv(args.replay)
  283. if not rows:
  284. print("CSV 里没有采样行:%s" % args.replay, file=sys.stderr)
  285. return 2
  286. base = os.path.splitext(args.replay)[0]
  287. deltas = sorted(b["t_s"] - a["t_s"] for a, b in zip(rows, rows[1:]))
  288. if deltas: # 摘要里的"间隔"按 CSV 实际采样间隔算
  289. args.interval = round(deltas[len(deltas) // 2], 1)
  290. print("重算 %s(%d 行;预热 %.0fs 不计入趋势)" % (args.replay, len(rows), args.warmup))
  291. return analyze(rows, args, [], base + ".stdout.log", args.replay,
  292. base + ".replay.txt")
  293. csv_path = os.path.join(args.outdir, "soak_%s.csv" % stamp)
  294. txt_path = os.path.join(args.outdir, "soak_%s.txt" % stamp)
  295. sampler = make_sampler()
  296. child = None
  297. log_path = ""
  298. if args.pid:
  299. pid = args.pid
  300. else:
  301. if not cmd:
  302. print("要么给 --pid,要么在 `--` 后给被测命令", file=sys.stderr)
  303. return 2
  304. log_path = os.path.join(args.outdir, "soak_%s.stdout.log" % stamp)
  305. log_fh = open(log_path, "wb")
  306. env = dict(os.environ)
  307. # 若被测程序是 sanitizer 构建:把报告落到日志里,别让它只打到控制台
  308. env.setdefault("ASAN_OPTIONS", "detect_leaks=0:print_stacktrace=1:abort_on_error=0")
  309. env.setdefault("UBSAN_OPTIONS", "print_stacktrace=1")
  310. child = subprocess.Popen(cmd, cwd=REPO, stdout=log_fh, stderr=subprocess.STDOUT, env=env)
  311. pid = child.pid
  312. handle = sampler.open(pid)
  313. if not handle:
  314. print("无法打开进程 %d(权限或已退出)" % pid, file=sys.stderr)
  315. return 2
  316. rows: list = []
  317. t0 = time.time()
  318. print("监测 pid=%d 采样间隔=%.1fs 输出=%s" % (pid, args.interval, csv_path))
  319. try:
  320. while True:
  321. now = time.time()
  322. sample = sampler.sample(pid, handle)
  323. alive = sampler.alive(handle)
  324. progress = read_log_progress(log_path)
  325. row = {
  326. "t_s": round(now - t0, 3),
  327. "wall": _dt.datetime.now().strftime("%H:%M:%S"),
  328. "rss_mb": round(sample.get("rss_mb", 0.0), 2),
  329. "private_mb": round(sample.get("private_mb", 0.0), 2),
  330. "peak_rss_mb": round(sample.get("peak_rss_mb", 0.0), 2),
  331. "paged_pool_mb": round(sample.get("paged_pool_mb", 0.0), 3),
  332. "nonpaged_pool_mb": round(sample.get("nonpaged_pool_mb", 0.0), 3),
  333. "handles": sample.get("handles"),
  334. "threads": sample.get("threads"),
  335. "cpu_s": round(sample.get("cpu_s", 0.0), 2),
  336. "io_read_mb": round(sample.get("io_read_mb", 0.0), 3),
  337. "io_write_mb": round(sample.get("io_write_mb", 0.0), 3),
  338. "frames": progress["frames"],
  339. "fps": progress["fps"],
  340. "warn_lines": progress["warn_lines"],
  341. "alive": int(alive),
  342. }
  343. rows.append(row)
  344. print(" t=%6.1fs rss=%8.2fMB priv=%8.2fMB handles=%s threads=%s cpu=%6.1fs "
  345. "frames=%s fps=%s warn=%s"
  346. % (row["t_s"], row["rss_mb"], row["private_mb"], row["handles"], row["threads"],
  347. row["cpu_s"], row["frames"], row["fps"], row["warn_lines"]))
  348. sys.stdout.flush()
  349. if child is not None and child.poll() is not None and not alive:
  350. print("被测进程已退出,rc=%s" % child.returncode)
  351. break
  352. if args.minutes > 0 and (now - t0) >= args.minutes * 60.0:
  353. print("到达 --minutes 上限,收尾(本脚本拉起的进程会被终止)")
  354. break
  355. time.sleep(args.interval)
  356. except KeyboardInterrupt:
  357. print("收到中断,收尾")
  358. finally:
  359. sampler.close(handle)
  360. if child is not None and child.poll() is None:
  361. child.terminate()
  362. try:
  363. child.wait(timeout=15)
  364. except subprocess.TimeoutExpired:
  365. child.kill()
  366. if log_path: # 不关会在长跑结束时留 ResourceWarning
  367. try:
  368. log_fh.close()
  369. except Exception: # noqa: BLE001 - 收尾路径不抛
  370. pass
  371. if not rows:
  372. print("没有采样数据", file=sys.stderr)
  373. return 2
  374. with open(csv_path, "w", newline="", encoding="utf-8") as fh:
  375. writer = csv.DictWriter(fh, fieldnames=list(rows[0]))
  376. writer.writeheader()
  377. writer.writerows(rows)
  378. return analyze(rows, args, cmd, log_path, csv_path, txt_path,
  379. child.returncode if child is not None else None)
  380. def _read_soak_csv(path: str) -> list:
  381. """把 ``soak_*.csv`` 读回成采样行(``--replay`` 用;缺列按 None/0 兜底)。"""
  382. rows: list = []
  383. with open(path, newline="", encoding="utf-8") as fh:
  384. for raw in csv.DictReader(fh):
  385. def num(key):
  386. value = raw.get(key)
  387. return None if value in (None, "", "None") else float(value)
  388. threads = num("threads")
  389. handles = num("handles")
  390. rows.append({
  391. "t_s": float(raw.get("t_s") or 0.0),
  392. "rss_mb": num("rss_mb") or 0.0,
  393. "private_mb": num("private_mb") or 0.0,
  394. "handles": None if handles is None else int(handles),
  395. "threads": None if threads is None else int(threads),
  396. "cpu_s": num("cpu_s") or 0.0,
  397. "io_read_mb": num("io_read_mb") or 0.0,
  398. "io_write_mb": num("io_write_mb") or 0.0,
  399. "frames": None if num("frames") is None else int(num("frames")),
  400. "fps": num("fps"),
  401. "warn_lines": int(num("warn_lines") or 0),
  402. })
  403. return rows
  404. def analyze(rows: list, args, cmd, log_path: str, csv_path: str, txt_path: str,
  405. child_rc=None) -> int:
  406. """判定 + 摘要(采样循环与 ``--replay`` 共用;``child_rc`` 非 0 时数据不作数)。"""
  407. # ---------------- 判定 ----------------
  408. post = [r for r in rows if r["t_s"] >= args.warmup] or rows[len(rows) // 2:]
  409. rss_series = [(r["t_s"], r["rss_mb"]) for r in post]
  410. priv_series = [(r["t_s"], r["private_mb"]) for r in post]
  411. handle_series = [(r["t_s"], float(r["handles"])) for r in post if r["handles"] is not None]
  412. rss_slope = slope_per_min(rss_series)
  413. priv_slope = slope_per_min(priv_series)
  414. handle_slope = slope_per_min(handle_series)
  415. handle_net = (handle_series[-1][1] - handle_series[0][1]) if len(handle_series) > 1 else 0.0
  416. rss_rise = rise_ratio(rss_series)
  417. handle_rise = rise_ratio(handle_series)
  418. thread_values = [r["threads"] for r in rows if r["threads"]]
  419. last = rows[-1]
  420. first = post[0] if post else rows[0] # 首值取预热后:避开 exec 瞬间的 0 MB / 1 线程
  421. verdict = []
  422. ok = True
  423. # 先判"这份数据算不算数":进程异常退出 / 有效样本太少时,任何"无泄漏"结论都是假的
  424. if child_rc not in (0, None):
  425. verdict.append("被测进程异常退出 rc=%s → 本次数据不作数(先看它的日志)" % child_rc)
  426. ok = False
  427. if len(post) < 5:
  428. verdict.append("预热后有效样本仅 %d 个(< 5)→ 不足以判定泄漏" % len(post))
  429. ok = False
  430. if rss_slope > args.rss_slope:
  431. verdict.append("RSS 持续上升 %.2f MB/min(阈值 %.2f)→ 疑似内存泄漏"
  432. % (rss_slope, args.rss_slope))
  433. ok = False
  434. if handle_slope > args.handle_slope or handle_net > 10:
  435. verdict.append("句柄净增 %.0f 个(%.2f 个/min)→ 疑似句柄/描述符泄漏"
  436. % (handle_net, handle_slope))
  437. ok = False
  438. leaked_threads = thread_leak(post)
  439. if leaked_threads:
  440. verdict.append(leaked_threads)
  441. ok = False
  442. if rss_rise >= 0.9 and rss_slope > 0:
  443. verdict.append("预热后 %.0f%% 的分钟 RSS 都在涨 → 值得人看一眼" % (rss_rise * 100))
  444. ok = False
  445. if last["warn_lines"] > max(20, len(rows)):
  446. verdict.append("[warn] 行数 %d 偏高 → 检查日志是否刷屏(现场会塞满磁盘)"
  447. % last["warn_lines"])
  448. ok = False
  449. if not verdict:
  450. verdict.append("无明显泄漏迹象(RSS %.2f MB/min、句柄 %.2f 个/min,均在阈值内)"
  451. % (rss_slope, handle_slope))
  452. summary = [
  453. "浸泡测试 / 资源监测摘要",
  454. " 被测: %s" % (cmd if cmd else "pid=%d(外部进程)" % args.pid),
  455. " 样本: %d 个 / %.1f 分钟(间隔 %.1fs;预热 %.0fs 不计入趋势)"
  456. % (len(rows), (rows[-1]["t_s"] - rows[0]["t_s"]) / 60.0, args.interval, args.warmup),
  457. " RSS: 预热后首 %.2f → 末 %.2f MB(峰 %.2f),趋势 %+.2f MB/min"
  458. % (first["rss_mb"], last["rss_mb"], max(r["rss_mb"] for r in rows), rss_slope),
  459. " 私有提交: 预热后首 %.2f → 末 %.2f MB,趋势 %+.2f MB/min"
  460. % (first["private_mb"], last["private_mb"], priv_slope),
  461. " 句柄: 预热后首 %s → 末 %s(净 %+.0f,趋势 %+.2f 个/min;逐分钟上升比例 %.0f%%)"
  462. % (first["handles"], last["handles"], handle_net, handle_slope, handle_rise * 100),
  463. " 线程: 预热后首 %s → 末 %s(全程峰值 %s)"
  464. % (first["threads"], last["threads"],
  465. max(r["threads"] or 0 for r in rows) or None),
  466. " CPU: %.1f s(累计) IO: 读 %.2f MB / 写 %.2f MB"
  467. % (last["cpu_s"], last["io_read_mb"], last["io_write_mb"]),
  468. " 进度: 发布帧数=%s 实测 fps=%s [warn] 行=%d"
  469. % (last["frames"], last["fps"], last["warn_lines"]),
  470. " 日志: %s" % (log_path or "(外部进程,未由本脚本拉起)"),
  471. " 结论: " + ";".join(verdict),
  472. " 明细: %s" % csv_path,
  473. ]
  474. text = "\n".join(summary) + "\n"
  475. with open(txt_path, "w", encoding="utf-8") as fh:
  476. fh.write(text)
  477. print(text)
  478. print("退出码 %d(0 = 无泄漏迹象,1 = 需人工确认)" % (0 if ok else 1))
  479. return 0 if ok else 1
  480. if __name__ == "__main__":
  481. raise SystemExit(main())