forked from mtusi2026/mtusi2026lab6
Перенесена реализация 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)
158 lines
6.4 KiB
Python
158 lines
6.4 KiB
Python
"""Помощники lab6: запросы к Prometheus / Loki / Tempo ЧЕРЕЗ Grafana (datasource proxy).
|
|
|
|
Так проверка заодно подтверждает, что Grafana видит все три хранилища по provisioning.
|
|
Пароль admin Grafana читается из secrets/grafana_admin_password и нигде не печатается.
|
|
Только стандартная библиотека.
|
|
"""
|
|
import base64
|
|
import json
|
|
import os
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
GRAFANA = os.environ.get("GRAFANA_URL", "http://127.0.0.1:%s" % os.environ.get("GRAFANA_PORT", "3000"))
|
|
|
|
|
|
def _auth_header():
|
|
password = (ROOT / "secrets/grafana_admin_password").read_text(encoding="utf-8").strip()
|
|
return "Basic " + base64.b64encode(("admin:" + password).encode()).decode()
|
|
|
|
|
|
def grafana(path, params=None, timeout=20, accept="application/json"):
|
|
url = GRAFANA + path + ("?" + urllib.parse.urlencode(params, doseq=True) if params else "")
|
|
req = urllib.request.Request(url, headers={"Authorization": _auth_header(), "Accept": accept})
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
return json.loads(resp.read() or b"null")
|
|
except urllib.error.HTTPError as exc:
|
|
if exc.code == 404:
|
|
return None
|
|
raise RuntimeError("grafana %s -> HTTP %d: %s" % (path, exc.code, exc.read()[:300]))
|
|
|
|
|
|
# ------------------------------------------------------------------ Prometheus
|
|
def prom(path, **params):
|
|
return grafana("/api/datasources/proxy/uid/prometheus/api/v1/" + path, params)
|
|
|
|
|
|
def prom_query(expr, at=None):
|
|
params = {"query": expr}
|
|
if at is not None:
|
|
params["time"] = "%.3f" % at
|
|
data = prom("query", **params)
|
|
return data["data"]["result"]
|
|
|
|
|
|
def prom_value(expr, at=None, default=None):
|
|
res = prom_query(expr, at)
|
|
if not res:
|
|
return default
|
|
return float(res[0]["value"][1])
|
|
|
|
|
|
def prom_range(expr, start, end, step=15):
|
|
data = prom("query_range", query=expr, start="%.3f" % start, end="%.3f" % end, step=str(step))
|
|
return data["data"]["result"]
|
|
|
|
|
|
def prom_alerts():
|
|
return prom("alerts")["data"]["alerts"]
|
|
|
|
|
|
# ------------------------------------------------------------------ Loki
|
|
def loki_query(query, start, end, limit=100, direction="forward"):
|
|
data = grafana("/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
|
|
{"query": query, "start": str(int(start * 1e9)), "end": str(int(end * 1e9)),
|
|
"limit": str(limit), "direction": direction})
|
|
out = []
|
|
for stream in data["data"]["result"]:
|
|
for ts, line, *meta in stream["values"]:
|
|
item = {"ts": int(ts) / 1e9, "line": line, "labels": stream["stream"]}
|
|
if meta:
|
|
item["metadata"] = meta[0]
|
|
out.append(item)
|
|
out.sort(key=lambda x: x["ts"])
|
|
return out
|
|
|
|
|
|
# ------------------------------------------------------------------ Tempo
|
|
def tempo_trace(trace_id):
|
|
"""Трасса в формате OTLP JSON (batches/resourceSpans) или None, если ещё не доступна."""
|
|
return grafana("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id)
|
|
|
|
|
|
def tempo_search(traceql, start, end, limit=20):
|
|
return grafana("/api/datasources/proxy/uid/tempo/api/search",
|
|
{"q": traceql, "start": str(int(start)), "end": str(int(end)), "limit": str(limit)})
|
|
|
|
|
|
def _attr_value(v):
|
|
for key in ("stringValue", "intValue", "boolValue", "doubleValue"):
|
|
if key in v:
|
|
return v[key]
|
|
return v
|
|
|
|
|
|
def _hex(b64_or_hex):
|
|
if not b64_or_hex:
|
|
return ""
|
|
if len(b64_or_hex) in (16, 32) and all(c in "0123456789abcdef" for c in b64_or_hex):
|
|
return b64_or_hex
|
|
return base64.b64decode(b64_or_hex).hex()
|
|
|
|
|
|
def flatten_spans(trace):
|
|
"""[{service, name, kind, span_id, parent_id, start, end, duration_ms, status, attrs}]"""
|
|
spans = []
|
|
batches = (trace or {}).get("batches") or (trace or {}).get("resourceSpans") or []
|
|
for batch in batches:
|
|
res = {a["key"]: _attr_value(a["value"]) for a in batch.get("resource", {}).get("attributes", [])}
|
|
for scope in batch.get("scopeSpans") or batch.get("instrumentationLibrarySpans") or []:
|
|
for s in scope.get("spans", []):
|
|
start, end = int(s["startTimeUnixNano"]), int(s["endTimeUnixNano"])
|
|
spans.append({
|
|
"service": res.get("service.name"), "instance": res.get("service.instance.id"),
|
|
"name": s["name"], "kind": s.get("kind", ""), "span_id": _hex(s.get("spanId")),
|
|
"parent_id": _hex(s.get("parentSpanId")), "trace_id": _hex(s.get("traceId")),
|
|
"start": start / 1e9, "end": end / 1e9, "duration_ms": round((end - start) / 1e6, 3),
|
|
"status": (s.get("status") or {}).get("code", "STATUS_CODE_UNSET"),
|
|
"attrs": {a["key"]: _attr_value(a["value"]) for a in s.get("attributes", [])}})
|
|
spans.sort(key=lambda x: x["start"])
|
|
return spans
|
|
|
|
|
|
def wait_trace(trace_id, predicate=None, timeout=60, interval=2):
|
|
"""Ждём, пока трасса появится в Tempo (и удовлетворит predicate(spans))."""
|
|
deadline = time.monotonic() + timeout
|
|
spans = []
|
|
while time.monotonic() < deadline:
|
|
tr = tempo_trace(trace_id)
|
|
spans = flatten_spans(tr) if tr else []
|
|
if spans and (predicate is None or predicate(spans)):
|
|
return spans
|
|
time.sleep(interval)
|
|
return spans
|
|
|
|
|
|
def tree(spans):
|
|
"""Текстовое дерево трассы (для evidence): отступ = глубина, длительность, сервис."""
|
|
by_parent = {}
|
|
ids = {s["span_id"] for s in spans}
|
|
for s in spans:
|
|
by_parent.setdefault(s["parent_id"] if s["parent_id"] in ids else "", []).append(s)
|
|
t0 = min((s["start"] for s in spans), default=0)
|
|
lines = []
|
|
|
|
def walk(pid, depth):
|
|
for s in sorted(by_parent.get(pid, []), key=lambda x: x["start"]):
|
|
lines.append("%s%-44s %-17s +%8.1fms %9.1fms %s%s" % (
|
|
" " * depth, s["name"][:44], s["service"] or "", (s["start"] - t0) * 1000, s["duration_ms"],
|
|
s["kind"].replace("SPAN_KIND_", ""), " ERROR" if s["status"] == "STATUS_CODE_ERROR" else ""))
|
|
walk(s["span_id"], depth + 1)
|
|
walk("", 0)
|
|
return lines
|