Files
mtusi2026lab6/student-tests/s3_outage.py
T

144 lines
7.1 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: деградация только операций с файлами, восстановление без рестарта API.
python student-tests/s3_outage.py --base-url http://127.0.0.1:8080 --output evidence/s3_outage.json
По умолчанию останавливает/запускает сервис s3 через docker compose и ждёт
прогрева чтения/записи (python scripts/ops.py wait-s3). Для другого стенда —
--stop-cmd / --start-cmd. Тома не удаляются.
Ожидаемое поведение (S3 НЕ входит в readiness, см. REPORT.md):
* /health/ready = 200, обе реплики остаются в LB;
* регистрация, вход, сообщения и история — работают;
* GET метаданных вложения — 200 (это PostgreSQL);
* POST вложения и GET /content -> 503 unavailable (+ Retry-After) за ограниченное
время (таймауты клиента S3); pending-строку удаляет компенсация
(проверяется в test_attachment_consistency.py через api-fault-s3);
* после возврата S3 тот же токен загружает и скачивает файлы, старый файл цел.
"""
import argparse
import hashlib
import http.client
import json
import os
import shlex
import subprocess
import sys
import time
import uuid
from pathlib import Path
from urllib.parse import urlparse
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import common # noqa: E402
import imagegen # noqa: E402
from common import actor, create_chat, request # noqa: E402
ROOT = HERE.parent
MAX_FAIL_SECONDS = 15.0 # connect 2 с x 2 попытки + backoff; ответ клиенту не позже
class Check:
def __init__(self):
self.results = []
def __call__(self, name, ok, detail=""):
self.results.append({"check": name, "ok": bool(ok), "detail": detail})
print(("PASS " if ok else "FAIL ") + name + (" — " + detail if detail else ""), flush=True)
def run(cmd):
print("$ " + " ".join(cmd), flush=True)
subprocess.run(cmd, cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180)
def upload(token, chat_id, data):
return request("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat_id, token=token, raw=data,
headers={"Content-Type": "image/png"}, timeout=40)
def download(token, att_id):
u = urlparse(common.BASE_URL)
conn = http.client.HTTPConnection(u.hostname, u.port or 80, timeout=40)
t = time.monotonic()
conn.request("GET", "/api/v1/attachments/%s/content" % att_id, headers={"Authorization": "Bearer " + token})
r = conn.getresponse()
body = r.read()
conn.close()
return r.status, body, time.monotonic() - t, r.headers
def main():
p = argparse.ArgumentParser()
p.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
py = sys.executable or "python3"
p.add_argument("--stop-cmd", default="docker compose --env-file .env stop s3")
p.add_argument("--start-cmd", default="docker compose --env-file .env start s3")
p.add_argument("--wait-cmd", default="%s scripts/ops.py wait-s3" % shlex.quote(py))
p.add_argument("--output")
args = p.parse_args()
common.BASE_URL = args.base_url.rstrip("/")
check = Check()
alice, bob = actor("s3o_a"), actor("s3o_b")
chat = create_chat(alice, bob)
original = imagegen.sample_png()
r = upload(alice["_token"], chat["id"], original)
check("baseline upload 202 (lab5)", r.status == 202, str(r.status))
att = common.wait_ready(alice["_token"], r.json["id"]) # lab5: обработку делает worker
run(shlex.split(args.stop_cmd))
try:
ready = request("GET", "/health/ready")
check("readiness stays 200 while S3 is down (S3 is not a readiness dependency)", ready.status == 200,
str(ready.status))
m = request("POST", "/api/v1/chats/%s/messages" % chat["id"], token=alice["_token"],
payload={"text": "S3 лежит, а чат работает"}, headers={"Idempotency-Key": uuid.uuid4().hex})
check("text message 201 during S3 outage", m.status == 201, str(m.status))
h = request("GET", "/api/v1/chats/%s/messages?limit=10" % chat["id"], token=bob["_token"])
check("history 200 during S3 outage", h.status == 200, str(h.status))
meta = request("GET", "/api/v1/attachments/" + att["id"], token=bob["_token"])
check("attachment metadata 200 (PostgreSQL only)", meta.status == 200, str(meta.status))
ref = request("POST", "/api/v1/chats/%s/messages" % chat["id"], token=alice["_token"],
payload={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
check("message referencing existing attachment 201", ref.status == 201, str(ref.status))
for i in range(2):
u = upload(alice["_token"], chat["id"], imagegen.png(10 + i, 10))
code = (u.json or {}).get("error", {}).get("code")
check("upload #%d -> 503 unavailable" % (i + 1), u.status == 503 and code == "unavailable",
"%s %s in %.2fs" % (u.status, code, u.elapsed))
check("upload #%d failed fast (<= %.0fs)" % (i + 1, MAX_FAIL_SECONDS), u.elapsed <= MAX_FAIL_SECONDS,
"%.2fs" % u.elapsed)
check("upload #%d has Retry-After" % (i + 1), bool(u.headers.get("Retry-After")))
status, _, elapsed, _ = download(bob["_token"], att["id"])
check("download -> 503 during outage", status == 503, "%s in %.2fs" % (status, elapsed))
check("download failed fast", elapsed <= MAX_FAIL_SECONDS, "%.2fs" % elapsed)
me = request("GET", "/api/v1/users/me", token=alice["_token"])
check("session still valid", me.status == 200, str(me.status))
finally:
run(shlex.split(args.start_cmd))
t0 = time.monotonic()
run(shlex.split(args.wait_cmd))
recovered = round(time.monotonic() - t0, 2)
check("S3 read/write warm-up after start", True, "%.2fs" % recovered)
status, body, elapsed, headers = download(bob["_token"], att["id"])
check("old file downloads byte-for-byte after recovery",
status == 200 and hashlib.sha256(body).hexdigest() == att["sha256"], "%s %.2fs" % (status, elapsed))
u = upload(alice["_token"], chat["id"], imagegen.png(12, 12))
check("new upload 202 after recovery (same token, no API restart)", u.status == 202, str(u.status))
report = {"scenario": "S3 outage and recovery", "max_fail_seconds": MAX_FAIL_SECONDS,
"s3_warmup_seconds": recovered, "checks": check.results,
"pass": all(c["ok"] for c in check.results)}
if args.output:
Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print("PASS" if report["pass"] else "FAIL")
sys.exit(0 if report["pass"] else 1)
if __name__ == "__main__":
main()