#!/usr/bin/env python3 """Run a command with a wall-clock limit, then fail if it leaked runner processes. tools/guard.py [-t SECONDS] -- [args...] Kills the command's whole process group when it exceeds the limit (default 600 s). Afterwards, any process still matching the dsflow_tui runner or its bash helpers is reported and the guard exits non-zero: a leak is a finding. """ import argparse import os import signal import subprocess import sys import time LEAK_PATTERN = "_runjob|dsflow-tui" def leftovers(): out = subprocess.run(["pgrep", "-fl", LEAK_PATTERN], stdout=subprocess.PIPE, universal_newlines=True).stdout return [l for l in out.splitlines() if "guard.py" not in l] def main(): ap = argparse.ArgumentParser(description=__doc__.splitlines()[0]) ap.add_argument("-t", type=int, default=600, metavar="SECONDS") ap.add_argument("command", nargs=argparse.REMAINDER) args = ap.parse_args() cmd = args.command[1:] if args.command[:1] == ["--"] else args.command if not cmd: ap.error("no command given") p = subprocess.Popen(cmd, start_new_session=True) try: rc = p.wait(timeout=args.t) except subprocess.TimeoutExpired: os.killpg(p.pid, signal.SIGKILL) p.wait() print("guard: killed after %ds: %s" % (args.t, " ".join(cmd)), file=sys.stderr) rc = 124 time.sleep(1) # let detached runners finish their own cleanup leaked = leftovers() if leaked: print("guard: leftover processes (a finding - report the command):", file=sys.stderr) for line in leaked: print(" " + line, file=sys.stderr) return rc or 3 return rc if __name__ == "__main__": sys.exit(main())