Files
mtusi2026lab5/student-tests/stand.py
T
alenchha 633fb96920 ЛР 5 — БВТ2301 — Курлова — на 5
RabbitMQ + transactional outbox, отдельный worker (thumbnail/crop/WebP), lease и heartbeat, retry с backoff+jitter, DLQ и replay, admission control; тесты отказов, трек 1 и отчёт.
2026-11-06 12:10:16 +03:00

133 lines
5.1 KiB
Python
Executable File

"""Helpers for student resilience tests: the public HTTP client plus docker compose / psql / mc access.
Standard library only (Python 3.9+). Images that need Pillow are generated inside the API container.
Never prints tokens or secrets.
"""
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
from urllib.parse import quote
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run # noqa: E402,F401
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def log(*parts):
print(time.strftime("%H:%M:%S"), *parts, flush=True)
def compose(*args, check_rc=True, capture=True, timeout=180):
done = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=capture, text=True, timeout=timeout)
if check_rc and done.returncode != 0:
raise Failure("docker compose %s failed: %s" % (" ".join(args[:2]), (done.stderr or "")[-300:]))
return done.stdout if capture else ""
def started_at(*services):
"""Container name -> State.StartedAt, proof that a restart really happened."""
ids = compose("ps", "-q", *services).split()
out = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.StartedAt}}", *ids],
capture_output=True, text=True).stdout
return "; ".join(line.strip("/")[:60] for line in out.splitlines())
def sql(query):
"""Run a read query in postgres; returns rows as lists of strings (tab separated)."""
out = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-F", "\t", "-c", query)
return [line.split("\t") for line in out.splitlines() if line]
def s3_keys(prefix):
"""Object keys starting with prefix, listed with the root credentials inside a throwaway minio-init container."""
wanted, prefix = prefix, prefix[:prefix.rfind("/") + 1]
script = ('mc alias set l http://minio:9000 "$(cat /run/secrets/minio_root_user)" '
'"$(cat /run/secrets/minio_root_password)" >/dev/null && '
'mc ls --recursive --json l/messenger-attachments/%s || true' % prefix)
out = compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "sh", "minio-init", "-c", script)
keys = []
for line in out.splitlines():
try:
item = json.loads(line)
except ValueError:
continue
if item.get("key"):
keys.append(prefix + item["key"])
return sorted(k for k in keys if k.startswith(wanted))
def queue_depth(queue="attachments.process"):
out = compose("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "--vhost", "messenger", "list_queues",
"name", "messages", "messages_ready", "messages_unacknowledged")
for line in out.splitlines():
parts = line.split()
if parts and parts[0] == queue:
return {"messages": int(parts[1]), "ready": int(parts[2]), "unacked": int(parts[3])}
return None
def wait_queue(min_ready=1, seconds=30):
"""Quorum queue counters are refreshed by the stats emitter (~5 s), so poll."""
deadline = time.monotonic() + seconds
depth = None
while time.monotonic() < deadline:
depth = queue_depth()
if depth and depth["ready"] >= min_ready:
return depth
time.sleep(1)
return depth
def jobs_cli(*args):
done = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "scripts/jobs.py", *args],
cwd=ROOT, capture_output=True, text=True, timeout=60)
return done.returncode, json.loads(done.stdout) if done.stdout.strip() else None
def wait_http_ready(c, seconds=120):
deadline = time.monotonic() + seconds
while time.monotonic() < deadline:
try:
c.call("GET", "/health/ready", 200)
return
except Failure:
time.sleep(1)
raise Failure("API not ready after %ds" % seconds)
def upload(c, actor, chat, body=SAMPLE, filename="sample.png", ctype="image/png", expected=202):
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
schema = "Attachment" if expected == 202 else None
return c.call("POST", path, expected, actor=actor, raw=body, headers={"Content-Type": ctype}, schema=schema)["json"]
def get(c, actor, att_id):
return c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
def wait_status(c, actor, att_id, statuses, seconds=120):
deadline = time.monotonic() + seconds
seen = []
while time.monotonic() < deadline:
att = get(c, actor, att_id)
if not seen or seen[-1] != att["status"]:
seen.append(att["status"])
if att["status"] in statuses:
return att, seen
time.sleep(0.5)
raise Failure("attachment %s did not reach %s in %ds (seen %s)" % (att_id, statuses, seconds, seen))
def objects_of(att_id):
return s3_keys("attachments/%s/" % att_id) + s3_keys("staging/%s" % att_id)
def unique_name(fault=None):
tag = uuid.uuid4().hex[:8]
return ("fault-%s-%s.png" % (fault, tag)) if fault else ("plain-%s.png" % tag)