forked from mtusi2026/mtusi2026lab5
86 lines
4.6 KiB
Python
86 lines
4.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Недоступность S3 (lab4). Сам останавливает и запускает MinIO; из корня репозитория:
|
|
|
|
python student-tests/s3_outage.py --base-url http://localhost:8080
|
|
|
|
Ожидание: пока MinIO остановлен, загрузка и скачивание дают быстрый 503 в формате
|
|
контракта (не зависание и не 500), а текстовая часть мессенджера, метаданные
|
|
вложений и /health/ready работают (S3 не критичен для обязательного текстового пути).
|
|
После старта MinIO всё снова работает, ранее загруженный файл не изменился.
|
|
Брошенная во время отказа запись журнала дочищается janitor после grace period.
|
|
"""
|
|
import argparse
|
|
import time
|
|
|
|
from common import wait_ready, SAMPLE_PNG, Api, Report, compose, janitor, sha256, tool, upload
|
|
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser()
|
|
ap.add_argument("--base-url", default="http://localhost:8080")
|
|
args = ap.parse_args()
|
|
api, r = Api(args.base_url), Report()
|
|
u = api.new_user("s3down")
|
|
T = u["token"]
|
|
st, chat, _ = api.call("POST", "/api/v1/chats", {"title": "s3 outage", "member_ids": [u["id"]]}, token=T)
|
|
st, before, _ = upload(api, T, chat["id"], SAMPLE_PNG, "before.png")
|
|
r.check(st == 202, "upload before outage")
|
|
r.check(wait_ready(api, T, before["id"], seconds=120).get("status") == "ready",
|
|
"it is processed to ready before the outage (lab5: 202 → worker)")
|
|
content = f"/api/v1/attachments/{before['id']}/content"
|
|
|
|
print("== MinIO остановлен ==")
|
|
compose("stop", "s3")
|
|
try:
|
|
t0 = time.monotonic()
|
|
st, body, _ = upload(api, T, chat["id"], SAMPLE_PNG, "during.png", timeout=30)
|
|
took = time.monotonic() - t0
|
|
r.check(st == 503 and body and body["error"]["code"] == "unavailable", f"upload -> 503 unavailable (got {st})")
|
|
r.check(took < 15, f"bounded by timeouts, not a hang ({took:.1f} s)")
|
|
st, _, _ = api.raw("GET", content, headers={"Authorization": "Bearer " + T}, timeout=30)
|
|
r.check(st == 503, f"download -> 503 (got {st})")
|
|
st, meta, _ = api.call("GET", f"/api/v1/attachments/{before['id']}", token=T)
|
|
r.check(st == 200 and meta["sha256"] == before["sha256"], "metadata still served from PostgreSQL")
|
|
st, _, _ = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", {"text": "S3 лежит, а чат работает"}, token=T)
|
|
r.check(st == 201, "text messages still work")
|
|
st, _, _ = api.call("POST", f"/api/v1/chats/{chat['id']}/messages",
|
|
{"text": "с вложением", "attachment_ids": [before["id"]]}, token=T)
|
|
r.check(st == 201, "message referencing an existing attachment still works (metadata only)")
|
|
r.check(api.raw("GET", "/health/ready")[0] == 200, "/health/ready = 200 (S3 is not critical for text path)")
|
|
finally:
|
|
compose("start", "s3")
|
|
|
|
print("== MinIO снова работает ==")
|
|
# После старта MinIO каждая реплика может ещё до S3_BREAKER_SECONDS (5 c) отвечать 503:
|
|
# предохранитель закрывается по таймеру. Поэтому ждём, пока ОБЕ реплики восстановятся:
|
|
# несколько успешных загрузок подряд (LB чередует реплики).
|
|
t0 = time.monotonic()
|
|
ok = False
|
|
for _ in range(40):
|
|
st, raw, _ = api.raw("GET", content, headers={"Authorization": "Bearer " + T})
|
|
if st == 200:
|
|
ok = sha256(raw) == before["sha256"]
|
|
break
|
|
time.sleep(0.5)
|
|
r.check(ok, "file uploaded before outage downloads unchanged")
|
|
streak, codes = 0, []
|
|
while time.monotonic() - t0 < 40 and streak < 4:
|
|
st, _, rh = upload(api, T, chat["id"], SAMPLE_PNG, "after.png")
|
|
codes.append(st)
|
|
streak = streak + 1 if st == 202 else 0
|
|
if st != 202:
|
|
time.sleep(0.5)
|
|
recovered = time.monotonic() - t0
|
|
r.check(streak >= 4, f"uploads work again on all replicas: 4 x 202 in a row after {recovered:.1f} s "
|
|
f"(codes during recovery: {codes})")
|
|
stats = tool("stats")
|
|
print(" stats:", stats)
|
|
s = janitor("--grace-seconds", "0")
|
|
r.check(s["errors"] == 0, f"janitor cleaned journal rows left by failed uploads ({s})")
|
|
r.finish()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|