406 lines
20 KiB
Python
406 lines
20 KiB
Python
"""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)
|