"""Start a job worker that outlives the API server. A split takes minutes, so restarting the server, pressing Ctrl+C or closing its terminal must not kill the worker. Each of those normally would, for a different reason: * Console signals: Ctrl+C and closing the window reach every process attached to that console. The worker gets its own hidden console on Windows (CREATE_NO_WINDOW, so tools it starts, such as ffmpeg, open no windows either) or its own session on POSIX. * Process-tree kills: `concurrently -k`, terminal panels and `taskkill /T` kill a process and every descendant. The worker is started by a short-lived intermediate process (`python -m stemdeck.detach`) that exits at once, so the worker is no longer a descendant of the server. * Windows job objects that kill their members when closed: the worker breaks away when the job allows it. The server's own shutdown no longer kills the worker either (see JobRunner.stop). """ from __future__ import annotations import argparse import logging import subprocess import sys from pathlib import Path SPAWN_TIMEOUT_SEC = 60.0 PID_PREFIX = "PID " WARNING_PREFIX = "WARNING " _ERROR_TAIL_CHARS = 500 log = logging.getLogger(__name__) class SpawnError(RuntimeError): """The worker process could not be started.""" def spawn_detached(cmd: list[str], *, cwd: Path, env: dict[str, str], log_path: Path) -> int: """Start `cmd` detached from this process (stdout/stderr appended to `log_path`) and return its pid.""" launcher = [sys.executable, "-m", "stemdeck.detach", "--cwd", str(cwd), "--log", str(log_path), "--", *cmd] try: result = subprocess.run(launcher, cwd=str(cwd), env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=SPAWN_TIMEOUT_SEC) except (OSError, subprocess.TimeoutExpired) as exc: raise SpawnError(f"could not run the worker launcher: {exc}") from exc lines = result.stdout.splitlines() for line in lines: if line.startswith(WARNING_PREFIX): log.warning("worker launcher: %s", line.removeprefix(WARNING_PREFIX)) for line in reversed(lines): if line.startswith(PID_PREFIX): return int(line.removeprefix(PID_PREFIX)) detail = (result.stderr or result.stdout).strip()[-_ERROR_TAIL_CHARS:] raise SpawnError(f"worker launcher exited with {result.returncode}: {detail}") def _launch(cmd: list[str], cwd: Path, log_path: Path) -> int: log_path.parent.mkdir(parents=True, exist_ok=True) with open(log_path, "ab") as log_file: options: dict[str, object] = {"cwd": str(cwd), "stdin": subprocess.DEVNULL, "stdout": log_file, "stderr": subprocess.STDOUT, "close_fds": True} if sys.platform != "win32": return subprocess.Popen(cmd, start_new_session=True, **options).pid # type: ignore[arg-type] flags = subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP try: proc = subprocess.Popen(cmd, creationflags=flags | subprocess.CREATE_BREAKAWAY_FROM_JOB, **options) # type: ignore[arg-type] except PermissionError: # the job we are in forbids breakaway; the other two measures still apply print(f"{WARNING_PREFIX}could not break away from the parent's Windows job object; the worker may " "stop if the program that started the server closes", flush=True) proc = subprocess.Popen(cmd, creationflags=flags, **options) # type: ignore[arg-type] return proc.pid def main() -> None: argv = sys.argv[1:] if "--" not in argv or argv.index("--") == len(argv) - 1: raise SystemExit("usage: python -m stemdeck.detach --cwd DIR --log FILE -- COMMAND [ARGS...]") split = argv.index("--") parser = argparse.ArgumentParser(prog="python -m stemdeck.detach") parser.add_argument("--cwd", required=True, type=Path) parser.add_argument("--log", required=True, type=Path) options = parser.parse_args(argv[:split]) pid = _launch(argv[split + 1:], options.cwd, options.log) print(f"{PID_PREFIX}{pid}", flush=True) if __name__ == "__main__": main()