Files
mtusi2026lab3/scripts/replicas.py
T

62 lines
1.6 KiB
Python

"""Match an API response alias to a container in this Compose project."""
import json
import os
from pathlib import Path
import subprocess
import sys
from typing import NamedTuple
ROOT = Path(__file__).resolve().parents[1]
class Replica(NamedTuple):
id: str
alias: str
name: str
image: str
status: str
def docker(*args, timeout=30):
return subprocess.run(
["docker", *args], cwd=ROOT, text=True, encoding="utf-8",
stdout=subprocess.PIPE, check=True, timeout=timeout,
).stdout.strip()
def compose(*args, **kwargs):
return docker("compose", *args, **kwargs)
def replicas():
ids = compose("ps", "-a", "-q", "api").splitlines()
if not ids:
return []
fields = "{{.Id}} {{.Config.Hostname}} {{.Name}} {{.Image}} {{.State.Status}}"
return [Replica(*line.split()) for line in docker("inspect", "--format", fields, *ids).splitlines()]
def stop(replica):
docker("stop", "--time", "7", replica.id, timeout=9)
def main():
target = os.environ.get("TARGET_INSTANCE_ID")
running = [replica for replica in replicas() if replica.status == "running"]
matched = [replica for replica in running if replica.alias == target]
if len(matched) != 1 or len(running) < 2:
raise ValueError("TARGET_INSTANCE_ID must match one of at least two running API replicas")
replica = matched[0]
stop(replica)
print(json.dumps({"stopped_container": replica.name, "instance_id": replica.alias}))
if __name__ == "__main__":
try:
main()
except (ValueError, OSError, subprocess.SubprocessError) as error:
print(f"Stop hook failed: {error}", file=sys.stderr)
sys.exit(1)