"""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, assert_ready, check, eventually, image_bytes, run, upload, ) GRAFANA = "https://localhost:3443" PROXY = GRAFANA + "/api/datasources/proxy/uid/lab6-" PROM, LOKI, TEMPO = (PROXY + role for role in ("prometheus", "loki", "tempo")) 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, verify="secrets/ca/server.crt") 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.7.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" resource_labels = {"service_name", "service_instance_id", "service_version", "deployment_environment_name"} for row in rows: fields = row["metric"] check(set(fields) == labels | {"__name__", "job", "instance"} | resource_labels, 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") check(fields["service_name"] == expected_service and fields["service_instance_id"] == fields["instance"], "inconsistent OTLP resource identity") 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",)), 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",)), 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 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 main(): global AUTH, START AUTH = ("admin", Path("secrets/grafana/password").read_text().strip()) START = time.time_ns() for url in (PROM + "/-/ready", LOKI + "/ready", TEMPO + "/ready", GRAFANA + "/api/health"): eventually(url, lambda: http(url), seconds=75, interval=1) client = Client("https://127.0.0.1:8443", "secrets/ca/public.crt", 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)) attachment = upload(client, alice, chat, data=SQUARE, filename=filename)["json"] assert_ready(client, bob, attachment, SQUARE, (256, 256)) success_id = attachment["id"] 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) worker = correlate("worker.ready", f' | attachment_id="{success_id}" | event="job.outcome" | outcome="ready"', "messenger-worker", 5, "attachment_id", success_id, "ready", 1) 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"]]) print("PASS: real metrics, logs and traces through the provisioned Grafana data sources") if __name__ == "__main__": run(main)