Files
mtusi2026lab5/scripts/fault_injection_live.py
T
2026-11-24 17:58:42 +03:00

95 lines
3.3 KiB
Python

#!/usr/bin/env python3
"""Exercise worker crash failpoints against the running local Compose stack."""
import json
import os
from pathlib import Path
import subprocess
import sys
from urllib.parse import urlparse
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, LAB, check
def compose(args, env, timeout=90):
result = subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
env=env,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
timeout=timeout,
)
if result.returncode:
raise RuntimeError("docker compose failed: " + "\n".join(result.stdout.splitlines()[-25:]))
return result.stdout.strip()
def retry_record(attachment_id, env):
attachment_id = str(uuid.UUID(attachment_id))
query = (
"SELECT concat_ws('|',j.status,j.attempt::text,count(ja.id)::text,"
"coalesce(min(ja.outcome),'none')) "
"FROM jobs j LEFT JOIN job_attempts ja ON ja.job_id=j.id "
f"WHERE j.attachment_id='{attachment_id}' GROUP BY j.id"
)
return compose(
["exec", "-T", "postgres", "psql", "-X", "-A", "-t", "-U", "messenger", "-d", "messenger", "-c", query],
env,
timeout=15,
).strip()
def main():
if LAB < 5:
raise RuntimeError("live fault injection requires lab5")
base_url = os.environ.get("BASE_URL", "http://localhost:8080")
parsed = urlparse(base_url)
if not parsed.hostname:
raise ValueError("BASE_URL must be an absolute HTTP(S) URL")
env = dict(os.environ)
env["HTTP_PORT"] = str(parsed.port or (443 if parsed.scheme == "https" else 80))
env["WORKER_FAULT_INJECTION"] = ""
client = Client(base_url, timeout=10)
alice, _, _, chat = client.bootstrap()
results = []
try:
for stage in ("before_original_put", "after_original_put"):
compose(["stop", "worker"], env)
attachment, original = client.attachment(alice, chat)
injection_env = dict(env)
injection_env["WORKER_FAULT_INJECTION"] = f"{attachment['id']}:1:{stage}"
compose(["up", "-d", "--force-recreate", "worker"], injection_env)
ready = client.wait_ready(alice, attachment, wait_seconds=60)
downloaded = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
actor=alice,
)
check(downloaded["bytes"] == original, "original changed during injected retry")
check({item["name"] for item in ready["variants"]} == {"thumbnail", "crop", "optimized"},
"retry did not create all pipeline variants")
record = retry_record(attachment["id"], env)
check(record == "ready|2|1|retry", "injected crash did not recover through retry: " + record)
results.append({
"stage": stage,
"attachment_id": attachment["id"],
"status": ready["status"],
"job_retry_record": record,
"original_unchanged": True,
})
finally:
env["WORKER_FAULT_INJECTION"] = ""
compose(["up", "-d", "--force-recreate", "worker"], env)
print(json.dumps({"result": "PASS", "faults": results}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()