#!/usr/bin/env python3 """Linux-only E2E lifecycle owner, independent of make's signal disposition. The detached watcher outlives a killed launcher/make, acts as child subreaper, then terminates and reaps the whole descendant tree before removing its workspace. Never scans/kills by executable name and never removes shared caches. """ import ctypes import json import os import math import re from pathlib import Path import select import shutil import signal import subprocess import sys import tempfile import time PR_SET_CHILD_SUBREAPER = 36 PR_SET_PDEATHSIG = 1 def process(pid): """Identity includes start ticks to avoid acting on a recycled PID.""" try: fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split() return int(fields[1]), fields[19], fields[0] # ppid, starttime, state except (OSError, ValueError, IndexError): return None def same_process(pid, identity): current = process(pid) return current is not None and current[1] == identity[1] and current[2] != "Z" def descendants(root): records = {} for item in Path("/proc").iterdir(): if item.name.isdigit(): identity = process(int(item.name)) if identity is not None: records[int(item.name)] = identity owned = {root} while True: found = {pid for pid, identity in records.items() if identity[0] in owned} if found <= owned: break owned |= found return {pid: records[pid] for pid in owned if pid != root and pid in records} def direct_children(root): # Unlike a cross-process ancestry scan, these lists come from the kernel's # actual child ownership. Include every thread, not just the group leader. records = {} for entry in Path(f"/proc/{root}/task").glob("*/children"): for value in entry.read_text().split(): pid = int(value) identity = process(pid) if identity is not None and identity[0] == root: records[pid] = identity return records def reap(): """Return True while the kernel still owns a live child, False on ECHILD.""" while True: try: pid, _ = os.waitpid(-1, os.WNOHANG) if pid == 0: return True except ChildProcessError: return False def stop_tree(worker): root = os.getpid() known = {} identity = process(worker.pid) if identity is not None: known[worker.pid] = identity signalled = set() grace = time.monotonic() + 1.5 deadline = grace + 3 empty_confirmations = 0 while time.monotonic() < deadline: # Never forget previously observed live identities when an ancestry # snapshot temporarily loses a parent during exit/adoption. known.update(descendants(root)) known.update(direct_children(root)) force = time.monotonic() >= grace for pid, identity in known.items(): if same_process(pid, identity): key = (pid, identity[1]) if force or key not in signalled: try: os.kill(pid, signal.SIGKILL if force else signal.SIGTERM) signalled.add(key) except ProcessLookupError: pass worker.poll() has_children = reap() alive = any(same_process(pid, identity) for pid, identity in known.items()) if not has_children and not alive: empty_confirmations += 1 if empty_confirmations >= 2: return else: empty_confirmations = 0 time.sleep(0.03) raise RuntimeError("E2E kernel-owned descendants failed to terminate; workspace retained") def timeout_duration(arguments): """Read a GNU timeout soft duration; never extend an enclosing deadline.""" position = 1 while position < len(arguments): value = arguments[position] if value == "--": position += 1 break if value in ("-k", "--kill-after", "-s", "--signal"): position += 2 elif value in ("--foreground", "--preserve-status", "--verbose", "-v") or value.startswith(("--signal=", "--kill-after=")): position += 1 elif value.startswith("-"): return None else: break if position >= len(arguments): return None match = re.fullmatch(r"([0-9]+(?:\.[0-9]+)?)([smhd]?)", arguments[position]) if not match: return None duration = float(match[1]) * {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}[match[2]] return duration if duration > 0 and math.isfinite(duration) else None def enclosing_deadline(pid): deadlines = [] for _ in range(64): identity = process(pid) if identity is None: break try: executable = Path(os.readlink(f"/proc/{pid}/exe")).name if executable == "timeout": arguments = Path(f"/proc/{pid}/cmdline").read_bytes().decode().strip("\0").split("\0") duration = timeout_duration(arguments) if duration is not None: boot_now = time.clock_gettime(time.CLOCK_BOOTTIME) started = int(identity[1]) / os.sysconf("SC_CLK_TCK") remaining = max(0, duration - (boot_now - started)) deadlines.append(time.monotonic() + remaining) except (OSError, ValueError): pass if identity[0] <= 0 or identity[0] == pid: break pid = identity[0] return min(deadlines) if deadlines else None def watcher(project, owner_pid, owner_start, life_fd, deadline=None): libc = ctypes.CDLL(None, use_errno=True) if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0: raise OSError(ctypes.get_errno(), "E2E subreaper setup failed") interrupted = [] for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(sig, lambda received, _frame: interrupted.append(received)) base = os.environ.get("TMPDIR") or os.environ.get("IDEA_MANAGED_TMP") or "/tmp" work = Path(tempfile.mkdtemp(prefix="tradarr-e2e.", dir=base)) worker = None expected_parent = os.getpid() def parent_death_guard(): if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0: os._exit(125) if os.getppid() != expected_parent: os._exit(125) try: env = dict(os.environ, TRADARR_E2E_RUN_DIR=str(work)) worker = subprocess.Popen( ["bash", str(project / "backend/scripts/test-e2e-worker.sh")], cwd=project, env=env, start_new_session=True, preexec_fn=parent_death_guard, ) # Diagnostic process identities only; never credentials or DSNs. (work / "supervisor.json").write_text(json.dumps({ "watcher": os.getpid(), "worker": worker.pid, "owner": owner_pid, })) while True: result = worker.poll() if result is not None: return result if result >= 0 else 128 - result ready, _, _ = select.select([life_fd], [], [], 0.05) alive = process(owner_pid) if (deadline is not None and time.monotonic() >= deadline) or interrupted or alive is None or alive[1] != owner_start or alive[2] == "Z": return 130 if ready and os.read(life_fd, 1) == b"": return 130 finally: if worker is not None: stop_tree(worker) shutil.rmtree(work) os.close(life_fd) def launch(project): if sys.platform != "linux" or not Path("/proc/self/stat").exists(): raise RuntimeError("E2E supervision requires Linux /proc and child-subreaper support") owner_pid = os.getppid() owner = process(owner_pid) if owner is None: raise RuntimeError("E2E owner disappeared before supervision") read_fd, write_fd = os.pipe() watch = None pending = [] def forward(received, _frame): pending.append(received) if watch is not None: try: os.kill(watch.pid, signal.SIGTERM) except ProcessLookupError: pass for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP): signal.signal(sig, forward) # Kernel notification complements polling when make itself is SIGKILLed. # Install handlers first, then close the setup race by rechecking the parent. libc = ctypes.CDLL(None, use_errno=True) if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0: raise OSError(ctypes.get_errno(), "E2E launcher parent-death guard failed") if os.getppid() != owner_pid: os.close(read_fd) os.close(write_fd) raise RuntimeError("E2E owner disappeared during launcher setup") try: watch = subprocess.Popen( [sys.executable, "-E", __file__, "--watch", str(project), str(owner_pid), owner[1], str(read_fd), str(enclosing_deadline(owner_pid) or 0)], pass_fds=(read_fd,), start_new_session=True, ) os.close(read_fd) if pending: os.kill(watch.pid, signal.SIGTERM) return watch.wait() finally: os.close(write_fd) # abrupt launcher death closes it in the kernel too if watch is not None and watch.poll() is None: os.kill(watch.pid, signal.SIGTERM) watch.wait(timeout=6) if __name__ == "__main__": try: if len(sys.argv) == 7 and sys.argv[1] == "--watch": code = watcher(Path(sys.argv[2]), int(sys.argv[3]), sys.argv[4], int(sys.argv[5]), float(sys.argv[6]) or None) elif len(sys.argv) == 2: code = launch(Path(sys.argv[1])) else: raise RuntimeError("invalid E2E supervisor invocation") sys.exit(code) except Exception as error: print(f"E2E supervisor: {error}", file=sys.stderr) sys.exit(1)