forked from mtusi2026/mtusi2026lab4
63 lines
2.6 KiB
Python
63 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
|
"""Test lifecycle hooks: operate only on existing API containers in an explicit project."""
|
|
import argparse
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
|
|
|
|
def execute(argv):
|
|
p = subprocess.run(argv, cwd=ROOT, capture_output=True, timeout=15, check=False)
|
|
if p.returncode:
|
|
raise RuntimeError("Docker action failed; inspect the selected test project")
|
|
return p.stdout
|
|
|
|
|
|
def inspect(identifier):
|
|
return json.loads(execute(["docker", "inspect", identifier]))[0]
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("action", choices=["start_one", "recover_all"])
|
|
args = parser.parse_args()
|
|
project = os.environ.get("COMPOSE_PROJECT_NAME")
|
|
if not project:
|
|
raise RuntimeError("set COMPOSE_PROJECT_NAME to the explicit synthetic test project")
|
|
ids = execute(["docker", "ps", "-aq", "--filter", "label=com.docker.compose.project=" + project,
|
|
"--filter", "label=com.docker.compose.service=api"]).decode().split()
|
|
values = [inspect(identifier) for identifier in ids]
|
|
if len(values) < 2:
|
|
raise RuntimeError("selected project needs at least two existing API containers")
|
|
for value in values:
|
|
labels = value["Config"]["Labels"]
|
|
if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "api":
|
|
raise RuntimeError("container ownership mismatch")
|
|
if args.action == "start_one":
|
|
target = os.environ.get("TARGET_INSTANCE_ID")
|
|
values = [v for v in values if v["Config"]["Hostname"] == target]
|
|
if len(values) != 1:
|
|
raise RuntimeError("target must identify exactly one owned API container")
|
|
for value in values:
|
|
if not value["State"]["Running"]:
|
|
execute(["docker", "start", value["Id"]])
|
|
deadline = time.monotonic() + 40
|
|
while time.monotonic() < deadline:
|
|
current = [inspect(value["Id"])["State"] for value in values]
|
|
if all(s["Running"] and s.get("Health", {}).get("Status") == "healthy" for s in current):
|
|
print(json.dumps({"action": args.action, "recovered_containers": len(values)}))
|
|
return
|
|
time.sleep(.25)
|
|
raise RuntimeError("API did not regain Docker health in 40 seconds")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
try:
|
|
main()
|
|
except (OSError, RuntimeError, ValueError, KeyError, subprocess.SubprocessError) as exc:
|
|
raise SystemExit("FAIL: " + type(exc).__name__ + ": lifecycle hook unavailable") from None
|