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())
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
# Только для Docker Desktop с docker/cli#4958: прямой Compose сохраняет
|
||||
# OTEL_RESOURCE_ATTRIBUTES приложения. Остальные команды идут в Docker CLI.
|
||||
set -eu
|
||||
docker_cli=${LAB6_DOCKER_CLI:-/Applications/Docker.app/Contents/Resources/bin/docker}
|
||||
script_dir=$(CDPATH= cd "$(dirname "$0")" && pwd)
|
||||
compose_cli=${LAB6_COMPOSE_CLI:-$script_dir/../../.local-tools/compose-v5.6.1/docker-compose}
|
||||
if [ "${1:-}" = compose ]; then
|
||||
shift
|
||||
if [ ! -x "$compose_cli" ]; then
|
||||
echo 'Run sh tools/docker-compat/setup.sh or set LAB6_COMPOSE_CLI.' >&2
|
||||
exit 2
|
||||
fi
|
||||
exec "$compose_cli" "$@"
|
||||
fi
|
||||
exec "$docker_cli" "$@"
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Локальный Compose для машины замеров; установленный Docker не меняется.
|
||||
set -eu
|
||||
if [ "$(uname -sm)" != 'Darwin arm64' ]; then
|
||||
echo 'This helper is for macOS arm64; set LAB6_COMPOSE_CLI to Compose 5.6.1 on other hosts.' >&2
|
||||
exit 2
|
||||
fi
|
||||
root=$(CDPATH= cd "$(dirname "$0")/../.." && pwd)
|
||||
cache_dir="$root/.local-tools/compose-v5.6.1"
|
||||
expected=fcce41226abd2b7b2936094e688bbd61284673dddafea542e08cb9a3b4423a8b
|
||||
mkdir -p "$cache_dir"
|
||||
if [ -x "$cache_dir/docker-compose" ]; then
|
||||
actual=$(shasum -a 256 "$cache_dir/docker-compose" | awk '{print $1}')
|
||||
if [ "$actual" = "$expected" ]; then
|
||||
"$cache_dir/docker-compose" version
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
download_file=$(mktemp "$cache_dir/download.XXXXXX")
|
||||
trap 'rm -f "$download_file"' EXIT
|
||||
curl --fail --location --silent --show-error --max-time 60 \
|
||||
https://github.com/docker/compose/releases/download/v5.6.1/docker-compose-darwin-aarch64 \
|
||||
--output "$download_file"
|
||||
actual=$(shasum -a 256 "$download_file" | awk '{print $1}')
|
||||
if [ "$actual" != "$expected" ]; then
|
||||
echo 'Compose checksum mismatch; installation stopped.' >&2
|
||||
exit 1
|
||||
fi
|
||||
chmod +x "$download_file"
|
||||
mv "$download_file" "$cache_dir/docker-compose"
|
||||
"$cache_dir/docker-compose" version
|
||||
Reference in New Issue
Block a user