85 lines
2.1 KiB
Python
85 lines
2.1 KiB
Python
import json
|
|
import os
|
|
import time
|
|
from pathlib import Path
|
|
from urllib.parse import urlencode
|
|
from urllib.request import urlopen
|
|
|
|
from client import check
|
|
|
|
|
|
GRAFANA = os.getenv("GRAFANA_URL", "http://127.0.0.1:13006")
|
|
EVIDENCE = Path("evidence")
|
|
|
|
|
|
def fetch(path, **params):
|
|
suffix = "?" + urlencode(params) if params else ""
|
|
with urlopen(GRAFANA + path + suffix, timeout=8) as response:
|
|
return json.load(response)
|
|
|
|
|
|
def datasource(name, path, **params):
|
|
return fetch(f"/api/datasources/proxy/uid/{name}{path}", **params)
|
|
|
|
|
|
def prom(expression):
|
|
response = datasource("prometheus", "/api/v1/query", query=expression)
|
|
check(response["status"] == "success", "PromQL query failed")
|
|
return response["data"]["result"]
|
|
|
|
|
|
def value(expression, default=0.0):
|
|
values = prom(expression)
|
|
return float(values[0]["value"][1]) if values else default
|
|
|
|
|
|
def states():
|
|
return {
|
|
row["name"]: row["state"]
|
|
for row in datasource("prometheus", "/api/v1/rules")["data"]["groups"][0]["rules"]
|
|
}
|
|
|
|
|
|
def logs(query, since=None, limit=100):
|
|
result = datasource(
|
|
"loki",
|
|
"/loki/api/v1/query_range",
|
|
query=query,
|
|
start=int((since or time.time() - 180) * 1e9),
|
|
limit=limit,
|
|
)
|
|
return result["data"]["result"]
|
|
|
|
|
|
def spans(trace_id):
|
|
trace = datasource("tempo", "/api/traces/" + trace_id)
|
|
return [
|
|
dict(
|
|
span,
|
|
service=next(
|
|
a["value"]["stringValue"]
|
|
for a in batch["resource"]["attributes"]
|
|
if a["key"] == "service.name"
|
|
),
|
|
)
|
|
for batch in trace.get("batches", trace.get("resourceSpans", []))
|
|
for scope in batch["scopeSpans"]
|
|
for span in scope["spans"]
|
|
]
|
|
|
|
|
|
def save(name, data):
|
|
(EVIDENCE / name).write_text(
|
|
json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
|
)
|
|
|
|
|
|
def wait_until(probe, timeout, description):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
result = probe()
|
|
if result:
|
|
return result
|
|
time.sleep(1)
|
|
raise AssertionError(description)
|