#!/usr/bin/env python3 """Targeted API failure test. Uses synthetic data; leaves target stopped.""" import json import os from pathlib import Path import subprocess import sys import time import uuid ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure, arguments, check, run from resilience import history PROJECT = "mtusi2026lab3" def docker_output(*args): return subprocess.check_output( ["docker", *args], cwd=ROOT, text=True, ).strip() def target_instance(container): labels = json.loads( docker_output( "inspect", "--format", "{{json .Config.Labels}}", container, ) ) check( labels.get("com.docker.compose.project") == PROJECT, "target belongs to another Compose project", ) check( labels.get("com.docker.compose.service") == "api", "target is not an API container", ) check( docker_output( "inspect", "--format", "{{.State.Running}}", container, ) == "true", "target container is not running", ) code = ( "import urllib.request; " "r=urllib.request.urlopen(" "'http://127.0.0.1:8080/health/live', timeout=2); " "print(r.headers.get('X-Instance-Id', '')); " "r.close()" ) instance = docker_output( "exec", container, "python", "-c", code ) check(bool(instance), "target has no X-Instance-Id") return instance def main(): def configure(parser): parser.add_argument( "--target-container", required=True, ) args = arguments( "Targeted API failover through the load balancer", configure, ) script = ROOT / "scripts" / "stop-one.sh" check( script.is_file() and os.access(script, os.X_OK), "stop-one.sh must exist and be executable", ) target = target_instance(args.target_container) client = Client(args.base_url, args.ca_file, timeout=2) alice, bob, eve, chat = client.bootstrap() original_key = uuid.uuid4().hex original_text = "Подтверждено до отказа " + original_key original = client.message( alice, chat, original_text, key=original_key, )["json"] observed = set() for _ in range(40): response = client.call( "GET", "/api/v1/users/me", actor=alice, schema="User", ) observed.add(response["headers"]["X-Instance-Id"]) check(len(observed) >= 2, "less than two API instances") check(target in observed, "target is not observed through LB") env = dict(os.environ) env["TARGET_INSTANCE_ID"] = target print( "Target container:", args.target_container, "| instance:", target, flush=True, ) started = time.monotonic() proc = subprocess.Popen( [str(script)], cwd=ROOT, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) successes = [] write_failures = 0 read_successes = 0 read_failures = 0 after_instances = [] first_recovery = None attempts = 0 key = uuid.uuid4().hex text = "Во время отказа " + key try: while time.monotonic() - started < 15: code = proc.poll() elapsed = time.monotonic() - started check( code is None or code == 0, "stop-one hook failed", ) check( code is not None or elapsed < 10, "stop-one hook exceeded 10 seconds", ) attempts += 1 try: response = client.message( alice, chat, text, key=key, ) except Failure: write_failures += 1 # Keep the same key and text after uncertain POST. else: successes.append(response["json"]) if proc.poll() == 0: if first_recovery is None: first_recovery = time.monotonic() - started after_instances.append( response["headers"]["X-Instance-Id"] ) key = uuid.uuid4().hex text = "Во время отказа " + key if attempts % 5 == 0: try: page = client.call( "GET", ( "/api/v1/chats/" + chat["id"] + "/messages?limit=100" ), actor=bob, schema="MessagePage", )["json"] except Failure: read_failures += 1 else: check( any( message == original for message in page["items"] ), "confirmed message absent during read", ) read_successes += 1 time.sleep(0.1) elapsed = time.monotonic() - started check(proc.poll() == 0, "stop-one hook did not finish") check( first_recovery is not None and first_recovery <= 10, "writes did not recover within 10 seconds", ) check( len(after_instances) >= 5, "too few writes after stop", ) check( target not in after_instances[-5:], "stopped instance still serves requests", ) check(read_successes > 0, "no successful history reads") check( docker_output( "inspect", "--format", "{{.State.Running}}", args.target_container, ) == "false", "target container is still running", ) replay = client.message( alice, chat, original_text, key=original_key, )["json"] check( replay == original, "replay after failure returned another message", ) messages = history(client, bob, chat) by_id = {message["id"]: message for message in messages} check( len(by_id) == len(messages), "duplicate message IDs", ) check( by_id.get(original["id"]) == original, "pre-failure message lost or altered", ) for message in successes: check( by_id.get(message["id"]) == message, "confirmed in-flight message lost or altered", ) texts = [message["text"] for message in messages] check( len(texts) == len(set(texts)), "retry created duplicate message text", ) print( json.dumps( { "target_container": args.target_container, "target_instance": target, "observed_instances_before": len(observed), "duration_seconds": round(elapsed, 3), "successful_writes": len(successes), "failed_write_attempts": write_failures, "successful_reads": read_successes, "failed_read_attempts": read_failures, "successful_write_rps": round( len(successes) / elapsed, 3 ), "first_recovery_seconds": round( first_recovery, 3 ), "replay_preserved": True, "target_stopped": True, }, ensure_ascii=False, ) ) print( "PASS: targeted failover; session, messages " "and replay preserved. Target remains stopped." ) finally: if proc.poll() is None: proc.terminate() try: proc.wait(timeout=5) except subprocess.TimeoutExpired: proc.kill() proc.wait() if __name__ == "__main__": run(main)