forked from mtusi2026/mtusi2026lab7
99 lines
5.8 KiB
Python
99 lines
5.8 KiB
Python
"""lab6, уровни 3–4: dashboard и источники данных импортируются из Git, а запросы панелей работают.
|
||
|
||
make dashboard-check (= python student-tests/check_dashboard.py)
|
||
|
||
1. Grafana (https://127.0.0.1:3000): здорова; источники prometheus, loki, tempo созданы provisioning
|
||
(а не руками) и проходят проверку подключения; dashboard messenger-lab6 импортирован из
|
||
infra/grafana/dashboards/messenger.json (тот же набор панелей), помечен как provisioned.
|
||
2. Каждый запрос каждой панели из JSON выполняется в своём хранилище без ошибок: PromQL — в
|
||
Prometheus, LogQL — в Loki, TraceQL — в Tempo. Пустой результат разрешён только у панелей,
|
||
которые показывают отказы (например, потери Collector при здоровом стенде), — они перечислены.
|
||
3. Alert rules загружены в Prometheus (HighErrorRate, QueueLagHigh, TelemetryExportFailing) и здоровы.
|
||
Выводится таблица «панель — единица — запрос» для REPORT.md.
|
||
GRAFANA_URL=none — пропустить шаг 1 (например, если проверяются только запросы).
|
||
"""
|
||
import json
|
||
import os
|
||
|
||
import obs
|
||
from helpers import ROOT, check, run
|
||
|
||
DASHBOARD = ROOT / "infra" / "grafana" / "dashboards" / "messenger.json"
|
||
# Эти запросы при здоровом стенде законно пусты: отказов нет.
|
||
MAY_BE_EMPTY = ("send_failed", "ALERTS", "outcome=\"ready\"", "time_to_ready", "4..", "5..")
|
||
|
||
|
||
def panels(dashboard):
|
||
for panel in dashboard["panels"]:
|
||
if panel.get("type") == "row":
|
||
continue
|
||
yield panel
|
||
|
||
|
||
def grafana_checks(dashboard):
|
||
health = obs.get_json(obs.GRAFANA_URL + "/api/health")
|
||
check(health.get("database") == "ok", f"grafana health: {health}")
|
||
sources = {ds["uid"]: ds for ds in obs.grafana("/api/datasources")}
|
||
for uid, kind in (("prometheus", "prometheus"), ("loki", "loki"), ("tempo", "tempo")):
|
||
check(uid in sources and sources[uid]["type"] == kind, f"datasource {uid} is not provisioned")
|
||
check(sources[uid].get("readOnly") is True, f"datasource {uid} must come from provisioning (readOnly)")
|
||
if uid == "tempo":
|
||
# Плагин Tempo в Grafana 12 не реализует /health через API (404 plugin.notImplemented):
|
||
# проверяем подключение настоящим запросом к Tempo через прокси Grafana.
|
||
check(isinstance(obs.grafana("/api/datasources/proxy/uid/tempo/api/search?limit=1"), dict),
|
||
"tempo datasource: search through Grafana failed")
|
||
continue
|
||
result = obs.grafana(f"/api/datasources/uid/{uid}/health")
|
||
check(result.get("status") == "OK", f"datasource {uid} health: {result}")
|
||
print("1. Grafana " + health.get("version", "?") + ": datasources prometheus, loki, tempo — provisioned "
|
||
"(readOnly); prometheus, loki health OK; tempo answers a search through Grafana")
|
||
imported = obs.grafana("/api/dashboards/uid/" + dashboard["uid"])
|
||
check(imported["meta"].get("provisioned") is True, "dashboard must be provisioned from a file")
|
||
got = sorted(p["title"] for p in imported["dashboard"]["panels"])
|
||
want = sorted(p["title"] for p in dashboard["panels"])
|
||
check(got == want, "imported dashboard differs from infra/grafana/dashboards/messenger.json")
|
||
print(f" dashboard '{imported['dashboard']['title']}' provisioned from {imported['meta'].get('provisionedExternalId')}, "
|
||
f"{len(got)} panels (same as the JSON in Git)")
|
||
|
||
|
||
def main():
|
||
dashboard = json.loads(DASHBOARD.read_text(encoding="utf-8"))
|
||
if os.environ.get("GRAFANA_URL", "") != "none":
|
||
grafana_checks(dashboard)
|
||
else:
|
||
print("1. Grafana checks skipped (GRAFANA_URL=none)")
|
||
|
||
print("2. every panel query against its store:")
|
||
print(f" {'panel':<46} {'unit':<11} {'series':>6} query")
|
||
empty = []
|
||
for panel in panels(dashboard):
|
||
unit = panel.get("fieldConfig", {}).get("defaults", {}).get("unit", "-")
|
||
for target in panel["targets"]:
|
||
kind = target["datasource"]["uid"]
|
||
if kind == "prometheus":
|
||
rows = obs.prom(target["expr"])
|
||
query = target["expr"]
|
||
elif kind == "loki":
|
||
rows = obs.loki(target["expr"], minutes=60, limit=20)
|
||
query = target["expr"]
|
||
else:
|
||
rows = obs.tempo_search(target["query"], limit=5)
|
||
query = target["query"]
|
||
if not rows:
|
||
empty.append((panel["title"], query))
|
||
print(f" {panel['title'][:46]:<46} {unit:<11} {len(rows):>6} {' '.join(query.split())[:150]}")
|
||
unexpected = [(title, q) for title, q in empty if not any(m in q for m in MAY_BE_EMPTY)]
|
||
check(not unexpected, f"queries without data: {unexpected}")
|
||
print(f" all queries succeeded; empty (allowed: failure-only panels): {len(empty)}")
|
||
|
||
names = {r["name"]: r for r in obs.rules()}
|
||
for alert in ("HighErrorRate", "QueueLagHigh", "TelemetryExportFailing"):
|
||
check(alert in names and names[alert]["health"] == "ok", f"alert rule {alert} missing or unhealthy")
|
||
print("3. alert rules loaded and healthy: " + ", ".join(f"{n} ({names[n]['state']}, for {names[n].get('duration', 0)} s)"
|
||
for n in ("HighErrorRate", "QueueLagHigh", "TelemetryExportFailing")))
|
||
print("PASS: provisioning from Git, every panel query returns data from Prometheus/Loki/Tempo, alert rules loaded")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
run(main)
|