From af52ead24e6e8ff326b329842a7deb3cc13b2863 Mon Sep 17 00:00:00 2001 From: Budilov Date: Fri, 4 Dec 2026 05:46:58 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B8=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=BB?= =?UTF-8?q?=D0=B5=D0=BD=D0=B8=D1=8F=20dashboard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- REPORT.md | 142 ++++++++++++++++++++++++++++++++++++++++-- app/main.py | 8 ++- infra/otel/alerts.yml | 32 +++++----- 3 files changed, 160 insertions(+), 22 deletions(-) diff --git a/REPORT.md b/REPORT.md index 4a23a3b..8af27d0 100644 --- a/REPORT.md +++ b/REPORT.md @@ -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): docker compose ps -5. Прогнать smoke-тест при включённой телеметрии: - python3 tests/smoke.py --base-url http://localhost:8080 +5. # Health check + curl -s http://localhost:8080/health/live | jq + # Ожидаем: {"status": "ok"} -6. Безопасная остановка (сохраняет volumes): - docker compose stop + curl -s http://localhost:8080/health/ready | jq + # Ожидаем: {"status": "ok"} -7. Намеренное удаление учебных данных: - docker compose down -v + # Проверить заголовки ответа (X-Request-Id, X-Instance-Id) + curl -sI http://localhost:8080/health/live | grep -i "x-" + # Ожидаем: + # x-request-id: + # 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 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. diff --git a/app/main.py b/app/main.py index ca7502c..c28fe77 100644 --- a/app/main.py +++ b/app/main.py @@ -75,6 +75,8 @@ class OtelASGIMiddleware: await self.app(scope, receive, send_wrapper) finally: dur_ms = (time.perf_counter() - started) * 1000.0 + if status_holder["code"] == 0: + status_holder["code"] = 500 attrs = { "http.method": method, "http.target": path, @@ -133,4 +135,8 @@ async def health_live(): @app.get("/health/ready") async def health_ready(): - return {"status": "ok"} \ No newline at end of file + return {"status": "ok"} + +@app.get("/debug/boom") +async def debug_boom(): + raise RuntimeError("demo failure for 5xx alerting") diff --git a/infra/otel/alerts.yml b/infra/otel/alerts.yml index 46c5011..4fa9faa 100644 --- a/infra/otel/alerts.yml +++ b/infra/otel/alerts.yml @@ -1,26 +1,28 @@ groups: - - name: messenger_slo + - name: messenger.sli rules: - - alert: HighErrorRate + - alert: High5xxErrorRatio 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 - for: 2m - labels: { severity: critical } + for: 1m + labels: {severity: critical} annotations: - summary: "API error rate > 5% (SLO 99%)" - description: "Доля 5xx за 5-минутное окно превысила 5%. SLI из histogram-метрик API." - - alert: WorkerQueueLagging + summary: "API 5xx ratio > 5% ({{ $value | humanizePercentage }})" + + - alert: QueueLagHigh expr: messenger_queue_oldest_job_age_seconds > 60 for: 1m - labels: { severity: warning } + labels: {severity: warning} annotations: - summary: "Старейшая job в очереди > 60 с" - - alert: QueueGrowing - expr: messenger_queue_active_jobs > 10 + summary: "Oldest queued job age > 60s ({{ $value }}s)" + + - alert: WorkerNotProcessing + expr: increase(messenger_worker_jobs_completed_total[3m]) == 0 + and messenger_queue_active_jobs > 0 for: 2m - labels: { severity: warning } + labels: {severity: warning} annotations: - summary: "Очередь растёт (> 10 задач)" \ No newline at end of file + summary: "Jobs queued but worker completed none in 3m" \ No newline at end of file