Files
mtusi2026lab4/scripts/wait_ready.py
T

35 lines
1.4 KiB
Python

#!/usr/bin/env python3
"""Wait for actual healthy Compose API containers and their public LB aliases."""
import argparse
import json
from pathlib import Path
import subprocess
import time
import urllib.request
ROOT=Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser()
parser.add_argument('--base-url',default='http://localhost:8084')
parser.add_argument('--replicas',type=int,default=2)
args=parser.parse_args()
deadline=time.monotonic()+90
while time.monotonic()<deadline:
ids=subprocess.check_output([str(ROOT/'scripts/compose.sh'),'ps','-q','api'],cwd=ROOT,text=True).split()
if len(ids)==args.replicas:
state=json.loads(subprocess.check_output(['docker','inspect',*ids],text=True))
if all(c['State'].get('Health',{}).get('Status')=='healthy' for c in state):
expected={c['Config']['Hostname'] for c in state}
try:
observed=set()
for _ in range(16):
with urllib.request.urlopen(args.base_url+'/health/ready',timeout=2) as response:
observed.add(response.headers.get('X-Instance-Id'))
if observed==expected:
print('PASS: healthy API replicas observed through LB')
break
except OSError:
pass
time.sleep(.5)
else:
raise SystemExit('API readiness/LB discovery exceeded 90 seconds')