forked from mtusi2026/mtusi2026lab5
ЛР5: асинхронная обработка вложений (RabbitMQ + worker), transactional outbox, варианты, трек 5.1
This commit is contained in:
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade-4 failure scenarios for the lab5 attachment pipeline.
|
||||
|
||||
Each scenario is explicit and reproducible:
|
||||
1. worker-stopped accept: 202 while no worker, resume -> ready;
|
||||
2. outbox gap: broker down at COMMIT -> job stays unpublished -> API restart
|
||||
-> broker returns -> ready (no new task needed);
|
||||
3. retry/replay: repeated transient failures -> failed(retry_exhausted) ->
|
||||
operator replay after recovery -> ready;
|
||||
4. redelivery of a ready job is a no-op (variants not duplicated);
|
||||
5. lease recovery: a stuck 'processing' job is requeued by the watchdog.
|
||||
|
||||
Run from the repository root (docker CLI + running lab5 stand).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
|
||||
|
||||
def _png_chunk(tag, data):
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def make_png(width=320, height=200):
|
||||
raw = bytearray()
|
||||
pixels = os.urandom(width * height * 3)
|
||||
for row in range(height):
|
||||
raw.append(0)
|
||||
raw += pixels[row * width * 3 : (row + 1) * width * 3]
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _png_chunk(b"IHDR", ihdr) + _png_chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _png_chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def http(method, path, token=None, body=None, raw=None, content_type=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
return 0, b""
|
||||
|
||||
|
||||
def compose(*args, check=True):
|
||||
return subprocess.run(["docker", "compose", *args], check=check, capture_output=True, text=True)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-tAc", sql],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def service_running(name: str) -> bool:
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "ps", "--status", "running", "--format", "{{.Service}}"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
return name in result.stdout.split()
|
||||
|
||||
|
||||
def storage_reachable() -> bool:
|
||||
# Raw TCP probe (bypasses the app's circuit breaker, which cannot be used to
|
||||
# decide whether the store is really down).
|
||||
result = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "api", "python", "-c",
|
||||
"import socket,sys; socket.create_connection(('s3',8333),1); sys.exit(0)"],
|
||||
capture_output=True, text=True, timeout=30,
|
||||
)
|
||||
return result.returncode == 0
|
||||
|
||||
|
||||
def wait_storage_down(timeout: float = 60.0) -> None:
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if not storage_reachable():
|
||||
return
|
||||
time.sleep(1)
|
||||
raise SystemExit("S3 still reachable; cannot run the failure scenario")
|
||||
|
||||
|
||||
def wait_ready(timeout=90.0):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if http("GET", "/health/ready")[0] == 200:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise SystemExit("stand did not become ready")
|
||||
|
||||
|
||||
def new_actor():
|
||||
username = "fail_" + uuid.uuid4().hex[:8]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
http("POST", "/api/v1/users", body={"username": username, "display_name": "Fail", "password": password})
|
||||
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
token = json.loads(response.read())["token"]
|
||||
user_id = json.loads(http("GET", "/api/v1/users/me", token=token)[1])["id"]
|
||||
chat = json.loads(http("POST", "/api/v1/chats", token=token, body={"title": "fail", "member_ids": [user_id]})[1])
|
||||
return token, chat["id"]
|
||||
|
||||
|
||||
def upload(token, chat_id, data=None):
|
||||
data = data if data is not None else make_png()
|
||||
status, body = http("POST", f"/api/v1/chats/{chat_id}/attachments?filename=x.png", token=token, raw=data, content_type="image/png")
|
||||
assert status == 202, (status, body)
|
||||
return json.loads(body)["id"]
|
||||
|
||||
|
||||
def status_of(token, attachment_id):
|
||||
return json.loads(http("GET", f"/api/v1/attachments/{attachment_id}", token=token)[1])
|
||||
|
||||
|
||||
def wait_status(token, attachment_id, wanted, timeout=120.0):
|
||||
deadline = time.time() + timeout
|
||||
last = None
|
||||
while time.time() < deadline:
|
||||
last = status_of(token, attachment_id)
|
||||
if last["status"] == wanted:
|
||||
return last
|
||||
time.sleep(0.5)
|
||||
raise SystemExit(f"attachment {attachment_id} did not reach {wanted}: {last}")
|
||||
|
||||
|
||||
def scenario_worker_stopped(log):
|
||||
log("\n== scenario 1: accept while worker stopped, resume -> ready ==")
|
||||
compose("stop", "worker")
|
||||
try:
|
||||
token, chat_id = new_actor()
|
||||
att_id = upload(token, chat_id)
|
||||
time.sleep(2)
|
||||
state = status_of(token, att_id)
|
||||
log(f"with worker stopped: status={state['status']} (expected queued)")
|
||||
assert state["status"] == "queued", state
|
||||
compose("restart", "api")
|
||||
wait_ready()
|
||||
log("API restarted; work still queued (durable)")
|
||||
assert status_of(token, att_id)["status"] == "queued"
|
||||
finally:
|
||||
compose("start", "worker")
|
||||
ready = wait_status(token, att_id, "ready")
|
||||
names = sorted(v["name"] for v in ready["variants"])
|
||||
log(f"worker resumed: status=ready variants={names}")
|
||||
assert {"thumbnail", "crop", "optimized"} <= set(names)
|
||||
|
||||
|
||||
def scenario_outbox_gap(log):
|
||||
log("\n== scenario 2: COMMIT/publish gap (broker down), API restart, then broker ==")
|
||||
compose("stop", "broker")
|
||||
try:
|
||||
token, chat_id = new_actor()
|
||||
att_id = upload(token, chat_id)
|
||||
time.sleep(2)
|
||||
job = psql(f"select published_at from attachment_jobs where attachment_id='{att_id}'")
|
||||
log(f"broker down: status={status_of(token, att_id)['status']} published_at={job!r} (expected empty)")
|
||||
assert status_of(token, att_id)["status"] in {"queued", "processing"}
|
||||
compose("restart", "api")
|
||||
wait_ready()
|
||||
log("API restarted with broker still down; intent preserved in PostgreSQL")
|
||||
finally:
|
||||
compose("start", "broker")
|
||||
ready = wait_status(token, att_id, "ready", timeout=180)
|
||||
log(f"broker back: status={ready['status']} (outbox republished without new task)")
|
||||
|
||||
|
||||
def scenario_retry_replay(log):
|
||||
log("\n== scenario 3: transient failures -> failed(retry_exhausted) -> replay ==")
|
||||
compose("stop", "worker")
|
||||
while service_running("worker"):
|
||||
time.sleep(0.5)
|
||||
token, chat_id = new_actor()
|
||||
att_id = upload(token, chat_id)
|
||||
original_key = psql(f"select staging_key from attachments where id='{att_id}'")
|
||||
# Fault injection: the durable original is (temporarily) unavailable, so the
|
||||
# worker's fetch fails and is retried with backoff until attempts are spent.
|
||||
psql(f"update attachments set staging_key='staging/missing-{att_id}' where id='{att_id}'")
|
||||
log("injected: staging object points to a missing key (transient fetch failure)")
|
||||
compose("start", "worker")
|
||||
failed = wait_status(token, att_id, "failed", timeout=180)
|
||||
log(f"status=failed error_code={failed['error_code']} (expected retry_exhausted)")
|
||||
assert failed["error_code"] == "retry_exhausted", failed
|
||||
# Operator repairs the cause and replays the failed job explicitly.
|
||||
psql(f"update attachments set staging_key='{original_key}' where id='{att_id}'")
|
||||
job_id = att_id_job(att_id)
|
||||
replayed = subprocess.run(
|
||||
["docker", "compose", "exec", "-T", "api", "python", "-m", "src.replay", job_id],
|
||||
capture_output=True, text=True,
|
||||
).stdout.strip()
|
||||
log(f"explicit replay after recovery: {replayed}")
|
||||
ready = wait_status(token, att_id, "ready", timeout=120)
|
||||
log(f"after replay: status=ready variants={sorted(v['name'] for v in ready['variants'])}")
|
||||
|
||||
|
||||
def att_id_job(attachment_id):
|
||||
return psql(f"select job_id from attachment_jobs where attachment_id='{attachment_id}'")
|
||||
|
||||
|
||||
def scenario_redelivery(log):
|
||||
log("\n== scenario 4: redelivery of a ready job is a no-op ==")
|
||||
token, chat_id = new_actor()
|
||||
att_id = upload(token, chat_id)
|
||||
ready = wait_status(token, att_id, "ready")
|
||||
before = sorted((v["name"], v["sha256"]) for v in ready["variants"])
|
||||
# Republish the finished job (duplicate delivery).
|
||||
psql(f"update attachment_jobs set status='pending', published_at=null, available_at=now() where attachment_id='{att_id}'")
|
||||
log("re-queued the same job (duplicate delivery)")
|
||||
time.sleep(6)
|
||||
after = status_of(token, att_id)
|
||||
after_variants = sorted((v["name"], v["sha256"]) for v in after["variants"])
|
||||
log(f"status={after['status']} variants={[n for n,_ in after_variants]} (must be unchanged)")
|
||||
assert after["status"] == "ready"
|
||||
assert after_variants == before, "duplicate delivery changed variants"
|
||||
|
||||
|
||||
def scenario_lease_recovery(log):
|
||||
log("\n== scenario 5: stuck processing -> lease recovery ==")
|
||||
compose("stop", "worker")
|
||||
token, chat_id = new_actor()
|
||||
att_id = upload(token, chat_id)
|
||||
job_id = att_id_job(att_id)
|
||||
# Simulate a worker that died mid-processing with an already-expired lease.
|
||||
psql(f"update attachments set status='processing' where id='{att_id}'")
|
||||
psql(f"update attachment_jobs set status='processing', lease_until=now() - interval '5 seconds' where job_id='{job_id}'")
|
||||
log("marked attachment+job processing with an expired lease")
|
||||
compose("start", "worker")
|
||||
ready = wait_status(token, att_id, "ready", timeout=120)
|
||||
log(f"watchdog requeued and finished the job: status={ready['status']}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--only", choices=["1", "2", "3", "4", "5"], help="run one scenario")
|
||||
args = parser.parse_args()
|
||||
wait_ready()
|
||||
|
||||
def log(message):
|
||||
print(message, flush=True)
|
||||
|
||||
scenarios = {
|
||||
"1": scenario_worker_stopped,
|
||||
"2": scenario_outbox_gap,
|
||||
"3": scenario_retry_replay,
|
||||
"4": scenario_redelivery,
|
||||
"5": scenario_lease_recovery,
|
||||
}
|
||||
if args.only:
|
||||
scenarios[args.only](log)
|
||||
else:
|
||||
for name in ("1", "2", "3", "4", "5"):
|
||||
scenarios[name](log)
|
||||
print("\nPASS: lab5 grade-4 failure scenarios" + (f" (scenario {args.only})" if args.only else ""))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,243 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 5.1 - the attachment queue under overload.
|
||||
|
||||
Hypothesis: raising worker concurrency increases throughput and shortens
|
||||
time-to-ready up to a point, after which CPU contention (Pillow resizing) and
|
||||
memory set the ceiling; the durable queue lets the API keep accepting (202) and
|
||||
bounds in-flight work, then drains and recovers afterwards.
|
||||
|
||||
Method (reproducible):
|
||||
* for each (concurrency, image size) pair, recreate the worker with a fixed
|
||||
WORKER_CONCURRENCY, submit a burst of uploads, and poll every attachment
|
||||
until ready;
|
||||
* record accepted/errors, throughput, p50/p95 time-to-ready, queue depth over
|
||||
time (backpressure) and peak worker RSS (docker stats);
|
||||
* after the largest burst, wait for the queue to drain and confirm a fresh
|
||||
upload still becomes ready quickly (recovery).
|
||||
|
||||
Output: a JSON document plus a readable table. Run from the repository root.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import struct
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
BASE = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
||||
RESULTS = []
|
||||
|
||||
|
||||
def _chunk(tag, data):
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def make_png(width, height):
|
||||
raw = bytearray()
|
||||
pixels = os.urandom(width * height * 3)
|
||||
stride = width * 3
|
||||
for row in range(height):
|
||||
raw.append(0)
|
||||
raw += pixels[row * stride : (row + 1) * stride]
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(bytes(raw), 0)) + _chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def http(method, path, token=None, body=None, raw=None, content_type=None):
|
||||
headers = {"Accept": "application/json"}
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
headers["Content-Type"] = "application/json"
|
||||
if content_type:
|
||||
headers["Content-Type"] = content_type
|
||||
if token:
|
||||
headers["Authorization"] = "Bearer " + token
|
||||
request = urllib.request.Request(BASE + path, data=data, headers=headers, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=30) as response:
|
||||
return response.status, response.read()
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read()
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
return 0, b""
|
||||
|
||||
|
||||
def login():
|
||||
username = "q_" + uuid.uuid4().hex[:8]
|
||||
password = "T3st-" + uuid.uuid4().hex
|
||||
http("POST", "/api/v1/users", body={"username": username, "display_name": "Q", "password": password})
|
||||
credential = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
request = urllib.request.Request(
|
||||
BASE + "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + credential, "Accept": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=20) as response:
|
||||
token = json.loads(response.read())["token"]
|
||||
user_id = json.loads(http("GET", "/api/v1/users/me", token=token)[1])["id"]
|
||||
chat = json.loads(http("POST", "/api/v1/chats", token=token, body={"title": "q", "member_ids": [user_id]})[1])
|
||||
return token, chat["id"]
|
||||
|
||||
|
||||
def worker_mem_mb():
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}|{{.MemUsage}}"],
|
||||
capture_output=True, text=True).stdout
|
||||
for line in out.splitlines():
|
||||
name, _, usage = line.partition("|")
|
||||
if "worker" not in name:
|
||||
continue
|
||||
value = usage.split("/")[0].strip()
|
||||
number = "".join(ch for ch in value if ch.isdigit() or ch == ".")
|
||||
if value.endswith("GiB"):
|
||||
return float(number) * 1024
|
||||
if value.endswith("MiB"):
|
||||
return float(number)
|
||||
return 0.0
|
||||
|
||||
|
||||
def set_worker_concurrency(value):
|
||||
env = dict(os.environ, WORKER_CONCURRENCY=str(value))
|
||||
subprocess.run(["docker", "compose", "up", "-d", "--force-recreate", "worker"],
|
||||
env=env, check=True, capture_output=True, text=True)
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def percentile(values, pct):
|
||||
if not values:
|
||||
return 0.0
|
||||
ordered = sorted(values)
|
||||
index = min(len(ordered) - 1, int(round((pct / 100.0) * (len(ordered) - 1))))
|
||||
return ordered[index]
|
||||
|
||||
|
||||
def run_case(concurrency, size_name, width, height, count, submit_workers=8):
|
||||
set_worker_concurrency(concurrency)
|
||||
token, chat_id = login()
|
||||
payload = make_png(width, height)
|
||||
|
||||
pending = {}
|
||||
codes = {}
|
||||
lock = threading.Lock()
|
||||
|
||||
def submit(_):
|
||||
status, body = http("POST", f"/api/v1/chats/{chat_id}/attachments?filename=q.png", token=token,
|
||||
raw=payload, content_type="image/png")
|
||||
with lock:
|
||||
codes[status] = codes.get(status, 0) + 1
|
||||
if status != 202:
|
||||
return
|
||||
attachment_id = json.loads(body)["id"]
|
||||
with lock:
|
||||
pending[attachment_id] = time.time()
|
||||
|
||||
queue_samples = []
|
||||
stop = threading.Event()
|
||||
peak = {"value": worker_mem_mb()}
|
||||
|
||||
def sampler():
|
||||
while not stop.is_set():
|
||||
with lock:
|
||||
depth = len(pending)
|
||||
queue_samples.append(depth)
|
||||
peak["value"] = max(peak["value"], worker_mem_mb())
|
||||
time.sleep(0.2)
|
||||
|
||||
thread = threading.Thread(target=sampler, daemon=True)
|
||||
thread.start()
|
||||
submit_start = time.time()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, min(submit_workers, count))) as pool:
|
||||
list(pool.map(submit, range(count)))
|
||||
submit_done = time.time()
|
||||
latencies = []
|
||||
deadline = time.time() + 300
|
||||
while pending and time.time() < deadline:
|
||||
with lock:
|
||||
ids = list(pending.keys())
|
||||
for attachment_id in ids:
|
||||
status, body = http("GET", f"/api/v1/attachments/{attachment_id}", token=token)
|
||||
if status != 200:
|
||||
continue
|
||||
state = json.loads(body)["status"]
|
||||
if state in {"ready", "failed"}:
|
||||
with lock:
|
||||
started = pending.pop(attachment_id, None)
|
||||
if started is not None:
|
||||
latencies.append((time.time() - started, state))
|
||||
time.sleep(0.2)
|
||||
stop.set()
|
||||
thread.join(timeout=2)
|
||||
|
||||
ready = [lat for lat, state in latencies if state == "ready"]
|
||||
failed = [lat for lat, state in latencies if state == "failed"]
|
||||
result = {
|
||||
"concurrency": concurrency,
|
||||
"size": size_name,
|
||||
"bytes": len(payload),
|
||||
"submitted": count,
|
||||
"accepted": codes.get(202, 0),
|
||||
"errors": sum(v for k, v in codes.items() if k != 202),
|
||||
"codes": codes,
|
||||
"ready": len(ready),
|
||||
"failed": len(failed),
|
||||
"submit_seconds": round(submit_done - submit_start, 2),
|
||||
"drain_seconds": round(time.time() - submit_done, 2),
|
||||
"throughput_per_s": round(len(ready) / max(0.001, time.time() - submit_start), 2),
|
||||
"p50_ready_s": round(statistics.median(ready), 2) if ready else None,
|
||||
"p95_ready_s": round(percentile(ready, 95), 2) if ready else None,
|
||||
"max_queue_depth": max(queue_samples) if queue_samples else 0,
|
||||
"worker_peak_mem_mb": round(peak["value"], 1),
|
||||
}
|
||||
RESULTS.append(result)
|
||||
print(json.dumps(result, ensure_ascii=False), flush=True)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--count", type=int, default=12)
|
||||
parser.add_argument("--output", default="evidence/lab5-overload.json")
|
||||
args = parser.parse_args()
|
||||
|
||||
os.makedirs(os.path.dirname(args.output), exist_ok=True)
|
||||
plan = [
|
||||
(1, "small", 640, 480, 8),
|
||||
(2, "small", 640, 480, 8),
|
||||
(4, "small", 640, 480, 8),
|
||||
(1, "large", 2200, 1500, 4),
|
||||
(2, "large", 2200, 1500, 4),
|
||||
(4, "large", 2200, 1500, 4),
|
||||
]
|
||||
for concurrency, size_name, width, height, workers in plan:
|
||||
run_case(concurrency, size_name, width, height, args.count, submit_workers=workers)
|
||||
|
||||
# Recovery: after the heaviest cases the queue must drain and a fresh upload
|
||||
# must still be served promptly.
|
||||
set_worker_concurrency(2)
|
||||
token, chat_id = login()
|
||||
fresh = run_case(2, "recovery", 800, 600, 1)
|
||||
drained = fresh["ready"] == 1 and fresh["p95_ready_s"] is not None and fresh["p95_ready_s"] < 30
|
||||
|
||||
with open(args.output, "w", encoding="utf-8") as handle:
|
||||
json.dump({"results": RESULTS, "recovered": drained}, handle, ensure_ascii=False, indent=2)
|
||||
|
||||
print("\nconcurrency size bytes accepted ready p50_s p95_s maxq peakRSS_MB")
|
||||
for r in RESULTS:
|
||||
print(f"{r['concurrency']:>11} {r['size']:<7} {r['bytes']:>7} {r['accepted']:>8} {r['ready']:>5} "
|
||||
f"{str(r['p50_ready_s']):>5} {str(r['p95_ready_s']):>5} {r['max_queue_depth']:>5} {r['worker_peak_mem_mb']:>10}")
|
||||
print(f"\nrecovery after overload: {'OK' if drained else 'FAILED'}")
|
||||
print(json.dumps({"output": args.output, "recovered": drained}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,79 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regression check: logout must not be bypassed while Valkey is unavailable.
|
||||
|
||||
Scenario (the one that used to fail):
|
||||
1. login and warm any session cache;
|
||||
2. pause Valkey;
|
||||
3. logout -> 204 (session row removed from PostgreSQL);
|
||||
4. resume Valkey;
|
||||
5. after the cache circuit breaker window, the old token must still be 401 on
|
||||
every replica, and it must not be able to send a message.
|
||||
|
||||
Requires the docker CLI and a running lab3 stack.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
|
||||
def _docker(*args: str) -> None:
|
||||
subprocess.run(["docker", *args], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://localhost:8080"))
|
||||
parser.add_argument("--valkey-container", default=os.environ.get("VALKEY_CONTAINER", "messenger-lab3-valkey-1"))
|
||||
parser.add_argument("--wait", type=float, default=6.0, help="seconds to wait after resuming Valkey")
|
||||
args = parser.parse_args()
|
||||
|
||||
c = Client(args.base_url)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
|
||||
# Warm the cache on both replicas.
|
||||
for _ in range(6):
|
||||
c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
c.message(alice, chat, "warm-up before revocation")
|
||||
|
||||
print("Pausing Valkey (%s) ..." % args.valkey_container)
|
||||
_docker("pause", args.valkey_container)
|
||||
try:
|
||||
logout = c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
assert logout["status"] == 204, logout["status"]
|
||||
print("Logout returned 204 while the cache was unavailable.")
|
||||
finally:
|
||||
_docker("unpause", args.valkey_container)
|
||||
print("Valkey resumed; waiting %.1fs for the cache circuit breaker ..." % args.wait)
|
||||
time.sleep(args.wait)
|
||||
|
||||
seen = set()
|
||||
for _ in range(12):
|
||||
response = c.call("GET", "/api/v1/users/me", 401, actor=alice, schema="Error")
|
||||
seen.add(response["headers"].get("X-Instance-Id"))
|
||||
assert len(seen) >= 1, "no replica observed"
|
||||
|
||||
blocked = c.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
401,
|
||||
actor=alice,
|
||||
body={"text": "must not be written"},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
schema="Error",
|
||||
)
|
||||
assert blocked["status"] == 401, blocked["status"]
|
||||
|
||||
print(
|
||||
"PASS: revoked session stays 401 through %d replica(s) and cannot post after a "
|
||||
"failed cache invalidation." % len(seen)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+52
@@ -0,0 +1,52 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Generate local (gitignored) compose secrets with random credentials.
|
||||
# Writes database, cache and S3 credentials plus the SeaweedFS S3 config that
|
||||
# declares the limited "messenger-api" identity (separate from root).
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p secrets
|
||||
|
||||
BUCKET="${S3_BUCKET:-messenger-attachments}"
|
||||
|
||||
rand() { head -c 24 /dev/urandom | od -An -tx1 | tr -d ' \n'; }
|
||||
|
||||
PASSWORD=$(rand)
|
||||
ROOT_KEY="root$(rand)"
|
||||
ROOT_SECRET=$(rand)
|
||||
API_KEY="api$(rand)"
|
||||
API_SECRET=$(rand)
|
||||
BROKER_PASSWORD=$(rand)
|
||||
|
||||
printf '%s' "$PASSWORD" > secrets/database_password
|
||||
printf '%s' "postgresql://messenger:${PASSWORD}@postgres:5432/messenger" > secrets/database_url
|
||||
printf '%s' "redis://valkey:6379/0" > secrets/cache_url
|
||||
|
||||
printf '%s' "$BROKER_PASSWORD" > secrets/broker_password
|
||||
printf '%s' "amqp://messenger:${BROKER_PASSWORD}@broker:5672/%2F" > secrets/broker_url
|
||||
|
||||
printf '%s' "$ROOT_KEY" > secrets/s3_root_access_key_id
|
||||
printf '%s' "$ROOT_SECRET" > secrets/s3_root_secret_access_key
|
||||
printf '%s' "$API_KEY" > secrets/s3_access_key_id
|
||||
printf '%s' "$API_SECRET" > secrets/s3_secret_access_key
|
||||
|
||||
# The API/worker identity may only Read/Write/List/Delete THIS bucket; root
|
||||
# (Admin) is used solely by the one-shot s3-init bootstrap.
|
||||
cat > secrets/s3_config.json <<EOF
|
||||
{
|
||||
"identities": [
|
||||
{
|
||||
"name": "root",
|
||||
"credentials": [{"accessKey": "${ROOT_KEY}", "secretKey": "${ROOT_SECRET}"}],
|
||||
"actions": ["Admin", "Read", "Write", "List", "Tagging", "Delete"]
|
||||
},
|
||||
{
|
||||
"name": "messenger-api",
|
||||
"credentials": [{"accessKey": "${API_KEY}", "secretKey": "${API_SECRET}"}],
|
||||
"actions": ["Read:${BUCKET}", "Write:${BUCKET}", "List:${BUCKET}", "Delete:${BUCKET}"]
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
|
||||
chmod 600 secrets/* 2>/dev/null || true
|
||||
echo "Wrote ./secrets/{database_password,database_url,cache_url,broker_*,s3_*,s3_config.json} (not committed)."
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Restart the API replicas, the balancer, the worker and ALL state stores used
|
||||
# by this stack (PostgreSQL, Valkey, S3, RabbitMQ). Volumes are preserved;
|
||||
# schema, bucket, queues and data are never dropped or re-seeded. Used by:
|
||||
# make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart api lb worker postgres valkey s3 broker
|
||||
exit 0
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Restore the API service to the desired replica count after a failover test.
|
||||
# Stopped replicas are started again; volumes and data are untouched.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose up -d --no-recreate api
|
||||
exit 0
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Sequential (rolling) replacement of the API replicas under load.
|
||||
#
|
||||
# The image is rebuilt once, then each running replica is stopped (the balancer
|
||||
# drains it and keeps serving from the peers) and recreated from the new image.
|
||||
# Before the next replica is touched we wait until every running replica is
|
||||
# healthy, so the balancer always has somewhere to send traffic.
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
N="${API_REPLICAS:-2}"
|
||||
|
||||
wait_healthy() {
|
||||
for _ in $(seq 1 90); do
|
||||
total=$(docker compose ps -q api | wc -l)
|
||||
healthy=$(docker ps --filter label=com.docker.compose.service=api --filter health=healthy --format '{{.ID}}' | wc -l)
|
||||
if [ "$total" -ge "$N" ] && [ "$healthy" -ge "$total" ]; then
|
||||
return 0
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
}
|
||||
|
||||
echo "Building new API image..."
|
||||
docker compose build api
|
||||
|
||||
# Wait for the current generation to be healthy before starting.
|
||||
wait_healthy
|
||||
|
||||
for id in $(docker compose ps -q api); do
|
||||
echo "Replacing replica $id ..."
|
||||
docker stop -t 10 "$id" >/dev/null
|
||||
docker rm "$id" >/dev/null
|
||||
docker compose up -d --no-recreate api >/dev/null
|
||||
wait_healthy
|
||||
done
|
||||
|
||||
echo "Rolling update complete; all replicas healthy."
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Start the worker again after stop-worker.sh.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose start worker
|
||||
exit 0
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Stop exactly ONE API replica and leave it stopped.
|
||||
#
|
||||
# TARGET_INSTANCE_ID is the X-Instance-Id observed by the test, which equals the
|
||||
# replica's container hostname (Docker's short container id). We map it to the
|
||||
# running api container and stop it with a short grace period so the hook
|
||||
# returns well within the 10 second budget. PostgreSQL, Valkey and the balancer
|
||||
# are never touched.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
target=""
|
||||
for id in $(docker ps --filter "label=com.docker.compose.service=api" --format '{{.ID}}'); do
|
||||
case "$id" in
|
||||
"$TARGET_INSTANCE_ID"*) target="$id" ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
echo "no running API replica matches X-Instance-Id=$TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
docker stop -t 5 "$target" >/dev/null
|
||||
exit 0
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Stop the worker (leave it stopped). Used to demonstrate that uploads are
|
||||
# accepted (202) while no worker is running, and resume when it returns.
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose stop worker
|
||||
exit 0
|
||||
Reference in New Issue
Block a user