forked from mtusi2026/mtusi2026lab6
ЛР 6 — БВТ2301 — Курлова — на 5 (трек 1 «Цена наблюдаемости»)
Перенесён минимум lab5 без изменения API и добавлена наблюдаемость: - OTel SDK в API и worker: traces, metrics, logs по OTLP; W3C trace context API -> outbox -> RabbitMQ -> worker (producer/consumer spans, retry в той же трассе); - OTel Collector (memory_limiter, scrub, batch, ограниченные очереди, профиль tail sampling), Prometheus, Loki, Tempo, Grafana с provisioning, dashboard и 6 alert rules с runbooks; - проверки: наблюдаемость и приватность, инциденты A/B/C, насыщение worker, переполнение очереди exporter, эксперимент трека 1 (4 конфигурации x 3 прогона); - CI job со сборкой и запуском стенда; REPORT.md с доказательствами в evidence/.
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Every Prometheus query of the provisioned dashboard must parse and return data (after some traffic).
|
||||
|
||||
python3 student-tests/check_dashboard.py
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
dash = json.loads((ROOT / "infra/grafana/dashboards/messenger.json").read_text(encoding="utf-8"))
|
||||
bad = 0
|
||||
for panel in dash["panels"]:
|
||||
for t in panel.get("targets", []):
|
||||
if t.get("datasource", {}).get("type") != "prometheus":
|
||||
continue
|
||||
expr = t["expr"].replace("$__rate_interval", "2m")
|
||||
try:
|
||||
rows = obs.prom(expr)
|
||||
status = "ok %3d series" % len(rows) if rows else "EMPTY"
|
||||
except urllib.error.HTTPError as exc:
|
||||
status, rows = "ERROR %s" % exc.read()[:120], None
|
||||
if not rows:
|
||||
bad += 1
|
||||
print("%-16s %-48s %s" % (status, panel["title"][:48], t.get("legendFormat", "")))
|
||||
print("panels: %d, prometheus queries without data: %d" % (len(dash["panels"]), bad))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- the same panels executed BY GRAFANA (/api/ds/query)
|
||||
# Proves the provisioned datasources work from Grafana itself (Prometheus, Loki and Tempo), with Grafana macros.
|
||||
import base64 # noqa: E402
|
||||
import urllib.request # noqa: E402
|
||||
|
||||
password = (ROOT / "secrets/grafana_admin_password").read_text().strip()
|
||||
auth = "Basic " + base64.b64encode(("admin:" + password).encode()).decode()
|
||||
via_bad = 0
|
||||
for panel in dash["panels"]:
|
||||
for t in panel.get("targets", []):
|
||||
q = dict(t)
|
||||
q.setdefault("datasource", panel.get("datasource"))
|
||||
if q["datasource"]["type"] == "tempo":
|
||||
# Grafana 11 runs TraceQL search in the browser through the datasource proxy, not /api/ds/query
|
||||
# ("backend TraceQL search queries are not supported"): check exactly that proxy path.
|
||||
import time as _t
|
||||
import urllib.parse as _p
|
||||
url = ("http://127.0.0.1:3000/api/datasources/proxy/uid/tempo/api/search?" +
|
||||
_p.urlencode({"q": q["query"], "limit": q.get("limit", 20), "start": int(_t.time()) - 1800,
|
||||
"end": int(_t.time())}))
|
||||
req = urllib.request.Request(url, headers={"Authorization": auth})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as response:
|
||||
n = len(json.loads(response.read()).get("traces", []))
|
||||
status = "ok %5d traces" % n if n else "EMPTY"
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = "ERROR HTTP %s" % exc.code
|
||||
if not status.startswith("ok"):
|
||||
via_bad += 1
|
||||
print("grafana %-8s %-18s %-48s (datasource proxy)" % ("tempo", status, panel["title"][:48]))
|
||||
continue
|
||||
body = json.dumps({"queries": [q], "from": "now-30m", "to": "now"}).encode()
|
||||
req = urllib.request.Request("http://127.0.0.1:3000/api/ds/query", data=body, method="POST",
|
||||
headers={"Content-Type": "application/json", "Authorization": auth})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=60) as response:
|
||||
res = json.loads(response.read())["results"][q["refId"]]
|
||||
frames = res.get("frames", [])
|
||||
rows = sum(len((f.get("data") or {}).get("values", [[]])[0] or []) for f in frames)
|
||||
status = "ERROR %s" % res["error"][:100] if res.get("error") else ("ok %5d values" % rows if rows else "EMPTY")
|
||||
except urllib.error.HTTPError as exc:
|
||||
status = "ERROR HTTP %s %s" % (exc.code, exc.read()[:100])
|
||||
if not status.startswith("ok"):
|
||||
via_bad += 1
|
||||
print("grafana %-8s %-18s %-48s" % (q["datasource"]["type"], status, panel["title"][:48]))
|
||||
print("via Grafana: queries without data or with errors: %d" % via_bad)
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Query helpers for the telemetry backends (stdlib only). Backends listen on 127.0.0.1 (compose.yaml).
|
||||
|
||||
Never prints tokens or passwords; callers print only ids, counts, span names and attributes.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
PROM = os.environ.get("PROM_URL", "http://127.0.0.1:9090")
|
||||
LOKI = os.environ.get("LOKI_URL", "http://127.0.0.1:3100")
|
||||
TEMPO = os.environ.get("TEMPO_URL", "http://127.0.0.1:3200")
|
||||
|
||||
|
||||
def _get(url, params=None, timeout=15):
|
||||
if params:
|
||||
url += "?" + urllib.parse.urlencode(params)
|
||||
with urllib.request.urlopen(url, timeout=timeout) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def prom(expr, at=None):
|
||||
"""Instant query -> list of (labels, float value)."""
|
||||
params = {"query": expr}
|
||||
if at:
|
||||
params["time"] = at
|
||||
data = _get(PROM + "/api/v1/query", params)["data"]["result"]
|
||||
return [(r["metric"], float(r["value"][1])) for r in data]
|
||||
|
||||
|
||||
def prom_scalar(expr, default=0.0, at=None):
|
||||
rows = prom(expr, at)
|
||||
return rows[0][1] if rows else default
|
||||
|
||||
|
||||
def prom_range(expr, start, end, step=5):
|
||||
data = _get(PROM + "/api/v1/query_range", {"query": expr, "start": start, "end": end, "step": step})
|
||||
return data["data"]["result"]
|
||||
|
||||
|
||||
def alerts():
|
||||
"""{alertname: state} for pending/firing alerts in Prometheus."""
|
||||
out = {}
|
||||
for a in _get(PROM + "/api/v1/alerts")["data"]["alerts"]:
|
||||
out[a["labels"]["alertname"]] = a["state"]
|
||||
return out
|
||||
|
||||
|
||||
def loki(query, minutes=15, limit=500):
|
||||
end = time.time_ns()
|
||||
data = _get(LOKI + "/loki/api/v1/query_range", {"query": query, "limit": limit, "direction": "forward",
|
||||
"start": end - minutes * 60 * 10**9, "end": end})
|
||||
lines = []
|
||||
for stream in data["data"]["result"]:
|
||||
for ts, line in stream["values"]:
|
||||
lines.append({"ts": int(ts), "line": line, **stream["stream"]})
|
||||
return sorted(lines, key=lambda item: item["ts"])
|
||||
|
||||
|
||||
def tempo_search(traceql, minutes=30, limit=100, start=None, end=None):
|
||||
end = int(end or time.time() + 60)
|
||||
start = int(start or end - 60 - minutes * 60)
|
||||
data = _get(TEMPO + "/api/search", {"q": traceql, "start": start, "end": end, "limit": limit, "spss": 50},
|
||||
timeout=60)
|
||||
return data.get("traces", [])
|
||||
|
||||
|
||||
def _hex(value):
|
||||
return base64.b64decode(value).hex() if value else None
|
||||
|
||||
|
||||
def _attr(value):
|
||||
for key in ("stringValue", "intValue", "boolValue", "doubleValue"):
|
||||
if key in value:
|
||||
return value[key]
|
||||
return None
|
||||
|
||||
|
||||
def tempo_trace(trace_id):
|
||||
"""Flat list of spans: service, name, kind, span_id, parent_id, duration_ms, status, attrs (dict)."""
|
||||
try:
|
||||
data = _get(TEMPO + "/api/traces/" + trace_id)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code == 404:
|
||||
return []
|
||||
raise
|
||||
spans = []
|
||||
for batch in data.get("batches", []):
|
||||
service = {a["key"]: _attr(a["value"]) for a in batch["resource"]["attributes"]}.get("service.name")
|
||||
for scope in batch.get("scopeSpans", []):
|
||||
for s in scope["spans"]:
|
||||
spans.append({
|
||||
"service": service, "name": s["name"], "kind": s.get("kind", "").replace("SPAN_KIND_", ""),
|
||||
"span_id": _hex(s["spanId"]), "parent_id": _hex(s.get("parentSpanId")),
|
||||
"start": int(s["startTimeUnixNano"]),
|
||||
"duration_ms": (int(s["endTimeUnixNano"]) - int(s["startTimeUnixNano"])) / 1e6,
|
||||
"status": s.get("status", {}).get("code", "").replace("STATUS_CODE_", "") or "UNSET",
|
||||
"attrs": {a["key"]: _attr(a["value"]) for a in s.get("attributes", [])},
|
||||
})
|
||||
return sorted(spans, key=lambda item: item["start"])
|
||||
|
||||
|
||||
def tempo_raw(trace_id):
|
||||
with urllib.request.urlopen(TEMPO + "/api/traces/" + trace_id, timeout=15) as response:
|
||||
return response.read().decode("utf-8", "replace")
|
||||
|
||||
|
||||
def print_tree(spans, out=print, skip_db=False):
|
||||
children = {}
|
||||
ids = {s["span_id"] for s in spans}
|
||||
for s in spans:
|
||||
children.setdefault(s["parent_id"] if s["parent_id"] in ids else None, []).append(s)
|
||||
|
||||
def walk(parent, depth):
|
||||
for s in children.get(parent, []):
|
||||
if skip_db and s["kind"] == "CLIENT" and s["name"].split()[0] in ("SELECT", "UPDATE", "INSERT", "DELETE"):
|
||||
continue
|
||||
extra = {k: v for k, v in s["attrs"].items() if k.startswith(("messenger.", "messaging.message", "db.system",
|
||||
"http.response.status_code", "rpc.method"))}
|
||||
out("%s%-8s %-9s %-44s %8.1f ms %-5s %s" % (" " * depth, s["service"].replace("messenger-", ""), s["kind"],
|
||||
s["name"][:44], s["duration_ms"], s["status"],
|
||||
json.dumps(extra, ensure_ascii=False)))
|
||||
walk(s["span_id"], depth + 1)
|
||||
|
||||
walk(None, 0)
|
||||
|
||||
|
||||
def wait_for(predicate, seconds=60, interval=2):
|
||||
deadline = time.monotonic() + seconds
|
||||
value = None
|
||||
while time.monotonic() < deadline:
|
||||
value = predicate()
|
||||
if value:
|
||||
return value
|
||||
time.sleep(interval)
|
||||
return value
|
||||
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Open-loop load generator (stdlib only): fixed arrival rate, latency measured from the SCHEDULED send time,
|
||||
so a slow server cannot slow down the generator (no coordinated omission while threads are available).
|
||||
|
||||
Mix per arrival: 75% POST message, 25% GET history (limit=20); plus an independent upload stream (sample.png).
|
||||
Rare injected requests (FAULT_INJECTION=1 on the stand): `X-Fault: slow` (+600 ms) and `X-Fault: error` (500)
|
||||
are added to GET history with the given percentages, to measure whether such traces survive sampling.
|
||||
|
||||
python3 student-tests/openloop.py --rate 40 --duration 60 --upload-rate 1 --slow-pct 1 --error-pct 1 \
|
||||
--output evidence/x.json
|
||||
Tokens stay in memory; the summary contains counts, percentiles and timestamps only.
|
||||
"""
|
||||
import argparse
|
||||
import http.client
|
||||
import json
|
||||
import queue
|
||||
import random
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
k = max(0, min(len(values) - 1, int(round(p / 100.0 * len(values) + 0.5)) - 1))
|
||||
return values[k]
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, base_url, users=4, threads=64, timeout=30.0):
|
||||
self.base = urlsplit(base_url)
|
||||
self.threads = threads
|
||||
self.timeout = timeout
|
||||
c = Client(base_url)
|
||||
self.actors = []
|
||||
for i in range(users):
|
||||
a, b = c.user("load%da" % i), c.user("load%db" % i)
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=a,
|
||||
body={"title": "load %d" % i, "member_ids": [a["id"], b["id"]]}, schema="Chat")["json"]
|
||||
self.actors.append((a["token"], chat["id"]))
|
||||
self.lock = threading.Lock()
|
||||
self.results = []
|
||||
self.local = threading.local()
|
||||
|
||||
def conn(self):
|
||||
c = getattr(self.local, "conn", None)
|
||||
if c is None:
|
||||
c = http.client.HTTPConnection(self.base.hostname, self.base.port or 80, timeout=self.timeout)
|
||||
self.local.conn = c
|
||||
return c
|
||||
|
||||
def request(self, method, path, body=None, headers=None):
|
||||
for attempt in (1, 2): # second attempt only for a dropped keep-alive connection BEFORE sending
|
||||
conn = self.conn()
|
||||
try:
|
||||
conn.request(method, path, body=body, headers=headers or {})
|
||||
response = conn.getresponse()
|
||||
response.read()
|
||||
return response.status, response.getheader("X-Request-Id")
|
||||
except (http.client.RemoteDisconnected, ConnectionResetError, BrokenPipeError) as exc:
|
||||
conn.close()
|
||||
self.local.conn = None
|
||||
if attempt == 2:
|
||||
return "conn_error:" + type(exc).__name__, None
|
||||
except (OSError, http.client.HTTPException) as exc:
|
||||
conn.close()
|
||||
self.local.conn = None
|
||||
return "error:" + type(exc).__name__, None
|
||||
return "error", None
|
||||
|
||||
def one(self, kind, fault, scheduled):
|
||||
token, chat = random.choice(self.actors)
|
||||
headers = {"Authorization": "Bearer " + token}
|
||||
if fault:
|
||||
headers["X-Fault"] = fault
|
||||
if kind == "post_message":
|
||||
headers.update({"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex})
|
||||
status, rid = self.request("POST", "/api/v1/chats/%s/messages" % chat,
|
||||
json.dumps({"text": "нагрузка " + uuid.uuid4().hex[:8]}).encode(), headers)
|
||||
elif kind == "get_history":
|
||||
status, rid = self.request("GET", "/api/v1/chats/%s/messages?limit=20" % chat, None, headers)
|
||||
else:
|
||||
headers["Content-Type"] = "image/png"
|
||||
status, rid = self.request("POST", "/api/v1/chats/%s/attachments?filename=load.png" % chat, SAMPLE, headers)
|
||||
done = time.monotonic()
|
||||
with self.lock:
|
||||
self.results.append({"kind": kind, "fault": fault, "status": status, "latency": done - scheduled,
|
||||
"at": time.time(), "rid": rid})
|
||||
|
||||
def run(self, rate, duration, upload_rate=0.0, slow_pct=0.0, error_pct=0.0, stop_event=None):
|
||||
work = queue.Queue()
|
||||
start = time.monotonic()
|
||||
self.started_at = time.time()
|
||||
|
||||
def worker():
|
||||
while True:
|
||||
item = work.get()
|
||||
if item is None:
|
||||
return
|
||||
self.one(*item)
|
||||
|
||||
pool = [threading.Thread(target=worker, daemon=True) for _ in range(self.threads)]
|
||||
for t in pool:
|
||||
t.start()
|
||||
|
||||
def schedule(r, picker):
|
||||
if r <= 0:
|
||||
return
|
||||
n = 0
|
||||
while True:
|
||||
due = start + n / r
|
||||
if due - start >= duration or (stop_event and stop_event.is_set()):
|
||||
return
|
||||
delay = due - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
work.put(picker() + (due,))
|
||||
n += 1
|
||||
|
||||
def pick_main():
|
||||
if random.random() < 0.75:
|
||||
return ("post_message", None)
|
||||
roll = random.random() * 100
|
||||
fault = "slow" if roll < slow_pct * 4 else "error" if roll < (slow_pct + error_pct) * 4 else None
|
||||
return ("get_history", fault) # 25% share * 4 = requested share of ALL requests
|
||||
|
||||
schedulers = [threading.Thread(target=schedule, args=(rate, pick_main), daemon=True),
|
||||
threading.Thread(target=schedule, args=(upload_rate, lambda: ("upload", None)), daemon=True)]
|
||||
for t in schedulers:
|
||||
t.start()
|
||||
for t in schedulers:
|
||||
t.join()
|
||||
backlog = work.qsize()
|
||||
for _ in pool:
|
||||
work.put(None)
|
||||
for t in pool:
|
||||
t.join(self.timeout + 5)
|
||||
self.finished_at = time.time()
|
||||
return self.summary(rate, duration, upload_rate, slow_pct, error_pct, backlog)
|
||||
|
||||
def summary(self, rate, duration, upload_rate, slow_pct, error_pct, backlog):
|
||||
res = self.results
|
||||
ok = [r for r in res if isinstance(r["status"], int) and r["status"] < 400]
|
||||
plain_ok = [r["latency"] for r in ok if r["fault"] is None and r["kind"] != "upload"]
|
||||
out = {
|
||||
"profile": {"rate_rps": rate, "duration_s": duration, "upload_rate_rps": upload_rate,
|
||||
"slow_pct": slow_pct, "error_pct": error_pct, "threads": self.threads,
|
||||
"mix": "75% POST message / 25% GET history(limit=20); uploads separate"},
|
||||
"started_at": self.started_at, "finished_at": self.finished_at, "generator_backlog_at_end": backlog,
|
||||
"requests": len(res), "ok": len(ok),
|
||||
"successful_rps": round(len(ok) / max(duration, 1e-9), 2),
|
||||
"status_counts": {},
|
||||
"server_errors_unexpected": sum(1 for r in res if r["fault"] != "error" and (
|
||||
not isinstance(r["status"], int) or r["status"] >= 500)),
|
||||
"latency_ms_plain_ok": {p: round(percentile(plain_ok, q) * 1000, 2) if plain_ok else None
|
||||
for p, q in (("p50", 50), ("p95", 95), ("p99", 99), ("max", 100))},
|
||||
"faults_sent": {"slow": sum(1 for r in res if r["fault"] == "slow"),
|
||||
"error": sum(1 for r in res if r["fault"] == "error")},
|
||||
"by_kind": {},
|
||||
}
|
||||
for r in res:
|
||||
key = str(r["status"])
|
||||
out["status_counts"][key] = out["status_counts"].get(key, 0) + 1
|
||||
for kind in ("post_message", "get_history", "upload"):
|
||||
lat = [r["latency"] for r in ok if r["kind"] == kind and r["fault"] is None]
|
||||
out["by_kind"][kind] = {"n": sum(1 for r in res if r["kind"] == kind),
|
||||
"p50_ms": round(percentile(lat, 50) * 1000, 2) if lat else None,
|
||||
"p99_ms": round(percentile(lat, 99) * 1000, 2) if lat else None}
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--rate", type=float, default=40)
|
||||
p.add_argument("--duration", type=float, default=60)
|
||||
p.add_argument("--upload-rate", type=float, default=0)
|
||||
p.add_argument("--slow-pct", type=float, default=0)
|
||||
p.add_argument("--error-pct", type=float, default=0)
|
||||
p.add_argument("--threads", type=int, default=64)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
load = Load(a.base_url, threads=a.threads)
|
||||
summary = load.run(a.rate, a.duration, a.upload_rate, a.slow_pct, a.error_pct)
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if a.output:
|
||||
Path(a.output).write_text(text + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 1: the queue under load. Open-loop upload arrivals against the running stack, metrics from the DB.
|
||||
|
||||
Each run:
|
||||
1. (re)creates the worker service with WORKER_REPLICAS / WORKER_CONCURRENCY / WORKER_PREFETCH
|
||||
2. sends uploads at a FIXED arrival rate (open loop: the schedule does not wait for responses)
|
||||
3. samples worker container memory (docker stats) and accepted-but-unfinished jobs once per second
|
||||
4. waits until every accepted upload is ready/failed and computes from attachment_jobs:
|
||||
queue lag = first_started_at - created_at (time a job waited for a worker)
|
||||
time to ready = finished_at - attachment.created_at
|
||||
throughput = finished jobs / (last finish - first arrival)
|
||||
Rejections (503 queue_full from admission control) are counted, not retried.
|
||||
|
||||
python3 student-tests/queue_load.py run --size medium --rate 4 --duration 30 --concurrency 2 --prefetch 2
|
||||
python3 student-tests/queue_load.py overload --max-pending 30 --size medium --rate 12 --duration 30
|
||||
Results are appended as JSON lines to evidence/track1/results.jsonl.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from stand import ROOT, Client, Failure, compose, log, sql, wait_http_ready
|
||||
|
||||
OUT = ROOT / "evidence/track1"
|
||||
SIZES = {"small": (640, 400, "JPEG"), "medium": (4000, 3000, "JPEG"), "large": (6000, 4000, "PNG")}
|
||||
|
||||
GEN = r'''
|
||||
import io, random, sys
|
||||
from PIL import Image, ImageChops, ImageDraw
|
||||
w, h, fmt = int(sys.argv[1]), int(sys.argv[2]), sys.argv[3]
|
||||
if fmt == "JPEG": # photo-like noise: realistic JPEG sizes
|
||||
chan = [Image.effect_noise((max(8, w // 24), max(8, h // 24)), 90).resize((w, h), Image.Resampling.BICUBIC) for _ in range(3)]
|
||||
grain = Image.effect_noise((w, h), 12)
|
||||
img = Image.merge("RGB", [ImageChops.add(c, grain, 1.0, -6) for c in chan])
|
||||
else: # graphics-like PNG: compresses well (stays under 10 MiB) but must be fully decoded (no DCT scaling)
|
||||
img = Image.linear_gradient("L").resize((w, h)).convert("RGB")
|
||||
draw, rnd = ImageDraw.Draw(img), random.Random(1)
|
||||
for _ in range(400):
|
||||
x, y, r = rnd.randrange(w), rnd.randrange(h), rnd.randrange(20, 300)
|
||||
draw.ellipse((x, y, x + r, y + r), fill=(rnd.randrange(256), rnd.randrange(256), rnd.randrange(256)))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, fmt, **({"quality": 90} if fmt == "JPEG" else {"compress_level": 6}))
|
||||
sys.stdout.buffer.write(buf.getvalue())
|
||||
'''
|
||||
|
||||
|
||||
def image(size):
|
||||
w, h, fmt = SIZES[size]
|
||||
cache = OUT / ("fixture-%s.%s" % (size, fmt.lower()))
|
||||
if not cache.exists():
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
data = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "-c", GEN, str(w), str(h), fmt],
|
||||
cwd=ROOT, capture_output=True, check=True).stdout
|
||||
cache.write_bytes(data)
|
||||
return cache.read_bytes(), "image/png" if fmt == "PNG" else "image/jpeg"
|
||||
|
||||
|
||||
def set_worker(replicas, concurrency, prefetch, cpus="2.00"):
|
||||
env = dict(os.environ, WORKER_REPLICAS=str(replicas), WORKER_CONCURRENCY=str(concurrency),
|
||||
WORKER_PREFETCH=str(prefetch), WORKER_CPUS=cpus)
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--wait", "worker"],
|
||||
cwd=ROOT, env=env, check=True, capture_output=True, timeout=180)
|
||||
|
||||
|
||||
def set_admission(max_pending):
|
||||
env = dict(os.environ, MAX_PENDING_JOBS=str(max_pending))
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--no-deps", "--wait", "api-1", "api-2"],
|
||||
cwd=ROOT, env=env, check=True, capture_output=True, timeout=180)
|
||||
|
||||
|
||||
def parse_mem(text):
|
||||
value = text.split("/")[0].strip()
|
||||
for unit, mult in (("GiB", 1024), ("MiB", 1), ("KiB", 1 / 1024), ("B", 1 / 1048576)):
|
||||
if value.endswith(unit):
|
||||
return float(value[: -len(unit)]) * mult
|
||||
return 0.0
|
||||
|
||||
|
||||
class Sampler(threading.Thread):
|
||||
def __init__(self, tag):
|
||||
super().__init__(daemon=True)
|
||||
self.tag = tag
|
||||
self.stop = threading.Event()
|
||||
self.rss, self.pending, self.cpu = [], [], []
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
ids = compose("ps", "-q", "worker", check_rc=False).split()
|
||||
if ids:
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}|{{.CPUPerc}}", *ids],
|
||||
capture_output=True, text=True).stdout
|
||||
rows = [line.split("|") for line in out.splitlines() if "|" in line]
|
||||
self.rss.append(sum(parse_mem(r[0]) for r in rows))
|
||||
self.cpu.append(sum(float(r[1].rstrip("%") or 0) for r in rows))
|
||||
try:
|
||||
self.pending.append(int(sql("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
|
||||
" WHERE a.filename LIKE 'load-%s-%%' AND j.state IN ('queued','processing')"
|
||||
% self.tag)[0][0]))
|
||||
except Exception:
|
||||
pass
|
||||
self.stop.wait(1.0)
|
||||
|
||||
|
||||
def pct(values, q):
|
||||
if not values:
|
||||
return None
|
||||
values = sorted(values)
|
||||
return round(values[min(len(values) - 1, int(round(q * (len(values) - 1))))], 3)
|
||||
|
||||
|
||||
def drive(c, actor, chat, body, ctype, rate, duration, tag):
|
||||
"""Open-loop: request i is sent at t0 + i/rate regardless of earlier responses."""
|
||||
total = int(rate * duration)
|
||||
results = {"accepted": 0, "rejected_503": 0, "other_errors": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
def one(i):
|
||||
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote("load-%s-%05d.img" % (tag, i)))
|
||||
try:
|
||||
r = c.call("POST", path, [202, 503], actor=actor, raw=body, headers={"Content-Type": ctype})
|
||||
key = "accepted" if r["status"] == 202 else "rejected_503"
|
||||
except Exception: # connection errors, timeouts: counted, never retried
|
||||
key = "other_errors"
|
||||
with lock:
|
||||
results[key] += 1
|
||||
|
||||
t0 = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=64) as pool:
|
||||
for i in range(total):
|
||||
delay = t0 + i / rate - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
pool.submit(one, i)
|
||||
results["send_seconds"] = round(time.monotonic() - t0, 2)
|
||||
results["offered"] = total
|
||||
return results
|
||||
|
||||
|
||||
def wait_drained(tag, seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
left = int(sql("SELECT count(*) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
|
||||
" WHERE a.filename LIKE 'load-%s-%%' AND j.state IN ('queued','processing')" % tag)[0][0])
|
||||
if left == 0:
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def job_metrics(tag):
|
||||
rows = sql(
|
||||
"SELECT extract(epoch FROM a.created_at), extract(epoch FROM j.first_started_at), extract(epoch FROM j.finished_at),"
|
||||
" j.state, j.attempt FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id"
|
||||
" WHERE a.filename LIKE 'load-%s-%%'" % tag)
|
||||
done = [(float(a), float(s), float(f)) for a, s, f, st, _ in rows if st == "succeeded"]
|
||||
lag = [s - a for a, s, f in done]
|
||||
ttr = [f - a for a, s, f in done]
|
||||
span = (max(f for _, _, f in done) - min(a for a, _, _ in done)) if done else 0
|
||||
return {
|
||||
"succeeded": len(done), "failed": sum(1 for r in rows if r[3] == "failed"),
|
||||
"retries": sum(int(r[4]) - 1 for r in rows),
|
||||
"throughput_jobs_s": round(len(done) / span, 3) if span else None,
|
||||
"lag_p50_s": pct(lag, 0.5), "lag_p95_s": pct(lag, 0.95), "lag_max_s": pct(lag, 1.0),
|
||||
"ttr_p50_s": pct(ttr, 0.5), "ttr_p95_s": pct(ttr, 0.95), "ttr_max_s": pct(ttr, 1.0),
|
||||
}
|
||||
|
||||
|
||||
def record(summary):
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
with open(OUT / "results.jsonl", "a") as handle:
|
||||
handle.write(json.dumps(summary, ensure_ascii=False) + "\n")
|
||||
log(json.dumps(summary, ensure_ascii=False))
|
||||
|
||||
|
||||
def experiment(args, label, max_pending=None):
|
||||
c = Client(timeout=60)
|
||||
wait_http_ready(c)
|
||||
alice = c.user("load")
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, body={"title": "load", "member_ids": [alice["id"]]},
|
||||
schema="Chat")["json"]
|
||||
body, ctype = image(args.size)
|
||||
set_worker(args.replicas, args.concurrency, args.prefetch)
|
||||
time.sleep(2)
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
sampler = Sampler(tag)
|
||||
sampler.start()
|
||||
log("run %s tag=%s size=%s (%d KiB) rate=%s/s duration=%ss workers=%dx(c=%d,p=%d)" % (
|
||||
label, tag, args.size, len(body) >> 10, args.rate, args.duration, args.replicas, args.concurrency, args.prefetch))
|
||||
sent = drive(c, alice, chat, body, ctype, args.rate, args.duration, tag)
|
||||
load_end = time.monotonic()
|
||||
drained = wait_drained(tag, args.drain_timeout)
|
||||
drain_seconds = round(time.monotonic() - load_end, 2)
|
||||
sampler.stop.set()
|
||||
sampler.join()
|
||||
summary = {"label": label, "tag": tag, "size": args.size, "file_kib": len(body) >> 10, "rate": args.rate,
|
||||
"duration": args.duration, "replicas": args.replicas, "concurrency": args.concurrency,
|
||||
"prefetch": args.prefetch, "max_pending": max_pending, **sent, "drained": drained,
|
||||
"drain_after_load_s": drain_seconds, **job_metrics(tag),
|
||||
"pending_max": max(sampler.pending or [0]),
|
||||
"worker_mem_peak_mib": round(max(sampler.rss or [0]), 1),
|
||||
"worker_mem_median_mib": round(statistics.median(sampler.rss), 1) if sampler.rss else None,
|
||||
"worker_cpu_peak_pct": round(max(sampler.cpu or [0]), 1),
|
||||
"at": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
||||
return summary, c, alice, chat
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("mode", choices=["run", "overload"])
|
||||
parser.add_argument("--size", choices=sorted(SIZES), default="medium")
|
||||
parser.add_argument("--rate", type=float, default=4)
|
||||
parser.add_argument("--duration", type=float, default=30)
|
||||
parser.add_argument("--replicas", type=int, default=1)
|
||||
parser.add_argument("--concurrency", type=int, default=2)
|
||||
parser.add_argument("--prefetch", type=int, default=2)
|
||||
parser.add_argument("--max-pending", type=int, default=30)
|
||||
parser.add_argument("--drain-timeout", type=float, default=600)
|
||||
parser.add_argument("--label", default="")
|
||||
args = parser.parse_args()
|
||||
if args.mode == "run":
|
||||
summary, *_ = experiment(args, args.label or "c%d-p%d" % (args.concurrency, args.prefetch))
|
||||
record(summary)
|
||||
return
|
||||
# Overload: admission limit on, offered rate far above capacity, then recovery.
|
||||
set_admission(args.max_pending)
|
||||
try:
|
||||
summary, c, alice, chat = experiment(args, args.label or "overload", args.max_pending)
|
||||
# Recovery probe: after the backlog drained, a fresh upload must be ready quickly again.
|
||||
body, ctype = image("small")
|
||||
t = time.monotonic()
|
||||
att = c.call("POST", "/api/v1/chats/%s/attachments?filename=probe.png" % chat["id"], 202, actor=alice, raw=body,
|
||||
headers={"Content-Type": ctype}, schema="Attachment")["json"]
|
||||
while c.call("GET", "/api/v1/attachments/" + att["id"], actor=alice, schema="Attachment")["json"]["status"] != "ready":
|
||||
time.sleep(0.2)
|
||||
summary["recovery_probe_ready_s"] = round(time.monotonic() - t, 2)
|
||||
record(summary)
|
||||
finally:
|
||||
set_admission(200)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+132
@@ -0,0 +1,132 @@
|
||||
"""Helpers for student resilience tests: the public HTTP client plus docker compose / psql / mc access.
|
||||
|
||||
Standard library only (Python 3.9+). Images that need Pillow are generated inside the API container.
|
||||
Never prints tokens or secrets.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check, run # noqa: E402,F401
|
||||
|
||||
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
|
||||
|
||||
def log(*parts):
|
||||
print(time.strftime("%H:%M:%S"), *parts, flush=True)
|
||||
|
||||
|
||||
def compose(*args, check_rc=True, capture=True, timeout=180):
|
||||
done = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=capture, text=True, timeout=timeout)
|
||||
if check_rc and done.returncode != 0:
|
||||
raise Failure("docker compose %s failed: %s" % (" ".join(args[:2]), (done.stderr or "")[-300:]))
|
||||
return done.stdout if capture else ""
|
||||
|
||||
|
||||
def started_at(*services):
|
||||
"""Container name -> State.StartedAt, proof that a restart really happened."""
|
||||
ids = compose("ps", "-q", *services).split()
|
||||
out = subprocess.run(["docker", "inspect", "-f", "{{.Name}} {{.State.StartedAt}}", *ids],
|
||||
capture_output=True, text=True).stdout
|
||||
return "; ".join(line.strip("/")[:60] for line in out.splitlines())
|
||||
|
||||
|
||||
def sql(query):
|
||||
"""Run a read query in postgres; returns rows as lists of strings (tab separated)."""
|
||||
out = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-F", "\t", "-c", query)
|
||||
return [line.split("\t") for line in out.splitlines() if line]
|
||||
|
||||
|
||||
def s3_keys(prefix):
|
||||
"""Object keys starting with prefix, listed with the root credentials inside a throwaway minio-init container."""
|
||||
wanted, prefix = prefix, prefix[:prefix.rfind("/") + 1]
|
||||
script = ('mc alias set l http://minio:9000 "$(cat /run/secrets/minio_root_user)" '
|
||||
'"$(cat /run/secrets/minio_root_password)" >/dev/null && '
|
||||
'mc ls --recursive --json l/messenger-attachments/%s || true' % prefix)
|
||||
out = compose("run", "--rm", "--no-deps", "-T", "--entrypoint", "sh", "minio-init", "-c", script)
|
||||
keys = []
|
||||
for line in out.splitlines():
|
||||
try:
|
||||
item = json.loads(line)
|
||||
except ValueError:
|
||||
continue
|
||||
if item.get("key"):
|
||||
keys.append(prefix + item["key"])
|
||||
return sorted(k for k in keys if k.startswith(wanted))
|
||||
|
||||
|
||||
def queue_depth(queue="attachments.process"):
|
||||
out = compose("exec", "-T", "rabbitmq", "rabbitmqctl", "-q", "--vhost", "messenger", "list_queues",
|
||||
"name", "messages", "messages_ready", "messages_unacknowledged")
|
||||
for line in out.splitlines():
|
||||
parts = line.split()
|
||||
if parts and parts[0] == queue:
|
||||
return {"messages": int(parts[1]), "ready": int(parts[2]), "unacked": int(parts[3])}
|
||||
return None
|
||||
|
||||
|
||||
def wait_queue(min_ready=1, seconds=30):
|
||||
"""Quorum queue counters are refreshed by the stats emitter (~5 s), so poll."""
|
||||
deadline = time.monotonic() + seconds
|
||||
depth = None
|
||||
while time.monotonic() < deadline:
|
||||
depth = queue_depth()
|
||||
if depth and depth["ready"] >= min_ready:
|
||||
return depth
|
||||
time.sleep(1)
|
||||
return depth
|
||||
|
||||
|
||||
def jobs_cli(*args):
|
||||
done = subprocess.run(["docker", "compose", "exec", "-T", "api-1", "python", "scripts/jobs.py", *args],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=60)
|
||||
return done.returncode, json.loads(done.stdout) if done.stdout.strip() else None
|
||||
|
||||
|
||||
def wait_http_ready(c, seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/health/ready", 200)
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
raise Failure("API not ready after %ds" % seconds)
|
||||
|
||||
|
||||
def upload(c, actor, chat, body=SAMPLE, filename="sample.png", ctype="image/png", expected=202):
|
||||
path = "/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe=""))
|
||||
schema = "Attachment" if expected == 202 else None
|
||||
return c.call("POST", path, expected, actor=actor, raw=body, headers={"Content-Type": ctype}, schema=schema)["json"]
|
||||
|
||||
|
||||
def get(c, actor, att_id):
|
||||
return c.call("GET", "/api/v1/attachments/" + att_id, actor=actor, schema="Attachment")["json"]
|
||||
|
||||
|
||||
def wait_status(c, actor, att_id, statuses, seconds=120):
|
||||
deadline = time.monotonic() + seconds
|
||||
seen = []
|
||||
while time.monotonic() < deadline:
|
||||
att = get(c, actor, att_id)
|
||||
if not seen or seen[-1] != att["status"]:
|
||||
seen.append(att["status"])
|
||||
if att["status"] in statuses:
|
||||
return att, seen
|
||||
time.sleep(0.5)
|
||||
raise Failure("attachment %s did not reach %s in %ds (seen %s)" % (att_id, statuses, seconds, seen))
|
||||
|
||||
|
||||
def objects_of(att_id):
|
||||
return s3_keys("attachments/%s/" % att_id) + s3_keys("staging/%s" % att_id)
|
||||
|
||||
|
||||
def unique_name(fault=None):
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
return ("fault-%s-%s.png" % (fault, tag)) if fault else ("plain-%s.png" % tag)
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded buffering at the limit: Tempo stopped under 100 req/s until the exporter queue is FULL.
|
||||
Expected: queue_size stops at capacity, extra spans are dropped and counted, collector RSS stays under the container
|
||||
limit, API has no unexpected errors. python3 student-tests/test_exporter_queue_full.py (~5 min)
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import check, compose, log, run
|
||||
from test_incidents import docker_mem
|
||||
|
||||
|
||||
def value(expr):
|
||||
return obs.prom_scalar("sum(%s)" % expr)
|
||||
|
||||
|
||||
def main():
|
||||
load = Load("http://localhost:8080", users=4, threads=96)
|
||||
stop, summary = threading.Event(), {}
|
||||
thread = threading.Thread(target=lambda: summary.update(load.run(100, 900, 1, stop_event=stop)), daemon=True)
|
||||
thread.start()
|
||||
time.sleep(20)
|
||||
q = 'otelcol_exporter_queue_size{exporter="otlp/tempo"}'
|
||||
capacity = value('otelcol_exporter_queue_capacity{exporter="otlp/tempo"}')
|
||||
dropped0, refused0 = value("otelcol_exporter_enqueue_failed_spans_total"), value("otelcol_receiver_refused_spans_total")
|
||||
compose("stop", "-t", "5", "tempo")
|
||||
t0 = time.time()
|
||||
log("tempo stopped; 100 req/s + 1 upload/s; exporter queue capacity=%.0f batches" % capacity)
|
||||
peak_q, mems = 0, []
|
||||
try:
|
||||
for _ in range(16):
|
||||
time.sleep(12)
|
||||
size, mem = value(q), docker_mem("otel-collector")[0]
|
||||
peak_q, _ = max(peak_q, size), mems.append(mem)
|
||||
log(" +%3d s queue=%.0f/%.0f collector_rss=%s dropped=%.0f refused=%.0f" % (
|
||||
time.time() - t0, size, capacity, mem, value("otelcol_exporter_enqueue_failed_spans_total") - dropped0,
|
||||
value("otelcol_receiver_refused_spans_total") - refused0))
|
||||
dropped = value("otelcol_exporter_enqueue_failed_spans_total") - dropped0
|
||||
refused = value("otelcol_receiver_refused_spans_total") - refused0
|
||||
finally:
|
||||
compose("start", "tempo")
|
||||
stop.set()
|
||||
thread.join(60)
|
||||
log("result: peak queue=%.0f/%.0f, dropped by full queue=%.0f spans, refused by memory_limiter=%.0f spans, peak RSS=%s MiB"
|
||||
% (peak_q, capacity, dropped, refused, max(float(m.replace("MiB", "")) for m in mems)))
|
||||
log("API: requests=%s ok=%s unexpected_errors=%s p99=%s ms" % (
|
||||
summary["requests"], summary["ok"], summary["server_errors_unexpected"], summary["latency_ms_plain_ok"]["p99"]))
|
||||
check(peak_q <= capacity, "queue must stay within capacity")
|
||||
check(peak_q >= capacity * 0.95 or refused > 0, "the limit must really be reached")
|
||||
check(dropped + refused > 0, "overflow must be counted")
|
||||
check(summary["server_errors_unexpected"] == 0, "API must be unaffected")
|
||||
print("PASS: exporter buffering is bounded, overflow is dropped and counted, API unaffected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Executable
+194
@@ -0,0 +1,194 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 4 fault-injection suite (needs FAULT_INJECTION=1 on the stand, see REPORT.md).
|
||||
|
||||
Each scenario uploads a file whose display name selects an injected fault (app/faults.py) and checks the
|
||||
recovery through the public API plus DB/S3/broker state:
|
||||
A api_crash_after_commit crash between COMMIT(job+outbox) and publish -> another replica's relay publishes
|
||||
B worker_crash_after_put crash after S3 writes, before result COMMIT -> lease expiry -> same keys, one result
|
||||
C worker_crash_after_commit crash after COMMIT, before ack -> redelivery is a no-op
|
||||
D transient3 3 transient errors -> retries with growing jittered backoff -> ready
|
||||
E permanent permanent error -> failed at attempt 1, no retry, content/attach 409
|
||||
F transient6 attempts exhausted -> failed/retry_exhausted -> registry -> explicit replay -> ready;
|
||||
replay of a ready job is refused
|
||||
G worker_hang hung worker (no heartbeats) -> other worker takes over, hung one is fenced
|
||||
H poison message invalid broker message -> DLQ, not retried forever
|
||||
I broker down RabbitMQ stopped: upload still 202 (job waits in outbox) -> broker back -> ready
|
||||
usage: python3 student-tests/test_failure_windows.py [A B C ...]
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
|
||||
from stand import (Client, Failure, check, compose, get, jobs_cli, log, objects_of, queue_depth, run, sql, upload,
|
||||
unique_name, wait_http_ready, wait_status)
|
||||
|
||||
|
||||
def audit(att_id):
|
||||
return sql("SELECT action, actor, attempt, coalesce(detail->>'error_code',''), coalesce(detail->>'delay_seconds','')"
|
||||
" FROM job_audit WHERE attachment_id='%s' ORDER BY id" % att_id)
|
||||
|
||||
|
||||
def show_audit(att_id):
|
||||
for action, actor, attempt, code, delay in audit(att_id):
|
||||
log(" audit attempt=%s %-16s %-28s %s %s" % (attempt, action, actor[:28], code, ("delay=%ss" % delay) if delay else ""))
|
||||
|
||||
|
||||
def one_result(att_id):
|
||||
variants = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att_id)[0][0]
|
||||
succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att_id)[0][0]
|
||||
keys = objects_of(att_id)
|
||||
check(variants == "3", "exactly one set of 3 variant rows, got %s" % variants)
|
||||
check(succeeded == "1", "exactly one committed success, got %s" % succeeded)
|
||||
check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys),
|
||||
"original + 3 variants, staging cleaned: %s" % keys)
|
||||
|
||||
|
||||
def ready_and_single(c, actor, att_id, seconds=120):
|
||||
att, seen = wait_status(c, actor, att_id, ("ready", "failed"), seconds)
|
||||
check(att["status"] == "ready", "expected ready, got %s/%s" % (att["status"], att["error_code"]))
|
||||
log(" statuses:", " -> ".join(seen))
|
||||
show_audit(att_id)
|
||||
one_result(att_id)
|
||||
return att
|
||||
|
||||
|
||||
def scenario_a(c, alice, bob, chat):
|
||||
name = unique_name("api_crash_after_commit")
|
||||
try:
|
||||
upload(c, alice, chat, filename=name, expected=[202, 500, 502, 503])
|
||||
except Failure as exc:
|
||||
log(" client saw:", exc)
|
||||
wait_http_ready(c)
|
||||
rows = sql("SELECT id FROM attachments WHERE filename='%s'" % name)
|
||||
check(len(rows) == 1, "committed attachment must exist after API crash")
|
||||
att_id = rows[0][0]
|
||||
log(" committed attachment %s survived the API crash" % att_id)
|
||||
ready_and_single(c, bob, att_id)
|
||||
pub = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
|
||||
" WHERE j.attachment_id='%s' AND o.published_at IS NOT NULL" % att_id)[0][0]
|
||||
check(pub == "1", "outbox row published exactly once by the relay")
|
||||
|
||||
|
||||
def scenario_b(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("worker_crash_after_put"))
|
||||
ready_and_single(c, bob, att["id"])
|
||||
actions = [r[0] for r in audit(att["id"])]
|
||||
check("retry_scheduled" in actions, "lease expiry must schedule a new attempt")
|
||||
|
||||
|
||||
def scenario_c(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("worker_crash_after_commit"))
|
||||
ready_and_single(c, bob, att["id"])
|
||||
time.sleep(8)
|
||||
logs = compose("logs", "--since", "60s", "worker")
|
||||
check("decision=done" in logs, "redelivered message after crash must be a no-op")
|
||||
one_result(att["id"])
|
||||
|
||||
|
||||
def scenario_d(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("transient3"))
|
||||
ready_and_single(c, bob, att["id"])
|
||||
delays = [float(r[4]) for r in audit(att["id"]) if r[0] == "retry_scheduled"]
|
||||
check(len(delays) == 3, "three retries expected, got %s" % delays)
|
||||
bounds = [(1, 2), (2, 4), (4, 8)]
|
||||
check(all(lo <= d <= hi for d, (lo, hi) in zip(delays, bounds)), "equal-jitter backoff bounds %s" % delays)
|
||||
log(" backoff delays:", delays)
|
||||
|
||||
|
||||
def scenario_e(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("permanent"))
|
||||
failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 60)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "invalid_image", "permanent -> failed/invalid_image")
|
||||
check(failed["variants"] == [], "failed attachment has no variants")
|
||||
show_audit(att["id"])
|
||||
check([r[0] for r in audit(att["id"])].count("claimed") == 1, "permanent errors are not retried")
|
||||
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
|
||||
c.call("POST", "/api/v1/chats/%s/messages" % chat["id"], 409, actor=alice,
|
||||
body={"text": "", "attachment_ids": [att["id"]]}, headers={"Idempotency-Key": "k-" + att["id"]})
|
||||
|
||||
|
||||
def scenario_f(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("transient6"))
|
||||
failed, _ = wait_status(c, bob, att["id"], ("failed", "ready"), 120)
|
||||
check(failed["status"] == "failed" and failed["error_code"] == "retry_exhausted", "exhausted -> retry_exhausted")
|
||||
attempts = sql("SELECT attempt, max_attempts FROM attachment_jobs WHERE attachment_id='%s'" % att["id"])[0]
|
||||
check(attempts == ["5", "5"], "bounded: stopped at attempt 5 of 5, got %s" % attempts)
|
||||
rc, registry = jobs_cli("failed")
|
||||
check(any(r["attachment_id"] == att["id"] for r in registry), "failed job listed in operator registry")
|
||||
log(" failed registry contains the job; replay")
|
||||
rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite")
|
||||
check(rc == 0 and result["result"] == "queued", "replay must queue: %s" % result)
|
||||
ready_and_single(c, bob, att["id"], 120)
|
||||
rc, result = jobs_cli("replay", att["id"], "--actor", "test-suite")
|
||||
check(rc == 3 and result["result"] == "refused", "replay of a ready job must be refused: %s" % result)
|
||||
log(" second replay refused:", result["reason"])
|
||||
one_result(att["id"])
|
||||
|
||||
|
||||
def scenario_g(c, alice, bob, chat):
|
||||
att = upload(c, alice, chat, filename=unique_name("worker_hang"))
|
||||
ready_and_single(c, bob, att["id"], 150)
|
||||
rows = audit(att["id"])
|
||||
check(any(r[0] == "retry_scheduled" and r[3] == "lease_expired" for r in rows), "lease expiry detected")
|
||||
time.sleep(30) # the hung worker wakes up and must be fenced
|
||||
logs = compose("logs", "--since", "180s", "worker")
|
||||
check("lease_lost" in logs or "job_result_not_committed" in logs, "hung worker must be fenced by the lease")
|
||||
one_result(att["id"])
|
||||
|
||||
|
||||
POISON = ("import asyncio, aio_pika\n"
|
||||
"from app import config, broker\n"
|
||||
"async def m():\n"
|
||||
" conn = await broker.connect(); ch = await conn.channel(publisher_confirms=True)\n"
|
||||
" ex, _ = await broker.declare(ch)\n"
|
||||
" await ex.publish(aio_pika.Message(b'{not json', delivery_mode=2), routing_key=broker.ROUTING_KEY)\n"
|
||||
" await conn.close()\n"
|
||||
"asyncio.run(m())\n")
|
||||
|
||||
|
||||
def scenario_h(c, alice, bob, chat):
|
||||
before = (queue_depth("attachments.dlq") or {}).get("messages", 0)
|
||||
compose("exec", "-T", "api-1", "python", "-c", POISON)
|
||||
deadline = time.monotonic() + 30
|
||||
after = before
|
||||
while time.monotonic() < deadline and after <= before:
|
||||
time.sleep(1)
|
||||
after = (queue_depth("attachments.dlq") or {}).get("messages", 0)
|
||||
check(after == before + 1, "poison message must land in attachments.dlq (%s -> %s)" % (before, after))
|
||||
log(" DLQ depth %s -> %s" % (before, after))
|
||||
|
||||
|
||||
def scenario_i(c, alice, bob, chat):
|
||||
compose("stop", "-t", "10", "rabbitmq")
|
||||
try:
|
||||
att = upload(c, alice, chat, filename=unique_name())
|
||||
check(att["status"] == "queued", "upload accepted while broker is down")
|
||||
c.message(alice, chat, "", attachments=[att["id"]])
|
||||
time.sleep(3)
|
||||
pending = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
|
||||
" WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0]
|
||||
check(pending == "1", "job must wait in the outbox, got %s" % pending)
|
||||
check(get(c, bob, att["id"])["status"] == "queued", "still queued while broker is down")
|
||||
log(" broker down: upload 202, outbox holds 1 unpublished job")
|
||||
finally:
|
||||
compose("start", "rabbitmq")
|
||||
ready_and_single(c, bob, att["id"], 120)
|
||||
|
||||
|
||||
SCENARIOS = {"A": scenario_a, "B": scenario_b, "C": scenario_c, "D": scenario_d, "E": scenario_e,
|
||||
"F": scenario_f, "G": scenario_g, "H": scenario_h, "I": scenario_i}
|
||||
|
||||
|
||||
def main():
|
||||
c = Client(timeout=30)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
picked = sys.argv[1:] or list(SCENARIOS)
|
||||
for key in picked:
|
||||
log("scenario %s: %s" % (key, SCENARIOS[key].__name__))
|
||||
started = time.monotonic()
|
||||
SCENARIOS[key](c, alice, bob, chat)
|
||||
log("scenario %s PASS (%.1fs)" % (key, time.monotonic() - started))
|
||||
print("PASS: failure windows %s" % " ".join(picked))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,269 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Level 4 controlled incidents, diagnosed ONLY from stored telemetry (Prometheus / Loki / Tempo), with alert
|
||||
firing -> resolved timings. A background open-loop traffic (messages + history, 2% slow handler requests) runs all
|
||||
the time so that error ratios have a denominator.
|
||||
|
||||
A. worker stopped -> MessengerQueueLagGrowing firing; start worker -> backlog drains -> resolved
|
||||
B. DB table lock (slow DB) -> MessengerApiHighErrorRate firing; trace shows the INSERT span waiting 5 s on the lock
|
||||
(vs. an X-Fault: slow request: long handler, short DB spans); unlock -> resolved
|
||||
C. Tempo + Loki stopped -> API keeps working, collector queue bounded, drops counted, TelemetryExportFailing;
|
||||
collector stopped -> API keeps working, SDK queues bounded (RSS flat)
|
||||
|
||||
python3 student-tests/test_incidents.py [--only A,B,C] (stack running, FAULT_INJECTION=1; ~15 min)
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import Client, check, compose, log, run, upload, wait_status
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
RESULTS = {}
|
||||
|
||||
|
||||
def docker_mem(service):
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.MemUsage}}\t{{.CPUPerc}}"],
|
||||
capture_output=True, text=True).stdout
|
||||
for line in out.splitlines():
|
||||
name, mem, cpu = line.split("\t")
|
||||
if name.startswith("mtusi-lab6-%s-" % service):
|
||||
return mem.split(" / ")[0], cpu
|
||||
return "stopped", "-"
|
||||
|
||||
|
||||
def wait_alert(name, want, seconds, t0):
|
||||
"""want='firing' waits for firing; want='resolved' waits until the alert is gone. Returns seconds since t0."""
|
||||
deadline = time.monotonic() + seconds
|
||||
pending_at = None
|
||||
while time.monotonic() < deadline:
|
||||
state = obs.alerts().get(name)
|
||||
if state == "pending" and pending_at is None:
|
||||
pending_at = time.time() - t0
|
||||
log(" %s pending (+%.0f s)" % (name, pending_at))
|
||||
if (want == "firing" and state == "firing") or (want == "resolved" and state is None):
|
||||
elapsed = time.time() - t0
|
||||
log(" %s %s (+%.0f s)" % (name, want, elapsed))
|
||||
return elapsed, pending_at
|
||||
time.sleep(5)
|
||||
raise AssertionError("%s did not become %s within %d s" % (name, want, seconds))
|
||||
|
||||
|
||||
def psql(query):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-At", "-c", query)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ A
|
||||
def incident_worker(c, alice, chat):
|
||||
log("=== A. worker stopped (queue lag)")
|
||||
t0 = time.time()
|
||||
compose("stop", "-t", "20", "worker")
|
||||
log("worker stopped at %s" % time.strftime("%H:%M:%S"))
|
||||
atts = [upload(c, alice, chat, filename="incident-a.png") for _ in range(3)]
|
||||
log("3 uploads accepted (202) while worker is down: %s" % [a["id"][:8] for a in atts])
|
||||
firing, pending = wait_alert("MessengerQueueLagGrowing", "firing", 300, t0)
|
||||
|
||||
log("diagnosis from telemetry:")
|
||||
age = obs.prom_scalar('max(messenger_queue_oldest_age_seconds{queue="attachments.process"})')
|
||||
depth = {m["state"]: v for m, v in obs.prom('max by (state) (messenger_queue_depth{queue="attachments.process"})')}
|
||||
processed = obs.prom_scalar('sum(rate(messenger_jobs_processed_total[1m]))')
|
||||
log(" metrics: oldest job age=%.0f s, depth=%s, worker jobs/s over 1m=%.3f" % (age, depth, processed))
|
||||
since = int((time.time() - t0) / 60) + 1
|
||||
worker_lines = obs.loki('{service_name="messenger-worker"} | event=~"job_.*"', minutes=since)
|
||||
worker_lines = [l for l in worker_lines if l["ts"] / 1e9 > t0 + 25]
|
||||
stop_lines = obs.loki('{service_name="messenger-worker"} | event=~"worker_stop.*"', minutes=since + 1)
|
||||
log(" logs: worker job_* events after stop: %d; last worker events: %s" % (
|
||||
len(worker_lines), [l.get("event") for l in stop_lines[-2:]]))
|
||||
traces = obs.tempo_search('{span.messenger.attachment_id="%s"}' % atts[0]["id"], minutes=since + 1)
|
||||
spans = obs.tempo_trace(traces[0]["traceID"]) if traces else []
|
||||
kinds = sorted({s["kind"] for s in spans if s["kind"] != "CLIENT"})
|
||||
log(" trace of upload %s: span kinds %s -> published, no CONSUMER: the job waits in the queue" % (
|
||||
atts[0]["id"][:8], kinds))
|
||||
check("PRODUCER" in kinds and "CONSUMER" not in kinds, "trace must stop at the producer while worker is down")
|
||||
|
||||
t1 = time.time()
|
||||
compose("start", "worker")
|
||||
log("worker started (+%.0f s)" % (t1 - t0))
|
||||
for att in atts:
|
||||
wait_status(c, alice, att["id"], ("ready",), 120)
|
||||
drained = time.time() - t1
|
||||
log("backlog drained: all 3 ready %.1f s after worker start" % drained)
|
||||
resolved, _ = wait_alert("MessengerQueueLagGrowing", "resolved", 300, t1)
|
||||
RESULTS["A_worker_stopped"] = {"alert_pending_s": pending, "alert_firing_s": round(firing), "age_at_firing_s":
|
||||
round(age), "drain_after_restart_s": round(drained, 1),
|
||||
"resolved_after_restart_s": round(resolved), "lost_jobs": 0}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ B
|
||||
def incident_db(c):
|
||||
log("=== B. DB lock on messages (slow/unavailable DB for writes and history reads)")
|
||||
t0 = time.time()
|
||||
locker = subprocess.Popen(
|
||||
["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
|
||||
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(600); COMMIT;"],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
log("ACCESS EXCLUSIVE lock taken on table messages at %s" % time.strftime("%H:%M:%S"))
|
||||
try:
|
||||
firing, pending = wait_alert("MessengerApiHighErrorRate", "firing", 300, t0)
|
||||
log("diagnosis from telemetry:")
|
||||
ratio = obs.prom_scalar("messenger:http_error_ratio:rate2m")
|
||||
p95 = obs.prom_scalar("messenger:http_latency_p95:rate5m")
|
||||
by_route = obs.prom('sum by (http_route, http_response_status_code) (rate(http_server_request_duration_seconds_count'
|
||||
'{service_name="messenger-api",http_response_status_code=~"5.."}[1m]))')
|
||||
waiting = obs.prom_scalar("max(db_client_connection_pending_requests)")
|
||||
used = obs.prom_scalar('max(db_client_connection_count{service_name="messenger-api",db_client_connection_state="used"})')
|
||||
log(" metrics: 5xx ratio=%.1f%%, p95=%.2f s, pool used(max replica)=%.0f waiting=%.0f" % (
|
||||
ratio * 100, p95, used, waiting))
|
||||
for m, v in by_route:
|
||||
log(" 5xx/s %-40s %s %.2f" % (m.get("http_route"), m.get("http_response_status_code"), v))
|
||||
db_err = obs.tempo_search('{resource.service.name="messenger-api" && span.db.operation.name="INSERT"'
|
||||
' && status=error}', minutes=5, limit=5)
|
||||
check(db_err, "no trace with a failed DB span")
|
||||
spans = obs.tempo_trace(db_err[0]["traceID"])
|
||||
log(" trace %s (failed request):" % db_err[0]["traceID"])
|
||||
obs.print_tree(spans, out=lambda line: print(" " + line))
|
||||
raw = obs.tempo_raw(db_err[0]["traceID"])
|
||||
cause = next((name for name in ("LockNotAvailable", "QueryCanceled", "PoolTimeout") if name in raw), "?")
|
||||
db_span = max((s for s in spans if s["attrs"].get("db.system") == "postgresql"), key=lambda s: s["duration_ms"])
|
||||
server = [s for s in spans if s["kind"] == "SERVER"][0]
|
||||
log(" => DB span %s took %.0f ms of %.0f ms request, status %s, exception %s: the time is spent in PostgreSQL"
|
||||
% (db_span["name"], db_span["duration_ms"], server["duration_ms"], db_span["status"], cause))
|
||||
slow = obs.tempo_search('{span.messenger.fault="slow" && span.http.route="/api/v1/chats/{chat_id}/messages"}',
|
||||
minutes=10, limit=50)
|
||||
contrast = None
|
||||
for item in slow:
|
||||
sp = obs.tempo_trace(item["traceID"])
|
||||
srv = [s for s in sp if s["kind"] == "SERVER"]
|
||||
dbs = [s["duration_ms"] for s in sp if s["attrs"].get("db.system") == "postgresql"]
|
||||
if srv and dbs and srv[0]["attrs"].get("http.response.status_code") in ("200", 200) and max(dbs) < 100:
|
||||
contrast = (item["traceID"], srv[0]["duration_ms"], max(dbs), sum(dbs))
|
||||
break
|
||||
if contrast:
|
||||
log(" contrast: slow HANDLER trace %s: request %.0f ms, longest DB span %.1f ms, all DB %.1f ms"
|
||||
% contrast)
|
||||
errors = obs.loki('{service_name="messenger-api"} | severity_text=~"WARN.*|ERROR"', minutes=5)
|
||||
log(" logs: %d API warning/error records in 5 min, events=%s" % (
|
||||
len(errors), sorted({l.get("event") for l in errors})))
|
||||
blocker = psql("SELECT pid, state, wait_event_type, left(query, 60) FROM pg_stat_activity "
|
||||
"WHERE query LIKE '%LOCK TABLE messages%' AND pid <> pg_backend_pid()").strip()
|
||||
log(" operator step (pg_stat_activity) finds the blocker: %s" % blocker)
|
||||
finally:
|
||||
t1 = time.time()
|
||||
psql("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE query LIKE '%LOCK TABLE messages%'"
|
||||
" AND pid <> pg_backend_pid()")
|
||||
locker.wait(30)
|
||||
log("lock released (+%.0f s)" % (t1 - t0))
|
||||
resolved, _ = wait_alert("MessengerApiHighErrorRate", "resolved", 400, t1)
|
||||
RESULTS["B_db_lock"] = {"alert_pending_s": pending, "alert_firing_s": round(firing),
|
||||
"error_ratio_at_firing": round(ratio, 3), "p95_at_firing_s": round(p95, 2),
|
||||
"db_span_ms": round(db_span["duration_ms"]), "request_ms": round(server["duration_ms"]),
|
||||
"cause": cause, "resolved_after_unlock_s": round(resolved)}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------------------------------------ C
|
||||
def counter(expr):
|
||||
return obs.prom_scalar("sum(%s)" % expr)
|
||||
|
||||
|
||||
def incident_telemetry(load):
|
||||
log("=== C1. Tempo and Loki stopped (telemetry backends down)")
|
||||
before_res = len(load.results)
|
||||
dropped0 = counter('otelcol_exporter_enqueue_failed_spans_total') + counter(
|
||||
'otelcol_exporter_enqueue_failed_log_records_total')
|
||||
failed0 = counter('otelcol_exporter_send_failed_spans_total') + counter(
|
||||
'otelcol_exporter_send_failed_log_records_total')
|
||||
t0 = time.time()
|
||||
compose("stop", "-t", "5", "tempo", "loki")
|
||||
samples = []
|
||||
for i in range(14): # ~140 s
|
||||
time.sleep(10)
|
||||
mem, cpu = docker_mem("otel-collector")
|
||||
q_tempo = obs.prom_scalar('sum(otelcol_exporter_queue_size{exporter="otlp/tempo"})')
|
||||
q_loki = obs.prom_scalar('sum(otelcol_exporter_queue_size{exporter="otlphttp/loki"})')
|
||||
samples.append({"t": round(time.time() - t0), "collector_mem": mem, "cpu": cpu, "queue_tempo": q_tempo,
|
||||
"queue_loki": q_loki})
|
||||
log(" +%3d s collector mem=%s cpu=%s queue tempo=%.0f loki=%.0f (capacity 100 batches)" % (
|
||||
samples[-1]["t"], mem, cpu, q_tempo, q_loki))
|
||||
alert_state = obs.alerts().get("TelemetryExportFailing")
|
||||
log(" alert TelemetryExportFailing during outage: %s" % alert_state)
|
||||
check(alert_state == "firing", "TelemetryExportFailing must fire while backends are down")
|
||||
window = [r for r in load.results[before_res:]]
|
||||
bad = [r for r in window if r["fault"] != "error" and (not isinstance(r["status"], int) or r["status"] >= 500)]
|
||||
log(" API during the outage: %d requests, unexpected errors=%d; alert TelemetryExportFailing=%s" % (
|
||||
len(window), len(bad), alert_state))
|
||||
check(not bad, "API must keep working while telemetry backends are down")
|
||||
compose("start", "tempo", "loki")
|
||||
obs.wait_for(lambda: subprocess.run(["curl", "-sf", obs.TEMPO + "/ready"], capture_output=True).returncode == 0
|
||||
and subprocess.run(["curl", "-sf", obs.LOKI + "/ready"], capture_output=True).returncode == 0, 120, 3)
|
||||
t1 = time.time()
|
||||
log(" tempo/loki started and ready (+%.0f s)" % (t1 - t0))
|
||||
fresh = obs.wait_for(lambda: obs.tempo_search('{resource.service.name="messenger-api"}', start=t1,
|
||||
end=time.time() + 5, limit=20), 90, 5)
|
||||
log(" new traces after restart visible: %d (export resumed)" % len(fresh or []))
|
||||
check(fresh, "traces must flow again after the backends are back")
|
||||
resolved, _ = wait_alert("TelemetryExportFailing", "resolved", 300, t1)
|
||||
time.sleep(20)
|
||||
dropped = counter('otelcol_exporter_enqueue_failed_spans_total') + counter(
|
||||
'otelcol_exporter_enqueue_failed_log_records_total') - dropped0
|
||||
failed = counter('otelcol_exporter_send_failed_spans_total') + counter(
|
||||
'otelcol_exporter_send_failed_log_records_total') - failed0
|
||||
log(" telemetry lost and counted: enqueue_failed(queue full)=%.0f items, send_failed(retries exhausted)=%.0f items"
|
||||
% (dropped, failed))
|
||||
RESULTS["C1_backends_down"] = {"outage_s": round(t1 - t0), "api_requests": len(window), "api_unexpected_errors":
|
||||
len(bad), "collector_samples": samples, "alert": alert_state,
|
||||
"dropped_items": dropped, "send_failed_items": failed,
|
||||
"traces_after_restart": len(fresh or []),
|
||||
"alert_resolved_after_restart_s": round(resolved)}
|
||||
|
||||
log("=== C2. Collector stopped (SDK side buffering)")
|
||||
before_res = len(load.results)
|
||||
api_before = docker_mem("api-1")[0]
|
||||
compose("stop", "-t", "5", "otel-collector")
|
||||
mems = []
|
||||
for _ in range(6):
|
||||
time.sleep(10)
|
||||
mems.append(docker_mem("api-1")[0])
|
||||
window = load.results[before_res:]
|
||||
bad = [r for r in window if r["fault"] != "error" and (not isinstance(r["status"], int) or r["status"] >= 500)]
|
||||
compose("start", "otel-collector")
|
||||
log(" api-1 RSS before=%s during=%s; %d requests, unexpected errors=%d" % (api_before, mems, len(window), len(bad)))
|
||||
check(not bad, "API must keep working while the collector is down")
|
||||
RESULTS["C2_collector_down"] = {"outage_s": 60, "api1_mem_before": api_before, "api1_mem_during": mems,
|
||||
"api_requests": len(window), "api_unexpected_errors": len(bad)}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--only", default="A,B,C")
|
||||
p.add_argument("--output", default=str(ROOT / "evidence/incidents.json"))
|
||||
args = p.parse_args()
|
||||
c = Client()
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
load = Load("http://localhost:8080", users=2, threads=48)
|
||||
stop = threading.Event()
|
||||
traffic = threading.Thread(target=lambda: RESULTS.setdefault("traffic", load.run(
|
||||
10, 3600, 0, slow_pct=2, error_pct=0, stop_event=stop)), daemon=True)
|
||||
traffic.start()
|
||||
log("background traffic: 10 req/s open-loop (75% POST message, 25% history, 2% X-Fault: slow)")
|
||||
time.sleep(30)
|
||||
try:
|
||||
if "A" in args.only:
|
||||
incident_worker(c, alice, chat)
|
||||
if "B" in args.only:
|
||||
incident_db(c)
|
||||
if "C" in args.only:
|
||||
incident_telemetry(load)
|
||||
finally:
|
||||
stop.set()
|
||||
traffic.join(60)
|
||||
Path(args.output).write_text(json.dumps(RESULTS, ensure_ascii=False, indent=2, default=str) + "\n")
|
||||
log("summary written to %s" % args.output)
|
||||
print("PASS: incidents %s diagnosed from telemetry, alerts fired and resolved" % args.only)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,159 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Levels 3-4: one controlled upload and one failed request are found in traces, logs and metrics; privacy checks.
|
||||
|
||||
1. upload with fault-transient1 (attempt 1 fails transiently, attempt 2 succeeds) -> ONE trace:
|
||||
API SERVER span -> PRODUCER -> CONSUMER (retry, ERROR) -> PRODUCER -> CONSUMER (succeeded) -> S3/DB spans
|
||||
2. the same trace_id in Loki for messenger-api and messenger-worker log records
|
||||
3. X-Request-Id of a 500 (X-Fault: error) -> Loki log line -> its trace_id -> Tempo server span with that request_id
|
||||
4. no password / token / message text / filename in logs or traces; no ids in metric labels
|
||||
5. all metric names used by the dashboard and alert rules exist and have samples
|
||||
|
||||
python3 student-tests/test_observability.py (stack from REPORT.md must be running; FAULT_INJECTION=1)
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import obs
|
||||
from stand import Client, check, log, run, unique_name, upload, wait_status
|
||||
|
||||
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
FORBIDDEN_LABELS = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "url_full", "url_query",
|
||||
"filename", "text", "http_target", "url_path"}
|
||||
REQUIRED_METRICS = [
|
||||
"http_server_request_duration_seconds_bucket", "messenger_jobs_processed_total",
|
||||
"messenger_job_duration_seconds_bucket", "messenger_attachment_time_to_ready_seconds_bucket",
|
||||
"messenger_queue_depth", "messenger_queue_oldest_age_seconds", "messenger_worker_busy",
|
||||
"messenger_worker_capacity", "db_client_connection_count", "db_client_connection_pending_requests",
|
||||
"process_cpu_time_seconds_total", "process_memory_usage_bytes", "otelcol_receiver_accepted_spans_total",
|
||||
"otelcol_exporter_sent_spans_total", "otelcol_exporter_queue_size",
|
||||
]
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, _eve, chat = c.bootstrap()
|
||||
marker = "secret-text-" + uuid.uuid4().hex
|
||||
sent = c.message(alice, chat, marker)
|
||||
msg_rid = sent["headers"]["X-Request-Id"]
|
||||
log("message sent request_id=%s (text marker kept private)" % msg_rid)
|
||||
|
||||
# ---------------------------------------------------------------- 1. upload -> retry -> ready, one trace
|
||||
filename = unique_name("transient1")
|
||||
att = upload(c, alice, chat, filename=filename)
|
||||
ready, seen = wait_status(c, bob, att["id"], ("ready", "failed"), 90)
|
||||
check(ready["status"] == "ready", "upload must become ready after one retry")
|
||||
log("upload %s: %s" % (att["id"], " -> ".join(["queued"] + seen)))
|
||||
|
||||
def find():
|
||||
found = obs.tempo_search('{span.messenger.attachment_id="%s"}' % att["id"])
|
||||
if not found:
|
||||
return None
|
||||
spans = obs.tempo_trace(found[0]["traceID"])
|
||||
consumers = [s for s in spans if s["kind"] == "CONSUMER"]
|
||||
producers = [s for s in spans if s["kind"] == "PRODUCER"]
|
||||
# Spans of one trace arrive from 3 processes with different batch delays: wait until all are in.
|
||||
return (found, spans) if len(consumers) >= 2 and len(producers) >= 2 and any(
|
||||
s["attrs"].get("messenger.job.outcome") == "succeeded" for s in consumers) else None
|
||||
|
||||
result = obs.wait_for(find, 60)
|
||||
check(result, "trace of the upload with both attempts not found in Tempo")
|
||||
found, spans = result
|
||||
trace_ids = {t["traceID"] for t in found}
|
||||
check(len(trace_ids) == 1, "upload and its jobs must be ONE trace, got %s" % trace_ids)
|
||||
trace_id = found[0]["traceID"]
|
||||
log("Tempo: trace %s, %d spans; tree (DB client spans omitted):" % (trace_id, len(spans)))
|
||||
obs.print_tree(spans, out=lambda line: print(" " + line), skip_db=True)
|
||||
|
||||
by_id = {s["span_id"]: s for s in spans}
|
||||
server = [s for s in spans if s["kind"] == "SERVER" and s["service"] == "messenger-api"]
|
||||
producers = [s for s in spans if s["kind"] == "PRODUCER"]
|
||||
consumers = [s for s in spans if s["kind"] == "CONSUMER"]
|
||||
check(len(server) == 1 and server[0]["name"] == "POST /api/v1/chats/{chat_id}/attachments", "API server span")
|
||||
check(len(producers) >= 2 and len(consumers) >= 2, "two publish/consume pairs (attempt 1 + retry)")
|
||||
for cons in consumers:
|
||||
parent = by_id.get(cons["parent_id"])
|
||||
check(parent is not None and parent["kind"] == "PRODUCER", "consumer must be a child of a producer span")
|
||||
check(by_id[producers[0]["parent_id"]]["kind"] == "SERVER", "first producer is a child of the upload request")
|
||||
retry_parent = by_id[producers[1]["parent_id"]]
|
||||
check(retry_parent["kind"] == "CONSUMER" and retry_parent["attrs"].get("messenger.job.outcome") == "retry",
|
||||
"retry producer must be a child of the failed consumer")
|
||||
check(consumers[0]["status"] == "ERROR" and consumers[-1]["attrs"].get("messenger.job.outcome") == "succeeded",
|
||||
"attempt 1 ERROR/retry, last attempt succeeded")
|
||||
worker_ops = {s["name"] for s in spans if s["service"] == "messenger-worker"}
|
||||
for op in ("S3.GetObject", "S3.CopyObject", "S3.PutObject", "imageproc"):
|
||||
check(op in worker_ops, "worker span %s missing" % op)
|
||||
check(any(s["service"] == "messenger-worker" and s["attrs"].get("db.system") == "postgresql" for s in spans),
|
||||
"worker DB spans missing")
|
||||
log("PASS: W3C context API -> outbox -> broker -> worker (retry) -> S3/DB is one trace with producer/consumer links")
|
||||
|
||||
# ---------------------------------------------------------------- 2. logs of both services with the trace_id
|
||||
lines = obs.wait_for(lambda: [l for l in obs.loki('{service_name=~"messenger-api|messenger-worker"} | trace_id="%s"'
|
||||
% trace_id) if True] or None, 30)
|
||||
check(lines, "no Loki records with the trace_id")
|
||||
services = {l["service_name"] for l in lines}
|
||||
events = [(l["service_name"].replace("messenger-", ""), l.get("event")) for l in lines]
|
||||
log("Loki: %d records with trace_id=%s: %s" % (len(lines), trace_id, events))
|
||||
check(services == {"messenger-api", "messenger-worker"}, "logs of both services must carry the trace_id")
|
||||
check({"attachment_queued", "job_attempt_failed", "job_finished"} <= {e for _, e in events},
|
||||
"expected events attachment_queued, job_attempt_failed, job_finished")
|
||||
sample = lines[0]
|
||||
log("Loki record fields: %s" % sorted(k for k in sample if k not in ("line",)))
|
||||
|
||||
# ---------------------------------------------------------------- 3. X-Request-Id of an HTTP error -> log -> trace
|
||||
err = c.call("GET", "/api/v1/chats", 500, actor=alice, headers={"X-Fault": "error"})
|
||||
rid = err["headers"]["X-Request-Id"]
|
||||
check(err["json"]["error"]["request_id"] == rid and "Traceback" not in err["bytes"].decode(), "500 body is clean")
|
||||
err_lines = obs.wait_for(lambda: obs.loki('{service_name="messenger-api"} |= "%s"' % rid, minutes=5) or None, 30)
|
||||
check(err_lines, "500 request_id not found in Loki")
|
||||
err_trace = err_lines[0].get("trace_id")
|
||||
log("HTTP 500 X-Request-Id=%s -> Loki event=%s trace_id=%s" % (rid, err_lines[0].get("event"), err_trace))
|
||||
err_spans = obs.wait_for(lambda: obs.tempo_trace(err_trace) or None, 30)
|
||||
check(err_spans, "trace of the 500 not in Tempo")
|
||||
srv = [s for s in err_spans if s["kind"] == "SERVER"][0]
|
||||
check(srv["attrs"].get("messenger.request_id") == rid and srv["status"] == "ERROR"
|
||||
and str(srv["attrs"].get("http.response.status_code")) == "500", "server span must carry request_id and ERROR")
|
||||
log("Tempo: %s status=%s request_id matches; exception event recorded=%s" % (
|
||||
srv["name"], srv["status"], "exception" in obs.tempo_raw(err_trace)))
|
||||
|
||||
msg_trace = obs.wait_for(lambda: obs.tempo_search('{span.messenger.request_id="%s"}' % msg_rid) or None, 30)
|
||||
check(msg_trace, "message request trace not found by request_id")
|
||||
msg_spans = obs.tempo_trace(msg_trace[0]["traceID"])
|
||||
log("message POST trace %s: %s" % (msg_trace[0]["traceID"], [s["name"] for s in msg_spans]))
|
||||
|
||||
# ---------------------------------------------------------------- 4. privacy
|
||||
secrets = {"password": alice["registration"]["password"], "token": alice["token"], "message text": marker,
|
||||
"filename": filename}
|
||||
raw = obs.tempo_raw(trace_id) + obs.tempo_raw(msg_trace[0]["traceID"]) + obs.tempo_raw(err_trace)
|
||||
logs_raw = "\n".join(str(l) for l in obs.loki('{service_name=~"messenger-.*"}', minutes=10, limit=5000))
|
||||
for what, value in secrets.items():
|
||||
check(value not in raw, "%s leaked into traces" % what)
|
||||
check(value not in logs_raw, "%s leaked into logs" % what)
|
||||
# Image bytes: PNG signature/IHDR chunk as raw, escaped or base64 text (sample.png starts with iVBORw0KGgo).
|
||||
for word in ("Authorization", "Bearer ", "filename=", "X-Amz-Signature", "iVBORw0KGgo", "IHDR", "\\x89PNG",
|
||||
"\\u0089PNG"):
|
||||
check(word not in raw and word not in logs_raw, "%r found in telemetry" % word)
|
||||
log("PASS: password, bearer token, message text, filename, Authorization, signed URLs, image bytes absent from "
|
||||
"traces and logs")
|
||||
|
||||
series = obs.prom('{__name__=~"messenger_.*|http_server_.*|db_client_.*|process_.*"}')
|
||||
labels = set()
|
||||
for metric, _ in series:
|
||||
labels |= set(metric)
|
||||
for name, value in metric.items():
|
||||
check(not UUID_RE.search(value), "UUID-like value in metric label %s=%s" % (name, value))
|
||||
check(not labels & FORBIDDEN_LABELS, "forbidden metric labels: %s" % (labels & FORBIDDEN_LABELS))
|
||||
log("PASS: %d series, label names: %s" % (len(series), sorted(labels)))
|
||||
routes = sorted({m.get("http_route") for m, _ in series if m.get("http_route")})
|
||||
log("http_route values (templates only): %s" % routes)
|
||||
|
||||
# ---------------------------------------------------------------- 5. metrics referenced by dashboard/alerts
|
||||
time.sleep(12) # one metric export interval
|
||||
for name in REQUIRED_METRICS:
|
||||
check(obs.prom(name), "metric %s has no samples" % name)
|
||||
log("PASS: required metrics present: %s" % ", ".join(REQUIRED_METRICS))
|
||||
print("PASS: observability levels 3-4 (traces/logs/metrics correlation and privacy)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade 3 demo: worker stopped -> upload 202 -> message with attachment -> restart API + broker (volumes kept)
|
||||
-> worker started -> ready + thumbnail. Then an explicit duplicate delivery of the finished job is a no-op.
|
||||
|
||||
python3 student-tests/test_worker_down.py (stack from REPORT.md must be running)
|
||||
"""
|
||||
import hashlib
|
||||
import time
|
||||
|
||||
from stand import (Client, check, compose, started_at, get, log, objects_of, wait_queue, run, sql, upload, wait_http_ready,
|
||||
wait_status, unique_name, SAMPLE)
|
||||
|
||||
|
||||
def main():
|
||||
c = Client()
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
log("stop all workers")
|
||||
compose("stop", "-t", "20", "worker")
|
||||
try:
|
||||
att = upload(c, alice, chat, filename=unique_name())
|
||||
check(att["status"] == "queued" and att["variants"] == [] and att["error_code"] is None, "upload must be 202 queued")
|
||||
log("upload 202 queued id=%s" % att["id"])
|
||||
msg = c.message(alice, chat, "", attachments=[att["id"]])["json"]
|
||||
check(msg["attachment_ids"] == [att["id"]], "message must reference the queued attachment")
|
||||
log("message %s created with queued attachment" % msg["id"])
|
||||
c.call("GET", "/api/v1/attachments/%s/content" % att["id"], 409, actor=bob)
|
||||
c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], 409, actor=bob)
|
||||
c.message(bob, chat, "другие сообщения работают")
|
||||
depth = wait_queue()
|
||||
log("broker queue while worker is down:", depth)
|
||||
check(depth and depth["ready"] >= 1, "job must be waiting in the broker")
|
||||
unpublished = sql("SELECT count(*) FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id"
|
||||
" WHERE j.attachment_id='%s' AND o.published_at IS NULL" % att["id"])[0][0]
|
||||
check(unpublished == "0", "outbox row must be published with confirm")
|
||||
|
||||
log("restart api-1 api-2 rabbitmq (volumes kept)")
|
||||
before = started_at("api-1", "api-2", "rabbitmq")
|
||||
compose("restart", "-t", "10", "rabbitmq", "api-1", "api-2")
|
||||
wait_http_ready(c)
|
||||
after = started_at("api-1", "api-2", "rabbitmq")
|
||||
log("started before:", before)
|
||||
log("started after: ", after)
|
||||
check(before != after, "containers must really restart")
|
||||
check(get(c, bob, att["id"])["status"] == "queued", "still queued after restart, nothing lost")
|
||||
depth = wait_queue()
|
||||
log("broker queue after broker restart:", depth)
|
||||
check(depth and depth["ready"] >= 1, "durable message must survive broker restart")
|
||||
finally:
|
||||
log("start workers")
|
||||
compose("start", "worker")
|
||||
ready, seen = wait_status(c, bob, att["id"], ("ready", "failed"), 90)
|
||||
check(ready["status"] == "ready", "expected ready, got %s" % ready["status"])
|
||||
log("status sequence observed:", " -> ".join(seen))
|
||||
names = sorted(v["name"] for v in ready["variants"])
|
||||
check(names == ["crop", "optimized", "thumbnail"], "expected thumbnail+crop+optimized, got %s" % names)
|
||||
thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"][0]
|
||||
check((thumb["width"], thumb["height"]) == (256, 160), "thumbnail 256x160")
|
||||
body = c.call("GET", "/api/v1/attachments/%s/content?variant=thumbnail" % att["id"], actor=bob)["bytes"]
|
||||
check(hashlib.sha256(body).hexdigest() == thumb["sha256"], "thumbnail checksum")
|
||||
orig = c.call("GET", "/api/v1/attachments/%s/content" % att["id"], actor=bob)["bytes"]
|
||||
check(orig == SAMPLE, "original unchanged byte for byte")
|
||||
keys = objects_of(att["id"])
|
||||
log("objects:", keys)
|
||||
check(len(keys) == 4 and not any(k.startswith("staging/") for k in keys), "original + 3 variants, staging removed")
|
||||
|
||||
log("redelivery: republish the finished job through the outbox (duplicate message)")
|
||||
sql("INSERT INTO outbox (job_id, payload, available_at, created_at) SELECT o.job_id, o.payload, now(), now()"
|
||||
" FROM outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE j.attachment_id='%s' ORDER BY o.id LIMIT 1"
|
||||
% att["id"])
|
||||
time.sleep(5)
|
||||
again = get(c, bob, att["id"])
|
||||
check(again["status"] == "ready" and again["variants"] == ready["variants"], "duplicate must not change the result")
|
||||
rows = sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='%s'" % att["id"])[0][0]
|
||||
succeeded = sql("SELECT count(*) FROM job_audit WHERE attachment_id='%s' AND action='succeeded'" % att["id"])[0][0]
|
||||
check(rows == "3" and succeeded == "1", "one set of variants and one success (rows=%s succeeded=%s)" % (rows, succeeded))
|
||||
check(len(objects_of(att["id"])) == 4, "no new objects after duplicate")
|
||||
noop = compose("logs", "--since", "30s", "worker")
|
||||
check("decision=done" in noop, "worker must log the duplicate as no-op")
|
||||
log("duplicate acked as no-op: variants=%s successes=%s" % (rows, succeeded))
|
||||
print("PASS: worker down / API+broker restart / redelivery no-op")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,75 @@
|
||||
#!/usr/bin/env python3
|
||||
"""MessengerWorkerSaturated: capacity is lowered (2 workers x 1 slot, 0.25 CPU each), uploads exceed it for longer than
|
||||
`for: 5m`; the alert must fire, and resolve after the normal configuration is restored and the backlog drains.
|
||||
|
||||
python3 student-tests/test_worker_saturation.py (stack running; ~10 min). Restores WORKER_* defaults at the end.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import check, log, run
|
||||
from test_incidents import wait_alert
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ALERT = "MessengerWorkerSaturated"
|
||||
|
||||
|
||||
def worker(env):
|
||||
done = subprocess.run(["docker", "compose", "--env-file", ".env", "up", "-d", "--wait", "--no-deps", "--force-recreate",
|
||||
"worker"], cwd=ROOT, env={**os.environ, **env}, capture_output=True, text=True, timeout=240)
|
||||
check(done.returncode == 0, "worker recreate failed: %s" % done.stderr[-300:])
|
||||
|
||||
|
||||
def main():
|
||||
result = {}
|
||||
log("lower capacity: WORKER_CONCURRENCY=1 WORKER_PREFETCH=1 WORKER_CPUS=0.25, 2 replicas")
|
||||
worker({"WORKER_CONCURRENCY": "1", "WORKER_PREFETCH": "1", "WORKER_CPUS": "0.25"})
|
||||
load = Load("http://localhost:8080", users=2, threads=32)
|
||||
stop = threading.Event()
|
||||
summary = {}
|
||||
thread = threading.Thread(target=lambda: summary.update(load.run(0, 900, upload_rate=4, stop_event=stop)), daemon=True)
|
||||
t0 = time.time()
|
||||
thread.start()
|
||||
log("uploads: 4/s open-loop (sample.png)")
|
||||
try:
|
||||
time.sleep(60)
|
||||
capacity = obs.prom_scalar("sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 30))")
|
||||
log("fresh capacity=%.0f slots (stale series of recreated containers are excluded)" % capacity)
|
||||
check(capacity == 2, "expected 2 slots, got %s" % capacity)
|
||||
firing, pending = wait_alert(ALERT, "firing", 480, t0)
|
||||
ratio = obs.prom_scalar("messenger:worker_saturation:ratio")
|
||||
depth = obs.prom_scalar('max(messenger_queue_depth{queue="attachments.process",state="queued"})')
|
||||
age = obs.prom_scalar('max(messenger_queue_oldest_age_seconds{queue="attachments.process"})')
|
||||
rate = obs.prom_scalar('sum(rate(messenger_jobs_processed_total{outcome="succeeded"}[2m]))')
|
||||
p95 = obs.prom_scalar('histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{outcome="succeeded"}[5m])))')
|
||||
others = obs.alerts()
|
||||
log("at firing: saturation=%.2f, queued=%.0f, oldest age=%.0f s, succeeded=%.2f jobs/s, job p95=%.2f s, alerts=%s"
|
||||
% (ratio, depth, age, rate, p95, others))
|
||||
check(ratio > 0.9, "saturation must be above the threshold")
|
||||
finally:
|
||||
stop.set()
|
||||
thread.join(60)
|
||||
log("restore default worker configuration")
|
||||
t1 = time.time()
|
||||
worker({})
|
||||
resolved, _ = wait_alert(ALERT, "resolved", 240, t1)
|
||||
drained = obs.wait_for(lambda: obs.prom_scalar('max(messenger_queue_depth{queue="attachments.process",state="queued"})',
|
||||
default=-1) == 0, 240, 5)
|
||||
log("backlog drained: %s (+%.0f s after restore)" % (bool(drained), time.time() - t1))
|
||||
check(drained, "backlog must drain")
|
||||
result.update({"alert_pending_s": pending, "alert_firing_s": round(firing), "saturation_at_firing": round(ratio, 3),
|
||||
"queued_at_firing": depth, "oldest_age_s": round(age), "jobs_per_s": round(rate, 2),
|
||||
"job_p95_s": round(p95, 2), "alerts_at_firing": others, "resolved_after_restore_s": round(resolved),
|
||||
"drained_after_restore_s": round(time.time() - t1), "uploads": summary.get("status_counts")})
|
||||
(ROOT / "evidence/worker_saturation.json").write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n")
|
||||
print("PASS: MessengerWorkerSaturated fired under saturation and resolved after recovery")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,343 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Track 5.1 "Цена наблюдаемости": the same open-loop load against several telemetry configurations.
|
||||
|
||||
Configurations (applied by recreating api-1, api-2, worker and otel-collector with shell env overrides):
|
||||
off OTEL_SDK_DISABLED=true no SDK, no instrumentation (baseline)
|
||||
on100 sampler ratio 1.0, collector profile default every span exported
|
||||
head10 sampler ratio 0.1, collector profile default head sampling of root spans (children follow)
|
||||
tail sampler ratio 1.0, collector profile tail balanced: errors + >500 ms + async pipeline + 10% rest
|
||||
|
||||
Per run: recreate -> ready -> warm-up 20 s -> idle 20 s -> counters A -> load (rate, duration) -> idle 30 s ->
|
||||
counters B. Delta(B-A) = telemetry produced by the measured load. CPU is the exact cgroup delta over the load window
|
||||
(Docker API); RSS is the maximum of `docker stats` samples taken every 5 s. Afterwards Tempo is searched in the load window for traces of injected slow/error requests and
|
||||
upload pipelines, to count what survives sampling.
|
||||
|
||||
python3 student-tests/track1.py run [--configs off,on100,head10,tail] [--repeats 2] [--rate 60] [--duration 90]
|
||||
python3 student-tests/track1.py summary # evidence/track1/results.jsonl -> evidence/track1/summary.md
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import statistics
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import obs
|
||||
from openloop import Load
|
||||
from stand import Client, log
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
OUT = ROOT / "evidence/track1"
|
||||
CONFIGS = {
|
||||
"off": {"OTEL_SDK_DISABLED": "true", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "default"},
|
||||
"on100": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "default"},
|
||||
"head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "0.1", "COLLECTOR_PROFILE": "default"},
|
||||
"tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "tail"},
|
||||
}
|
||||
SERVICES = ("api-1", "api-2", "worker", "otel-collector", "tempo", "loki", "prometheus", "postgres", "nginx")
|
||||
COUNTERS = {
|
||||
# SDK side (sum over all instances; absent when the SDK is off)
|
||||
"sdk_span_decisions_sample": 'sum(messenger_telemetry_sampler_decisions_total{decision="sample"})',
|
||||
"sdk_span_decisions_drop_ratio": 'sum(messenger_telemetry_sampler_decisions_total{decision="drop",rule=~"ratio|parent"})',
|
||||
"sdk_spans_exported_ok": 'sum(messenger_telemetry_spans_exported_total{outcome="success"})',
|
||||
"sdk_spans_exported_failed": 'sum(messenger_telemetry_spans_exported_total{outcome="failure"})',
|
||||
# Collector
|
||||
"col_spans_in": "sum(otelcol_receiver_accepted_spans_total)",
|
||||
"col_logs_in": "sum(otelcol_receiver_accepted_log_records_total)",
|
||||
"col_points_in": "sum(otelcol_receiver_accepted_metric_points_total)",
|
||||
"col_spans_out": 'sum(otelcol_exporter_sent_spans_total{exporter="otlp/tempo"})',
|
||||
"col_spans_refused": "sum(otelcol_receiver_refused_spans_total)",
|
||||
"col_spans_dropped": 'sum(otelcol_exporter_enqueue_failed_spans_total) or vector(0)',
|
||||
"col_otlp_bytes_in": 'sum({__name__="http.server.request.size_bytes_total"})',
|
||||
# Backends
|
||||
"tempo_spans_in": "sum(tempo_distributor_spans_received_total)",
|
||||
"tempo_bytes_in": "sum(tempo_distributor_bytes_received_total)",
|
||||
"loki_bytes_in": "sum(loki_distributor_bytes_received_total)",
|
||||
"loki_lines_in": "sum(loki_distributor_lines_received_total)",
|
||||
"prom_samples_in": "sum(prometheus_tsdb_head_samples_appended_total)",
|
||||
}
|
||||
|
||||
|
||||
def compose(*args, env=None, timeout=300):
|
||||
done = subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, capture_output=True,
|
||||
text=True, timeout=timeout, env={**os.environ, **(env or {})})
|
||||
if done.returncode != 0:
|
||||
raise RuntimeError("compose %s: %s" % (args[:2], done.stderr[-400:]))
|
||||
return done.stdout
|
||||
|
||||
|
||||
def apply(name):
|
||||
env = CONFIGS[name]
|
||||
compose("up", "-d", "--wait", "--force-recreate", "--no-deps", "otel-collector", "api-1", "api-2", "worker",
|
||||
env=env)
|
||||
compose("restart", "nginx") # re-resolve recreated replicas
|
||||
c = Client()
|
||||
deadline = time.monotonic() + 120
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
c.call("GET", "/health/ready", 200)
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(1)
|
||||
out = compose("exec", "-T", "api-1", "printenv", "OTEL_SDK_DISABLED", "OTEL_TRACES_SAMPLER_ARG")
|
||||
log("config %s applied: api-1 env %s" % (name, out.split()))
|
||||
|
||||
|
||||
def counters():
|
||||
values = {}
|
||||
for key, expr in COUNTERS.items():
|
||||
try:
|
||||
rows = obs.prom(expr)
|
||||
values[key] = rows[0][1] if rows else None
|
||||
except Exception:
|
||||
values[key] = None
|
||||
tail = {}
|
||||
for metric, value in obs.prom('{__name__=~"otelcol_processor_tail_sampling_count_traces_sampled.*"}'):
|
||||
tail["%s/%s" % (metric.get("policy"), metric.get("sampled"))] = value
|
||||
values["tail_policies"] = tail
|
||||
return values
|
||||
|
||||
|
||||
def delta(a, b):
|
||||
out = {}
|
||||
for key in COUNTERS:
|
||||
if a.get(key) is not None and b.get(key) is not None:
|
||||
out[key] = b[key] - a[key]
|
||||
elif b.get(key) is not None:
|
||||
out[key] = b[key] # series appeared during the window (counter started at 0)
|
||||
else:
|
||||
out[key] = None
|
||||
out["tail_policies"] = {k: v - a["tail_policies"].get(k, 0) for k, v in b["tail_policies"].items()}
|
||||
return out
|
||||
|
||||
|
||||
def parse_mem(text):
|
||||
"""'123.4MiB' -> 123.4 (MiB)."""
|
||||
match = re.match(r"\s*([\d.]+)\s*([A-Za-z]*)", text)
|
||||
if not match:
|
||||
return 0.0
|
||||
scale = {"B": 1 / 1048576, "kB": 1 / 1024, "KiB": 1 / 1024, "MiB": 1, "MB": 1, "GiB": 1024, "GB": 1024}
|
||||
return float(match.group(1)) * scale.get(match.group(2), 1)
|
||||
|
||||
|
||||
def sample_stats(stop, samples):
|
||||
while not stop.is_set():
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"],
|
||||
capture_output=True, text=True).stdout
|
||||
row = {}
|
||||
for line in out.splitlines():
|
||||
name, cpu, mem = line.split("\t")
|
||||
if not name.startswith("mtusi-lab6-"):
|
||||
continue
|
||||
svc = name[len("mtusi-lab6-"):].rsplit("-", 1)[0]
|
||||
cur = row.setdefault(svc, [0.0, 0.0])
|
||||
cur[0] += float(cpu.rstrip("%") or 0)
|
||||
cur[1] += parse_mem(mem.split(" / ")[0])
|
||||
samples.append(row)
|
||||
stop.wait(5)
|
||||
|
||||
|
||||
def docker_socket():
|
||||
host = subprocess.run(["docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
return host.replace("unix://", "")
|
||||
|
||||
|
||||
def cpu_seconds():
|
||||
"""Cumulative container CPU seconds per service from the Docker API (exact over a window, unlike docker stats)."""
|
||||
sock = docker_socket()
|
||||
ids = subprocess.run(["docker", "ps", "--filter", "label=com.docker.compose.project=mtusi-lab6", "--format",
|
||||
"{{.ID}} {{.Names}}"], capture_output=True, text=True).stdout.splitlines()
|
||||
out = {}
|
||||
for line in ids:
|
||||
cid, name = line.split()
|
||||
svc = name[len("mtusi-lab6-"):].rsplit("-", 1)[0]
|
||||
raw = subprocess.run(["curl", "-s", "--unix-socket", sock,
|
||||
"http://localhost/containers/%s/stats?stream=false&one-shot=true" % cid],
|
||||
capture_output=True, text=True).stdout
|
||||
out[svc] = out.get(svc, 0.0) + json.loads(raw)["cpu_stats"]["cpu_usage"]["total_usage"] / 1e9
|
||||
return out
|
||||
|
||||
|
||||
def count_traces(query, start, end):
|
||||
try:
|
||||
return len(obs.tempo_search(query, limit=10000, start=start, end=end))
|
||||
except Exception as exc:
|
||||
return "error:%s" % type(exc).__name__
|
||||
|
||||
|
||||
def one_run(name, rep, rate, duration):
|
||||
apply(name)
|
||||
load = Load("http://localhost:8080", users=4, threads=96)
|
||||
load.run(rate, 20, 0.5, 1, 1) # warm-up, same mix
|
||||
time.sleep(20)
|
||||
a = counters()
|
||||
load = Load("http://localhost:8080", users=4, threads=96)
|
||||
stop, samples = threading.Event(), []
|
||||
sampler = threading.Thread(target=sample_stats, args=(stop, samples), daemon=True)
|
||||
sampler.start()
|
||||
cpu_a = cpu_seconds()
|
||||
t_start = time.time()
|
||||
summary = load.run(rate, duration, 1, 1, 1)
|
||||
t_end = time.time()
|
||||
cpu_b = cpu_seconds()
|
||||
stop.set()
|
||||
sampler.join(15)
|
||||
time.sleep(30) # SDK batch (2 s) + collector batch (2 s) + tail decision_wait (10 s) + scrape (15 s)
|
||||
b = counters()
|
||||
d = delta(a, b)
|
||||
# % of one core averaged over the load window (cumulative cgroup CPU; several replicas of a service are summed)
|
||||
cpu = {svc: round((cpu_b[svc] - cpu_a[svc]) / (t_end - t_start) * 100, 2) for svc in cpu_b if svc in cpu_a}
|
||||
mem = {svc: round(max(s[svc][1] for s in samples if svc in s), 1) for svc in samples[0]} if samples else {}
|
||||
w0, w1 = int(t_start) - 2, int(t_end) + 15
|
||||
traces = {
|
||||
"server_api": count_traces('{resource.service.name="messenger-api" && kind=server}', w0, w1),
|
||||
"slow": count_traces('{span.messenger.fault="slow"}', w0, w1),
|
||||
"error": count_traces('{span.messenger.fault="error"}', w0, w1),
|
||||
"pipeline_consumer": count_traces('{kind=consumer && span.messenger.job.outcome="succeeded"}', w0, w1),
|
||||
}
|
||||
result = {"config": name, "rep": rep, "env": CONFIGS[name], "load": summary, "cpu_pct_avg": cpu,
|
||||
"mem_mib_max": mem, "telemetry_delta": d, "traces_in_tempo": traces,
|
||||
"window": [t_start, t_end], "stats_samples": len(samples)}
|
||||
log("%s#%d: ok_rps=%s p50/p95/p99=%s/%s/%s ms api_cpu=%s+%s%% spans_in=%s tempo_spans=%s slow=%s/%d err=%s/%d" % (
|
||||
name, rep, summary["successful_rps"], summary["latency_ms_plain_ok"]["p50"],
|
||||
summary["latency_ms_plain_ok"]["p95"], summary["latency_ms_plain_ok"]["p99"], cpu.get("api-1"),
|
||||
cpu.get("api-2"), d.get("col_spans_in"), d.get("tempo_spans_in"), traces["slow"],
|
||||
summary["faults_sent"]["slow"], traces["error"], summary["faults_sent"]["error"]))
|
||||
return result
|
||||
|
||||
|
||||
def cmd_run(args):
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
path = OUT / "results.jsonl"
|
||||
names = args.configs.split(",")
|
||||
try:
|
||||
for rep in range(1, args.repeats + 1):
|
||||
for name in names:
|
||||
result = one_run(name, rep, args.rate, args.duration)
|
||||
result["hardware"] = HARDWARE
|
||||
with path.open("a", encoding="utf-8") as handle:
|
||||
handle.write(json.dumps(result, ensure_ascii=False) + "\n")
|
||||
finally:
|
||||
log("restore default configuration (on100)")
|
||||
apply("on100")
|
||||
|
||||
|
||||
def fmt(v, digits=0):
|
||||
if v is None:
|
||||
return "—"
|
||||
if isinstance(v, str):
|
||||
return v
|
||||
return ("%%.%df" % digits) % v
|
||||
|
||||
|
||||
def metric_500s(run_result):
|
||||
"""Injected 500s as seen by METRICS for this run: metrics are computed in the SDK, before any trace sampling."""
|
||||
start, end = run_result["window"]
|
||||
if run_result["config"] == "off":
|
||||
return None
|
||||
# Exact counter difference at the window borders (increase() extrapolates and overstates by ~10% here).
|
||||
expr = 'sum(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code="500"})'
|
||||
try:
|
||||
return obs.prom_scalar(expr, at=end + 20) - obs.prom_scalar(expr, at=start - 5)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def cmd_summary(_args):
|
||||
rows = [json.loads(line) for line in (OUT / "results.jsonl").read_text(encoding="utf-8").splitlines() if line]
|
||||
by = {}
|
||||
for r in rows:
|
||||
by.setdefault(r["config"], []).append(r)
|
||||
|
||||
def values(items, fn):
|
||||
return [v for v in (fn(x) for x in items) if isinstance(v, (int, float))]
|
||||
|
||||
def avg(items, fn):
|
||||
vals = values(items, fn)
|
||||
return statistics.mean(vals) if vals else None
|
||||
|
||||
def spread(items, fn, digits=1):
|
||||
vals = values(items, fn)
|
||||
if not vals:
|
||||
return "—"
|
||||
return "%s (%s…%s)" % (fmt(statistics.mean(vals), digits), fmt(min(vals), digits), fmt(max(vals), digits))
|
||||
|
||||
lat = lambda q: (lambda x: x["load"]["latency_ms_plain_ok"][q]) # noqa: E731
|
||||
cpu = lambda *svc: (lambda x: sum(x["cpu_pct_avg"].get(s, 0) for s in svc)) # noqa: E731
|
||||
delta_of = lambda key: (lambda x: x["telemetry_delta"].get(key)) # noqa: E731
|
||||
traces = lambda key: (lambda x: x["traces_in_tempo"].get(key)) # noqa: E731
|
||||
faults = lambda key: (lambda x: x["load"]["faults_sent"][key]) # noqa: E731
|
||||
names = [n for n in CONFIGS if n in by]
|
||||
|
||||
lines = ["Среднее по прогонам (мин…макс). CPU — % одного ядра за окно нагрузки, реплики сервиса суммируются.", "",
|
||||
"| Конфигурация | Прогонов | Успешн. RPS | Неожид. ошибки | p50, ms | p95, ms | p99, ms | CPU api-1+2, % | CPU worker, % |",
|
||||
"|---|---|---|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
lines.append("| %s | %d | %s | %s | %s | %s | %s | %s | %s |" % (
|
||||
n, len(i), fmt(avg(i, lambda x: x["load"]["successful_rps"]), 1),
|
||||
fmt(avg(i, lambda x: x["load"]["server_errors_unexpected"])), spread(i, lat("p50")), spread(i, lat("p95")),
|
||||
spread(i, lat("p99")), spread(i, cpu("api-1", "api-2")), spread(i, cpu("worker"))))
|
||||
lines += ["", "| Конфигурация | CPU collector, % | CPU Tempo, % | CPU Loki, % | CPU Prometheus, % | RSS api-1 (макс), MiB | RSS collector, MiB | RSS Tempo, MiB |",
|
||||
"|---|---|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
mem = lambda s: (lambda x: x["mem_mib_max"].get(s)) # noqa: E731
|
||||
lines.append("| %s | %s | %s | %s | %s | %s | %s | %s |" % (
|
||||
n, spread(i, cpu("otel-collector"), 2), spread(i, cpu("tempo"), 2), spread(i, cpu("loki"), 2),
|
||||
spread(i, cpu("prometheus"), 2), fmt(avg(i, mem("api-1"))), fmt(avg(i, mem("otel-collector"))),
|
||||
fmt(avg(i, mem("tempo")))))
|
||||
lines += ["", "| Конфигурация | Spans → collector | Spans → Tempo | Отказы/отбросы collector | OTLP ingest, KiB | Tempo ingest, KiB | Loki ingest, KiB |",
|
||||
"|---|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
kib = lambda key: (avg(i, delta_of(key)) / 1024 if avg(i, delta_of(key)) is not None else None) # noqa: E731
|
||||
lost = avg(i, lambda x: (x["telemetry_delta"].get("col_spans_refused") or 0) + (x["telemetry_delta"].get("col_spans_dropped") or 0))
|
||||
lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (
|
||||
n, fmt(avg(i, delta_of("col_spans_in"))), fmt(avg(i, delta_of("tempo_spans_in"))), fmt(lost),
|
||||
fmt(kib("col_otlp_bytes_in")), fmt(kib("tempo_bytes_in")), fmt(kib("loki_bytes_in"))))
|
||||
lines += ["", "Сумма по всем прогонам конфигурации: сохранено трасс / отправлено. «500 в метриках» — разность счётчика HTTP в Prometheus на границах окна.", "",
|
||||
"| Конфигурация | Серверных трасс API | slow (+600 ms) | error (500) | upload-конвейеров | 500 в метриках / отправлено |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for n in names:
|
||||
i = by[n]
|
||||
total = lambda fn: sum(values(i, fn)) # noqa: E731
|
||||
m500 = [metric_500s(x) for x in i]
|
||||
lines.append("| %s | %d / %d | %d / %d | %d / %d | %d / %d | %s / %d |" % (
|
||||
n, total(traces("server_api")), total(lambda x: x["load"]["requests"]),
|
||||
total(traces("slow")), total(faults("slow")), total(traces("error")), total(faults("error")),
|
||||
total(traces("pipeline_consumer")), total(lambda x: x["load"]["by_kind"]["upload"]["n"]),
|
||||
"—" if None in m500 else "%.0f" % sum(m500), total(faults("error"))))
|
||||
text = "\n".join(lines) + "\n"
|
||||
(OUT / "summary.md").write_text(text, encoding="utf-8")
|
||||
print(text)
|
||||
|
||||
|
||||
HARDWARE = {}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
sub = p.add_subparsers(dest="cmd", required=True)
|
||||
r = sub.add_parser("run")
|
||||
r.add_argument("--configs", default="off,on100,head10,tail")
|
||||
r.add_argument("--repeats", type=int, default=2)
|
||||
r.add_argument("--rate", type=float, default=60)
|
||||
r.add_argument("--duration", type=float, default=90)
|
||||
sub.add_parser("summary")
|
||||
args = p.parse_args()
|
||||
if args.cmd == "run":
|
||||
info = subprocess.run(["docker", "info", "--format", "{{.ServerVersion}} {{.NCPU}} {{.MemTotal}}"],
|
||||
capture_output=True, text=True).stdout.split()
|
||||
HARDWARE.update({"docker": info[0], "vm_cpus": int(info[1]), "vm_mem_gib": round(int(info[2]) / 2**30, 1)})
|
||||
cmd_run(args)
|
||||
else:
|
||||
cmd_summary(args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Variant rules and worker resource limits. Runs INSIDE the worker container (Pillow + app code):
|
||||
|
||||
docker compose exec -T --index 1 worker python - < student-tests/variants_check.py
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import resource
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from PIL import Image
|
||||
|
||||
sys.path.insert(0, "/app")
|
||||
from app import config # noqa: E402
|
||||
|
||||
FAILS = []
|
||||
|
||||
|
||||
def check(cond, msg):
|
||||
print(("ok " if cond else "FAIL ") + msg, flush=True)
|
||||
if not cond:
|
||||
FAILS.append(msg)
|
||||
|
||||
|
||||
def run_child(path, mem_mb=config.WORKER_CHILD_MEMORY_MB, cpu=config.JOB_TIMEOUT_SECONDS, max_pixels=config.MAX_IMAGE_PIXELS):
|
||||
out = tempfile.mkdtemp()
|
||||
|
||||
def limits():
|
||||
resource.setrlimit(resource.RLIMIT_AS, (mem_mb << 20, mem_mb << 20))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu + 5))
|
||||
|
||||
start = time.monotonic()
|
||||
done = subprocess.run([sys.executable, "-m", "app.imageproc", path, out, str(max_pixels)], capture_output=True,
|
||||
preexec_fn=limits, timeout=120, env={"PATH": os.environ["PATH"], "MALLOC_ARENA_MAX": "2"})
|
||||
usage = resource.getrusage(resource.RUSAGE_CHILDREN)
|
||||
produced = {v["name"]: v for v in json.loads(done.stdout)} if done.returncode == 0 else {}
|
||||
return done.returncode, produced, time.monotonic() - start, usage.ru_maxrss / 1024
|
||||
|
||||
|
||||
def save(img, fmt, **kw):
|
||||
path = tempfile.mktemp(suffix="." + fmt.lower())
|
||||
img.save(path, fmt, **kw)
|
||||
return path
|
||||
|
||||
|
||||
def dims(v):
|
||||
return v["width"], v["height"]
|
||||
|
||||
|
||||
def real(v):
|
||||
with Image.open(v["file"]) as im:
|
||||
return im.format, im.size, "exif" in im.info, im
|
||||
|
||||
|
||||
# 1. fixture 320x200 -> 256x160, crop 128, optimized not upscaled
|
||||
rc, p, _, _ = run_child("/app/tests/fixtures/sample.png" if os.path.exists("/app/tests/fixtures/sample.png") else
|
||||
save(Image.new("RGB", (320, 200), "red"), "PNG"))
|
||||
check(rc == 0 and dims(p["thumbnail"]) == (256, 160), "320x200 -> thumbnail 256x160")
|
||||
check(dims(p["crop"]) == (128, 128), "crop 128x128")
|
||||
check(dims(p["optimized"]) == (320, 200) and real(p["optimized"])[0] == "WEBP", "optimized WebP 320x200, no upscale")
|
||||
check(real(p["thumbnail"])[0] == "JPEG" and real(p["crop"])[0] == "JPEG", "thumbnail/crop are JPEG")
|
||||
|
||||
# 2. small source: no upscale for thumbnail, upscale allowed for crop
|
||||
rc, p, _, _ = run_child(save(Image.new("RGB", (40, 10), "blue"), "PNG"))
|
||||
check(dims(p["thumbnail"]) == (40, 10) and dims(p["crop"]) == (128, 128), "40x10: thumbnail 40x10, crop 128x128")
|
||||
|
||||
# 3. extreme aspect ratio: floor rounding, minimum 1 px
|
||||
rc, p, _, _ = run_child(save(Image.new("RGB", (3000, 2), "blue"), "PNG"))
|
||||
check(dims(p["thumbnail"]) == (256, 1) and dims(p["optimized"]) == (1280, 1), "3000x2 -> 256x1 / 1280x1 (min 1px)")
|
||||
rc, p, _, _ = run_child(save(Image.new("RGB", (1001, 999), "blue"), "PNG"))
|
||||
check(dims(p["thumbnail"]) == (256, 255), "1001x999 -> 256x255 (floor)")
|
||||
|
||||
# 4. EXIF orientation 6 (rotate 90): stored 400x200 -> upright 200x400 -> thumbnail 128x256; EXIF stripped
|
||||
exif = Image.Exif()
|
||||
exif[0x0112] = 6
|
||||
img = Image.new("RGB", (400, 200), "white")
|
||||
img.paste((255, 0, 0), (0, 0, 200, 200)) # left half red
|
||||
rc, p, _, _ = run_child(save(img, "JPEG", exif=exif.tobytes(), quality=95))
|
||||
fmt, size, has_exif, im = real(p["thumbnail"])
|
||||
check(size == (128, 256), "EXIF orientation applied: 400x200 (o=6) -> 128x256")
|
||||
with Image.open(p["thumbnail"]["file"]) as t:
|
||||
top = t.convert("RGB").getpixel((64, 20))
|
||||
check(top[0] > 200 and top[1] < 80, "rotated content: red half on top after orientation 6")
|
||||
check(not has_exif and "exif" not in Image.open(p["optimized"]["file"]).info, "EXIF removed from thumbnail/optimized")
|
||||
|
||||
# 5. alpha composited on white for JPEG, kept for WebP
|
||||
rgba = Image.new("RGBA", (100, 100), (0, 0, 0, 0))
|
||||
rc, p, _, _ = run_child(save(rgba, "PNG"))
|
||||
with Image.open(p["thumbnail"]["file"]) as t:
|
||||
px = t.convert("RGB").getpixel((50, 50))
|
||||
check(min(px) >= 250, "transparent PNG -> white JPEG thumbnail")
|
||||
check(Image.open(p["optimized"]["file"]).mode == "RGBA", "WebP optimized keeps alpha")
|
||||
|
||||
# 6. 16-bit grayscale PNG, CMYK JPEG, palette PNG
|
||||
rc16, _, _, _ = run_child(save(Image.new("I;16", (300, 300), 40000), "PNG"))
|
||||
rcc, _, _, _ = run_child(save(Image.new("CMYK", (300, 300), (0, 255, 0, 0)), "JPEG"))
|
||||
rcp, _, _, _ = run_child(save(Image.new("P", (300, 300), 3), "PNG", transparency=3))
|
||||
check(rc16 == 0 and rcc == 0 and rcp == 0, "16-bit PNG, CMYK JPEG, palette+transparency PNG are processed")
|
||||
|
||||
# 7. limits: pixels (exit 4), not an image (exit 3), memory (exit 5), CPU (SIGXCPU)
|
||||
rc, _, _, _ = run_child(save(Image.new("RGB", (100, 100)), "PNG"), max_pixels=5000)
|
||||
check(rc == 4, "pixel limit enforced before decode -> image_too_large (exit 4)")
|
||||
junk = tempfile.mktemp()
|
||||
open(junk, "wb").write(b"\x89PNG\r\n\x1a\n" + os.urandom(2000))
|
||||
rc, _, _, _ = run_child(junk)
|
||||
check(rc == 3, "corrupted PNG -> invalid_image (exit 3)")
|
||||
big = save(Image.new("RGB", (6000, 6000), "green"), "PNG")
|
||||
rc, _, _, _ = run_child(big, mem_mb=160)
|
||||
check(rc == 5, "36 Mpx PNG with 160 MiB address-space limit -> image_too_complex (exit 5), got %s" % rc)
|
||||
|
||||
# 8. largest allowed inputs under the real limits: time and child peak RSS
|
||||
for name, w, h, fmt in (("png", 7900, 5000, "PNG"), ("jpeg", 7900, 5000, "JPEG")):
|
||||
noise = Image.effect_noise((w // 10, h // 10), 60).convert("RGB").resize((w, h))
|
||||
path = save(noise, fmt, **({"quality": 90} if fmt == "JPEG" else {"compress_level": 1}))
|
||||
rc, p, secs, rss = run_child(path)
|
||||
check(rc == 0 and dims(p["thumbnail"]) == (256, 162), "%.1f Mpx %s (%d MB file) ok in %.1fs, peak child RSS %.0f MiB"
|
||||
% (w * h / 1e6, name.upper(), os.path.getsize(path) >> 20, secs, rss))
|
||||
if fmt == "PNG":
|
||||
rc, _, _, _ = run_child(path, cpu=0)
|
||||
check(rc == -24, "CPU limit exhausted -> SIGXCPU (worker: permanent image_too_complex), got %s" % rc)
|
||||
|
||||
print("RESULT:", "PASS" if not FAILS else "FAIL %s" % FAILS)
|
||||
sys.exit(1 if FAILS else 0)
|
||||
Reference in New Issue
Block a user