Files
mtusi2026lab3-Chinyaeva/student-tests/rolling_update.py

196 lines
7.0 KiB
Python

#!/usr/bin/env python3
"""Sequential replacement (rolling update) under continuous writes.
Each replica is drained with SIGTERM (docker stop --time 20), the remaining
replica serves traffic, then the stopped replica is started again and verified.
This is the equivalent replacement step for a Compose image update; the image
build/pull itself is documented in REPORT.md.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import threading
import time
import uuid
from collections import defaultdict
from pathlib import Path
from common import HttpClient
ROOT = Path(__file__).resolve().parents[1]
def compose(*args: str) -> str:
return subprocess.check_output(
["docker", "compose", "--env-file", ".env", *args],
cwd=ROOT,
stderr=subprocess.STDOUT,
text=True,
)
def api_containers() -> list[dict]:
ids = compose("ps", "-q", "api").split()
result = []
for container_id in ids:
hostname = subprocess.check_output(
["docker", "inspect", "--format", "{{.Config.Hostname}}", container_id],
text=True,
).strip()
status = subprocess.check_output(
["docker", "inspect", "--format", "{{.State.Status}}", container_id],
text=True,
).strip()
if status == "running":
result.append({"id": container_id, "hostname": hostname})
return result
def wait_instances(client: HttpClient, token: str, expected: int, timeout: float = 30) -> set[str]:
deadline = time.monotonic() + timeout
seen: set[str] = set()
while time.monotonic() < deadline:
try:
status, headers, _payload, _raw = client.call("GET", "/api/v1/users/me", token=token)
if status == 200:
seen.add(headers.get("X-Instance-Id", ""))
if len(seen) >= expected:
return seen
except OSError:
pass
time.sleep(0.25)
return seen
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--duration", type=float, default=24.0)
parser.add_argument("--workers", type=int, default=8)
parser.add_argument("--output", default="evidence/rolling_update.json")
args = parser.parse_args()
client = HttpClient(args.base_url)
user, registration = client.register()
session = client.login(registration)
token = session["token"]
status, _headers, chat, _raw = client.call(
"POST",
"/api/v1/chats",
body={"title": "Rolling update", "member_ids": [user["id"]]},
token=token,
)
if status != 201:
raise AssertionError(f"chat creation failed: HTTP {status}")
targets = api_containers()
if len(targets) < 2:
raise AssertionError("at least two running API replicas are required")
stop_event = threading.Event()
lock = threading.Lock()
successes = defaultdict(int)
errors = defaultdict(int)
events: list[tuple[float, str]] = []
started = time.monotonic()
def worker(worker_id: int) -> None:
local = HttpClient(args.base_url)
index = 0
while not stop_event.is_set():
index += 1
key = uuid.uuid4().hex
try:
status, headers, _payload, _raw = local.call(
"POST",
f"/api/v1/chats/{chat['id']}/messages",
body={"text": f"rolling-{worker_id}-{index}"},
token=token,
headers={"Idempotency-Key": key},
)
bucket = int(time.monotonic() - started)
with lock:
if status == 201:
successes[bucket] += 1
events.append((time.monotonic(), headers.get("X-Instance-Id", "")))
else:
errors[bucket] += 1
except Exception:
bucket = int(time.monotonic() - started)
with lock:
errors[bucket] += 1
time.sleep(0.005)
threads = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(args.workers)]
for thread in threads:
thread.start()
runs = []
schedule = [(4.0, targets[0]), (14.0, targets[1])]
for planned_at, target in schedule:
while time.monotonic() - started < planned_at:
time.sleep(0.05)
stopped_at = time.monotonic()
subprocess.run(
["docker", "stop", "--time", "20", target["id"]],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
stop_returned = time.monotonic()
time.sleep(2.0)
restore_at = time.monotonic()
compose("start", "api")
seen = wait_instances(client, token, len(targets), timeout=30)
recovered_at = time.monotonic()
with lock:
after_stop = [event for event in events if event[0] > stop_returned]
first_after = min((event[0] for event in after_stop), default=None)
runs.append(
{
"target_instance": target["hostname"],
"stop_seconds": round(stopped_at - started, 3),
"stop_command_seconds": round(stop_returned - stopped_at, 3),
"restore_seconds": round(restore_at - started, 3),
"recovered_seconds": round(recovered_at - started, 3),
"first_write_after_stop_seconds": (
round(first_after - stop_returned, 3) if first_after else None
),
"target_served_during_outage": any(
event[1] == target["hostname"]
for event in events
if stop_returned < event[0] < restore_at
),
"instances_after_restore": sorted(item for item in seen if item),
}
)
print(json.dumps(runs[-1], ensure_ascii=False))
while time.monotonic() - started < args.duration:
time.sleep(0.05)
stop_event.set()
for thread in threads:
thread.join(timeout=5)
report = {
"base_url": args.base_url,
"workers": args.workers,
"duration_seconds": args.duration,
"success_by_second": [successes[i] for i in range(int(args.duration) + 1)],
"errors_by_second": [errors[i] for i in range(int(args.duration) + 1)],
"successes_total": sum(successes.values()),
"errors_total": sum(errors.values()),
"runs": runs,
"note": "sequential SIGTERM drain + restart; same image, no volume removal",
}
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS: sequential rolling replacement completed; evidence:", output)
if __name__ == "__main__":
main()