Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)

This commit is contained in:
Alexey Bodanyuk
2026-11-27 16:01:21 +03:00
parent 20afc2c790
commit 6435b6a1c5
111 changed files with 19604 additions and 0 deletions
+294
View File
@@ -0,0 +1,294 @@
#!/usr/bin/env python3
"""Generate the Grafana dashboard infra/grafana/dashboards/messenger.json (provisioned at start).
python scripts/build_dashboard.py
Every panel names its query and unit here, in one place (docs/OBSERVABILITY.md copies the list).
Percentiles are ALWAYS histogram_quantile over buckets summed `by (le)` across every replica -
never an average of per-replica percentiles. Datasource UIDs are the fixed provisioned ones.
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
OUT = Path(__file__).resolve().parents[1] / "infra" / "grafana" / "dashboards" / "messenger.json"
PROM = {"type": "prometheus", "uid": "prometheus"}
LOKI = {"type": "loki", "uid": "loki"}
TEMPO = {"type": "tempo", "uid": "tempo"}
BUSINESS = 'job="messenger-api", http_route!~"/health/.*"'
panels: list[dict] = []
_next_id = [1]
_y = [0]
def _id() -> int:
_next_id[0] += 1
return _next_id[0]
def row(title: str) -> None:
panels.append({"type": "row", "title": title, "id": _id(), "collapsed": False, "panels": [],
"gridPos": {"h": 1, "w": 24, "x": 0, "y": _y[0]}})
_y[0] += 1
class Grid:
"""Places panels left to right, wrapping at 24 columns."""
def __init__(self) -> None:
self.x = 0
self.h = 0
def place(self, w: int, h: int) -> dict:
if self.x + w > 24:
_y[0] += self.h
self.x, self.h = 0, 0
pos = {"h": h, "w": w, "x": self.x, "y": _y[0]}
self.x += w
self.h = max(self.h, h)
return pos
def end(self) -> None:
_y[0] += self.h
self.x, self.h = 0, 0
grid = Grid()
def ts(title: str, targets: list[tuple[str, str]], unit: str, description: str, *, w: int = 8, h: int = 8,
stack: bool = False, minimum: float | None = 0, maximum: float | None = None, thresholds=None) -> None:
defaults: dict = {"unit": unit, "custom": {"lineWidth": 1, "fillOpacity": 10 if not stack else 40,
"showPoints": "never",
"stacking": {"mode": "normal" if stack else "none", "group": "A"}}}
if minimum is not None:
defaults["min"] = minimum
if maximum is not None:
defaults["max"] = maximum
if thresholds:
defaults["thresholds"] = {"mode": "absolute", "steps": thresholds}
defaults["custom"]["thresholdsStyle"] = {"mode": "line+area"}
panels.append({
"type": "timeseries", "title": title, "id": _id(), "datasource": PROM,
"description": description + f"\n\nUnit: {unit}.",
"gridPos": grid.place(w, h),
"fieldConfig": {"defaults": defaults, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom", "showLegend": True},
"tooltip": {"mode": "multi", "sort": "desc"}},
"targets": [{"refId": chr(65 + i), "datasource": PROM, "expr": expr, "legendFormat": legend, "range": True}
for i, (expr, legend) in enumerate(targets)],
})
def stat(title: str, expr: str, unit: str, description: str, steps, *, w: int = 6, h: int = 5, decimals: int = 2) -> None:
panels.append({
"type": "stat", "title": title, "id": _id(), "datasource": PROM,
"description": description + f"\n\nUnit: {unit}.",
"gridPos": grid.place(w, h),
"fieldConfig": {"defaults": {"unit": unit, "decimals": decimals,
"thresholds": {"mode": "absolute", "steps": steps}}, "overrides": []},
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": False},
"colorMode": "background", "graphMode": "area", "textMode": "value"},
"targets": [{"refId": "A", "datasource": PROM, "expr": expr, "instant": False, "range": True}],
})
def q(phi: float, metric: str, selector: str, window: str = "$__rate_interval", by: str = "") -> str:
group = f"le{', ' + by if by else ''}"
return f"histogram_quantile({phi}, sum by ({group}) (rate({metric}_bucket{{{selector}}}[{window}])))"
# =============================================================================== API
row("API: requests, errors, latency (all replicas)")
ts("Requests per second by route",
[(f"sum by (http_route) (rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "{{http_route}}")],
"reqps", "Business requests (no /health/*) per second, summed over the API replicas. "
"Counter = _count of the histogram http.server.request.duration (no second instrument).", stack=True)
ts("Error ratio (5xx and 4xx / all business requests)",
[(f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"5xx\"}}[$__rate_interval])) or vector(0)) "
f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "5xx (SLI: server failures)"),
(f"(sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}, http_response_status_class=\"4xx\"}}[$__rate_interval])) or vector(0)) "
f"/ sum(rate(http_server_request_duration_seconds_count{{{BUSINESS}}}[$__rate_interval]))", "4xx (client errors, not in the SLI)")],
"percentunit", "Numerator: 5xx (or 4xx) business requests; denominator: all business requests. "
"Alert MessengerApiHighErrorRate: 5xx > 5 % for 1 min.",
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 0.05}])
ts("Latency p50 / p95 / p99 (all routes, all replicas)",
[(q(0.50, "http_server_request_duration_seconds", BUSINESS), "p50"),
(q(0.95, "http_server_request_duration_seconds", BUSINESS), "p95"),
(q(0.99, "http_server_request_duration_seconds", BUSINESS), "p99")],
"s", "histogram_quantile over the buckets of http.server.request.duration summed by le across replicas "
"(buckets 1 ms ... 10 s). Not an average, not per-replica p99s averaged.")
ts("p95 by route",
[(q(0.95, "http_server_request_duration_seconds", BUSINESS, by="http_route"), "{{http_route}}")],
"s", "Per route template, buckets of all replicas.", w=12)
ts("Requests in flight by replica",
[("sum by (instance) (http_server_active_requests{job=\"messenger-api\"})", "{{instance}}")],
"short", "UpDownCounter http.server.active_requests per API replica (saturation of the HTTP layer).", w=12)
grid.end()
# =============================================================================== worker
row("Worker and queue")
ts("Jobs handled per second by outcome",
[("sum by (outcome) (rate(messenger_jobs_processed_total[$__rate_interval]))", "{{outcome}}")],
"ops", "messenger.jobs.processed: succeeded / retry / failed / fenced / superseded / noop_* / deferred / rejected.",
stack=True)
ts("Job duration p50 / p95 / p99 (succeeded)",
[(q(0.50, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p50"),
(q(0.95, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p95"),
(q(0.99, "messenger_job_duration_seconds", 'outcome="succeeded"'), "p99")],
"s", "One delivery in the worker: claim -> S3 read -> variants -> S3 writes -> COMMIT -> ack.")
ts("Time to ready p50 / p95 / p99 (uploads)",
[(q(0.50, "messenger_attachment_time_to_ready_seconds", ""), "p50"),
(q(0.95, "messenger_attachment_time_to_ready_seconds", ""), "p95"),
(q(0.99, "messenger_attachment_time_to_ready_seconds", ""), "p99")],
"s", "From the durable acceptance (job COMMIT before 202) to the COMMIT of status ready. "
"Includes queue wait and retries. SLO: 99 % within 30 s.")
ts("Queue depth (PostgreSQL) and outbox",
[("max by (state) (messenger_queue_depth)", "jobs {{state}}"),
("max by (state) (messenger_outbox_pending)", "outbox {{state}}")],
"short", "messenger.queue.depth: unfinished jobs (queued incl. retry wait / processing); "
"messenger.outbox.pending: unpublished messages (due / delayed). Reported by the relay every 5 s.")
ts("Oldest job age / oldest due outbox row",
[("max(messenger_queue_oldest_age_seconds)", "oldest unfinished job"),
("max(messenger_outbox_oldest_age_seconds)", "oldest due outbox row (broker)")],
"s", "Age of the oldest unfinished job (now - acceptance). Grows when nobody processes the queue. "
"Alert MessengerQueueLagGrowing: > 60 s for 1 min with queued jobs.",
thresholds=[{"color": "green", "value": None}, {"color": "red", "value": 60}])
ts("Worker saturation (busy / capacity)",
[("sum(messenger_worker_busy) / sum(messenger_worker_capacity)", "busy share")],
"percentunit", "messenger.worker.busy (attempts running) / messenger.worker.capacity (WORKER_CONCURRENCY), "
"all worker processes. 100 % for long = the worker is the bottleneck.", maximum=1)
grid.end()
# =============================================================================== DB and resources
row("Database pool and resources")
ts("DB pool: used / max, waiting requests",
[("sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", "{{job}} used"),
("sum by (job) (db_client_connection_max)", "{{job}} max"),
("sum by (job) (db_client_connection_pending_requests)", "{{job}} waiting")],
"short", "psycopg_pool counters per service (all replicas summed). Waiting > 0 = pool exhausted.")
ts("DB unit of work p95 by service",
[(q(0.95, "db_client_operation_duration_seconds", "", by="job"), "{{job}}")],
"s", "db.client.operation.duration: pool wait + statements + COMMIT of one Database.run().")
ts("DB pool wait p95 by service",
[(q(0.95, "db_client_connection_wait_time_seconds", "", by="job"), "{{job}}")],
"s", "db.client.connection.wait_time: time to get a connection from the pool.")
ts("Container CPU (cores)",
[("sum by (job, instance) (rate(container_cpu_time_seconds_total[$__rate_interval]))", "{{job}} {{instance}}"),
("rate(otelcol_process_cpu_seconds[$__rate_interval])", "otel-collector")],
"short", "cgroup cpu.stat of each application container (1 = one full core); Collector: its own counter.", w=12)
ts("Container memory",
[("sum by (job, instance) (container_memory_usage_bytes)", "{{job}} {{instance}}"),
("otelcol_process_memory_rss", "otel-collector RSS")],
"bytes", "cgroup memory.current of each application container; Collector RSS (memory_limiter: 400 MiB).", w=12)
grid.end()
# =============================================================================== SLO
row("SLO (docs/SLO.md) and alerts")
stat("Availability, last 1 h (target 99 %)", "1 - messenger:http_error_ratio:rate1h", "percentunit",
"1 - 5xx/all business requests over 1 h.",
[{"color": "red", "value": None}, {"color": "orange", "value": 0.99}, {"color": "green", "value": 0.995}], decimals=3)
stat("Requests under 250 ms, last 5 min (target 95 %)", "messenger:http_fast_ratio:rate5m", "percentunit",
"Share of business requests in buckets le=0.25.",
[{"color": "red", "value": None}, {"color": "green", "value": 0.95}], decimals=3)
stat("Uploads ready within 30 s, last 1 h (target 99 %)", "messenger:ready_within_30s_ratio:rate1h", "percentunit",
"Share of uploads with time_to_ready <= 30 s.",
[{"color": "red", "value": None}, {"color": "green", "value": 0.99}], decimals=3)
stat("Alerts firing", "count(ALERTS{alertstate=\"firing\"}) or vector(0)", "none",
"Number of firing Prometheus alerts (table below).", [{"color": "green", "value": None}, {"color": "red", "value": 1}],
decimals=0)
panels.append({
"type": "table", "title": "Alerts (pending / firing)", "id": _id(), "datasource": PROM,
"description": "ALERTS series of Prometheus (rules: infra/prometheus/rules/alerts.yml, runbook: docs/RUNBOOK.md).",
"gridPos": grid.place(24, 6),
"targets": [{"refId": "A", "datasource": PROM, "expr": "ALERTS", "instant": True, "format": "table"}],
"transformations": [{"id": "organize", "options": {"excludeByName": {"Time": True, "Value": True, "__name__": True},
"indexByName": {}, "renameByName": {}}}],
"fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True},
})
grid.end()
# =============================================================================== telemetry pipeline
row("Telemetry pipeline (Collector, SDK)")
ts("Collector: spans accepted / sent / failed per second",
[("sum(rate(otelcol_receiver_accepted_spans[$__rate_interval]))", "accepted"),
("sum(rate(otelcol_receiver_refused_spans[$__rate_interval]))", "refused (memory_limiter)"),
("sum(rate(otelcol_exporter_sent_spans[$__rate_interval]))", "sent to Tempo"),
("sum(rate(otelcol_exporter_send_failed_spans[$__rate_interval]))", "send failed (dropped)")],
"ops", "otelcol_* self-metrics, scraped from :8888. sent < accepted with tail sampling (dropped by policy).")
ts("Collector: logs and metric points per second",
[("sum(rate(otelcol_receiver_accepted_log_records[$__rate_interval]))", "logs accepted"),
("sum(rate(otelcol_exporter_send_failed_log_records[$__rate_interval]))", "logs failed"),
("sum(rate(otelcol_receiver_accepted_metric_points[$__rate_interval]))", "metric points accepted"),
("sum(rate(otelcol_exporter_send_failed_metric_points[$__rate_interval]))", "metric points failed")],
"ops", "Same for the logs and metrics pipelines.")
ts("Collector: exporter queues",
[("max by (exporter) (otelcol_exporter_queue_size)", "{{exporter}} size"),
("max by (exporter) (otelcol_exporter_queue_capacity)", "{{exporter}} capacity")],
"short", "Bounded sending_queue (batches) per exporter: fills while a backend is down, never above capacity.")
ts("SDK: spans recorded vs exported (all processes)",
[("sum by (job) (rate(messenger_telemetry_spans_ended_total[$__rate_interval]))", "{{job}} recorded"),
("sum by (job, result) (rate(messenger_telemetry_spans_exported_total[$__rate_interval]))", "{{job}} export {{result}}")],
"ops", "Spans finished in the process (sampled) and handed to the OTLP exporter: success / failure (Collector down).",
w=12)
ts("Telemetry components up",
[("up{job=~\"otel-collector|prometheus|loki|tempo|grafana\"}", "{{job}}")],
"short", "1 = the scrape succeeded.", w=12, maximum=1)
grid.end()
# =============================================================================== logs and traces
row("Logs and traces")
panels.append({
"type": "logs", "title": "Application logs (Loki): warnings and errors", "id": _id(), "datasource": LOKI,
"description": "OTLP log records of api/relay/worker. Expand a line: trace_id links to Tempo. "
"Query: {service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\".",
"gridPos": grid.place(12, 10),
"targets": [{"refId": "A", "datasource": LOKI, "expr": "{service_name=~\"messenger-.+\"} | detected_level=~\"warn|error\"",
"queryType": "range"}],
"options": {"showTime": True, "wrapLogMessage": True, "enableLogDetails": True, "sortOrder": "Descending",
"dedupStrategy": "none", "prettifyLogMessage": False},
})
panels.append({
"type": "table", "title": "Recent upload traces (Tempo)", "id": _id(), "datasource": TEMPO,
"description": "TraceQL: POST of an attachment. Click a trace id: upload -> enqueue -> publish -> process -> S3/DB.",
"gridPos": grid.place(12, 10),
"targets": [{"refId": "A", "datasource": TEMPO, "queryType": "traceql", "limit": 20, "tableType": "traces",
"query": "{ span.http.route = \"/api/v1/chats/{chat_id}/attachments\" }"}],
"fieldConfig": {"defaults": {}, "overrides": []}, "options": {"showHeader": True},
})
grid.end()
dashboard = {
"uid": "messenger-lab6",
"title": "Messenger lab 6: API, worker, queue, SLO",
"description": "Generated by scripts/build_dashboard.py - edit the script, not the JSON.",
"tags": ["messenger", "lab6"],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"editable": False,
"graphTooltip": 1,
"refresh": "10s",
"time": {"from": "now-30m", "to": "now"},
"templating": {"list": []},
"annotations": {"list": [{"builtIn": 1, "datasource": {"type": "grafana", "uid": "-- Grafana --"}, "enable": True,
"hide": True, "iconColor": "rgba(0, 211, 255, 1)", "name": "Annotations & Alerts",
"type": "dashboard"}]},
"panels": panels,
}
def main() -> int:
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(dashboard, indent=1, ensure_ascii=False) + "\n", encoding="utf-8", newline="\n")
print(f"written {OUT.relative_to(OUT.parents[3])}: {len(panels)} panels")
return 0
if __name__ == "__main__":
sys.exit(main())
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Run EVERY query of the provisioned dashboard through Grafana (/api/ds/query) and report, per
panel: error / no data / number of series. Proves that the dashboard refers to metric names,
labels and datasource UIDs that really exist (not only that the JSON was imported).
python scripts/check_dashboard.py [--minutes 30] [--output evidence/dashboard-check.txt]
Exit code 1 if a query fails. "no data" is reported, not failed: an incident-only series
(5xx, failed spans) is legitimately empty on a healthy stand.
"""
from __future__ import annotations
import argparse
import json
import sys
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import obs # noqa: E402
def post(path: str, body: dict) -> dict:
request = urllib.request.Request(obs.GRAFANA + path, data=json.dumps(body).encode(), method="POST",
headers={"Authorization": obs._auth(), "Content-Type": "application/json"})
try:
with urllib.request.urlopen(request, timeout=60) as response:
return json.loads(response.read())
except urllib.error.HTTPError as exc:
return json.loads(exc.read() or b"{}") | {"_status": exc.code}
def get(path: str) -> dict:
request = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()})
with urllib.request.urlopen(request, timeout=30) as response:
return json.loads(response.read())
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--minutes", type=int, default=30)
parser.add_argument("--output")
args = parser.parse_args()
dashboard = get("/api/dashboards/uid/messenger-lab6")["dashboard"]
now = int(time.time() * 1000)
lines, failed = [], 0
lines.append(f"dashboard {dashboard['uid']} \"{dashboard['title']}\" (provisioned), window {args.minutes} min")
for panel in dashboard["panels"]:
if panel["type"] == "row":
lines.append(f"== {panel['title']}")
continue
results = []
for target in panel.get("targets", []):
query = {k: v for k, v in target.items()}
query.setdefault("datasource", panel["datasource"])
query["intervalMs"], query["maxDataPoints"] = 15000, 200
if query["datasource"]["type"] == "tempo":
query.update({"queryType": "traceql", "tableType": "traces"})
response = post("/api/ds/query", {"queries": [query], "from": str(now - args.minutes * 60000), "to": str(now)})
result = response.get("results", {}).get(target["refId"], {})
if "_status" in response or result.get("error"):
failed += 1
results.append(f"{target['refId']}: ERROR {result.get('error') or response.get('message')}")
continue
frames = result.get("frames", [])
rows = sum(len(f.get("data", {}).get("values", [[]])[0]) if f.get("data", {}).get("values") else 0 for f in frames)
results.append(f"{target['refId']}: {len(frames)} series/{rows} points" if rows else f"{target['refId']}: no data")
lines.append(f" [{panel['type']}] {panel['title']}: " + "; ".join(results))
lines.append(f"queries failed: {failed}")
text = "\n".join(lines)
print(text)
if args.output:
Path(args.output).write_text(text + "\n", encoding="utf-8", newline="\n")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())
+221
View File
@@ -0,0 +1,221 @@
#!/usr/bin/env python3
"""Run every check of REPORT.md on the current checkout and save the real output in evidence/.
python scripts/collect_evidence.py # ~3 h; the stand must NOT be running yet
python scripts/collect_evidence.py --skip-track1 # without the 45 min track 1 experiment
Intended for a CLEAN CLONE (fresh volumes): it creates secrets and .env, builds and starts the
stand, then runs make check/validate/test/test-persistence/test-failover, the lab 5 defense
scenario (scripts/demo_pipeline.py), lab 6: provisioning check of Grafana, the controlled trace
(scripts/trace_demo.py), every dashboard query (scripts/check_dashboard.py), the own tests, the
level 4 incidents (bench/incidents.py) and the track 1 experiment (bench/track1.py), and records
container states before/after every hook and the real resource limits (docker inspect). Prints no secrets
(hook output is shown by the public tests as suppressed; our scripts print names and states only).
On Windows the hooks are the scripts/*.cmd wrappers (Git Bash) and make needs Git's usr/bin.
"""
from __future__ import annotations
import datetime as dt
import json
import os
import shutil
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
EVIDENCE = ROOT / "evidence"
WINDOWS = os.name == "nt"
HOOK = ".cmd" if WINDOWS else ".sh"
PYTHON = sys.executable
VENV_PY = str(ROOT / ".venv" / ("Scripts/python.exe" if WINDOWS else "bin/python"))
# Makefile recipes use $(PYTHON) unquoted: pass interpreters WITHOUT spaces in the path.
MAKE_PY = "python" if WINDOWS else "python3"
MAKE_VENV = ".venv/Scripts/python.exe" if WINDOWS else ".venv/bin/python"
ENV = {**os.environ, "PYTHONUTF8": "1"}
if WINDOWS:
ENV["PATH"] = ENV["PATH"] + os.pathsep + r"C:\Program Files\Git\usr\bin"
def now() -> str:
return dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def sh(cmd: list[str], timeout: float = 1800, env: dict | None = None) -> tuple[int, str]:
started = time.monotonic()
result = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True, encoding="utf-8", errors="replace",
timeout=timeout, env={**ENV, **(env or {})})
took = time.monotonic() - started
return result.returncode, (result.stdout + result.stderr).rstrip() + f"\n[exit {result.returncode}, {took:.1f} s]\n"
class Log:
def __init__(self, name: str, title: str):
self.path = EVIDENCE / name
self.path.parent.mkdir(parents=True, exist_ok=True)
commit = subprocess.run(["git", "log", "-1", "--format=%h %s"], cwd=ROOT, capture_output=True, text=True,
encoding="utf-8").stdout.strip()
self.text = f"# {title}\n# {now()}, commit {commit}\n"
def run(self, cmd: list[str], shown: str | None = None, **kwargs) -> int:
code, out = sh(cmd, **kwargs)
self.text += f"\n$ {shown or ' '.join(cmd)}\n{out}"
self.save()
print(f" {self.path.name}: {shown or ' '.join(cmd[:4])} -> exit {code}", flush=True)
return code
def note(self, text: str) -> None:
self.text += f"\n{text}\n"
self.save()
def save(self) -> None:
self.path.write_text(self.text, encoding="utf-8")
def states() -> list[str]:
ids = subprocess.run(["docker", "compose", "ps", "-a", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split()
rows = []
for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True).stdout or "[]"):
st = item["State"]
rows.append(f"{item['Name'].lstrip('/'):24} host={item['Config']['Hostname']:13} {st['Status']:8} "
f"exit={st['ExitCode']:<3} pid={st['Pid']:<6} started={st['StartedAt'][:23]}")
return sorted(rows)
OBS_CHECK = """
import json, sys, time, urllib.request
sys.path.insert(0, "scripts")
import obs
for _ in range(60):
try:
urllib.request.urlopen(obs.GRAFANA + "/api/health", timeout=5).read(); break
except Exception:
time.sleep(2)
def get(path):
req = urllib.request.Request(obs.GRAFANA + path, headers={"Authorization": obs._auth()})
return json.loads(urllib.request.urlopen(req, timeout=30).read())
for uid in ("prometheus", "loki", "tempo"):
print(uid, get(f"/api/datasources/uid/{uid}/health"))
for d in get("/api/search?type=dash-db"):
print("dashboard", d["uid"], d["title"], "folder:", d.get("folderTitle"))
print("prometheus rules:", [r["name"] for g in obs.get("prometheus", "api/v1/rules")["data"]["groups"] for r in g["rules"]])
"""
def main() -> int:
EVIDENCE.mkdir(exist_ok=True)
make = shutil.which("make", path=ENV["PATH"]) or "make"
# 1. Clean clone -> secrets -> build -> start
log = Log("clean-clone.txt", "Clean clone: secrets, config, build, migrations from zero, start, versions")
log.run(["git", "status", "--short", "--branch"])
log.run([PYTHON, "--version"]); log.run(["docker", "version", "--format", "client {{.Client.Version}} / server {{.Server.Version}}"])
log.run(["docker", "compose", "version"]); log.run([make, "--version"], shown="make --version")
log.run([PYTHON, "scripts/init_secrets.py"], shown="python scripts/init_secrets.py")
if not (ROOT / ".env").exists():
shutil.copy(ROOT / ".env.example", ROOT / ".env")
log.note("$ cp .env.example .env")
log.run(["docker", "compose", "--env-file", ".env", "config", "--quiet"])
log.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--build", "--wait"], timeout=1800)
log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Image}}\t{{.Status}}"])
log.run(["docker", "compose", "logs", "--no-log-prefix", "migrate"])
log.run(["docker", "compose", "logs", "--no-log-prefix", "s3-init"]) # bucket + access-model verdicts
log.run([PYTHON, "scripts/lbctl.py", "replicas"]); log.run([PYTHON, "scripts/lbctl.py", "status"])
log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_users"])
log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "type",
"durable", "messages", "consumers", "arguments"])
log.run(["docker", "compose", "exec", "-T", "broker", "rabbitmqctl", "-q", "list_permissions"])
# lab 6: telemetry stores up, Grafana provisioned (datasources with fixed UIDs, dashboard)
log.run([PYTHON, "-c", OBS_CHECK], shown="python -c <Grafana: health of datasources prometheus/loki/tempo, dashboards>")
ids = subprocess.run(["docker", "compose", "ps", "-q"], cwd=ROOT, capture_output=True, text=True).stdout.split()
log.run(["docker", "inspect", "-f", "{{.Name}} cpus={{.HostConfig.NanoCpus}} memory={{.HostConfig.Memory}} "
"memswap={{.HostConfig.MemorySwap}} image={{.Config.Image}}", *ids], shown="docker inspect (limits)")
# venv for validate / own tests
if not Path(VENV_PY).exists():
log.run([PYTHON, "-m", "venv", ".venv"])
log.run([VENV_PY, "-m", "pip", "install", "-q", "--require-hashes", "--no-deps", "-r", "requirements.txt"], timeout=1800)
log.run([VENV_PY, "-m", "pip", "install", "-q", "-r", "requirements-test.txt", "-r", "requirements-dev.txt"], timeout=1800)
# 2. make check / validate / test
log = Log("make-check-validate-test.txt", "make check, make validate (venv), make test")
log.run([make, "check", f"PYTHON={MAKE_PY}"], shown="make check")
log.run([make, "validate", f"PYTHON={MAKE_VENV}"], shown=f"make validate PYTHON={MAKE_VENV}")
log.run([make, "test", f"PYTHON={MAKE_PY}"], shown="make test")
# 3. persistence with states before/after
log = Log("test-persistence.txt", "make test-persistence: restart of LB, API replicas, relay, worker, PostgreSQL, "
"Valkey, S3, RabbitMQ")
log.note("Containers BEFORE:\n" + "\n".join(states()))
log.run([make, "test-persistence", f"ACTION_SCRIPT=scripts/restart{HOOK}", f"PYTHON={MAKE_PY}"],
shown=f"make test-persistence ACTION_SCRIPT=scripts/restart{HOOK}")
log.note("Containers AFTER (new pid/started for lb, api-*, relay, worker, postgres, valkey, s3, broker; volumes "
"kept):\n" + "\n".join(states()))
log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"])
# 4. failover: until BOTH replicas have been the stopped one (each run is a real public test)
log = Log("test-failover.txt", "make test-failover with scripts/stop-one: which container is really stopped, restore, repeat")
stopped: set[str] = set()
import urllib.request
for attempt in range(1, 7):
# The public test stops the replica that served its first POST; its request sequence is
# fixed, so with round robin it hits the same replica every time. Shift the rotation by
# (attempt - 1) extra requests so that the other replica becomes the target as well.
for _ in range(attempt - 1):
urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=5).read()
before = {r for r in states() if "-api-" in r and " running " in r}
log.note(f"--- run {attempt}; running API replicas BEFORE:\n" + "\n".join(sorted(before)))
log.run([make, "test-failover", f"ACTION_SCRIPT=scripts/stop-one{HOOK}", f"PYTHON={MAKE_PY}"],
shown=f"make test-failover ACTION_SCRIPT=scripts/stop-one{HOOK}")
after = states()
gone = [r for r in after if "-api-" in r and " exited " in r]
log.note("AFTER (the stopped replica, left stopped by the hook):\n" + "\n".join(gone))
log.run([PYTHON, "scripts/lbctl.py", "status"])
stopped.update(r.split()[0] for r in gone)
log.run(["sh" if not WINDOWS else r"C:\Program Files\Git\bin\bash.exe", "scripts/restore-api.sh"],
shown="sh scripts/restore-api.sh")
log.run([PYTHON, "scripts/lbctl.py", "wait-up", "2"])
if len(stopped) >= 2:
break
log.note(f"Replicas stopped by the public test across runs: {sorted(stopped)}")
# 5a. lab 6 defense steps 2-3: controlled trace + logs; every dashboard query; load
log = Log("trace-demo.txt", "Defense step 2: upload with our own traceparent -> trace in Tempo + logs in Loki")
log.run([PYTHON, "tests/load.py", "--duration", "30", "--concurrency", "4", "--output", "evidence/load.json"])
log.run([PYTHON, "scripts/trace_demo.py"], shown="python scripts/trace_demo.py", timeout=300)
log = Log("dashboard-check.txt", "Every query of the provisioned dashboard through Grafana /api/ds/query")
log.run([PYTHON, "scripts/check_dashboard.py"], shown="python scripts/check_dashboard.py", timeout=600)
# 5. lab 5 defense scenario: worker stopped -> 202 -> 409 -> restart api+broker -> worker -> ready
log = Log("demo-pipeline.txt", "Defense steps 2-3: worker stopped, upload 202, content 409, restart API and broker "
"with volumes, worker started, ready + thumbnail")
log.note("Containers BEFORE:\n" + "\n".join(states()))
log.run([VENV_PY, "scripts/demo_pipeline.py"], shown="python scripts/demo_pipeline.py", timeout=900)
log.note("Containers AFTER (api-*, broker restarted; worker stopped and started):\n" + "\n".join(states()))
# 6. own tests
log = Log("student-tests.txt", "Own tests: unit + stand (pytest -v); failures restored in finally")
log.run([VENV_PY, "-m", "pytest", "student-tests", "-v", "-p", "no:cacheprovider"], shown="python -m pytest student-tests -v",
timeout=5400)
# 7. lab 6 level 4: incidents under load (alerts firing -> resolved, diagnosis by traces)
log = Log("incidents-runs.txt", "bench/incidents.py all: worker stop, DB lock, slow handler, Tempo+Loki down, "
"Collector down (details: evidence/incidents/*.txt)")
log.run([VENV_PY, "bench/incidents.py", "all"], shown="python bench/incidents.py all", timeout=5400)
log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "auditor"], shown="docker compose run --rm auditor",
timeout=900) # lab 5 invariants still hold after all of it
# 8. track 1: price of observability
if "--skip-track1" not in sys.argv:
log = Log("track1-runs.txt", "Track 1: bench/track1.py, off/full/head10/tail x 3 runs, then the summary")
log.run([VENV_PY, "bench/track1.py", "--runs", "3", "--output", "evidence/track1"],
shown="python bench/track1.py --runs 3", timeout=7200)
log.run([PYTHON, "bench/track1_summary.py", "evidence/track1"], shown="python bench/track1_summary.py")
log = Log("final-state.txt", "Final state of the stand")
log.run([PYTHON, "scripts/obs.py", "alerts"], shown="python scripts/obs.py alerts")
log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Status}}"])
print("done:", EVIDENCE)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+50
View File
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Resume scripts/collect_evidence.py after an interruption, on the SAME clean-clone stand.
python scripts/collect_evidence_resume.py
Used once in this work: during the clean-clone run Docker Desktop itself stopped after the own
tests (every later step failed with "cannot connect to the docker API"). This script re-runs, with
the same logging, the tests that failed in that run and the steps that never executed: level 4
incidents, the read-only audit and the final state. Earlier evidence files are kept unchanged.
"""
from __future__ import annotations
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import collect_evidence as ce # noqa: E402
FAILED = [
"student-tests/test_pipeline_flow.py::test_cleanup_racing_a_replay_never_deletes_the_replayed_source",
"student-tests/test_storage_failures.py::test_upload_survives_failover_of_the_serving_replica",
"student-tests/test_storage_failures.py::test_bucket_is_private_outside_the_api",
"student-tests/test_storage_failures.py::test_s3_restart_keeps_objects",
]
def main() -> int:
log = ce.Log("student-tests-rerun.txt", "Re-run of the 4 tests that failed in student-tests.txt (Docker Desktop "
"degraded and then stopped at the end of that run)")
log.note("Containers BEFORE:\n" + "\n".join(ce.states()))
log.run([ce.VENV_PY, "-m", "pytest", *FAILED, "-v", "-p", "no:cacheprovider"],
shown="python -m pytest <4 tests> -v", timeout=3600)
log = ce.Log("incidents-runs.txt", "bench/incidents.py all: worker stop, DB lock, slow handler, Tempo+Loki down, "
"Collector down (details: evidence/incidents/*.txt)")
log.run([ce.VENV_PY, "bench/incidents.py", "all"], shown="python bench/incidents.py all", timeout=5400)
log.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "auditor"], shown="docker compose run --rm auditor",
timeout=900)
log = ce.Log("final-state.txt", "Final state of the stand")
log.run([ce.PYTHON, "scripts/obs.py", "alerts"], shown="python scripts/obs.py alerts")
log.run(["docker", "compose", "ps", "-a", "--format", "table {{.Service}}\t{{.Status}}"])
print("done:", ce.EVIDENCE)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Lab 4 defense scenario (kept in lab 5; upload is now 202 queued, the download waits for ready):
upload the fixture, send a message with attachment_ids,
download as the second member and compare SHA-256; the outsider gets 404; an unauthenticated
request straight to S3 (from inside the storage network) is refused, the signed one works.
python scripts/demo_attachments.py [--base-url http://127.0.0.1:8080]
Prints requests and answers; never prints tokens or keys. Creates synthetic users.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import subprocess
import sys
import urllib.error
import urllib.request
import uuid
from email.message import Message
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
FIXTURE = ROOT / "tests" / "fixtures" / "sample.png"
PASSWORD = "Demo-password-Ω-12345"
class Client:
def __init__(self, base: str):
self.base = base.rstrip("/")
def call(self, method: str, path: str, *, token: str | None = None, body=None, raw: bytes | None = None,
headers: dict | None = None) -> tuple[int, Message, bytes]:
h = dict(headers or {})
if token:
h["Authorization"] = "Bearer " + token
data = raw
if body is not None:
data = json.dumps(body, ensure_ascii=False).encode()
h["Content-Type"] = "application/json"
req = urllib.request.Request(self.base + path, data=data, method=method, headers=h)
try:
with urllib.request.urlopen(req, timeout=30) as r:
return r.status, r.headers, r.read() # case-insensitive HTTPMessage
except urllib.error.HTTPError as e:
return e.code, e.headers, e.read()
def show(label: str, status: int, headers: Message, payload: bytes, *, binary: bool = False) -> None:
inst = headers.get("X-Instance-Id", "-")
if binary:
text = f"{len(payload)} bytes, Content-Type {headers.get('Content-Type')}"
else:
text = payload.decode("utf-8", "replace")[:300]
print(f" {label:58} -> {status} [X-Instance-Id {inst}] {text}")
def user(c: Client, label: str) -> dict:
name = f"{label}_{uuid.uuid4().hex[:8]}"
status, _, body = c.call("POST", "/api/v1/users", body={"username": name, "display_name": label.title(),
"password": PASSWORD})
assert status == 201, body
basic = base64.b64encode(f"{name}:{PASSWORD}".encode()).decode()
status, _, body = c.call("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
session = json.loads(body)
return {"id": session["user"]["id"], "token": session["token"], "name": name}
def wait_ready(c: Client, actor: dict, attachment_id: str, timeout: float = 60):
import time
deadline = time.monotonic() + timeout
while True:
st, h, b = c.call("GET", f"/api/v1/attachments/{attachment_id}", token=actor["token"])
if st != 200 or json.loads(b)["status"] in ("ready", "failed") or time.monotonic() > deadline:
return st, h, b
time.sleep(0.3)
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--base-url", default="http://127.0.0.1:8080")
args = p.parse_args()
c = Client(args.base_url)
content = FIXTURE.read_bytes()
print(f"fixture {FIXTURE.name}: {len(content)} bytes, sha256 {hashlib.sha256(content).hexdigest()}")
alice, bob, eve = user(c, "alice"), user(c, "bob"), user(c, "eve")
print(f"users: alice, bob (members), eve (outsider)")
status, _, body = c.call("POST", "/api/v1/chats", token=alice["token"],
body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]})
chat = json.loads(body)
print("\n1. upload -> message -> download by the second member")
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", token=alice["token"],
raw=content, headers={"Content-Type": "image/png"})
show("POST /chats/{id}/attachments (alice, raw PNG)", st, h, b)
att = json.loads(b)
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
show("POST /chats/{id}/messages text='' attachment_ids=[id]", st, h, b)
st, h, b = wait_ready(c, bob, att["id"])
show("GET /attachments/{id} (bob) until ready", st, h, b)
st, h, got = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"])
show("GET /attachments/{id}/content (bob)", st, h, got, binary=True)
same = hashlib.sha256(got).hexdigest() == hashlib.sha256(content).hexdigest() == att["sha256"]
print(f" SHA-256 of the download == fixture == metadata: {same}")
print("\n2. outsider and direct S3 access")
for suffix in ("", "/content"):
st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", token=eve["token"])
show(f"GET /attachments/{{id}}{suffix} (eve, not a member)", st, h, b)
key = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
"-At", "-c", f"SELECT object_key FROM attachments WHERE id = '{att['id']}'"],
cwd=ROOT, capture_output=True, text=True, check=True).stdout.strip()
print(f" object key in PostgreSQL: {key} (random; not in any API response: "
f"{key not in json.dumps(att)})")
probe = (
"import urllib.request as u, urllib.error as e, asyncio\n"
"def st(url):\n"
" try: return u.urlopen(url, timeout=3).status\n"
" except e.HTTPError as x: return x.code\n"
f"print('anonymous GET http://s3:8333/messenger-attachments/{key} ->', st('http://s3:8333/messenger-attachments/{key}'))\n"
"print('anonymous LIST http://s3:8333/messenger-attachments?list-type=2 ->', st('http://s3:8333/messenger-attachments?list-type=2'))\n"
"from messenger.config import Settings\nfrom messenger.storage import Storage\n"
"async def m():\n s = Storage(Settings.from_env()); await s.open()\n"
f" print('signed HEAD with the API key pair ->', (await s.head('{key}')).size, 'bytes'); await s.close()\n"
"asyncio.run(m())\n")
out = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-c", probe], cwd=ROOT,
capture_output=True, text=True).stdout
for line in out.splitlines():
print(" (inside network storage) " + line)
print(" S3 is not published on the host at all: only the LB has ports (127.0.0.1:8080, 8404).")
return 0 if same else 1
if __name__ == "__main__":
sys.exit(main())
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Lab 5 defense scenario, steps 2-3 (README): worker stopped -> upload 202 -> content 409 while the
rest of the API works -> a message with the attachment is created -> API and broker restarted with
their volumes -> worker started -> the same attachment becomes ready, thumbnail downloadable.
python scripts/demo_pipeline.py [--base-url http://127.0.0.1:8080]
Prints every step with HTTP codes, IDs, the outbox row and the queue depth; never prints tokens or
keys. Creates synthetic users. Always starts the worker again at the end.
"""
from __future__ import annotations
import argparse
import hashlib
import io
import json
import subprocess
import sys
import time
import uuid
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from demo_attachments import FIXTURE, ROOT, Client, show, user, wait_ready # noqa: E402
def compose(*args: str, check: bool = True) -> str:
return subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
check=check, timeout=300).stdout
def psql(sql: str) -> str:
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", sql).strip()
def queue_depth() -> str:
"""messages/consumers of the jobs queue; rabbitmqctl refreshes these counters every ~5 s."""
time.sleep(6)
out = compose("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "name", "messages", "consumers")
line = next(l for l in out.splitlines() if l.startswith("messenger.attachment-jobs\t"))
_, messages, consumers = line.split("\t")
return f"messages={messages} consumers={consumers}"
def wait_api(c: Client, timeout: float = 120) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
if c.call("GET", "/health/ready")[0] == 200:
return
except OSError:
pass
time.sleep(1)
raise SystemExit("API did not become ready")
def step(text: str) -> None:
print(f"\n[{time.strftime('%H:%M:%S')}] {text}")
def main() -> int:
p = argparse.ArgumentParser()
p.add_argument("--base-url", default="http://127.0.0.1:8080")
args = p.parse_args()
c = Client(args.base_url)
content = FIXTURE.read_bytes()
alice, bob = user(c, "alice"), user(c, "bob")
_, _, body = c.call("POST", "/api/v1/chats", token=alice["token"],
body={"title": "Демо lab5", "member_ids": [alice["id"], bob["id"]]})
chat = json.loads(body)
try:
step("1. docker compose stop worker")
compose("stop", "worker")
print(" " + compose("ps", "-a", "--format", "{{.Service}} {{.State}}", "worker").strip())
step("2. upload while the worker is stopped")
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=sample.png", token=alice["token"],
raw=content, headers={"Content-Type": "image/png"})
show("POST /chats/{id}/attachments", st, h, b)
att = json.loads(b)
print(f" attachment_id = {att['id']} status = {att['status']}")
for query in ("", "?variant=thumbnail"):
st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}/content{query}", token=bob["token"])
show(f"GET /attachments/{{id}}/content{query}", st, h, b)
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=bob["token"],
body={"text": "обычное сообщение работает"}, headers={"Idempotency-Key": uuid.uuid4().hex})
show("POST /messages (text only)", st, h, b)
st, h, b = c.call("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
body={"text": "фото", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": uuid.uuid4().hex})
show("POST /messages attachment_ids=[queued id]", st, h, b)
message_id = json.loads(b)["id"]
time.sleep(2)
print(" job + outbox in PostgreSQL: " + psql(
"SELECT j.id || ' state=' || j.state || ' attempt=' || j.attempt || ' | outbox published_at=' || "
f"coalesce(o.published_at::text, 'NULL') FROM jobs j JOIN outbox o ON o.job_id = j.id "
f"WHERE j.attachment_id = '{att['id']}'"))
print(" RabbitMQ queue messenger.attachment-jobs: " + queue_depth())
step("3. docker compose restart api broker (volumes preserved)")
compose("restart", "api", "broker")
wait_api(c)
time.sleep(3)
print(" RabbitMQ queue after the restart: " + queue_depth())
st, h, b = c.call("GET", f"/api/v1/attachments/{att['id']}", token=bob["token"])
show("GET /attachments/{id}", st, h, b)
finally:
step("4. docker compose start worker")
compose("start", "worker")
st, h, b = wait_ready(c, bob, att["id"], timeout=90)
show("GET /attachments/{id} until ready", st, h, b)
ready = json.loads(b)
thumb = next(v for v in ready["variants"] if v["name"] == "thumbnail")
st, h, data = c.call("GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", token=bob["token"])
show("GET /content?variant=thumbnail", st, h, data, binary=True)
from PIL import Image
size = Image.open(io.BytesIO(data)).size
ok = (st == 200 and hashlib.sha256(data).hexdigest() == thumb["sha256"] and size == (256, 160)
and ready["status"] == "ready")
print(f" thumbnail: real JPEG {size[0]}x{size[1]}, sha256 matches metadata: {ok}")
st, h, orig = c.call("GET", f"/api/v1/attachments/{att['id']}/content", token=bob["token"])
print(f" original unchanged byte for byte: {orig == content}")
print(f" message {message_id} still references it: "
f"{psql(f'SELECT attachment_ids FROM messages WHERE id = {chr(39)}{message_id}{chr(39)}')}")
step("5. job history (jobctl show)")
shown = json.loads(compose("run", "--rm", "--no-deps", "-T", "jobctl", "show", att["id"]))
for e in shown["events"]:
print(f" {e['at']} {e['event']:16} attempt={e['attempt']} actor={e['actor']}")
return 0 if ok and orig == content else 1
if __name__ == "__main__":
sys.exit(main())
+114
View File
@@ -0,0 +1,114 @@
#!/usr/bin/env python3
"""EXPLAIN (ANALYZE, BUFFERS) of the history query on >= 10 000 messages (level 4).
python scripts/explain_history.py --output evidence/explain-history.txt
Creates (once, idempotent) a synthetic chat with 20 000 messages plus 30 000 messages in
30 other chats, then explains the EXACT statements of src/messenger/repo.py:
1. first page (HISTORY_FIRST)
2. late page via cursor (HISTORY_AFTER) — generic plan forced, as a prepared statement
reused by the driver would get it
3. the rejected variant `($2 IS NULL OR (created_at, id) > ...)` — generic plan
4. the rejected OFFSET pagination for the same late page
Runs psql inside the postgres container; no database port is published.
"""
from __future__ import annotations
import argparse
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
from messenger.repo import HISTORY_AFTER, HISTORY_FIRST # noqa: E402 (the app's real SQL)
CHAT = "00000000-0000-4000-8000-00000000e002"
USER = "00000000-0000-4000-8000-00000000e001"
TARGET = 20_000
LATE = 19_950 # cursor position: the 50 newest messages remain
SEED = f"""
\\set ON_ERROR_STOP on
BEGIN;
INSERT INTO users (id, username, display_name, password_hash)
VALUES ('{USER}', 'explain_seed', convert_to('Explain seed', 'UTF8'), 'not-a-login') ON CONFLICT DO NOTHING;
INSERT INTO chats (id, title, created_by, created_at)
SELECT ('00000000-0000-4000-8000-0000000' || lpad(to_hex(n), 5, '0'))::uuid, convert_to('explain ' || n, 'UTF8'),
'{USER}', timestamptz '2026-01-01 00:00:00+00'
FROM generate_series(57346::int, 57376::int) AS n -- e002 .. e020: target + 30 noise chats
ON CONFLICT DO NOTHING;
INSERT INTO chat_members (chat_id, user_id, position, chat_created_at)
SELECT id, '{USER}', 0, created_at FROM chats WHERE created_by = '{USER}' ON CONFLICT DO NOTHING;
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), '{CHAT}', '{USER}', convert_to('synthetic message ' || g, 'UTF8'),
timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second'
FROM generate_series(1::int, {TARGET}::int) AS g
WHERE NOT EXISTS (SELECT 1 FROM messages WHERE chat_id = '{CHAT}');
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), c.id, '{USER}', convert_to('noise ' || g, 'UTF8'),
timestamptz '2026-01-01 00:00:00+00' + g * interval '1 second'
FROM chats c CROSS JOIN generate_series(1::int, 1000::int) AS g
WHERE c.created_by = '{USER}' AND c.id <> '{CHAT}'
AND NOT EXISTS (SELECT 1 FROM messages m WHERE m.chat_id = c.id);
COMMIT;
ANALYZE messages;
"""
def pg(sql_param: str) -> str:
"""Turn psycopg %s placeholders into $1..$n for a PREPARE statement."""
parts = sql_param.split("%s")
return "".join(p + (f"${i + 1}" if i < len(parts) - 1 else "") for i, p in enumerate(parts))
EXPLAIN = f"""
\\set ON_ERROR_STOP on
\\pset pager off
SELECT count(*) AS messages_total, count(*) FILTER (WHERE chat_id = '{CHAT}') AS messages_in_target_chat FROM messages;
SELECT created_at AS cur_ts, id AS cur_id FROM messages WHERE chat_id = '{CHAT}'
ORDER BY created_at, id OFFSET {LATE - 1} LIMIT 1 \\gset
SET plan_cache_mode = force_generic_plan;
PREPARE first_page(uuid, int) AS {pg(HISTORY_FIRST)};
PREPARE after_page(uuid, timestamptz, uuid, int) AS {pg(HISTORY_AFTER)};
PREPARE or_page(uuid, timestamptz, uuid, int) AS
SELECT id, sender_id, text, created_at FROM messages
WHERE chat_id = $1 AND ($2 IS NULL OR (created_at, id) > ($2, $3)) ORDER BY created_at, id LIMIT $4;
PREPARE offset_page(uuid, int, int) AS
SELECT id, sender_id, text, created_at FROM messages WHERE chat_id = $1 ORDER BY created_at, id OFFSET $2 LIMIT $3;
\\echo '=== 1. first page, app query HISTORY_FIRST, generic plan'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE first_page('{CHAT}', 51);
\\echo '=== 2. late page (cursor at {LATE}), app query HISTORY_AFTER, generic plan'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE after_page('{CHAT}', :'cur_ts', :'cur_id', 51);
\\echo '=== 3. REJECTED: one query with ($2 IS NULL OR ...), same late page, generic plan'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE or_page('{CHAT}', :'cur_ts', :'cur_id', 51);
\\echo '=== 4. REJECTED: OFFSET pagination, same late page'
EXPLAIN (ANALYZE, BUFFERS, SUMMARY ON) EXECUTE offset_page('{CHAT}', {LATE}, 51);
"""
def psql(script: str) -> str:
result = subprocess.run(
["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-X", "-q", "-f", "-"],
cwd=ROOT, input=script, capture_output=True, text=True, encoding="utf-8", check=True)
return result.stdout
def run() -> str:
psql(SEED)
return psql(EXPLAIN)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--output", default=None)
args = parser.parse_args()
text = run()
print(text)
if args.output:
Path(args.output).write_text(text, encoding="utf-8", newline="\n")
return 0
if __name__ == "__main__":
sys.exit(main())
+81
View File
@@ -0,0 +1,81 @@
#!/usr/bin/env python3
"""Create local synthetic credentials for the stand in ./secrets (ignored by Git).
python scripts/init_secrets.py
Idempotent: existing files are kept, so re-running never changes passwords of a
database that already has data. Prints only file names, never values.
Delete ./secrets together with the volumes (`docker compose down -v`) to start over.
"""
from __future__ import annotations
import base64
import hashlib
import json
import os
import secrets
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
SECRETS = ROOT / "secrets"
def write(name: str, value: str) -> None:
path = SECRETS / name
if path.exists():
print(f"keep secrets/{name}")
return
path.write_text(value + "\n", encoding="utf-8", newline="\n")
# Readable by the container users (postgres, valkey, seaweedfs, rabbitmq, app uid 10001)
# through the compose bind mount. Local synthetic lab credentials only.
os.chmod(path, 0o644)
print(f"created secrets/{name}")
def read(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def rabbit_hash(password: str) -> str:
"""RabbitMQ `rabbit_password_hashing_sha256`: base64(salt + sha256(salt + password)), 4-byte salt.
The broker stores and compares only this hash; the plain password is in the client's URL."""
salt = secrets.token_bytes(4)
return base64.b64encode(salt + hashlib.sha256(salt + password.encode("utf-8")).digest()).decode("ascii")
def main() -> int:
SECRETS.mkdir(exist_ok=True)
write("postgres_password", secrets.token_urlsafe(24)) # [A-Za-z0-9_-]: safe inside URLs
write("valkey_password", secrets.token_urlsafe(24))
write("database_url", f"postgresql://messenger:{read('postgres_password')}@postgres:5432/messenger")
write("cache_url", f"redis://:{read('valkey_password')}@valkey:6379/0")
# S3 key pairs (SeaweedFS identities, infra/seaweedfs/start.sh): admin = bucket bootstrap only;
# api = Write staging + Read final; worker = Read/Write both; auditor = Read + List (no Write).
for who in ("admin", "api", "worker", "auditor"):
write(f"s3_{who}_access_key_id", "AK" + secrets.token_hex(9).upper())
write(f"s3_{who}_secret_access_key", secrets.token_hex(20))
# Lab 5: RabbitMQ users. relay may only publish to the jobs exchange, worker may only consume
# the jobs queue; neither may declare/delete anything (configure "^$").
write("rabbitmq_relay_password", secrets.token_urlsafe(24))
write("rabbitmq_worker_password", secrets.token_urlsafe(24))
users = {
"users": [{"name": who, "password_hash": rabbit_hash(read(f"rabbitmq_{who}_password")),
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": []} for who in ("relay", "worker")],
"permissions": [
{"user": "relay", "vhost": "/", "configure": "^$", "write": "^messenger\\.jobs$", "read": "^$"},
{"user": "worker", "vhost": "/", "configure": "^$", "write": "^$", "read": "^messenger\\.attachment-jobs$"},
],
}
write("rabbitmq_users.json", json.dumps(users, indent=1))
for who in ("relay", "worker"):
# AMQP heartbeat 10 s: a frozen client loses its connection after ~2 missed heartbeats, and
# the broker returns its unacked messages to the queue for the other consumers.
write(f"broker_url_{who}", f"amqp://{who}:{read(f'rabbitmq_{who}_password')}@broker:5672/?heartbeat=10")
# Lab 6: Grafana admin (UI on 127.0.0.1:3000 and the evidence scripts, via its datasource proxy).
write("grafana_admin_password", secrets.token_urlsafe(18))
return 0
if __name__ == "__main__":
sys.exit(main())
+125
View File
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
"""What the load balancer thinks right now, mapped to real containers.
python scripts/lbctl.py status # table: HAProxy slot, IP, UP/DOWN/MAINT, container, X-Instance-Id
python scripts/lbctl.py wait-up 2 # wait until exactly 2 API replicas are UP in HAProxy
python scripts/lbctl.py replicas # api containers of this compose project: name, hostname, state
Reads HAProxy's runtime API (`show servers state api`) through `docker compose exec lb socat`,
so no admin port is published. Container hostname = X-Instance-Id of that replica.
Prints no secrets. Used by student-tests and bench scripts as a library as well.
"""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
# srv_op_state of HAProxy (src/server.h): 0 stopped, 1 starting, 2 running, 3 stopping.
OP_STATE = {0: "DOWN", 1: "STARTING", 2: "UP", 3: "STOPPING"}
ADMIN_RMAINT = 0x20 # slot without a resolved address (no running container behind it)
def run(*args: str, timeout: float = 60) -> str:
result = subprocess.run(list(args), cwd=ROOT, capture_output=True, text=True, encoding="utf-8",
timeout=timeout)
if result.returncode != 0:
raise RuntimeError(f"{' '.join(args[:3])}... failed: {result.stderr.strip()[:300]}")
return result.stdout
def replicas(all_states: bool = True) -> list[dict]:
"""API containers of this compose project (running and stopped)."""
ids = run("docker", "compose", "ps", "-q", *(["-a"] if all_states else []), "api").split()
if not ids:
return []
data = json.loads(run("docker", "inspect", *ids))
result = []
for item in data:
networks = item["NetworkSettings"]["Networks"] or {}
result.append({
"id": item["Id"][:12],
"name": item["Name"].lstrip("/"),
"hostname": item["Config"]["Hostname"],
"state": item["State"]["Status"],
"health": (item["State"].get("Health") or {}).get("Status", "-"),
"exit_code": item["State"]["ExitCode"],
"started_at": item["State"]["StartedAt"],
"pid": item["State"]["Pid"],
"ips": sorted(n["IPAddress"] for n in networks.values() if n.get("IPAddress")),
# compose network name without the project prefix -> IP, e.g. {"edge": ..., "data": ...}
"networks": {name.split("_", 1)[-1]: n["IPAddress"] for name, n in networks.items() if n.get("IPAddress")},
})
return sorted(result, key=lambda r: r["name"])
def lb_servers() -> list[dict]:
raw = run("docker", "compose", "exec", "-T", "lb", "sh", "-c",
'echo "show servers state api" | socat stdio /var/lib/haproxy/admin.sock')
by_ip = {ip: r for r in replicas() for ip in r["ips"]}
servers = []
for line in raw.splitlines():
parts = line.split()
if len(parts) < 7 or not parts[0].isdigit():
continue
name, addr, op, admin = parts[3], parts[4], int(parts[5]), int(parts[6])
if admin & ADMIN_RMAINT or addr == "-":
state = "MAINT"
else:
state = OP_STATE.get(op, str(op))
container = by_ip.get(addr)
servers.append({"slot": name, "addr": addr, "state": state,
"container": container["name"] if container else None,
"instance_id": container["hostname"] if container else None})
return servers
def up_instances() -> set[str]:
return {s["instance_id"] or s["addr"] for s in lb_servers() if s["state"] == "UP"}
def wait_up(count: int, timeout: float = 60) -> float:
"""Seconds until exactly `count` servers are UP (raises TimeoutError otherwise)."""
started = time.monotonic()
while True:
try:
if len(up_instances()) == count:
return time.monotonic() - started
except RuntimeError:
pass # lb restarting
if time.monotonic() - started > timeout:
raise TimeoutError(f"HAProxy does not report {count} UP API replicas after {timeout:.0f} s")
time.sleep(0.25)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
sub = parser.add_subparsers(dest="command", required=True)
sub.add_parser("status")
sub.add_parser("replicas")
wait = sub.add_parser("wait-up")
wait.add_argument("count", type=int)
wait.add_argument("--timeout", type=float, default=60)
args = parser.parse_args()
if args.command == "status":
for s in lb_servers():
if s["state"] != "MAINT" or s["container"]:
print(f"{s['slot']:6} {s['addr']:15} {s['state']:8} {s['container'] or '-':24} X-Instance-Id={s['instance_id'] or '-'}")
print(f"(other slots: MAINT, no container)")
elif args.command == "replicas":
for r in replicas():
print(f"{r['name']:24} X-Instance-Id={r['hostname']} {r['state']:8} health={r['health']:9} "
f"pid={r['pid']} started={r['started_at'][:23]} ip={','.join(r['ips']) or '-'}")
else:
took = wait_up(args.count, args.timeout)
print(f"{args.count} API replica(s) UP in HAProxy after {took:.1f} s: {sorted(up_instances())}")
return 0
if __name__ == "__main__":
sys.exit(main())
+213
View File
@@ -0,0 +1,213 @@
#!/usr/bin/env python3
"""Read the stored observations (Prometheus, Loki, Tempo) through Grafana's datasource proxy.
Only Grafana is published (127.0.0.1:3000); the stores stay on the internal network. The admin
password comes from secrets/grafana_admin_password and is never printed.
python scripts/obs.py promql 'sum(rate(http_server_request_duration_seconds_count[1m]))'
python scripts/obs.py alerts # Prometheus alerts: state, since
python scripts/obs.py trace <trace_id> # span tree of one trace (Tempo)
python scripts/obs.py logs <trace_id> # log records of one trace (Loki)
python scripts/obs.py search '{ span.messenger.job.outcome = "retry" }' # TraceQL
Used as a library by student-tests/test_observability.py and bench/*.py.
"""
from __future__ import annotations
import base64
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
GRAFANA = os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000").rstrip("/")
def _auth() -> str:
password = os.environ.get("GRAFANA_PASSWORD") or (ROOT / "secrets" / "grafana_admin_password").read_text(
encoding="utf-8").strip()
return "Basic " + base64.b64encode(f"admin:{password}".encode()).decode()
def get(uid: str, path: str, params: dict | None = None, timeout: float = 30) -> dict:
url = f"{GRAFANA}/api/datasources/proxy/uid/{uid}/{path.lstrip('/')}"
if params:
url += "?" + urllib.parse.urlencode(params)
request = urllib.request.Request(url, headers={"Authorization": _auth(), "Accept": "application/json"})
with urllib.request.urlopen(request, timeout=timeout) as response:
return json.loads(response.read())
# ----------------------------------------------------------------------------- Prometheus
def promql(expr: str, at: float | None = None) -> list[dict]:
params = {"query": expr}
if at is not None:
params["time"] = f"{at:.3f}"
return get("prometheus", "api/v1/query", params)["data"]["result"]
def scalar(expr: str, default: float | None = None) -> float | None:
"""Single value of an instant query (first series), or `default` when there is none."""
result = promql(expr)
if not result:
return default
value = float(result[0]["value"][1])
return default if value != value else value # NaN -> default
def series(expr: str, start: float, end: float, step: float = 5) -> list[dict]:
return get("prometheus", "api/v1/query_range",
{"query": expr, "start": f"{start:.3f}", "end": f"{end:.3f}", "step": str(step)})["data"]["result"]
def alerts() -> list[dict]:
"""Active alerts (pending/firing) of Prometheus: [{name, state, activeAt, value, labels}]."""
data = get("prometheus", "api/v1/alerts")["data"]["alerts"]
return [{"name": a["labels"].get("alertname"), "state": a["state"], "activeAt": a.get("activeAt"),
"value": a.get("value"), "labels": a["labels"]} for a in data]
def alert_state(name: str) -> str:
"""inactive | pending | firing (highest of the alert's series)."""
states = {a["state"] for a in alerts() if a["name"] == name}
return "firing" if "firing" in states else "pending" if "pending" in states else "inactive"
# ----------------------------------------------------------------------------- Tempo
def trace_spans(trace_id: str) -> list[dict]:
"""Flat list of spans: {service, name, kind, span_id, parent_id, start, end, duration_ms, status, attrs}."""
data = get("tempo", f"api/v2/traces/{trace_id}")
spans = []
for rs in data.get("trace", data).get("resourceSpans", []):
rattrs = _attrs(rs.get("resource", {}).get("attributes", []))
for ss in rs.get("scopeSpans", []):
for sp in ss.get("spans", []):
start, end = int(sp["startTimeUnixNano"]), int(sp["endTimeUnixNano"])
spans.append({
"service": rattrs.get("service.name"), "instance": rattrs.get("service.instance.id"),
"name": sp["name"], "kind": sp.get("kind", "").replace("SPAN_KIND_", ""),
"span_id": _hex(sp.get("spanId", "")), "parent_id": _hex(sp.get("parentSpanId", "")),
"start": start, "end": end, "duration_ms": (end - start) / 1e6,
"status": sp.get("status", {}).get("code", "STATUS_CODE_UNSET").replace("STATUS_CODE_", ""),
"attrs": _attrs(sp.get("attributes", [])),
})
return sorted(spans, key=lambda s: s["start"])
def wait_trace(trace_id: str, predicate, timeout: float = 60) -> list[dict]:
"""Poll Tempo until predicate(spans) is true (spans arrive within a few seconds)."""
deadline = time.monotonic() + timeout
spans: list[dict] = []
while time.monotonic() < deadline:
try:
spans = trace_spans(trace_id)
if spans and predicate(spans):
return spans
except urllib.error.HTTPError as exc:
if exc.code != 404:
raise
time.sleep(2)
raise AssertionError(f"trace {trace_id}: condition not met within {timeout} s; {len(spans)} spans")
def search(traceql: str, minutes: int = 60, limit: int = 20) -> list[dict]:
end = int(time.time())
return get("tempo", "api/search", {"q": traceql, "start": end - minutes * 60, "end": end,
"limit": limit}).get("traces", [])
def _hex(value: str) -> str:
if not value:
return ""
if all(c in "0123456789abcdef" for c in value.lower()) and len(value) in (16, 32):
return value.lower()
return base64.b64decode(value).hex() # OTLP JSON may carry ids base64-encoded
def _attrs(items: list) -> dict:
out = {}
for item in items:
value = item.get("value", {})
out[item["key"]] = next(iter(value.values())) if value else None
return out
def tree(spans: list[dict]) -> str:
"""Indented text tree (parent -> children), times relative to the first span."""
by_parent: dict[str, list[dict]] = {}
ids = {s["span_id"] for s in spans}
for s in spans:
by_parent.setdefault(s["parent_id"] if s["parent_id"] in ids else "", []).append(s)
t0 = spans[0]["start"] if spans else 0
lines: list[str] = []
def walk(parent: str, depth: int) -> None:
for s in by_parent.get(parent, []):
extra = {k: v for k, v in s["attrs"].items() if k in (
"http.route", "http.response.status_code", "messenger.job.attempt", "messenger.job.outcome",
"messenger.job.error_code", "db.client.connection.wait_time_ms", "error.type")}
lines.append(f"{' ' * depth}+{(s['start'] - t0) / 1e6:9.1f} ms {s['duration_ms']:8.1f} ms "
f"[{s['service']}] {s['kind']:<8} {s['name']} {s['status'] if s['status'] != 'UNSET' else ''} "
f"{json.dumps(extra, ensure_ascii=False) if extra else ''}".rstrip())
walk(s["span_id"], depth + 1)
walk("", 0)
return "\n".join(lines)
# ----------------------------------------------------------------------------- Loki
def logs(query: str, minutes: int = 60, limit: int = 200) -> list[dict]:
"""Records of a LogQL query: {ts, service, line, metadata} (oldest first)."""
end = time.time_ns()
data = get("loki", "loki/api/v1/query_range", {"query": query, "start": end - minutes * 60 * 10**9, "end": end,
"limit": limit, "direction": "backward"})
out = []
for stream in data["data"]["result"]:
labels = stream["stream"]
for value in stream["values"]:
ts, line = value[0], value[1]
meta = value[2].get("structuredMetadata", {}) if len(value) > 2 and isinstance(value[2], dict) else {}
out.append({"ts": int(ts), "service": labels.get("service_name"), "line": line,
"metadata": {**{k: v for k, v in labels.items()}, **meta}})
return sorted(out, key=lambda r: r["ts"])
def trace_logs(trace_id: str, minutes: int = 60) -> list[dict]:
return logs(f'{{service_name=~"messenger-.+"}} | trace_id="{trace_id}"', minutes)
# ----------------------------------------------------------------------------- CLI
def main(argv: list[str]) -> int:
if len(argv) < 2:
print(__doc__)
return 2
cmd, args = argv[1], argv[2:]
if cmd == "promql":
for s in promql(args[0]):
print(json.dumps(s["metric"], ensure_ascii=False), s["value"][1])
elif cmd == "alerts":
for a in alerts():
print(f"{a['name']:<32} {a['state']:<8} since {a['activeAt']} value={a['value']}")
elif cmd == "trace":
print(tree(trace_spans(args[0])))
elif cmd == "logs":
for r in trace_logs(args[0]):
meta = r["metadata"]
print(f"{r['service']:<17} {meta.get('detected_level', meta.get('severity_text', '')):<6} {r['line']:<22} "
f"span={meta.get('span_id', '')} " + " ".join(
f"{k}={meta[k]}" for k in ("request_id", "route", "status", "job_id", "outcome", "attempt")
if k in meta))
elif cmd == "search":
for t in search(args[0]):
print(t.get("traceID"), t.get("rootServiceName"), t.get("rootTraceName"), t.get("durationMs"), "ms")
else:
print(__doc__)
return 2
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
+6
View File
@@ -0,0 +1,6 @@
@echo off
rem Windows wrapper: tests/resilience.py starts the hook as a program, and Windows
rem cannot execute a .sh file directly. Runs the same scripts\restart.sh with Git Bash.
rem python tests/resilience.py --mode persistence --action-script scripts/restart.cmd
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0restart.sh"
exit /b %ERRORLEVEL%
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
# Restart hook for `make test-persistence ACTION_SCRIPT=scripts/restart.sh`.
# Restarts EVERY process of the stand: LB, all API replicas, relay, worker(s), PostgreSQL, Valkey,
# S3 (SeaweedFS) and the broker (RabbitMQ). Volumes, schema, data and queued messages are
# preserved: no `down -v`, no FLUSH, no purge, no re-seed.
# Output is suppressed by the test; run it by hand to see the steps.
set -eu
cd "$(dirname "$0")/.."
# 1. Entry point, API and the pipeline processes first: nothing is served or processed while the
# stores restart underneath.
docker compose stop lb api relay worker
# 2. Stores: clean shutdown (PostgreSQL checkpoint, Valkey AOF fsync, SeaweedFS volume/filer
# flush, RabbitMQ quorum log), then start again. Bytes live on s3data, messages on rabbitmqdata.
docker compose restart postgres valkey s3 broker
# 3. API replicas (wait for healthy stores via depends_on), the LB, then relay and worker. HAProxy
# resolves the new replica addresses through Docker DNS by itself - no stale backend list.
docker compose start api
docker compose start lb
docker compose start relay worker
echo "restart.sh: lb, api (all replicas), relay, worker, postgres, valkey, s3 and broker restarted with volumes preserved"
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
# Start every stopped API replica again (after scripts/stop-one.sh) and wait until Docker
# reports them healthy. The LB picks them up by itself (DNS re-resolution + checks, ~2-3 s);
# `python scripts/lbctl.py wait-up 2` waits for that explicitly.
set -eu
cd "$(dirname "$0")/.."
docker compose up -d --no-recreate --no-deps --wait api
docker compose ps api --format '{{.Name}} {{.Status}}'
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
# Rolling update of the API without downtime (Compose has no built-in one for a scaled service).
# 1. build the new image from the working tree;
# 2. run migrations ONCE with the new image (they must be additive / compatible with the
# running old version: expand first, contract in a later release);
# 3. for every OLD replica: start one NEW replica (scale N+1, old ones untouched), wait until
# Docker says healthy AND HAProxy has N+1 replicas UP, then stop the old one gracefully
# (SIGTERM -> readiness 503 -> HAProxy DOWN -> drain -> exit) and remove it.
# At every moment at least N replicas serve traffic. Stops on the first error (set -e);
# the old replicas that were not replaced yet keep running.
set -eu
cd "$(dirname "$0")/.."
PY="${PYTHON:-$(command -v python3 || command -v python)}"
# New image = new revision label (git commit + UTC time), visible in docker inspect and logs.
BUILD_REVISION="${BUILD_REVISION:-$(git rev-parse --short HEAD 2>/dev/null || echo dev)-$(date -u +%Y%m%dT%H%M%SZ)}"
export BUILD_REVISION
replicas="$(docker compose ps -q api | wc -l | tr -d ' ')"
[ "$replicas" -ge 1 ] || { echo "rolling-update: no running api replica" >&2; exit 2; }
old="$(docker compose ps -q api)"
echo "rolling-update: $replicas replica(s) to replace, new revision $BUILD_REVISION"
docker compose build api
docker compose run --rm --no-deps migrate
for id in $old; do
name="$(docker inspect -f '{{.Name}}' "$id" | tr -d '/')"
docker compose up -d --no-deps --no-recreate --wait --scale "api=$((replicas + 1))" api
"$PY" scripts/lbctl.py wait-up "$((replicas + 1))" --timeout 60
docker stop --time 15 "$id" >/dev/null
docker rm "$id" >/dev/null
"$PY" scripts/lbctl.py wait-up "$replicas" --timeout 60
echo "rolling-update: replaced $name"
done
for id in $(docker compose ps -q api); do
docker inspect -f '{{.Name}} revision={{index .Config.Labels "org.opencontainers.image.revision"}} {{.State.Status}}' "$id"
done
+7
View File
@@ -0,0 +1,7 @@
@echo off
rem Windows wrapper: tests/resilience.py starts the hook as a program, and Windows
rem cannot execute a .sh file directly. Runs the same scripts\stop-one.sh with Git Bash;
rem TARGET_INSTANCE_ID and STOP_MODE are inherited from the environment.
rem python tests/resilience.py --mode failover --action-script scripts/stop-one.cmd
"%ProgramFiles%\Git\bin\bash.exe" "%~dp0stop-one.sh"
exit /b %ERRORLEVEL%
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# Failover hook for `make test-failover ACTION_SCRIPT=scripts/stop-one.sh`.
# Stops exactly ONE API replica: the container whose X-Instance-Id (= container hostname,
# see src/messenger/config.py) is in TARGET_INSTANCE_ID. DB, Valkey, LB and volumes are
# not touched. The replica is LEFT STOPPED (`docker stop` = no restart by the policy);
# restore it explicitly afterwards: scripts/restore-api.sh.
# STOP_MODE=stop (default) SIGTERM: readiness 503, 3 s drain, graceful exit (~4 s)
# STOP_MODE=kill SIGKILL at once (`docker stop -t 0`): crash of the process
# Returns within 10 s. The test hides the output; run by hand to see it (no secrets printed).
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
*[!A-Za-z0-9._-]*) echo "stop-one: invalid TARGET_INSTANCE_ID" >&2; exit 2 ;;
esac
mode="${STOP_MODE:-stop}"
target=""
# Only RUNNING containers of THIS compose project's service `api` are candidates.
for id in $(docker compose ps -q api); do
if [ "$(docker inspect -f '{{.Config.Hostname}}' "$id")" = "$TARGET_INSTANCE_ID" ]; then
target="$id"
fi
done
if [ -z "$target" ]; then
echo "stop-one: no running api replica with X-Instance-Id=$TARGET_INSTANCE_ID" >&2
exit 3
fi
name="$(docker inspect -f '{{.Name}}' "$target")"
case "$mode" in
stop) docker stop --time 15 "$target" >/dev/null ;;
kill) docker stop --time 0 "$target" >/dev/null ;;
*) echo "stop-one: STOP_MODE must be stop or kill" >&2; exit 2 ;;
esac
echo "stop-one: $mode $name (X-Instance-Id=$TARGET_INSTANCE_ID) -> $(docker inspect -f '{{.State.Status}} exit={{.State.ExitCode}}' "$target")"
+138
View File
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
"""Controlled request -> its trace and logs (defense scenario, steps 2-3; evidence/trace-demo.txt).
python scripts/trace_demo.py [--base-url http://localhost:8080] [--output evidence/trace-demo.txt]
1. creates a synthetic user and chat, uploads tests/fixtures/sample.png with OUR OWN W3C
`traceparent` header (trace id chosen here) and X-Request-Id;
2. waits until the attachment is ready;
3. reads the trace from Tempo and the log records of that trace from Loki (through Grafana);
4. checks: the API continued OUR trace (same trace id, the SERVER span's parent = our span id),
the chain upload -> db enqueue -> relay PRODUCER -> worker CONSUMER -> s3/db spans exists,
and api + worker log records carry this trace_id. Prints the span tree and the log lines.
No token, password or image bytes are printed.
"""
from __future__ import annotations
import argparse
import base64
import json
import secrets
import sys
import time
import urllib.request
import uuid
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import obs # noqa: E402
def call(base: str, method: str, path: str, body=None, headers=None, raw: bytes | None = None):
h = dict(headers or {})
data = raw
if body is not None:
data = json.dumps(body).encode()
h["Content-Type"] = "application/json"
request = urllib.request.Request(base + path, data=data, method=method, headers=h)
with urllib.request.urlopen(request, timeout=30) as response:
return response.status, response.headers, json.loads(response.read() or b"null")
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://localhost:8080")
parser.add_argument("--output")
args = parser.parse_args()
base = args.base_url.rstrip("/") + "/api/v1"
out: list[str] = []
def say(line: str = "") -> None:
print(line)
out.append(line)
username = "trace_" + uuid.uuid4().hex[:10]
password = "Trace-demo-" + secrets.token_hex(8)
_, _, user = call(base, "POST", "/users", {"username": username, "display_name": "Trace demo", "password": password})
auth = "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
_, _, session = call(base, "POST", "/auth/sessions", headers={"Authorization": auth})
bearer = {"Authorization": "Bearer " + session["token"]}
_, _, chat = call(base, "POST", "/chats", {"title": "trace demo", "member_ids": [user["id"]]}, bearer)
trace_id, parent_span = secrets.token_hex(16), secrets.token_hex(8)
request_id = "trace-demo-" + uuid.uuid4().hex[:8]
image = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
status, headers, att = call(base, "POST", f"/chats/{chat['id']}/attachments?filename=sample.png", raw=image,
headers={**bearer, "Content-Type": "image/png", "X-Request-Id": request_id,
"traceparent": f"00-{trace_id}-{parent_span}-01"})
say(f"upload: HTTP {status}, status={att['status']}, X-Request-Id={headers.get('X-Request-Id')}, "
f"X-Instance-Id={headers.get('X-Instance-Id')}, X-Trace-Id={headers.get('X-Trace-Id')}")
say(f"sent traceparent: 00-{trace_id}-{parent_span}-01")
assert headers.get("X-Trace-Id") == trace_id, "the API must continue the caller's trace"
deadline = time.monotonic() + 60
while att["status"] not in ("ready", "failed"):
assert time.monotonic() < deadline, "not ready within 60 s"
time.sleep(0.5)
_, _, att = call(base, "GET", f"/attachments/{att['id']}", headers=bearer)
say(f"attachment {att['id']}: {att['status']}, variants={[v['name'] for v in att['variants']]}")
def complete(spans):
kinds = {(s["service"], s["kind"]) for s in spans}
return (("messenger-api", "SERVER") in kinds and ("messenger-relay", "PRODUCER") in kinds
and ("messenger-worker", "CONSUMER") in kinds
and any(s["name"] == "db jobs.complete" for s in spans))
spans = obs.wait_trace(trace_id, complete, timeout=90)
say(f"\nTempo: trace {trace_id}, {len(spans)} spans")
say(obs.tree(spans))
server = next(s for s in spans if s["service"] == "messenger-api" and s["kind"] == "SERVER")
producer = next(s for s in spans if s["kind"] == "PRODUCER")
consumer = next(s for s in spans if s["kind"] == "CONSUMER")
ids = {s["span_id"]: s for s in spans}
checks = {
"API SERVER span continues our traceparent (parent = our span id)": server["parent_id"] == parent_span,
"relay PRODUCER is inside the upload trace (ancestor = API SERVER span)": _ancestor(producer, server, ids),
"worker CONSUMER is a child of the PRODUCER": consumer["parent_id"] == producer["span_id"],
"worker wrote to S3 inside the job (s3 put spans)": any(
s["name"] == "s3 put" and _ancestor(s, consumer, ids) for s in spans),
"worker committed the result (db jobs.complete span)": any(
s["name"] == "db jobs.complete" and _ancestor(s, consumer, ids) for s in spans),
}
time.sleep(3)
records = obs.trace_logs(trace_id)
say(f"\nLoki: {len(records)} log records with trace_id={trace_id}")
for r in records:
m = r["metadata"]
say(f" {r['service']:<17} {r['line']:<18} span_id={m.get('span_id', '')} " + " ".join(
f"{k}={m[k]}" for k in ("request_id", "route", "status", "job_id", "outcome") if k in m))
services = {r["service"] for r in records}
checks["API log record of the request has this trace_id and our X-Request-Id"] = any(
r["service"] == "messenger-api" and r["metadata"].get("request_id") == request_id for r in records)
checks["worker log record (job_done) has this trace_id"] = any(
r["service"] == "messenger-worker" and r["line"] == "job_done" for r in records)
say("\nChecks:")
for name, ok in checks.items():
say(f" [{'PASS' if ok else 'FAIL'}] {name}")
say(f"services in logs: {sorted(services)}")
if args.output:
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
Path(args.output).write_text("\n".join(out) + "\n", encoding="utf-8", newline="\n")
return 0 if all(checks.values()) else 1
def _ancestor(span: dict, ancestor: dict, ids: dict) -> bool:
seen = 0
while span["parent_id"] and seen < 100:
if span["parent_id"] == ancestor["span_id"]:
return True
span = ids.get(span["parent_id"])
if span is None:
return False
seen += 1
return False
if __name__ == "__main__":
sys.exit(main())