Files
mtusi2026lab6/student-tests/dashboard_check.py
T
zemiles c199f6632a ЛР 6 — БПИ2303 — Лазарев — на 4
Перенесена реализация lab5 (API x2 за HAProxy, PostgreSQL, SeaweedFS S3,
RabbitMQ, relay outbox, worker x2, janitor) без изменения бизнес-API.

Наблюдаемость:
- OpenTelemetry SDK в API, relay, worker, janitor: traces, metrics, logs
  по OTLP/HTTP; структурные JSON-логи с trace_id/span_id
- OTel Collector (memory_limiter, batch, ограниченные очереди и retry),
  Prometheus (метрики, alert rules), Loki (логи), Tempo (трассы),
  Grafana с provisioning datasources и dashboard
- W3C trace context API -> outbox -> RabbitMQ -> worker (parent-child,
  включая retry); метрики очереди, пула БД, загрузки worker, CPU/RAM
- SLI/SLO, 10 alert rules с unit-тестами promtool и runbooks
- инциденты: остановка worker, блокировка БД, отказ telemetry backend;
  по наблюдениям исправлен простой worker в цикле AMQP (разбор x2.4)
2026-11-17 10:59:41 +03:00

104 lines
6.2 KiB
Python
Raw 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: dashboard импортирован provisioning-ом и все его запросы работают на реальных данных.
python3 student-tests/dashboard_check.py --output evidence/dashboard-check.json
* Grafana отдаёт dashboard uid=messenger-overview (provisioned, папка Messenger) и 3 datasource;
* каждый PromQL панели выполняется через Grafana (ошибка синтаксиса/имени = FAIL); для
ключевых панелей результат обязан быть непустым (метрика реально существует);
* LogQL и TraceQL панелей выполняются в Loki/Tempo без ошибок.
Перед проверкой — прогрев 40 с (сообщения, чтение, upload до ready): панели с rate()/increase()
за 1 мин пусты, если за последнюю минуту не было трафика (например, сразу после пересоздания worker).
"""
import argparse
import json
import sys
import time
from pathlib import Path
import obslib
from lab5lib import SAMPLE_PNG, Client, upload, wait_status
from traffic import Traffic
ROOT = Path(__file__).resolve().parents[1]
# Панели, данные которых есть всегда после smoke-трафика (остальные — ошибки/алерты, могут быть пусты).
MUST_HAVE_DATA = {
"RPS бизнес-запросов", "p95 API (5m)", "RPS по маршруту", "Ответы по классу статуса",
"Задержка API p50/p95/p99 (из histogram)", "p95 по маршруту", "Запросы в обработке (saturation API)",
"HAProxy: UP-реплики и очередь LB", "Задания по исходу (в минуту)", "Глубина очереди: PostgreSQL и RabbitMQ",
"Возраст старейшего задания и lag", "Saturation worker: занятость потребителей",
"Пул соединений API: used / idle / max", "Операции БД p95 по операции (API)", "S3 p95 по операции",
"CPU, ядер (cgroup контейнера)", "Память контейнеров приложений", "Память: доля лимита",
"Память telemetry-стека (RSS)", "Collector: принято / отправлено / потеряно (spans)", "Collector: логи",
"Collector: очередь экспортёров", "SDK: заполнение очереди BatchSpanProcessor", "Time to ready p95",
"Ready lag очереди", "Relay: публикации outbox", "Ожидание в очереди p95 (до claim)",
}
def main():
p = argparse.ArgumentParser()
p.add_argument("--output")
p.add_argument("--warmup", type=int, default=40)
args = p.parse_args()
if args.warmup:
c = Client(timeout=30)
alice, _bob, _eve, chat = c.bootstrap()
tr = Traffic(c, alice, chat, threads=2, think=0.3, upload_every=3).start()
att = upload(c, alice, chat, SAMPLE_PNG, "warmup.png")
wait_status(c, alice, att["id"], ("ready",), timeout=60)
time.sleep(args.warmup)
tr.stop()
print("warmup:", tr.window(0, args.warmup + 60))
dash = json.loads((ROOT / "infra/grafana/dashboards/messenger.json").read_text(encoding="utf-8"))
got = obslib.grafana("/api/dashboards/uid/" + dash["uid"])
assert got and got["dashboard"]["uid"] == dash["uid"], "dashboard is not provisioned"
meta = got["meta"]
ds = sorted(d["uid"] for d in obslib.grafana("/api/datasources"))
assert {"prometheus", "loki", "tempo"} <= set(ds), ds
health = {uid: obslib.grafana("/api/datasources/uid/%s/health" % uid) for uid in ("prometheus", "loki", "tempo")}
report = {"dashboard": {"uid": dash["uid"], "title": got["dashboard"]["title"], "provisioned": meta.get("provisioned"),
"folder": meta.get("folderTitle"), "panels": len(dash["panels"])},
"datasources": ds, "datasource_health": {k: (v or {}).get("status") for k, v in health.items()},
"panels": []}
failed = []
now = time.time()
for panel in dash["panels"]:
if panel["type"] == "row":
continue
for t in panel.get("targets", []):
uid = t["datasource"]["uid"]
item = {"panel": panel["title"], "ref": t["refId"], "datasource": uid}
try:
if uid == "prometheus":
expr = t["expr"].replace('instance=~"$instance"', 'instance=~".*"')
res = obslib.prom_query(expr)
item["series"] = len(res)
elif uid == "loki":
item["lines"] = len(obslib.loki_query(t["expr"], now - 3600, now, limit=20))
else:
r = obslib.tempo_search(t["query"], now - 3600, now, limit=5)
item["traces"] = len((r or {}).get("traces") or [])
item["ok"] = True
except Exception as exc:
item["ok"], item["error"] = False, str(exc)[:200]
failed.append(item)
report["panels"].append(item)
empty_required = sorted({i["panel"] for i in report["panels"] if i["panel"] in MUST_HAVE_DATA
and i.get("series", 1) == 0 and i["ref"] == "A"})
report["query_errors"] = failed
report["empty_required_panels"] = empty_required
report["pass"] = not failed and not empty_required and report["datasource_health"] == {
"prometheus": "OK", "loki": "OK", "tempo": "OK"}
for i in report["panels"]:
print("%-4s %-55s %-10s %s" % ("ok" if i["ok"] else "ERR", i["panel"][:55], i["datasource"],
i.get("series", i.get("lines", i.get("traces", i.get("error"))))))
print(json.dumps({k: report[k] for k in ("dashboard", "datasource_health", "query_errors",
"empty_required_panels", "pass")}, ensure_ascii=False))
if args.output:
Path(args.output).write_text(json.dumps(report, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
return 0 if report["pass"] else 1
if __name__ == "__main__":
sys.exit(main())