forked from mtusi2026/mtusi2026lab4
222 lines
11 KiB
Python
222 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
"""Validate both repair directions and measure the scan on a dedicated lab4-final-grade5 project."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import shlex
|
|
import statistics
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import uuid
|
|
from urllib.parse import quote
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
sys.path.insert(0, str(ROOT / "tests"))
|
|
from client import Client, check
|
|
|
|
BUCKET = "messenger-attachments"
|
|
|
|
|
|
class Experiment:
|
|
def __init__(self, args):
|
|
self.root = args.stack.resolve()
|
|
self.base = ["docker", "compose", "-p", args.project, "--env-file", ".env"]
|
|
self.client = Client(args.base_url, timeout=15)
|
|
self.fixture = ROOT / "tests/fixtures/sample.png"
|
|
self.original = self.fixture.read_bytes()
|
|
self.digest = hashlib.sha256(self.original).hexdigest()
|
|
self.report = {}
|
|
self.prefix = "attachments/reconcile-" + uuid.uuid4().hex[:12]
|
|
self.output = args.output.resolve()
|
|
self.output.mkdir(parents=True, exist_ok=True)
|
|
|
|
def run(self, command, *, data=None, expected=0, timeout=60):
|
|
proc = subprocess.run(command, cwd=self.root, input=data, capture_output=True, timeout=timeout)
|
|
if proc.returncode != expected:
|
|
raise RuntimeError(f"unexpected exit {proc.returncode}, expected {expected}: {proc.stderr.decode(errors='replace')[-1200:]}")
|
|
return proc
|
|
|
|
def compose(self, *args, **kwargs):
|
|
return self.run(self.base + list(args), **kwargs)
|
|
|
|
def sql(self, statement):
|
|
return self.compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
|
"-X", "-At", "-v", "ON_ERROR_STOP=1", "-c", statement).stdout.decode().strip()
|
|
|
|
def s3(self, method, key, status, body=None, conditional=False):
|
|
access = (self.root / "secrets/s3_access_key_id").read_text().strip()
|
|
secret = (self.root / "secrets/s3_secret_access_key").read_text().strip()
|
|
command = ["exec", "-T", "s3", "curl", "--config", "-", "-sS", "--max-time", "10",
|
|
"-o", "/dev/null", "-w", "%{http_code}", "--aws-sigv4", "aws:amz:us-east-1:s3"]
|
|
command += ["--head"] if method == "HEAD" else ["-X", method]
|
|
if body is not None:
|
|
command += ["--data-binary", body]
|
|
if conditional:
|
|
command += ["-H", "If-None-Match: *"]
|
|
command += ["http://127.0.0.1:9000/" + BUCKET + "/" + quote(key, safe="/")]
|
|
result = self.compose(*command, data=f'user = "{access}:{secret}"\n'.encode())
|
|
check(int(result.stdout) == status, f"S3 {method} returned {result.stdout!r}, want {status}")
|
|
|
|
def command(self, flags, *, extra=(), expected=0):
|
|
start = time.monotonic()
|
|
proc = self.compose("run", "--rm", "--no-deps", "-T", *extra, "attachment-cleanup",
|
|
"/app/attachment-cleanup", *flags, expected=expected, timeout=150)
|
|
report = json.loads(proc.stdout)
|
|
check(report["complete"] == (expected == 0), "incorrect complete flag")
|
|
report["wall_ms"] = round((time.monotonic() - start) * 1000, 2)
|
|
return report
|
|
|
|
def scan(self, dry=True, grace="4s", **kwargs):
|
|
return self.command(["-reconcile", f"-dry-run={str(dry).lower()}", "-grace-period=" + grace], **kwargs)
|
|
|
|
def restore(self, aid, path, dry, expected=0):
|
|
return self.command(["-restore-id", aid, "-backup-file", "/backup", "-grace-period=4s",
|
|
f"-dry-run={str(dry).lower()}"],
|
|
extra=("-v", f"{path.resolve()}:/backup:ro"), expected=expected)
|
|
|
|
def key(self, aid):
|
|
aid = str(uuid.UUID(aid))
|
|
key = self.sql(f"SELECT object_key FROM attachments WHERE id='{aid}'")
|
|
check(re.fullmatch(r"attachments/[0-9a-f-]+", key), "unexpected application key")
|
|
return key
|
|
|
|
def faults(self):
|
|
self.compose("stop", "attachment-cleanup")
|
|
alice, bob, eve, chat = self.client.bootstrap()
|
|
self.owner_id, self.chat_id = str(uuid.UUID(alice["id"])), str(uuid.UUID(chat["id"]))
|
|
missing, _ = self.client.attachment(alice, chat)
|
|
orphan, _ = self.client.attachment(alice, chat)
|
|
used, _ = self.client.attachment(alice, chat)
|
|
unused, _ = self.client.attachment(alice, chat)
|
|
msg = self.client.message(alice, chat, "", attachments=[used["id"], missing["id"]])["json"]
|
|
|
|
missing_key, orphan_key, used_key, unused_key = map(self.key, (missing["id"], orphan["id"], used["id"], unused["id"]))
|
|
self.sql(f"DELETE FROM attachments WHERE id='{uuid.UUID(orphan['id'])}'")
|
|
self.s3("DELETE", missing_key, 204)
|
|
self.client.call("GET", "/api/v1/attachments/" + missing["id"] + "/content", 404, actor=bob)
|
|
self.client.call("GET", "/api/v1/attachments/" + missing["id"], actor=bob, schema="Attachment")
|
|
|
|
time.sleep(5)
|
|
fresh = self.prefix + "-fresh"
|
|
self.s3("PUT", fresh, 200, body="fresh")
|
|
dry = self.scan()
|
|
check(dry["orphan_scan"]["orphan_candidates"] == 1 and dry["orphan_scan"]["objects_deleted"] == 0,
|
|
"dry-run must find exactly the old orphan")
|
|
check(dry["missing_scan"]["missing_attachment_ids"] == [missing["id"]], "wrong missing ID")
|
|
self.s3("HEAD", orphan_key, 200)
|
|
self.s3("HEAD", missing_key, 404)
|
|
|
|
with tempfile.NamedTemporaryFile() as wrong:
|
|
wrong.write(b"X" + self.original[1:])
|
|
wrong.flush()
|
|
os.chmod(wrong.name, 0o644)
|
|
rejected = self.restore(missing["id"], Path(wrong.name), False, expected=1)
|
|
self.s3("HEAD", missing_key, 404)
|
|
restore_dry = self.restore(missing["id"], self.fixture, True)
|
|
check(restore_dry["restore"] == "would_restore", "dry-run restore did not detect missing object")
|
|
self.s3("HEAD", missing_key, 404)
|
|
restored = self.restore(missing["id"], self.fixture, False)
|
|
check(restored["restore"] == "restored", "restore did not recreate original")
|
|
again = self.restore(missing["id"], self.fixture, False)
|
|
check(again["restore"] == "already_present", "repeat restore changed object")
|
|
self.s3("PUT", missing_key, 412, body="must not overwrite", conditional=True)
|
|
|
|
# Use a separate young key so the grace check is deterministic at apply time.
|
|
self.s3("DELETE", fresh, 204)
|
|
self.s3("PUT", fresh, 200, body="fresh")
|
|
applied = self.scan(False)
|
|
check(applied["orphan_scan"]["objects_deleted"] == 1 and applied["missing_scan"]["missing_objects"] == 0,
|
|
"apply did not reconcile both directions")
|
|
self.s3("HEAD", orphan_key, 404)
|
|
self.s3("HEAD", fresh, 200)
|
|
self.s3("HEAD", used_key, 200)
|
|
self.s3("HEAD", unused_key, 200)
|
|
self.s3("DELETE", fresh, 204)
|
|
repeated = self.scan(False)
|
|
check(repeated["orphan_scan"]["orphan_candidates"] == repeated["orphan_scan"]["objects_deleted"] ==
|
|
repeated["missing_scan"]["missing_objects"] == 0, "repeat performed unexpected work")
|
|
|
|
resource = "/api/v1/attachments/" + missing["id"]
|
|
received = self.client.call("GET", resource + "/content", actor=bob)
|
|
check(hashlib.sha256(received["bytes"]).hexdigest() == self.digest, "restored bytes changed")
|
|
check(self.client.call("GET", resource, schema="Attachment", actor=bob)["json"] == missing, "metadata changed")
|
|
self.client.call("GET", resource + "/content", 404, actor=eve)
|
|
history = self.client.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=bob)
|
|
check(msg in json.loads(history["bytes"])["items"], "restored attachment link changed")
|
|
|
|
outage = self.scan(extra=("-e", "S3_ENDPOINT=http://127.0.0.1:1"), expected=1)
|
|
check("orphan_scan" not in outage and outage["missing_scan"]["missing_objects"] == 0, "outage classified as missing")
|
|
self.report["faults"] = {
|
|
"injected": ["delete PostgreSQL row", "delete S3 object", "S3 connection refused"],
|
|
"dry_run": dry, "bad_backup_rejected": rejected, "restore_dry_run": restore_dry,
|
|
"restore": restored, "repeat_restore": again, "conditional_existing_put_status": 412,
|
|
"apply": applied, "repeat": repeated, "s3_outage": outage,
|
|
"fresh_preserved": True, "linked_preserved": True, "unlinked_preserved": True,
|
|
"sha256": self.digest, "message_and_metadata_preserved": True, "outsider_status": 404,
|
|
}
|
|
|
|
def seed(self, start, end):
|
|
access = (self.root / "secrets/s3_access_key_id").read_text().strip()
|
|
secret = (self.root / "secrets/s3_secret_access_key").read_text().strip()
|
|
check(re.fullmatch(r"[a-f0-9]+", access) and re.fullmatch(r"[a-f0-9]+", secret), "expected synthetic credentials")
|
|
seed_script = f"""
|
|
set -eu
|
|
export AUTH={shlex.quote(access + ':' + secret)} PREFIX={shlex.quote(self.prefix)}
|
|
seq {start} {end} | xargs -P 8 -n 1 sh -c 'curl -fsS --max-time 10 -o /dev/null --aws-sigv4 aws:amz:us-east-1:s3 -u "$AUTH" -X PUT --data-binary x "http://127.0.0.1:9000/{BUCKET}/$PREFIX-$1"' sh
|
|
"""
|
|
self.compose("exec", "-T", "s3", "sh", data=seed_script.encode(), timeout=120)
|
|
self.sql(f"""INSERT INTO attachments(chat_id, owner_id, filename, object_key, content_type, size_bytes, sha256, created_at)
|
|
SELECT '{self.chat_id}', '{self.owner_id}', 'synthetic.png', '{self.prefix}-' || i, 'image/png', 1,
|
|
'{hashlib.sha256(b"x").hexdigest()}', now() - interval '1 minute'
|
|
FROM generate_series({start}, {end}) AS i""")
|
|
|
|
def cost(self):
|
|
stages = []
|
|
size = 0
|
|
for target in (30, 230, 1050):
|
|
self.seed(size + 1, target)
|
|
size = target
|
|
# S3 LastModified may have second resolution. Exclude the boundary.
|
|
time.sleep(2.1)
|
|
runs = [self.scan(grace="1s") for _ in range(3)]
|
|
for run in runs:
|
|
check(run["orphan_scan"]["objects_scanned"] == size + 3, "unexpected object count")
|
|
check(run["orphan_scan"]["checked_in_db"] == size + 3, "not all object keys checked")
|
|
check(run["missing_scan"]["s3_head_attempts"] == size + 3, "not all DB keys checked")
|
|
check(run["orphan_scan"]["orphan_candidates"] == run["missing_scan"]["missing_objects"] == 0, "benchmark has anomalies")
|
|
stages.append({"synthetic_pairs": size, "measured_pairs": size + 3, "runs": runs,
|
|
"median_scan_ms": statistics.median(run["duration_ms"] for run in runs)})
|
|
self.report["cost"] = stages
|
|
self.save()
|
|
|
|
def save(self):
|
|
(self.output / "reconcile.json").write_text(json.dumps(self.report, ensure_ascii=False, indent=2) + "\n")
|
|
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument("--stack", type=Path, required=True)
|
|
p.add_argument("--project", required=True)
|
|
p.add_argument("--base-url", required=True)
|
|
p.add_argument("--output", type=Path, required=True)
|
|
args = p.parse_args()
|
|
if not re.fullmatch(r"lab4-final-grade5(?:-[a-z0-9-]+)?", args.project):
|
|
p.error("use an empty disposable lab4-final-grade5 project")
|
|
experiment = Experiment(args)
|
|
try:
|
|
experiment.faults()
|
|
experiment.save()
|
|
experiment.cost()
|
|
finally:
|
|
experiment.save()
|
|
print("PASS: bidirectional reconciliation, preservation, repeated apply, and cost profiles")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|