#!/usr/bin/env python3 """Linux process-group supervisor; clean up only this command's adopted descendants.""" import argparse import ctypes import os import signal import subprocess import time from contextlib import suppress from pathlib import Path from runtime_common import critical_log_lines, write_json def owned_processes(pgid): rows = [] for path in Path("/proc").glob("[0-9]*/stat"): try: text = path.read_text() fields = text.rsplit(") ", 1)[1].split() if int(fields[2]) == pgid or int(fields[1]) == os.getpid(): rows.append( { "pid": int(path.parent.name), "state": fields[0], "pgid": int(fields[2]), "name": text.split("(", 1)[1].rsplit(")", 1)[0], } ) except (FileNotFoundError, ProcessLookupError): pass return rows def cleanup(pgid): before = owned_processes(pgid) for sig in (signal.SIGTERM, signal.SIGKILL): for row in owned_processes(pgid): if row["state"] != "Z": with suppress(ProcessLookupError): os.kill(row["pid"], sig) for _ in range(30): try: while os.waitpid(-1, os.WNOHANG)[0]: pass except ChildProcessError: pass if not owned_processes(pgid): return {"before": before, "remaining": [], "clean": True} time.sleep(0.1) remaining = owned_processes(pgid) return {"before": before, "remaining": remaining, "clean": not remaining} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--log", type=Path, required=True) parser.add_argument("--report", type=Path, required=True) parser.add_argument("--timeout", type=float, default=420) parser.add_argument("command", nargs=argparse.REMAINDER) args = parser.parse_args() command = args.command[1:] if args.command[:1] == ["--"] else args.command if not command or args.timeout <= 0 or args.log.exists() or args.report.exists(): parser.error("Require command, positive timeout and unused log/report paths") if ctypes.CDLL(None, use_errno=True).prctl(36, 1, 0, 0, 0) != 0: raise RuntimeError("Linux subreaper setup failed") args.log.parent.mkdir(parents=True, exist_ok=True) info = {"passed": False, "status": "running", "command": command} write_json(args.report, info) start = time.monotonic() with args.log.open("x") as stream: child = subprocess.Popen(command, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True) info["pid"] = child.pid try: child.wait(timeout=args.timeout) except BaseException as error: info["error"] = repr(error) os.killpg(child.pid, signal.SIGTERM) try: child.wait(timeout=10) except subprocess.TimeoutExpired: os.killpg(child.pid, signal.SIGKILL) child.wait() finally: info["cleanup"] = cleanup(child.pid) info["returncode"] = child.returncode info["wall_seconds"] = time.monotonic() - start info["critical_log_lines"] = critical_log_lines(args.log) info["passed"] = ( child.returncode == 0 and info["cleanup"]["clean"] and "error" not in info and not info["critical_log_lines"] ) info["status"] = "completed" if info["passed"] else "failed" write_json(args.report, info) print(info) raise SystemExit(0 if info["passed"] else 1) if __name__ == "__main__": main()