#!/usr/bin/env python3 """Upload -> остановка обслужившей реплики -> download через другую. Публичный failover-тест проверяет сообщения, но не гарантирует, что остановлена именно реплика, принявшая файл. Этот probe выбирает attachment, загруженный конкретным X-Instance-Id, останавливает его через scripts/stop-one.cmd и скачивает файл через LB. После проверки восстанавливает 2 реплики. """ from __future__ import annotations import argparse import json import os import subprocess import sys import time from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure # noqa: E402 PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes() def main() -> int: parser = argparse.ArgumentParser(description="Failover вложения") parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080")) parser.add_argument("--attempts", type=int, default=20) parser.add_argument("--output", default="evidence/attachment-failover.json") args = parser.parse_args() api = Client(args.base_url, None, timeout=10) alice, bob, _eve, chat = api.bootstrap() chosen = None observed = set() for _ in range(args.attempts): attachment, content = api.attachment(alice, chat) instance = api.call( "GET", "/api/v1/attachments/" + attachment["id"], actor=alice, schema="Attachment" )["headers"]["X-Instance-Id"] observed.add(instance) chosen = (attachment, content, instance) if len(observed) >= 2: break if chosen is None: raise SystemExit("no attachment uploaded") attachment, content, target = chosen report = {"target_instance": target, "attachment_id": attachment["id"], "observed_instances": sorted(observed)} env = dict(os.environ) env["TARGET_INSTANCE_ID"] = target suffix = ".cmd" if os.name == "nt" else ".sh" proc = subprocess.run( [str(ROOT / "scripts" / ("stop-one" + suffix))], env=env, cwd=str(ROOT), capture_output=True, text=True, timeout=30, ) report["stop_exit"] = proc.returncode try: if proc.returncode != 0: raise SystemExit("stop-one failed: " + (proc.stderr or "")[:300]) deadline = time.monotonic() + 10 while time.monotonic() < deadline: try: api.call("GET", "/health/ready", schema="Health") break except Failure: time.sleep(0.3) download = api.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob) served_by = download["headers"]["X-Instance-Id"] report["download_matches"] = download["bytes"] == content report["download_served_by"] = served_by report["downloaded_from_other_replica"] = served_by != target report["metadata"] = api.call( "GET", "/api/v1/attachments/" + attachment["id"], actor=bob, schema="Attachment" )["json"]["status"] finally: restore = subprocess.run( [str(ROOT / "scripts" / ("restore" + suffix))], cwd=str(ROOT), capture_output=True, text=True, timeout=120, ) report["restore_exit"] = restore.returncode output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8") print(json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)) return 0 if report.get("download_matches") and report.get("downloaded_from_other_replica") else 1 if __name__ == "__main__": raise SystemExit(main())