ЛР 6: OpenTelemetry, Prometheus, Loki, Tempo и Grafana — на 3

This commit is contained in:
2026-11-20 21:52:10 +03:00
parent 470d9d6f1e
commit dc7745064d
72 changed files with 4684 additions and 44 deletions
+12
View File
@@ -0,0 +1,12 @@
# Проверки ЛР5
В Windows PowerShell поднимите стенд по REPORT.md, затем выполните:
```powershell
docker compose --profile test build tools
docker compose run --rm --no-deps tools python student-tests/grade3.py
```
Тест использует Docker socket из профиля tools и действует только на сервисы локального Compose-проекта `mtusi-lab6-grade3` или его именованного варианта с суффиксом. Он останавливает и запускает worker, API, S3 и RabbitMQ, временно блокирует запись одного типа данных в PostgreSQL для наблюдения processing и изменяет staging двух собственных вложений для инъекции ошибок. Не запускайте его на стенде с чужой нагрузкой или одновременно с публичными сценариями отказов.
Сохраняются тестовые пользователи, чаты, файлы и журнал попыток. Токены используются в памяти. Сценарий сам восстанавливает затронутые сервисы при проверяемых сбоях. После прерывания процесса состояние стенда можно привести к норме командой `docker compose up -d --wait --wait-timeout 150`.
+454
View File
@@ -0,0 +1,454 @@
"""Reproduce Lab 5 acceptance scenarios using only local Compose services."""
import hashlib
import json
import os
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from io import BytesIO
from pathlib import Path
import re
import subprocess
import sys
import time
from uuid import UUID, uuid4
import requests
from jsonschema import Draft202012Validator, FormatChecker
from PIL import Image
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, Failure, check, run
PROJECT = os.getenv("LAB6_PROJECT", "")
SERVICES = {"api1", "api2", "broker", "worker", "postgres", "s3", "lb"}
JOB_SCHEMA = json.loads((ROOT / "contracts/jobs.schema.json").read_text(encoding="utf-8"))
SAMPLE = (ROOT / "tests/fixtures/sample.png").read_bytes()
def docker(*args):
completed = subprocess.run(["docker", *args], capture_output=True, text=True, timeout=45)
check(completed.returncode == 0, f"docker {args[0]} returned {completed.returncode}")
return completed.stdout.strip()
def container(service):
check(service in SERVICES, "unexpected service")
ids = docker("ps", "-aq", "--filter", f"label=com.docker.compose.project={PROJECT}",
"--filter", f"label=com.docker.compose.service={service}",
"--filter", "label=com.docker.compose.oneoff=False").splitlines()
check(len(ids) == 1, f"expected one container for {service}")
return ids[0]
def action(verb, *services):
ids = [container(service) for service in services]
print(f"docker {verb} {' '.join(services)} containers={','.join(ids)}")
extra = ("--time", "2") if verb in {"stop", "restart"} else ()
docker(verb, *extra, *ids)
def inspect(service, fmt):
return docker("inspect", "--format", fmt, container(service))
def inside(service, *args):
return docker("exec", container(service), *args)
def psql_args():
return ("psql", "-XAt", "-v", "ON_ERROR_STOP=1", "-U", "messenger", "-d", "messenger")
def sql(statement):
return inside("postgres", *psql_args(), "-c", statement)
@contextmanager
def block_variant_insert():
# Compatible with metadata SELECT, blocks the worker's final INSERT only.
args = ["docker", "exec", "-i", container("postgres"), *psql_args()]
proc = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True)
try:
proc.stdin.write("BEGIN; LOCK attachment_variants IN SHARE MODE; SELECT 'locked';\n")
proc.stdin.flush()
for _ in range(3):
if proc.stdout.readline().strip() == "locked":
break
else:
raise Failure("could not lock variants")
yield
finally:
try:
proc.communicate("COMMIT;\n", timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait(timeout=5)
raise Failure("could not release variants lock") from None
check(proc.returncode == 0, "variant lock session failed")
def eventually(description, fn, seconds=45, interval=0.2):
start = time.monotonic()
last = ""
while time.monotonic() - start < seconds:
try:
value = fn()
if value:
print(f"{description} after {time.monotonic()-start:.3f}s")
return value
except Failure as exc:
last = str(exc)
time.sleep(interval)
raise Failure(f"timeout waiting for {description}: {last}")
def ready(client):
eventually("LB ready", lambda: client.call("GET", "/health/ready", schema="Health"))
def metadata(client, actor, attachment):
path = f"/api/v1/attachments/{attachment['id']}"
return client.call("GET", path, actor=actor, schema="Attachment")["json"]
def expect_unavailable(client, actor, attachment):
path = f"/api/v1/attachments/{attachment['id']}/content"
for variant in ("original", "thumbnail"):
client.call("GET", f"{path}?variant={variant}", 409, actor=actor)
def upload(client, actor, chat, data=SAMPLE, mime="image/png", expected=202, filename="fixture"):
response = client.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={filename}",
expected, actor=actor, raw=data, headers={"Content-Type": mime},
schema="Attachment" if expected == 202 else None)
if expected == 202:
row = response["json"]
check(row["status"] == "queued" and row["variants"] == [] and row["error_code"] is None,
"expected queued snapshot")
check((row["size_bytes"], row["sha256"], row["content_type"]) ==
(len(data), hashlib.sha256(data).hexdigest(), mime), "staging metadata mismatch")
return response
def assert_ready(client, actor, attachment, data, dimensions, mime="image/png"):
start = time.monotonic()
row = client.wait_ready(actor, attachment)
check(row["error_code"] is None and len(row["variants"]) == 1, "invalid ready result")
check((row["content_type"], row["size_bytes"], row["sha256"]) ==
(mime, len(data), hashlib.sha256(data).hexdigest()), "original metadata changed")
content_path = f"/api/v1/attachments/{attachment['id']}/content"
original = client.call("GET", content_path, actor=actor)
check(original["bytes"] == data and original["headers"].get_content_type() == mime,
"original content changed")
thumb = client.call("GET", content_path + "?variant=thumbnail", actor=actor)
check(thumb["headers"].get_content_type() == "image/jpeg", "thumbnail HTTP MIME")
variant = row["variants"][0]
check(variant["name"] == "thumbnail" and variant["content_type"] == "image/jpeg"
and (variant["width"], variant["height"]) == dimensions, "thumbnail metadata")
check((variant["sha256"], variant["size_bytes"]) ==
(hashlib.sha256(thumb["bytes"]).hexdigest(), len(thumb["bytes"])), "thumbnail checksum")
with Image.open(BytesIO(thumb["bytes"])) as im:
im.load()
check(im.format == "JPEG" and im.size == dimensions and not im.getexif(),
"invalid thumbnail format, dimensions or EXIF")
pixel = im.getpixel((0, 0))
print(f"ready id={row['id']} wait={time.monotonic()-start:.3f}s original_sha256={row['sha256']} "
f"jpeg={dimensions[0]}x{dimensions[1]} thumb_sha256={variant['sha256']} "
f"read={original['headers']['X-Instance-Id']}/{thumb['headers']['X-Instance-Id']}")
return row, pixel
def job_state(attachment):
aid = UUID(attachment["id"])
return sql(f"""SELECT a.status,j.attempt,COALESCE(j.last_error,''),j.max_attempts
FROM attachments a JOIN attachment_jobs j ON a.id=j.attachment_id
WHERE a.id='{aid}'""")
def private(service, key):
status = inside(service, "python", "-c", """
import sys
from urllib.error import HTTPError
from urllib.request import urlopen
from src import s3
try:
urlopen(f"http://s3:9000/{s3.BUCKET}/{sys.argv[1]}", timeout=3).close()
except HTTPError as error:
print(error.code)
else:
print(200)
""", key)
check(status == "403", "unsigned S3 request was not rejected")
print("private RustFS object unsigned GET HTTP 403")
def queued_carrier():
# Observe the real persistent AMQP message and put it back without ack.
raw = inside("api1", "python", "-c", """
import json
from src import jobs
with jobs.broker() as channel:
method, props, body = channel.basic_get(jobs.QUEUE, auto_ack=False)
if method:
channel.basic_nack(method.delivery_tag, requeue=True)
print(json.dumps({"delivery_mode":props.delivery_mode, "job":json.loads(body)}))
""")
check(bool(raw), "no queued job in RabbitMQ")
observed = json.loads(raw)
check(observed["delivery_mode"] == 2, "AMQP message is not persistent")
carrier = observed["job"]
Draft202012Validator(JOB_SCHEMA, format_checker=FormatChecker()).validate(carrier)
print(f"RabbitMQ persistent carrier schema valid job={carrier['job_id']} "
f"attempt={carrier['attempt']} fields={','.join(sorted(carrier))}")
return carrier
def queue_stats():
text = inside("broker", "rabbitmqctl", "-q", "list_queues",
"name", "durable", "messages_ready", "messages_unacknowledged")
for line in text.splitlines():
fields = line.split()
if fields and fields[0] == "attachment.process.v1":
check(fields[1] == "true", "queue durability is off")
print(f"broker queue={fields[0]} durable={fields[1]} ready={fields[2]} unacked={fields[3]}")
return tuple(map(int, fields[2:]))
raise Failure("RabbitMQ queue absent")
def duplicate(client, actor, attachment, carrier, ready_snapshot):
inside("api1", "python", "-c", """
import sys
from src import jobs
job = jobs.parse(sys.argv[1])
with jobs.broker() as channel:
jobs.publish(channel, job)
jobs.publish(channel, job)
""", json.dumps(carrier))
job_id = carrier["job_id"]
query = ('{service_name="messenger-worker"} | event="job.outcome" '
f'| job_id="{job_id}" | attempt="1" | outcome="duplicate_ready"')
def duplicates_logged():
response = requests.get("http://loki:3100/loki/api/v1/query_range",
params={"query": query, "limit": 10}, timeout=5)
check(response.ok, "Loki duplicate query failed")
rows = response.json()["data"]["result"]
return sum(len(row["values"]) for row in rows) >= 2
eventually("worker logged two ready duplicates in Loki", duplicates_logged)
eventually("worker acknowledged all messages", lambda: queue_stats()[:2] == (0, 0))
check(metadata(client, actor, attachment) == ready_snapshot, "duplicate changed ready metadata")
aid = UUID(attachment["id"])
check(sql(f"SELECT count(*) FROM attachment_variants WHERE attachment_id='{aid}'") == "1",
"duplicate created another variant row")
count = inside("api1", "python", "-c", """
import sys
from src import s3
result = s3.client.list_objects_v2(Bucket=s3.BUCKET, Prefix=f"variants/{sys.argv[1]}/")
print(result["KeyCount"])
""", str(aid))
check(count == "1", "duplicate created another variant object")
print("PASS duplicate delivery: ready snapshot unchanged, one SQL row and one S3 variant")
def restart_scenarios(c, alice, bob, eve, chat):
action("stop", "worker")
try:
a = upload(c, alice, chat)["json"]
carrier = queued_carrier()
check(carrier["attachment_id"] == a["id"] and carrier["attempt"] == 1,
"RabbitMQ job identity differs from upload")
b = upload(c, bob, chat)["json"]
check(a["id"] != b["id"], "distinct uploads reused ID")
key = uuid4().hex
with ThreadPoolExecutor(max_workers=8) as pool:
calls = list(pool.map(lambda _: c.message(bob, chat, "", key, [a["id"]]), range(8)))
check(len({x["json"]["id"] for x in calls}) == 1, "idempotency race produced duplicates")
observed = {x["headers"]["X-Instance-Id"] for x in calls}
check(observed == {"api1", "api2"}, "idempotency requests did not use both replicas")
check(calls[0]["json"]["attachment_ids"] == [a["id"]], "queued attachment link lost")
c.message(alice, chat, "ordinary text with worker stopped")
check(metadata(c, bob, a) == a, "queued metadata changed with worker stopped")
expect_unavailable(c, bob, a)
private("api1", f"staging/{a['id']}")
print(f"PASS stopped worker: uploads=202 ids={a['id']},{b['id']}; queued content=409; "
"linked and ordinary POST=201; concurrent same-key response identical via api1/api2")
starts = {s: inspect(s, "{{.State.StartedAt}}") for s in ("api1", "api2")}
action("restart", "api1", "api2")
ready(c)
for service, old in starts.items():
new = inspect(service, "{{.State.StartedAt}}")
check(new != old, f"{service} did not actually restart")
print(f"{service} started before={old} after={new}")
check(metadata(c, bob, a) == a and job_state(a).startswith("queued|1|"),
"accepted job lost after API restart")
volume_format = "{{range .Mounts}}{{if eq .Destination \"/var/lib/rabbitmq\"}}{{.Name}}{{end}}{{end}}"
volume = inspect("broker", volume_format)
check(volume == f"{PROJECT}_broker_data", "unexpected RabbitMQ volume")
check(queue_stats() == (2, 0), "expected two pending jobs before broker restart")
broker_start = inspect("broker", "{{.State.StartedAt}}")
action("restart", "broker")
eventually("broker healthy", lambda: inspect("broker", "{{.State.Health.Status}}") == "healthy")
broker_after = inspect("broker", "{{.State.StartedAt}}")
check(broker_start != broker_after and inspect("broker", volume_format) == volume,
"broker restart or volume identity mismatch")
print(f"broker started before={broker_start} after={broker_after} volume={volume}")
check(queue_stats() == (2, 0), "broker restart lost accepted jobs")
check(metadata(c, bob, b) == b, "second job metadata lost")
print("PASS both APIs + RabbitMQ restarted with queued work and unchanged RabbitMQ volume")
path = f"/api/v1/attachments/{a['id']}"
c.call("GET", path, 401)
c.call("GET", path + "/content?variant=thumbnail", 404, actor=eve)
with block_variant_insert():
action("start", "worker")
processing = eventually(
"HTTP processing state",
lambda: next((row for row in (a, b) if metadata(c, bob, row)["status"] == "processing"), None),
6, interval=0.05,
)
expect_unavailable(c, bob, processing)
c.message(bob, chat, "linked during processing", attachments=[processing["id"]])
print("PASS processing metadata visible, content=409, linking=201 before final SQL commit")
a_ready, _ = assert_ready(c, bob, a, SAMPLE, (256, 160))
assert_ready(c, alice, b, SAMPLE, (256, 160))
duplicate(c, bob, a, carrier, a_ready)
private("api1", f"originals/{a['id']}")
c.call("GET", path + "/content?variant=unknown", 404, actor=bob)
finally:
action("start", "worker")
def image_bytes(image, fmt, **kwargs):
data = BytesIO()
image.save(data, fmt, **kwargs)
return data.getvalue()
def input_and_image_cases(c, alice, eve, chat):
for data, mime, status, actor, filename in (
(SAMPLE, "image/jpeg", 415, alice, "wrong-mime"),
(SAMPLE[:-8], "image/png", 415, alice, "corrupt"),
(b"x" * (10 * 1024 * 1024 + 1), "image/png", 413, alice, "oversize"),
(SAMPLE, "image/png", 404, eve, "private"),
(SAMPLE, "image/png", 401, None, "anonymous"),
(SAMPLE, "image/png", 400, alice, "invalid%2Fname.png"),
):
upload(c, actor, chat, data, mime, status, filename)
print(f"negative upload {filename} HTTP {status}")
huge = image_bytes(Image.new("1", (8001, 5000)), "PNG")
upload(c, alice, chat, huge, expected=413)
print("negative upload 40,005,000 decoded pixels HTTP 413")
exif = Image.Exif()
exif[274] = 6
original = image_bytes(Image.new("RGB", (319, 101), "navy"), "JPEG", exif=exif)
broken = original[:100]
upload(c, alice, chat, broken, mime="image/jpeg", expected=415)
print("negative truncated JPEG HTTP 415")
oriented = upload(c, alice, chat, original, "image/jpeg")["json"]
assert_ready(c, alice, oriented, original, (81, 256), "image/jpeg")
original = image_bytes(Image.new("RGBA", (37, 19), (255, 0, 0, 0)), "PNG")
alpha = upload(c, alice, chat, original)["json"]
_, pixel = assert_ready(c, alice, alpha, original, (37, 19))
check(min(pixel) >= 250, "transparent pixel was not composited on white")
print(f"PASS true JPEG, EXIF orientation, floor rounding, no upscale, alpha pixel={pixel}")
def failure_cases(c, alice, bob, chat):
action("stop", "worker")
try:
a = upload(c, alice, chat)["json"]
action("stop", "s3")
action("start", "worker")
state = eventually("persistent retry after real S3 stop", lambda:
(s := job_state(a)) and "storage_unavailable" in s and s)
print(f"storage outage SQL status|attempt|reason|max={state}")
finally:
action("start", "s3", "worker")
ready(c)
assert_ready(c, bob, a, SAMPLE, (256, 160))
check(int(job_state(a).split("|")[1]) >= 2, "no durable retries recorded")
print("PASS temporary S3 outage recovered the same attachment")
action("stop", "worker")
try:
missing = upload(c, alice, chat)["json"]
corrupt = upload(c, alice, chat)["json"]
inside("api1", "python", "-c", """
from io import BytesIO
import sys
from src import s3
s3.delete(f"staging/{sys.argv[1]}")
damaged = BytesIO(b"X" * int(sys.argv[3]))
s3.put(f"staging/{sys.argv[2]}", damaged, damaged.getbuffer().nbytes, "image/png")
""", missing["id"], corrupt["id"], str(corrupt["size_bytes"]))
finally:
action("start", "worker")
for row, error in ((corrupt, "invalid_image"), (missing, "retry_exhausted")):
failed = eventually(f"failed {row['id']}", lambda:
(meta := metadata(c, bob, row))["status"] == "failed" and meta)
check(failed["error_code"] == error and failed["variants"] == [], "unsafe failed result")
state = job_state(row)
status, current, _, maximum = state.split("|")
check(status == "failed" and int(current) == (1 if error == "invalid_image" else int(maximum)),
"unexpected number of attempts")
expect_unavailable(c, bob, row)
c.call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, actor=bob,
body={"text": "", "attachment_ids": [row["id"]]},
headers={"Idempotency-Key": uuid4().hex})
print(f"PASS safe failure code={error}; status|attempt|reason|max={state}; content/link HTTP 409")
action("stop", "broker")
try:
response = upload(c, alice, chat, expected=503)
check(response["json"]["error"]["code"] == "unavailable", "unexpected queue-down response")
c.message(alice, chat, "normal API works when broker is stopped")
print("PASS unavailable broker upload=503 (no false 202), ordinary message=201")
finally:
action("start", "broker")
eventually("broker healthy after failure case", lambda:
inspect("broker", "{{.State.Health.Status}}") == "healthy")
def replica_cases(c, alice, bob, chat):
for stopped, survivor in (("api1", "api2"), ("api2", "api1")):
action("stop", stopped)
try:
eventually(f"{survivor} handles existing Bearer with {stopped} stopped", lambda:
c.call("GET", "/api/v1/users/me", actor=bob, schema="User")["headers"]
["X-Instance-Id"] == survivor)
response = upload(c, alice, chat)
check(response["headers"]["X-Instance-Id"] == survivor, "wrong upload replica")
assert_ready(c, bob, response["json"], SAMPLE, (256, 160))
finally:
action("start", stopped)
eventually(f"{stopped} container healthy", lambda:
inspect(stopped, "{{.State.Health.Status}}") == "healthy")
print("PASS authorized new uploads and thumbnail reads with either replica stopped")
def main():
check(re.fullmatch(r"mtusi-lab6-grade3(?:-[a-z0-9-]+)?", PROJECT), "unsafe project name")
c = Client("http://lb:8080")
ready(c)
alice, bob, eve, chat = c.bootstrap()
alice_id = UUID(alice["id"])
check(sql(f"SELECT password_hash LIKE '$argon2id$%' FROM users WHERE id='{alice_id}'") == "t",
"stored verifier is not Argon2id")
print("PASS Argon2id verifier confirmed without reading hash")
restart_scenarios(c, alice, bob, eve, chat)
input_and_image_cases(c, alice, eve, chat)
failure_cases(c, alice, bob, chat)
replica_cases(c, alice, bob, chat)
check(queue_stats() == (0, 0), "queue did not drain")
print("PASS Lab 5 grade 3 Docker scenarios")
if __name__ == "__main__":
run(main)
+405
View File
@@ -0,0 +1,405 @@
"""Exercise real OTLP storage, Grafana and two isolated Compose incidents."""
import base64
import json
import math
import re
import time
from pathlib import Path
from uuid import uuid4
import requests
from PIL import Image
from grade3 import (
Client, Failure, action, assert_ready, check, docker, eventually, inspect,
image_bytes, metadata, ready, run, upload,
)
PROM = "http://prometheus:9090"
LOKI = "http://loki:3100"
TEMPO = "http://tempo:3200"
GRAFANA = "http://grafana:3000"
SERVICES = r'{service_name=~"messenger-api|messenger-worker"}'
DASH = "lab6-messenger"
SQUARE = image_bytes(Image.new("RGB", (320, 320), "navy"), "PNG")
SESSION = requests.Session()
AUTH = None
START = 0
TRACE_RECORDS = []
METRIC_RECORDS = []
def http(url, params=None, payload=None):
try:
method = "POST" if payload is not None else "GET"
response = SESSION.request(method, url, params=params, json=payload, timeout=8,
auth=AUTH if url.startswith(GRAFANA + "/") else None)
check(response.ok, f"{method} {url}: HTTP {response.status_code}")
return response
except requests.RequestException as exc:
raise Failure(f"backend connection: {url} ({type(exc).__name__})") from None
def data(url, params=None, payload=None):
return http(url, params, payload).json()
def report(event, **fields):
print(json.dumps({"evidence": event, **fields}, ensure_ascii=False, sort_keys=True))
def prom(query, when=None, base=PROM):
params = {"query": query}
if when is not None:
params["time"] = when
response = data(base + "/api/v1/query", params)
check(response["status"] == "success", "Prometheus query failed")
return response["data"]["result"]
def loki(query, base=LOKI, end=None, limit=1000):
response = data(base + "/loki/api/v1/query_range", {
"query": query, "start": START, "end": end or time.time_ns(), "limit": limit,
})
check(response["status"] == "success", "Loki query failed")
return [(ts, body, series["stream"] | (extra[0] if extra else {}))
for series in response["data"]["result"] for ts, body, *extra in series["values"]]
def value(item):
return item["value"][1]
def trace_hex(value, length):
if re.fullmatch(r"[0-9a-f]{" + str(length) + "}", value or ""):
return value
return base64.b64decode(value or "").hex()
def get_span(trace_id, span_id, service, kind, base=TEMPO):
payload = data(base + "/api/traces/" + trace_id)
for batch in payload.get("batches", payload.get("resourceSpans", [])):
attrs = {a["key"]: a["value"] for a in batch["resource"]["attributes"]}
if attrs["service.name"]["stringValue"] != service:
continue
check(attrs["service.version"]["stringValue"] == "1.6.0", "incorrect service version")
check(attrs["deployment.environment.name"]["stringValue"] == "lab", "incorrect environment")
check(attrs["service.instance.id"]["stringValue"] in {"api1", "api2", "worker"}, "bad instance")
for scope in batch.get("scopeSpans", []):
for span in scope["spans"]:
if trace_hex(span["spanId"], 16) != span_id:
continue
check(trace_hex(span["traceId"], 32) == trace_id, "trace ID mismatch")
check(span["kind"] in (kind, {2: "SPAN_KIND_SERVER", 5: "SPAN_KIND_CONSUMER"}[kind]),
"unexpected span kind")
duration = int(span["endTimeUnixNano"]) - int(span["startTimeUnixNano"])
check(duration > 0, "non-positive span duration")
TRACE_RECORDS.append(payload)
return {"trace_id": trace_id, "span_id": span_id, "duration_ns": duration,
"service": service, "resource": attrs, "span": span}
raise Failure("Tempo did not return matching service/span")
def correlate(label, selector, service, kind, key, val, outcome, status):
query = '{service_name="' + service + '"}' + selector
def linked():
rows = loki(query)
if not rows:
return None
timestamp, body, fields = rows[0]
trace_id, span_id = fields["trace_id"], fields["span_id"]
check(re.fullmatch("[0-9a-f]{32}", trace_id) and int(trace_id, 16), "invalid Loki trace ID")
check(re.fullmatch("[0-9a-f]{16}", span_id) and int(span_id, 16), "invalid Loki span ID")
check(fields.get("severity_text") in {"INFO", "WARN", "WARNING", "ERROR"}
and fields["event"] == body, "missing structured log fields")
record = get_span(trace_id, span_id, service, kind)
span = record["span"]
attrs = {a["key"]: a["value"] for a in span["attributes"]}
check(attrs[key]["stringValue"] == val and attrs["outcome"]["stringValue"] == outcome,
"different event in Tempo")
check(span["status"]["code"] in (status, {1: "STATUS_CODE_OK", 2: "STATUS_CODE_ERROR"}[status]),
"incorrect trace status")
check(int(span["startTimeUnixNano"]) <= int(timestamp) <= int(span["endTimeUnixNano"]),
"log timestamp outside span")
return {"query": query, "log": [timestamp, body, fields], "tempo": record}
result = eventually(label, linked, seconds=45, interval=1)
report(label, **result)
return result
def check_metrics():
allowed = {
"messenger_http_requests_total": {"method", "route", "status_class"},
"messenger_http_duration_seconds_sum": {"method", "route", "status_class"},
"messenger_http_duration_seconds_count": {"method", "route", "status_class"},
"messenger_http_duration_seconds_bucket": {"method", "route", "status_class", "le"},
"messenger_job_outcomes_total": {"job_type", "outcome"},
"messenger_job_duration_seconds_sum": {"job_type", "outcome"},
"messenger_job_duration_seconds_count": {"job_type", "outcome"},
"messenger_job_duration_seconds_bucket": {"job_type", "outcome", "le"},
}
paths = json.loads(Path("contracts/openapi.json").read_text())["paths"]
metrics = {}
for name, labels in allowed.items():
rows = prom(name)
check(bool(rows), f"no series for {name}")
expected_service = "messenger-api" if "http" in name else "messenger-worker"
for row in rows:
fields = row["metric"]
check(set(fields) == labels | {"__name__", "job", "instance"}, f"unexpected labels on {name}")
check(fields["job"] == expected_service, "unexpected Prometheus service label")
check(fields["instance"] in ({"api1", "api2"} if "http" in name else {"worker"}),
"unexpected instance label")
if "route" in fields:
check(fields["route"] in paths or fields["route"] == "unmatched", "raw route label")
else:
check(fields["job_type"] == "attachment.process.v1", "unknown job type")
if "http" in name:
required = [row for row in rows if row["metric"]["route"] == "/api/v1/attachments/{attachment_id}/content"]
check(all(any(r["metric"]["status_class"] == status and float(value(r)) > 0
for r in required) for status in ("2xx", "5xx")), f"missing HTTP series for {name}")
else:
check(all(any(r["metric"]["outcome"] == outcome and float(value(r)) > 0
for r in rows) for outcome in ("success", "fail")), f"missing job series for {name}")
if "bucket" in name:
check({0.005, 0.25, 60, math.inf} <= {float(r["metric"]["le"]) for r in rows}, "missing histogram buckets")
METRIC_RECORDS.extend(rows)
metrics[name] = rows
# Keep the verified dynamic routes and an actual bucket sample in review evidence.
for name, rows in metrics.items():
samples = [r for r in rows if r["metric"].get("le", "+Inf") in ("0.005", "+Inf")
and r["metric"].get("route", "/api/v1/attachments/{attachment_id}/content")
== "/api/v1/attachments/{attachment_id}/content"]
report("prometheus", query=name, checked_series=len(rows), samples=samples)
return metrics
def check_grafana(api, worker):
sources = data(GRAFANA + "/api/datasources")
for kind in ("prometheus", "loki", "tempo"):
uid = "lab6-" + kind
source = next((s for s in sources if s["uid"] == uid and s["type"] == kind), None)
check(source is not None, "Grafana datasource not provisioned")
if kind == "tempo":
# The built-in Tempo plugin in this Grafana version has no
# plugin health handler. Prove readiness and real trace queries via proxy.
status = http(GRAFANA + f"/api/datasources/proxy/uid/{uid}/ready")
health = {"http_status": status.status_code, "body": status.text.strip()}
else:
health = data(GRAFANA + f"/api/datasources/uid/{uid}/health")
check(health["status"].lower() == "ok", "Grafana datasource unhealthy")
report("grafana.datasource", uid=uid, type=kind, url=source["url"], health=health)
dashboards = data(GRAFANA + "/api/dashboards/uid/" + DASH)
panels = dashboards["dashboard"]["panels"]
check(len(panels) == 6, "expected six Grafana panels")
start_ms = str(int(START / 1_000_000) - 30_000)
end_ms = str(time.time_ns() // 1_000_000)
for panel in panels:
target = panel["targets"][0]
ds = panel["datasource"]
if ds["type"] == "prometheus":
query = target | {"datasource": ds, "intervalMs": 5000, "maxDataPoints": 120, "range": True}
response = data(GRAFANA + "/api/ds/query", payload={
"from": start_ms, "to": end_ms, "queries": [query],
})["results"]["A"]
check(not response.get("error"), "Grafana panel query failed")
frames = response.get("frames", [])
values = [v for f in frames for v in f["data"]["values"][-1]
if isinstance(v, (int, float)) and math.isfinite(v)]
check(values and any(v > 0 for v in values), f"no signal in Grafana panel {panel['id']}")
report("grafana.panel", id=panel["id"], title=panel["title"], query=target["expr"],
frames=len(frames), numeric_samples=len(values), max_value=max(values))
else:
rows = loki(target["expr"], base=GRAFANA + "/api/datasources/proxy/uid/lab6-loki")
check({fields["service_name"] for _, _, fields in rows} >= {"messenger-api", "messenger-worker"},
"Grafana Loki query missing a service")
report("grafana.panel", id=panel["id"], title=panel["title"], query=target["expr"], rows=len(rows))
link = next(s for s in sources if s["uid"] == "lab6-loki")["jsonData"]["derivedFields"][0]
check(link["datasourceUid"] == "lab6-tempo" and link["matcherRegex"] == "trace_id"
and link["url"] == "${__value.raw}", "Grafana Loki-to-Tempo link not provisioned")
for linked in (api, worker):
trace = linked["tempo"]
result = get_span(trace["trace_id"], trace["span_id"], trace["service"],
2 if trace["service"] == "messenger-api" else 5,
base=GRAFANA + "/api/datasources/proxy/uid/lab6-tempo")
report("grafana.trace", trace_id=result["trace_id"], span_id=result["span_id"])
def incidents(client, alice, chat, filename):
from grade3 import SERVICES as compose_services
compose_services.update({"prometheus", "loki", "tempo", "grafana", "otel-collector"})
direct = Client("http://api1:8080", timeout=5)
started = time.monotonic()
action("stop", "worker")
try:
queued = upload(client, alice, chat, data=SQUARE, filename=filename)["json"]
check(metadata(client, alice, queued)["status"] == "queued", "worker was expected to be stopped")
check(inspect("worker", "{{.State.Running}}") == "false", "worker still running")
report("worker.stop", accepted=202, attachment_id=queued["id"], status="queued")
finally:
action("start", "worker")
assert_ready(client, alice, queued, SQUARE, (256, 256))
report("worker.recovered", attachment_id=queued["id"], status="ready",
seconds=round(time.monotonic() - started, 3))
action("stop", "worker")
failure_started = time.monotonic()
try:
failing = upload(client, alice, chat, data=SQUARE, filename=filename)["json"]
action("stop", "s3")
action("start", "worker")
path = f"/api/v1/attachments/{queued['id']}/content"
error = direct.call("GET", path, 503, actor=alice)
request_id = error["headers"]["X-Request-Id"]
# More than one scrape separates some errors, so rate() has a delta.
direct.call("GET", path, 503, actor=alice)
direct.call("GET", path, 503, actor=alice)
def failed():
state = metadata(direct, alice, failing)
return state if state["status"] == "failed" else None
failed_state = eventually("terminal S3 outage", failed, seconds=55, interval=0.7)
check(failed_state["error_code"] == "retry_exhausted", "expected retry budget exhaustion")
report("s3.outage", http_status=503, request_id=request_id, attachment_id=failing["id"],
status="failed", error_code=failed_state["error_code"],
seconds=round(time.monotonic() - failure_started, 3))
finally:
action("start", "s3", "worker")
ready(client)
assert_ready(client, alice, queued, SQUARE, (256, 256))
new_attachment = upload(client, alice, chat, data=SQUARE, filename=filename)["json"]
assert_ready(client, alice, new_attachment, SQUARE, (256, 256))
report("s3.recovered", existing=queued["id"], new=new_attachment["id"],
seconds=round(time.monotonic() - failure_started, 3))
return queued["id"], failing["id"], request_id
def verify_safe(actors, marker, filename, headers):
logs = loki(SERVICES + ' | event != ""', limit=4000)
literals = [marker, filename, b"\x89PNG".hex()]
for actor in actors:
registration = actor["registration"]
password = registration["password"]
literals.extend((actor["token"], password,
base64.b64encode(f"{registration['username']}:{password}".encode()).decode()))
literals.extend(headers)
# Inspect raw backend responses in memory and emit only counts.
blob = json.dumps([logs, METRIC_RECORDS, TRACE_RECORDS], ensure_ascii=False)
matches = sum(blob.count(secret) for secret in literals)
patterns = re.compile(
r'(?i)\b(?:authorization|secret_access_key|x-amz-signature|password|bearer)\b'
r'|-----BEGIN [A-Z ]*PRIVATE KEY-----|iVBORw0KGgo|/9j/'
r'|/api/v1/(?:chats|attachments)/[0-9a-f]{8}-'
)
matches += len(patterns.findall(blob))
check(matches == 0, "sensitive data found in backend responses")
report("telemetry.scan", loki_rows=len(logs), spans_queries=len(TRACE_RECORDS),
metric_samples=len(METRIC_RECORDS), matches=matches)
def restart_stores(api, worker):
services = ("prometheus", "loki", "tempo", "grafana")
def starts():
return {service: inspect(service, "{{.State.StartedAt}}") for service in services}
def volumes():
return {service: inspect(service, '{{range .Mounts}}{{if eq .Type "volume"}}{{.Name}}{{end}}{{end}}')
for service in services}
before = starts()
mounts = volumes()
check(all(mounts.values()), "missing named backend volume")
when = time.time()
end = time.time_ns()
query = 'sum(messenger_job_outcomes_total{outcome="success"})'
historical = prom(query, when)
check(historical and float(value(historical[0])) > 0, "missing historical sample")
action("restart", *services)
def same_history():
check(prom(query, when) == historical, "Prometheus historical sample changed")
for linked in (api, worker):
check(tuple(linked["log"]) in loki(linked["query"], end=end), "Loki lost control event")
trace = linked["tempo"]
repeat = get_span(trace["trace_id"], trace["span_id"], trace["service"],
2 if trace["service"] == "messenger-api" else 5)
check(repeat["span"] == trace["span"], "Tempo lost control span")
return data(GRAFANA + "/api/dashboards/uid/" + DASH)["dashboard"]["uid"] == DASH
eventually("same samples, logs, spans and dashboard after restart", same_history, seconds=80, interval=1)
after = starts()
check(all(before[s] != after[s] for s in services) and volumes() == mounts,
"unexpected process or volume after restart")
report("storage.restart", before=before, after=after, volumes=mounts, historical_query=query,
unix_time=when, historical_samples=historical,
trace_ids=[api["tempo"]["trace_id"], worker["tempo"]["trace_id"]], dashboard=DASH)
def main():
global AUTH, START
AUTH = ("admin", Path("/run/secrets/grafana_admin_password").read_text().strip())
START = time.time_ns()
for url in (PROM + "/-/ready", LOKI + "/ready", TEMPO + "/ready", GRAFANA + "/api/health",
"http://otel-collector:13133/"):
eventually(url, lambda: http(url), seconds=75, interval=1)
client = Client(timeout=10)
alice, bob, eve, chat = client.bootstrap()
marker = "message-canary-" + uuid4().hex
filename = "filename-canary-" + uuid4().hex + ".png"
header_canary = "header-canary-" + uuid4().hex
created = client.message(alice, chat, marker, key=header_canary)
api_id = created["headers"]["X-Request-Id"]
check(created["status"] == 201, "POST must succeed")
denied = client.call("GET", "/api/v1/users/me", 401)
request_401 = denied["headers"]["X-Request-Id"]
started = time.monotonic()
for index in range(48):
client.call("GET", "/api/v1/users/me", actor=alice)
if index % 8 == 0:
client.call("GET", "/api/v1/users/me", 401)
time.sleep(0.14)
report("traffic", get=48, post_status=201, error_status=401, seconds=round(time.monotonic()-started, 3))
success_id, failure_id, request_503 = incidents(client, alice, chat, filename)
api = correlate("api.success", f' | request_id="{api_id}" | event="http.completed"',
"messenger-api", 2, "request.id", api_id, "2xx", 1)
correlate("api.401", f' | request_id="{request_401}" | event="http.completed"',
"messenger-api", 2, "request.id", request_401, "4xx", 1)
error = correlate("api.503", f' | request_id="{request_503}" | event="http.completed"',
"messenger-api", 2, "request.id", request_503, "5xx", 2)
check(any(a["key"] == "dependency.name" and a["value"]["stringValue"] == "s3"
for a in error["tempo"]["span"]["attributes"]), "S3 not diagnosed by API trace")
worker = correlate("worker.ready", f' | attachment_id="{success_id}" | event="job.outcome" | outcome="ready"',
"messenger-worker", 5, "attachment_id", success_id, "ready", 1)
retry = correlate("worker.retry", f' | attachment_id="{failure_id}" | event="job.outcome" | outcome="retry"',
"messenger-worker", 5, "attachment_id", failure_id, "retry", 2)
check(retry["log"][2]["reason"] == "storage_unavailable", "S3 not diagnosed by retry log")
correlate("worker.failed", f' | attachment_id="{failure_id}" | event="job.outcome" | outcome="failed"',
"messenger-worker", 5, "attachment_id", failure_id, "failed", 2)
eventually("all real counter and histogram series", check_metrics, seconds=30, interval=2)
check_grafana(api, worker)
verify_safe((alice, bob, eve), marker, filename, [header_canary, chat["id"]])
restart_stores(api, worker)
action("stop", "otel-collector", "grafana")
try:
client.call("GET", "/health/ready", schema="Health")
client.call("GET", "/api/v1/users/me", actor=alice)
attachment = upload(client, alice, chat, data=SQUARE)["json"]
assert_ready(client, alice, attachment, SQUARE, (256, 256))
report("telemetry.outage", health=200, authenticated_get=200, uploaded=202,
state="ready", disabled=["otel-collector", "grafana"])
finally:
action("start", "otel-collector", "grafana")
print("PASS: real metrics/logs/traces, provisioned Grafana, incidents and persistent telemetry")
if __name__ == "__main__":
run(main)