135 lines
5.5 KiB
Python
135 lines
5.5 KiB
Python
#!/usr/bin/env python3
|
||
"""Проверяет метрики, логи и трассы API и worker через Grafana."""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import base64
|
||
import json
|
||
import ssl
|
||
from pathlib import Path
|
||
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, ca_file: Path):
|
||
"""Сохраняет адрес Grafana и формирует заголовок авторизации."""
|
||
|
||
self.base_url = base_url.rstrip("/")
|
||
self.context = ssl.create_default_context(cafile=str(ca_file))
|
||
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, context=self.context) 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 log_trace_ids(grafana: Grafana, service: str, event: str, since_ns: int) -> list[str]:
|
||
payload = grafana.get(
|
||
"/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
|
||
{
|
||
"query": (
|
||
f'{{service_name="{service}"}} | json | event="{event}" '
|
||
'| line_format "{{.trace_id}}"'
|
||
),
|
||
"start": str(since_ns),
|
||
"end": str(time.time_ns()),
|
||
"direction": "backward",
|
||
"limit": "100",
|
||
},
|
||
)
|
||
trace_ids = []
|
||
for stream in payload["data"]["result"]:
|
||
for entry in stream["values"]:
|
||
metadata = entry[2] if len(entry) > 2 else {}
|
||
trace_id = metadata.get("trace_id") or entry[1]
|
||
if len(trace_id) == 32 and all(char in "0123456789abcdef" for char in trace_id):
|
||
trace_ids.append(trace_id)
|
||
return trace_ids
|
||
|
||
|
||
def verify_signals(grafana: Grafana, since_ns: int) -> None:
|
||
for series, service in (
|
||
("http_server_request_count_total", "messenger-api"),
|
||
("http_server_request_duration_seconds_count", "messenger-api"),
|
||
("messenger_jobs_processed_total", "messenger-worker"),
|
||
("messenger_job_processing_duration_seconds_count", "messenger-worker"),
|
||
):
|
||
result = grafana.get(
|
||
"/api/datasources/proxy/uid/prometheus/api/v1/query",
|
||
{"query": f'sum({series}{{service_name="{service}"}}) > 0'},
|
||
)
|
||
check(result["data"]["result"], f"Metric is absent: {series}")
|
||
|
||
api_traces = log_trace_ids(grafana, "messenger-api", "attachment.accepted", since_ns)
|
||
worker_traces = set(log_trace_ids(grafana, "messenger-worker", "job.completed", since_ns))
|
||
trace_id = next((trace_id for trace_id in api_traces if trace_id in worker_traces), None)
|
||
check(trace_id, "Fresh matching API and worker logs are absent; run make test first")
|
||
trace_payload = grafana.get(f"/api/datasources/proxy/uid/tempo/api/traces/{trace_id}")
|
||
services = trace_services(trace_payload)
|
||
check({"messenger-api", "messenger-publisher", "messenger-worker"} <= services,
|
||
f"Cross-process trace is incomplete: {sorted(services)}")
|
||
|
||
|
||
def main() -> None:
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument("--grafana-url", default="https://grafana:3000")
|
||
parser.add_argument("--user", default="admin")
|
||
parser.add_argument("--password-file", required=True, type=Path)
|
||
parser.add_argument("--ca-file", required=True, type=Path)
|
||
args = parser.parse_args()
|
||
grafana = Grafana(args.grafana_url, args.user, args.password_file.read_text().strip(), args.ca_file)
|
||
check(grafana.get("/api/health").get("database") == "ok", "Grafana is not ready")
|
||
dashboard = grafana.get("/api/dashboards/uid/messenger-observability")
|
||
check(dashboard["dashboard"].get("panels"), "Dashboard panels are absent")
|
||
|
||
deadline = time.monotonic() + 45
|
||
since_ns = time.time_ns() - 300_000_000_000
|
||
while True:
|
||
try:
|
||
verify_signals(grafana, since_ns)
|
||
break
|
||
except RuntimeError:
|
||
if time.monotonic() >= deadline:
|
||
raise
|
||
time.sleep(2)
|
||
print("PASS: dashboard, API/worker metrics and logs, and correlated trace")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|