Files
mtusi2026lab5/student-tests/lab5/pipeline_action.py
T

478 lines
21 KiB
Python
Executable File

#!/usr/bin/env python3
"""Fault adapter for the Lab 5 Compose implementation, only on an isolated project."""
import json
import os
import re
from pathlib import Path
import subprocess
import sys
import time
import uuid
sys.dont_write_bytecode = True
from compose_action import API, DB, PROJECT, ROOT
HERE = Path(__file__).resolve().parent
BROKER = os.environ.get("LAB5_TEST_BROKER", "rabbitmq")
WORKER = os.environ.get("LAB5_TEST_WORKER", "worker")
RELAY = os.environ.get("LAB5_TEST_RELAY", "relay")
CLEANER = os.environ.get("LAB5_TEST_CLEANUP", "attachment-cleanup")
POINTS = {"commit-before-publish": ("before_publish", RELAY),
"publish-before-mark": ("after_publish", RELAY),
"object-before-ack": ("after_objects", WORKER),
"ready-before-ack": ("before_ack", WORKER)}
ORIGINAL = (ROOT / "tests/fixtures/sample.png").read_bytes()
S3_SETUP = """set -eu
rc=/usr/bin/rc
"$rc" alias set app http://s3:9000 "$(cat /run/secrets/s3_access_key_id)" \
"$(cat /run/secrets/s3_secret_access_key)" --bucket-lookup path \
--region "$S3_REGION" >/dev/null
"""
S3_RC = S3_SETUP + """for prefix do
"$rc" bucket list --recursive --json "app/$S3_BUCKET/$prefix"
done
"""
class Unsupported(Exception):
pass
def require(ok, message):
if not ok:
raise RuntimeError(message)
def run(argv, label, timeout=30, allow_fail=False):
try:
r = subprocess.run(argv, cwd=ROOT, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
except subprocess.TimeoutExpired:
raise RuntimeError(f"{label}: exceeded {timeout}s") from None
require(allow_fail or r.returncode == 0, f"{label}: exit {r.returncode}")
return r
def until(fn, label, seconds=24):
end = time.monotonic() + seconds
while time.monotonic() < end:
try:
value = fn()
except (RuntimeError, ValueError):
value = None
if value:
return value
time.sleep(0.2)
raise RuntimeError(label)
def compose(*args, label=None, timeout=30, allow_fail=False):
files = json.loads(os.environ.get("LAB5_TEST_COMPOSE_FILES", "[]"))
cmd = ["docker", "compose", "--project-name", PROJECT]
for file in files:
cmd += ["-f", file]
return run(cmd + list(args), label or "compose " + args[0], timeout, allow_fail)
def sql(query):
return compose("exec", "-T", DB, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-At",
"-U", os.environ["LAB5_TEST_DB_USER"], "-d", os.environ["LAB5_TEST_DB_NAME"],
"-c", query, label="fixture SQL").stdout.decode().strip()
def one_container(service):
rows = compose("ps", "-aq", service).stdout.decode().split()
require(len(rows) == 1, f"expected one {service} in isolated project")
return rows[0]
def start(*services):
# Start the existing containers only. Compose start can also rerun a finished
# one-shot dependency, which would invalidate the migration experiment.
ids = [one_container(service) for service in services]
run(["docker", "start", *ids], "start selected containers")
def set_storage_net(attached):
cid = one_container(WORKER)
net = PROJECT + "_lab5_object"
current = json.loads(run(["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", cid],
"worker networks").stdout)
if attached and net not in current:
run(["docker", "network", "connect", "--alias", WORKER, net, cid], "restore worker S3 network")
if not attached and net in current:
run(["docker", "network", "disconnect", net, cid], "isolate worker S3 network")
def marker_dir():
path = Path(os.environ.get("LAB5_TEST_FAULT_HOST_DIR", "/nonexistent")).resolve()
if not path.is_dir() or not (path / ".lab5-test-project").is_file():
raise Unsupported("set a dedicated fault directory with .lab5-test-project marker")
require((path / ".lab5-test-project").read_text().strip() == PROJECT, "fault directory belongs to another project")
return path
def clean_point(point):
for suffix in ("arm", "used", "hit", "release"):
p = marker_dir() / f"{point}.{suffix}"
if p.exists():
p.unlink()
def broker_ctl(command, *columns):
return compose("exec", "-T", "-e", "RABBITMQ_CTL_ERL_ARGS=+S 1:1 +A 1", BROKER,
"rabbitmqctl", command, "-p", "messenger", "--quiet", "--formatter", "json",
*columns, label="RabbitMQ " + command, timeout=20)
def queue(name="image.jobs"):
r = broker_ctl("list_queues", "name", "durable", "messages_ready", "messages_unacknowledged", "consumers").stdout
rows = json.loads(r)
image = [row for row in rows if row["name"] == name]
require(len(image) == 1 and image[0]["durable"] is True, "expected durable queue not found")
return image[0]
def snapshot(att):
row = sql(f"""
SELECT json_build_object(
'job_id', j.id, 'jobs', (SELECT count(*) FROM attachment_jobs WHERE attachment_id=a.id),
'outbox', (SELECT count(*) FROM outbox WHERE job_id=j.id),
'published', (SELECT count(*) FROM outbox WHERE job_id=j.id AND sent_at IS NOT NULL),
'status', a.status, 'max_attempts', j.max_attempts,
'failed_registered', a.status='failed' AND a.error_code IS NOT NULL,
'generation', j.lease_generation, 'original_key', a.object_key,
'has_staging_ref', a.staging_key IS NOT NULL,
'processing_age_seconds', (SELECT extract(epoch FROM clock_timestamp()-r.started_at)
FROM attachment_attempts r WHERE r.job_id=j.id AND r.lease_generation=j.lease_generation),
'variant_keys', COALESCE((SELECT json_object_agg(name, object_key) FROM attachment_variants
WHERE attachment_id = a.id AND pipeline_version = j.pipeline_version), '{{}}'),
'audit_replays', (SELECT count(*) FROM attachment_replays WHERE job_id=j.id),
'envelope_valid', EXISTS (SELECT 1 FROM outbox o WHERE o.job_id=j.id AND
o.payload->>'schema_version'='1' AND o.payload->>'type'='attachment.process.v1'
AND o.payload->>'job_id'=j.id::text AND o.payload->>'attachment_id'=a.id::text
AND o.payload->>'attempt'='1' AND o.payload->>'pipeline_version'=j.pipeline_version::text
AND (o.payload - ARRAY['schema_version','type','job_id','attachment_id','attempt','pipeline_version',
'created_at','traceparent','tracestate']) = '{{}}'::jsonb),
'attempts', COALESCE((SELECT json_agg(json_build_object(
'attempt', r.attempt,
'kind', CASE r.outcome WHEN 'ready' THEN 'success' WHEN 'retry' THEN 'temporary'
WHEN 'failed' THEN CASE WHEN r.error_code='retry_exhausted' THEN 'temporary' ELSE 'permanent' END
WHEN 'lease_expired' THEN 'lease_expired' ELSE 'processing' END,
'delay_seconds', extract(epoch FROM o.available_at-r.finished_at), 'error_code', r.error_code
) ORDER BY r.attempt) FROM attachment_attempts r LEFT JOIN outbox o
ON o.dedup_key = 'retry/' || j.id || '/' || (r.attempt + 1) WHERE r.job_id=j.id), '[]')
)
FROM attachments a JOIN attachment_jobs j ON j.attachment_id=a.id AND j.pipeline_version=a.pipeline_version
WHERE a.id='{att}';
""")
require(row and "\n" not in row, "expected exactly one pipeline observation")
return json.loads(row)
def list_key_sets(*prefixes):
r = compose("run", "--no-deps", "--rm", "-T", "--entrypoint", "/bin/sh", "s3-init",
"-c", S3_RC, "lab5-test", *prefixes, label="list synthetic S3 prefixes", timeout=20)
source = r.stdout.decode().lstrip()
decoder = json.JSONDecoder()
sets = []
for prefix in prefixes:
page, offset = decoder.raw_decode(source)
source = source[offset:].lstrip()
require(page.get("truncated") is False and isinstance(page.get("items"), list),
"S3 prefix listing is incomplete")
keys = {entry["key"] for entry in page["items"] if not entry["is_dir"]}
require(all(key.startswith(prefix) for key in keys), "S3 response escaped the fixture prefix")
sets.append(keys)
require(not source, "unexpected S3 output after the requested listings")
return sets
def runtime():
cid = one_container(WORKER)
fields = run(["docker", "inspect", "-f", "{{json .Config.Env}}\t{{.HostConfig.Memory}}", cid],
"worker limits").stdout.decode().strip().split("\t")
env, mem = json.loads(fields[0]), int(fields[1])
settings = dict(x.split("=", 1) for x in env if "=" in x)
def value(names, default):
return next((int(settings[n]) for n in names if n in settings), default)
return {"worker_memory_bytes": mem,
"concurrency": value(("WORKER_CONCURRENCY",), 1),
"prefetch": value(("WORKER_PREFETCH", "JOB_PREFETCH"), 1),
"lease_seconds": value(("JOB_LEASE_SECONDS", "WORKER_LEASE_SECONDS"), 90),
"job_timeout_seconds": value(("JOB_TIMEOUT_SECONDS", "WORKER_TIMEOUT_SECONDS"), 60),
"retry_base_seconds": value(("JOB_RETRY_BASE_SECONDS", "WORKER_RETRY_BASE_SECONDS"), 2)}
def worker_limits():
settings = runtime()
r = compose("exec", "-T", WORKER, "magick", "-list", "resource", label="ImageMagick policy")
limits = dict((name.strip(), val.strip()) for line in r.stdout.decode().splitlines()
if ":" in line for name, val in [line.split(":", 1)])
settings["image_limits"] = {key: limits.get(key, "") for key in ("Memory", "Map", "Disk", "Thread", "Time")}
r = broker_ctl("list_consumers")
rows = json.loads(r.stdout)
settings["consumers"] = [
{"prefetch": row["prefetch_count"], "ack_required": row["ack_required"], "active": row["active"]}
for row in rows if row["queue_name"] == "image.jobs"
]
return settings
def retry_delays_ms(job_id):
cid = one_container(WORKER)
# Preserve only the observed scheduling values, never container logs.
output = run(["docker", "logs", cid], "worker retry delay evidence")
delays = []
for line in (output.stderr + output.stdout).decode().splitlines():
if "job retry scheduled" not in line:
continue
if line.startswith("{"):
item = json.loads(line)
if item.get("job_id") == job_id and item.get("msg") == "job retry scheduled":
delays.append(int(item["delay_ms"]))
elif f"job_id={job_id}" in line:
match = re.search(r"\bdelay_ms=(\d+)", line)
require(match is not None, "worker retry log did not record jitter")
delays.append(int(match.group(1)))
return delays
def inspect(att):
row = snapshot(att)
staging, results = list_key_sets(f"staging/{att}/", f"results/{att}/")
keys = row.pop("variant_keys")
original = row.pop("original_key")
row["staging_exists"] = f"staging/{att}/original" in staging
row["variant_objects"] = sorted(name for name in keys if keys[name] in results)
row["original_exists"] = original in results
row["result_count"] = len(results)
row["scheduled_delays_ms"] = retry_delays_ms(row["job_id"]) if any(
attempt["delay_seconds"] is not None for attempt in row["attempts"]) else []
row.update(runtime())
return row
def restart_broker_with_pending():
# Stop the relay so it cannot republish a lost message during recovery.
compose("stop", "-t", "4", RELAY)
before = until(lambda: (q if (q := queue())["messages_ready"] > 0 and q["consumers"] == 0 else None),
"expected a durable broker delivery before restart")
cid = one_container(BROKER)
run(["docker", "restart", "--time", "8", cid], "physical RabbitMQ restart", timeout=70)
after = until(queue, "durable queue did not reappear", seconds=45)
require(after["messages_ready"] == before["messages_ready"] and after["consumers"] == 0,
"accepted broker deliveries did not survive restart")
return {"broker_before": before, "broker_after": after}
def drained():
def empty():
value = queue()
return value if value["consumers"] > 0 and value["messages_ready"] == 0 and value["messages_unacknowledged"] == 0 else None
return until(empty, "broker delivery was not acknowledged/drained", seconds=45)
def await_publication(outbox_id):
until(lambda: sql(f"SELECT sent_at IS NOT NULL FROM outbox WHERE id='{outbox_id}'") == "t",
"fixture delivery not confirmed")
return drained()
def publish_fixture(att, field=None, *, version=None):
dedup = "test_delivery/" + str(uuid.uuid4())
payload = "o.payload"
if field in ("attachment_id", "job_id"):
payload = f"jsonb_set(o.payload, '{{{field}}}', to_jsonb('{uuid.uuid4()}'::text))"
elif field == "pipeline_version":
payload = "jsonb_set(o.payload, '{pipeline_version}', to_jsonb(j.pipeline_version+1))"
version_filter = "" if version is None else f" AND j.pipeline_version={int(version)}"
row = sql(f"""INSERT INTO outbox(job_id,payload,available_at,dedup_key)
SELECT o.job_id,{payload}, clock_timestamp(), '{dedup}' FROM outbox o
JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='{att}'{version_filter}
ORDER BY o.created_at, o.id LIMIT 1 RETURNING id""").splitlines()
require(len(row) == 2 and row[1] == "INSERT 0 1", "unable to insert fixture delivery")
outbox_id = str(uuid.UUID(row[0]))
await_publication(outbox_id)
return outbox_id
def invalid_job(att):
before = queue("image.invalid")["messages_ready"]
for field in ("attachment_id", "job_id", "pipeline_version"):
publish_fixture(att, field)
after = until(lambda: (n if (n := queue("image.invalid")["messages_ready"]) == before+3 else None),
"invalid delivery was not rejected to DLQ")
return {"dead_letters_before": before, "dead_letters_after": after}
def failed(att):
row = snapshot(att)
result = compose("exec", "-T", CLEANER, "/app/jobs", "failed", label="list failed via operator CLI")
values = json.loads(result.stdout)
require(isinstance(values, list) and any(r["job_id"] == row["job_id"] and r["attachment_id"] == att
for r in values),
"failed job absent from operator registry")
def replay(att):
default = [CLEANER, "/app/jobs", "replay", "-job-id", "{job_id}", "-request-id", "{request_id}",
"-operator", "test", "-reason", "acceptance", "-extra-attempts", "1"]
# JSON argv with explicitly recognized substitutions; shell is never used.
cmd = json.loads(os.environ["LAB5_TEST_REPLAY_CMD"]) if os.environ.get("LAB5_TEST_REPLAY_CMD") else default
row = snapshot(att)
mapping = {"{job_id}": row["job_id"], "{attachment_id}": att, "{request_id}": str(uuid.uuid4())}
argv = [mapping.get(x, x) for x in cmd]
result = compose("exec", "-T", *argv, label="operator replay")
data = json.loads(result.stdout)
require(data["job_id"] == row["job_id"] and data["replayed"] is (row["status"] == "failed"),
"operator replay did not report the expected status")
return {"accepted": data["replayed"], "request_id": mapping["{request_id}"], "job_id": row["job_id"]}
def wait_marker(label, att):
point, _ = POINTS[label]
job = snapshot(att)["job_id"]
hit = marker_dir() / (point + ".hit")
matched = until(lambda: hit.read_text().strip() if hit.is_file() else None,
"instrumented process did not reach intended fault")
require(matched == job, "fault marker matched a different job")
return hit, {"point": label, "attachment_id": att, "job_id": matched}
def crash_observed(label, att):
point, service = POINTS[label]
cid = one_container(service)
hit, evidence = wait_marker(label, att)
row = snapshot(att)
expected = {"commit-before-publish": "queued", "publish-before-mark": "queued",
"object-before-ack": "processing", "ready-before-ack": "ready"}[label]
require(row["status"] == expected, "attachment state does not match held crash boundary")
if expected == "queued":
require(row["published"] == 0 and row["outbox"] == 1, "outbox is not committed and unsent")
if expected != "ready":
require(row["has_staging_ref"], "staging reference removed before safe completion")
if expected == "processing":
age_limit = runtime()["job_timeout_seconds"] - row["processing_age_seconds"]
else:
age_limit = None
marker_mtime = hit.stat().st_mtime
started = time.monotonic()
# Read state and signal consecutively, within the actual fault window.
# The relay timeout starts slightly before the marker (transaction setup).
limit = 6 if expected == "queued" else 25
if expected == "processing":
require(age_limit > 0.3, "worker deadline expired before the crash")
else:
require(time.time() - marker_mtime < limit, "fault marker expired before the crash")
require(not (marker_dir() / (point + ".release")).exists(), "fault point was released")
run(["docker", "kill", "--signal", "KILL", cid], "kill at held fault marker", timeout=5)
elapsed = time.monotonic() - started
if expected == "processing":
require(elapsed < age_limit, "worker deadline elapsed before SIGKILL")
else:
require(time.time() - marker_mtime < limit, "fault window elapsed before SIGKILL")
stored = None
try:
if expected == "processing":
stored = len(list_key_sets(f"results/{att}/")[0])
require(stored >= 4, "S3 did not contain the written output set at worker crash")
finally:
clean_point(point)
start(service)
evidence.update(container=cid, signal="SIGKILL", status=expected, generation=row["generation"],
attempts=row["attempts"], outbox=row["outbox"], published=row["published"],
result_count=stored, kill_elapsed_s=elapsed)
return evidence
def main():
require(bool(PROJECT) and PROJECT != "highload-lab5", "explicit disposable project required")
marker_dir()
command, *args = sys.argv[1:]
if command == "reset":
services = set(compose("config", "--services").stdout.decode().split())
if not {WORKER, RELAY, BROKER} <= services:
raise Unsupported("worker, relay and broker are not configured")
for point, _ in POINTS.values():
hit = marker_dir() / (point + ".hit")
if hit.exists():
(marker_dir() / (point + ".release")).touch()
(marker_dir() / (point + ".arm")).unlink(missing_ok=True)
start(BROKER, RELAY, WORKER)
set_storage_net(True)
return None
if command == "worker-limits":
return worker_limits()
if command == "drain":
return drained()
if command == "worker-stop":
compose("stop", "-t", "5", WORKER)
elif command == "worker-start":
start(WORKER)
elif command == "relay-start":
start(RELAY)
elif command == "restart-apis":
old = compose("ps", "-q", API).stdout.decode().split()
require(len(old) >= 2, "need two real API containers to restart")
def starts():
return {i: run(["docker", "inspect", "-f", "{{.State.StartedAt}}", i],
"API StartedAt").stdout.decode().strip() for i in old}
before = starts()
run(["docker", "restart", "--time", "8", *old], "restart APIs")
after = starts()
require(all(after[i] != before[i] for i in old), "not all APIs restarted")
return {"started_before": before, "started_after": after}
elif command == "broker-restart":
return restart_broker_with_pending()
elif command == "arm" and args[0] in POINTS:
point, _ = POINTS[args[0]]
clean_point(point)
(marker_dir() / (point + ".arm")).touch(exist_ok=False)
elif command == "await":
return wait_marker(args[0], str(uuid.UUID(args[1])))[1]
elif command == "crash":
return crash_observed(args[0], str(uuid.UUID(args[1])))
elif command == "arm" and args[0] == "retry-transient":
set_storage_net(False)
elif command == "clear" and args[0] == "retry-transient":
set_storage_net(True)
elif command == "arm" and args[0] == "fail-permanent":
compose("stop", "-t", "5", WORKER)
elif command in ("activate", "clear") and args[0] == "fail-permanent":
att = str(uuid.UUID(args[1]))
if command == "activate":
value = "0" * 64
else:
import hashlib
value = hashlib.sha256(ORIGINAL).hexdigest()
require(sql(f"UPDATE attachments SET sha256='{value}' WHERE id='{att}' RETURNING id").splitlines() ==
[att, "UPDATE 1"],
"could not inject/restore staging checksum fault")
if command == "activate":
start(WORKER)
elif command == "activate" and args[0] == "retry-transient":
pass
elif command in ("inspect", "redeliver", "replay", "failed", "invalid-job"):
att = str(uuid.UUID(args[0]))
return {"inspect": inspect, "redeliver": publish_fixture, "replay": replay,
"failed": failed, "invalid-job": invalid_job}[command](att)
else:
raise Unsupported("pipeline action unavailable")
return None
if __name__ == "__main__":
try:
result = main()
if result is not None:
print(json.dumps(result))
except Unsupported as exc:
print(str(exc), file=sys.stderr)
sys.exit(78)
except (RuntimeError, OSError, ValueError, subprocess.TimeoutExpired) as exc:
print("pipeline adapter:", exc if isinstance(exc, RuntimeError) else type(exc).__name__, file=sys.stderr)
sys.exit(1)