исправления dashboard

This commit is contained in:
2026-12-04 05:46:58 +03:00
parent 54ccb8efc6
commit af52ead24e
3 changed files with 160 additions and 22 deletions
+136 -6
View File
@@ -23,14 +23,144 @@ Prerequisites: Docker 24+, Docker Compose v2, Python 3.9+.
4. Дождаться готовности (healthy для postgres/redis/rabbitmq/s3/api, Up для collector/prometheus/loki/tempo/grafana): 4. Дождаться готовности (healthy для postgres/redis/rabbitmq/s3/api, Up для collector/prometheus/loki/tempo/grafana):
docker compose ps docker compose ps
5. Прогнать smoke-тест при включённой телеметрии: 5. # Health check
python3 tests/smoke.py --base-url http://localhost:8080 curl -s http://localhost:8080/health/live | jq
# Ожидаем: {"status": "ok"}
6. Безопасная остановка (сохраняет volumes): curl -s http://localhost:8080/health/ready | jq
docker compose stop # Ожидаем: {"status": "ok"}
7. Намеренное удаление учебных данных: # Проверить заголовки ответа (X-Request-Id, X-Instance-Id)
docker compose down -v curl -sI http://localhost:8080/health/live | grep -i "x-"
# Ожидаем:
# x-request-id: <uuid>
# x-instance-id: <8 символов>
6. # Запустить smoke-тест через Docker (Python 3.12)
docker run --rm --network mtusi2026lab6_default \
-v /mnt/mydisk/uni_related_projects/mtusi2026lab6:/workspace \
python:3.12-slim \
sh -c "cd /workspace && pip install -q httpx && python3 tests/smoke.py --base-url http://mtusi2026lab6-api-1:8080"
# Ожидаем: PASS: lab6 public API scenario
7. # Посмотреть логи API с диагностическими print'ами
docker compose logs api --tail 50 | grep "!!!"
# Ожидаем:
# !!! MW SPAN: GET /health/live trace_id=abc123...
# !!! ENDPOINT trace_id=abc123...
# !!! METRIC: GET /health/live 1.6ms
# !!! MW SPAN: POST /api/v1/chats/.../attachments trace_id=def456...
8. # Найти trace_id для POST /attachments (upload)
docker compose logs api 2>/dev/null | grep "!!! MW SPAN" | grep "POST.*attachments" | tail -1
# Скопировать trace_id (например: 8c6974d3373758808a575d9d814731ea)
# Проверить в Tempo — должны быть оба сервиса в одном trace
set TRACE_ID "8c6974d3373758808a575d9d814731ea"
docker run --rm --network mtusi2026lab6_default curlimages/curl:latest \
-s "http://tempo:3200/api/traces/$TRACE_ID" | \
jq -r '.batches[] | .resource.attributes[] | select(.key=="service.name") | .value.stringValue' | sort -u
# Ожидаем:
# messenger-api
# messenger-worker
# Посмотреть дерево спанов
docker run --rm --network mtusi2026lab6_default curlimages/curl:latest \
-s "http://tempo:3200/api/traces/$TRACE_ID" | \
jq -r '.batches[].scopeSpans[].spans[] | "\(.kind)\t\(.name)"'
# Ожидаем:
# SPAN_KIND_SERVER POST /api/v1/chats/.../attachments
# SPAN_KIND_CLIENT BEGIN/SELECT/COMMIT (children HTTP)
# SPAN_KIND_PRODUCER attachment.publish
# SPAN_KIND_CONSUMER attachment.process (тот же traceID!)
# SPAN_KIND_CLIENT BEGIN/SELECT/COMMIT (children CONSUMER)
9. # Проверить, что метрики дошли до Prometheus
docker run --rm --network mtusi2026lab6_default curlimages/curl:latest \
-s "http://prometheus:9090/api/v1/query?query=http_server_duration_milliseconds_count" | \
jq '.data.result | length'
# Ожидаем: >= 1
# Посмотреть значения метрик
docker run --rm --network mtusi2026lab6_default curlimages/curl:latest \
-s "http://prometheus:9090/api/v1/query?query=http_server_duration_milliseconds_count" | \
jq '.data.result[] | .metric'
# Ожидаем:
# {
# "http_method": "GET",
# "http_target": "/health/live",
# "http_status_code": "200",
# ...
# }
10. # Открыть в браузере: http://localhost:3000
# Логин: admin / admin
# Выбрать дашборд (обычно автоматически открывается)
# В правом верхнем углу выбрать "Last 15 minutes" или "Last 30 minutes"
# Нажать Refresh (иконка обновления)
# Ожидаем 4 панели:
# 1. RPS (no endpoint'am) — линия /health/live и /health/ready
# 2. Доля ошибок 5xx (SLI) — error ratio на 0%
# 3. API latency p50/p95/p99 (из histogram, ms) — три линии
# 4. Worker jobs: completed / failed — линия completed
11. # В Grafana перейти в Explore (иконка компаса слева)
# Выбрать источник данных: Loki
# Запрос: {service_name="messenger-api"} |= "!!!"
# Ожидаем: логи с print'ами middleware
# Запрос: {service_name="messenger-worker"} |= "Job"
# Ожидаем: логи обработки job'ов
# Запрос: {service_name="messenger-api"} |= "ERROR"
# Ожидаем: пустой результат (если нет ошибок)
12. # 1) эндпоинт-«бомба» возвращает 500 (пишет http_status_code=500 через фикс middleware)
curl -s -o /dev/null -w "boom: %{http_code}\n" http://localhost:8080/debug/boom # 500
# 2) непрерывная нагрузка ~3 мин (boom + нормальный трафик для знаменателя SLI)
for i in (seq 1 90)
curl -s -o /dev/null http://localhost:8080/debug/boom
curl -s -o /dev/null http://localhost:8080/health/live
sleep 2
end
# 3) во время нагрузки — алерт FIRING
docker run --rm --network mtusi2026lab6_default curlimages/curl:latest \
-s "http://prometheus:9090/api/v1/rules?type=alert" | \
jq -r '.data.groups[].rules[] | "\(.name): \(.state)"'
# High5xxErrorRatio: firing (value ≈ 0.5)
# Grafana Alerts → красная плашка FIRING; панель «Доля ошибок 5xx» → ~50%
# 4) прекратить нагрузку, ждать затухания окон (rate[2m] + for:1m)
sleep 180
docker run --rm --network mtusi2026lab6_default curlimages/curl:latest \
-s "http://prometheus:9090/api/v1/alerts" | jq '.data.alerts' # []
# High5xxErrorRatio: inactive → полный цикл firing→resolved
13. # Посмотреть логи worker
docker compose logs worker --tail 50 | grep -E "Job|process|attachment"
# Ожидаем:
# Job <id> completed successfully (attempt 1)
# Waiting for messages on attachment.process.v1
# Проверить метрики worker
docker run --rm --network mtusi2026lab6_default curlimages/curl:latest \
-s "http://prometheus:9090/api/v1/query?query=messenger_worker_jobs_completed_total" | \
jq '.data.result'
# Ожидаем: значение >= 1 (если smoke-тест создал вложение)
Grafana на http://localhost:3000 (admin/admin), Prometheus на http://localhost:9090. Grafana на http://localhost:3000 (admin/admin), Prometheus на http://localhost:9090.
+6
View File
@@ -75,6 +75,8 @@ class OtelASGIMiddleware:
await self.app(scope, receive, send_wrapper) await self.app(scope, receive, send_wrapper)
finally: finally:
dur_ms = (time.perf_counter() - started) * 1000.0 dur_ms = (time.perf_counter() - started) * 1000.0
if status_holder["code"] == 0:
status_holder["code"] = 500
attrs = { attrs = {
"http.method": method, "http.method": method,
"http.target": path, "http.target": path,
@@ -134,3 +136,7 @@ async def health_live():
@app.get("/health/ready") @app.get("/health/ready")
async def health_ready(): async def health_ready():
return {"status": "ok"} return {"status": "ok"}
@app.get("/debug/boom")
async def debug_boom():
raise RuntimeError("demo failure for 5xx alerting")
+17 -15
View File
@@ -1,26 +1,28 @@
groups: groups:
- name: messenger_slo - name: messenger.sli
rules: rules:
- alert: HighErrorRate - alert: High5xxErrorRatio
expr: | expr: |
sum(rate(http_server_duration_milliseconds_count{http_status_code=~"5.."}[5m])) sum(rate(http_server_duration_milliseconds_count{http_status_code=~"5.."}[2m]))
/ /
sum(rate(http_server_duration_milliseconds_count[5m])) sum(rate(http_server_duration_milliseconds_count[2m]))
> 0.05 > 0.05
for: 2m for: 1m
labels: { severity: critical } labels: {severity: critical}
annotations: annotations:
summary: "API error rate > 5% (SLO 99%)" summary: "API 5xx ratio > 5% ({{ $value | humanizePercentage }})"
description: "Доля 5xx за 5-минутное окно превысила 5%. SLI из histogram-метрик API."
- alert: WorkerQueueLagging - alert: QueueLagHigh
expr: messenger_queue_oldest_job_age_seconds > 60 expr: messenger_queue_oldest_job_age_seconds > 60
for: 1m for: 1m
labels: { severity: warning } labels: {severity: warning}
annotations: annotations:
summary: "Старейшая job в очереди > 60 с" summary: "Oldest queued job age > 60s ({{ $value }}s)"
- alert: QueueGrowing
expr: messenger_queue_active_jobs > 10 - alert: WorkerNotProcessing
expr: increase(messenger_worker_jobs_completed_total[3m]) == 0
and messenger_queue_active_jobs > 0
for: 2m for: 2m
labels: { severity: warning } labels: {severity: warning}
annotations: annotations:
summary: "Очередь растёт (> 10 задач)" summary: "Jobs queued but worker completed none in 3m"