Files
mtusi2026lab3/scripts/stop_one.py
T

20 lines
1.0 KiB
Python

"""Stop exactly the process identified by TARGET_INSTANCE_ID; never remove volumes."""
import os
from pathlib import Path
import re
import subprocess
ROOT = Path(__file__).resolve().parents[1]
target = os.environ.get("TARGET_INSTANCE_ID", "")
if not re.fullmatch(r"api[12]-[0-9a-f]{12}", target):
raise SystemExit("TARGET_INSTANCE_ID must be the exact X-Instance-Id from a running API")
service = target.split("-", 1)[0]
compose = ["docker", "compose", "--env-file", ".env"]
# Compare to the real API process, rather than trusting a supplied service name.
code = "from urllib.request import urlopen; print(urlopen('http://127.0.0.1:8080/health/live',timeout=2).headers['X-Instance-Id'])"
actual = subprocess.check_output(compose + ["exec", "-T", service, "python", "-c", code], cwd=ROOT, text=True).strip()
if actual != target:
raise SystemExit("Target process changed; refusing to stop another instance")
subprocess.run(compose + ["stop", "--timeout", "6", service], cwd=ROOT, check=True)
print("Stopped " + service + " instance=" + target)