#!/usr/bin/env python3 """Foreground API/worker supervisor: service.py [start|stop|status]. Run inside the workspace container as llmuser. Keep systemd outside the container; never grant this script a Docker socket or host privileges. """ import argparse import json import logging import os from pathlib import Path import signal import subprocess import sys import time SCRIPT = Path(__file__).resolve() sys.path.insert(0, str(SCRIPT.parents[1])) from llm_services.store import Settings, atomic_json, confined_path, open_confined_file from llm_services.worker import process_identity LOG = logging.getLogger("llm-service") GPU_UUID = "GPU-6f547b70-7a25-70cb-e134-888402be61e2" def configuration(): settings = Settings.from_env() data = {} for path in (settings.app_root / "config" / "settings.json", settings.app_root / "settings.json"): if path.exists(): with open_confined_file(path, settings.workspace_root) as handle: data = json.load(handle) break environment = dict(os.environ) overrides = data.get("runner_env", data.get("env", {})) if not isinstance(overrides, dict) or any(not isinstance(k, str) or not isinstance(v, str) for k, v in overrides.items()): raise ValueError("runner_env must be an object of string environment variables") environment.update(overrides) environment.setdefault("LLM_GPU_UUID", GPU_UUID) environment.setdefault("LLM_GPU_BUDGET_GIB", "68") environment.setdefault("LLM_GPU_RESERVE_GIB", "8") environment.update(APP_ROOT=str(settings.app_root), WORKSPACE_ROOT=str(settings.workspace_root), PYTHONPATH=str(settings.app_root), PYTHONUNBUFFERED="1") return settings, data, environment def read_record(path, workspace): if not path.exists() and not path.is_symlink(): return None with open_confined_file(path, workspace) as handle: record = json.load(handle) if not isinstance(record, dict): raise ValueError("Invalid service identity record") return record def verified_supervisor(record): """Require both Linux birth identity and this exact script in argv.""" if not record or record.get("script") != str(SCRIPT): return False identity = process_identity(record["pid"]) if not identity or identity["state"] in {"Z", "X"} or identity["start"] != record.get("start"): return False try: argv = Path(f"/proc/{record['pid']}/cmdline").read_bytes().split(b"\0") cwd = Path(os.readlink(f"/proc/{record['pid']}/cwd")) return any((cwd / os.fsdecode(arg)).resolve() == SCRIPT for arg in argv if arg and not arg.startswith(b"-")) except (FileNotFoundError, ProcessLookupError): return False def stop_child(process, identity, timeout): if process.poll() is not None: return True current = process_identity(process.pid) if not current or not identity or current["start"] != identity["start"]: raise RuntimeError("Child PID identity changed; refusing to signal") try: # Signal the worker leader first: it owns the runner cleanup protocol. os.kill(process.pid, signal.SIGTERM) except ProcessLookupError: return True try: process.wait(timeout=timeout) return True except subprocess.TimeoutExpired: current = process_identity(process.pid) if not current or current["start"] != identity["start"]: raise RuntimeError("Child identity changed before forced stop") LOG.error("Child %s exceeded graceful shutdown; KILL, preserving job recovery records", process.pid) os.killpg(process.pid, signal.SIGKILL) process.wait(timeout=5) return False def start(settings, data, environment): import fcntl settings.state_dir.mkdir(parents=True, exist_ok=True) lock_path = confined_path(settings.state_dir / "service.lock", settings.workspace_root) record_path = confined_path(settings.state_dir / "service.json", settings.workspace_root) lock_fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600) children = {} owned_record = False stopping = False exit_code = 0 def request_stop(signum, frame): nonlocal stopping stopping = True previous_handlers = {} try: try: fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: LOG.error("Another supervisor owns service.lock") return 2 if record_path.exists() or record_path.is_symlink(): LOG.error("service.json already exists; verify old supervisor/children before operator recovery") return 2 identity = process_identity(os.getpid()) record = {"pid": os.getpid(), "start": identity["start"], "script": str(SCRIPT), "children": {}, "created_at": time.time()} for sig in (signal.SIGTERM, signal.SIGINT): previous_handlers[sig] = signal.signal(sig, request_stop) atomic_json(record_path, record) owned_record = True python = str(data.get("service_python", sys.executable)) commands = { "api": [python, "-m", "uvicorn", "llm_services.api:app", "--host", str(data.get("api_host", "127.0.0.1")), "--port", str(data.get("api_port", 18190))], "worker": [python, "-m", "llm_services.worker"], } for name, command in commands.items(): if stopping: break log_path = confined_path(settings.state_dir / (name + ".log"), settings.workspace_root) with log_path.open("ab") as stream: process = subprocess.Popen(command, cwd=settings.app_root, env=environment, stdin=subprocess.DEVNULL, stdout=stream, stderr=subprocess.STDOUT, start_new_session=True, close_fds=True) identity = process_identity(process.pid) children[name] = process, identity record["children"][name] = {"pid": process.pid, "start": identity["start"] if identity else None} atomic_json(record_path, record) while not stopping: for name, (process, _) in children.items(): if process.poll() is not None: LOG.error("%s exited unexpectedly with code %s", name, process.returncode) exit_code, stopping = 1, True break time.sleep(.1) except Exception: LOG.exception("Supervisor failed") exit_code = 1 finally: clean = True for name in ("worker", "api"): if name in children: try: graceful = stop_child(*children[name], timeout=float(data.get("service_shutdown_seconds", 30))) if not graceful: exit_code = 1 except Exception: LOG.exception("Cannot verify %s shutdown; keeping service.json", name) clean, exit_code = False, 1 if owned_record and clean: record_path.unlink(missing_ok=True) for sig, handler in previous_handlers.items(): signal.signal(sig, handler) os.close(lock_fd) return exit_code def stop(settings, data): record = read_record(settings.state_dir / "service.json", settings.workspace_root) if record is None: print(json.dumps({"state": "stopped"})) return 0 if not verified_supervisor(record): LOG.error("Stale/unverified service PID; no signal sent. Inspect old children before recovery") return 2 os.kill(record["pid"], signal.SIGTERM) deadline = time.monotonic() + 2 * float(data.get("service_shutdown_seconds", 30)) + 8 while time.monotonic() < deadline: if not verified_supervisor(record): print(json.dumps({"state": "stopped"})) return 0 time.sleep(.1) LOG.error("Supervisor has not stopped; job and service identity records retained") return 1 def status(settings): record = read_record(settings.state_dir / "service.json", settings.workspace_root) running = verified_supervisor(record) print(json.dumps({"state": "running" if running else "stale" if record else "stopped", "pid": record.get("pid") if record else None, "children": record.get("children", {}) if record else {}})) return 0 if running else 3 def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("start", "stop", "status"), default="start", nargs="?") args = parser.parse_args() logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") if not sys.platform.startswith("linux"): LOG.error("Service supervision requires Linux flock and /proc") return 2 try: settings, data, environment = configuration() if args.action == "start": return start(settings, data, environment) if args.action == "stop": return stop(settings, data) return status(settings) except (OSError, ValueError, KeyError, RuntimeError): LOG.exception("Service command failed") return 2 if __name__ == "__main__": raise SystemExit(main())