"""7x24 浸泡 / 稳定性验收 harness(工业落地前门禁)。 与 ``scripts/soak_watch.py`` 的分工: * ``soak_watch.py``:30 分钟 ~ 几小时的"看一眼资源曲线",进程退出即收尾; * 本脚本:面向 **168 小时无人值守**,重点解决长跑才会暴露的问题: - 采样边采边落盘(CSV 每行 flush,崩溃/重启不丢证据); - 日志增量解析(不随日志变大而变慢),按大小轮转; - 进程崩溃/退出后按策略重启,并记录重启次数与退出码; - 句柄/fd、RSS/私有内存、线程、CPU、IO、磁盘、温度、可用内存; - Modbus/TCP 主动探活(FC4 读 12 字 + CRC 校验),测"还活着但已经傻了"; - 帧进度/心跳停滞检测(相机断流、主循环卡死); - 每日汇总、最终 Markdown/JSON 报告与明确 PASS/FAIL 判据; - 同一 campaign 目录可断点续跑(systemd 重启监测器后接着写)。 用法(Linux 现场,监测 systemd 拉起的 C++ 服务):: python3 scripts/soak_7x24.py --duration 7d --interval 60 --warmup 3600 \\ --process-name portcv_run \\ --campaign /var/lib/portcv-soak/campaign \\ --modbus-host 127.0.0.1 --modbus-port 1502 用法(自己拉起被测程序,重启策略由本脚本负责):: python3 scripts/soak_7x24.py --duration 7d --interval 60 \\ --campaign runs/soak7_site1 -- \\ /opt/portcv/bin/portcv_run -c /opt/portcv/configs/site.json 快速冒烟(开发机 / Windows):: python scripts/soak_7x24.py --duration 10m --interval 5 --warmup 30 \\ --campaign runs/soak7_smoke -- \\ build\\tools\\portcv_run.exe -c configs/edge-cpp.json \\ --backend edge --edge-demo ground --port 15502 退出码:``0`` = PASS(WARN 不算失败,除非 ``--strict``);``1`` = FAIL/未跑满; ``2`` = 用法或环境问题。产物全部落在 campaign 目录(默认 ``runs/soak7_<时间戳>``)。 """ from __future__ import annotations import argparse import csv import ctypes import datetime as _dt import glob import json import logging import logging.handlers import math import os import re import shutil import signal import socket import statistics import subprocess import sys import threading import time import traceback from collections import Counter from dataclasses import asdict, dataclass from pathlib import Path SCRIPTS = os.path.dirname(os.path.abspath(__file__)) REPO = os.path.dirname(SCRIPTS) sys.path.insert(0, SCRIPTS) from soak_watch import make_sampler # noqa: E402 (复用 Windows PSAPI / Linux /proc 采样) SCHEMA = 1 DEFAULT_DURATION_S = 7 * 24 * 3600.0 SAMPLE_FIELDS = [ "wall", "iso", "epoch", "elapsed_s", "run_id", "pid", "alive", "rss_mb", "private_mb", "peak_rss_mb", "paged_pool_mb", "nonpaged_pool_mb", "handles", "threads", "cpu_s", "cpu_pct", "io_read_mb", "io_write_mb", "frames", "fps_x10", "warn_lines", "error_lines", "fatal_lines", "frame_timeout_lines", "modbus_ok", "modbus_rtt_ms", "modbus_state", "modbus_flags", "modbus_heartbeat", "modbus_fps_x10", "modbus_latency_ms", "modbus_seq", "modbus_error", "avail_mb", "disk_free_mb", "temp_c", "load1", ] EVENT_FIELDS = ["wall", "iso", "epoch", "elapsed_s", "event", "detail"] FLOAT_FIELDS = { "epoch", "elapsed_s", "rss_mb", "private_mb", "peak_rss_mb", "paged_pool_mb", "nonpaged_pool_mb", "cpu_s", "cpu_pct", "io_read_mb", "io_write_mb", "modbus_rtt_ms", "avail_mb", "disk_free_mb", "temp_c", "load1", } INT_FIELDS = { "run_id", "pid", "alive", "handles", "threads", "frames", "fps_x10", "warn_lines", "error_lines", "fatal_lines", "frame_timeout_lines", "modbus_ok", "modbus_state", "modbus_flags", "modbus_heartbeat", "modbus_fps_x10", "modbus_latency_ms", "modbus_seq", } # flags 位(docs/plc_interface.md §3) FLAG_READY = 0x0001 FLAG_FRAME_OK = 0x0002 FLAG_STABLE = 0x0004 FLAG_LOW_FPS = 0x0008 FLAG_FRAME_TIMEOUT = 0x0010 FLAG_ON_DEMAND = 0x0020 FLAG_RESULT_VALID = 0x0040 FLAG_PUBLISH_OK = 0x0080 FATAL_MARKERS = ( "terminate called", "std::bad_alloc", "runtime error:", "hardening assertion", "segmentation fault", "access violation", "stack overflow", "abort() has been called", "addresssanitizer", "leaksanitizer", "undefinedbehaviorsanitizer", ) _URI_CRED = re.compile(r"(?Prtsps?|https?|rtmp)://[^/\s:@]+(?::[^/\s@]*)?@") def redact(text: str) -> str: """掩掉命令行/日志里的 RTSP/HTTP 口令,报告可外发。""" return _URI_CRED.sub(lambda m: m.group("scheme") + "://***@", text) def redact_cmd(cmd) -> str: return redact(" ".join(str(x) for x in cmd)) def redacted_meta(meta: dict) -> dict: """报告可外发:保留元数据结构,只对命令参数做脱敏。""" out = dict(meta) if out.get("cmd"): out["cmd"] = [redact(str(item)) for item in out["cmd"]] if out.get("cmd_text"): out["cmd_text"] = redact(str(out["cmd_text"])) return out def redacted_events(events) -> list: """事件详情也常带命令(START/ATTACH),外发报告必须一起脱敏。""" out = [] for event in events: item = dict(event) if item.get("detail"): item["detail"] = redact(str(item["detail"])) out.append(item) return out def parse_duration(text: str) -> float: """``7d`` / ``168h`` / ``30m`` / ``90s`` → 秒;不带单位按小时。""" value = str(text).strip().lower() match = re.fullmatch(r"(\d+(?:\.\d+)?)\s*([dhms]?)", value) if not match: raise ValueError("时长格式应为 7d / 168h / 30m / 90s(不带单位按小时): %r" % text) number = float(match.group(1)) unit = match.group(2) or "h" factor = {"d": 86400.0, "h": 3600.0, "m": 60.0, "s": 1.0}[unit] seconds = number * factor if seconds <= 0: raise ValueError("时长必须 > 0: %r" % text) return seconds def percentile(values, q: float): """线性插值分位数(与 numpy.percentile 默认口径一致)。""" data = sorted(float(v) for v in values if v is not None) if not data: return None if len(data) == 1: return data[0] pos = (len(data) - 1) * float(q) low = int(math.floor(pos)) high = int(math.ceil(pos)) if low == high: return data[low] return data[low] * (high - pos) + data[high] * (pos - low) def slope_per_min(samples) -> float: """最小二乘斜率,单位 / 分钟;样本 = [(t_s, y), ...]。""" data = [(float(x), float(y)) for x, y in samples if y is not None] if len(data) < 3: return 0.0 mean_x = sum(x for x, _ in data) / len(data) mean_y = sum(y for _, y in data) / len(data) den = sum((x - mean_x) ** 2 for x, _ in data) if den <= 0.0: return 0.0 return sum((x - mean_x) * (y - mean_y) for x, y in data) / den * 60.0 def rise_ratio(samples) -> float: """按分钟取最后值,逐分钟比较上升占比(1.0 = 每分钟都在涨)。""" if not samples: return 0.0 by_minute = {} for t, y in samples: if y is not None: by_minute[int(float(t) // 60)] = float(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) def median_window(rows, key: str, start_s: float, end_s: float): values = [ float(r[key]) for r in rows if r.get(key) is not None and start_s <= float(r["elapsed_s"]) <= end_s ] return statistics.median(values) if values else None def metric_series(rows, key: str, start_s: float = 0.0): return [ (float(r["elapsed_s"]), float(r[key])) for r in rows if r.get(key) is not None and float(r["elapsed_s"]) >= start_s ] def progress_gap_seconds(rows): """最长"进度不变"时长:frames 或 Modbus heartbeat 任一前进即算有进度。 返回 ``(max_gap_s, metric_name)``;没有任何进度信号时返回 ``(None, "")``。 同时看两路信号,避免 stdout 管道卡住但 Modbus 心跳仍在时误判卡死。 """ last_values = {} last_change = None max_gap = 0.0 metric = "" for row in rows: elapsed = float(row["elapsed_s"]) changed = False names = [] for key, label in (("frames", "frames"), ("modbus_heartbeat", "heartbeat")): value = row.get(key) if value is None: continue names.append(label) value = int(value) # 进程重启会让 frames 归零:值变小也视为一次"有新进度" if key not in last_values or value != last_values[key]: last_values[key] = value changed = True if names: metric = "/".join(names) if changed: last_change = elapsed continue if last_change is not None: max_gap = max(max_gap, elapsed - last_change) if last_change is None: return None, "" if rows: max_gap = max(max_gap, float(rows[-1]["elapsed_s"]) - last_change) return max_gap, metric def crc16_modbus(data: bytes) -> int: crc = 0xFFFF for byte in data: crc ^= byte for _ in range(8): crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1 return crc & 0xFFFF def _u16(value: int) -> bytes: return int(value).to_bytes(2, "big", signed=False) def parse_snapshot(words): """解析结果区 12 字;CRC 不符或长度不对返回 ``(None, 原因)``。""" if len(words) != 12: return None, "结果区应为 12 字,实际 %d" % len(words) payload = b"".join(_u16(w) for w in words[:-1]) if crc16_modbus(payload) != int(words[-1]): return None, "CRC 不符" flags = int(words[2]) return { "state": int(words[0]), "confidence": int(words[1]), "flags": flags, "seq": (int(words[3]) << 16) | int(words[4]), "ts_s": (int(words[5]) << 16) | int(words[6]), "heartbeat": int(words[7]), "fps_x10": int(words[8]), "latency_ms": int(words[9]), "reserved": int(words[10]), "ready": bool(flags & FLAG_READY), "frame_ok": bool(flags & FLAG_FRAME_OK), "stable": bool(flags & FLAG_STABLE), "low_fps": bool(flags & FLAG_LOW_FPS), "frame_timeout": bool(flags & FLAG_FRAME_TIMEOUT), "on_demand": bool(flags & FLAG_ON_DEMAND), "result_valid": bool(flags & FLAG_RESULT_VALID), "publish_ok": bool(flags & FLAG_PUBLISH_OK), }, "" def _recv_exact(sock: socket.socket, count: int) -> bytes: data = b"" while len(data) < count: chunk = sock.recv(count - len(data)) if not chunk: raise RuntimeError("连接被对端关闭(需要 %d 字节,收到 %d)" % (count, len(data))) data += chunk return data def modbus_probe(host: str, port: int, unit: int, address: int, count: int = 12, timeout: float = 1.0): """FC4 读结果区 + CRC 校验 + 往返时延;返回 ``(ok, rtt_ms, snapshot, error)``。""" started = time.perf_counter() try: with socket.create_connection((host, int(port)), timeout=timeout) as sock: sock.settimeout(timeout) pdu = bytes([4]) + _u16(address) + _u16(count) frame = _u16(1) + _u16(0) + _u16(len(pdu) + 1) + bytes([unit & 0xFF]) + pdu sock.sendall(frame) header = _recv_exact(sock, 7) length = int.from_bytes(header[4:6], "big") if length < 2 or length > 260: raise RuntimeError("MBAP length 异常: %d" % length) body = _recv_exact(sock, length - 1) rtt_ms = (time.perf_counter() - started) * 1000.0 if not body: raise RuntimeError("空响应") if body[0] & 0x80: code = body[1] if len(body) > 1 else -1 raise RuntimeError("Modbus 异常响应 0x%02X" % code) if body[0] != 4: raise RuntimeError("功能码不符: %d" % body[0]) byte_count = int(body[1]) if len(body) > 1 else 0 payload = body[2:2 + byte_count] if byte_count != count * 2 or len(payload) != byte_count: raise RuntimeError("字节数不符: byte_count=%d payload=%d" % (byte_count, len(payload))) words = [int.from_bytes(payload[i:i + 2], "big") for i in range(0, byte_count, 2)] snapshot, error = parse_snapshot(words) if error: return False, rtt_ms, None, error return True, rtt_ms, snapshot, "" except Exception as exc: # noqa: BLE001 - 探活要把所有网络错误记进报告 return False, (time.perf_counter() - started) * 1000.0, None, str(exc) class LogStats: """增量解析 portcv 日志:帧数 / fps / warn / error / 帧超时 / 致命标记。""" _FRAMES = re.compile(r"已发布\s+(\d+)\s*帧") _FPS_X10 = re.compile(r"fps_x10=(\d+)") _FPS = re.compile(r"本轮\s+([0-9.]+)\s*fps") def __init__(self) -> None: self.lock = threading.Lock() self.buffer = "" self.lines = 0 self.frames = None self.fps_x10 = None self.warn_lines = 0 self.error_lines = 0 self.frame_timeout_lines = 0 self.last_line = "" self.fatal = [] def feed(self, text: str) -> None: if not text: return with self.lock: self.buffer += text.replace("\r\n", "\n").replace("\r", "\n") while "\n" in self.buffer: line, self.buffer = self.buffer.split("\n", 1) self._line(line) # 防止异常超长行把内存撑爆(正常 [stat] 行约 200 字节) if len(self.buffer) > 64 * 1024: self._line(self.buffer) self.buffer = "" def flush(self) -> None: with self.lock: if self.buffer: self._line(self.buffer) self.buffer = "" def _line(self, line: str) -> None: self.lines += 1 if not line: return self.last_line = line[-500:] lowered = line.lower() if "[warn]" in line: self.warn_lines += 1 if "[error]" in lowered or " error:" in lowered: self.error_lines += 1 if "frame_timeout" in lowered or "帧超时" in line: self.frame_timeout_lines += 1 for marker in FATAL_MARKERS: if marker in lowered: if len(self.fatal) < 20: self.fatal.append(line.strip()[:300]) break frames = self._FRAMES.search(line) if frames: self.frames = int(frames.group(1)) fps = self._FPS_X10.search(line) if fps: self.fps_x10 = int(fps.group(1)) elif "fps" in line and line.startswith("[stat]"): other = self._FPS.search(line) if other: self.fps_x10 = int(round(float(other.group(1)) * 10.0)) def snapshot(self) -> dict: with self.lock: return { "frames": self.frames, "fps_x10": self.fps_x10, "warn_lines": self.warn_lines, "error_lines": self.error_lines, "frame_timeout_lines": self.frame_timeout_lines, "last_line": self.last_line, "fatal": list(self.fatal), } class RotatingLineWriter: """按大小轮转的文本日志(stdout.log / stdout.1.log ...),纯标准库。""" def __init__(self, path: Path, max_bytes: int = 64 * 1024 * 1024, backups: int = 4) -> None: self.path = Path(path) self.max_bytes = max(0, int(max_bytes)) self.backups = max(1, int(backups)) self.lock = threading.Lock() self.fh = None self.size = 0 self._open() def _open(self) -> None: self.path.parent.mkdir(parents=True, exist_ok=True) self.fh = open(self.path, "ab", buffering=0) try: self.size = self.path.stat().st_size except OSError: self.size = 0 def _rotate(self) -> None: if self.fh is not None: self.fh.close() self.fh = None oldest = Path(str(self.path) + ".%d" % self.backups) if oldest.exists(): try: oldest.unlink() except OSError: pass for index in range(self.backups - 1, 0, -1): src = Path(str(self.path) + ".%d" % index) dst = Path(str(self.path) + ".%d" % (index + 1)) if src.exists(): try: os.replace(src, dst) except OSError: pass try: os.replace(self.path, Path(str(self.path) + ".1")) except OSError: pass self._open() def write(self, text: str) -> None: data = text.encode("utf-8", "replace") if not data: return with self.lock: if self.fh is None: return if self.max_bytes and self.size + len(data) > self.max_bytes: self._rotate() self.fh.write(data) self.size += len(data) def close(self) -> None: with self.lock: if self.fh is not None: try: self.fh.close() finally: self.fh = None class ChildProcess: """拉起被测进程,stdout/stderr 走管道 → 增量日志 + 轮转文件。""" def __init__(self, cmd, log_dir: Path, run_id: int, stats: LogStats, max_log_bytes: int, log_backups: int) -> None: self.cmd = list(cmd) self.log_dir = Path(log_dir) self.run_id = int(run_id) self.stats = stats self.max_log_bytes = max_log_bytes self.log_backups = log_backups self.proc = None self.reader = None self.writer = None self.log_path = self.log_dir / ("stdout_run%03d.log" % self.run_id) def start(self) -> None: env = dict(os.environ) env.setdefault("ASAN_OPTIONS", "detect_leaks=0:print_stacktrace=1:abort_on_error=0") env.setdefault("UBSAN_OPTIONS", "print_stacktrace=1") env.setdefault("PYTHONUNBUFFERED", "1") self.proc = subprocess.Popen( self.cmd, cwd=REPO, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, bufsize=0, ) try: self.writer = RotatingLineWriter(self.log_path, self.max_log_bytes, self.log_backups) self.writer.write("\n===== RUN %d START %s pid=%d =====\n%s\n" % ( self.run_id, _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), self.proc.pid, redact_cmd(self.cmd), )) self.reader = threading.Thread(target=self._read_loop, name="portcv-log", daemon=True) try: self.reader.start() except BaseException: self.reader = None # 未启动的 Thread.join() 会抛 RuntimeError raise except BaseException: # Popen 已成功但日志/线程初始化失败:必须回收,避免孤儿进程继续占端口。 try: self.stop(force=True) except Exception: pass raise def _read_loop(self) -> None: assert self.proc is not None and self.proc.stdout is not None while True: try: chunk = self.proc.stdout.readline() except (OSError, ValueError): break if not chunk: break text = chunk.decode("utf-8", "replace") self.stats.feed(text) writer = self.writer if writer is not None: try: writer.write(text) except (OSError, ValueError, AttributeError): # 日志盘写失败不能停止读管道,否则被测进程可能被 stdout 背压卡死。 try: writer.close() except (OSError, ValueError): pass if self.writer is writer: self.writer = None @property def pid(self) -> int: return int(self.proc.pid) if self.proc is not None else 0 def poll(self): return self.proc.poll() if self.proc is not None else None def stop(self, timeout: float = 15.0, force: bool = False) -> None: if self.proc is not None and self.proc.poll() is None: if force: self.proc.kill() else: self.proc.terminate() try: self.proc.wait(timeout=timeout) except subprocess.TimeoutExpired: self.proc.kill() try: self.proc.wait(timeout=5.0) except subprocess.TimeoutExpired: pass if self.proc is not None and self.proc.stdout is not None: try: self.proc.stdout.close() except OSError: pass if self.reader is not None: try: self.reader.join(timeout=3.0) except RuntimeError: pass # 线程未启动(初始化失败路径) self.reader = None self.stats.flush() writer = self.writer self.writer = None if writer is not None: try: writer.write("\n===== RUN %d STOP rc=%s =====\n" % (self.run_id, self.poll())) except (OSError, ValueError, AttributeError): pass finally: try: writer.close() except (OSError, ValueError): pass class _ProcessEntry32W(ctypes.Structure): _fields_ = [ ("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32ProcessID", ctypes.c_ulong), ("th32DefaultHeapID", ctypes.c_size_t), ("th32ModuleID", ctypes.c_ulong), ("cntThreads", ctypes.c_ulong), ("th32ParentProcessID", ctypes.c_ulong), ("pcPriClassBase", ctypes.c_long), ("dwFlags", ctypes.c_ulong), ("szExeFile", ctypes.c_wchar * 260), ] def find_pids_by_name(name: str): """按进程名查 PID;Linux 读 /proc,Windows 走 Toolhelp32。只返回精确匹配。""" target = os.path.basename(str(name)).lower() if not target: return [] if os.name == "nt": if not target.endswith(".exe"): candidates = {target, target + ".exe"} else: candidates = {target} k32 = ctypes.WinDLL("kernel32", use_last_error=True) k32.CreateToolhelp32Snapshot.restype = ctypes.c_void_p k32.CreateToolhelp32Snapshot.argtypes = [ctypes.c_ulong, ctypes.c_ulong] k32.Process32FirstW.argtypes = [ctypes.c_void_p, ctypes.POINTER(_ProcessEntry32W)] k32.Process32NextW.argtypes = [ctypes.c_void_p, ctypes.POINTER(_ProcessEntry32W)] k32.CloseHandle.argtypes = [ctypes.c_void_p] snapshot = k32.CreateToolhelp32Snapshot(0x00000002, 0) if not snapshot or snapshot == ctypes.c_void_p(-1).value: return [] found = [] try: entry = _ProcessEntry32W() entry.dwSize = ctypes.sizeof(entry) ok = k32.Process32FirstW(snapshot, ctypes.byref(entry)) while ok: if str(entry.szExeFile).lower() in candidates: found.append(int(entry.th32ProcessID)) ok = k32.Process32NextW(snapshot, ctypes.byref(entry)) finally: k32.CloseHandle(snapshot) return found found = [] for entry in os.listdir("/proc"): if not entry.isdigit(): continue pid = int(entry) try: with open("/proc/%d/comm" % pid, encoding="utf-8", errors="replace") as fh: comm = fh.read().strip() except OSError: continue if comm.lower() == target: found.append(pid) continue try: with open("/proc/%d/cmdline" % pid, "rb") as fh: argv0 = fh.read().split(b"\0")[0].decode("utf-8", "replace") except OSError: continue if os.path.basename(argv0).lower() == target: found.append(pid) return found def read_pid_file(path: str) -> int: try: text = Path(path).read_text(encoding="utf-8").strip() return int(text.split()[0]) if text else 0 except (OSError, ValueError, IndexError): return 0 def last_known_pid(rows) -> int: """取 CSV 里最后一个有效 PID;用于监测器重启后续跑时发现目标已更换。""" for row in reversed(rows): try: pid = int(row.get("pid") or 0) except (TypeError, ValueError): continue if pid > 0: return pid return 0 class _MemStatusEx(ctypes.Structure): _fields_ = [ ("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong), ("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong), ("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong), ("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong), ("ullAvailExtendedVirtual", ctypes.c_ulonglong), ] def system_metrics(path: Path) -> dict: """主机级指标:可用内存 / 磁盘 / 负载 / 温度(Linux)。""" out = {} try: usage = shutil.disk_usage(str(path)) out["disk_free_mb"] = usage.free / 1048576.0 except OSError: pass if os.name == "nt": try: status = _MemStatusEx() status.dwLength = ctypes.sizeof(status) if ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status)): out["avail_mb"] = status.ullAvailPhys / 1048576.0 except (AttributeError, OSError): pass return out try: with open("/proc/meminfo", encoding="utf-8") as fh: for line in fh: if line.startswith("MemAvailable:"): out["avail_mb"] = float(line.split()[1]) / 1024.0 break except OSError: pass try: out["load1"] = float(os.getloadavg()[0]) except (OSError, AttributeError): pass temps = [] for pattern in ("/sys/class/thermal/thermal_zone*/temp", "/sys/class/hwmon/hwmon*/temp*_input"): for name in glob.glob(pattern): try: value = float(Path(name).read_text(encoding="utf-8").strip()) except (OSError, ValueError): continue if abs(value) > 1000.0: value /= 1000.0 if -40.0 <= value <= 200.0: temps.append(value) if temps: out["temp_c"] = max(temps) return out def fd_summary(pid: int, limit: int = 10) -> dict: """Linux fd 类型 TopN(排查句柄泄漏:socket/pipe/文件各涨了多少)。""" if os.name == "nt" or not pid: return {} counter = Counter() try: for name in os.listdir("/proc/%d/fd" % pid): try: target = os.readlink("/proc/%d/fd/%s" % (pid, name)) except OSError: continue if target.startswith("socket:"): key = "socket" elif target.startswith("pipe:"): key = "pipe" elif target.startswith("anon_inode:"): key = target else: key = os.path.basename(target) or target counter[key] += 1 except OSError: return {} return dict(counter.most_common(limit)) class Campaign: """一个 7x24 验收目录:元数据、CSV、事件、日志、报告。""" def __init__(self, path) -> None: self.dir = Path(path).resolve() self.dir.mkdir(parents=True, exist_ok=True) self.meta_path = self.dir / "campaign.json" self.samples_path = self.dir / "samples.csv" self.events_path = self.dir / "events.csv" self.latest_path = self.dir / "latest.md" self.report_md = self.dir / "report.md" self.report_json = self.dir / "report.json" self.log_path = self.dir / "soak7.log" self.fd_path = self.dir / "fd_summary.json" self._samples_written = 0 def load_meta(self) -> dict: if not self.meta_path.exists(): return {} try: return json.loads(self.meta_path.read_text(encoding="utf-8")) except (OSError, ValueError): return {} def ensure_meta(self, values: dict) -> dict: meta = self.load_meta() if meta: return meta meta = dict(values) meta.setdefault("schema", SCHEMA) meta.setdefault("created_epoch", time.time()) meta.setdefault("created_iso", _dt.datetime.now().astimezone().isoformat(timespec="seconds")) self.write_json(self.meta_path, meta) return meta def write_json(self, path: Path, data) -> None: tmp = Path(str(path) + ".tmp") tmp.write_text(json.dumps(data, ensure_ascii=False, indent=2, default=str), encoding="utf-8") os.replace(tmp, path) def append_sample(self, row: dict, fsync_every: int = 10) -> None: exists = self.samples_path.exists() and self.samples_path.stat().st_size > 0 payload = {key: ("" if row.get(key) is None else row.get(key)) for key in SAMPLE_FIELDS} with open(self.samples_path, "a", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=SAMPLE_FIELDS, extrasaction="ignore") if not exists: writer.writeheader() writer.writerow(payload) self._samples_written += 1 if fsync_every <= 0 or self._samples_written % fsync_every == 0: fh.flush() os.fsync(fh.fileno()) def append_event(self, elapsed_s: float, event: str, detail: str = "") -> dict: now = time.time() row = { "wall": _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "iso": _dt.datetime.now().astimezone().isoformat(timespec="seconds"), "epoch": round(now, 3), "elapsed_s": round(float(elapsed_s), 3), "event": str(event), "detail": redact(str(detail))[:2000], } exists = self.events_path.exists() and self.events_path.stat().st_size > 0 with open(self.events_path, "a", newline="", encoding="utf-8") as fh: writer = csv.DictWriter(fh, fieldnames=EVENT_FIELDS, extrasaction="ignore") if not exists: writer.writeheader() writer.writerow(row) fh.flush() os.fsync(fh.fileno()) return row def load_rows(self) -> list: rows = [] if not self.samples_path.exists(): return rows with open(self.samples_path, newline="", encoding="utf-8") as fh: for raw in csv.DictReader(fh): row = {} for key, value in raw.items(): if value is None or value == "": row[key] = None elif key in FLOAT_FIELDS: try: row[key] = float(value) except ValueError: row[key] = None elif key in INT_FIELDS: try: row[key] = int(float(value)) except ValueError: row[key] = None else: row[key] = value rows.append(row) rows.sort(key=lambda r: float(r.get("elapsed_s") or 0.0)) return rows def load_events(self) -> list: events = [] if not self.events_path.exists(): return events with open(self.events_path, newline="", encoding="utf-8") as fh: for raw in csv.DictReader(fh): if raw.get("elapsed_s"): try: raw["elapsed_s"] = float(raw["elapsed_s"]) except ValueError: raw["elapsed_s"] = 0.0 events.append(raw) return events def write_text(self, path: Path, text: str) -> None: tmp = Path(str(path) + ".tmp") tmp.write_text(text, encoding="utf-8") os.replace(tmp, path) @dataclass class Criteria: duration_s: float interval_s: float warmup_s: float max_restarts: int = 0 rss_slope_mb_per_hour: float = 1.0 rss_growth_mb: float = 32.0 handle_slope_per_hour: float = 0.5 handle_growth: float = 10.0 thread_growth: int = 2 max_frame_stall_s: float = 300.0 min_modbus_success_pct: float = 99.9 max_modbus_p99_ms: float = 200.0 max_frame_timeout_pct: float = 5.0 min_disk_free_mb: float = 1024.0 max_temp_c: float = 85.0 min_available_mb: float = 128.0 max_warn_per_hour: float = 60.0 require_modbus: bool = False def _stat_delta(rows, key: str): values = [r.get(key) for r in rows if r.get(key) is not None] if len(values) < 2: return None, None return int(values[-1]) - int(values[0]), values[-1] def analyze_rows(rows, events, criteria: Criteria) -> dict: """对 CSV 行做验收判定;纯函数,便于单测和复算历史 campaign。""" failures = [] warnings = [] metrics = {} if not rows: return { "verdict": "FAIL", "failures": ["没有任何采样数据"], "warnings": [], "metrics": {}, "criteria": asdict(criteria), } t0 = float(rows[0]["elapsed_s"]) t1 = float(rows[-1]["elapsed_s"]) duration = max(0.0, t1 - t0) hours = duration / 3600.0 base_start = t0 + max(0.0, criteria.warmup_s) post = [r for r in rows if float(r["elapsed_s"]) >= base_start] if len(post) < 3: # 少于 3 个点无法做最小二乘/首末窗口比较;不能把“无法判定”当成 0 增长。 failures.append("预热后有效采样点只有 %d 个(至少 3 个)→ 无法证明趋势/存活" % len(post)) post = rows base_start = t0 post_t0 = float(post[0]["elapsed_s"]) post_t1 = float(post[-1]["elapsed_s"]) rss_series = metric_series(post, "rss_mb", post_t0) private_series = metric_series(post, "private_mb", post_t0) handle_series = metric_series(post, "handles", post_t0) thread_series = metric_series(post, "threads", post_t0) rss_slope = slope_per_min(rss_series) * 60.0 private_slope = slope_per_min(private_series) * 60.0 handle_slope = slope_per_min(handle_series) * 60.0 if not rss_series: failures.append("没有任何 RSS 样本 → 无法证明内存稳定") if not handle_series: failures.append("没有任何句柄/fd 样本 → 无法证明句柄稳定") if not thread_series: failures.append("没有任何线程样本 → 无法证明线程稳定") compare_window = min(86400.0, max(60.0, duration / 4.0)) early_end = min(post_t1, base_start + compare_window) late_start = max(base_start, post_t1 - compare_window) rss_early = median_window(post, "rss_mb", base_start, early_end) rss_late = median_window(post, "rss_mb", late_start, post_t1) handle_early = median_window(post, "handles", base_start, early_end) handle_late = median_window(post, "handles", late_start, post_t1) thread_early = median_window(post, "threads", base_start, early_end) thread_late = median_window(post, "threads", late_start, post_t1) rss_growth = (rss_late - rss_early) if rss_early is not None and rss_late is not None else None handle_growth = (handle_late - handle_early) if handle_early is not None and handle_late is not None else None thread_growth = (thread_late - thread_early) if thread_early is not None and thread_late is not None else None rss_rise = rise_ratio(rss_series) handle_rise = rise_ratio(handle_series) thread_values = [int(v) for _, v in thread_series] max_threads = max(thread_values) if thread_values else None min_threads = min(thread_values) if thread_values else None max_rss = max((v for _, v in rss_series), default=None) max_handles = max((v for _, v in handle_series), default=None) last = rows[-1] last_alive = int(last.get("alive") or 0) == 1 alive_values = [int(r["alive"]) for r in rows if r.get("alive") is not None] alive_ratio = (sum(alive_values) / len(alive_values) * 100.0) if alive_values else 0.0 run_ids = {int(r["run_id"]) for r in rows if r.get("run_id") is not None} start_events = [e for e in events if e.get("event") in ("START", "REATTACH")] restarts = max(max(run_ids, default=1) - 1, max(0, len(start_events) - 1)) gap, gap_metric = progress_gap_seconds(post) frame_values = [int(r["frames"]) for r in post if r.get("frames") is not None] frames_last = frame_values[-1] if frame_values else None fps_values = [float(r["fps_x10"]) / 10.0 for r in post if r.get("fps_x10") is not None] fps_median = statistics.median(fps_values) if fps_values else None probes = [r for r in post if r.get("modbus_ok") is not None] probe_ok = [r for r in probes if int(r["modbus_ok"]) == 1] modbus_success = (len(probe_ok) / len(probes) * 100.0) if probes else None modbus_rtt_p50 = percentile([r.get("modbus_rtt_ms") for r in probe_ok], 0.50) modbus_rtt_p95 = percentile([r.get("modbus_rtt_ms") for r in probe_ok], 0.95) modbus_rtt_p99 = percentile([r.get("modbus_rtt_ms") for r in probe_ok], 0.99) timeout_hits = sum( 1 for r in probe_ok if r.get("modbus_flags") is not None and (int(r["modbus_flags"]) & FLAG_FRAME_TIMEOUT) ) frame_timeout_pct = (timeout_hits / len(probe_ok) * 100.0) if probe_ok else None warn_delta, warn_last = _stat_delta(post, "warn_lines") error_delta, _ = _stat_delta(post, "error_lines") fatal_delta, fatal_last = _stat_delta(post, "fatal_lines") fatal_values = [int(r["fatal_lines"]) for r in post if r.get("fatal_lines") is not None] fatal_peak = max(fatal_values) if fatal_values else None warn_per_hour = (warn_delta / hours) if warn_delta is not None and hours > 0 else None disk_min = min((r["disk_free_mb"] for r in rows if r.get("disk_free_mb") is not None), default=None) avail_min = min((r["avail_mb"] for r in rows if r.get("avail_mb") is not None), default=None) temp_max = max((r["temp_c"] for r in rows if r.get("temp_c") is not None), default=None) elapsed_values = [float(r["elapsed_s"]) for r in rows] sample_gaps = [b - a for a, b in zip(elapsed_values, elapsed_values[1:])] max_sample_gap = max(sample_gaps) if sample_gaps else 0.0 fatal_events = sum(1 for e in events if e.get("event") == "FATAL") metrics.update({ "duration_s": duration, "samples": len(rows), "alive_ratio_pct": alive_ratio, "last_alive": last_alive, "restarts": restarts, "rss_slope_mb_per_hour": rss_slope, "private_slope_mb_per_hour": private_slope, "rss_growth_mb": rss_growth, "rss_rise_ratio": rss_rise, "peak_rss_mb": max_rss, "handle_slope_per_hour": handle_slope, "handle_growth": handle_growth, "handle_rise_ratio": handle_rise, "peak_handles": max_handles, "thread_early": thread_early, "thread_late": thread_late, "thread_growth": thread_growth, "max_threads": max_threads, "min_threads": min_threads, "progress_gap_s": gap, "progress_metric": gap_metric, "frames_last": frames_last, "fps_median": fps_median, "modbus_probes": len(probes), "modbus_success_pct": modbus_success, "modbus_rtt_p50_ms": modbus_rtt_p50, "modbus_rtt_p95_ms": modbus_rtt_p95, "modbus_rtt_p99_ms": modbus_rtt_p99, "frame_timeout_pct": frame_timeout_pct, "warn_delta": warn_delta, "warn_per_hour": warn_per_hour, "warn_last": warn_last, "error_delta": error_delta, "fatal_delta": fatal_delta, "fatal_last": fatal_last, "fatal_peak": fatal_peak, "disk_free_min_mb": disk_min, "avail_min_mb": avail_min, "temp_max_c": temp_max, "max_sample_gap_s": max_sample_gap, "fatal_events": fatal_events, }) # ---------------- 硬判据 ---------------- tolerance = max(120.0, 2.0 * criteria.interval_s) if duration + tolerance < criteria.duration_s: failures.append("实际只覆盖 %.2f h,未跑满 %.2f h" % (duration / 3600.0, criteria.duration_s / 3600.0)) gap_limit = max(300.0, 5.0 * criteria.interval_s) if max_sample_gap > gap_limit: failures.append("采样出现 %.1f s 空洞(上限 %.1f s)→ 监测器中断,证据不连续" % (max_sample_gap, gap_limit)) if restarts > criteria.max_restarts: failures.append("进程重启 %d 次(上限 %d)" % (restarts, criteria.max_restarts)) if not last_alive: failures.append("最后一次采样时被测进程已不在") if rss_slope > criteria.rss_slope_mb_per_hour: failures.append("RSS 趋势 %+.2f MB/h(上限 %.2f)→ 疑似内存泄漏" % (rss_slope, criteria.rss_slope_mb_per_hour)) if rss_growth is not None and rss_growth > criteria.rss_growth_mb: failures.append("首末窗口 RSS 中位数增长 %+.2f MB(上限 %.2f)" % (rss_growth, criteria.rss_growth_mb)) if handle_slope > criteria.handle_slope_per_hour: failures.append("句柄趋势 %+.2f 个/h(上限 %.2f)→ 疑似句柄/fd 泄漏" % (handle_slope, criteria.handle_slope_per_hour)) if handle_growth is not None and handle_growth > criteria.handle_growth: failures.append("首末窗口句柄中位数增长 %+.1f 个(上限 %.1f)" % (handle_growth, criteria.handle_growth)) if thread_growth is not None and thread_growth > criteria.thread_growth: failures.append("线程数增长 %+.1f(上限 %d)→ 疑似线程泄漏" % (thread_growth, criteria.thread_growth)) if gap is not None and gap > criteria.max_frame_stall_s: failures.append("%s 最长停滞 %.1f s(上限 %.0f s)→ 卡死/断流未恢复" % (gap_metric or "进度", gap, criteria.max_frame_stall_s)) if probes: if modbus_success is not None and modbus_success < criteria.min_modbus_success_pct: failures.append("Modbus 探活成功率 %.3f%%(下限 %.3f%%)" % (modbus_success, criteria.min_modbus_success_pct)) if modbus_rtt_p99 is not None and modbus_rtt_p99 > criteria.max_modbus_p99_ms: failures.append("Modbus 探活 p99 %.1f ms(上限 %.1f ms)" % (modbus_rtt_p99, criteria.max_modbus_p99_ms)) if frame_timeout_pct is not None and frame_timeout_pct > criteria.max_frame_timeout_pct: failures.append("探活样本中 FRAME_TIMEOUT 占 %.2f%%(上限 %.2f%%)" % (frame_timeout_pct, criteria.max_frame_timeout_pct)) elif criteria.require_modbus: failures.append("要求 Modbus 探活,但没有探活样本(未配置 --modbus-host 或进程未起来)") else: warnings.append("未配置 Modbus 探活:无法区分\"进程活着\"与\"结果链路正常\"") if fatal_delta is not None and fatal_delta > 0: failures.append("日志出现 %d 条致命标记(崩溃/未捕获异常)" % fatal_delta) elif fatal_peak is not None and fatal_peak > 0: # 预热期内的致命标记、日志轮转/监测器重启导致的计数回退,都应保留为失败。 failures.append("日志累计出现 %d 条致命标记(崩溃/未捕获异常)" % fatal_peak) elif fatal_events > 0: failures.append("事件表记录 %d 次致命标记(崩溃/未捕获异常)" % fatal_events) # 监测器在终点附近坏掉/退出时,最后一行样本可能仍是 alive,且时长落在容差内; # 这类“没有继续采样”的终止事件必须单独判 FAIL,不能被 last_alive 掩盖。 terminal_names = ("SAMPLE_ERROR", "TARGET_LOST_FINAL", "RESTART_DENIED", "START_FAILED") terminal = [e.get("event") for e in events if e.get("event") in terminal_names] if terminal: failures.append("监测器记录终止事件 %s → 证据不完整" % ", ".join(sorted(set(terminal)))) last_start = max((i for i, e in enumerate(events) if e.get("event") in ("START", "REATTACH")), default=-1) last_exit = max((i for i, e in enumerate(events) if e.get("event") == "EXIT"), default=-1) if last_exit > last_start: failures.append("被测进程在跑满时长前退出(最后一次 EXIT 后没有新的 START)") if disk_min is not None and disk_min < criteria.min_disk_free_mb: failures.append("磁盘余量最低 %.1f MB(下限 %.1f MB)" % (disk_min, criteria.min_disk_free_mb)) if temp_max is not None and temp_max > criteria.max_temp_c: failures.append("最高温度 %.1f ℃(上限 %.1f ℃)" % (temp_max, criteria.max_temp_c)) if avail_min is not None and avail_min < criteria.min_available_mb: failures.append("系统可用内存最低 %.1f MB(下限 %.1f MB)" % (avail_min, criteria.min_available_mb)) # ---------------- 软判据(人工复核) ---------------- if rss_rise >= 0.9 and rss_slope > 0: warnings.append("预热后 %.0f%% 的分钟 RSS 都在上涨,建议画曲线复核" % (rss_rise * 100.0)) if handle_rise >= 0.9 and handle_slope > 0: warnings.append("预热后 %.0f%% 的分钟句柄都在上涨,建议看 fd_summary.json" % (handle_rise * 100.0)) if gap is None: warnings.append("没有帧数/心跳进度信号(attach 模式需 --log-file 或 Modbus 探活)") if warn_per_hour is not None and warn_per_hour > criteria.max_warn_per_hour: warnings.append("[warn] %.1f 行/h(上限 %.1f)→ 检查日志刷屏/相机重连" % (warn_per_hour, criteria.max_warn_per_hour)) if error_delta is not None and error_delta > 0: warnings.append("日志出现 %d 条 [error](致命标记会单独判 FAIL)" % error_delta) if alive_ratio < 99.0 and restarts == 0: warnings.append("存活采样占比 %.2f%%,建议核对采样期间是否有进程退出" % alive_ratio) verdict = "FAIL" if failures else ("WARN" if warnings else "PASS") return { "verdict": verdict, "failures": failures, "warnings": warnings, "metrics": metrics, "criteria": asdict(criteria), } def _fmt(value, digits=1, suffix="", dash="—"): if value is None: return dash if isinstance(value, bool): return "是" if value else "否" if isinstance(value, int): return "%d%s" % (value, suffix) return "%.*f%s" % (digits, float(value), suffix) def _daily_table(rows): groups = {} for row in rows: wall = str(row.get("wall") or "") day = wall[:10] if len(wall) >= 10 else "unknown" groups.setdefault(day, []).append(row) lines = [ "| 日期 | 样本 | 覆盖 h | RSS 首→末 / 峰 (MB) | 句柄 首→末 | 线程 末 | 帧数 末 | Modbus 成功 | 温度峰 ℃ |", "| --- | ---: | ---: | --- | --- | ---: | ---: | ---: | ---: |", ] for day in sorted(groups): group = groups[day] rss_values = [r["rss_mb"] for r in group if r.get("rss_mb") is not None] handle_values = [r["handles"] for r in group if r.get("handles") is not None] thread_values = [r["threads"] for r in group if r.get("threads") is not None] frame_values = [r["frames"] for r in group if r.get("frames") is not None] probes = [r for r in group if r.get("modbus_ok") is not None] temps = [r["temp_c"] for r in group if r.get("temp_c") is not None] span = (float(group[-1]["elapsed_s"]) - float(group[0]["elapsed_s"])) / 3600.0 success = ("%.2f%%" % (sum(int(r["modbus_ok"]) for r in probes) / len(probes) * 100.0) if probes else "—") lines.append("| %s | %d | %.2f | %s → %s / %s | %s → %s | %s | %s | %s | %s |" % ( day, len(group), span, _fmt(rss_values[0] if rss_values else None, 1), _fmt(rss_values[-1] if rss_values else None, 1), _fmt(max(rss_values) if rss_values else None, 1), _fmt(handle_values[0] if handle_values else None, 0), _fmt(handle_values[-1] if handle_values else None, 0), _fmt(thread_values[-1] if thread_values else None, 0), _fmt(frame_values[-1] if frame_values else None, 0), success, _fmt(max(temps) if temps else None, 1), )) return "\n".join(lines) def render_report(campaign: Campaign, meta: dict, analysis: dict, events, cmd_text: str, rows=None) -> str: metrics = analysis.get("metrics", {}) criteria = analysis.get("criteria", {}) verdict = analysis.get("verdict", "FAIL") lines = [ "# portcv 7x24 浸泡 / 稳定性验收报告", "", "> 本报告由 `scripts/soak_7x24.py` 自动生成。原始证据在同目录 `samples.csv`、" "`events.csv`、`stdout_run*.log`、`soak7.log`、`fd_summary.json`。", "", "## 结论", "", "**%s**" % verdict, "", ] if analysis.get("failures"): lines += ["### FAIL(必须处理)", ""] lines += ["- %s" % item for item in analysis["failures"]] lines.append("") if analysis.get("warnings"): lines += ["### WARN(人工复核)", ""] lines += ["- %s" % item for item in analysis["warnings"]] lines.append("") lines += [ "## 被测对象", "", "| 项 | 值 |", "| --- | --- |", "| campaign | `%s` |" % campaign.dir, "| 被测命令/进程 | `%s` |" % cmd_text.replace("|", "\\|"), "| 创建时间 | %s |" % meta.get("created_iso", "—"), "| 采样间隔 | %.1f s |" % float(meta.get("interval_s", 0.0) or 0.0), "| 预热期 | %.0f s |" % float(meta.get("warmup_s", 0.0) or 0.0), "| 目标时长 | %.2f h |" % (float(meta.get("duration_s", 0.0) or 0.0) / 3600.0), "| 平台 | %s / Python %s / CPU %s |" % ( sys.platform, sys.version.split()[0], os.cpu_count()), "", "## 关键指标", "", "| 指标 | 实测 | 判据 |", "| --- | ---: | ---: |", "| 实际覆盖 | %.2f h / %d 样本 | ≥ %.2f h |" % ( metrics.get("duration_s", 0.0) / 3600.0, metrics.get("samples", 0), criteria.get("duration_s", 0.0) / 3600.0), "| 进程重启 | %s | ≤ %s |" % ( _fmt(metrics.get("restarts"), 0), _fmt(criteria.get("max_restarts"), 0)), "| 存活采样占比 | %s | 观察项 |" % _fmt(metrics.get("alive_ratio_pct"), 2, "%"), "| RSS 趋势 | %s | ≤ %s |" % ( _fmt(metrics.get("rss_slope_mb_per_hour"), 2, " MB/h"), _fmt(criteria.get("rss_slope_mb_per_hour"), 2, " MB/h")), "| RSS 首末窗口增长 | %s | ≤ %s |" % ( _fmt(metrics.get("rss_growth_mb"), 2, " MB"), _fmt(criteria.get("rss_growth_mb"), 2, " MB")), "| RSS 峰值 | %s | 观察项 |" % _fmt(metrics.get("peak_rss_mb"), 2, " MB"), "| 句柄趋势 | %s | ≤ %s |" % ( _fmt(metrics.get("handle_slope_per_hour"), 2, " 个/h"), _fmt(criteria.get("handle_slope_per_hour"), 2, " 个/h")), "| 句柄首末窗口增长 | %s | ≤ %s |" % ( _fmt(metrics.get("handle_growth"), 1, " 个"), _fmt(criteria.get("handle_growth"), 1, " 个")), "| 句柄峰值 | %s | 观察项 |" % _fmt(metrics.get("peak_handles"), 0), "| 线程数(首→末) | %s → %s | 增长 ≤ %s |" % ( _fmt(metrics.get("thread_early"), 1), _fmt(metrics.get("thread_late"), 1), _fmt(criteria.get("thread_growth"), 0)), "| 最长进度停滞 | %s | ≤ %s |" % ( _fmt(metrics.get("progress_gap_s"), 1, " s"), _fmt(criteria.get("max_frame_stall_s"), 0, " s")), "| 最大采样空洞 | %s | ≤ %s |" % ( _fmt(metrics.get("max_sample_gap_s"), 1, " s"), _fmt(max(300.0, 5.0 * float(criteria.get("interval_s", 0.0) or 0.0)), 0, " s")), "| 实测 fps 中位数 | %s | 观察项 |" % _fmt(metrics.get("fps_median"), 1, " fps"), "| Modbus 探活成功 | %s / %s 次 | ≥ %s |" % ( _fmt(metrics.get("modbus_success_pct"), 3, "%"), _fmt(metrics.get("modbus_probes"), 0), _fmt(criteria.get("min_modbus_success_pct"), 3, "%")), "| Modbus RTT p99 | %s | ≤ %s |" % ( _fmt(metrics.get("modbus_rtt_p99_ms"), 1, " ms"), _fmt(criteria.get("max_modbus_p99_ms"), 1, " ms")), "| 探活中 FRAME_TIMEOUT | %s | ≤ %s |" % ( _fmt(metrics.get("frame_timeout_pct"), 2, "%"), _fmt(criteria.get("max_frame_timeout_pct"), 2, "%")), "| 磁盘余量最低 | %s | ≥ %s |" % ( _fmt(metrics.get("disk_free_min_mb"), 0, " MB"), _fmt(criteria.get("min_disk_free_mb"), 0, " MB")), "| 可用内存最低 | %s | ≥ %s |" % ( _fmt(metrics.get("avail_min_mb"), 0, " MB"), _fmt(criteria.get("min_available_mb"), 0, " MB")), "| 温度最高 | %s | ≤ %s |" % ( _fmt(metrics.get("temp_max_c"), 1, " ℃"), _fmt(criteria.get("max_temp_c"), 1, " ℃")), "| [warn] 速率 | %s | ≤ %s |" % ( _fmt(metrics.get("warn_per_hour"), 1, " 行/h"), _fmt(criteria.get("max_warn_per_hour"), 1, " 行/h")), "", "## 每日汇总", "", _daily_table(rows if rows is not None else campaign.load_rows()), "", "## 事件", "", ] if events: lines += ["| 时间 | 事件 | 详情 |", "| --- | --- | --- |"] for event in events[-50:]: lines.append("| %s | %s | %s |" % ( event.get("iso", ""), event.get("event", ""), redact(str(event.get("detail", ""))).replace("|", "\\|")[:220])) if len(events) > 50: lines.append("| ... | ... | 其余 %d 条见 `events.csv` |" % (len(events) - 50)) else: lines.append("(无事件)") lines += [ "", "## 判据说明", "", "* **RSS 趋势/首末窗口增长**:预热期后做最小二乘,排除分配器冷启动;同时比较首末 1/4 窗口" "(7 天时窗口封顶 24 h)的中位数,避免只看首末两个点。", "* **句柄趋势**:Linux 是 `/proc//fd` 条目数;Windows 是内核句柄计数。" "两个判据都要过:斜率与首末净增。", "* **进度停滞**:优先看 `[stat] 已发布 N 帧`,没有日志时退化到 Modbus `heartbeat`。" "进程活着但帧不前进,仍判 FAIL。", "* **Modbus 探活**:FC4 读 12 字并校验 CRC;它同时检查\"服务端在监听\"与\"快照是自洽的\"。", "* **严格模式**:`--strict` 时 WARN 也返回退出码 1;默认 WARN 只提示、不阻断。", "", "## 复现/复算", "", "```bash", "# 用同一份 CSV 复算(不重新跑设备):", "python scripts/soak_7x24.py --analyze-only %s --duration 7d" % campaign.dir, "```", "", "> 注意:本报告只能证明**本次采样窗口内**的资源与链路行为;" "算法准确率、阈值整定、PLC 联锁仍需按 `docs/deployment.md` §6 与 " "`docs/edge_evidence.md` 单独验收。", "", ] return "\n".join(lines) def render_latest(meta: dict, last: dict, recent, restarts: int, criteria: Criteria, session_started: float) -> str: rss = metric_series(recent, "rss_mb", 0.0) handles = metric_series(recent, "handles", 0.0) rss_slope = slope_per_min(rss) * 60.0 handle_slope = slope_per_min(handles) * 60.0 elapsed_h = float(last.get("elapsed_s") or 0.0) / 3600.0 target_h = criteria.duration_s / 3600.0 return "\n".join([ "# 7x24 浸泡进行中", "", "- campaign 创建: `%s`" % meta.get("created_iso", "—"), "- 进度: **%.2f / %.2f h**(%.1f%%),本轮监测已运行 %.1f min" % ( elapsed_h, target_h, (elapsed_h / target_h * 100.0) if target_h else 0.0, (time.time() - session_started) / 60.0), "- PID / run: `%s` / `%s`,alive=%s,重启累计 **%d**" % ( _fmt(last.get("pid"), 0), _fmt(last.get("run_id"), 0), "是" if int(last.get("alive") or 0) else "否", restarts), "- RSS: **%s MB**(近窗趋势 %s)" % ( _fmt(last.get("rss_mb"), 2), _fmt(rss_slope, 2, " MB/h")), "- 句柄: **%s**(近窗趋势 %s)" % ( _fmt(last.get("handles"), 0), _fmt(handle_slope, 2, " 个/h")), "- 线程: **%s**" % _fmt(last.get("threads"), 0), "- 帧数 / fps: **%s** / **%s**" % ( _fmt(last.get("frames"), 0), _fmt((last.get("fps_x10") or 0) / 10.0, 1)), "- Modbus: ok=%s rtt=%s flags=0x%s" % ( last.get("modbus_ok"), _fmt(last.get("modbus_rtt_ms"), 1, " ms"), ("%04X" % int(last["modbus_flags"])) if last.get("modbus_flags") is not None else "—"), "- 磁盘余量 / 可用内存 / 温度: %s / %s / %s" % ( _fmt(last.get("disk_free_mb"), 0, " MB"), _fmt(last.get("avail_mb"), 0, " MB"), _fmt(last.get("temp_c"), 1, " ℃")), "- 最新采样: `%s`" % str(last.get("wall") or ""), "", "> 最终 PASS/FAIL 以 `report.md` 为准;本文件每轮采样更新。", "", ]) def process_alive(sampler, pid: int) -> bool: if not pid: return False try: handle = sampler.open(pid) except (OSError, ValueError): return False if not handle: return False try: return bool(sampler.alive(handle)) except (OSError, ValueError): return False finally: sampler.close(handle) def sample_row(sampler, pid: int, run_id: int, stats: LogStats, previous, args, elapsed_s: float, campaign: Campaign) -> dict: """采一次样:进程资源 + 日志进度 + Modbus 探活 + 主机环境。""" now = time.time() snap = stats.snapshot() row = {key: None for key in SAMPLE_FIELDS} row.update({ "wall": _dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "iso": _dt.datetime.now().astimezone().isoformat(timespec="seconds"), "epoch": round(now, 3), "elapsed_s": round(float(elapsed_s), 3), "run_id": int(run_id), "pid": int(pid) if pid else None, "alive": 0, "frames": snap["frames"], "fps_x10": snap["fps_x10"], "warn_lines": snap["warn_lines"], "error_lines": snap["error_lines"], "fatal_lines": len(snap["fatal"]), "frame_timeout_lines": snap["frame_timeout_lines"], }) handle = sampler.open(pid) if pid else 0 if handle: values = {} try: values = sampler.sample(pid, handle) or {} row["alive"] = 1 if sampler.alive(handle) else 0 except (OSError, ValueError): row["alive"] = 0 finally: sampler.close(handle) if row["alive"]: for key in ("rss_mb", "private_mb", "peak_rss_mb", "paged_pool_mb", "nonpaged_pool_mb", "handles", "threads", "cpu_s", "io_read_mb", "io_write_mb"): if key in values: row[key] = round(float(values[key]), 3) if (previous is not None and previous.get("pid") == pid and previous.get("run_id") == run_id and previous.get("cpu_s") is not None and row["cpu_s"] is not None): delta_cpu = float(row["cpu_s"]) - float(previous["cpu_s"]) delta_t = float(row["elapsed_s"]) - float(previous["elapsed_s"]) if delta_t > 0 and delta_cpu >= 0: row["cpu_pct"] = round(delta_cpu / delta_t * 100.0, 2) if args.modbus_host: ok, rtt, snapshot, error = modbus_probe( args.modbus_host, args.modbus_port, args.modbus_unit, args.modbus_addr, count=12, timeout=args.modbus_timeout, ) row["modbus_ok"] = 1 if ok else 0 row["modbus_rtt_ms"] = round(rtt, 3) row["modbus_error"] = redact(error)[:300] if error else "" if snapshot: row["modbus_state"] = snapshot["state"] row["modbus_flags"] = snapshot["flags"] row["modbus_heartbeat"] = snapshot["heartbeat"] row["modbus_fps_x10"] = snapshot["fps_x10"] row["modbus_latency_ms"] = snapshot["latency_ms"] row["modbus_seq"] = snapshot["seq"] row.update(system_metrics(campaign.dir)) return row def build_criteria(args, duration_s: float) -> Criteria: return Criteria( duration_s=float(duration_s), interval_s=float(args.interval), warmup_s=float(args.warmup), max_restarts=int(args.allow_restarts), rss_slope_mb_per_hour=float(args.rss_slope_mb_per_hour), rss_growth_mb=float(args.rss_growth_mb), handle_slope_per_hour=float(args.handle_slope_per_hour), handle_growth=float(args.handle_growth), thread_growth=int(args.thread_growth), max_frame_stall_s=float(args.max_frame_stall_s), min_modbus_success_pct=float(args.min_modbus_success_pct), max_modbus_p99_ms=float(args.max_modbus_p99_ms), max_frame_timeout_pct=float(args.max_frame_timeout_pct), min_disk_free_mb=float(args.min_disk_free_mb), max_temp_c=float(args.max_temp_c), min_available_mb=float(args.min_available_mb), max_warn_per_hour=float(args.max_warn_per_hour), require_modbus=bool(args.require_modbus), ) def setup_logging(campaign: Campaign) -> logging.Logger: logger = logging.getLogger("soak7") logger.setLevel(logging.INFO) for handler in logger.handlers[:]: logger.removeHandler(handler) try: handler.close() except OSError: pass fmt = logging.Formatter("%(asctime)s %(levelname)s %(message)s", "%Y-%m-%d %H:%M:%S") fh = logging.handlers.RotatingFileHandler( campaign.log_path, maxBytes=16 * 1024 * 1024, backupCount=5, encoding="utf-8", ) fh.setFormatter(fmt) sh = logging.StreamHandler() sh.setFormatter(fmt) logger.addHandler(fh) logger.addHandler(sh) return logger def parse_args(argv=None): parser = argparse.ArgumentParser( description="portcv 7x24 浸泡 / 稳定性验收(内存·句柄·线程·Modbus·温度)", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=( "示例:\n" " python scripts/soak_7x24.py --duration 7d --interval 60 \\\n" " --process-name portcv_run --campaign /var/lib/portcv-soak/campaign \\\n" " --modbus-host 127.0.0.1 --modbus-port 1502\n" " python scripts/soak_7x24.py --duration 90s --interval 5 --warmup 10 \\\n" " --campaign runs/soak7_smoke -- build/tools/portcv_run.exe ...\n" " python scripts/soak_7x24.py --analyze-only runs/soak7_smoke --duration 7d\n" ), ) parser.add_argument("--duration", default=None, help="目标时长:7d / 168h / 30m / 90s(不带单位按小时;默认 7d)") parser.add_argument("--days", type=float, default=None, help="目标天数(与 --duration 二选一)") parser.add_argument("--interval", type=float, default=60.0, help="采样间隔秒(默认 60)") parser.add_argument("--warmup", type=float, default=3600.0, help="预热期秒(默认 3600;不计入趋势)") parser.add_argument("--campaign", default=None, help="证据目录(可断点续跑;默认 runs/soak7_<时间戳>)") parser.add_argument("--outdir", default=os.path.join(REPO, "runs"), help="未指定 --campaign 时的父目录") target = parser.add_mutually_exclusive_group() target.add_argument("--pid", type=int, default=0, help="监测已存在的 PID(退出即 FAIL)") target.add_argument("--pid-file", default="", help="从 PID 文件读取;变化时重新 attach") target.add_argument("--process-name", default="", help="按进程名查找并跟随 systemd 重启(Linux /proc / Windows Toolhelp32)") parser.add_argument("--log-file", default="", help="attach 模式读这个日志文件(增量解析;不轮转)") parser.add_argument("--restart", choices=("never", "on-failure", "always"), default="on-failure", help="自己拉起进程时的重启策略(默认 on-failure)") parser.add_argument("--max-restarts", type=int, default=5, help="崩溃后最多继续拉起几次(硬上限,默认 5;证据仍会判 1 次重启 FAIL)") parser.add_argument("--restart-backoff", type=float, default=10.0, help="重启退避秒(指数退避,封顶 300 s)") parser.add_argument("--reattach-timeout", type=float, default=120.0, help="attach 模式发现进程消失后等待重新出现的秒数(默认 120)") parser.add_argument("--kill-timeout", type=float, default=15.0, help="收尾时 SIGTERM 等待秒") parser.add_argument("--modbus-host", default="", help="Modbus 探活主机;空 = 不探活") parser.add_argument("--modbus-port", type=int, default=1502) parser.add_argument("--modbus-unit", type=int, default=1) parser.add_argument("--modbus-addr", type=int, default=0) parser.add_argument("--modbus-timeout", type=float, default=1.0) parser.add_argument("--require-modbus", action="store_true", help="没有配置 Modbus 探活就判 FAIL(默认只 WARN)") parser.add_argument("--allow-restarts", type=int, default=0, help="验收允许的重启次数(默认 0;故障注入阶段可临时放宽)") parser.add_argument("--rss-slope-mb-per-hour", type=float, default=1.0) parser.add_argument("--rss-growth-mb", type=float, default=32.0) parser.add_argument("--handle-slope-per-hour", type=float, default=0.5) parser.add_argument("--handle-growth", type=float, default=10.0) parser.add_argument("--thread-growth", type=int, default=2) parser.add_argument("--max-frame-stall-s", type=float, default=300.0) parser.add_argument("--min-modbus-success-pct", type=float, default=99.9) parser.add_argument("--max-modbus-p99-ms", type=float, default=200.0) parser.add_argument("--max-frame-timeout-pct", type=float, default=5.0) parser.add_argument("--min-disk-free-mb", type=float, default=1024.0) parser.add_argument("--max-temp-c", type=float, default=85.0) parser.add_argument("--min-available-mb", type=float, default=128.0) parser.add_argument("--max-warn-per-hour", type=float, default=60.0) parser.add_argument("--report-every", type=int, default=10, help="每 N 个样本刷新 latest.md(默认 10)") parser.add_argument("--fsync-every", type=int, default=10, help="每 N 行 fsync 一次 samples.csv(默认 10;0 = 每行)") parser.add_argument("--max-log-mb", type=float, default=64.0, help="stdout 日志单文件上限 MB(默认 64;0 = 不轮转)") parser.add_argument("--log-backups", type=int, default=4) parser.add_argument("--strict", action="store_true", help="WARN 也返回退出码 1") parser.add_argument("--json", action="store_true", help="结束时把报告 JSON 打到 stdout") parser.add_argument("--analyze-only", default=None, metavar="DIR", help="只复算已有 campaign,不启动/监测进程") parser.add_argument("cmd", nargs=argparse.REMAINDER, help="`-- 被测程序 参数...`") return parser.parse_args(argv) def _duration_from_args(args) -> float: if args.duration is not None and args.days is not None: raise ValueError("--duration 与 --days 只能给一个") if args.duration is not None: return parse_duration(args.duration) if args.days is not None: if args.days <= 0: raise ValueError("--days 必须 > 0") return float(args.days) * 86400.0 return DEFAULT_DURATION_S def _analyze_only(args, duration_s: float) -> int: campaign = Campaign(args.analyze_only) meta = campaign.load_meta() rows = campaign.load_rows() events = campaign.load_events() if not meta and not rows: print("目录里没有 campaign.json / samples.csv: %s" % campaign.dir, file=sys.stderr) return 2 if meta.get("duration_s"): duration_s = max(duration_s, float(meta["duration_s"])) criteria = build_criteria(args, duration_s) analysis = analyze_rows(rows, events, criteria) cmd_text = redact(str(meta.get("cmd_text") or redact_cmd(meta.get("cmd") or []))) or "—" campaign.write_text(campaign.report_md, render_report(campaign, meta, analysis, events, cmd_text, rows=rows)) campaign.write_json(campaign.report_json, { "meta": redacted_meta(meta), "analysis": analysis, "events": redacted_events(events), "generated": _dt.datetime.now().astimezone().isoformat(timespec="seconds"), }) print("复算结论: %s" % analysis["verdict"]) for item in analysis["failures"]: print(" FAIL: %s" % item) for item in analysis["warnings"]: print(" WARN: %s" % item) print("报告: %s" % campaign.report_md) if args.json: print(json.dumps(analysis, ensure_ascii=False, indent=2, default=str)) failed = analysis["verdict"] == "FAIL" if args.strict and analysis["warnings"]: failed = True return 1 if failed else 0 def main(argv=None) -> int: args = parse_args(argv) try: duration_s = _duration_from_args(args) except ValueError as exc: print(str(exc), file=sys.stderr) return 2 if args.analyze_only: return _analyze_only(args, duration_s) if args.interval <= 0 or args.interval > 3600: print("--interval 必须在 (0, 3600] 秒", file=sys.stderr) return 2 if args.warmup < 0: print("--warmup 必须 >= 0", file=sys.stderr) return 2 if args.max_restarts < 0 or args.allow_restarts < 0: print("--max-restarts / --allow-restarts 必须 >= 0", file=sys.stderr) return 2 if args.report_every < 1 or args.fsync_every < 0: print("--report-every 必须 >= 1,--fsync-every 必须 >= 0", file=sys.stderr) return 2 if args.max_log_mb < 0: print("--max-log-mb 必须 >= 0", file=sys.stderr) return 2 if args.modbus_host and not (0 < args.modbus_port <= 65535): print("--modbus-port 非法: %d" % args.modbus_port, file=sys.stderr) return 2 if args.modbus_addr < 0 or args.modbus_addr + 12 > 65536: print("--modbus-addr 非法: %d(12 字结果区越界)" % args.modbus_addr, file=sys.stderr) return 2 cmd = list(args.cmd) if cmd and cmd[0] == "--": cmd = cmd[1:] target_count = sum(bool(x) for x in (args.pid, args.pid_file, args.process_name)) if target_count + (1 if cmd else 0) != 1: print("被测目标必须且只能选一个:--pid / --pid-file / --process-name / `-- cmd ...`", file=sys.stderr) return 2 if args.campaign: campaign = Campaign(args.campaign) else: stamp = _dt.datetime.now().strftime("%Y%m%d_%H%M%S") campaign = Campaign(Path(args.outdir) / ("soak7_%s" % stamp)) rows = campaign.load_rows() events = campaign.load_events() existing_meta = campaign.load_meta() if (rows or events) and not existing_meta: print("campaign 目录已有 samples.csv/events.csv,但 campaign.json 缺失或损坏;" "无法证明目标/配置一致,拒绝续跑", file=sys.stderr) return 2 target_mode = ("child" if cmd else "process-name" if args.process_name else "pid-file" if args.pid_file else "pid") target_text = (redact_cmd(cmd) if cmd else ( "process-name=%s" % args.process_name if args.process_name else "pid-file=%s" % args.pid_file if args.pid_file else "pid=%d" % args.pid)) modbus_cfg = { "host": args.modbus_host, "port": args.modbus_port, "unit": args.modbus_unit, "addr": args.modbus_addr, } meta = campaign.ensure_meta({ "schema": SCHEMA, "cmd": cmd, "cmd_text": target_text, "target_mode": target_mode, "interval_s": args.interval, "warmup_s": args.warmup, "duration_s": duration_s, "modbus": modbus_cfg, }) if meta.get("target_mode") and meta["target_mode"] != target_mode: print("campaign 的目标模式是 %s,本次是 %s;请换一个 campaign 目录" % (meta["target_mode"], target_mode), file=sys.stderr) return 2 old_cmd = meta.get("cmd") or [] if cmd and old_cmd and list(old_cmd) != cmd: print("campaign 里的被测命令与本次不一致,拒绝混写证据:\n 旧: %s\n 新: %s" % (redact_cmd(old_cmd), redact_cmd(cmd)), file=sys.stderr) return 2 # 旧 campaign 可能保存的是未脱敏的 cmd_text;比较前先脱敏,既兼容旧证据, # 也避免不一致提示把口令打到 stderr。 old_target_text = redact(str(meta.get("cmd_text") or "")) if old_target_text and old_target_text != target_text: print("campaign 的目标与本次不一致,拒绝混写证据:\n 旧: %s\n 新: %s" % (old_target_text, target_text), file=sys.stderr) return 2 if rows: try: saved_interval = (float(meta["interval_s"]) if meta.get("interval_s") is not None else None) except (TypeError, ValueError): saved_interval = None if saved_interval is not None and abs(saved_interval - float(args.interval)) > 1e-9: print("campaign 采样间隔是 %s s,本次是 %s s;请换一个 campaign 目录" % (saved_interval, args.interval), file=sys.stderr) return 2 try: saved_warmup = (float(meta["warmup_s"]) if meta.get("warmup_s") is not None else None) except (TypeError, ValueError): saved_warmup = None if saved_warmup is not None and abs(saved_warmup - float(args.warmup)) > 1e-9: print("campaign 预热期是 %s s,本次是 %s s;请换一个 campaign 目录" % (saved_warmup, args.warmup), file=sys.stderr) return 2 saved_modbus = meta.get("modbus") if saved_modbus and saved_modbus != modbus_cfg: print("campaign 的 Modbus 探活配置与本次不一致,拒绝混写证据", file=sys.stderr) return 2 meta["cmd"] = cmd or old_cmd meta["cmd_text"] = target_text meta["interval_s"] = args.interval meta["warmup_s"] = args.warmup meta["modbus"] = modbus_cfg meta["duration_s"] = max(duration_s, float(meta.get("duration_s") or 0.0)) duration_s = float(meta["duration_s"]) if not rows: meta["started_epoch"] = time.time() elif not meta.get("started_epoch"): first = rows[0] meta["started_epoch"] = float(first.get("epoch") or time.time()) - float(first.get("elapsed_s") or 0.0) start_epoch = float(meta["started_epoch"]) campaign.write_json(campaign.meta_path, meta) criteria = build_criteria(args, duration_s) logger = setup_logging(campaign) stats = LogStats() sampler = make_sampler() stop = {"flag": False} def _on_signal(signum, _frame): logger.warning("收到信号 %s,准备收尾", signum) stop["flag"] = True for sig in (getattr(signal, "SIGINT", None), getattr(signal, "SIGTERM", None)): if sig is not None: try: signal.signal(sig, _on_signal) except (OSError, ValueError): pass def current_elapsed() -> float: observed = max(0.0, time.time() - start_epoch) if rows: return max(observed, float(rows[-1]["elapsed_s"])) return observed def add_event(name: str, detail: str = "") -> None: event = campaign.append_event(current_elapsed(), name, detail) events.append(event) logger.info("event %-16s %s", name, detail) ambiguous_pids = [] ambiguous_event_open = False def resolve_external() -> int: nonlocal ambiguous_event_open if args.process_name: pids = sorted(find_pids_by_name(args.process_name)) if len(pids) > 1: ambiguous_pids[:] = pids if not ambiguous_event_open: add_event("TARGET_AMBIGUOUS", "process-name=%s 匹配多个 PID: %s" % (args.process_name, pids)) ambiguous_event_open = True return 0 ambiguous_pids[:] = [] ambiguous_event_open = False return pids[0] if pids else 0 if args.pid_file: return read_pid_file(args.pid_file) return int(args.pid or 0) child = None launch_count = 0 run_ids = [int(r["run_id"]) for r in rows if r.get("run_id") is not None] run_id = max(run_ids) if run_ids else 0 if not cmd and not run_ids: run_id = 1 if cmd and run_ids: run_id = max(run_ids) # launch() 会先 +1 pid = 0 target_dead = False lost_since = None last_progress_values = {} last_progress_elapsed = current_elapsed() stall_event_open = False probe_fail_streak = 0 probe_event_open = False last_fatal_count = 0 last_timeout_count = 0 session_started = time.time() def launch() -> bool: nonlocal child, run_id, launch_count, target_dead run_id += 1 try: child = ChildProcess( cmd, campaign.dir, run_id, stats, int(args.max_log_mb * 1024 * 1024), args.log_backups, ) child.start() except Exception as exc: # noqa: BLE001 - 启动失败要落事件,不能静默 child = None target_dead = True add_event("START_FAILED", "%s: %s" % (type(exc).__name__, exc)) return False launch_count += 1 add_event("START", "run=%d pid=%d cmd=%s" % (run_id, child.pid, redact_cmd(cmd))) return True def handle_child_exit() -> None: nonlocal child, target_dead assert child is not None rc = child.poll() add_event("EXIT", "run=%d pid=%d rc=%s" % (child.run_id, child.pid, rc)) child.stop(timeout=args.kill_timeout) child = None if stop["flag"]: target_dead = True return if args.restart == "never": target_dead = True return if args.restart == "on-failure" and rc == 0: target_dead = True return if launch_count - 1 >= args.max_restarts: add_event("RESTART_DENIED", "已达到硬上限 %d" % args.max_restarts) target_dead = True return delay = min(300.0, max(0.0, args.restart_backoff) * (2 ** max(0, launch_count - 2))) add_event("RESTART", "%.1f s 后第 %d 次重新拉起" % (delay, launch_count)) deadline = time.monotonic() + delay while time.monotonic() < deadline and not stop["flag"]: time.sleep(0.2) if stop["flag"] or not launch(): target_dead = True def refresh_external() -> bool: nonlocal pid, run_id, target_dead, lost_since if process_alive(sampler, pid): lost_since = None return True if lost_since is None: lost_since = time.time() add_event("TARGET_LOST", "pid=%d 暂时不可打开" % pid) if args.pid: if time.time() - lost_since >= args.reattach_timeout: target_dead = True add_event("TARGET_LOST_FINAL", "固定 PID=%d 已退出" % pid) return False new_pid = resolve_external() if new_pid and new_pid != pid and process_alive(sampler, new_pid): old_pid = pid pid = int(new_pid) run_id += 1 lost_since = None add_event("REATTACH", "pid %d → %d" % (old_pid, pid)) return True if time.time() - lost_since >= args.reattach_timeout: target_dead = True add_event("TARGET_LOST_FINAL", "等待 %.0f s 仍未重新发现进程" % args.reattach_timeout) return False if rows: add_event("RESUME", "已有 %d 个样本,从 t=%.1fs 继续;目标 %.2fh" % (len(rows), float(rows[-1]["elapsed_s"]), duration_s / 3600.0)) else: add_event("CAMPAIGN_START", "target=%s interval=%.1fs warmup=%.0fs" % (meta.get("cmd_text", "—"), args.interval, args.warmup)) if cmd: if not launch(): return 2 pid = child.pid else: pid = resolve_external() if not pid: if ambiguous_pids: print("进程名 %s 匹配到多个 PID %s;请先确认只有一个实例" % (args.process_name, ambiguous_pids), file=sys.stderr) else: print("找不到被测进程(--process-name / --pid-file / --pid)", file=sys.stderr) return 2 previous_pid = last_known_pid(rows) if previous_pid and previous_pid != pid: # 监测器停机期间 systemd 可能已重启目标;沿用旧 run_id 会把重启藏掉。 run_id += 1 add_event("REATTACH", "pid %d → %d(监测器重启期间目标已更换)" % (previous_pid, pid)) add_event("ATTACH", "pid=%d log=%s" % (pid, args.log_file or "—")) tail = None if not cmd and args.log_file: tail_path = Path(args.log_file) try: stat = tail_path.stat() tail = {"path": tail_path, "offset": stat.st_size, "inode": stat.st_ino} except OSError: tail = {"path": tail_path, "offset": 0, "inode": None} next_sample = time.monotonic() try: while not stop["flag"]: elapsed = current_elapsed() if elapsed >= duration_s: break if cmd and child is not None and child.poll() is not None: handle_child_exit() if target_dead: break pid = child.pid if not cmd and not target_dead: if not refresh_external(): if target_dead: break if time.monotonic() >= next_sample: sample_elapsed = current_elapsed() if cmd and child is not None: pid = child.pid # attach 模式:先把上次采样以来的日志喂给 LogStats,再采样本, # 否则 frames/heartbeat 会永远慢一个 interval。 if tail is not None: try: stat = tail["path"].stat() if (tail["inode"] is not None and (stat.st_ino != tail["inode"] or stat.st_size < tail["offset"])): tail["offset"] = 0 tail["inode"] = stat.st_ino if stat.st_size > tail["offset"]: with open(tail["path"], "rb") as fh: fh.seek(tail["offset"]) blob = fh.read(8 * 1024 * 1024) tail["offset"] = fh.tell() stats.feed(blob.decode("utf-8", "replace")) except OSError: pass try: row = sample_row(sampler, pid, run_id, stats, rows[-1] if rows else None, args, sample_elapsed, campaign) except Exception as exc: # noqa: BLE001 - 采样异常必须留证据 logger.exception("采样失败") add_event("SAMPLE_ERROR", "%s: %s" % (type(exc).__name__, exc)) target_dead = True break campaign.append_sample(row, args.fsync_every) rows.append(row) snap = stats.snapshot() if len(snap["fatal"]) > last_fatal_count: last_fatal_count = len(snap["fatal"]) add_event("FATAL", snap["fatal"][-1]) if snap["frame_timeout_lines"] > last_timeout_count: last_timeout_count = snap["frame_timeout_lines"] add_event("FRAME_TIMEOUT", "日志累计 %d 条" % snap["frame_timeout_lines"]) if args.modbus_host: if row.get("modbus_ok") == 0: probe_fail_streak += 1 if probe_fail_streak >= 3 and not probe_event_open: add_event("PROBE_FAIL", "连续 3 次失败:%s" % (row.get("modbus_error") or "—")) probe_event_open = True else: if probe_event_open: add_event("PROBE_RECOVER", "探活恢复") probe_event_open = False probe_fail_streak = 0 progress_pairs = [ (name, int(value)) for name, value in (("frames", row.get("frames")), ("heartbeat", row.get("modbus_heartbeat"))) if value is not None ] if progress_pairs: changed = any(last_progress_values.get(name) != value for name, value in progress_pairs) for name, value in progress_pairs: last_progress_values[name] = value if changed: last_progress_elapsed = sample_elapsed stall_event_open = False elif (sample_elapsed - last_progress_elapsed > args.max_frame_stall_s and not stall_event_open): add_event("STALL", "进度 %.0f s 未变化(%s)" % (sample_elapsed - last_progress_elapsed, ", ".join("%s=%d" % item for item in progress_pairs))) stall_event_open = True if len(rows) % args.report_every == 0: current_run_ids = sorted({int(r["run_id"]) for r in rows if r.get("run_id") is not None}) restarts_now = (max(current_run_ids) - min(current_run_ids) if current_run_ids else 0) window_points = max(3, int(min(3600.0, max(60.0, args.interval * 60.0)) / args.interval) + 1) campaign.write_text(campaign.latest_path, render_latest( meta, row, rows[-window_points:], restarts_now, criteria, session_started, )) # Linux 上每小时留一份 fd 类型快照,句柄涨了可直接回溯(不覆盖报告) if (os.name != "nt" and pid and len(rows) % max(1, int(3600.0 / args.interval)) == 0): try: campaign.write_json(campaign.fd_path, { "wall": row.get("wall"), "pid": pid, "counts": fd_summary(pid), }) except OSError: pass logger.info( "t=%7.1fs run=%d pid=%s alive=%d rss=%s handles=%s threads=%s " "cpu=%s frames=%s fps=%s modbus=%s/%s", row["elapsed_s"], row["run_id"], _fmt(row.get("pid"), 0), int(row.get("alive") or 0), _fmt(row.get("rss_mb"), 2), _fmt(row.get("handles"), 0), _fmt(row.get("threads"), 0), _fmt(row.get("cpu_pct"), 1, "%"), _fmt(row.get("frames"), 0), _fmt((row.get("fps_x10") or 0) / 10.0, 1), "ok" if row.get("modbus_ok") == 1 else "fail", _fmt(row.get("modbus_rtt_ms"), 1, "ms"), ) next_sample += max(0.5, args.interval) if next_sample < time.monotonic() - args.interval: next_sample = time.monotonic() + args.interval time.sleep(0.2) except KeyboardInterrupt: stop["flag"] = True logger.warning("KeyboardInterrupt,准备收尾") finally: # 收尾前再采一个点:既记录最终状态,也让"刚好到时长"有闭环证据 try: final_elapsed = min(duration_s, max( current_elapsed(), float(rows[-1]["elapsed_s"]) if rows else 0.0, )) if (not rows or final_elapsed - float(rows[-1]["elapsed_s"]) >= min(1.0, args.interval * 0.2)): row = sample_row(sampler, pid, run_id, stats, rows[-1] if rows else None, args, final_elapsed, campaign) campaign.append_sample(row, args.fsync_every) rows.append(row) except Exception: # noqa: BLE001 logger.exception("最终采样失败") if pid and os.name != "nt": try: campaign.write_json(campaign.fd_path, { "pid": pid, "counts": fd_summary(pid), }) except OSError: pass if child is not None: add_event("STOP", "收尾,run=%d pid=%d" % (child.run_id, child.pid)) child.stop(timeout=args.kill_timeout) child = None stats.flush() if not cmd: add_event("DETACH", "监测结束,未终止外部进程 pid=%d" % pid) analysis = analyze_rows(rows, events, criteria) cmd_text = redact(str(meta.get("cmd_text") or redact_cmd(meta.get("cmd") or []))) or "—" report = render_report(campaign, meta, analysis, events, cmd_text, rows=rows) campaign.write_text(campaign.report_md, report) campaign.write_json(campaign.report_json, { "meta": redacted_meta(meta), "analysis": analysis, "events": redacted_events(events), "generated": _dt.datetime.now().astimezone().isoformat(timespec="seconds"), }) if rows: current_run_ids = sorted({int(r["run_id"]) for r in rows if r.get("run_id") is not None}) restarts_now = (max(current_run_ids) - min(current_run_ids) if current_run_ids else 0) campaign.write_text(campaign.latest_path, render_latest( meta, rows[-1], rows[-min(len(rows), 121):], restarts_now, criteria, session_started, )) print("\n===== 7x24 浸泡验收结果 =====") print("campaign : %s" % campaign.dir) print("结论 : %s" % analysis["verdict"]) if analysis["failures"]: print("FAIL:") for item in analysis["failures"]: print(" - %s" % item) if analysis["warnings"]: print("WARN:") for item in analysis["warnings"]: print(" - %s" % item) print("报告 : %s" % campaign.report_md) print("原始 CSV : %s" % campaign.samples_path) print("事件 : %s" % campaign.events_path) if args.json: print(json.dumps({"meta": redacted_meta(meta), "analysis": analysis}, ensure_ascii=False, indent=2, default=str)) failed = analysis["verdict"] == "FAIL" if args.strict and analysis["warnings"]: failed = True return 1 if failed else 0 if __name__ == "__main__": try: raise SystemExit(main()) except SystemExit: raise except Exception: # 未捕获异常不能伪装成 exit 1:systemd 用 RestartPreventExitStatus=1 # 阻止验收 FAIL 被重跑,会把监测器崩溃也一起挡住。 traceback.print_exc() raise SystemExit(2)