Files
mtusi2026lab4/scripts/s3_outage.py
T

86 lines
2.8 KiB
Python

"""Stop MinIO, observe ready=503, start it again, and read the same bytes."""
import hashlib
import json
import subprocess
import time
import urllib.error
import urllib.request
from pathlib import Path
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check # noqa: E402
FIXTURE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
def status(path: str) -> int:
try:
with urllib.request.urlopen("http://127.0.0.1:8080" + path, timeout=15) as response:
return response.status
except urllib.error.HTTPError as exc:
return exc.code
def wait_ready(expected: int) -> None:
deadline = time.time() + 90
last = None
while time.time() < deadline:
try:
last = status("/health/ready")
except Exception:
last = None
if last == expected:
return
time.sleep(1)
raise SystemExit(f"ready did not become {expected}; last={last}")
def main() -> None:
client = Client("http://127.0.0.1:8080", timeout=20)
alice = client.user("out_alice")
bob = client.user("out_bob")
chat = client.call(
"POST",
"/api/v1/chats",
201,
actor=alice,
body={"title": "Отказ S3", "member_ids": [alice["id"], bob["id"]]},
schema="Chat",
)["json"]
uploaded = client.call(
"POST",
f"/api/v1/chats/{chat['id']}/attachments?filename=outage.png",
201,
actor=alice,
raw=FIXTURE,
headers={"Content-Type": "image/png"},
schema="Attachment",
)["json"]
subprocess.check_call(["docker", "compose", "--env-file", ".env", "stop", "-t", "2", "minio"], cwd=ROOT)
time.sleep(2)
live = status("/health/live")
ready = status("/health/ready")
check(live == 200, "liveness failed while S3 was stopped")
check(ready == 503, "readiness stayed 200 while S3 was stopped")
subprocess.check_call(["docker", "compose", "--env-file", ".env", "start", "minio"], cwd=ROOT)
wait_ready(200)
downloaded = client.call("GET", "/api/v1/attachments/" + uploaded["id"] + "/content", actor=bob)
check(downloaded["bytes"] == FIXTURE, "original changed after the S3 restart")
check(hashlib.sha256(downloaded["bytes"]).hexdigest() == uploaded["sha256"], "checksum changed after S3 restart")
report = {"live_while_s3_down": live, "ready_while_s3_down": ready, "download_after_start": "match"}
dest = ROOT / "evidence" / "s3_outage.json"
dest.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(json.dumps(report, ensure_ascii=False))
print("PASS: S3 outage fails readiness and preserves the original")
if __name__ == "__main__":
try:
main()
except Exception as exc:
print("FAIL:", exc)
raise SystemExit(1)