Files
mtusi2026lab4/student-tests/s3_outage.py
T
zemiles 0341b4e674 Исправить проблемы, найденные повторной проверкой из чистого clone
- Healthcheck S3 проверяет реальную запись (PUT во внутренний filer):
  после рестарта SeaweedFS запись готова на 10–20 с позже /healthz, и
  make test-failover сразу после make test-persistence падал с 503.
- Upload на старте реплики ждёт первой успешной проверки S3 до 5 с.
- stop-one.sh берёт реплики из docker compose ps, а не по имени проекта.
- s3_outage.py в конце ждёт восстановления S3; переключение
  FAULT_INJECTION выполняется с --no-deps.
- Перезаписаны evidence/, в REPORT.md добавлен раздел повторной проверки.
2026-11-07 11:34:41 +03:00

110 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Недоступность S3: stop (порт закрыт) и pause (S3 «завис», TCP не отвечает).
python3 student-tests/s3_outage.py [--output evidence/s3-outage.json]
Ожидания: upload и download — быстрый 503 unavailable c Retry-After (не 500 и не
таймаут LB), текстовые сообщения и /health/ready продолжают работать (S3 не входит в
readiness), после восстановления S3 загрузка снова 201 без перезапуска API.
"""
import argparse
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client # noqa: E402
PNG = (ROOT / "tests/fixtures/sample.png").read_bytes()
log = []
def probe(c, alice, chat, att):
out = {}
for name, args in (
("upload", ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"])),
("download", ("GET", "/api/v1/attachments/%s/content" % att["id"])),
("text_message", ("POST", "/api/v1/chats/%s/messages" % chat["id"])),
("ready", ("GET", "/health/ready"))):
kw = {}
if name == "upload":
kw = {"raw": PNG, "headers": {"Content-Type": "image/png"}}
if name == "text_message":
kw = {"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}
t = time.monotonic()
r = c.call(*args, [200, 201, 503, 502, 504], actor=alice if name != "ready" else None, **kw)
out[name] = {"status": r["status"], "ms": round((time.monotonic() - t) * 1000),
"code": (r["json"] or {}).get("error", {}).get("code"),
"retry_after": r["headers"].get("Retry-After")}
return out
def phase(name, c, alice, chat, att):
entry = {"phase": name, "probe": probe(c, alice, chat, att)}
log.append(entry)
print(json.dumps(entry, ensure_ascii=False), flush=True)
return entry
def recover(c, alice, chat, started):
while time.monotonic() - started < 120:
r = c.call("POST", "/api/v1/chats/%s/attachments?filename=r.png" % chat["id"], [201, 503], actor=alice,
raw=PNG, headers={"Content-Type": "image/png"})
if r["status"] == 201:
return round(time.monotonic() - started, 1)
time.sleep(0.5)
return None
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--base-url", default="http://localhost:8080")
ap.add_argument("--output")
args = ap.parse_args()
c = Client(args.base_url, timeout=30)
alice, _bob, _eve, chat = c.bootstrap()
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=a.png" % chat["id"], 201, actor=alice, raw=PNG,
headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
phase("baseline", c, alice, chat, att)
for action, undo in ((["stop", "s3"], ["start", "s3"]), (["pause", "s3"], ["unpause", "s3"])):
subprocess.run(["docker", "compose"] + action, cwd=ROOT, check=True, capture_output=True)
time.sleep(1)
phase("immediately after `%s` (S3Health not yet stale)" % " ".join(action), c, alice, chat, att)
time.sleep(4)
phase("S3 down for 5 s (`%s`)" % " ".join(action), c, alice, chat, att)
subprocess.run(["docker", "compose"] + undo, cwd=ROOT, check=True, capture_output=True)
t0 = time.monotonic()
rec = recover(c, alice, chat, t0)
log.append({"phase": "recovery after `%s`" % " ".join(undo), "upload_201_after_s": rec})
print(json.dumps(log[-1]), flush=True)
# Оставляем стенд рабочим: ждём, пока healthcheck S3 снова станет healthy (после pause
# он несколько проверок подряд был unhealthy, а `docker compose up api` при нездоровой
# зависимости не запускает реплики).
cid = subprocess.run(["docker", "compose", "ps", "-q", "s3"], cwd=ROOT, capture_output=True, text=True).stdout.strip()
t0 = time.monotonic()
while time.monotonic() - t0 < 120:
st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True, text=True).stdout.strip()
if st == "healthy":
break
time.sleep(1)
log.append({"phase": "s3 healthcheck healthy again", "after_s": round(time.monotonic() - t0, 1), "status": st})
print(json.dumps(log[-1]), flush=True)
down = [e for e in log if e.get("phase", "").startswith("S3 down")]
ok = all(e["probe"]["upload"]["status"] == 503 and e["probe"]["download"]["status"] == 503
and e["probe"]["text_message"]["status"] == 201 and e["probe"]["ready"]["status"] == 200
for e in down) and all(e.get("upload_201_after_s") is not None for e in log if "upload_201_after_s" in e)
no5xx = all(p["status"] in (200, 201, 503) for e in log if "probe" in e for p in e["probe"].values())
ok = ok and st == "healthy"
print(json.dumps({"pass": ok and no5xx, "only_200_201_503": no5xx}))
if args.output:
Path(args.output).write_text(json.dumps({"pass": ok and no5xx, "phases": log}, ensure_ascii=False, indent=1))
return 0 if ok and no5xx else 1
if __name__ == "__main__":
sys.exit(main())