#!/usr/bin/env python3 """Fault adapters restricted to a disposable lab3 Compose project.""" import argparse import json import os from pathlib import Path import re import subprocess import sys import time import uuid ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "student-tests")) import stack # noqa: E402 def execute(argv, allow_failure=False, timeout=30): result = subprocess.run(argv, cwd=ROOT, capture_output=True, text=True, timeout=timeout) if result.returncode and not allow_failure: raise RuntimeError("test Docker action failed") return result def owned_project(): project = os.environ.get("COMPOSE_PROJECT_NAME", "") if not re.fullmatch(r"lab3-test-[a-f0-9]{12}", project): raise RuntimeError("fault hooks require an isolated lab3-test-* Compose project") if not os.environ.get("COMPOSE_FILE"): raise RuntimeError("COMPOSE_FILE must identify the isolated project override") return project, stack.compose_base(os.environ) def inspect(identifier): value = json.loads(execute(["docker", "inspect", identifier]).stdout) if len(value) != 1: raise RuntimeError("Docker inspect did not select one container") return value[0] def api_map(project, base): ids = execute(base + ["ps", "-aq", "api"]).stdout.split() if len(ids) != 2: raise RuntimeError("isolated project needs exactly two API containers") mapped = {} for identifier in ids: value = inspect(identifier) labels = value["Config"]["Labels"] if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "api": raise RuntimeError("API container ownership mismatch") alias = value["Config"]["Hostname"] if alias in mapped: raise RuntimeError("duplicate API alias") mapped[alias] = value return mapped def target(project, base): alias = os.environ.get("TARGET_INSTANCE_ID", "") mapped = api_map(project, base) if alias not in mapped: raise RuntimeError("TARGET_INSTANCE_ID is not an owned API alias") return mapped[alias] def wait_healthy(identifier, seconds=30): deadline = time.monotonic() + seconds while time.monotonic() < deadline: state = inspect(identifier)["State"] if state["Running"] and state.get("Health", {}).get("Status") == "healthy": return time.sleep(.2) raise RuntimeError("API did not regain Docker readiness") def state_network(project): name = os.environ.get("HL_STATE_NETWORK", "") if name != project + "_state": raise RuntimeError("state network must belong to isolated project") network = json.loads(execute(["docker", "network", "inspect", name]).stdout)[0] if network["Labels"].get("com.docker.compose.project") != project: raise RuntimeError("state network ownership mismatch") return name def http_status_inside(identifier, path): result = execute(["docker", "exec", identifier, "wget", "-S", "-O", "/dev/null", "http://127.0.0.1:8080" + path], allow_failure=True, timeout=5) found = re.findall(r"HTTP/\d(?:\.\d)?\s+(\d{3})", result.stderr + result.stdout) if not found: raise RuntimeError("cannot read internal HTTP status") return int(found[-1]) def lb_timing(): source = (ROOT / "infra/haproxy.cfg").read_text() check = re.search(r"timeout check\s+(\d+)s", source) server = re.search(r"server-template[^\n]*\binter\s+(\d+)s\s+fall\s+(\d+)", source) if not check or not server: raise RuntimeError("cannot derive LB health timing from HAProxy config") timeout, interval, failures = int(check[1]), int(server[1]), int(server[2]) print(json.dumps({"health_interval_seconds": interval, "health_timeout_seconds": timeout, "configured_max_detection_seconds": interval * failures + timeout})) def migration_evidence(project): path = Path(os.environ["HL_MIGRATION_EVIDENCE"]) value = json.loads(path.read_text()) if value.get("project") != project: raise RuntimeError("migration evidence belongs to another project") print(json.dumps(value)) def access_action(project, base, action): chat = str(uuid.UUID(os.environ["TEST_CHAT_ID"])) owner = str(uuid.UUID(os.environ["TEST_USER_ID"])) replacement = str(uuid.UUID(os.environ["TEST_REPLACEMENT_USER_ID"])) message = str(uuid.UUID(os.environ["TEST_MESSAGE_ID"])) key = os.environ["TEST_IDEMPOTENCY_KEY"] if owner == replacement or not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key): raise RuntimeError("invalid isolated access fixture") ids = execute(base + ["ps", "-q", "postgres"]).stdout.split() if len(ids) != 1: raise RuntimeError("isolated project must have exactly one running PostgreSQL") raw = inspect(ids[0]) labels = raw["Config"]["Labels"] if labels.get("com.docker.compose.project") != project or labels.get("com.docker.compose.service") != "postgres": raise RuntimeError("PostgreSQL container ownership mismatch") if action == "revoke_access": statement = f""" DO $lab3$ DECLARE affected integer; BEGIN IF (SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}') <> 1 OR (SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{replacement}') <> 1 OR (SELECT count(*) FROM messages WHERE chat_id='{chat}' AND sender_id='{owner}') <> 1 OR (SELECT count(*) FROM messages WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}') <> 1 OR (SELECT count(*) FROM message_idempotency WHERE user_id='{owner}' AND chat_id='{chat}' AND idempotency_key='{key}' AND message_id='{message}') <> 1 THEN RAISE EXCEPTION 'synthetic access fixture precondition failed'; END IF; UPDATE messages SET sender_id='{replacement}' WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}'; GET DIAGNOSTICS affected = ROW_COUNT; IF affected <> 1 THEN RAISE EXCEPTION 'message reassignment was not unique'; END IF; DELETE FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}'; GET DIAGNOSTICS affected = ROW_COUNT; IF affected <> 1 THEN RAISE EXCEPTION 'membership deletion was not unique'; END IF; END $lab3$; """ else: statement = f""" DO $lab3$ DECLARE affected integer; BEGIN INSERT INTO chat_members(chat_id,user_id) VALUES('{chat}','{owner}') ON CONFLICT DO NOTHING; UPDATE messages SET sender_id='{owner}' WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{replacement}'; GET DIAGNOSTICS affected = ROW_COUNT; IF affected > 1 OR (SELECT count(*) FROM chat_members WHERE chat_id='{chat}' AND user_id='{owner}') <> 1 OR (SELECT count(*) FROM messages WHERE id='{message}' AND chat_id='{chat}' AND sender_id='{owner}') <> 1 OR (SELECT count(*) FROM message_idempotency WHERE user_id='{owner}' AND chat_id='{chat}' AND idempotency_key='{key}' AND message_id='{message}') <> 1 THEN RAISE EXCEPTION 'synthetic access fixture restoration failed'; END IF; END $lab3$; """ execute(["docker", "exec", ids[0], "psql", "-X", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger", "-c", statement]) print(json.dumps({"action": action, "project": project, "chat_id": chat, "user_id": owner, "replacement_user_id": replacement, "message_id": message, "validated_exact_message": True, "membership_present_after": action == "restore_access"})) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("start_one", "recover_all", "sigterm_one", "probe_stopped", "make_unready", "restore_ready", "probe_health", "lb_timing_evidence", "migration_evidence", "revoke_access", "restore_access")) args = parser.parse_args() project, base = owned_project() action = args.action if action == "lb_timing_evidence": lb_timing() elif action == "migration_evidence": migration_evidence(project) elif action in ("revoke_access", "restore_access"): access_action(project, base, action) elif action == "recover_all": for value in api_map(project, base).values(): if not value["State"]["Running"]: execute(["docker", "start", value["Id"]]) wait_healthy(value["Id"]) else: value = target(project, base) identifier = value["Id"] if action == "start_one": if not value["State"]["Running"]: execute(["docker", "start", identifier]) wait_healthy(identifier) elif action == "sigterm_one": execute(["docker", "stop", "--time", "18", identifier], timeout=25) if inspect(identifier)["State"]["Running"]: raise RuntimeError("SIGTERM did not stop selected API") elif action == "probe_stopped": print(json.dumps({"accepting": bool(inspect(identifier)["State"]["Running"])})) elif action == "make_unready": execute(["docker", "network", "disconnect", state_network(project), identifier]) elif action == "restore_ready": execute(["docker", "network", "connect", state_network(project), identifier]) wait_healthy(identifier) elif action == "probe_health": print(json.dumps({"live_status": http_status_inside(identifier, "/health/live"), "ready_status": http_status_inside(identifier, "/health/ready")})) return 0 if __name__ == "__main__": try: raise SystemExit(main()) except (OSError, ValueError, KeyError, RuntimeError, subprocess.TimeoutExpired) as exc: print("FAIL: lab3 Docker action " + type(exc).__name__, file=sys.stderr) raise SystemExit(1)