feat: implement lab 6 observability and telemetry cost research
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка диагностики двух инцидентов через реальные Tempo/Loki-наблюдения.
|
||||
|
||||
Запуск после make up: python3 tools/audit_incidents.py.
|
||||
Использует сценарии alerts-check; останавливает worker и блокирует sessions
|
||||
только своего compose-проекта. Приложение и правила телеметрии не меняет.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def main() -> int:
|
||||
sys.stdout.reconfigure(line_buffering=True)
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import lab6 as ops
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url")
|
||||
args = parser.parse_args()
|
||||
args.base_url = args.base_url or (
|
||||
"http://localhost:" + ops._env_value("HOST_PORT", "8080")
|
||||
)
|
||||
checks = ops.Checks()
|
||||
started = time.time()
|
||||
saved: dict[str, str] = {}
|
||||
original_wait = ops._wait_alert
|
||||
|
||||
def find_trace(
|
||||
grafana: Any,
|
||||
query: str,
|
||||
predicate: Callable[[list[dict[str, Any]]], bool],
|
||||
) -> tuple[str, list[dict[str, Any]]] | None:
|
||||
for trace_id in ops._tempo_find(grafana, query, started):
|
||||
spans = ops._trace_spans(ops._tempo_trace(grafana, trace_id))
|
||||
if predicate(spans):
|
||||
return trace_id, spans
|
||||
return None
|
||||
|
||||
def linked_log(grafana: Any, service: str, trace_id: str) -> None:
|
||||
rows = ops._poll(
|
||||
lambda: ops._loki_lines(
|
||||
grafana,
|
||||
f'{{service_name="{service}"}} | trace_id="{trace_id}"',
|
||||
started,
|
||||
),
|
||||
timeout=30,
|
||||
)
|
||||
checks.add(bool(rows), "incident log linked to trace", service)
|
||||
for _, line in rows[:3]:
|
||||
print(f" Loki trace_id={trace_id}: {line}")
|
||||
|
||||
def observed_wait(
|
||||
grafana: Any, name: str, firing: bool, timeout: float
|
||||
) -> float | None:
|
||||
result = original_wait(grafana, name, firing, timeout)
|
||||
if result is None:
|
||||
return result
|
||||
if name == "MessengerQueueLagGrowing" and firing:
|
||||
|
||||
def queued_trace(spans: list[dict[str, Any]]) -> bool:
|
||||
return (
|
||||
any(s["kind"] == "SPAN_KIND_SERVER" for s in spans)
|
||||
and any(s["kind"] == "SPAN_KIND_PRODUCER" for s in spans)
|
||||
and not any(s["kind"] == "SPAN_KIND_CONSUMER" for s in spans)
|
||||
)
|
||||
|
||||
found = ops._poll(
|
||||
lambda: find_trace(
|
||||
grafana,
|
||||
'{ span.http.route = "/api/v1/chats/{chat_id}/attachments" }',
|
||||
queued_trace,
|
||||
),
|
||||
timeout=30,
|
||||
)
|
||||
checks.add(bool(found), "worker stopped: producer exists, consumer absent")
|
||||
if found:
|
||||
trace_id, spans = found
|
||||
saved["worker"] = trace_id
|
||||
print(f"DIAGNOSTIC worker stopped trace_id={trace_id}")
|
||||
ops._print_tree(spans)
|
||||
linked_log(grafana, "messenger-api", trace_id)
|
||||
elif name == "MessengerQueueLagGrowing" and not firing:
|
||||
trace_id = saved.get("worker")
|
||||
if trace_id:
|
||||
|
||||
def ready_spans() -> list[dict[str, Any]] | None:
|
||||
spans = ops._trace_spans(ops._tempo_trace(grafana, trace_id))
|
||||
return (
|
||||
spans
|
||||
if any(
|
||||
s["kind"] == "SPAN_KIND_CONSUMER"
|
||||
and s["attrs"].get("messenger.job.outcome") == "ready"
|
||||
for s in spans
|
||||
)
|
||||
else None
|
||||
)
|
||||
|
||||
spans = ops._poll(ready_spans, timeout=30)
|
||||
checks.add(
|
||||
bool(spans), "worker restored: same trace has ready consumer"
|
||||
)
|
||||
if spans:
|
||||
print(f"DIAGNOSTIC worker restored trace_id={trace_id}")
|
||||
ops._print_tree(spans)
|
||||
linked_log(grafana, "messenger-worker", trace_id)
|
||||
elif name == "MessengerHighErrorRate" and firing:
|
||||
|
||||
def database_trace(spans: list[dict[str, Any]]) -> bool:
|
||||
return any(
|
||||
s["kind"] == "SPAN_KIND_SERVER"
|
||||
and str(s["attrs"].get("http.response.status_code")) == "503"
|
||||
for s in spans
|
||||
) and any(
|
||||
s["name"].startswith("postgresql") and s["ms"] >= 1000
|
||||
for s in spans
|
||||
)
|
||||
|
||||
found = ops._poll(
|
||||
lambda: find_trace(
|
||||
grafana, "{ span.http.response.status_code = 503 }", database_trace
|
||||
),
|
||||
timeout=30,
|
||||
)
|
||||
checks.add(bool(found), "DB incident: real 503 trace with slow SQL span")
|
||||
if found:
|
||||
trace_id, spans = found
|
||||
server = next(s for s in spans if s["kind"] == "SPAN_KIND_SERVER")
|
||||
sql_ms = max(
|
||||
s["ms"] for s in spans if s["name"].startswith("postgresql")
|
||||
)
|
||||
checks.add(
|
||||
sql_ms >= server["ms"] * 0.9,
|
||||
"DB span explains at least 90% of server latency",
|
||||
f"server={server['ms']:.1f} ms SQL={sql_ms:.1f} ms",
|
||||
)
|
||||
print(f"DIAGNOSTIC database locked trace_id={trace_id}")
|
||||
ops._print_tree(spans)
|
||||
linked_log(grafana, "messenger-api", trace_id)
|
||||
return result
|
||||
|
||||
ops._wait_alert = observed_wait
|
||||
try:
|
||||
status = ops.alerts_check(args)
|
||||
finally:
|
||||
ops._wait_alert = original_wait
|
||||
passed = sum(checks.results)
|
||||
good = status == 0 and len(checks.results) == 7 and all(checks.results)
|
||||
print(f"audit-incidents: {'PASS' if good else 'FAIL'} ({passed}/7 checks)")
|
||||
return 0 if good else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user