#!/usr/bin/env python3 """Map a process alias to ONE container belonging to this Compose service.""" import json import os import re import subprocess from concurrent.futures import ThreadPoolExecutor from pathlib import Path ROOT = Path(__file__).resolve().parents[1] def alias(container): code = "from pathlib import Path; print(Path('/tmp/api-instance-id').read_text())" r = subprocess.run( ["docker", "exec", container, "python", "-c", code], cwd=ROOT, capture_output=True, text=True, timeout=3, check=True, ) return container, r.stdout.strip() def main(): target = os.environ.get("TARGET_INSTANCE_ID", "") if not re.fullmatch(r"[a-f0-9]{32}", target): raise SystemExit("TARGET_INSTANCE_ID must name a live API process") ids = subprocess.check_output( ["docker", "compose", "ps", "-q", "api"], cwd=ROOT, text=True ).split() with ThreadPoolExecutor(max_workers=8) as pool: matches = [cid for cid, identity in pool.map(alias, ids) if identity == target] if len(matches) != 1: raise SystemExit("Expected exactly one matching API in this project") subprocess.run( ["docker", "stop", "--time", "5", matches[0]], check=True, capture_output=True, timeout=7 ) print(json.dumps({"stopped_container": matches[0], "instance": target})) if __name__ == "__main__": main()