forked from mtusi2026/mtusi2026lab7
Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)
This commit is contained in:
+213
@@ -0,0 +1,213 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read the stored observations (Prometheus, Loki, Tempo) through Grafana's datasource proxy.
|
||||
|
||||
Only Grafana is published (127.0.0.1:3000); the stores stay on the internal network. The admin
|
||||
password comes from secrets/grafana_admin_password and is never printed.
|
||||
|
||||
python scripts/obs.py promql 'sum(rate(http_server_request_duration_seconds_count[1m]))'
|
||||
python scripts/obs.py alerts # Prometheus alerts: state, since
|
||||
python scripts/obs.py trace <trace_id> # span tree of one trace (Tempo)
|
||||
python scripts/obs.py logs <trace_id> # log records of one trace (Loki)
|
||||
python scripts/obs.py search '{ span.messenger.job.outcome = "retry" }' # TraceQL
|
||||
Used as a library by student-tests/test_observability.py and bench/*.py.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
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:3000").rstrip("/")
|
||||
|
||||
|
||||
def _auth() -> str:
|
||||
password = os.environ.get("GRAFANA_PASSWORD") or (ROOT / "secrets" / "grafana_admin_password").read_text(
|
||||
encoding="utf-8").strip()
|
||||
return "Basic " + base64.b64encode(f"admin:{password}".encode()).decode()
|
||||
|
||||
|
||||
def get(uid: str, path: str, params: dict | None = None, timeout: float = 30) -> dict:
|
||||
url = f"{GRAFANA}/api/datasources/proxy/uid/{uid}/{path.lstrip('/')}"
|
||||
if params:
|
||||
url += "?" + urllib.parse.urlencode(params)
|
||||
request = urllib.request.Request(url, headers={"Authorization": _auth(), "Accept": "application/json"})
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- Prometheus
|
||||
def promql(expr: str, at: float | None = None) -> list[dict]:
|
||||
params = {"query": expr}
|
||||
if at is not None:
|
||||
params["time"] = f"{at:.3f}"
|
||||
return get("prometheus", "api/v1/query", params)["data"]["result"]
|
||||
|
||||
|
||||
def scalar(expr: str, default: float | None = None) -> float | None:
|
||||
"""Single value of an instant query (first series), or `default` when there is none."""
|
||||
result = promql(expr)
|
||||
if not result:
|
||||
return default
|
||||
value = float(result[0]["value"][1])
|
||||
return default if value != value else value # NaN -> default
|
||||
|
||||
|
||||
def series(expr: str, start: float, end: float, step: float = 5) -> list[dict]:
|
||||
return get("prometheus", "api/v1/query_range",
|
||||
{"query": expr, "start": f"{start:.3f}", "end": f"{end:.3f}", "step": str(step)})["data"]["result"]
|
||||
|
||||
|
||||
def alerts() -> list[dict]:
|
||||
"""Active alerts (pending/firing) of Prometheus: [{name, state, activeAt, value, labels}]."""
|
||||
data = get("prometheus", "api/v1/alerts")["data"]["alerts"]
|
||||
return [{"name": a["labels"].get("alertname"), "state": a["state"], "activeAt": a.get("activeAt"),
|
||||
"value": a.get("value"), "labels": a["labels"]} for a in data]
|
||||
|
||||
|
||||
def alert_state(name: str) -> str:
|
||||
"""inactive | pending | firing (highest of the alert's series)."""
|
||||
states = {a["state"] for a in alerts() if a["name"] == name}
|
||||
return "firing" if "firing" in states else "pending" if "pending" in states else "inactive"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- Tempo
|
||||
def trace_spans(trace_id: str) -> list[dict]:
|
||||
"""Flat list of spans: {service, name, kind, span_id, parent_id, start, end, duration_ms, status, attrs}."""
|
||||
data = get("tempo", f"api/v2/traces/{trace_id}")
|
||||
spans = []
|
||||
for rs in data.get("trace", data).get("resourceSpans", []):
|
||||
rattrs = _attrs(rs.get("resource", {}).get("attributes", []))
|
||||
for ss in rs.get("scopeSpans", []):
|
||||
for sp in ss.get("spans", []):
|
||||
start, end = int(sp["startTimeUnixNano"]), int(sp["endTimeUnixNano"])
|
||||
spans.append({
|
||||
"service": rattrs.get("service.name"), "instance": rattrs.get("service.instance.id"),
|
||||
"name": sp["name"], "kind": sp.get("kind", "").replace("SPAN_KIND_", ""),
|
||||
"span_id": _hex(sp.get("spanId", "")), "parent_id": _hex(sp.get("parentSpanId", "")),
|
||||
"start": start, "end": end, "duration_ms": (end - start) / 1e6,
|
||||
"status": sp.get("status", {}).get("code", "STATUS_CODE_UNSET").replace("STATUS_CODE_", ""),
|
||||
"attrs": _attrs(sp.get("attributes", [])),
|
||||
})
|
||||
return sorted(spans, key=lambda s: s["start"])
|
||||
|
||||
|
||||
def wait_trace(trace_id: str, predicate, timeout: float = 60) -> list[dict]:
|
||||
"""Poll Tempo until predicate(spans) is true (spans arrive within a few seconds)."""
|
||||
deadline = time.monotonic() + timeout
|
||||
spans: list[dict] = []
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
spans = trace_spans(trace_id)
|
||||
if spans and predicate(spans):
|
||||
return spans
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 404:
|
||||
raise
|
||||
time.sleep(2)
|
||||
raise AssertionError(f"trace {trace_id}: condition not met within {timeout} s; {len(spans)} spans")
|
||||
|
||||
|
||||
def search(traceql: str, minutes: int = 60, limit: int = 20) -> list[dict]:
|
||||
end = int(time.time())
|
||||
return get("tempo", "api/search", {"q": traceql, "start": end - minutes * 60, "end": end,
|
||||
"limit": limit}).get("traces", [])
|
||||
|
||||
|
||||
def _hex(value: str) -> str:
|
||||
if not value:
|
||||
return ""
|
||||
if all(c in "0123456789abcdef" for c in value.lower()) and len(value) in (16, 32):
|
||||
return value.lower()
|
||||
return base64.b64decode(value).hex() # OTLP JSON may carry ids base64-encoded
|
||||
|
||||
|
||||
def _attrs(items: list) -> dict:
|
||||
out = {}
|
||||
for item in items:
|
||||
value = item.get("value", {})
|
||||
out[item["key"]] = next(iter(value.values())) if value else None
|
||||
return out
|
||||
|
||||
|
||||
def tree(spans: list[dict]) -> str:
|
||||
"""Indented text tree (parent -> children), times relative to the first span."""
|
||||
by_parent: dict[str, list[dict]] = {}
|
||||
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 = spans[0]["start"] if spans else 0
|
||||
lines: list[str] = []
|
||||
|
||||
def walk(parent: str, depth: int) -> None:
|
||||
for s in by_parent.get(parent, []):
|
||||
extra = {k: v for k, v in s["attrs"].items() if k in (
|
||||
"http.route", "http.response.status_code", "messenger.job.attempt", "messenger.job.outcome",
|
||||
"messenger.job.error_code", "db.client.connection.wait_time_ms", "error.type")}
|
||||
lines.append(f"{' ' * depth}+{(s['start'] - t0) / 1e6:9.1f} ms {s['duration_ms']:8.1f} ms "
|
||||
f"[{s['service']}] {s['kind']:<8} {s['name']} {s['status'] if s['status'] != 'UNSET' else ''} "
|
||||
f"{json.dumps(extra, ensure_ascii=False) if extra else ''}".rstrip())
|
||||
walk(s["span_id"], depth + 1)
|
||||
walk("", 0)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- Loki
|
||||
def logs(query: str, minutes: int = 60, limit: int = 200) -> list[dict]:
|
||||
"""Records of a LogQL query: {ts, service, line, metadata} (oldest first)."""
|
||||
end = time.time_ns()
|
||||
data = get("loki", "loki/api/v1/query_range", {"query": query, "start": end - minutes * 60 * 10**9, "end": end,
|
||||
"limit": limit, "direction": "backward"})
|
||||
out = []
|
||||
for stream in data["data"]["result"]:
|
||||
labels = stream["stream"]
|
||||
for value in stream["values"]:
|
||||
ts, line = value[0], value[1]
|
||||
meta = value[2].get("structuredMetadata", {}) if len(value) > 2 and isinstance(value[2], dict) else {}
|
||||
out.append({"ts": int(ts), "service": labels.get("service_name"), "line": line,
|
||||
"metadata": {**{k: v for k, v in labels.items()}, **meta}})
|
||||
return sorted(out, key=lambda r: r["ts"])
|
||||
|
||||
|
||||
def trace_logs(trace_id: str, minutes: int = 60) -> list[dict]:
|
||||
return logs(f'{{service_name=~"messenger-.+"}} | trace_id="{trace_id}"', minutes)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------- CLI
|
||||
def main(argv: list[str]) -> int:
|
||||
if len(argv) < 2:
|
||||
print(__doc__)
|
||||
return 2
|
||||
cmd, args = argv[1], argv[2:]
|
||||
if cmd == "promql":
|
||||
for s in promql(args[0]):
|
||||
print(json.dumps(s["metric"], ensure_ascii=False), s["value"][1])
|
||||
elif cmd == "alerts":
|
||||
for a in alerts():
|
||||
print(f"{a['name']:<32} {a['state']:<8} since {a['activeAt']} value={a['value']}")
|
||||
elif cmd == "trace":
|
||||
print(tree(trace_spans(args[0])))
|
||||
elif cmd == "logs":
|
||||
for r in trace_logs(args[0]):
|
||||
meta = r["metadata"]
|
||||
print(f"{r['service']:<17} {meta.get('detected_level', meta.get('severity_text', '')):<6} {r['line']:<22} "
|
||||
f"span={meta.get('span_id', '')} " + " ".join(
|
||||
f"{k}={meta[k]}" for k in ("request_id", "route", "status", "job_id", "outcome", "attempt")
|
||||
if k in meta))
|
||||
elif cmd == "search":
|
||||
for t in search(args[0]):
|
||||
print(t.get("traceID"), t.get("rootServiceName"), t.get("rootTraceName"), t.get("durationMs"), "ms")
|
||||
else:
|
||||
print(__doc__)
|
||||
return 2
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main(sys.argv))
|
||||
Reference in New Issue
Block a user