Files
mtusi2026lab4/student-tests/lab4/attachment_runtime_faults.py

90 lines
4.1 KiB
Python

import argparse
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys
import time
sys.path.insert(0, str(Path.cwd() / "tests"))
from client import Client, check
parser = argparse.ArgumentParser(description="Check attachment failover and S3 outage on a disposable stack")
parser.add_argument("--base-url", required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--probe", type=Path, required=True, help="Path to the Linux direct HTTP probe")
parser.add_argument("--probe-image", required=True, help="Locally built API image used to run the probe")
args = parser.parse_args()
project = os.environ["COMPOSE_PROJECT_NAME"]
if not project.startswith("lab4-final-"):
parser.error("use an isolated lab4-final-* project")
c = Client(args.base_url, timeout=3)
compose = ["docker", "compose", "--env-file", ".env"]
out = args.output
out.mkdir(parents=True, exist_ok=True)
def run(*argv, **kw):
return subprocess.run(argv, check=True, capture_output=True, timeout=65, **kw).stdout
def sql(query):
return run(*compose, "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-Atqc", query).decode().strip()
def ready():
end = time.monotonic()+30
while time.monotonic()<end:
try:
return c.call("GET", "/health/ready", schema="Health")
except AssertionError:
time.sleep(.2)
raise AssertionError("API did not recover")
def direct(cid, method, path, data=b"", token=None):
request = (f"{method} {path} HTTP/1.1\n" + (token or "") + "\n").encode()+data
response=json.loads(run("docker","run","--rm","-i","--network","container:"+cid,
"-v",str(args.probe.resolve())+":/direct:ro","--entrypoint","/direct",args.probe_image,input=request))
check(response["instance"], "response from API expected")
return response["status"],response["body"].encode()
def download(bob, att, data):
end = time.monotonic()+20
failures = 0
start=time.monotonic()
while time.monotonic()<end:
try:
saved=c.call("GET","/api/v1/attachments/"+att["id"]+"/content",actor=bob)
check(saved["bytes"]==data, "download changed")
return {"replica":saved["headers"]["X-Instance-Id"], "failures":failures, "seconds":round(time.monotonic()-start,3),"sha256":hashlib.sha256(data).hexdigest()}
except AssertionError:
failures+=1
time.sleep(.2)
raise AssertionError("download recovery timed out")
alice,bob,_,chat=c.bootstrap()
att,data=c.attachment(alice,chat)
phase = c.call("POST", "/api/v1/chats/"+chat["id"]+"/attachments?filename=failover.png",201,actor=alice,raw=data,headers={"Content-Type":"image/png"},schema="Attachment")
instance=phase["headers"]["X-Instance-Id"]
run("sh","scripts/stop-one.sh",env=dict(os.environ,TARGET_INSTANCE_ID=instance))
try:
failover=download(bob,phase["json"],data)
check(failover["replica"]!=instance,"same replica served failover")
finally:
run(*compose, "up", "-d","--no-build","--wait","api","lb")
(out/"file-failover.json").write_text(json.dumps({"source":instance,**failover},indent=2)+"\n")
cid=run(*compose,"ps","-q","api").decode().splitlines()[0]
before=sql("SELECT count(*) FROM attachments")
run(*compose, "stop", "-t", "10", "s3")
try:
live,_=direct(cid,"GET","/health/live")
rd,_=direct(cid,"GET","/health/ready")
upload,body=direct(cid,"POST","/api/v1/chats/"+chat["id"]+"/attachments?filename=outage.png",data,alice["token"])
print("outage statuses",live,rd,upload,flush=True)
check((live,rd,upload)==(200,503,503) and b'unavailable' in body, "wrong API outage statuses")
check(sql("SELECT count(*) FROM attachments")==before,"outage created an attachment row")
finally:
run(*compose,"start","s3")
ready()
saved=download(bob,att,data)
(out/"s3-failure.json").write_text(json.dumps({"fault":"s3_unreachable","live_status":live,"ready_status":rd,"upload_status":upload,"false_ready_attachments":0,"restored_original_checksum_equal":saved["sha256"]==att["sha256"]},indent=2)+"\n")
print("PASS: file failover and actual S3 outage/recovery")