run_visible.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. #!/usr/bin/env python3
  2. """Visible, cancellable subprocess runner with heartbeat and receipts."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import os
  7. import signal
  8. import subprocess
  9. import sys
  10. import threading
  11. import time
  12. from datetime import datetime, timezone
  13. from pathlib import Path
  14. from typing import Any
  15. try:
  16. import psutil # type: ignore
  17. except ImportError: # pragma: no cover
  18. psutil = None
  19. def _utc_now() -> str:
  20. return datetime.now(timezone.utc).isoformat()
  21. def _atomic_write(path: Path, payload: dict[str, Any]) -> None:
  22. path.parent.mkdir(parents=True, exist_ok=True)
  23. tmp = path.with_suffix(path.suffix + ".tmp")
  24. tmp.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
  25. tmp.replace(path)
  26. def _resource_snapshot(pid: int) -> dict[str, Any]:
  27. if psutil is None:
  28. return {"cpu_percent": None, "rss_bytes": None, "children": None}
  29. try:
  30. proc = psutil.Process(pid)
  31. children = proc.children(recursive=True)
  32. rss = proc.memory_info().rss + sum(c.memory_info().rss for c in children)
  33. cpu = proc.cpu_percent(interval=None) + sum(c.cpu_percent(interval=None) for c in children)
  34. return {"cpu_percent": cpu, "rss_bytes": rss, "children": len(children)}
  35. except Exception:
  36. return {"cpu_percent": None, "rss_bytes": None, "children": None}
  37. def run_visible(
  38. command: list[str],
  39. *,
  40. cwd: Path | None = None,
  41. env: dict[str, str] | None = None,
  42. log_path: Path,
  43. status_path: Path,
  44. name: str = "task",
  45. heartbeat_s: float = 8.0,
  46. timeout_s: float | None = None,
  47. no_progress_s: float | None = None,
  48. ) -> int:
  49. log_path.parent.mkdir(parents=True, exist_ok=True)
  50. status: dict[str, Any] = {
  51. "schema": "prod2u-run-visible-status-v1",
  52. "name": name,
  53. "command": command,
  54. "cwd": str(cwd or Path.cwd()),
  55. "state": "running",
  56. "started_at_utc": _utc_now(),
  57. "pid": None,
  58. "pgid": None,
  59. "exit_code": None,
  60. "log_path": str(log_path),
  61. "heartbeat": [],
  62. }
  63. _atomic_write(status_path, status)
  64. clean_env = os.environ.copy()
  65. if env:
  66. clean_env.update(env)
  67. with log_path.open("w", encoding="utf-8", errors="replace") as log_file:
  68. proc = subprocess.Popen(
  69. command,
  70. cwd=str(cwd) if cwd else None,
  71. env=clean_env,
  72. stdout=subprocess.PIPE,
  73. stderr=subprocess.STDOUT,
  74. text=True,
  75. bufsize=1,
  76. start_new_session=True,
  77. )
  78. status["pid"] = proc.pid
  79. try:
  80. status["pgid"] = os.getpgid(proc.pid)
  81. except Exception:
  82. status["pgid"] = proc.pid
  83. _atomic_write(status_path, status)
  84. last_output = time.monotonic()
  85. last_heartbeat = time.monotonic()
  86. started = time.monotonic()
  87. stop_reader = threading.Event()
  88. def reader() -> None:
  89. nonlocal last_output
  90. assert proc.stdout is not None
  91. for line in proc.stdout:
  92. sys.stdout.write(line)
  93. sys.stdout.flush()
  94. log_file.write(line)
  95. log_file.flush()
  96. last_output = time.monotonic()
  97. thread = threading.Thread(target=reader, daemon=True)
  98. thread.start()
  99. try:
  100. while True:
  101. code = proc.poll()
  102. now = time.monotonic()
  103. if now - last_heartbeat >= heartbeat_s:
  104. resources = _resource_snapshot(proc.pid)
  105. log_size = log_path.stat().st_size if log_path.exists() else 0
  106. beat = {
  107. "elapsed_s": round(now - started, 1),
  108. "log_bytes": log_size,
  109. "seconds_since_output": round(now - last_output, 1),
  110. **resources,
  111. }
  112. status["heartbeat"].append(beat)
  113. status["last_heartbeat"] = beat
  114. _atomic_write(status_path, status)
  115. print(
  116. f"[heartbeat] {name} elapsed={beat['elapsed_s']}s "
  117. f"cpu={beat['cpu_percent']} rss={beat['rss_bytes']} "
  118. f"children={beat['children']} log={log_size}B "
  119. f"quiet={beat['seconds_since_output']}s",
  120. flush=True,
  121. )
  122. last_heartbeat = now
  123. if code is not None:
  124. thread.join(timeout=2)
  125. status["state"] = "pass" if code == 0 else "fail"
  126. status["exit_code"] = code
  127. status["ended_at_utc"] = _utc_now()
  128. _atomic_write(status_path, status)
  129. return code
  130. if timeout_s is not None and (now - started) > timeout_s:
  131. status["state"] = "timeout"
  132. status["timeout_reason"] = "total_timeout"
  133. _terminate_group(status["pgid"])
  134. proc.wait(timeout=30)
  135. status["exit_code"] = proc.returncode
  136. status["ended_at_utc"] = _utc_now()
  137. _atomic_write(status_path, status)
  138. return status["exit_code"] or 124
  139. if no_progress_s is not None:
  140. resources = _resource_snapshot(proc.pid)
  141. quiet = (now - last_output) > no_progress_s
  142. idle_cpu = (resources.get("cpu_percent") or 0) < 1.0
  143. if quiet and idle_cpu:
  144. # Diagnostic only — do not kill solely for quiet logs if CPU active.
  145. status["suspect_stall"] = True
  146. _atomic_write(status_path, status)
  147. time.sleep(0.2)
  148. except KeyboardInterrupt:
  149. status["state"] = "interrupted"
  150. _terminate_group(status["pgid"])
  151. proc.wait(timeout=30)
  152. status["exit_code"] = proc.returncode
  153. status["ended_at_utc"] = _utc_now()
  154. _atomic_write(status_path, status)
  155. raise
  156. finally:
  157. stop_reader.set()
  158. def _terminate_group(pgid: int | None) -> None:
  159. if pgid is None:
  160. return
  161. try:
  162. os.killpg(pgid, signal.SIGTERM)
  163. except ProcessLookupError:
  164. return
  165. time.sleep(5)
  166. try:
  167. os.killpg(pgid, signal.SIGKILL)
  168. except ProcessLookupError:
  169. return
  170. def main() -> int:
  171. parser = argparse.ArgumentParser(description=__doc__)
  172. parser.add_argument("--name", default="task")
  173. parser.add_argument("--cwd", type=Path, default=None)
  174. parser.add_argument("--log", type=Path, required=True)
  175. parser.add_argument("--status", type=Path, required=True)
  176. parser.add_argument("--timeout-s", type=float, default=None)
  177. parser.add_argument("--heartbeat-s", type=float, default=8.0)
  178. parser.add_argument("command", nargs=argparse.REMAINDER)
  179. args = parser.parse_args()
  180. command = args.command
  181. if command and command[0] == "--":
  182. command = command[1:]
  183. if not command:
  184. parser.error("command required after --")
  185. return run_visible(
  186. command,
  187. cwd=args.cwd,
  188. log_path=args.log,
  189. status_path=args.status,
  190. name=args.name,
  191. heartbeat_s=args.heartbeat_s,
  192. timeout_s=args.timeout_s,
  193. )
  194. if __name__ == "__main__":
  195. raise SystemExit(main())