49 lines
1.5 KiB
Python
49 lines
1.5 KiB
Python
#!/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 = (
|
|
"import urllib.request; r=urllib.request.urlopen("
|
|
"'http://127.0.0.1:8080/health/live',timeout=1); print(r.headers['X-Instance-Id'])"
|
|
)
|
|
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()
|