#!/usr/bin/env python3 """Поочерёдный отказ каждой реплики и rolling restart под нагрузкой.""" import json import subprocess import threading import time import uuid from pathlib import Path from httpapi import basic, bearer, call ROOT = Path(__file__).resolve().parents[1] OUT = ROOT / "evidence" / "grade4.txt" LINES = [] def log(text): print(text) LINES.append(text) def save(): OUT.parent.mkdir(exist_ok=True) OUT.write_text("\n".join(LINES) + "\n", encoding="utf-8") def docker(*args, check=True): proc = subprocess.run(["docker", *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) if check and proc.returncode != 0: raise RuntimeError(proc.stderr.decode("utf-8", "replace")[-500:]) return proc def api_ids(): proc = docker( "ps", "-q", "--filter", "label=com.docker.compose.project=mtusi-lab3", "--filter", "label=com.docker.compose.service=api", ) return [line.strip() for line in proc.stdout.decode().splitlines() if line.strip()] def hostname(container_id): proc = docker("inspect", "-f", "{{.Config.Hostname}}", container_id) return proc.stdout.decode().strip() def wait_instances(token, expect, timeout=40): auth = bearer(token) deadline = time.monotonic() + timeout while time.monotonic() < deadline: seen = set() ok = True for _ in range(12): try: status, headers, _ = call("GET", "/api/v1/users/me", headers=auth, timeout=3) except Exception: ok = False break if status != 200 or not headers.get("X-Instance-Id"): ok = False break seen.add(headers["X-Instance-Id"]) if ok and len(seen) >= expect: return seen time.sleep(0.5) raise RuntimeError("instances did not return to {}".format(expect)) def load_loop(auth, path, seconds, bucket): deadline = time.monotonic() + seconds n = 0 while time.monotonic() < deadline: key = uuid.uuid4().hex started = time.monotonic() try: status, headers, _ = call( "POST", path, {"text": "load-" + key}, headers={**auth, "Idempotency-Key": key}, timeout=5, ) bucket.append( { "ok": status == 201, "status": status, "instance": headers.get("X-Instance-Id", ""), "at": round(started, 3), } ) except Exception: bucket.append({"ok": False, "status": 0, "instance": "", "at": round(started, 3)}) n += 1 def summarize(bucket, mark): total = len(bucket) ok = [item for item in bucket if item["ok"]] bad = total - len(ok) after = [item for item in ok if item["at"] >= mark] if mark is not None else ok instances = sorted({item["instance"] for item in after if item["instance"]}) elapsed = (bucket[-1]["at"] - bucket[0]["at"]) if len(bucket) > 1 else 0 rps = round(len(ok) / elapsed, 3) if elapsed else None return { "requests": total, "ok": len(ok), "errors": bad, "error_ratio": round(bad / total, 4) if total else None, "successful_rps": rps, "instances_after_mark": instances, } def register_and_chat(): suffix = uuid.uuid4().hex[:10] password = "grade4-password-1" status, _, alice = call( "POST", "/api/v1/users", {"username": "g4_" + suffix, "display_name": "Нагрузка", "password": password}, ) if status != 201: raise RuntimeError("register {}".format(status)) status, _, session = call( "POST", "/api/v1/auth/sessions", headers=basic("g4_" + suffix, password), ) if status != 201: raise RuntimeError("login {}".format(status)) status, _, chat = call( "POST", "/api/v1/chats", {"title": "Отказы", "member_ids": [alice["id"]]}, headers=bearer(session["token"]), ) if status != 201: raise RuntimeError("chat {}".format(status)) return session["token"], "/api/v1/chats/" + chat["id"] + "/messages" def failover_one(token, path, container_id): target = hostname(container_id) auth = bearer(token) bucket = [] thread = threading.Thread(target=load_loop, args=(auth, path, 15, bucket)) thread.start() time.sleep(2) stopped_at = time.monotonic() docker("stop", "--time", "5", container_id) thread.join() started_ids = set(hostname(item) for item in api_ids()) summary = summarize(bucket, stopped_at) summary["stopped"] = target summary["stopped_still_running"] = target in started_ids summary["served_by_stopped_after"] = target in summary["instances_after_mark"] log("failover " + json.dumps(summary, ensure_ascii=False)) docker("start", container_id) seen = wait_instances(token, 2) log("restored instances {}".format(len(seen))) return summary def rolling(token, path): auth = bearer(token) before = {item: docker("inspect", "-f", "{{.State.StartedAt}}", item).stdout.decode().strip() for item in api_ids()} bucket = [] thread = threading.Thread(target=load_loop, args=(auth, path, 28, bucket)) thread.start() time.sleep(2) mark = time.monotonic() for container_id in list(before): docker("restart", "--time", "5", container_id) deadline = time.monotonic() + 40 while time.monotonic() < deadline: status = docker( "inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}", container_id, ).stdout.decode().strip() if status == "healthy": break time.sleep(1) time.sleep(2) thread.join() after = {item: docker("inspect", "-f", "{{.State.StartedAt}}", item).stdout.decode().strip() for item in api_ids()} changed = sorted(item[:12] for item in before if before.get(item) != after.get(item)) summary = summarize(bucket, mark) summary["restarted"] = len(changed) log("rolling " + json.dumps(summary, ensure_ascii=False)) wait_instances(token, 2) return summary def main(): token, path = register_and_chat() ids = api_ids() if len(ids) < 2: raise SystemExit("need 2 api replicas, have {}".format(len(ids))) rolling(token, path) # Снимок id заново: rolling не меняет container id, но список перечитываем. for container_id in api_ids(): failover_one(token, path, container_id) save() print("PASS grade4") if __name__ == "__main__": try: main() except Exception as exc: log("FAIL: " + type(exc).__name__ + " " + str(exc)[:300]) save() raise