213 lines
8.4 KiB
Python
213 lines
8.4 KiB
Python
"""Чтение хранилищ телеметрии стенда для профиля telemetry. Только stdlib.
|
|
|
|
Работает внутри контейнера генератора `vlad-bench-gen`, который
|
|
`bench/run.py` на время варианта с телеметрией подключает к сети
|
|
`vlad-bench_telemetry`: Prometheus, Loki и Tempo наружу не опубликованы.
|
|
Оркестратор копирует файл (`docker cp`), вызывает через `docker exec` и
|
|
читает одну строку JSON из stdout. Только чтение по HTTP: ни записи, ни
|
|
удаления в хранилищах.
|
|
|
|
Команды:
|
|
ready ждать готовности Collector (:8888), Prometheus, Loki и Tempo
|
|
snap счётчики приёма и потерь: собственные метрики Collector, Tempo,
|
|
Loki и Prometheus (текстовый формат /metrics), сумма по меткам
|
|
find по id запросов классов (`--input` JSON): запись доступа в Loki
|
|
(статус, длительность на сервере, trace_id), затем трасса этого
|
|
trace_id в Tempo — найдена ли, сколько span, есть ли consumer
|
|
span задания и его исход
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import re
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
COLLECTOR = "http://otel-collector:8888"
|
|
PROMETHEUS = "http://prometheus:9090"
|
|
LOKI = "http://loki:3100"
|
|
TEMPO = "http://tempo:3200"
|
|
# ряды, которые нужны профилю; сумма по всем меткам ряда
|
|
PREFIXES = {
|
|
"collector": ("otelcol_receiver_", "otelcol_exporter_", "otelcol_processor_"),
|
|
"tempo": ("tempo_distributor_", "tempo_discarded_"),
|
|
"loki": ("loki_distributor_", "loki_discarded_"),
|
|
"prometheus": ("prometheus_tsdb_head_",),
|
|
}
|
|
SOURCES = {
|
|
"collector": f"{COLLECTOR}/metrics",
|
|
"tempo": f"{TEMPO}/metrics",
|
|
"loki": f"{LOKI}/metrics",
|
|
"prometheus": f"{PROMETHEUS}/metrics",
|
|
}
|
|
ACCESS = re.compile(r"-> (\d{3}) \(([\d.]+) ms\)")
|
|
LOKI_BATCH = 25
|
|
TEMPO_THREADS = 3
|
|
|
|
|
|
def fetch(url: str, timeout: float = 10.0) -> tuple[int, bytes]:
|
|
try:
|
|
with urllib.request.urlopen(url, timeout=timeout) as response: # noqa: S310
|
|
return response.status, response.read()
|
|
except urllib.error.HTTPError as exc:
|
|
return exc.code, b""
|
|
except (OSError, ValueError):
|
|
return 0, b""
|
|
|
|
|
|
def metric_sums(text: str, prefixes: tuple[str, ...]) -> dict[str, float]:
|
|
"""Сумма значений ряда по всем меткам: `name{…} 12` → name: 12."""
|
|
sums: dict[str, float] = {}
|
|
for line in text.splitlines():
|
|
if not line or line.startswith("#") or not line.startswith(prefixes):
|
|
continue
|
|
name_part, _, value = line.rpartition(" ")
|
|
name = name_part.split("{", 1)[0].strip()
|
|
try:
|
|
number = float(value)
|
|
except ValueError:
|
|
continue
|
|
sums[name] = sums.get(name, 0.0) + number
|
|
return sums
|
|
|
|
|
|
def cmd_ready(args: argparse.Namespace) -> dict:
|
|
urls = {
|
|
"collector": f"{COLLECTOR}/metrics",
|
|
"prometheus": f"{PROMETHEUS}/-/ready",
|
|
"loki": f"{LOKI}/ready",
|
|
"tempo": f"{TEMPO}/ready",
|
|
}
|
|
started = time.monotonic()
|
|
waiting = dict(urls)
|
|
while waiting and time.monotonic() - started < args.timeout:
|
|
for name, url in list(waiting.items()):
|
|
if fetch(url, timeout=2)[0] == 200:
|
|
del waiting[name]
|
|
if waiting:
|
|
time.sleep(0.5)
|
|
return {
|
|
"ready": not waiting,
|
|
"waiting": sorted(waiting),
|
|
"waited_s": round(time.monotonic() - started, 1),
|
|
}
|
|
|
|
|
|
def cmd_snap(args: argparse.Namespace) -> dict:
|
|
out: dict = {"ts": round(time.time(), 3)}
|
|
for name, url in SOURCES.items():
|
|
status, body = fetch(url)
|
|
out[name] = (
|
|
metric_sums(body.decode("utf-8", "replace"), PREFIXES[name])
|
|
if status == 200
|
|
else None
|
|
)
|
|
# применена ли копия с отбором рядов (вариант balanced)
|
|
status, body = fetch(f"{PROMETHEUS}/api/v1/status/config")
|
|
out["prom_relabel"] = b"metric_relabel_configs" in body if status == 200 else None
|
|
return out
|
|
|
|
|
|
def loki_records(rids: list[str], start: float, end: float) -> dict[str, dict]:
|
|
"""Запись доступа API на каждый id: статус, мс на сервере, trace_id."""
|
|
found: dict[str, dict] = {}
|
|
for offset in range(0, len(rids), LOKI_BATCH):
|
|
batch = rids[offset : offset + LOKI_BATCH]
|
|
query = (
|
|
'{service_name="messenger-api"} | event="http request" | request_id=~"'
|
|
+ "|".join(batch)
|
|
+ '"'
|
|
)
|
|
params = urllib.parse.urlencode(
|
|
{
|
|
"query": query,
|
|
"start": int((start - 60) * 1e9),
|
|
"end": int((end + 60) * 1e9),
|
|
"limit": 5000,
|
|
"direction": "forward",
|
|
}
|
|
)
|
|
status, body = fetch(f"{LOKI}/loki/api/v1/query_range?{params}", timeout=30)
|
|
if status != 200:
|
|
raise SystemExit(f"loki query failed: HTTP {status}")
|
|
for stream in json.loads(body).get("data", {}).get("result", []):
|
|
labels = stream.get("stream", {})
|
|
rid = labels.get("request_id", "")
|
|
for _, line in stream.get("values", []):
|
|
match = ACCESS.search(line)
|
|
if rid and match:
|
|
found[rid] = {
|
|
"status": int(match.group(1)),
|
|
"server_ms": float(match.group(2)),
|
|
"trace_id": labels.get("trace_id", ""),
|
|
}
|
|
return found
|
|
|
|
|
|
def tempo_trace(trace_id: str) -> dict:
|
|
"""Трасса по id: найдена ли, span, consumer span и его исход."""
|
|
status, body = fetch(f"{TEMPO}/api/v2/traces/{trace_id}", timeout=30)
|
|
if status == 404:
|
|
return {"found": False}
|
|
if status != 200:
|
|
return {"found": None, "http": status}
|
|
data = json.loads(body or b"{}")
|
|
trace = data.get("trace", data)
|
|
spans = 0
|
|
consumer = None
|
|
for resource in trace.get("resourceSpans") or trace.get("batches") or []:
|
|
for scope in resource.get("scopeSpans", []):
|
|
for span in scope.get("spans", []):
|
|
spans += 1
|
|
if span.get("kind") in ("SPAN_KIND_CONSUMER", 5):
|
|
for attr in span.get("attributes", []):
|
|
if attr.get("key") == "messenger.job.outcome":
|
|
consumer = next(iter(attr["value"].values()), "")
|
|
if consumer is None:
|
|
consumer = ""
|
|
return {"found": spans > 0, "spans": spans, "consumer": consumer}
|
|
|
|
|
|
def cmd_find(args: argparse.Namespace) -> dict:
|
|
with open(args.input, encoding="ascii") as handle:
|
|
request = json.load(handle)
|
|
rids = sorted({rid for items in request["classes"].values() for rid in items})
|
|
records = loki_records(rids, request["start"], request["end"])
|
|
trace_ids = sorted({r["trace_id"] for r in records.values() if r.get("trace_id")})
|
|
with ThreadPoolExecutor(TEMPO_THREADS) as pool:
|
|
traces = dict(zip(trace_ids, pool.map(tempo_trace, trace_ids), strict=True))
|
|
out: dict = {"classes": {}}
|
|
for name, items in request["classes"].items():
|
|
rows = []
|
|
for rid in items:
|
|
record = records.get(rid)
|
|
row = {"rid": rid, "log": record is not None}
|
|
if record:
|
|
row.update(record)
|
|
row.update(traces.get(record.get("trace_id", ""), {"found": False}))
|
|
rows.append(row)
|
|
out["classes"][name] = rows
|
|
return out
|
|
|
|
|
|
def main() -> None:
|
|
root = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
commands = root.add_subparsers(dest="command", required=True)
|
|
ready = commands.add_parser("ready")
|
|
ready.add_argument("--timeout", type=float, default=90)
|
|
commands.add_parser("snap")
|
|
find = commands.add_parser("find")
|
|
find.add_argument("--input", required=True)
|
|
args = root.parse_args()
|
|
handler = {"ready": cmd_ready, "snap": cmd_snap, "find": cmd_find}
|
|
json.dump(handler[args.command](args), sys.stdout)
|
|
sys.stdout.write("\n")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|