import os import subprocess import sys def main(): target_id = os.environ.get("TARGET_INSTANCE_ID", "").strip().lower() res = subprocess.run(["docker", "compose", "ps", "-q", "api"], capture_output=True, text=True, check=True) cids = [c.strip() for c in res.stdout.splitlines() if c.strip()] for cid in cids: out = subprocess.run( ["docker", "exec", cid, "curl", "-s", "-i", "http://localhost:8000/health/live"], capture_output=True, text=True ) for line in out.stdout.splitlines(): if line.lower().startswith("x-instance-id:"): inst_id = line.split(":", 1)[1].strip().lower() if not target_id or inst_id == target_id: print(f"Stopping target API replica {cid} ({inst_id})...") subprocess.run(["docker", "stop", "-t", "2", cid], check=True) return if cids: subprocess.run(["docker", "stop", "-t", "2", cids[0]], check=True) else: sys.exit(1) if __name__ == "__main__": main()