forked from mtusi2026/mtusi2026lab6
118 lines
4.8 KiB
Python
118 lines
4.8 KiB
Python
#!/usr/bin/env python3
|
||
"""Проверяет сквозной контур наблюдаемости ЛР6 через HTTP API Grafana."""
|
||
import argparse
|
||
import base64
|
||
import json
|
||
import os
|
||
import time
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
|
||
|
||
class Grafana:
|
||
"""Минимальный HTTP-клиент Grafana с Basic-аутентификацией."""
|
||
|
||
def __init__(self, base_url: str, user: str, password: str):
|
||
"""Сохраняет адрес Grafana и формирует заголовок авторизации."""
|
||
|
||
self.base_url = base_url.rstrip("/")
|
||
token = base64.b64encode(f"{user}:{password}".encode()).decode()
|
||
self.headers = {"Authorization": f"Basic {token}"}
|
||
|
||
def get(self, path: str, params: dict[str, str] | None = None):
|
||
"""Выполняет GET-запрос к Grafana и возвращает декодированный JSON."""
|
||
|
||
if params:
|
||
path += "?" + urllib.parse.urlencode(params)
|
||
request = urllib.request.Request(self.base_url + path, headers=self.headers)
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=10) as response:
|
||
return json.load(response)
|
||
except urllib.error.HTTPError as error:
|
||
body = error.read().decode(errors="replace")
|
||
raise RuntimeError(f"Grafana GET {path}: HTTP {error.code}: {body[:300]}") from error
|
||
|
||
|
||
def check(condition: bool, message: str):
|
||
"""Завершает проверку понятной ошибкой, если условие не выполнено."""
|
||
|
||
if not condition:
|
||
raise RuntimeError(message)
|
||
|
||
|
||
def trace_services(payload) -> set[str]:
|
||
"""Извлекает множество значений service.name из ответа Tempo с трассой."""
|
||
|
||
result: set[str] = set()
|
||
for batch in payload.get("batches", []):
|
||
resource = batch.get("resource", {})
|
||
attrs = resource.get("attributes", [])
|
||
for attr in attrs:
|
||
if attr.get("key") == "service.name":
|
||
result.add(attr.get("value", {}).get("stringValue", ""))
|
||
return result
|
||
|
||
|
||
def main():
|
||
"""Проверяет dashboard, alerts, метрики, логи и cross-process trace."""
|
||
|
||
parser = argparse.ArgumentParser()
|
||
parser.add_argument("--grafana-url", default="http://localhost:3000")
|
||
parser.add_argument("--user", default=os.getenv("GRAFANA_ADMIN_USER", "admin"))
|
||
parser.add_argument("--password", default=os.getenv("GRAFANA_ADMIN_PASSWORD"), required=os.getenv("GRAFANA_ADMIN_PASSWORD") is None)
|
||
args = parser.parse_args()
|
||
grafana = Grafana(args.grafana_url, args.user, args.password)
|
||
|
||
health = grafana.get("/api/health")
|
||
check(health.get("database") == "ok", "Grafana database is not ready")
|
||
dashboard = grafana.get("/api/dashboards/uid/messenger-observability")
|
||
check(len(dashboard["dashboard"].get("panels", [])) >= 12, "dashboard panels are missing")
|
||
rules = grafana.get("/api/v1/provisioning/alert-rules")
|
||
titles = {rule.get("title") for rule in rules}
|
||
check({"ApiHighServerErrorRate", "QueueOldestJobGrowing"} <= titles, "alert rules are missing")
|
||
|
||
prom = grafana.get(
|
||
"/api/datasources/proxy/uid/prometheus/api/v1/query",
|
||
{"query": 'sum(http_server_request_count_total{service_name="messenger-api"})'},
|
||
)
|
||
check(prom.get("status") == "success" and prom["data"]["result"], "API metric is absent")
|
||
|
||
now_ns = time.time_ns()
|
||
loki = grafana.get(
|
||
"/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
|
||
{
|
||
"query": (
|
||
'{service_name="messenger-api"} | json '
|
||
'| event="attachment.accepted" | line_format "{{.trace_id}}"'
|
||
),
|
||
"start": str(now_ns - 3_600_000_000_000),
|
||
"end": str(now_ns),
|
||
"direction": "backward",
|
||
"limit": "20",
|
||
},
|
||
)
|
||
streams = loki.get("data", {}).get("result", [])
|
||
check(streams, "correlated attachment.accepted log is absent; run make test first")
|
||
entry = streams[0]["values"][0]
|
||
metadata = entry[2] if len(entry) > 2 else {}
|
||
trace_id = metadata.get("trace_id")
|
||
if not trace_id and len(entry[1]) == 32:
|
||
trace_id = entry[1]
|
||
if not trace_id:
|
||
try:
|
||
trace_id = json.loads(entry[1]).get("trace_id")
|
||
except json.JSONDecodeError:
|
||
trace_id = None
|
||
check(bool(trace_id), f"Loki log has no trace_id; metadata keys: {sorted(metadata)}")
|
||
|
||
trace = grafana.get(f"/api/datasources/proxy/uid/tempo/api/traces/{trace_id}")
|
||
services = trace_services(trace)
|
||
expected = {"messenger-api", "messenger-publisher", "messenger-worker"}
|
||
check(expected <= services, f"cross-process trace is incomplete: {sorted(services)}")
|
||
print("PASS: dashboard, alerts, metrics, correlated logs and cross-process trace")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|