Files
mtusi2026lab6/student-tests/test_observability.py

281 lines
16 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Собственные проверки lab6 (уровни 3–4): telemetry своего приложения находится в сохранённых
наблюдениях — Prometheus/Loki/Tempo через Grafana (datasource proxy), без доступа к stdout контейнеров.
python3 student-tests/test_observability.py (стенд запущен, Grafana на 127.0.0.1:3000)
"""
import re
import time
import uuid
from common import BASE_URL, Client, Suite, check, new_user, login, upload, wait_status
from obs import Grafana, ObsError, wait_for
suite = Suite("lab6: наблюдаемость — provisioning, сигналы, корреляция, безопасность telemetry")
c = Client(BASE_URL)
g = Grafana()
ctx = {}
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", "url_full", "url_path",
"http_target", "filename", "text", "job_id", "trace_id", "span_id"}
def setup_actors():
if "alice" not in ctx:
ctx["password"] = "Obs-Secret-" + uuid.uuid4().hex # ищем его потом в telemetry
alice = new_user(c, "obs", password=ctx["password"])
login(c, alice)
chat = c.call("POST", "/api/v1/chats", 201, actor=alice, schema="Chat",
body={"title": "obs", "member_ids": [alice["id"]]})["json"]
ctx.update(alice=alice, chat=chat)
return ctx["alice"], ctx["chat"]
def log_by_request(rid, service="messenger-api"):
recs = g.loki('{service_name="%s"} | request_id="%s"' % (service, rid), since=600)
return [r for r in recs if r.get("event") == "http.request"]
def descendants_of(spans, root_id):
kids = {}
for s in spans:
kids.setdefault(s["parent"], []).append(s)
out, stack = [], [root_id]
while stack:
for s in kids.get(stack.pop(), []):
out.append(s)
stack.append(s["span_id"])
return out
def ancestors(spans, span):
by_id = {s["span_id"]: s for s in spans}
out, cur = [], by_id.get(span["parent"])
while cur is not None:
out.append(cur)
cur = by_id.get(cur["parent"])
return out
@suite.case("provisioning: Prometheus/Loki/Tempo из Git, health OK")
def provisioning_datasources():
ds = {d["uid"]: d for d in g.get("/api/datasources")}
check({"prometheus", "loki", "tempo"} <= set(ds), "datasources: %s" % sorted(ds))
check(all(ds[u]["readOnly"] for u in ("prometheus", "loki", "tempo")), "datasources must be provisioned (read-only)")
out = []
for uid in ("prometheus", "loki", "tempo"):
h = g.get("/api/datasources/uid/%s/health" % uid)
check(h.get("status") == "OK", "%s health: %s" % (uid, h))
out.append(uid)
return "health OK: " + ", ".join(out)
@suite.case("provisioning: dashboard импортирован, все запросы панелей выполняются")
def provisioning_dashboard():
d = g.get("/api/dashboards/uid/messenger-overview")
check(d["meta"].get("provisioned"), "dashboard is not provisioned from file")
panels = [p for p in d["dashboard"]["panels"] if p.get("type") != "row"]
queries = with_data = 0
errors = []
for p in panels:
for t in p.get("targets", []):
queries += 1
res = g.ds_query({k: v for k, v in t.items() if k != "datasource"}, t.get("datasource") or p["datasource"], since=1800)
r = res["results"][t.get("refId", "A")]
if r.get("error") or r.get("status", 200) >= 400:
errors.append("%s: %s" % (p["title"], (r.get("error") or "")[:120]))
elif any(f.get("data", {}).get("values") and any(len(v) for v in f["data"]["values"]) for f in r.get("frames", [])):
with_data += 1
check(not errors, "panel query errors: %s" % errors[:5])
return "%d панелей, %d запросов без ошибок, с данными %d" % (len(panels), queries, with_data)
@suite.case("HTTP: X-Request-Id → структурный лог → trace (server + DB spans)")
def request_log_trace():
alice, chat = setup_actors()
ctx["marker"] = "obs-marker-" + uuid.uuid4().hex # текст сообщения: не должен попасть в telemetry
r = c.message(alice, chat, "Тайное содержимое " + ctx["marker"])
rid = r["headers"]["X-Request-Id"]
recs = wait_for(lambda: log_by_request(rid), 60, what="log with request_id")
rec = recs[-1]
for f in ("trace_id", "span_id", "severity_text", "service_name", "event", "route", "status"):
check(rec.get(f), "log record lacks %s: %s" % (f, sorted(rec)))
check(rec["route"] == "/api/v1/chats/{chat_id}/messages" and rec["status"] == "201", "log route/status: %s" % rec)
spans = wait_for(lambda: g.trace(rec["trace_id"]), 60, what="trace " + rec["trace_id"])
server = [s for s in spans if s["kind"] == "SERVER"]
check(len(server) == 1, "expected one server span, got %s" % [s["name"] for s in spans])
sv = server[0]
check(sv["name"] == "POST /api/v1/chats/{chat_id}/messages", "server span name: %s" % sv["name"])
check(sv["attrs"].get("messenger.request_id") == rid and sv["attrs"].get("http.response.status_code") == 201,
"server span attrs: %s" % sv["attrs"])
check(sv["span_id"] == rec["span_id"], "log span_id %s != server span %s" % (rec["span_id"], sv["span_id"]))
db = [s for s in descendants_of(spans, sv["span_id"]) if s["attrs"].get("db.system.name") == "postgresql"]
check(any(s["name"] == "INSERT messages" for s in db), "no INSERT messages span: %s" % [s["name"] for s in db])
ctx["msg_trace"] = rec["trace_id"]
return "request_id → trace %s…, %d spans (%d DB)" % (rec["trace_id"][:12], len(spans), len(db))
@suite.case("безопасность: пароль, токен, тело сообщения не попадают в логи/трассы")
def no_secrets():
alice, chat = setup_actors()
if "marker" not in ctx:
request_log_trace()
r = login(c, alice) # Basic с паролем → токен в ответе
rid = r["headers"]["X-Request-Id"]
rec = wait_for(lambda: log_by_request(rid), 60, what="login log")[-1]
login_trace = wait_for(lambda: g.trace_raw_text(rec["trace_id"]), 60, what="login trace")
msg_trace = g.trace_raw_text(ctx["msg_trace"])
secrets = {"password": ctx["password"], "token": alice["token"], "message text": ctx["marker"], "Bearer": "Bearer "}
leaks = []
for name, value in secrets.items():
for where, text in (("login trace", login_trace), ("message trace", msg_trace)):
if value in text:
leaks.append("%s in %s" % (name, where))
if name != "Bearer" and g.loki('{service_name=~"messenger-api|messenger-worker"} |= "%s"' % value, since=900):
leaks.append(name + " in Loki")
check(not leaks, "telemetry leaks: %s" % leaks)
check("password.verify" in login_trace, "login trace has no password.verify span (KDF time not visible)")
return "проверено в Loki и 2 trace: пароль, токен, текст сообщения, Authorization"
@suite.case("upload → create → send → process → S3/DB: один trace; лог worker с тем же trace_id")
def upload_chain():
alice, chat = setup_actors()
att, _ = upload(c, alice, chat)
wait_status(c, alice, att["id"], "ready", timeout=60)
def find():
traces = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=600)
if not traces:
return None
spans = g.trace(traces[0]["traceID"])
procs = [s for s in spans or [] if s["kind"] == "CONSUMER" and s["attrs"].get("messenger.job.outcome")]
return spans if procs else None
spans = wait_for(find, 90, what="worker span in upload trace")
by = lambda n: [s for s in spans if s["name"] == n] # noqa: E731
server = by("POST /api/v1/chats/{chat_id}/attachments")
create, send = by("create attachments.process.v1"), by("send attachments.process.v1")
process = by("process attachments.process.v1")
check(len(server) == 1 and server[0]["kind"] == "SERVER" and server[0]["service"] == "messenger-api", "server span")
check(len(create) == 1 and create[0]["kind"] == "PRODUCER" and create[0]["parent"] == server[0]["span_id"],
"create span must be PRODUCER child of upload server span")
check(len(send) >= 1 and all(s["kind"] == "PRODUCER" and s["parent"] == create[0]["span_id"] for s in send),
"send span must be PRODUCER child of create")
check(len(process) == 1 and process[0]["kind"] == "CONSUMER" and process[0]["service"] == "messenger-worker"
and process[0]["parent"] == send[0]["span_id"], "process must be CONSUMER child of send (worker)")
p = process[0]
check(p["attrs"].get("messenger.job.outcome") == "ready" and p["attrs"].get("messaging.system") == "nats", "process attrs")
inner = descendants_of(spans, p["span_id"])
names = [s["name"] for s in inner]
check(names.count("S3.PutObject") >= 4, "original + 3 variants PUT expected: %s" % names)
check("imgproc.run" in names and "job.commit" in names and "UPDATE attachments" in names, "pipeline spans: %s" % names)
tid = p["trace_id"]
rec = wait_for(lambda: g.loki('{service_name="messenger-worker"} | event="job.finished" | attachment_id="%s"' % att["id"],
since=600), 60, what="worker log")[-1]
check(rec.get("trace_id") == tid and rec.get("span_id") == p["span_id"], "worker log not linked to process span")
ctx["upload_trace"] = tid
return "%d spans: SERVER→create→send→process(%s)→S3×%d; queue %.2f с" % (
len(spans), p["service"], names.count("S3.PutObject"), p["start"] - send[0]["end"])
@suite.case("retry: 2 временные ошибки + успех — три попытки в одном trace")
def retry_chain():
alice, chat = setup_actors()
att, _ = upload(c, alice, chat, filename="obs-fault-transient-2.png")
wait_status(c, alice, att["id"], "ready", timeout=90)
def find():
traces = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=600)
spans = g.trace(traces[0]["traceID"]) if traces else None
procs = [s for s in spans or [] if s["name"] == "process attachments.process.v1"]
return spans if len(procs) >= 3 and any(s["attrs"].get("messenger.job.outcome") == "ready" for s in procs) else None
spans = wait_for(find, 90, what="3 process spans")
procs = sorted([s for s in spans if s["name"] == "process attachments.process.v1"], key=lambda s: s["start"])
outcomes = [s["attrs"].get("messenger.job.outcome") for s in procs]
check(outcomes == ["retry", "retry", "ready"], "outcomes: %s" % outcomes)
check([s["attrs"].get("messenger.job.attempt") for s in procs] == [1, 2, 3], "attempts")
check(all(s["status"] == "ERROR" and s["attrs"].get("error.type") == "processing_failed" for s in procs[:2]),
"failed attempts must be marked as errors")
check(procs[0] in ancestors(spans, procs[1]) and procs[1] in ancestors(spans, procs[2]),
"next attempt must descend from previous attempt (retry → outbox → send → process)")
return "попытки 1→2→3: %s; паузы backoff %.1f с и %.1f с" % (
outcomes, procs[1]["start"] - procs[0]["end"], procs[2]["start"] - procs[1]["end"])
@suite.case("метрики контракта: имена, низкая кардинальность, шаблоны маршрутов")
def metric_contract():
required = ["http_server_request_duration_seconds_count", "http_server_active_requests",
"db_client_operation_duration_seconds_count", "db_client_connection_count",
"db_client_connection_pending_requests", "db_client_connection_max",
"messenger_jobs_processed_total", "messenger_job_duration_seconds_count",
"messenger_attachment_time_to_ready_seconds_count", "messenger_job_queue_wait_seconds_count",
"messenger_queue_depth", "messenger_queue_lag_seconds", "messenger_queue_oldest_age_seconds",
"messenger_broker_pending", "messenger_worker_busy", "messenger_worker_capacity",
"container_cpu_time_seconds_total", "container_memory_usage_bytes", "process_memory_usage_bytes",
"otel_sdk_processor_span_processed_total"]
missing = [m for m in required if not g.series(m, since=900)]
check(not missing, "metrics missing: %s" % missing)
series = g.series('{__name__=~"messenger_.*|http_server_.*|db_client_.*|container_.*"}', since=900)
labels = set().union(*(s.keys() for s in series))
bad = labels & FORBIDDEN_LABELS
check(not bad, "forbidden metric labels: %s" % bad)
routes = {s.get("http_route") for s in series if s.get("http_route")}
check(routes and not any(UUID_RE.search(r) for r in routes), "routes must be templates: %s" % routes)
check(all(s.get("service_name") in ("messenger-api", "messenger-worker") and s.get("deployment_environment_name") == "lab"
and s.get("service_instance_id") for s in series), "resource labels missing on some series")
n_http = len([s for s in series if s["__name__"] == "http_server_request_duration_seconds_count"])
check(n_http < 300, "too many http series: %d" % n_http)
return "%d метрик; серий %d (HTTP count — %d); маршрутов %d; запрещённых labels нет" % (
len(required), len(series), n_http, len(routes))
@suite.case("метрики отражают обработку: jobs, retry, time-to-ready, p95 из histogram")
def metric_values():
def ok():
ready = g.prom_value('sum(messenger_jobs_processed_total{outcome="ready"})', 0)
retry = g.prom_value('sum(messenger_jobs_processed_total{outcome="retry"})', 0)
ttr = g.prom_value("sum(messenger_attachment_time_to_ready_seconds_count)", 0)
return (ready, retry, ttr) if ready >= 2 and retry >= 2 and ttr >= 2 else None
ready, retry, ttr = wait_for(ok, 40, what="job metrics")
p95 = g.prom_value('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket'
'{service_name="messenger-api",http_route!~"/health/.*"}[10m])))')
check(p95 is not None and p95 > 0, "p95 from histogram: %s" % p95)
t95 = g.prom_value("histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[30m])))")
return "ready=%d retry=%d time_to_ready count=%d; p95 HTTP %.0f мс, p95 ready %.2f с" % (ready, retry, ttr, p95 * 1000, t95 or 0)
@suite.case("алерты: правила загружены и вычисляются без ошибок")
def alert_rules():
groups = g.rules()
rules = [r for grp in groups for r in grp["rules"]]
names = {r["name"] for r in rules if r["type"] == "alerting"}
need = {"ApiHighErrorRate", "JobQueueLagGrowing", "WorkerHeartbeatMissing", "DbSlowQueries", "ApiLatencyHigh",
"TelemetryExportFailing"}
check(need <= names, "alerts missing: %s" % (need - names))
bad = [r["name"] for r in rules if r.get("health") != "ok" or r.get("lastError")]
check(not bad, "rules with evaluation errors: %s" % bad)
for r in rules:
if r["type"] == "alerting":
ann = r.get("annotations", {})
check(ann.get("summary") and ann.get("runbook_url"), "alert %s lacks summary/runbook" % r["name"])
firing = [a["labels"]["alertname"] for a in g.alerts() if a["state"] == "firing"]
return "%d правил (%d алертов), firing сейчас: %s" % (len(rules), len(names), firing or "нет")
@suite.case("SDK: spans/logs не отбрасываются при работающем Collector")
def sdk_no_drops():
total = g.prom_value("sum(otel_sdk_processor_span_processed_total)", 0)
dropped = g.prom_value('sum(otel_sdk_processor_span_processed_total{error_type!=""})', 0)
ldropped = g.prom_value('sum(otel_sdk_processor_log_processed_total{error_type!=""})', 0)
check(total > 0, "no SDK span counters")
check(dropped == 0 and ldropped == 0, "dropped spans=%s logs=%s" % (dropped, ldropped))
return "обработано spans %d, отброшено 0" % total
if __name__ == "__main__":
try:
g.get("/api/health")
except ObsError as e:
raise SystemExit("Grafana недоступна: %s" % e)
suite.run()