#!/usr/bin/env python3 """Change the address of one real API container in this project's network.""" import ipaddress import json from pathlib import Path import subprocess import sys import time ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'tests')) from client import Client, Failure from resilience import history def cmd(*args): return subprocess.check_output(args,text=True).strip() compose=[str(ROOT/'scripts/compose.sh')] c=Client(timeout=2) a,b,e,chat=c.bootstrap() message=c.message(a,chat,'DNS synthetic confirmed')['json'] target=cmd(*compose,'ps','-q','api').splitlines()[0] info=json.loads(cmd('docker','inspect',target))[0] network=next(iter(info['NetworkSettings']['Networks'])) assert network=='mtusi2026lab3_default' old_ip=info['NetworkSettings']['Networks'][network]['IPAddress'] alias=cmd('docker','exec',target,'python','-c','import urllib.request; print(urllib.request.urlopen("http://127.0.0.1:8080/health/live").headers["X-Instance-Id"])') start=time.monotonic() # Keep the old address occupied by a third REAL API process, then reconnect # the original. No fixed subnet or synthetic/dummy backend is needed. cmd('docker','network','disconnect',network,target) temporary = None try: temporary=cmd(*compose,'run','-d','--no-deps','--use-aliases','api').splitlines()[-1] cmd('docker','network','connect','--alias','api',network,target) moved=json.loads(cmd('docker','inspect',target))[0] new_ip=moved['NetworkSettings']['Networks'][network]['IPAddress'] assert new_ip != old_ip finally: if temporary: cmd('docker','stop','--timeout','6',temporary) cmd('docker','rm',temporary) current=json.loads(cmd('docker','inspect',target))[0] if network not in current['NetworkSettings']['Networks']: cmd('docker','network','connect','--alias','api',network,target) errors=0 seen=set() while time.monotonic()-start<15: try: r=c.message(a,chat,'DNS-'+str(time.monotonic_ns())) seen.add(r['headers']['X-Instance-Id']) if alias in seen and len(seen)>=2: break except Failure: errors+=1 time.sleep(.05) else: raise AssertionError('HAProxy failed to discover moved API') assert message in history(c,b,chat) report={'result':'PASS','container':target,'instance':alias,'old_ip':old_ip,'new_ip':new_ip, 'discovery_seconds':round(time.monotonic()-start,3),'failed_attempts':errors, 'observed_instances':sorted(seen),'existing_session_and_confirmed_message':'PASS'} (ROOT/'evidence/dns-change.json').write_text(json.dumps(report,indent=2)+'\n') print(json.dumps(report,indent=2))