Files
mtusi2026lab6/student-tests/obs.py
T

178 lines
8.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.
"""Доступ к сохранённым наблюдениям через Grafana API (stdlib): Prometheus, Loki, Tempo — через
datasource proxy, т. е. ровно тем путём, которым смотрит человек в Grafana (заодно проверяется provisioning).
Пароль admin читается из secrets/grafana_admin_password (или GRAFANA_PASSWORD_FILE) и нигде не печатается.
"""
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_URL = os.environ.get("GRAFANA_URL", "http://127.0.0.1:3000").rstrip("/")
PASSWORD_FILE = os.environ.get("GRAFANA_PASSWORD_FILE", str(ROOT / "secrets" / "grafana_admin_password"))
class ObsError(Exception):
pass
class Grafana:
def __init__(self, url=GRAFANA_URL, user="admin", password_file=PASSWORD_FILE, timeout=20):
self.url = url
pw = Path(password_file).read_text(encoding="utf-8").strip()
self.auth = "Basic " + base64.b64encode(("%s:%s" % (user, pw)).encode()).decode()
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
self.timeout = timeout
def request(self, method, path, params=None, body=None, raw=False):
url = self.url + path + ("?" + urllib.parse.urlencode(params, doseq=True) if params else "")
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method, headers={
"Authorization": self.auth, "Accept": "application/json",
**({"Content-Type": "application/json"} if data else {})})
try:
with self.opener.open(req, timeout=self.timeout) as r:
payload = r.read()
except urllib.error.HTTPError as e:
payload = e.read()
if e.code == 404 and raw:
return None
raise ObsError("%s %s -> HTTP %d: %s" % (method, path.split("?")[0], e.code, payload[:300].decode(errors="replace"))) from None
except (urllib.error.URLError, OSError) as e:
raise ObsError("%s %s: %s" % (method, path, type(e).__name__)) from None
return json.loads(payload) if payload else None
def get(self, path, params=None, **kw):
return self.request("GET", path, params=params, **kw)
# ------------------------------------------------------------------ Prometheus
def prom(self, expr, at=None):
params = {"query": expr}
if at is not None:
params["time"] = "%.3f" % at
d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/query", params)
if d.get("status") != "success":
raise ObsError("prometheus: %s" % d)
return d["data"]["result"]
def prom_value(self, expr, default=None, at=None):
res = self.prom(expr, at)
if not res:
return default
return float(res[0]["value"][1])
def prom_range(self, expr, start, end, step=5):
d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/query_range",
{"query": expr, "start": "%.3f" % start, "end": "%.3f" % end, "step": step})
return d["data"]["result"]
def series(self, match, since=600):
now = time.time()
d = self.get("/api/datasources/proxy/uid/prometheus/api/v1/series",
{"match[]": match, "start": "%.0f" % (now - since), "end": "%.0f" % now})
return d["data"]
def alerts(self):
return self.get("/api/datasources/proxy/uid/prometheus/api/v1/alerts")["data"]["alerts"]
def rules(self):
return self.get("/api/datasources/proxy/uid/prometheus/api/v1/rules")["data"]["groups"]
# ------------------------------------------------------------------ Loki
def loki(self, query, since=900, limit=200, start=None, end=None):
"""Список записей: dict(stream labels + structured metadata) + 'line' + 'ts' (секунды)."""
end = end or time.time()
start = start or end - since
d = self.get("/api/datasources/proxy/uid/loki/loki/api/v1/query_range",
{"query": query, "limit": limit, "start": "%d" % (start * 1e9), "end": "%d" % (end * 1e9),
"direction": "backward"})
out = []
for stream in d["data"]["result"]:
for ts, line, *rest in stream["values"]:
rec = dict(stream["stream"])
if rest and isinstance(rest[0], dict):
rec.update(rest[0].get("structuredMetadata", {}))
rec["line"], rec["ts"] = line, int(ts) / 1e9
out.append(rec)
return sorted(out, key=lambda r: r["ts"])
def loki_metric(self, query, at=None):
d = self.get("/api/datasources/proxy/uid/loki/loki/api/v1/query",
{"query": query, **({"time": "%d" % (at * 1e9)} if at else {})})
return d["data"]["result"]
# ------------------------------------------------------------------ Tempo
def trace(self, trace_id):
"""Spans trace (плоский список) или None, если Tempo его не нашёл."""
d = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id, raw=True)
if d is None:
return None
spans = []
for b in d.get("batches", d.get("resourceSpans", [])):
res = {a["key"]: _val(a["value"]) for a in b["resource"].get("attributes", [])}
for ss in b.get("scopeSpans", b.get("instrumentationLibrarySpans", [])):
for s in ss.get("spans", []):
spans.append({
"trace_id": _hex(s["traceId"]), "span_id": _hex(s["spanId"]),
"parent": _hex(s.get("parentSpanId", "")), "name": s["name"],
"kind": s.get("kind", "").replace("SPAN_KIND_", ""), "service": res.get("service.name"),
"instance": res.get("service.instance.id"),
"attrs": {a["key"]: _val(a["value"]) for a in s.get("attributes", [])},
"links": [_hex(l["spanId"]) for l in s.get("links", [])],
"status": s.get("status", {}).get("code", "").replace("STATUS_CODE_", ""),
"start": int(s["startTimeUnixNano"]) / 1e9, "end": int(s["endTimeUnixNano"]) / 1e9,
"raw": s})
return spans
def search(self, traceql, since=1800, limit=50):
now = time.time()
d = self.get("/api/datasources/proxy/uid/tempo/api/search",
{"q": traceql, "start": "%d" % (now - since), "end": "%d" % (now + 60), "limit": limit,
"spss": 50})
return d.get("traces", [])
def trace_raw_text(self, trace_id):
d = self.get("/api/datasources/proxy/uid/tempo/api/traces/" + trace_id, raw=True)
return json.dumps(d, ensure_ascii=False) if d else ""
# ------------------------------------------------------------------ Grafana
def ds_query(self, target, ds, since=900):
now = int(time.time() * 1000)
q = dict(target, refId=target.get("refId", "A"), datasource=ds, intervalMs=10000, maxDataPoints=200)
return self.request("POST", "/api/ds/query", body={"queries": [q], "from": str(now - since * 1000), "to": str(now)})
def _val(v):
for k in ("stringValue", "intValue", "doubleValue", "boolValue"):
if k in v:
return int(v[k]) if k == "intValue" else v[k]
return v
def _hex(b64_or_hex):
"""Tempo отдаёт ID в base64 (protobuf JSON) — приводим к hex, как в логах."""
if not b64_or_hex:
return ""
if all(c in "0123456789abcdef" for c in b64_or_hex) and len(b64_or_hex) in (16, 32):
return b64_or_hex
return base64.b64decode(b64_or_hex).hex()
def wait_for(probe, timeout=60, interval=1.0, what="condition"):
deadline = time.monotonic() + timeout
last_exc = None
while time.monotonic() < deadline:
try:
v = probe()
if v:
return v
except ObsError as e:
last_exc = e
time.sleep(interval)
raise ObsError("%s not observed in %ss%s" % (what, timeout, (" (%s)" % last_exc) if last_exc else ""))