"""Run the three default unit groups concurrently on the current runner. Usage: run-unit-groups.py PLAN_DIR EVIDENCE_DIR TMP_DIR RECORDER [RECORDER_ARG ...] The recorder accepts OUTPUT followed by go-test flags and packages. Each group owns its logs/events; they are combined only after all group processes exit. """ from contextlib import ExitStack import json import os from pathlib import Path import signal import subprocess import sys import time def stop(_signum, _frame): raise KeyboardInterrupt def terminate(processes): for process in processes: try: if os.name == "posix": os.killpg(process.pid, signal.SIGTERM) elif process.poll() is None: process.terminate() except ProcessLookupError: pass if os.name == "posix": # The leader may exit on TERM while its descendants remain in the group. # Bound the grace period by group lifetime, never by leader lifetime. deadline = time.monotonic() + 5 remaining = list(processes) while remaining and time.monotonic() < deadline: alive = [] for process in remaining: process.poll() # Reap an exited leader without forgetting its PGID. try: os.killpg(process.pid, 0) alive.append(process) except ProcessLookupError: pass remaining = alive if remaining: time.sleep(.05) for process in remaining: try: os.killpg(process.pid, signal.SIGKILL) except ProcessLookupError: pass for process in processes: try: process.wait(timeout=5) except subprocess.TimeoutExpired: process.kill() process.wait(timeout=5) def run(plan, evidence, temp, recorder): groups = {g: (plan / (g + ".txt")).read_text().splitlines() for g in ("g1", "g2", "g3")} evidence.mkdir(parents=True, exist_ok=True) started = time.monotonic() processes, results, times = {}, {}, {} with ExitStack() as files: try: for group, packages in groups.items(): results[group] = {"packages": len(packages), "status": 0, "elapsed_seconds": 0} if not packages: print(f"{group}: no packages selected by scope", flush=True) continue out = evidence / group; out.mkdir(parents=True, exist_ok=True) scratch = temp / group; scratch.mkdir(parents=True, exist_ok=True) # /proc/self/fd exposes resolved paths; preserve fixture identity even # when the runner temp directory is a symlink to its data disk. scratch = scratch.resolve(strict=True) log = files.enter_context((out / "console.log").open("w", encoding="utf-8")) command = recorder + [str(out / "go-test.json"), "-p=" + ("4" if group == "g3" else "1"), "-short", "-count=1", "-timeout", "20m", *packages] times[group] = time.monotonic() processes[group] = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, env=dict(os.environ, TMPDIR=str(scratch)), start_new_session=os.name == "posix") print(f"{group}: started {len(packages)} packages", flush=True) remaining = set(processes) while remaining: for group in tuple(remaining): status = processes[group].poll() if status is not None: results[group]["status"] = status results[group]["elapsed_seconds"] = round(time.monotonic() - times[group], 3) remaining.remove(group) if remaining: time.sleep(.05) except BaseException: signal.signal(signal.SIGTERM, signal.SIG_IGN) signal.signal(signal.SIGINT, signal.SIG_IGN) terminate(processes.values()) raise for group in processes: print(f"--- {group} ---", flush=True) print((evidence / group / "console.log").read_text(errors="replace"), flush=True) summary = {"elapsed_seconds": round(time.monotonic() - started, 3), "groups": results} try: (evidence / "unit-groups.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8") with (evidence / "go-test.json").open("ab") as combined: for group in processes: events = evidence / group / "go-test.json" if events.exists(): combined.write(events.read_bytes()) except OSError as error: print(f"test evidence unavailable: {error}", file=sys.stderr) print(json.dumps(summary), flush=True) return int(any(r["status"] != 0 for r in results.values())) def main(argv): if len(argv) < 5: print(__doc__.strip(), file=sys.stderr) return 2 signal.signal(signal.SIGTERM, stop) try: return run(Path(argv[1]), Path(argv[2]), Path(argv[3]), argv[4:]) except KeyboardInterrupt: return 130 except (OSError, ValueError) as error: print(f"unit groups: {error}", file=sys.stderr) return 2 if __name__ == "__main__": sys.exit(main(sys.argv))