run_visible.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. #!/usr/bin/env python3
  2. """Visible, cancellable subprocess runner with heartbeat and receipts.
  3. POSIX process groups: each task starts a new session (start_new_session).
  4. Timeouts / interrupts signal only that task's PGID via killpg — never pkill/killall.
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import json
  9. import os
  10. import signal
  11. import subprocess
  12. import sys
  13. import threading
  14. import time
  15. from datetime import datetime, timezone
  16. from pathlib import Path
  17. from typing import Any
  18. try:
  19. import psutil # type: ignore
  20. except ImportError: # pragma: no cover
  21. psutil = None
  22. # Keys that must never leak from a prior TD invocation into ordinary tasks.
  23. _TD_POLLUTE_KEYS = ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH")
  24. def _utc_now() -> str:
  25. return datetime.now(timezone.utc).isoformat()
  26. def _atomic_write(path: Path, payload: dict[str, Any]) -> None:
  27. path.parent.mkdir(parents=True, exist_ok=True)
  28. tmp = path.with_suffix(path.suffix + ".tmp")
  29. tmp.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  30. tmp.replace(path)
  31. def _clean_env(extra: dict[str, str] | None = None, *, keep_td_libs: bool = False) -> dict[str, str]:
  32. clean = os.environ.copy()
  33. if not keep_td_libs:
  34. for key in _TD_POLLUTE_KEYS:
  35. clean.pop(key, None)
  36. if extra:
  37. clean.update(extra)
  38. return clean
  39. def _resource_snapshot(pid: int) -> dict[str, Any]:
  40. """Real process metrics only — never invent progress percentages."""
  41. if psutil is None:
  42. return {"cpu_percent": None, "rss_bytes": None, "children": None}
  43. try:
  44. proc = psutil.Process(pid)
  45. children = proc.children(recursive=True)
  46. rss = proc.memory_info().rss + sum(c.memory_info().rss for c in children)
  47. # interval=None returns rate since last call (or 0.0 on first sample).
  48. cpu = proc.cpu_percent(interval=None) + sum(c.cpu_percent(interval=None) for c in children)
  49. return {"cpu_percent": round(cpu, 1), "rss_bytes": rss, "children": len(children)}
  50. except Exception:
  51. return {"cpu_percent": None, "rss_bytes": None, "children": None}
  52. def _terminate_group(pgid: int | None) -> None:
  53. """Kill only the given process group. Never use pkill/killall."""
  54. if pgid is None:
  55. return
  56. try:
  57. os.killpg(pgid, signal.SIGTERM)
  58. except ProcessLookupError:
  59. return
  60. deadline = time.monotonic() + 5.0
  61. while time.monotonic() < deadline:
  62. try:
  63. os.killpg(pgid, 0)
  64. except ProcessLookupError:
  65. return
  66. time.sleep(0.2)
  67. try:
  68. os.killpg(pgid, signal.SIGKILL)
  69. except ProcessLookupError:
  70. return
  71. def run_visible(
  72. command: list[str],
  73. *,
  74. cwd: Path | None = None,
  75. env: dict[str, str] | None = None,
  76. log_path: Path,
  77. status_path: Path,
  78. name: str = "task",
  79. heartbeat_s: float = 5.0,
  80. timeout_s: float | None = None,
  81. no_progress_s: float | None = None,
  82. keep_td_libs: bool = False,
  83. ) -> int:
  84. log_path.parent.mkdir(parents=True, exist_ok=True)
  85. status: dict[str, Any] = {
  86. "schema": "prod2u-run-visible-status-v1",
  87. "name": name,
  88. "command": command,
  89. "cwd": str(cwd or Path.cwd()),
  90. "state": "running",
  91. "started_at_utc": _utc_now(),
  92. "pid": None,
  93. "pgid": None,
  94. "exit_code": None,
  95. "log_path": str(log_path),
  96. "heartbeat": [],
  97. }
  98. _atomic_write(status_path, status)
  99. clean_env = _clean_env(env, keep_td_libs=keep_td_libs)
  100. with log_path.open("w", encoding="utf-8", errors="replace") as log_file:
  101. proc = subprocess.Popen(
  102. command,
  103. cwd=str(cwd) if cwd else None,
  104. env=clean_env,
  105. stdout=subprocess.PIPE,
  106. stderr=subprocess.STDOUT,
  107. text=True,
  108. bufsize=1,
  109. start_new_session=True, # new POSIX process group / session
  110. )
  111. status["pid"] = proc.pid
  112. try:
  113. status["pgid"] = os.getpgid(proc.pid)
  114. except Exception:
  115. status["pgid"] = proc.pid
  116. _atomic_write(status_path, status)
  117. # Prime CPU percent baseline so the first heartbeat is meaningful.
  118. _resource_snapshot(proc.pid)
  119. last_output = time.monotonic()
  120. last_heartbeat = time.monotonic()
  121. started = time.monotonic()
  122. last_log_bytes = 0
  123. def reader() -> None:
  124. nonlocal last_output
  125. assert proc.stdout is not None
  126. for line in proc.stdout:
  127. sys.stdout.write(line)
  128. sys.stdout.flush()
  129. log_file.write(line)
  130. log_file.flush()
  131. last_output = time.monotonic()
  132. thread = threading.Thread(target=reader, daemon=True)
  133. thread.start()
  134. try:
  135. while True:
  136. code = proc.poll()
  137. now = time.monotonic()
  138. if now - last_heartbeat >= heartbeat_s:
  139. resources = _resource_snapshot(proc.pid)
  140. log_size = log_path.stat().st_size if log_path.exists() else 0
  141. log_delta = log_size - last_log_bytes
  142. last_log_bytes = log_size
  143. beat = {
  144. "task": name,
  145. "elapsed_s": round(now - started, 1),
  146. "pid": status["pid"],
  147. "pgid": status["pgid"],
  148. "log_bytes": log_size,
  149. "log_growth_bytes": log_delta,
  150. "seconds_since_output": round(now - last_output, 1),
  151. **resources,
  152. }
  153. status["heartbeat"].append(beat)
  154. # Cap retained heartbeat history to keep status files small.
  155. if len(status["heartbeat"]) > 200:
  156. status["heartbeat"] = status["heartbeat"][-100:]
  157. status["last_heartbeat"] = beat
  158. _atomic_write(status_path, status)
  159. print(
  160. f"[heartbeat] task={name} elapsed={beat['elapsed_s']}s "
  161. f"pid={beat['pid']} pgid={beat['pgid']} "
  162. f"cpu={beat['cpu_percent']} rss={beat['rss_bytes']} "
  163. f"children={beat['children']} "
  164. f"log={log_size}B (+{log_delta}B) "
  165. f"quiet={beat['seconds_since_output']}s",
  166. flush=True,
  167. )
  168. last_heartbeat = now
  169. if code is not None:
  170. thread.join(timeout=2)
  171. status["state"] = "pass" if code == 0 else "fail"
  172. status["exit_code"] = code
  173. status["ended_at_utc"] = _utc_now()
  174. _atomic_write(status_path, status)
  175. return code
  176. if timeout_s is not None and (now - started) > timeout_s:
  177. status["state"] = "timeout"
  178. status["timeout_reason"] = "total_timeout"
  179. _terminate_group(status["pgid"])
  180. try:
  181. proc.wait(timeout=30)
  182. except subprocess.TimeoutExpired:
  183. _terminate_group(status["pgid"])
  184. proc.wait(timeout=10)
  185. status["exit_code"] = 124
  186. status["ended_at_utc"] = _utc_now()
  187. _atomic_write(status_path, status)
  188. return 124
  189. if no_progress_s is not None:
  190. resources = _resource_snapshot(proc.pid)
  191. quiet = (now - last_output) > no_progress_s
  192. idle_cpu = (resources.get("cpu_percent") or 0) < 1.0
  193. if quiet and idle_cpu:
  194. # Diagnostic only — do not kill solely for quiet logs.
  195. status["suspect_stall"] = True
  196. _atomic_write(status_path, status)
  197. time.sleep(0.2)
  198. except KeyboardInterrupt:
  199. status["state"] = "interrupted"
  200. _terminate_group(status["pgid"])
  201. try:
  202. proc.wait(timeout=30)
  203. except subprocess.TimeoutExpired:
  204. _terminate_group(status["pgid"])
  205. status["exit_code"] = proc.returncode
  206. status["ended_at_utc"] = _utc_now()
  207. _atomic_write(status_path, status)
  208. raise
  209. def main() -> int:
  210. parser = argparse.ArgumentParser(description=__doc__)
  211. parser.add_argument("--name", default="task")
  212. parser.add_argument("--cwd", type=Path, default=None)
  213. parser.add_argument("--log", type=Path, required=True)
  214. parser.add_argument("--status", type=Path, required=True)
  215. parser.add_argument("--timeout-s", type=float, default=None)
  216. parser.add_argument("--heartbeat-s", type=float, default=5.0)
  217. parser.add_argument(
  218. "--keep-td-libs",
  219. action="store_true",
  220. help="Keep LD_LIBRARY_PATH/QT vars (TD subprocess only).",
  221. )
  222. parser.add_argument("command", nargs=argparse.REMAINDER)
  223. args = parser.parse_args()
  224. command = args.command
  225. if command and command[0] == "--":
  226. command = command[1:]
  227. if not command:
  228. parser.error("command required after --")
  229. return run_visible(
  230. command,
  231. cwd=args.cwd,
  232. log_path=args.log,
  233. status_path=args.status,
  234. name=args.name,
  235. heartbeat_s=args.heartbeat_s,
  236. timeout_s=args.timeout_s,
  237. keep_td_libs=args.keep_td_libs,
  238. )
  239. if __name__ == "__main__":
  240. raise SystemExit(main())