diff --git a/DEMO.md b/DEMO.md new file mode 100644 index 00000000..d9b28e72 --- /dev/null +++ b/DEMO.md @@ -0,0 +1,159 @@ +# DEMO.md — сценарии прогонов лабораторной 6 (БВТ2304, Тюрина, на 4) + +Все проверки текстовые (по COURSE.md скриншоты — дополнение). Стенд один Docker-host: +эксперименты проверяют отказы отдельных сервисов, а не потерю host. Данные синтетические. +Отказы запускаются явно, scaffold сам контейнеры не останавливает. + +## 0. Поднятие стенда из чистого clone + +```bash +git clone && cd mtusi2026lab6-fork +git checkout solution/bvt2304-tyurina +cp .env.example .env +docker compose --env-file .env up -d --build +sleep 30 +make check +make test +``` + +Ожидание: `PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.` + +## 0.1 Общие переменные и хелперы (выполнить один раз в терминале) + +```bash +PROM=http://localhost:9090 +LOKI=http://localhost:3100 +TEMPO=http://localhost:3200 +API=http://localhost:8080 +pq() { curl -s -G "$PROM/api/v1/query" --data-urlencode "query=$1"; } +alerts_state() { + curl -s "$PROM/api/v1/alerts" | python3 -c "import sys,json; d=json.load(sys.stdin); print(','.join(a['labels']['alertname']+':'+a['state'] for a in d['data'].get('alerts',[])) or 'NONE')" +} +share() { + pq 'messenger:http_5xx_share:ratio2m' | python3 -c "import sys,json; r=json.load(sys.stdin)['data']['result']; print(round(float(r[0]['value'][1])*100,2) if r else 0)" +} +``` + +Важно: `/api/v1/alerts` возвращает `data.alerts` (плоский список); `data.groups` есть только у `/api/v1/rules`. + +## 1. Sanity: сигналы на месте, нули вместо No data + +```bash +curl -s "$PROM/api/v1/targets" | python3 -c "import sys,json; [print(t['labels'].get('job'), t['health']) for t in json.load(sys.stdin)['data']['activeTargets']]" +curl -s "$PROM/api/v1/rules" | python3 -c "import sys,json; [print(r['name'], r.get('state'), r.get('health')) for g in json.load(sys.stdin)['data']['groups'] for r in g['rules']]" +pq 'messenger:http_5xx_share:ratio2m' +pq 'messenger:worker_job_rate:by_status5m' +pq 'messenger:worker_job_duration_seconds:p95_5m' +pq 'messenger:queue_depth' +pq 'messenger:collector_up' +START=$(date -u -v-5M +%s)000000000; END=$(date -u +%s)000000000 +curl -sG "$LOKI/loki/api/v1/query_range" --data-urlencode 'query={service_name=~"messenger-.+"}' --data-urlencode 'limit=3' --data-urlencode "start=$START" --data-urlencode "end=$END" | head -c 600 +curl -s "$TEMPO/api/search?service.name=messenger-worker&limit=3" | head -c 400 +curl -s -u admin:admin http://localhost:3000/api/datasources | python3 -c "import sys,json; [print(d['name'], d['type']) for d in json.load(sys.stdin)]" +``` + +Ожидание: targets UP; правила health=ok; recording-серии отдают `0` (done/failed по статусам), collector_up=1; +в Loki строки с `traceid`; в Tempo трейсы worker; datasources Prometheus/Loki/Tempo. +Нули обеспечены праймингом счётчиков в коде и `or vector(0)` в recording rules. + +## 2. Нагрузка через контракт + свежие метрики приложения + +```bash +python3 student-tests/loadgen.py --duration 120 --workers 6 --burst 120 +pq 'sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))' +pq 'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api",http_route!~"/health/.*"}[2m])))' +pq 'sum by (status) (rate(worker_jobs_processed_total[2m]))' +pq 'sum(attachment_jobs_queue_depth)' +pq 'sum(worker_in_flight_jobs)' +pq 'sum(db_pool_acquired_conns)' +make test +``` + +Ожидание: RPS>0, p95 в секундах, jobs/s по статусам, depth возвращается к 0 после дренажа. +В Grafana (Last 15 minutes, refresh 5s): всплеск RPS, пик queue depth, линии p50/p95/p99, db pool. +Username в генераторах без дефисов: контракт валидирует username, дефис даёт 400 invalid_request. + +## 3. Сквозной трейс upload → broker → worker + +```bash +TRACE=$(curl -s "$TEMPO/api/search?service.name=messenger-worker&limit=1" | python3 -c "import sys,json; print(json.load(sys.stdin)['traces'][0]['traceID'])") +echo "$TRACE" +curl -s "$TEMPO/api/traces/$TRACE" > evidence/trace_upload_to_worker.json +python3 - << 'PY' +import json +data = json.load(open('evidence/trace_upload_to_worker.json')) +kinds = {1:'INTERNAL',2:'SERVER',3:'CLIENT',4:'PRODUCER',5:'CONSUMER'} +for b in data.get('batches', []): + svc = next((a['value']['stringValue'] for a in b['resource']['attributes'] if a['key']=='service.name'), '?') + print('===', svc) + for sc in b.get('scopeSpans', []): + for s in sc.get('spans', []): + k = s.get('kind') + kind = k.replace('SPAN_KIND_','') if isinstance(k,str) else kinds.get(k,'?') + print(f" {s['name']:45s} kind={kind:9s} parent={s.get('parentSpanId','')[:16] or '(root)'}") +PY +docker compose logs --since 10m api | grep -c "$TRACE" +docker compose logs --since 10m worker | grep -c "$TRACE" +``` + +Ожидание: один traceID в двух сервисах; SERVER-span API и CONSUMER-span `process_job` worker с parent из API; +счётчики grep > 0 в обоих логах. Tempo отдаёт kind строкой `SPAN_KIND_*` — дамп это учитывает. + +## 4. Ошибка worker, отслеженная по trace_id (инцидент S3) + +```bash +./student-tests/trace_error_scenario.sh +cat evidence/error_trace_id.txt +python3 - << 'PY' +import json +att = open('evidence/attachment_id.txt').read().strip() +data = json.load(open('evidence/trace_with_error.json')) +kinds = {1:'INTERNAL',2:'SERVER',3:'CLIENT',4:'PRODUCER',5:'CONSUMER'} +for b in data.get('batches', []): + svc = next((a['value']['stringValue'] for a in b['resource']['attributes'] if a['key']=='service.name'), '?') + print('===', svc) + for sc in b.get('scopeSpans', []): + for s in sc.get('spans', []): + k = s.get('kind') + kind = k.replace('SPAN_KIND_','') if isinstance(k,str) else kinds.get(k,'?') + st = s.get('status', {}) or {} + c = st.get('code', 0) + status = 'ERROR' if c in (2,'STATUS_CODE_ERROR') else ('OK' if c in (1,'STATUS_CODE_OK') else 'UNSET') + attrs = {a['key']: list(a['value'].values())[0] for a in s.get('attributes', [])} + tie = {k2:v for k2,v in attrs.items() if att in str(v)} + print(f" {s['name']:40s} kind={kind:9s} status={status}") + if tie: print(' tie-in:', tie) + for ev in s.get('events', []): print(' event:', ev.get('name')) +PY +``` + +Сценарий: pause worker → upload(202/queued) → stop S3 → unpause → worker падает на `s3_download_failed` → +лог ERROR в Loki с trace_id → тот же trace в Tempo содержит spans worker → start S3 → retry → attachment `ready`. +Trap в скрипте возвращает стенд в рабочее состояние при любом падении. +Ожидание: `evidence/loki_worker_logs.json` содержит ERROR-строку с trace_id; трейс содержит `process_job` и `s3.get_staging`; +после восстановления `status=ready`, error_code пуст. + +## 5. Окно 5xx: firing → resolved без перезапуска API (инцидент PostgreSQL) + +```bash +./student-tests/five_xx_demo.sh +grep -c '"state": "firing"' evidence/alerts_firing.json +python3 -c "import json; d=json.load(open('evidence/alerts_resolved.json')); print('active after recovery:', len(d['data']['alerts']))" +python3 -c "import json; d=json.load(open('evidence/five_xx_share_series.json')); v=[float(x[1]) for r in d['data']['result'] for x in r['values']]; print('peak 5xx share %:', round(max(v)*100,1))" +make test +``` + +Правило (оконная доля, не накопленный счётчик): +`sum(rate(...{status=~"5..",http_route!~"/health/.*"}[2m])) / clamp_min(sum(rate(...{http_route!~"/health/.*"}[2m])),0.001) > 0.05`, `for: 1m`. +Health-маршруты исключены, чтобы всегда-200 healthcheck не размывал долю. +Ожидание: в фазе down доля ~100% и `ApiHighErrorRate:firing`; после старта PostgreSQL запросы становятся 4xx, +доля падает до 0 за окно 2m, alert уходит из active — resolved штатно, без рестарта процессов. +В Grafana панель «API 5xx share» показывает пик и спад (range Last 30 minutes). + +Ручные проверки в любой момент: + +```bash +share +alerts_state +pq 'sum by (http_route,http_response_status_code) (increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[5m]))' +``` \ No newline at end of file diff --git a/evidence/alerts_firing.json b/evidence/alerts_firing.json index 96be84af..e1ea9f94 100644 --- a/evidence/alerts_firing.json +++ b/evidence/alerts_firing.json @@ -1 +1 @@ -{"status":"success","data":{"alerts":[{"labels":{"alertname":"ApiHighErrorRate","severity":"critical","slo":"availability"},"annotations":{"description":"Total 5xx count: 245","summary":"More than 10 total 5xx responses"},"state":"firing","activeAt":"2026-11-19T15:20:36.76716048Z","value":"2.45e+02"}]}} \ No newline at end of file +{"status":"success","data":{"alerts":[{"labels":{"alertname":"ApiHighErrorRate","severity":"critical","slo":"availability"},"annotations":{"description":"5xx share = 100%","summary":"API business 5xx share > 5% in 2m window"},"state":"firing","activeAt":"2026-12-01T10:24:06.76716048Z","value":"1e+00"}]}} \ No newline at end of file diff --git a/evidence/alerts_resolved.json b/evidence/alerts_resolved.json index 39697de3..9e1f5fad 100644 --- a/evidence/alerts_resolved.json +++ b/evidence/alerts_resolved.json @@ -1 +1 @@ -{"status":"success","data":{"alerts":[]}} \ No newline at end of file +{"status":"success","data":{"alerts":[{"labels":{"alertname":"ApiLatencyP95High","severity":"warning","slo":"latency"},"annotations":{"summary":"API p95 latency > 500ms"},"state":"firing","activeAt":"2026-12-01T10:25:36.76716048Z","value":"2.9374326287031076e+00"}]}} \ No newline at end of file diff --git a/evidence/five_xx_by_route.json b/evidence/five_xx_by_route.json new file mode 100644 index 00000000..d50cf83d --- /dev/null +++ b/evidence/five_xx_by_route.json @@ -0,0 +1 @@ +{"status":"success","data":{"resultType":"vector","result":[{"metric":{"http_response_status_code":"503","http_route":"/api/v1/chats/{chat_id}/attachments"},"value":[1796120708.502,"0"]},{"metric":{"http_response_status_code":"500","http_route":"/api/v1/chats/{chat_id}/messages"},"value":[1796120708.502,"0"]},{"metric":{"http_response_status_code":"500","http_route":"/api/v1/users/me"},"value":[1796120708.502,"0"]},{"metric":{"http_response_status_code":"500","http_route":"/api/v1/chats/{chat_id}/attachments"},"value":[1796120708.502,"0"]},{"metric":{"http_response_status_code":"503","http_route":"/api/v1/users/me"},"value":[1796120708.502,"159.5"]}]}} \ No newline at end of file diff --git a/evidence/five_xx_share_series.json b/evidence/five_xx_share_series.json new file mode 100644 index 00000000..0e117e9d --- /dev/null +++ b/evidence/five_xx_share_series.json @@ -0,0 +1 @@ +{"status":"success","data":{"resultType":"matrix","result":[{"metric":{"__name__":"messenger:http_5xx_share:ratio2m"},"values":[[1796120565,"0"],[1796120580,"0"],[1796120595,"0"],[1796120610,"0"],[1796120625,"0"],[1796120640,"1"],[1796120655,"1"],[1796120670,"1"],[1796120685,"1"],[1796120700,"1"],[1796120715,"1"],[1796120730,"1"],[1796120745,"1"],[1796120760,"1"],[1796120775,"1"],[1796120790,"1"],[1796120805,"1"],[1796120820,"1"],[1796120835,"1"],[1796120850,"1"],[1796120865,"0.7450980392156863"],[1796120880,"0.5660406003039626"],[1796120895,"0.37681176796879473"],[1796120910,"0.2638922195557757"],[1796120925,"0.1704546487593914"],[1796120940,"0.07865451136985267"],[1796120955,"0.03409121900544706"],[1796120970,"0"],[1796120985,"0"],[1796121000,"0"],[1796121015,"0"],[1796121030,"0"],[1796121045,"0"]]}]}} \ No newline at end of file diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml index 2bd585b2..56f7909b 100644 --- a/infra/prometheus/prometheus.yml +++ b/infra/prometheus/prometheus.yml @@ -12,4 +12,8 @@ scrape_configs: - job_name: 'prometheus' static_configs: - - targets: ['localhost:9090'] \ No newline at end of file + - targets: ['localhost:9090'] + + - job_name: otelcol-internal + static_configs: + - targets: [ 'otelcol:8888' ] \ No newline at end of file diff --git a/infra/prometheus/rules.yml b/infra/prometheus/rules.yml index 9d3edbbf..8f87ca73 100644 --- a/infra/prometheus/rules.yml +++ b/infra/prometheus/rules.yml @@ -5,28 +5,23 @@ groups: - record: messenger:http_5xx_share:ratio2m expr: | ( - sum(rate(messenger_http_responses_total{status_class="5xx"}[2m])) + sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!~"/health/.*"}[2m])) / - clamp_min(sum(rate(messenger_http_responses_total[2m])), 0.001) + clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*"}[2m])), 0.001) ) or vector(0) - - record: messenger:worker_job_rate:by_status5m expr: | sum by (status) (rate(worker_jobs_processed_total[5m])) or max by (status) (worker_jobs_processed_total) * 0 - - record: messenger:worker_job_duration_seconds:p95_5m expr: | histogram_quantile(0.95, sum by (le) (rate(worker_job_duration_seconds_bucket[5m]))) or vector(0) - - record: messenger:queue_depth expr: max(attachment_jobs_queue_depth) or vector(0) - - record: messenger:collector_up expr: max(up{job="otel-collector"}) or vector(0) - - name: messenger-slo rules: - alert: ApiHighErrorRate @@ -36,6 +31,35 @@ groups: severity: critical slo: availability annotations: - summary: "API 5xx share > 5% in 2m window" + summary: "API business 5xx share > 5% in 2m window" description: "5xx share = {{ $value | humanizePercentage }}" - # ... остальные alert'ы без изменений \ No newline at end of file + - alert: AttachmentQueueLagHigh + expr: attachment_jobs_oldest_age_seconds > 60 + for: 1m + labels: + severity: warning + slo: freshness + annotations: + summary: "Oldest unfinished attachment job > 60s" + - alert: WorkerStalled + expr: | + attachment_jobs_queue_depth > 0 + and + increase(worker_jobs_processed_total{status="done"}[10m]) == 0 + for: 5m + labels: + severity: critical + slo: freshness + annotations: + summary: "Queue non-empty but no jobs completed in 10m" + - alert: ApiLatencyP95High + expr: | + histogram_quantile(0.95, + sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api",http_route!~"/health/.*"}[5m])) + ) > 0.5 + for: 5m + labels: + severity: warning + slo: latency + annotations: + summary: "API p95 latency > 500ms" diff --git a/student-tests/five_xx_demo.sh b/student-tests/five_xx_demo.sh new file mode 100755 index 00000000..0665d73b --- /dev/null +++ b/student-tests/five_xx_demo.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -e +mkdir -p evidence +Q5='sum by (http_route,http_response_status_code) (increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[5m]))' +QS='messenger:http_5xx_share:ratio2m' +share() { + curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$QS" \ + | python3 -c "import sys,json; r=json.load(sys.stdin)['data']['result']; print(round(float(r[0]['value'][1])*100,1) if r else -1)" +} +echo "=== baseline: 5xx by route ===" +curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$Q5" | python3 -m json.tool | head -30 +echo "=== stop postgres ===" +docker compose stop postgres +python3 - << 'PY' & +import requests, time +for i in range(150): + try: + requests.get('http://localhost:8080/api/v1/users/me', headers={'Authorization':'Bearer invalid'}, timeout=2) + except Exception: + pass + time.sleep(1) +PY +GEN=$! +FIRED=0 +for i in $(seq 1 30); do + sleep 5 + STATE=$(curl -s http://localhost:9090/api/v1/alerts | python3 -c "import sys,json; d=json.load(sys.stdin); f=[a['labels']['alertname'] for a in d['data'].get('alerts',[]) if a['state']=='firing']; print(','.join(f) or 'NONE')") + echo "[down $((i*5))s] 5xx share=$(share)% firing=$STATE" + if [ "$STATE" != "NONE" ] && [ $FIRED -eq 0 ]; then + FIRED=1 + curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_firing.json + curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$Q5" > evidence/five_xx_by_route.json + echo "captured firing + 5xx by route" + fi +done +echo "=== start postgres ===" +docker compose start postgres +wait $GEN || true +for i in $(seq 1 24); do + sleep 5 + curl -s -o /dev/null http://localhost:8080/api/v1/users/me -H "Authorization: Bearer invalid" + echo "[up $((i*5))s] 5xx share=$(share)%" +done +curl -s http://localhost:9090/api/v1/alerts > evidence/alerts_resolved.json +curl -s -G http://localhost:9090/api/v1/query_range --data-urlencode "query=$QS" \ + --data-urlencode "start=$(date -u -v-8M +%s)" --data-urlencode "end=$(date -u +%s)" \ + --data-urlencode 'step=15s' > evidence/five_xx_share_series.json +echo "=== final: 5xx by route ===" +curl -s -G http://localhost:9090/api/v1/query --data-urlencode "query=$Q5" | python3 -m json.tool | head -30 +make test