"""Measure replica failures and replacement while clients write through HAProxy.""" from __future__ import annotations from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager from http.client import HTTPException import json import math import os from pathlib import Path import subprocess import sys from threading import Barrier, Event, Lock import time from typing import NamedTuple from uuid import uuid4 ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) sys.path.insert(0, str(ROOT / "scripts")) from client import Client, Failure, arguments, check, run from replicas import compose, docker, replicas, stop from resilience import history WORKERS = 4 PAUSE_SECONDS = 0.12 WARMUP_SECONDS = 1 BASELINE_SECONDS = 2 OUTAGE_SECONDS = 6 def wait_routed(client, actor, expected): seen = set() deadline = time.monotonic() + 25 while time.monotonic() < deadline: try: response = client.call("GET", "/api/v1/users/me", actor=actor, schema="User") except Failure: time.sleep(0.1) continue check(response["json"] == actor["user"], "session resolved to the wrong user") seen.add(response["headers"]["X-Instance-Id"]) if expected <= seen: return time.sleep(0.05) raise Failure(f"LB did not route the shared session to expected replicas: {sorted(expected - seen)}") def race(client, actor, other, chat): key = uuid4().hex text = "parallel replay " + key count = 8 barrier = Barrier(count, timeout=10) def send(_): worker = Client(client.base, timeout=5) barrier.wait() return worker.message(actor, chat, text, key=key) with ThreadPoolExecutor(max_workers=count) as pool: responses = list(pool.map(send, range(count))) message = responses[0]["json"] seen = {response["headers"]["X-Instance-Id"] for response in responses} check(len(seen) >= 2, "parallel requests did not reach different replicas") check(all(response["json"] == message for response in responses), "replay changed the result") check([m for m in history(client, actor, chat) if m["text"] == text] == [message], "parallel replay must store exactly one message") path = "/api/v1/chats/" + chat["id"] + "/messages" client.call("POST", path, 409, actor=actor, body={"text": "different " + key}, headers={"Idempotency-Key": key}) another = client.message(other, chat, text, key=key)["json"] check(another["id"] != message["id"], "the key must be scoped to the sender") return {"requests": count, "replicas": sorted(seen), "original_messages": 1, "different_body_status": 409, "same_key_for_another_sender": 201} class Attempt(NamedTuple): started: float finished: float instance: str | None message: dict | None class Traffic: def __init__(self, client, actor, chat): self.base = client.base self.actor = actor self.chat = chat self.done = Event() self.lock = Lock() self.attempts = [] def worker(self): client = Client(self.base, timeout=2) key = uuid4().hex while not self.done.is_set(): started = time.monotonic() try: response = client.message(self.actor, self.chat, "load " + key, key=key) except (Failure, OSError, HTTPException): attempt = Attempt(started, time.monotonic(), None, None) else: attempt = Attempt(started, time.monotonic(), response["headers"]["X-Instance-Id"], response["json"]) key = uuid4().hex with self.lock: self.attempts.append(attempt) self.done.wait(PAUSE_SECONDS) def window(self, start, end): with self.lock: return [attempt for attempt in self.attempts if start <= attempt.finished < end] def verify(self, client): stored = history(client, self.actor, self.chat) by_id = {message["id"]: message for message in stored} check(len({message["text"] for message in stored}) == len(stored), "a retry created a duplicate") acknowledged = [attempt.message for attempt in self.attempts if attempt.message is not None] check(all(by_id.get(message["id"]) == message for message in acknowledged), "an acknowledged message was lost") return {"acknowledged_messages": len(acknowledged), "stored_messages": len(stored)} @contextmanager def traffic(client, actor, chat): load = Traffic(client, actor, chat) with ThreadPoolExecutor(max_workers=WORKERS) as pool: workers = [pool.submit(load.worker) for _ in range(WORKERS)] try: yield load finally: load.done.set() for worker in workers: worker.result() def metrics(load, start, end): attempts = load.window(start, end) success = [attempt for attempt in attempts if attempt.message is not None] check(bool(success), "no successful writes during the measured window") latencies = sorted((attempt.finished - attempt.started) * 1000 for attempt in success) return { "seconds": round(end - start, 3), "successful_writes": len(success), "failed_attempts": len(attempts) - len(success), "successful_rps": round(len(success) / (end - start), 2), "latency_ms": { f"p{p}": round(latencies[math.ceil(p * len(latencies) / 100) - 1], 2) for p in (50, 95, 99) }, "serving_aliases": sorted({attempt.instance for attempt in success}), } def first_write(load, started, stopped, end, survivor_aliases): writes = [attempt.finished for attempt in load.window(stopped, end) if attempt.started >= stopped and attempt.instance in survivor_aliases] check(bool(writes), "no confirmed write through a surviving replica after the stop") elapsed = min(writes) - started check(elapsed <= 10, "writes did not recover within 10 seconds") return round(elapsed, 3) def failover(client, actor, load, initial): for target in initial: survivors = {replica.alias for replica in initial if replica.id != target.id} started = time.monotonic() try: stop(target) stopped = time.monotonic() state = next(replica.status for replica in replicas() if replica.id == target.id) check(state == "exited", "target is still running") wait_routed(client, actor, survivors) first_read = time.monotonic() - started check(first_read <= 10, "reads did not recover within 10 seconds") time.sleep(OUTAGE_SECONDS) end = time.monotonic() during = metrics(load, started, end) check(target.alias not in metrics(load, stopped + 2, end)["serving_aliases"], "stopped replica still serves traffic") recovered = first_write(load, started, stopped, end, survivors) finally: docker("start", target.id) wait_routed(client, actor, survivors | {target.alias}) yield {"stopped": target.name, "target_alias": target.alias, "target_status": state, "first_survivor_read_seconds": round(first_read, 3), "first_survivor_write_seconds": recovered, **during} def roll(client, actor, load, initial, new_image): count = str(len(initial)) for target in initial: before = replicas() survivors = [replica for replica in before if replica.id != target.id] survivor_aliases = {replica.alias for replica in survivors} started = time.monotonic() try: stop(target) stopped = time.monotonic() docker("rm", target.id) compose("up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={count}", "api") after = replicas() added = [replica for replica in after if replica.id not in {item.id for item in before}] check(len(added) == 1 and added[0].image == new_image, "expected one replacement from the new image") check({item.id for item in survivors} <= {item.id for item in after}, "a survivor was replaced") new = added[0] wait_routed(client, actor, survivor_aliases | {new.alias}) ready = time.monotonic() time.sleep(1) except (Failure, OSError, subprocess.SubprocessError): compose("up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={count}", "api") raise end = time.monotonic() during = metrics(load, started, end) check(new.alias in during["serving_aliases"], "new replica did not accept writes") recovered = first_write(load, started, stopped, end, survivor_aliases) yield {"removed": target.name, "old_alias": target.alias, "old_image": target.image, "replacement_alias": new.alias, "new_image": new.image, "replacement_routed_seconds": round(ready - started, 3), "first_survivor_write_seconds": recovered, **during} check(all(replica.image == new_image for replica in replicas()), "rollout left old images running") def main(): def configure(parser): parser.add_argument("--mode", choices=("race", "failover", "rolling"), required=True) parser.add_argument("--output", type=Path) args = arguments("Lab 3 grade 4 checks", configure) client = Client(args.base_url or os.environ.get("BASE_URL") or "http://127.0.0.1:8081", timeout=5) actor, other, _, chat = client.bootstrap() initial = replicas() check(len(initial) >= 2 and all(replica.status == "running" for replica in initial), "start all API replicas before the experiment") wait_routed(client, actor, {replica.alias for replica in initial}) result = {"mode": args.mode, "initial_replicas": [replica._asdict() for replica in initial]} if args.mode == "race": result.update(race(client, actor, other, chat)) else: if args.mode == "rolling": revision = uuid4().hex[:12] compose("build", "--build-arg", f"BUILD_REVISION={revision}", "api", timeout=180) new_image = docker("image", "inspect", "bruh-lab3-api:local", "--format", "{{.Id}}") check(new_image not in {replica.image for replica in initial}, "rollout requires a new image") with traffic(client, actor, chat) as load: time.sleep(WARMUP_SECONDS) start = time.monotonic() time.sleep(BASELINE_SECONDS) result["baseline"] = metrics(load, start, time.monotonic()) if args.mode == "failover": result["steps"] = list(failover(client, actor, load, initial)) else: result["steps"] = list(roll(client, actor, load, initial, new_image)) result.update(load.verify(client), workers=WORKERS, pause_seconds=PAUSE_SECONDS, warmup_seconds=WARMUP_SECONDS) text = json.dumps(result, indent=2) if args.output: args.output.write_text(text + "\n", encoding="utf-8") print(text) if __name__ == "__main__": run(main)