#!/usr/bin/env python3 """Недоступность S3 в lab5 (переписано из lab4 по аудиту F14: там ожидался синхронный 201). python3 student-tests/s3_outage.py --output evidence/s3-outage.json API (как в lab4): при остановленном (`stop`) и зависшем (`pause`) S3 upload и download — быстрый 503 unavailable с Retry-After, текстовые сообщения 201, /health/ready 200, GET метаданных 200. Worker (новое): задание, принятое ДО отказа S3, при обработке получает storage_unavailable и уходит в retry с backoff; после восстановления S3 оно доходит до ready. Если отказ длился дольше всех попыток — failed(retry_exhausted), и оператор делает replay (это тоже проверяется). """ import argparse import json import time import uuid from lab5lib import (Client, Log, SAMPLE_PNG, check, compose, events, ops, upload, wait_status, wait_until) def probe(c, alice, chat, att_ready, att_queued): out = {} calls = { "upload": ("POST", "/api/v1/chats/%s/attachments?filename=o.png" % chat["id"], {"raw": SAMPLE_PNG, "headers": {"Content-Type": "image/png"}}), "download_ready": ("GET", "/api/v1/attachments/%s/content" % att_ready["id"], {}), "metadata_queued": ("GET", "/api/v1/attachments/%s" % att_queued["id"], {}), "text_message": ("POST", "/api/v1/chats/%s/messages" % chat["id"], {"body": {"text": "без S3"}, "headers": {"Idempotency-Key": uuid.uuid4().hex}}), "ready": ("GET", "/health/ready", {}), } for name, (method, path, kw) in calls.items(): t = time.monotonic() r = c.call(method, path, [200, 201, 202, 503], actor=None if name == "ready" else alice, **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 s3_healthy(): cid = compose("ps", "-q", "s3").stdout.strip() import subprocess st = subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid], capture_output=True, text=True).stdout.strip() return st == "healthy" def main(): ap = argparse.ArgumentParser() ap.add_argument("--base-url", default="http://localhost:8080") ap.add_argument("--output") args = ap.parse_args() log = Log("S3 outage: API answers 503 fast, accepted jobs retry and complete") c = Client(args.base_url, timeout=30) alice, bob, _eve, chat = c.bootstrap() att_ready = c.wait_ready(alice, upload(c, alice, chat, SAMPLE_PNG, "before.png")) res = {} try: compose("stop", "worker") queued = upload(c, alice, chat, SAMPLE_PNG, "accepted-before-outage.png") log.step("worker stopped, job accepted before outage", attachment_id=queued["id"]) for action, undo in (("stop", "start"), ("pause", "unpause")): compose(action, "s3") time.sleep(5) # S3Health (1 с) заметил отказ, данные устарели (3 с) pr = probe(c, alice, chat, att_ready, queued) res["s3_" + action] = pr log.step("S3 `%s` for 5 s" % action, **pr) check(pr["upload"]["status"] == 503 and pr["download_ready"]["status"] == 503 and pr["text_message"]["status"] == 201 and pr["ready"]["status"] == 200 and pr["metadata_queued"]["status"] == 200, "API during S3 %s: %s" % (action, pr)) if action == "stop": compose("up", "-d", "--no-deps", "--no-recreate", "worker") info = wait_until(lambda: (lambda i: i if "retry_scheduled" in events(i) else None)( ops("inspect", queued["id"])), 60, 1, "worker retry on storage error") retries = [e["detail"] for e in info["events"] if e["event"] == "retry_scheduled"] res["worker_during_outage"] = {"events": events(info), "retries": retries} log.step("worker meets S3 outage -> retry with backoff", **res["worker_during_outage"]) check(all(r["error_code"] == "storage_unavailable" for r in retries), "retry reason") compose(undo, "s3") t0 = time.monotonic() wait_until(s3_healthy, 120, 1, "s3 healthy") log.step("S3 `%s` -> healthy" % undo, seconds=round(time.monotonic() - t0, 1)) final = wait_status(c, bob, queued["id"], {"ready", "failed"}, 120) replayed = None if final["status"] == "failed": check(final["error_code"] == "retry_exhausted", "unexpected failure " + str(final["error_code"])) replayed = ops("replay", queued["id"], "--reason", "S3 restored")["replay"][0]["result"] final = wait_status(c, bob, queued["id"], {"ready", "failed"}, 60) info = ops("inspect", queued["id"]) res["accepted_job"] = {"final": final["status"], "replay": replayed, "attempts": info["jobs"][0]["attempt"], "events": events(info)} check(final["status"] == "ready", "accepted job not completed") log.step("job accepted before outage completed", **res["accepted_job"]) after = c.wait_ready(alice, upload(c, alice, chat, SAMPLE_PNG, "after.png")) res["upload_after_recovery"] = after["status"] log.step("upload after recovery", status=after["status"]) finally: compose("unpause", "s3", ok=False) compose("start", "s3", ok=False) compose("up", "-d", "--no-deps", "--no-recreate", "--wait", "worker", ok=False) log.save(args.output, results=res) print("PASS: S3 outage handled by API (503) and worker (retry), accepted work completed") if __name__ == "__main__": main()