ЛР 6 — БВТ2302 — Лебедев — на 5
This commit is contained in:
@@ -28,3 +28,56 @@ OTEL_SERVICE_NAME=messenger-api
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
# --- реализация lab5–6 (см. REPORT.md, «Соответствие переменных») ---
|
||||
# Порты LB на хосте (только 127.0.0.1): API, api-ttl (профиль ttl), api-fault (профиль fault), статистика.
|
||||
API_PORT=8080
|
||||
API_TTL_PORT=8081
|
||||
API_FAULT_PORT=8082
|
||||
LB_STATS_PORT=8404
|
||||
API_CPUS=1.0
|
||||
API_MEMORY=512M
|
||||
PG_CPUS=1.0
|
||||
PG_MAX_CONNECTIONS=100
|
||||
SESSION_CACHE=redis
|
||||
SESSION_CACHE_TTL_SECONDS=60
|
||||
DB_POOL_MAX=10
|
||||
KDF_CONCURRENCY=4
|
||||
SHUTDOWN_DRAIN_SECONDS=3
|
||||
LB_SERVER_MAXCONN=10
|
||||
LB_QUEUE_TIMEOUT=2s
|
||||
UPLOAD_CONCURRENCY=16
|
||||
UPLOAD_GRACE_SECONDS=900
|
||||
# Worker и очередь (NATS JetStream). Аренда задания = BROKER_ACK_WAIT_SECONDS (брокер) и
|
||||
# JOB_LEASE_SECONDS (БД); worker продлевает обе каждые ¼ срока, пока жив.
|
||||
WORKER_REPLICAS=2
|
||||
WORKER_CPUS=1.0
|
||||
WORKER_MEMORY=1G
|
||||
WORKER_PIPELINES=1,2
|
||||
PIPELINE_VERSION=1
|
||||
JOB_LEASE_SECONDS=20
|
||||
BROKER_ACK_WAIT_SECONDS=20
|
||||
BROKER_MAX_ACK_PENDING=16
|
||||
JOB_RETRY_BASE_SECONDS=2
|
||||
JOB_RETRY_MAX_SECONDS=60
|
||||
JOB_STUCK_SECONDS=600
|
||||
WORKER_PROCESS_MEMORY_MB=768
|
||||
# Учебные хуки отказов worker по маркеру в имени файла (fault-crash-after-s3 и т. п.): «lab» — включены
|
||||
# на учебном стенде для тестов отказов; в боевой конфигурации — пусто.
|
||||
FAULT_HOOKS=lab
|
||||
# --- lab6: наблюдаемость (см. REPORT.md, «Соответствие переменных»). service.name задаётся в compose
|
||||
# отдельно для API (messenger-api) и worker (messenger-worker); OTEL_SERVICE_NAME выше — значение API.
|
||||
# Telemetry выключается целиком (эксперимент «off», трек 1):
|
||||
OTEL_SDK_DISABLED=false
|
||||
# Head sampling в SDK: доля новых trace (1.0 — все; дочерние spans наследуют решение родителя).
|
||||
OTEL_TRACES_SAMPLER=parentbased_traceidratio
|
||||
OTEL_TRACES_SAMPLER_ARG=1.0
|
||||
# Период экспорта метрик SDK, мс (= разрешение графиков; алерты рассчитаны на 10 с).
|
||||
OTEL_METRIC_EXPORT_INTERVAL=10000
|
||||
# Предел очередей SDK (spans/logs) при недоступном Collector: лишнее отбрасывается и считается.
|
||||
OTEL_BSP_MAX_QUEUE_SIZE=2048
|
||||
OTEL_BLRP_MAX_QUEUE_SIZE=2048
|
||||
# Конфигурация Collector: collector.yaml (хранить все trace) или collector-tail.yaml (tail sampling, трек 1).
|
||||
OTEL_COLLECTOR_CONFIG=collector.yaml
|
||||
COLLECTOR_CPUS=0.5
|
||||
# Grafana — единственный UI наблюдаемости, только 127.0.0.1. Логин admin, пароль — secrets/grafana_admin_password.
|
||||
GRAFANA_PORT=3000
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
name: Application stack
|
||||
# Отдельный job решения: сборка образа (API и worker), Compose-стенд (LB + 2 API + 2 worker + migrate +
|
||||
# s3-init + broker-init + PostgreSQL + Redis + SeaweedFS S3 + NATS JetStream + OTel Collector + Prometheus +
|
||||
# Loki + Tempo + Grafana), публичные smoke/persistence/failover при включённой telemetry, проверки
|
||||
# наблюдаемости (provisioning, корреляция, секреты), инциденты с алертами firing→resolved, регрессия lab2–5.
|
||||
# Секреты синтетические, генерируются на лету.
|
||||
on: [push, pull_request]
|
||||
permissions:
|
||||
contents: read
|
||||
jobs:
|
||||
stack:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 90
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Secrets and env (synthetic; FAULT_HOOKS=lab for the failure tests)
|
||||
run: ./scripts/init-secrets.sh
|
||||
- name: Compose config
|
||||
run: docker compose --env-file .env config --quiet
|
||||
- name: Build and start
|
||||
run: docker compose --env-file .env --profile ttl up -d --build --wait
|
||||
- name: Public smoke via LB (202 → ready, original + JPEG thumbnail 256×160)
|
||||
run: make test BASE_URL=http://127.0.0.1:8080
|
||||
- name: Observability (provisioning, signals, request→log→trace, upload→worker, retry, no secrets)
|
||||
run: make test-observability
|
||||
- name: Telemetry history survives restart of all stores
|
||||
run: make test-telemetry-persistence
|
||||
- name: Incidents (worker stop, slow DB vs slow handler, DB down, telemetry backend/collector down)
|
||||
run: make incidents
|
||||
- name: Defense scenario (worker down → 202 → 409 → restart API+broker → worker → ready)
|
||||
run: python3 student-tests/defense_demo.py
|
||||
- name: Failover (stop one API replica), then restore
|
||||
run: |
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8080
|
||||
./scripts/start-replicas.sh
|
||||
- name: Persistence (restart LB, API, worker, all stores incl. telemetry; volumes kept)
|
||||
run: make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080
|
||||
- name: Student tests (pipeline, variants, crash windows, outbox, retry/DLQ/replay, lab2–4 regression)
|
||||
run: make test-student
|
||||
- name: Track 1 (cost of observability), short run
|
||||
run: python3 research/telemetry_cost.py --reps 1 --window 30 --out evidence/track1-ci
|
||||
- name: Logs on failure
|
||||
if: failure()
|
||||
run: docker compose --env-file .env --profile ttl --profile fault logs --no-color --tail=200
|
||||
- name: Stop
|
||||
if: always()
|
||||
run: docker compose --env-file .env --profile ttl --profile fault down -v
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
# API и worker мессенджера lab6 (один образ, разные команды; OpenTelemetry SDK в requirements.txt). Python 3.13, зависимости — в venv отдельной стадии.
|
||||
ARG PYTHON_IMAGE=python:3.13.5-slim-bookworm
|
||||
|
||||
FROM ${PYTHON_IMAGE} AS deps
|
||||
ENV PIP_NO_CACHE_DIR=1 PIP_DISABLE_PIP_VERSION_CHECK=1
|
||||
WORKDIR /build
|
||||
COPY requirements.txt ./
|
||||
RUN python -m venv /opt/venv \
|
||||
&& /opt/venv/bin/pip install --require-virtualenv --no-compile -r requirements.txt
|
||||
|
||||
FROM ${PYTHON_IMAGE}
|
||||
ARG APP_VERSION=dev
|
||||
LABEL org.opencontainers.image.version=$APP_VERSION
|
||||
ENV PATH=/opt/venv/bin:$PATH \
|
||||
PYTHONPATH=/app/src \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
PYTHONDONTWRITEBYTECODE=1 \
|
||||
APP_VERSION=$APP_VERSION \
|
||||
APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080
|
||||
RUN groupadd --system --gid 10001 app \
|
||||
&& useradd --system --uid 10001 --gid app --home-dir /app --shell /usr/sbin/nologin app
|
||||
COPY --from=deps /opt/venv /opt/venv
|
||||
WORKDIR /app
|
||||
COPY migrations ./migrations
|
||||
COPY src ./src
|
||||
USER 10001:10001
|
||||
EXPOSE 8080
|
||||
STOPSIGNAL SIGTERM
|
||||
HEALTHCHECK --interval=5s --timeout=3s --start-period=30s --retries=6 \
|
||||
CMD ["python", "-m", "messenger", "healthcheck"]
|
||||
# PID 1 — сам HTTP-процесс (exec-форма), SIGTERM даёт graceful shutdown uvicorn.
|
||||
ENTRYPOINT ["python", "-m", "messenger"]
|
||||
CMD ["serve"]
|
||||
@@ -28,3 +28,138 @@ test-persistence:
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
# Цели решения (lab6, включая цели lab2–lab5). Публичные цели выше не изменены.
|
||||
# ---------------------------------------------------------------------------------------------
|
||||
COMPOSE ?= docker compose --env-file .env
|
||||
IN_WORKER = $(COMPOSE) run --rm --no-deps -T -v "$(CURDIR)/student-tests:/app/student-tests:ro" --entrypoint python worker
|
||||
IN_API = $(COMPOSE) run --rm --no-deps -T -v "$(CURDIR)/student-tests:/app/student-tests:ro" --entrypoint python api
|
||||
|
||||
.PHONY: secrets up down ps logs destroy-data restore stop-worker start-worker restart-api-broker s3-check \
|
||||
jobs-failed jobs-invariants test-student test-pipeline test-imgproc test-jobs-failures test-track2 \
|
||||
chaos test-attachments test-storage-failures test-api test-idempotency test-expiry test-cache-race \
|
||||
test-failures upload-memory evidence test-observability test-telemetry-persistence incidents \
|
||||
incident-worker-stop incident-db-slow incident-handler-slow incident-db-down incident-telemetry-down \
|
||||
incident-collector-down telemetry-cost grafana
|
||||
|
||||
secrets:
|
||||
./scripts/init-secrets.sh
|
||||
|
||||
# Единая команда запуска: LB + 2 API + 2 worker + migrate/s3-init/broker-init (one-shot) + PostgreSQL + Redis + S3 + NATS
|
||||
# + OTel Collector + Prometheus + Loki + Tempo + Grafana (provisioning из infra/grafana).
|
||||
up: secrets
|
||||
$(COMPOSE) --profile ttl up -d --build --wait
|
||||
|
||||
ps:
|
||||
$(COMPOSE) --profile ttl --profile fault ps -a
|
||||
|
||||
logs:
|
||||
$(COMPOSE) logs --tail=100 lb api worker nats otel-collector
|
||||
|
||||
# Безопасная остановка: контейнеры удаляются, volumes (данные и история telemetry) сохраняются.
|
||||
down:
|
||||
$(COMPOSE) --profile ttl --profile fault down
|
||||
|
||||
# НАМЕРЕННОЕ удаление учебных данных (pgdata, s3data, natsdata и история promdata/lokidata/tempodata/grafanadata).
|
||||
destroy-data:
|
||||
@echo "This deletes ALL lab6 volumes (PostgreSQL, S3, NATS, Prometheus, Loki, Tempo, Grafana). Type 'yes' to continue:"; read ans; [ "$$ans" = yes ]
|
||||
$(COMPOSE) --profile ttl --profile fault down -v
|
||||
|
||||
# Вернуть реплики API после make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
restore:
|
||||
./scripts/start-replicas.sh
|
||||
|
||||
# Сценарий защиты: остановить/запустить worker; перезапустить API и брокер (volumes сохраняются).
|
||||
stop-worker:
|
||||
./scripts/stop-worker.sh
|
||||
|
||||
start-worker:
|
||||
./scripts/start-worker.sh
|
||||
|
||||
restart-api-broker:
|
||||
./scripts/restart-api-broker.sh
|
||||
|
||||
s3-check:
|
||||
$(COMPOSE) exec -T api python -m messenger s3-check
|
||||
|
||||
# Реестр failed (DLQ) и проверка инвариантов pipeline.
|
||||
jobs-failed:
|
||||
$(COMPOSE) exec -T api python -m messenger jobs failed
|
||||
|
||||
jobs-invariants:
|
||||
$(COMPOSE) exec -T api python -m messenger jobs invariants --settled --verify-bytes
|
||||
|
||||
test-pipeline:
|
||||
$(PYTHON) student-tests/test_pipeline.py
|
||||
|
||||
# Правила вариантов и лимиты worker — внутри образа (нужен Pillow).
|
||||
test-imgproc:
|
||||
$(IN_WORKER) student-tests/test_imgproc.py
|
||||
|
||||
# Останавливает/запускает worker, брокер и реплики API, профиль fault. Volumes не трогает. ≈ 6 мин.
|
||||
test-jobs-failures:
|
||||
$(PYTHON) student-tests/test_jobs_failures.py
|
||||
|
||||
# Трек 2: автоматическая инъекция отказов (дубли, reorder, crash, версии) + инварианты. ≈ 3 мин.
|
||||
test-track2:
|
||||
$(PYTHON) student-tests/test_pipeline_idempotency.py
|
||||
|
||||
# Трек 2: рандомизированный хаос-прогон (три seed).
|
||||
chaos:
|
||||
mkdir -p evidence/track2
|
||||
for s in 1 2 3; do $(PYTHON) research/track2_chaos.py --seed $$s --uploads 60 --output evidence/track2/chaos-seed$$s.json || exit 1; done
|
||||
|
||||
test-attachments:
|
||||
$(PYTHON) student-tests/test_attachments.py
|
||||
|
||||
test-storage-failures:
|
||||
$(PYTHON) student-tests/test_storage_failures.py
|
||||
|
||||
test-api:
|
||||
$(PYTHON) student-tests/test_api.py
|
||||
|
||||
test-idempotency:
|
||||
$(PYTHON) student-tests/test_idempotency.py
|
||||
|
||||
test-expiry:
|
||||
$(PYTHON) student-tests/test_expiry.py
|
||||
|
||||
test-cache-race:
|
||||
$(IN_API) student-tests/test_cache_race.py
|
||||
|
||||
test-failures:
|
||||
$(PYTHON) student-tests/test_failures.py
|
||||
|
||||
test-student: test-pipeline test-imgproc test-attachments test-api test-idempotency test-expiry test-cache-race \
|
||||
test-jobs-failures test-storage-failures test-failures test-track2
|
||||
|
||||
upload-memory:
|
||||
$(PYTHON) research/upload_memory.py --output evidence/upload-memory.json
|
||||
|
||||
evidence:
|
||||
./scripts/collect-evidence.sh
|
||||
|
||||
# ----------------------------------------------------------------------------------------- lab6: наблюдаемость
|
||||
grafana:
|
||||
@echo "Grafana: http://127.0.0.1:3000 (admin / пароль в secrets/grafana_admin_password)"
|
||||
|
||||
# Уровни 3–4: provisioning, сигналы, корреляция запрос→лог→trace, upload→worker, retry, отсутствие секретов.
|
||||
test-observability:
|
||||
$(PYTHON) student-tests/test_observability.py
|
||||
|
||||
# История telemetry переживает перезапуск всех хранилищ (scripts/restart.sh).
|
||||
test-telemetry-persistence:
|
||||
$(PYTHON) student-tests/test_telemetry_persistence.py
|
||||
|
||||
# Контролируемые инциденты под нагрузкой: firing → resolved (≈ 20 мин все). Вывод — evidence/incidents.
|
||||
incidents:
|
||||
$(PYTHON) research/incidents.py all --out evidence/incidents
|
||||
|
||||
incident-worker-stop incident-db-slow incident-handler-slow incident-db-down incident-telemetry-down incident-collector-down:
|
||||
$(PYTHON) research/incidents.py $(@:incident-%=%) --out evidence/incidents
|
||||
|
||||
# Трек 1: цена наблюдаемости (off / full / head10 / tail), 3 повтора × 4 конфигурации ≈ 35 мин.
|
||||
telemetry-cost:
|
||||
$(PYTHON) research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1
|
||||
|
||||
|
||||
@@ -1,37 +1,284 @@
|
||||
# Отчёт — лабораторная 6
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Автор, группа: **Лебедев Дмитрий Алексеевич, БВТ2302**
|
||||
- Целевая оценка; выбранный трек 5: **5, трек 1 «Цена наблюдаемости»**
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Использованные источники, библиотеки и помощь ИИ:
|
||||
- библиотеки приложения: Starlette 1.7.0, uvicorn 0.54.0, psycopg 3.2.10 + psycopg_pool 3.2.6, redis-py 5.2.1, httpx 0.28.1, nats-py 2.11.0, Pillow 12.3.0; **OpenTelemetry Python 1.45.0** (api, sdk, OTLP/HTTP exporter; semantic conventions 0.66b0), protobuf 7.36.1. Автоинструментация (contrib) не используется: spans и метрики написаны вручную — так видно и контролируется каждый атрибут (нет риска утечки заголовков/тела);
|
||||
- компоненты наблюдаемости: **OTel Collector contrib 0.130.0, Prometheus 3.5.0 (LTS), Loki 3.5.3, Tempo 2.8.2, Grafana 13.3.1**; инфраструктура lab5: HAProxy 3.0, PostgreSQL 16, Redis 7, SeaweedFS 4.52, NATS 2.11.9;
|
||||
- документация: OTel Collector configuration (memory_limiter, batch, exporterhelper sending_queue/retry_on_failure, tail_sampling), OTel context propagation и W3C Trace Context, OTel semantic conventions (HTTP, DB, messaging, OTel SDK self-metrics), Prometheus (histograms and summaries, OTLP receiver, recording/alerting rules), Loki OTLP ingestion и structured metadata, Tempo (TraceQL, metrics-generator), Grafana provisioning; Google SRE Workbook (SLO, alerting on SLOs);
|
||||
- **ИИ:** реализация, тесты, эксперименты и этот отчёт подготовлены с помощью ИИ-ассистента Claude (Anthropic). Код других студентов не использовался.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
**Вариант: Docker Compose.** Prerequisites: Docker Engine 24+ с Compose v2 (Docker Desktop на Windows), Python 3.9+ на хосте (все тесты — stdlib), `make` (Linux/macOS; для Windows — PowerShell-команды ниже), ≈ 4 ГБ свободной RAM для стенда. Порты на хосте — только `127.0.0.1`: `8080` (API через LB), `8081` (api-ttl), `8082` (api-fault), `8404` (статистика HAProxy), **`3000` (Grafana)**. OTLP, Prometheus, Loki, Tempo, S3 и брокер на хост **не публикуются**.
|
||||
|
||||
**Образы (закреплены тегами):** `haproxy:3.0.5-alpine`, `python:3.13.5-slim-bookworm` (база API и worker, собираются из исходников), `postgres:16.10-alpine`, `redis:7.4.2-alpine`, `chrislusf/seaweedfs:4.52`, `nats:2.11.9-alpine`, **`otel/opentelemetry-collector-contrib:0.130.0`, `prom/prometheus:v3.5.0`, `grafana/loki:3.5.3`, `grafana/tempo:2.8.2`, `grafana/grafana:13.3.1`**.
|
||||
|
||||
```sh
|
||||
./scripts/init-secrets.sh # secrets/* (БД, Redis, S3, NATS, пароль admin Grafana) и .env
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env --profile ttl up -d --build --wait # = make up
|
||||
# порядок: postgres, redis, s3, nats (healthy) → migrate + s3-init + broker-init (one-shot) → api ×2, worker ×2 → lb;
|
||||
# otel-collector, prometheus, loki, tempo-init → tempo, grafana — параллельно (API от них НЕ зависит)
|
||||
# Grafana: http://127.0.0.1:3000, логин admin, пароль — secrets/grafana_admin_password;
|
||||
# dashboard «Messenger → Messenger — обзор (lab6)» и datasources импортируются сами (provisioning).
|
||||
|
||||
make test BASE_URL=http://127.0.0.1:8080 # публичный smoke при включённой telemetry
|
||||
make test-observability # уровни 3–4: provisioning, сигналы, запрос→лог→trace, upload→worker, retry, секреты
|
||||
make test-telemetry-persistence # история метрик/логов/трасс переживает рестарт всех хранилищ
|
||||
make incidents # 6 инцидентов под нагрузкой: firing → resolved (≈ 20 мин); по одному: make incident-worker-stop …
|
||||
make telemetry-cost # трек 1: off / full / head10 / tail × 3 повтора (≈ 35 мин)
|
||||
python3 tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 4 --output evidence/load.json
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://127.0.0.1:8080 && ./scripts/start-replicas.sh
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://127.0.0.1:8080
|
||||
make test-student # регрессия lab2–lab5
|
||||
./scripts/collect-evidence.sh # всё сразу, вывод в evidence/ (≈ 90 мин; SKIP_REGRESSION=1 / SKIP_RESEARCH=1 короче)
|
||||
|
||||
make down # безопасно: контейнеры удаляются, ВСЕ volumes (данные и история telemetry) сохраняются
|
||||
make destroy-data # НАМЕРЕННОЕ удаление данных и истории telemetry (down -v), с подтверждением
|
||||
```
|
||||
|
||||
**Windows (PowerShell 5.1, без make/WSL).** Docker Desktop запущен, Python с python.org. Адрес — `127.0.0.1` (не `localhost`), команды — по одной строке:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\init-secrets.ps1
|
||||
docker compose --env-file .env --profile ttl up -d --build --wait
|
||||
$env:NO_PROXY = '127.0.0.1,localhost'
|
||||
py -3 tests\smoke.py --base-url http://127.0.0.1:8080
|
||||
py -3 student-tests\test_observability.py
|
||||
py -3 student-tests\test_telemetry_persistence.py
|
||||
py -3 research\incidents.py worker-stop # и db-slow, handler-slow, db-down, telemetry-down, collector-down
|
||||
py -3 research\telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence\track1
|
||||
Get-Content secrets\grafana_admin_password # пароль admin для http://127.0.0.1:3000
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1 # всё сразу
|
||||
```
|
||||
|
||||
**Действия оператора:** только создание secrets. Миграции (в т. ч. новая `0006_observability`) применяет one-shot `migrate`; bucket — `s3-init`; stream и consumer — `broker-init`; datasources и dashboards Grafana — provisioning при старте; права на volume Tempo — one-shot `tempo-init`. Повторы безопасны. `FAULT_HOOKS=lab` в `.env` включает учебные отказы (нужны инцидентам и треку 1); в боевой конфигурации переменная пуста.
|
||||
|
||||
> **Где собраны доказательства.** В среде разработки Docker daemon работал, но Docker Hub и PyPI были закрыты политикой сети. Поэтому `evidence/` получены на **том же `compose.yaml`** с локальными образами-заменителями: **OTel Collector contrib 0.130.0, Prometheus 3.5.0, Loki 3.5.3, Tempo 2.8.2, NATS 2.11.9, SeaweedFS 4.52 — официальные бинарники релизов с GitHub, Grafana 13.3.1 — официальный пакет (.deb) с GitHub-релиза**, PostgreSQL 16/Redis 7 — пакеты хоста, HAProxy 3.0.0 — из исходников, Python 3.13 с теми же версиями библиотек (OpenTelemetry 1.45.0 — из исходников тега `v1.45.0`). Подмена — только `image`/сборка в override-файле вне репозитория; топология, сети, лимиты, конфиги Collector/Prometheus/Loki/Tempo/Grafana, правила алертов и тесты — те же. Хост сборки — cgroup v1 (Docker Desktop — cgroup v2): код CPU/RAM контейнера поддерживает обе версии. Перед защитой выполните `make up && ./scripts/collect-evidence.sh` (Windows: `scripts\collect-evidence.ps1`), чтобы `evidence/` содержал вывод официальных образов; тот же сценарий гоняет `.github/workflows/app.yml`.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```
|
||||
127.0.0.1:8080/8081/8082/8404 127.0.0.1:3000
|
||||
клиент ─HTTP─► lb: HAProxy ─(app)─► api ×2 ──(data/objects/broker)──► PostgreSQL, Redis, S3, NATS ◄── worker ×2
|
||||
│ OTLP/HTTP :4318 (сеть telemetry) │
|
||||
└──────────────────────► otel-collector ◄────────────────────┘
|
||||
memory_limiter → scrub → [tail_sampling] → batch
|
||||
┌──────────────── (сеть observability) ───────────────┐
|
||||
▼ metrics (OTLP) ▼ logs (OTLP) ▼ traces (OTLP)
|
||||
prometheus [promdata] loki [lokidata] tempo [tempodata]
|
||||
правила SLI + алертов structured metadata metrics-generator ─┐
|
||||
▲ scrape :8888/3100/3200 (сам Collector, Loki, Tempo) │ remote write
|
||||
└──────────────────────────────────────────────────────────┘
|
||||
▲ ▲ ▲
|
||||
└────────── grafana [grafanadata] ┘ ← provisioning из infra/grafana
|
||||
Trace задания: POST /attachments (SERVER) → create (PRODUCER, в транзакции upload; контекст → payload outbox)
|
||||
→ send (PRODUCER, relay; контекст → заголовки NATS) → process (CONSUMER, worker) → S3/DB spans;
|
||||
повтор: process#1 → job.finish_error → новая строка outbox → send → process#2 (тот же trace).
|
||||
```
|
||||
|
||||
| Роль | Service | Образ | Health/readiness | Volume | Сеть / порт | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| api (≥2), worker (×2), lb, postgres, redis, s3, broker, one-shot bootstrap | как в lab5 | | API ready = PostgreSQL (telemetry/Grafana в readiness **не входят**) | `pgdata`, `s3data`, `natsdata` | + сеть `telemetry` у api/worker | как в lab5 |
|
||||
| otel_collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.130.0` | `health_check` :13133 (внутри); состояние — scrape `up{job="otel-collector"}` и алерт `OtelCollectorDown` (образ без shell — без Docker healthcheck) | — (очереди в памяти, ограничены) | telemetry + observability; :4318 только внутри | — |
|
||||
| metrics store | `prometheus` | `prom/prometheus:v3.5.0` | `/-/ready` | `promdata` (7 дней / 1 ГБ) | observability | — |
|
||||
| logs store | `loki` | `grafana/loki:3.5.3` | datasource health в Grafana | `lokidata` (7 дней) | observability | — (auth_enabled: false во внутренней сети) |
|
||||
| traces store | `tempo` (+ one-shot `tempo-init`: chown volume) | `grafana/tempo:2.8.2` | datasource health в Grafana | `tempodata` (7 дней) | observability | — |
|
||||
| grafana | `grafana` | `grafana/grafana:13.3.1` | `/api/health` | `grafanadata` (БД настроек; dashboards — из Git) | observability + ui; `127.0.0.1:3000` | `grafana_admin_password` (secret, `GF_SECURITY_ADMIN_PASSWORD__FILE`); анонимный доступ и регистрация выключены |
|
||||
|
||||
### Зачем каждое хранилище
|
||||
|
||||
- **Prometheus — метрики** (числовые ряды): *сколько* и *как быстро* — RPS, доля ошибок, перцентили из histogram, глубина и возраст очереди, насыщение пулов/worker, CPU/RAM; на них же правила SLI и алерты (локальное состояние firing/resolved). Дёшево хранить долго, нельзя хранить высокую кардинальность.
|
||||
- **Loki — логи** (события с контекстом): *почему* — текст ошибки, тип исключения, параметры попытки задания. Индексирует только ресурсные labels (`service_name`, `service_instance_id`, `deployment_environment_name`, `service_namespace`), а `event`, `request_id`, `job_id`, `trace_id`, `span_id` хранит как structured metadata — по ним можно фильтровать, не раздувая индекс.
|
||||
- **Tempo — трассы**: *где* внутри конкретного запроса/задания тратится время или возникает ошибка, причинная связь API → брокер → worker. Поиск TraceQL (`{ span.messenger.attachment.id = "…" }`).
|
||||
- **OTel Collector** — не хранилище: приём OTLP, защита памяти, вычистка запрещённых атрибутов, (в треке 1 — tail sampling), батчинг и **ограниченная** очередь к каждому backend. Одна точка смены backend без изменения кода.
|
||||
- **Grafana** — только интерфейс и запросы (dashboards, Explore, переходы лог ⇄ trace ⇄ метрики); данные не хранит. Её недоступность не влияет ни на API, ни на сбор telemetry.
|
||||
|
||||
### Схема сигналов (contracts/observability.md → фактические имена)
|
||||
|
||||
Имена Prometheus получаются из OTel-имени переводом `UnderscoreEscapingWithSuffixes` (точки → `_`, единица `s` → `_seconds`, `By` → `_bytes`, counter → `_total`). Ресурсные атрибуты становятся labels каждой серии: `service_name` (messenger-api / messenger-worker), `service_instance_id` (= `X-Instance-Id` реплики / id worker), `service_namespace=messenger`, `deployment_environment_name=lab`; `service.version` — в `target_info` и ресурсе логов/трасс.
|
||||
|
||||
| Сигнал контракта | Инструмент OTel → имя в Prometheus | Тип, единица | Измерения (labels) | Источник |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| HTTP requests (counter) | `http.server.request.duration` → `http_server_request_duration_seconds_count` (count histogram — это и есть счётчик; второй инструмент не заводится) | counter | `http_request_method`, `http_route` (**шаблон**, `unmatched` для 404 роутера), `http_response_status_code`, `http_response_status_class` (2xx…5xx) | API middleware |
|
||||
| HTTP duration | `http.server.request.duration` → `…_bucket/_sum/_count` | histogram, **секунды**; buckets 5 мс…10 с (semconv) | те же | API |
|
||||
| Saturation API | `http.server.active_requests` | up-down counter, запросы | `http_request_method` | API |
|
||||
| Jobs processed / failed | `messenger.jobs.processed` → `messenger_jobs_processed_total` | counter | `job_type=attachment.process.v1`, `outcome` (ready, retry, failed, superseded, duplicate, stale, nak, rejected, lease_lost, claim_error, invalid), `messenger_pipeline_version` | worker |
|
||||
| Job processing duration | `messenger.job.duration` → `messenger_job_duration_seconds_*` | histogram, с; 50 мс…120 с | `job_type`, `outcome` | worker |
|
||||
| Queue depth / oldest job age | `messenger.queue.depth`, `messenger.queue.lag`, `messenger.queue.oldest_age` → `messenger_queue_depth`, `messenger_queue_lag_seconds`, `messenger_queue_oldest_age_seconds` | gauge: задания / с | `queue=attachments.process.v1`, у depth — `state` (ready, retry_wait, processing, failed) | **API** (раз в 5 с из PostgreSQL — работает и при остановленных worker); реплики сообщают одно значение → `max()` |
|
||||
| Broker / outbox backlog | `messenger.broker.pending`, `messenger.broker.ack_pending`, `messenger.outbox.pending`, `messenger.outbox.lag`, `messenger.outbox.publish` | gauge / counter | `queue`; у publish — `outcome` | API (consumer info JetStream, outbox) |
|
||||
| Ожидание в очереди (≠ backlog) | `messenger.job.queue_wait` | histogram, с | `job_type` | worker (от доступности попытки до захвата) |
|
||||
| End-to-end time to ready | `messenger.attachment.time_to_ready` → `messenger_attachment_time_to_ready_seconds_*` | histogram, с; 0.25 с…10 мин | `job_type` | worker: от `attachments.created_at` (COMMIT upload, после которого 202) до COMMIT ready (только первая публикация) |
|
||||
| DB pool used/waiting | `db.client.connection.count` (`state`=used/idle), `.max`, `.pending_requests`, `.timeouts`; `messenger.db.pool.wait_time` | up-down counter / counter | `db_client_connection_pool_name` (api/worker) | psycopg_pool.get_stats() |
|
||||
| DB latency (отличить БД от обработчика) | `db.client.operation.duration` → `db_client_operation_duration_seconds_*` | histogram, с; 0.5 мс…5 с | `db_system_name=postgresql`, `db_operation_name` (SELECT/INSERT/…/CHECK), `error_type` | курсор psycopg (все запросы) |
|
||||
| Worker busy/capacity | `messenger.worker.busy`, `messenger.worker.capacity` | up-down counter / gauge, слоты | — | worker |
|
||||
| Process/container CPU/RAM | `process.cpu.time` (`cpu_mode`), `process.memory.usage` (RSS), `container.cpu.time`, `container.memory.usage` (cgroup usage − inactive_file), `messenger.container.memory.limit`, `messenger.container.cpu.limit` | counter с / gauge байты | — | /proc и cgroup v2/v1 внутри контейнера |
|
||||
| Потери telemetry | `otel.sdk.processor.span.processed`, `otel.sdk.exporter.span.exported`, `…log…` (self-метрики SDK), `otelcol_*` Collector | counter | `error_type` (`queue_full`, `MaxRetryError`) | SDK, Collector |
|
||||
| Logs | OTLP logs: `timestamp`, `severity_text/number`, ресурс `service.name`, атрибуты `event`, `logger`, поля события; `trace_id`/`span_id` активного span | — | — | Loki; тот же JSON — в stdout |
|
||||
| Traces | server spans `POST /api/v1/chats/{chat_id}/messages` …; client spans PostgreSQL (`INSERT messages`, `pool.check`, `pool.acquire`), Redis (`GET`), S3 (`S3.PutObject`), KDF (`password.verify`); producer `create`/`send`, consumer `process`; `job.execute`, `imgproc.run`, `job.commit` | — | статус ERROR + `error.type` у 5xx и неудачных попыток | Tempo |
|
||||
|
||||
**Не labels метрик:** user_id, chat_id, message_id, attachment_id, request_id, URL, filename, текст — проверяется тестом по всем сериям (`test_observability.py`: «метрики контракта»). Технические UUID учебных данных есть **только** в spans/логах: `messenger.request_id` (связь ответа с trace), `messenger.attachment.id`/`messenger.job.id` (поиск trace загрузки) — без них не найти конкретную загрузку; паролей, токенов, Authorization, текста сообщений, байтов, ключей S3 нет (проверено тестом).
|
||||
|
||||
**Error ratio:** числитель — ответы **5xx** бизнес-запросов, знаменатель — все бизнес-запросы; `/health/*` и `/internal/*` исключены. 4xx (неверный пароль, чужой чат, валидация) — ошибки клиента, в бюджет не входят. **Перцентили** считаются `histogram_quantile` из buckets, **сложенных по всем репликам** (`sum by (le)`), — не среднее p95 реплик (усреднять перцентили нельзя: среднее двух p95 не является p95 объединённого потока).
|
||||
|
||||
### Трассировка и перенос контекста через очередь
|
||||
|
||||
- Публичный вход **не принимает** внешний `traceparent`: каждый запрос — новый trace (клиент не навязывает нам trace/sampling). Связь «ответ → лог → trace» — по `X-Request-Id` (поле `request_id` лога, атрибут `messenger.request_id` server span); тесты используют именно этот путь.
|
||||
- **Producer:** в транзакции upload `create_job` открывает span `create attachments.process.v1` (PRODUCER, `messaging.operation.type=create`) и кладёт его W3C-контекст в **payload** строки outbox (`traceparent`/`tracestate` — поля `jobs.schema.json`) и в `attachment_jobs.trace_context` (миграция 0006). Контекст надёжен, как и сама работа: переживает падение API, рестарт брокера и повторы.
|
||||
- **Relay** (любой процесс, позже): span `send attachments.process.v1` (PRODUCER) — **дочерний** к контексту из payload; его контекст уходит в **native headers NATS** (`traceparent`/`tracestate`) вместе с `Nats-Msg-Id`.
|
||||
- **Consumer:** worker берёт родителя из заголовков NATS (нет — из payload) и создаёт `process attachments.process.v1` (CONSUMER) с атрибутами `messaging.*`, `messenger.job.*`, числом доставок; **link** на контекст payload. Выбрана связь parent-child (а не только link): одна загрузка = один trace от HTTP до S3/DB результата, включая повторы.
|
||||
- **Retry:** `finish_error` → новая строка outbox с контекстом текущего span (`job.finish_error`, потомок неудачной попытки) → следующий `send` → `process` попытки 2. Restore истёкшего lease (maintenance) — span `job.requeue_expired_lease` с родителем из `attachment_jobs.trace_context`. Дубли/устаревшие сообщения видны в том же trace (outcome duplicate/stale).
|
||||
- Spans БД/S3/Redis создаются **только внутри существующего trace**: фоновые циклы (relay каждую секунду, maintenance, health checks LB) не порождают тысячи одиночных trace; их стоимость видна в метриках (`db.client.operation.duration`).
|
||||
|
||||
### Логи
|
||||
|
||||
Один `logging`-конвейер: JSON в stdout (для `docker logs`, когда Loki недоступен) и OTLP-handler → Collector → Loki. Поля: `ts`, `level`/`severity_text`, `service`, `event` (стабильное имя: `http.request`, `dependency.unavailable`, `http.unhandled_error`, `attachment.accepted`, `job.claimed`, `job.finished`, `job.attempt_failed`, `job.lease_lost` …), `trace_id`/`span_id` активного span, поля события (`request_id`, `route`, `status`, `duration_ms`, `job_id`, `attempt`, `outcome`, `error`, `error_code`). Access-log пишет **шаблон маршрута**, а не URL. Успешные `/health/*` не логируются (проверки LB каждую секунду). Защита от утечек — три слоя: в коде поля с именами `password|token|authorization|cookie|secret|text|body` отбрасываются при форматировании (`telemetry.SCRUB`), атрибуты задаются вручную (нет автоинструментации заголовков), Collector `attributes/scrub` удаляет такие ключи и `http.request.header.authorization|cookie`.
|
||||
|
||||
### SLI / SLO и алерты
|
||||
|
||||
Окна сжаты под учебный стенд (минуты вместо 28–30 дней): цель — проверяемо увидеть firing → resolved за время защиты. Правила — `infra/prometheus/rules/messenger.yml` (recording `sli:*` и alerting), runbook для каждого — [`docs/runbooks.md`](docs/runbooks.md); состояние видно в Grafana (Alerting → Data source-managed; панель «Алерты» dashboard) и в `ALERTS` Prometheus.
|
||||
|
||||
| SLI | Определение | SLO (окно) |
|
||||
| --- | --- | --- |
|
||||
| Доступность API | доля не-5xx бизнес-запросов | 99.5% за 1 ч |
|
||||
| Задержка API | доля бизнес-запросов ≤ 250 мс (bucket `le="0.25"`); без upload (передача файла клиентом) и регистрации/входа (scrypt намеренно ~0.1–0.3 с) | 95% за 1 ч (на dashboard — 5 мин) |
|
||||
| Time to ready | доля вложений, ставших ready ≤ 10 с после 202 | 95% за 15 мин |
|
||||
|
||||
| Алерт | Условие и окно | Порог / for | Что проверено |
|
||||
| --- | --- | --- | --- |
|
||||
| ApiHighErrorRate | доля 5xx за 1 мин при трафике > 0.2 запроса/с | > 5% / 30 с | db-down |
|
||||
| ApiLatencyHigh | p95 (histogram, все реплики) за 1 мин | > 250 мс (= SLO) / 1 мин | db-slow, handler-slow |
|
||||
| DbSlowQueries | p95 `db.client.operation.duration` за 1 мин | > 50 мс / 30 с | db-slow (и НЕ срабатывает в handler-slow) |
|
||||
| DbPoolSaturated | ждущие соединения пула (последние 30 с) | > 0 / 30 с | db-down |
|
||||
| JobQueueLagGrowing | queue lag (самое старое доступное задание ждёт worker) | > 30 с / 20 с | worker-stop |
|
||||
| WorkerHeartbeatMissing | нет свежих метрик ни одного worker | > 45 с / 15 с | worker-stop |
|
||||
| JobsFailing | failed-задания за 5 мин | > 0 | регрессия (invalid_image) |
|
||||
| TelemetryExportFailing | send/enqueue failed Collector или очередь экспортёра > 20 батчей | / 30 с | telemetry-down |
|
||||
| OtelCollectorDown | `up{job="otel-collector"} == 0` | / 20 с | collector-down |
|
||||
| TelemetryLostInSdk | потери spans/logs в SDK за 5 мин (видно после восстановления канала) | > 0 | collector-down |
|
||||
|
||||
Почему queue **lag**, а не глубина: глубина растёт и при нормальной пиковой нагрузке; lag (сколько ждёт самое старое задание, уже доступное worker — без ожидания backoff) растёт только когда разбор не успевает. Backlog и время обработки — разные метрики (`messenger_queue_depth` / `messenger_job_queue_wait_seconds` / `messenger_job_duration_seconds`).
|
||||
|
||||
### Collector: память, батчи, недоступный backend
|
||||
|
||||
`memory_limiter` (первым в каждой pipeline: limit 200 MiB, spike 50 MiB при лимите контейнера 256 MiB + `GOMEMLIMIT=180MiB`) → `attributes/scrub` → `batch` (1024/2048, 2 с) → `otlphttp` с `sending_queue` (**200 батчей**, 2 потребителя) и `retry_on_failure` (1 → 10 с, не дольше **120 с**). Backend недоступен: батчи ждут в ограниченной очереди и повторяются; переполнение — `enqueue_failed`, истечение 120 с — `send_failed` (счётчики, алерт). Память ограничена очередью и memory_limiter. Collector недоступен: SDK держит не больше `OTEL_BSP_MAX_QUEUE_SIZE=2048` spans и `OTEL_BLRP_MAX_QUEUE_SIZE=2048` записей на процесс, экспорт — в фоновом потоке с таймаутом 5 с; неудачный пакет отбрасывается и считается (`otel_sdk_exporter_*_exported_total{error_type}`), RAM API не растёт, запросы не ждут telemetry. Метрики при простое теряют только точки (кумулятивные счётчики при восстановлении дают верный `increase`).
|
||||
|
||||
### Что перенесено из lab5 и что изменено
|
||||
|
||||
Весь минимум lab5 (LB + 2 API + 2 worker, PostgreSQL, Redis-кэш, S3 SeaweedFS, NATS JetStream, outbox, retry/DLQ, варианты) — без изменений поведения; публичный smoke и регрессия lab2–lab5 проходят **при включённой telemetry**. Изменено/добавлено:
|
||||
|
||||
- `src/messenger/telemetry.py` — инициализация SDK (resource, OTLP/HTTP, self-метрики), инструменты, курсор psycopg с client spans и histogram, метрики пулов и CPU/RAM (cgroup v2/v1), OTLP-handler логов, утилиты контекста; `OTEL_SDK_DISABLED=true` выключает всё (stdout-лог остаётся);
|
||||
- API: server spans/RED в ASGI middleware (шаблон маршрута), `error.type` у 5xx, метрики очереди/outbox/брокера; worker: consumer span, jobs/duration/queue_wait/time_to_ready, busy/capacity; spans S3, Redis, KDF, `pool.acquire`;
|
||||
- `jobs.py`: producer spans `create`/`send`, контекст в payload и заголовках NATS; миграция **0006_observability** (expand-only: `attachment_jobs.trace_context`, индекс незавершённых работ по `created_at`);
|
||||
- учебные отказы обработчика `fault-api-error` / `fault-api-slow-<мс>` (только `FAULT_HOOKS=lab`, см. `contracts/EXTENSIONS.md`);
|
||||
- инфраструктура: `infra/otel/collector.yaml` (+ `collector-tail.yaml` трека 1), `infra/prometheus/{prometheus.yml,rules/messenger.yml}`, `infra/loki/loki.yaml`, `infra/tempo/tempo.yaml`, `infra/grafana/provisioning/*`, `infra/grafana/dashboards/messenger-overview.json`, `docs/runbooks.md`; restart-hook перезапускает и хранилища telemetry.
|
||||
|
||||
### Соответствие переменных `.env.example`
|
||||
|
||||
`OTEL_SERVICE_NAME=messenger-api` — значение API; worker в compose получает `messenger-worker` (отдельный `service.name`). `OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318`, `OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`, `OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab` — как названы. Дополнительно: `OTEL_SDK_DISABLED`, `OTEL_TRACES_SAMPLER=parentbased_traceidratio` + `OTEL_TRACES_SAMPLER_ARG` (head sampling), `OTEL_METRIC_EXPORT_INTERVAL=10000`, `OTEL_BSP_MAX_QUEUE_SIZE`/`OTEL_BLRP_MAX_QUEUE_SIZE=2048`, `OTEL_EXPORTER_OTLP_TIMEOUT=5` (**секунды** — так читает Python SDK, хотя спецификация говорит о мс), `OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED=true`, `OTEL_COLLECTOR_CONFIG` (collector.yaml / collector-tail.yaml), `COLLECTOR_CPUS`, `GRAFANA_PORT`. Переменные lab2–lab5 — как раньше.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
Все файлы — в `evidence/`; полный прогон `scripts/collect-evidence.sh` на **пустых volumes** (все 7 volumes — данные и история telemetry — созданы заново). Стенд — см. примечание выше; версии и контейнеры — `evidence/stack.txt`. Хост: 2 vCPU, Docker 29.10, Compose 5.7.1.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke при включённой telemetry | `tests/smoke.py --base-url http://127.0.0.1:8080` | `PASS: lab6 public API scenario` (202 → ready, SHA-256, JPEG thumbnail 256×160) | `smoke.txt` |
|
||||
| 3: весь минимум lab5 работает | регрессия lab2–lab5 | API 18/18, идемпотентность 9/9, TTL 3/3, гонка кэша, вложения 13/13, pipeline 8/8, обработка изображений 8/8, окна отказов pipeline 14/14, отказы S3 5/5, Redis/PostgreSQL 2/2, трек 2 lab5 7/7, хаос 60 загрузок — инварианты `ok`; failover ×2, persistence — PASS; сценарий защиты lab5 — PASS; повтор миграций `applied: []` | `test-*.txt`, `failover-*.txt`, `persistence.txt`, `defense-demo.txt`, `track2-chaos-seed1.txt`, `jobs-invariants.txt` |
|
||||
| 3: Collector, три хранилища и Grafana в общем стенде; конфиги и provisioning в Git; volumes | `compose.yaml`, `infra/*`, `collector-config-validate.txt`, `observability.txt` | 5 сервисов + `tempo-init`; datasources `prometheus`/`loki`/`tempo` (readOnly, health OK), dashboard `messenger-overview` provisioned (33 панели); volumes `promdata`, `lokidata`, `tempodata`, `grafanadata`; на хост — только `127.0.0.1:3000` Grafana | `observability.txt`, `published-ports.txt` |
|
||||
| 3: история сохраняется (persistent volumes) | `test_telemetry_persistence.py`: контрольный запрос → restart-hook (все сервисы и хранилища) | после рестарта тот же лог (по request_id), тот же trace и **то же** историческое значение метрики; новые данные снова доходят во все три хранилища | `test-telemetry-persistence.txt` (4/4), `restart-hook.txt` |
|
||||
| 3: API и worker → OTLP → Collector; RPS/errors/duration API, jobs ok/failed и duration worker | `test_observability.py` «метрики контракта», «метрики отражают обработку» | 20 обязательных метрик есть, `service_name` = messenger-api/worker, `deployment_environment_name=lab`; ready=76, retry=2, time_to_ready count=76, p95 HTTP 41 мс, p95 time-to-ready 2.6 с | `test-observability-final.txt` |
|
||||
| 3: структурные логи и реальные трассы API и worker; на запросе — trace и лог; на job — worker trace и лог | «HTTP: X-Request-Id → лог → trace», «upload → … → process» | лог с `trace_id`/`span_id`/`severity_text`/`event`/`route`; его `span_id` = server span `POST /api/v1/chats/{chat_id}/messages` (+ DB spans); лог worker `job.finished` того же trace, `span_id` = consumer span | `test-observability*.txt`, `grafana-trace-db-slow.png` |
|
||||
| 3: импортируемый dashboard (не только screenshot) | `infra/grafana/dashboards/messenger-overview.json` + provisioning | все 60 запросов 33 панелей выполняются через Grafana `/api/ds/query` без ошибок | `test-observability*.txt`, `grafana-dashboard.png` |
|
||||
| 3: низкокардинальные labels; нет содержимого, паролей, токенов | «метрики контракта», «безопасность» | ни одной серии с user_id/chat_id/message_id/attachment_id/request_id/URL/filename/текстом; маршруты — шаблоны (12); пароль, токен, текст сообщения и `Bearer` не найдены ни в Loki, ни в trace входа и сообщения | `test-observability*.txt` |
|
||||
| 3: make test при включённой telemetry; назначение хранилищ | smoke + регрессия; раздел «Зачем каждое хранилище» | PASS | `smoke.txt` |
|
||||
| 4: W3C context API → broker → worker; producer/consumer spans; цепочка до S3/DB, включая retry | «upload → create → send → process», «retry», `research/trace_demo.py` | `create` (PRODUCER, родитель — server span) → `send` (PRODUCER) → `process` (CONSUMER, worker) → `S3.PutObject` ×4, `imgproc.run`, `job.commit`/`COMMIT`; 55 spans в одном trace; retry: попытки 1→2→3 = retry, retry, ready, неудачные — ERROR `error.type=processing_failed`, каждая следующая — потомок предыдущей; паузы backoff 1.7 и 3.7 с | `test-observability*.txt` |
|
||||
| 4: p50/p95/p99, доля ошибок, queue depth/возраст, DB pool, saturation worker; запросы и единицы | dashboard; раздел «Схема сигналов» | перцентили — `histogram_quantile` из buckets всех реплик; у каждой панели описание запроса и единиц | `grafana-dashboard.png`, JSON dashboard |
|
||||
| 4: SLI/SLO и окно; alert rules для error rate и queue lag; проверены отказом; firing → resolved | `research/incidents.py` (6 сценариев) | см. «Эксперименты и отказы»: ApiHighErrorRate, JobQueueLagGrowing, WorkerHeartbeatMissing, DbSlowQueries, ApiLatencyHigh, DbPoolSaturated, TelemetryExportFailing, OtelCollectorDown, TelemetryLostInSdk — каждое firing и resolved; 18 правил вычисляются без ошибок; по `ALERTS` за прогон срабатывали все 10 алертов (JobsFailing — на failed `invalid_image` регрессии) | `incident-*.txt`, `incidents/*.json` |
|
||||
| 4: Collector — memory limiter/batch, ограниченная буферизация; остановка хранилища не ломает сообщения и RAM не растёт бесконечно | `telemetry-down`, `collector-down` | Tempo+Loki остановлены 128 с: 772/772 сообщений и 42/42 загрузки успешны, RSS Collector 50 → 55 МиБ, очередь ≤ 64 из 200 батчей; Collector остановлен 93 с: 748/748 успешны, p95 40 мс, RSS API +6 МиБ; потери посчитаны | `incident-telemetry-down.txt`, `incident-collector-down.txt` |
|
||||
| 4: разбор двух инцидентов и шаги диагностики | разделы ниже, `docs/runbooks.md` | остановка worker; медленная БД против медленного обработчика (+ недоступная БД) | этот отчёт |
|
||||
| 5, трек 1 | `research/telemetry_cost.py --reps 3` | см. раздел «Трек 1» | `track1/summary.json`, `track1/runs.json`, `track1-telemetry-cost.txt` |
|
||||
| Нагрузка (регрессия, telemetry включена) | `tests/load.py --duration 30 --concurrency 4` | 180.9 успешных RPS, 0 ошибок, p50/p95/p99 = 16.9/53.1/107.2 мс (в lab5 без telemetry, другой прогон: 253.6 RPS, 13.4/33.1/53.7 мс; цену telemetry честно сравнивает трек 1) | `load.json` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Нагрузка во время инцидентов — `research/incidents.py`: 3–8 сообщений/с (4 потока) и, где нужно, upload раз в 2–3 с. Обнаружение — **только** по сохранённым наблюдениям: состояние алертов Prometheus, метрики, TraceQL-поиск в Tempo и логи Loki через Grafana API (сценарий не читает stdout контейнеров). Время — от воздействия; правила вычисляются каждые 10 с, метрики SDK экспортируются каждые 10 с.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Обнаружение / восстановление, потери |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| **Все worker остановлены** 93 с под нагрузкой | 202 продолжаются, растёт queue lag; алерты; после старта backlog разбирается | 78 загрузок — 202 (API 276/276 успешных, p95 37 мс); `messenger_queue_depth{state=ready}` и `messenger_broker_pending` растут до 48/46, `outbox pending` = 0; после `worker stopped` логов worker в Loki нет | JobQueueLagGrowing и WorkerHeartbeatMissing **firing через 78 с**; resolved через 25 с (heartbeat) и 45 с (lag, после разбора backlog); все 78 вложений ready — потерь 0 |
|
||||
| **Медленная БД**: PostgreSQL ограничен 0.03 CPU | растёт p95 БД и API; trace показывает время в PostgreSQL | p95 запросов к БД 3.5 → 222 мс, p95 API 42 → 717 мс, ошибок 0 (516/516); самый медленный trace 702 мс: **99%** — spans PostgreSQL (`pool.check` 192, `DELETE` 94, `INSERT messages` 301, `COMMIT` 106 мс) | DbSlowQueries firing через **57 с**, ApiLatencyHigh через 87 с; после снятия лимита resolved через 56 и 66 с |
|
||||
| **Медленный обработчик** (контраст): 50% сообщений с `fault-api-slow-400` | p95 API растёт, БД — нет | p95 API 475 мс, p95 БД **2.6 мс**; trace 422 мс: БД 12 мс (**3%**), 409 мс — в server span вне дочерних spans | ApiLatencyHigh firing через 88 с, **DbSlowQueries — нет**; resolved ≈ через 70 с после снятия нагрузки |
|
||||
| **БД недоступна** (`docker compose pause postgres`, 82 с) | 503, алерт ошибок, причина в trace | 136/136 сообщений → 503 (таймаут пула 2 с); все trace ошибок — `error.type=PoolTimeout`; в Loki 136 записей `dependency.unavailable` (`error`: PoolTimeout/TimeoutError) | DbPoolSaturated через 46 с, ApiHighErrorRate через 82 с; после unpause resolved через 10 и 72 с |
|
||||
| **Tempo и Loki остановлены** 128 с | API работает; очередь Collector ограничена; алерт; после возврата данные дослать | 772/772 сообщений и 42/42 загрузки успешны (p95 40 мс); RSS Collector 50 → 55 МиБ; очередь экспортёров ≤ 64 из 200 батчей; trace периода простоя найдены в Tempo после восстановления | TelemetryExportFailing через 67 с, resolved через 17 с после старта; не доставлено **275 spans и 30 записей** из 9 907 принятых (батчи старше `max_elapsed_time` 120 с) — посчитаны `otelcol_exporter_send_failed_*` |
|
||||
| **Collector остановлен** 93 с | API не замедляется, RAM SDK ограничена, потери считаются | 748/748 сообщений успешны, p95 40 мс (до — 44 мс); RSS API 47 → 54 МиБ; новых данных нет | OtelCollectorDown через 36 с; после старта — resolved и **TelemetryLostInSdk** firing: потеряно 5 712 spans и 715 записей лога (`error_type=MaxRetryError`), очередь SDK не переполнялась (`queue_full` = 0) |
|
||||
|
||||
### Разбор инцидента 1: остановлены все worker
|
||||
|
||||
1. **Симптом** (dashboard «SLO и алерты», затем «Очередь заданий»): firing `JobQueueLagGrowing` (lag > 30 с) и `WorkerHeartbeatMissing`. Ошибок HTTP нет (`ApiHighErrorRate` молчит) — пользователи получают 202, но вложения не становятся ready.
|
||||
2. **Где застряло:** «Глубина очереди»: `ready` растёт (до 48), `processing` = 0; «Брокер и outbox»: `outbox: не опубликовано` ≈ 0 (relay публикует), а `NATS: не выдано` растёт до 46 — сообщения есть в JetStream, их никто не забирает. Значит, не разрыв DB→broker, а отсутствие consumer.
|
||||
3. **Почему:** «Worker: занятые слоты / ёмкость» — capacity пропала (метрик worker нет 45+ с); Loki `{service_name="messenger-worker"}` — последние записи `worker stopping; draining in-flight jobs` / `worker stopped`. Вывод: worker остановлены штатно (не упали от ошибки).
|
||||
4. **Действие и проверка:** `make start-worker` → busy = capacity (разбор backlog на полной ёмкости), lag падает, через 25–45 с оба алерта resolved; `make jobs-invariants` — ничего не потеряно.
|
||||
|
||||
### Разбор инцидента 2: «медленно» — это БД или обработчик?
|
||||
|
||||
1. **Симптом:** `ApiLatencyHigh` (p95 > 250 мс = цель SLO). Ошибок нет.
|
||||
2. **Метрики:** «PostgreSQL: p95 по операции» — в db-slow вырос с 3.5 до 222 мс **вместе** с HTTP p95, сработал `DbSlowQueries`; в handler-slow p95 БД остался 2.6 мс при HTTP p95 475 мс, `DbSlowQueries` не сработал → проблема не в БД.
|
||||
3. **Trace** (панель «Медленные запросы API > 250 мс» → trace): в db-slow весь запрос состоит из spans PostgreSQL — даже пустая проверка соединения `pool.check` 192 мс, `COMMIT` 106 мс (сервер БД не успевает), `pool.acquire` ≈ `pool.check` (соединения есть — не исчерпание пула); в handler-slow DB spans — 3% длительности, 409 мс «ничьих» — время внутри кода обработчика.
|
||||
4. **Различие с недоступной БД:** в db-down запросы получают 503, в trace `error.type=PoolTimeout`, раньше всего срабатывает `DbPoolSaturated` (waiting > 0), логи `dependency.unavailable`.
|
||||
5. **Действие:** для БД — ресурсы/запрос/блокировки (runbook `DbSlowQueries`); для обработчика — профилировать код маршрута из «p95 по маршруту».
|
||||
|
||||
## Трек 1. Цена наблюдаемости
|
||||
|
||||
**Гипотеза.** (H1) Основная цена telemetry для API — создание и экспорт spans в процессе (CPU SDK), она пропорциональна числу spans и не зависит от того, что потом сохранит backend; (H2) head sampling 10% снижает и CPU, и объём хранения примерно в 10 раз, но теряет ≈ 90% редких ошибок и медленных запросов — решение принимается до того, как исход известен; (H3) tail sampling в Collector сохраняет все ошибки и медленные запросы при объёме хранения трасс ≈ 15–20% от полного, но не снижает CPU SDK; (H4) RED-метрики SDK точны при любом sampling, а метрики, построенные из сохранённых spans, — нет.
|
||||
|
||||
**Методика** (`research/telemetry_cost.py`, повторяемо одной командой). 4 конфигурации, переключаются пересозданием `api`, `worker`, `otel-collector` с переменными окружения Compose: `off` (`OTEL_SDK_DISABLED=true`), `full` (100%), `head10` (`parentbased_traceidratio` 0.1), `tail` (SDK 100% → `collector-tail.yaml`: ошибки, > 250 мс, trace pipeline вложений, 10% остальных). Нагрузка одинаковая: **open-loop 60 запросов/с** (латентность от запланированного момента — без coordinated omission), 85% POST сообщения / 15% GET истории, **1% намеренных ошибок** (`fault-api-error` → 500) и **1% намеренно медленных** (`fault-api-slow-300`), upload раз в 2 с (spans worker). Прогрев 15 с, окно 60 с, **3 повтора с чередованием** конфигураций (off, full, head10, tail, off, …), медиана по повторам. CPU/RAM — `docker stats` раз в ~1 с (среднее), ingest — счётчики Collector/Tempo/Loki/Prometheus за прогон, потери — self-метрики SDK и Collector, сохранность редких событий — поиск каждого намеренного запроса в Tempo по `messenger.request_id`. Хост: 2 vCPU, все ~20 контейнеров стенда на них же; лимиты — как в `compose.yaml`.
|
||||
|
||||
| Конфигурация | p50 / p95 / p99, мс | p95 по повторам | CPU API, % ядра (2 реплики) | RAM API, МиБ | Collector CPU / RAM | spans → Collector, /с | spans в Tempo, /с | Tempo, КБ/с | Loki, строк/с (КБ/с) | Prometheus, samples/с | Потери spans | Ошибки в Tempo | Медленные в Tempo |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| off | 6.2 / **21.5** / 41.5 | 27.2, 21.5, 18.7 | **30.5** | 106 | 0.1% / 31 МиБ | — | — | — | — | — | — | — | — |
|
||||
| full | 8.7 / **43.2** / 113.0 | 43.2, 50.5, 42.8 | **43.4** | 124 | 1.3% / 46 МиБ | 483 | 483 | **147** | 62 (18.8) | 1 275 | 0 | 135/135 | 135/135 |
|
||||
| head10 | 6.7 / **24.6** / 53.6 | 29.2, 24.6, 22.2 | **32.2** | 116 | 0.6% / 51 МиБ | 48 | 48 | **15** | 62 (18.8) | 1 254 | 0 | **5/135** | **9/135** |
|
||||
| tail | 9.1 / **55.7** / 140.1 | 67.0, 55.7, 37.8 | **42.8** | 124 | 1.4% / 50 МиБ | 483 | **80** | **28** | 62 (18.8) | 1 269 | 0 | **135/135** | **135/135** |
|
||||
|
||||
Успешных запросов во всех прогонах 58.8/с (план 60/с минус 2% намеренных), неожиданных ошибок 0.
|
||||
|
||||
**Результаты.**
|
||||
|
||||
- **H1 подтверждена.** Telemetry `full` против `off`: p95 21.5 → 43.2 мс, p99 41 → 113 мс; CPU двух API 30.5 → 43.4% ядра, т. е. **≈ 2.2 мс CPU на запрос** (≈ 8 spans на запрос сообщения: server, Redis, `pool.acquire`/`pool.check`, 3–4 SQL, COMMIT; плюс запись лога и метрики — ≈ 0.25 мс на span). RAM API +18 МиБ (очереди SDK, состояние метрик). Collector — 1.3% ядра и 46 МиБ. На 2-vCPU-хосте часть роста латентности — конкуренция за CPU с Collector/Tempo/Loki/Prometheus, работающими на тех же ядрах (при `off` они простаивают).
|
||||
- **H2 подтверждена.** `head10`: CPU API 32.2% (+1.7 п. п. от `off` — почти бесплатно), p95 24.6 мс, Tempo 15 КБ/с (−90%). Но из 135 намеренных ошибок в Tempo нашлись **5 (3.7%)**, из 135 медленных — **9 (6.7%)**: ≈ 10% с биномиальным разбросом. Ошибку или задержку, которую «не повезло» сэмплировать, по trace не разобрать.
|
||||
- **H3 подтверждена.** `tail`: сохраняются **все** 135 ошибок и 135 медленных запросов при объёме Tempo **28 КБ/с = 19%** от `full` (80 spans/с = 16.5%). CPU SDK — как у `full` (42.8%): SDK по-прежнему создаёт и экспортирует 100% spans, отбрасывает Collector. Медиана p95 55.7 мс с большим разбросом (37.8–67 мс) — в пределах шума `full` на этом хосте; дополнительная цена tail — память Collector (буфер trace на `decision_wait` 10 с, ограничен `num_traces: 20000`; здесь +4 МиБ).
|
||||
- **H4 подтверждена.** Счётчик 5xx SDK во всех «on»-прогонах = числу намеренных ошибок (45 = 45). Span-метрики Tempo (metrics-generator, из *сохранённых* spans) при `full` = 4 500 = SDK, а при `head10` ≈ 430 (**9.6%**), при `tail` ≈ 550 (**12%**) — RED нельзя строить из сэмплированных trace, поэтому dashboard и алерты используют только метрики SDK.
|
||||
- **Объём по сигналам:** при `full` трассы — 147 КБ/с, логи — 18.8 КБ/с (13% от трасс), метрики — ≈ 1.3 тыс. samples/с; sampling трасс не меняет логи и метрики. Потерь spans нет ни в одной конфигурации (очереди SDK/Collector не переполнялись).
|
||||
|
||||
**Какие события теряются и почему.** Head sampling решает в момент **начала** trace (по trace_id), когда неизвестно, будет ли ошибка или задержка: редкие события теряются пропорционально доле отбрасываемых (здесь ≈ 90–96%). Особенно опасно для редких, но важных случаев — единичный 500, медленный запрос из-за блокировки, сбой одной попытки задания. Tail sampling решает **после** завершения trace, но видит только то, что попало в trace: из 34 запросов, медленных **по мнению клиента** (> 250 мс), `tail` сохранил 15 — у остальных время ушло вне сервера (очередь LB, соединение, клиент), server span был короче порога. Задержки до сервера ловятся метриками/логами LB, не трассами.
|
||||
|
||||
**Сбалансированная конфигурация (предложена и проверена) — `tail`:** SDK 100% → Collector tail sampling (ошибки + > 250 мс + все trace pipeline вложений + 10% остальных) + RED/SLO из метрик SDK (не из trace). Проверено: 100% ошибок и медленных запросов, все trace заданий; хранение трасс в 5 раз меньше, чем `full`; метрики точны; потерь нет. Цена: CPU SDK как у `full` (≈ 2 мс CPU на запрос на этом хосте) и единственный Collector (для нескольких — `loadbalancing` exporter по trace_id, иначе spans одного trace попадут в разные tail-samplers). Если CPU приложения дороже хранения, следующий шаг — уменьшить число spans на запрос (например, не создавать `pool.check`/`pool.acquire`/Redis spans, перенеся время ожидания пула в атрибут server span) — это **гипотеза**, в эксперименте не проверялась.
|
||||
|
||||
**Ограничения измерения.** Один 2-vCPU-хост, на котором работают и приложение, и все backends; `docker stats` — среднее по ~1-секундным выборкам; 3 повтора — разброс p95 ±10–15 мс (видно в таблице); Python-генератор open-loop ограничен ~60–80 запросами/с. Память backends не сравнивается между конфигурациями: в каждом `tail`-прогоне RSS Tempo вырастал до 400–520 МиБ (в остальных 160–210 МиБ) — причина не установлена (гипотеза — приём целых trace пакетами после `decision_wait`), нужна отдельная проверка. В первом повторе `head10` счётчик 5xx за прогон занижен (7 из 45) — артефакт подсчёта: «устаревшие» серии пересозданных контейнеров выпали из суммы; исправлено (дельты считаются по экземплярам), в остальных прогонах 45/45.
|
||||
|
||||
## Сценарий защиты (README) — что показывать
|
||||
|
||||
1. **С нуля:** `make destroy-data` (или `docker compose --env-file .env down -v`), затем `make up` → Grafana `http://127.0.0.1:3000`: datasources Prometheus/Loki/Tempo и dashboard «Messenger — обзор (lab6)» уже есть (ничего не набирается руками). `make test` и нагрузка `python3 tests/load.py --duration 30 --concurrency 4`.
|
||||
2. **Свои метрики, trace и лог:** `python3 research/trace_demo.py` — делает upload, ждёт ready и печатает дерево spans (`POST …/attachments` → `create` → `send` → `process` в worker → `S3.PutObject` ×4 → `job.commit`), логи API и worker того же `trace_id` и ссылку на trace в Grafana Explore. В Explore: Loki `{service_name="messenger-api"} | event="http.request"` → кнопка «Открыть trace» у `trace_id`; Prometheus `sum by (http_route) (rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[1m]))`. Это данные своего приложения: `service_name=messenger-api/worker`, `service_instance_id` = `X-Instance-Id` ответа.
|
||||
3. **Уровень 4:** `python3 research/trace_demo.py --retry` — две попытки в одном trace; `python3 research/incidents.py worker-stop` (на dashboard растёт «Queue lag», панель «Алерты»: JobQueueLagGrowing и WorkerHeartbeatMissing firing → после старта worker resolved); `python3 research/incidents.py db-slow` и `handler-slow` — как отличить медленную БД от медленного обработчика (runbook `ApiLatencyHigh`).
|
||||
4. **Отказ telemetry:** `python3 research/incidents.py telemetry-down` (Tempo+Loki остановлены: API — 0 ошибок, очередь Collector ограничена, TelemetryExportFailing firing → resolved) и `collector-down`; трек 1 повторяется `python3 research/telemetry_cost.py --reps 1`.
|
||||
|
||||
## Ответы на вопросы защиты
|
||||
|
||||
- **Чем лог, метрика и trace отвечают на разные вопросы об одном инциденте?** Метрика — *что и насколько* (доля 5xx 12%, p95 870 мс, lag 40 с) и *с какого момента*: дёшево, по всем запросам, основа алертов, но без деталей отдельного запроса. Trace — *где* в конкретном запросе/задании: в db-slow 99% времени внутри spans PostgreSQL, в handler-slow 1% — значит, обработчик; в db-down `error.type=PoolTimeout`. Лог — *почему*: текст/тип ошибки, параметры попытки (`error_code`, `attempt`), связанный с trace по `trace_id`. Порядок разбора: алерт (метрика) → медленный/ошибочный trace → его логи.
|
||||
- **Почему chat_id в labels может исчерпать хранилище?** Каждое уникальное сочетание labels — отдельная серия (в TSDB — индекс, head chunks в RAM). С `chat_id` число серий растёт с числом чатов × маршрутов × кодов × buckets histogram (×14 у нас): 10⁵ чатов → ~10⁷ серий — память Prometheus/индекс Loki заканчиваются, запросы замедляются. Поэтому в labels — только ограниченные множества (шаблон маршрута, класс статуса, outcome), а конкретный чат/вложение ищется в trace/логах.
|
||||
- **Как очередь переносит причинную связь между процессами?** Контекст W3C (`traceparent`: trace_id + id родительского span + флаги) едет вместе с сообщением: у нас — в payload строки outbox (span `create`, переживает рестарты) и в native headers NATS (span `send`). Worker извлекает его и делает свой `process` span дочерним (плюс link на контекст payload) — трасса процесса API и процесса worker становится одной.
|
||||
- **Почему среднее latency не заменяет p99 и почему нельзя усреднять p99 реплик?** Распределение задержек тяжелохвостое: среднее 30 мс может скрывать 1% запросов по 2 с (каждый сотый пользователь страдает) — p99 это показывает. Перцентиль не аддитивен: p99 объединённого потока ≠ среднему p99 реплик (реплика с малым трафиком и плохим p99 исказит среднее; реальный p99 зависит от долей трафика). Поэтому складываем **buckets** histogram всех реплик (`sum by (le)`) и уже из суммы считаем `histogram_quantile` (точность — в пределах границ bucket).
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- **Выдерживается:** недоступность Grafana, Collector или любого хранилища telemetry — бизнес-API продолжает работать, память ограничена очередями (проверено); потери telemetry считаются. Перезапуск всех хранилищ с volumes — история сохраняется.
|
||||
- **Не выдерживается / упрощения:** один экземпляр Collector, Prometheus, Loki и Tempo (нет HA и репликации; при потере volume история теряется); алерты локальные (без Alertmanager и доставки наружу — по заданию не нужно); окна SLO сжаты до минут/часа (в эксплуатации — 28–30 дней с multi-window burn-rate, см. трек 2 курса); PostgreSQL, Redis, NATS и HAProxy не экспортируют собственные метрики (их состояние видно косвенно — клиентскими spans и метриками пула), экспортеры postgres/nats/haproxy — следующий шаг.
|
||||
- Метрики очереди считает API раз в 5 с (одинаково на каждой реплике, в запросах `max`); при недоступной БД они пропадают («нет данных» вместо устаревших значений).
|
||||
- `service.instance.id` — случайный alias процесса: при частых пересозданиях контейнеров (эксперимент трека 1) число серий растёт за счёт «ушедших» экземпляров (до выхода из окна хранения); в обычной работе — 2 API + 2 worker.
|
||||
- Логи пишутся и в stdout, и в OTLP (двойной объём ради диагностики при недоступном Loki).
|
||||
- Учебные отказы (`FAULT_HOOKS=lab`) включены в `.env.example` для тестов; в боевой конфигурации переменная пуста.
|
||||
- Трек 1: снижение CPU SDK уменьшением числа spans — гипотеза, не проверена; рост памяти Tempo при tail sampling не объяснён.
|
||||
|
||||
+556
@@ -0,0 +1,556 @@
|
||||
# Учебный стенд lab6: HAProxy (единственная точка входа) → API × N → PostgreSQL (метаданные, jobs, outbox)
|
||||
# + приватный S3 bucket в SeaweedFS (staging, оригиналы, варианты) + Redis (кэш сессий)
|
||||
# + NATS JetStream (durable очередь заданий) → worker × N (обработка изображений)
|
||||
# + наблюдаемость: API/worker → OTLP/HTTP → OTel Collector → Prometheus (метрики), Loki (логи),
|
||||
# Tempo (трассы) → Grafana (provisioning из Git; единственный UI, 127.0.0.1:3000).
|
||||
# Запуск: ./scripts/init-secrets.sh && docker compose --env-file .env up -d --build --wait
|
||||
name: mtusi-lab6
|
||||
|
||||
x-api-common: &api-common
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: mtusi-lab6-api:local
|
||||
environment: &api-env
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: "8080"
|
||||
APP_ENV: ${APP_ENV:-lab}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
SESSION_STORE: postgres
|
||||
SESSION_CACHE: ${SESSION_CACHE:-redis}
|
||||
SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CACHE_URL_FILE: /run/secrets/cache_url
|
||||
DB_POOL_MIN: "1"
|
||||
DB_POOL_MAX: ${DB_POOL_MAX:-10}
|
||||
DB_POOL_TIMEOUT_SECONDS: "2"
|
||||
KDF_CONCURRENCY: ${KDF_CONCURRENCY:-4} # каждый scrypt ≈ 32 MiB RAM: учитывайте в API_MEMORY
|
||||
DB_STATEMENT_TIMEOUT_MS: "5000"
|
||||
CACHE_TIMEOUT_SECONDS: "0.2"
|
||||
REQUEST_TIMEOUT_SECONDS: "10"
|
||||
SHUTDOWN_DRAIN_SECONDS: ${SHUTDOWN_DRAIN_SECONDS:-3}
|
||||
MIGRATE_ON_START: "false" # миграции — только сервис migrate
|
||||
# S3: отдельная identity API с правами Read/Write/List ТОЛЬКО на свой bucket (не admin).
|
||||
S3_ENDPOINT: http://s3:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
UPLOAD_CONCURRENCY: ${UPLOAD_CONCURRENCY:-16}
|
||||
UPLOAD_TIMEOUT_SECONDS: "120"
|
||||
UPLOAD_GRACE_SECONDS: ${UPLOAD_GRACE_SECONDS:-900}
|
||||
JANITOR_INTERVAL_SECONDS: "60"
|
||||
# lab5: задания — через transactional outbox в NATS JetStream (учётные данные — в файле-секрете).
|
||||
BROKER_URL_FILE: /run/secrets/broker_url
|
||||
BROKER_ACK_WAIT_SECONDS: ${BROKER_ACK_WAIT_SECONDS:-20}
|
||||
BROKER_MAX_ACK_PENDING: ${BROKER_MAX_ACK_PENDING:-16}
|
||||
PIPELINE_VERSION: ${PIPELINE_VERSION:-1}
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_LEASE_SECONDS: ${JOB_LEASE_SECONDS:-20}
|
||||
RELAY_INTERVAL_SECONDS: "1"
|
||||
FAULT_HOOKS: ${FAULT_HOOKS:-} # «lab»: учебные отказы (fault-api-* в тексте, fault-* в имени файла)
|
||||
# lab6: OpenTelemetry SDK → Collector (OTLP/HTTP, сеть telemetry). Telemetry не блокирует запросы:
|
||||
# экспорт фоновый, очереди ограничены (OTEL_BSP/BLRP_MAX_QUEUE_SIZE), лишнее отбрасывается и считается.
|
||||
OTEL_SERVICE_NAME: messenger-api
|
||||
OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false}
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
OTEL_EXPORTER_OTLP_TIMEOUT: "5" # Python SDK: секунды (а не мс, как в спецификации)
|
||||
OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=${APP_ENV:-lab}
|
||||
OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-parentbased_traceidratio}
|
||||
OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-1.0}
|
||||
OTEL_METRIC_EXPORT_INTERVAL: ${OTEL_METRIC_EXPORT_INTERVAL:-10000}
|
||||
OTEL_BSP_MAX_QUEUE_SIZE: ${OTEL_BSP_MAX_QUEUE_SIZE:-2048}
|
||||
OTEL_BSP_SCHEDULE_DELAY: "1000"
|
||||
OTEL_BLRP_MAX_QUEUE_SIZE: ${OTEL_BLRP_MAX_QUEUE_SIZE:-2048}
|
||||
OTEL_BLRP_SCHEDULE_DELAY: "1000"
|
||||
OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT: "1024"
|
||||
OTEL_PYTHON_SDK_INTERNAL_METRICS_ENABLED: "true"
|
||||
secrets: [database_url, cache_url, s3_access_key_id, s3_secret_access_key, broker_url]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
broker-init:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_started # Redis — кэш: реплики работают и без него
|
||||
networks: [app, data, objects, broker, telemetry] # НЕТ ports: API доступен только через LB
|
||||
read_only: true
|
||||
tmpfs: [/tmp]
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
restart: unless-stopped
|
||||
stop_signal: SIGTERM
|
||||
stop_grace_period: 15s # drain 3 с + завершение запросов в полёте (≤10 с)
|
||||
|
||||
services:
|
||||
lb:
|
||||
image: haproxy:3.0.5-alpine
|
||||
volumes:
|
||||
- ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
environment:
|
||||
LB_SERVER_MAXCONN: ${LB_SERVER_MAXCONN:-10}
|
||||
LB_QUEUE_TIMEOUT: ${LB_QUEUE_TIMEOUT:-2s}
|
||||
ports:
|
||||
- "127.0.0.1:${API_PORT:-8080}:8080" # публичный API
|
||||
- "127.0.0.1:${API_TTL_PORT:-8081}:8081" # api-ttl (профиль ttl), тоже только через LB
|
||||
- "127.0.0.1:${API_FAULT_PORT:-8082}:8082" # api-fault (профиль fault): только для теста компенсации
|
||||
- "127.0.0.1:${LB_STATS_PORT:-8404}:8404" # статистика HAProxy (только чтение)
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8404/stats"]
|
||||
interval: 5s
|
||||
timeout: 2s
|
||||
retries: 3
|
||||
networks: [edge, app]
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 5s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 128M}
|
||||
|
||||
# One-shot: миграции применяются ОДИН раз до запуска реплик (не гонкой реплик).
|
||||
# Повторный запуск (docker compose run --rm migrate) — no-op. Реплики не становятся ready,
|
||||
# пока схема не содержит все известные им миграции.
|
||||
migrate:
|
||||
<<: *api-common
|
||||
command: ["migrate"]
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
networks: [data]
|
||||
restart: "no"
|
||||
secrets: [database_url]
|
||||
environment:
|
||||
<<: *api-env
|
||||
SESSION_CACHE: "off"
|
||||
S3_ACCESS_KEY_ID_FILE: "" # migrate не работает с S3 и брокером
|
||||
S3_SECRET_ACCESS_KEY_FILE: ""
|
||||
BROKER_URL_FILE: ""
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
api:
|
||||
<<: *api-common
|
||||
deploy:
|
||||
replicas: ${API_REPLICAS:-2}
|
||||
resources:
|
||||
limits: {cpus: "${API_CPUS:-1.0}", memory: "${API_MEMORY:-512M}"}
|
||||
|
||||
# Экземпляр с коротким TTL — только для теста истечения; доступен через LB на :8081.
|
||||
api-ttl:
|
||||
<<: *api-common
|
||||
profiles: [ttl]
|
||||
environment:
|
||||
<<: *api-env
|
||||
SESSION_TTL_SECONDS: "2"
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
# ТОЛЬКО для тестов отказов (уровень 4), доступен через LB :8082. Точка отказа — API_FAULT_INJECT:
|
||||
# crash_after_commit_before_publish (по умолчанию) — процесс умирает между COMMIT задания и publish;
|
||||
# crash_after_publish_before_mark — между publish ack и отметкой строки outbox;
|
||||
# crash_after_s3_put — между записью staging и COMMIT (компенсация lab4).
|
||||
api-fault:
|
||||
<<: *api-common
|
||||
profiles: [fault]
|
||||
environment:
|
||||
<<: *api-env
|
||||
FAULT_INJECT: ${API_FAULT_INJECT:-crash_after_commit_before_publish}
|
||||
UPLOAD_GRACE_SECONDS: "10"
|
||||
UPLOAD_TIMEOUT_SECONDS: "5" # intent «брошен» не раньше max(grace, timeout+5) = 10 с
|
||||
JANITOR_INTERVAL_SECONDS: "2"
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
# Worker: отдельный процесс/сервис (тот же образ, команда worker). Портов нет, в сеть LB не входит.
|
||||
# Обработка каждого файла — в подпроцессе с RLIMIT_AS/RLIMIT_CPU и таймаутом; конкуренция —
|
||||
# WORKER_CONCURRENCY слотов на процесс (столько же сообщений берётся из брокера, не больше).
|
||||
worker:
|
||||
<<: *api-common
|
||||
command: ["worker"]
|
||||
environment:
|
||||
<<: *api-env
|
||||
SESSION_CACHE: "off"
|
||||
WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2}
|
||||
WORKER_PIPELINES: ${WORKER_PIPELINES:-1,2}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
JOB_RETRY_BASE_SECONDS: ${JOB_RETRY_BASE_SECONDS:-2}
|
||||
JOB_RETRY_MAX_SECONDS: ${JOB_RETRY_MAX_SECONDS:-60}
|
||||
JOB_STUCK_SECONDS: ${JOB_STUCK_SECONDS:-600}
|
||||
WORKER_PROCESS_MEMORY_MB: ${WORKER_PROCESS_MEMORY_MB:-768}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
MAINTENANCE_INTERVAL_SECONDS: "5"
|
||||
WORKER_DRAIN_SECONDS: "20"
|
||||
OTEL_SERVICE_NAME: messenger-worker
|
||||
secrets: [database_url, s3_access_key_id, s3_secret_access_key, broker_url]
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
broker-init:
|
||||
condition: service_completed_successfully
|
||||
networks: [data, objects, broker, telemetry]
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-m", "messenger", "worker-healthcheck"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 6
|
||||
start_period: 20s
|
||||
stop_grace_period: 30s # дорабатывает текущие задания ≤ 20 с, остальное вернёт брокер
|
||||
deploy:
|
||||
replicas: ${WORKER_REPLICAS:-2}
|
||||
resources:
|
||||
# WORKER_CONCURRENCY × пик RSS одной обработки (≈ 250 МиБ на 40 Мп) + сам процесс ≤ лимита.
|
||||
limits: {cpus: "${WORKER_CPUS:-1.0}", memory: "${WORKER_MEMORY:-1G}"}
|
||||
|
||||
# Брокер: NATS JetStream. Stream на диске (volume natsdata, fsync каждой записи), доступ по паролю
|
||||
# (конфигурация с учётными данными — secret). Порт 4222 — только во внутренней сети broker,
|
||||
# мониторинг :8222 — только 127.0.0.1 внутри контейнера (для healthcheck). На хост ничего не публикуется.
|
||||
nats:
|
||||
image: nats:2.11.9-alpine
|
||||
entrypoint: ["nats-server"]
|
||||
command: ["--config", "/run/secrets/nats_config"]
|
||||
secrets: [nats_config]
|
||||
volumes:
|
||||
- natsdata:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8222/healthz?js-enabled-only=true"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
start_period: 5s
|
||||
networks: [broker]
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 10s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 256M}
|
||||
|
||||
# One-shot bootstrap брокера: идемпотентно создаёт stream и durable consumer (повтор — no-op).
|
||||
broker-init:
|
||||
<<: *api-common
|
||||
command: ["broker-bootstrap"]
|
||||
environment:
|
||||
<<: *api-env
|
||||
SESSION_CACHE: "off"
|
||||
S3_ACCESS_KEY_ID_FILE: "" # broker-init работает только с брокером
|
||||
S3_SECRET_ACCESS_KEY_FILE: ""
|
||||
secrets: [database_url, broker_url]
|
||||
depends_on:
|
||||
nats:
|
||||
condition: service_healthy
|
||||
networks: [broker]
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 128M}
|
||||
|
||||
# S3-совместимое хранилище: SeaweedFS (master+volume+filer+S3 в одном процессе).
|
||||
# master/volume/filer (и их web-консоли) слушают только 127.0.0.1 внутри контейнера; наружу
|
||||
# контейнера — только S3 API :9000, и только во внутренней сети objects. Порты на хост не публикуются.
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.52
|
||||
entrypoint: ["/usr/bin/weed"]
|
||||
# Быстрая остановка: SIGINT + preStopSeconds=1 (иначе restart s3 занимает ~10 с впустую)
|
||||
stop_signal: SIGINT
|
||||
stop_grace_period: 5s
|
||||
command:
|
||||
- -logtostderr=true
|
||||
- server
|
||||
- -dir=/data
|
||||
- -ip=127.0.0.1
|
||||
- -ip.bind=127.0.0.1
|
||||
- -s3
|
||||
- -s3.port=9000
|
||||
- -s3.ip.bind=0.0.0.0
|
||||
- -s3.config=/run/secrets/s3_config
|
||||
- -master.volumeSizeLimitMB=1024
|
||||
- -master.electionTimeout=2s # единственный master: быстрее становится лидером после рестарта
|
||||
- -volume.max=0
|
||||
- -volume.preStopSeconds=1 # по умолчанию 10 с ожидания при остановке (рассчитано на кластер)
|
||||
# Без лимитов weed буферизует все одновременные загрузки и при 10×10 МиБ был убит OOM (512M).
|
||||
# С лимитами лишние загрузки ждут очереди внутри S3, а не роняют его (см. REPORT.md, эксперимент).
|
||||
- -s3.concurrentFileUploadLimit=8
|
||||
- -s3.concurrentUploadLimitMB=96
|
||||
- -filer.concurrentUploadLimitMB=96
|
||||
- -volume.concurrentUploadLimitMB=96
|
||||
- -s3.cacheCapacityMB=32
|
||||
- -master.telemetry=false # не отправлять статистику во внешний интернет
|
||||
environment:
|
||||
# Мягкий лимит кучи Go: GC держит weed ниже ~640 МиБ при лимите контейнера 1 ГиБ (без него
|
||||
# куча после пика не отдаётся и под нагрузкой процесс убивает OOM).
|
||||
GOMEMLIMIT: 640MiB
|
||||
secrets: [s3_config]
|
||||
volumes:
|
||||
- s3data:/data
|
||||
healthcheck:
|
||||
# healthy = S3-шлюз жив, master — лидер И запись возможна. После рестарта SeaweedFS 4.52 ~15 с
|
||||
# «прогревает» топологию (pulse 5 с × 3, в коде не настраивается): чтение уже работает, а запись
|
||||
# ждёт. /dir/assign отдаёт fid только по окончании прогрева, поэтому хуки ждут именно его.
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:9000/healthz && wget -q -O /dev/null http://127.0.0.1:9333/cluster/healthz && wget -q -O - http://127.0.0.1:9333/dir/assign | grep -q fid"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
start_period: 10s
|
||||
networks: [objects]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "1.0", memory: 1G}
|
||||
|
||||
# One-shot bootstrap S3: идемпотентно создаёт приватный bucket ключом администратора и проверяет,
|
||||
# что анонимный доступ запрещён, а ключи API не могут создавать бакеты. Admin-ключи есть только здесь.
|
||||
s3-init:
|
||||
<<: *api-common # тот же образ (сборка из исходников), свои env/secrets/сеть
|
||||
command: ["s3-bootstrap"]
|
||||
environment:
|
||||
S3_ENDPOINT: http://s3:9000
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id
|
||||
S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
secrets: [s3_admin_access_key_id, s3_admin_secret_access_key, s3_access_key_id, s3_secret_access_key]
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
networks: [objects]
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 128M}
|
||||
|
||||
postgres:
|
||||
image: postgres:16.10-alpine
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
POSTGRES_INITDB_ARGS: "--auth-host=scram-sha-256 --data-checksums"
|
||||
command: ["postgres", "-c", "max_connections=${PG_MAX_CONNECTIONS:-100}"]
|
||||
secrets: [postgres_password]
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger -h 127.0.0.1"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
start_period: 10s
|
||||
networks: [data]
|
||||
shm_size: 256m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 30s
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${PG_CPUS:-1.0}", memory: 1G}
|
||||
|
||||
# Redis — общий кэш сессий без persistence; источник истины сессий — PostgreSQL.
|
||||
redis:
|
||||
image: redis:7.4.2-alpine
|
||||
command:
|
||||
- sh
|
||||
- -c
|
||||
- |
|
||||
umask 077
|
||||
printf 'requirepass %s\n' "$$(cat /run/secrets/redis_password)" > /tmp/redis.conf
|
||||
exec redis-server /tmp/redis.conf --save '' --appendonly no --maxmemory 64mb --maxmemory-policy allkeys-lru
|
||||
user: redis
|
||||
secrets: [redis_password]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "REDISCLI_AUTH=\"$$(cat /run/secrets/redis_password)\" redis-cli ping | grep -q PONG"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 15
|
||||
networks: [data]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.25", memory: 128M}
|
||||
|
||||
# ===================================================================================== наблюдаемость (lab6)
|
||||
# OTel Collector: приём OTLP/HTTP от API/worker (сеть telemetry), обработка (memory_limiter, scrub, batch)
|
||||
# и экспорт в три хранилища (сеть observability). Ничего не публикуется на хост. Не хранит данные сам.
|
||||
# API/worker от Collector НЕ зависят (depends_on нет): без него бизнес-путь работает, telemetry теряется.
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.130.0
|
||||
command: ["--config=/etc/otelcol-contrib/${OTEL_COLLECTOR_CONFIG:-collector.yaml}"]
|
||||
volumes:
|
||||
- ./infra/otel:/etc/otelcol-contrib:ro
|
||||
environment:
|
||||
GOMEMLIMIT: 180MiB # мягкий лимит кучи Go ниже memory_limiter и лимита контейнера
|
||||
networks: [telemetry, observability]
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 10s # успеть отправить накопленные батчи
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "${COLLECTOR_CPUS:-0.5}", memory: 256M}
|
||||
|
||||
# Метрики: Prometheus 3.5 LTS. Приложение — push через Collector на OTLP receiver; компоненты
|
||||
# наблюдаемости — scrape. Правила SLI и алертов — infra/prometheus/rules (локальное firing/resolved).
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.5.0
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=7d
|
||||
- --storage.tsdb.retention.size=1GB
|
||||
- --web.enable-otlp-receiver # POST /api/v1/otlp/v1/metrics (только сеть observability)
|
||||
- --web.enable-remote-write-receiver # span-метрики/service graph от Tempo
|
||||
- --web.enable-lifecycle
|
||||
volumes:
|
||||
- ./infra/prometheus:/etc/prometheus:ro
|
||||
- promdata:/prometheus
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 10s
|
||||
networks: [observability]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
# Логи: Loki 3.5 (single binary, native OTLP). Volume lokidata, retention 7 дней.
|
||||
loki:
|
||||
image: grafana/loki:3.5.3
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
volumes:
|
||||
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- lokidata:/loki
|
||||
networks: [observability]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
# Трассы: Tempo 2.8 (monolithic). Образ работает от uid 10001 — one-shot tempo-init выдаёт права на volume.
|
||||
tempo-init:
|
||||
image: grafana/tempo:2.8.2
|
||||
user: root
|
||||
entrypoint: ["chown", "-R", "10001:10001", "/var/tempo"]
|
||||
volumes:
|
||||
- tempodata:/var/tempo
|
||||
network_mode: none
|
||||
restart: "no"
|
||||
tempo:
|
||||
image: grafana/tempo:2.8.2
|
||||
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||
volumes:
|
||||
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempodata:/var/tempo
|
||||
depends_on:
|
||||
tempo-init:
|
||||
condition: service_completed_successfully
|
||||
networks: [observability]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
# Grafana — интерфейс и запросы (данные не хранит, кроме своей БД настроек на volume grafanadata).
|
||||
# Datasources и dashboards импортируются из Git (provisioning); анонимного доступа нет; пароль admin —
|
||||
# secret. Опубликована только на 127.0.0.1. Недоступность Grafana не влияет на API (нет зависимостей).
|
||||
grafana:
|
||||
image: grafana/grafana:13.3.1
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password
|
||||
GF_SECURITY_DISABLE_GRAVATAR: "true"
|
||||
GF_AUTH_ANONYMOUS_ENABLED: "false"
|
||||
GF_USERS_ALLOW_SIGN_UP: "false"
|
||||
GF_ANALYTICS_REPORTING_ENABLED: "false"
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: "false"
|
||||
GF_ANALYTICS_CHECK_FOR_PLUGIN_UPDATES: "false"
|
||||
GF_PLUGINS_PREINSTALL_DISABLED: "true" # без загрузки плагинов из интернета
|
||||
GF_NEWS_NEWS_FEED_ENABLED: "false"
|
||||
GF_SERVER_ROOT_URL: http://127.0.0.1:${GRAFANA_PORT:-3000}/
|
||||
GF_LOG_LEVEL: warn
|
||||
secrets: [grafana_admin_password]
|
||||
volumes:
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/grafana/dashboards:/etc/grafana/dashboards:ro
|
||||
- grafanadata:/var/lib/grafana
|
||||
ports:
|
||||
- "127.0.0.1:${GRAFANA_PORT:-3000}:3000"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:3000/api/health || curl -fsS -o /dev/null http://127.0.0.1:3000/api/health"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
start_period: 20s
|
||||
depends_on:
|
||||
prometheus:
|
||||
condition: service_started
|
||||
loki:
|
||||
condition: service_started
|
||||
tempo:
|
||||
condition: service_started
|
||||
networks: [observability, ui]
|
||||
restart: unless-stopped
|
||||
deploy:
|
||||
resources:
|
||||
limits: {cpus: "0.5", memory: 512M}
|
||||
|
||||
networks:
|
||||
edge: {} # только LB: публикация портов на 127.0.0.1
|
||||
app:
|
||||
internal: true # LB ↔ API
|
||||
data:
|
||||
internal: true # API ↔ PostgreSQL/Redis
|
||||
objects:
|
||||
internal: true # API/worker ↔ S3 (SeaweedFS); PostgreSQL/Redis отсюда недоступны
|
||||
broker:
|
||||
internal: true # API/worker ↔ NATS
|
||||
telemetry:
|
||||
internal: true # API/worker → OTel Collector (OTLP :4318)
|
||||
observability:
|
||||
internal: true # Collector ↔ Prometheus/Loki/Tempo ↔ Grafana
|
||||
ui: {} # только Grafana: публикация 127.0.0.1:3000
|
||||
|
||||
volumes:
|
||||
pgdata: {}
|
||||
s3data: {} # объекты вложений (persistent)
|
||||
natsdata: {} # JetStream: принятые, но не подтверждённые задания (persistent)
|
||||
promdata: {} # метрики (TSDB, retention 7 дней / 1 ГБ)
|
||||
lokidata: {} # логи (retention 7 дней)
|
||||
tempodata: {} # трассы (retention 7 дней)
|
||||
grafanadata: {} # БД Grafana (пользователи/настройки; dashboards — из Git)
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
redis_password:
|
||||
file: ./secrets/redis_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cache_url:
|
||||
file: ./secrets/cache_url
|
||||
s3_config: # identities SeaweedFS: admin и api (права только на bucket)
|
||||
file: ./secrets/s3_config.json
|
||||
s3_admin_access_key_id:
|
||||
file: ./secrets/s3_admin_access_key_id
|
||||
s3_admin_secret_access_key:
|
||||
file: ./secrets/s3_admin_secret_access_key
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id
|
||||
s3_secret_access_key:
|
||||
file: ./secrets/s3_secret_access_key
|
||||
broker_url: # nats://messenger:<пароль>@nats:4222
|
||||
file: ./secrets/broker_url
|
||||
nats_config: # конфигурация nats-server с учётными данными
|
||||
file: ./secrets/nats.conf
|
||||
grafana_admin_password: # пароль пользователя admin Grafana
|
||||
file: ./secrets/grafana_admin_password
|
||||
@@ -0,0 +1,23 @@
|
||||
# Расширения решения (обратно совместимые)
|
||||
|
||||
Обязательный контракт (`openapi.json`, `README.md`) не изменён. Дополнительно реализовано:
|
||||
|
||||
| Что | Где | Семантика |
|
||||
| --- | --- | --- |
|
||||
| Заголовок ответа `Idempotent-Replayed: true` | `POST /api/v1/chats/{chat_id}/messages` | Ответ 201 — повтор ранее сохранённого результата по тому же `Idempotency-Key` (тело и код совпадают с первым ответом). Клиент может игнорировать. |
|
||||
| `GET /internal/stats` | только изнутри контейнера реплики (`127.0.0.1`); LB отвечает на `/internal/*` 404 в формате ошибок API | Диагностика для исследования: alias реплики, версия, счётчики запросов, кэша сессий и пула соединений psycopg. `python -m messenger stats` в контейнере. |
|
||||
| `GET /internal/stats` (lab4): `memory.rss_kib`/`peak_rss_kib` (VmRSS/VmHWM), `uploads_in_flight`, счётчики `uploads_*`, `compensations`, `janitor_removed`; `?reset_peak=1` сбрасывает VmHWM | изнутри контейнера: `python -m messenger stats [--reset-peak]` | Измерение пика памяти в эксперименте с одновременными загрузками. |
|
||||
| Ответ на `GET /api/v1/attachments/{id}/content`, если объект ready-вложения утрачен в S3 | API | `500 internal` «Содержимое вложения утрачено» (не маскируется под 404: метаданные есть, байтов нет). Пока S3 недоступен — `503 unavailable`. Для queued/processing/failed — `409 conflict` по контракту. |
|
||||
| `GET /internal/stats` (lab5): `broker` — подключение, сообщений в stream, pending/ack_pending/redelivered consumer'а; `app.outbox_published` | изнутри контейнера API | Наблюдение за очередью и relay. |
|
||||
| Заголовки ответа download | API | `Content-Type` из метаданных (проверен по содержимому), `Content-Length`, `ETag: "<sha256>"`, `X-Content-Type-Options: nosniff`, `Cache-Control: private, no-store`, `Content-Disposition: inline; filename*=UTF-8''…` (filename только для отображения). |
|
||||
| Операционные команды (не HTTP) | `python -m messenger s3-bootstrap \| s3-check \| broker-bootstrap \| worker \| jobs status\|failed\|replay\|reprocess\|invariants` | Bootstrap bucket и stream/consumer (one-shot сервисы, идемпотентно), процесс worker, операторские команды: журнал работы, реестр failed (DLQ), явный replay failed (ready — no-op), новая версия pipeline (трек 2), проверка инвариантов. Тестовые инструменты `jobs publish-raw` (дубли/reorder) и `jobs purge-stream` (потеря сообщений) — только для учебного стенда. |
|
||||
| Ответы, созданные самим LB (502/503/504/404 для `/internal/*`) | HAProxy | Тело в формате ошибок API с `request_id` = `X-Request-Id` (случайный uuid). `X-Instance-Id` у них нет — контракт это допускает. |
|
||||
|
||||
Область ключа идемпотентности: пользователь + `POST` + `/api/v1/chats/{chat_id}/messages` + ключ. Других
|
||||
идемпотентных endpoint в обязательном API нет, поэтому хранится тройка `(user_id, chat_id, key)`.
|
||||
Срок хранения — `IDEMPOTENCY_TTL_SECONDS` (по умолчанию 86 400 с = 24 ч).
|
||||
| Сообщение задания (jobs.schema.json) | NATS JetStream, subject `attachments.process.v1`, stream `ATTACHMENT_JOBS` | Поля строго по схеме v1 (`schema_version, job_id, type, attachment_id, pipeline_version, attempt, created_at` и необязательные `traceparent`/`tracestate`); заголовок `Nats-Msg-Id: outbox-<id>` — дедупликация повторной публикации. Байтов, URL и credentials нет. |
|
||||
| Trace context задания (lab6) | payload + native headers NATS | `traceparent`/`tracestate` в payload — контекст span «create» (сохраняется в outbox в транзакции upload, переживает рестарты и повторы); заголовки NATS `traceparent`/`tracestate` — контекст span «send» relay. Worker берёт родителя из заголовков (если нет — из payload) и ставит link на контекст payload. Отображение: W3C carrier ↔ поля payload/headers с теми же именами. |
|
||||
| Учебные отказы API (lab6) | `POST /api/v1/chats/{chat_id}/messages`, только при `FAULT_HOOKS=lab` | Маркер `fault-api-error` в тексте → 500 (ничего не записано), `fault-api-slow-<мс>` → задержка обработчика (≤ 5 с). Нужны для трека 1 и разбора инцидентов; в боевой конфигурации `FAULT_HOOKS` пуст и маркеры — обычный текст. |
|
||||
| Входящий `traceparent` клиента | публичный API | Не принимается: каждый внешний запрос начинает новый trace (клиент не может навязать trace/sampling). Связь запроса с логом — `X-Request-Id` (поле `request_id` лога и атрибут `messenger.request_id` server span). |
|
||||
| Состояние `superseded` работы | только в БД (`attachment_jobs.status`), не в публичном API | Работа старой версии pipeline, обогнанная новой (трек 2): результат не публикуется, указатель версии не откатывается. |
|
||||
@@ -0,0 +1,112 @@
|
||||
# Runbooks алертов мессенджера (lab6)
|
||||
|
||||
Как найти причину **только по сохранённым наблюдениям** (Grafana → Prometheus/Loki/Tempo), не заходя в контейнеры.
|
||||
Все ссылки ниже — в Grafana `http://127.0.0.1:3000` (логин `admin`, пароль — `secrets/grafana_admin_password`),
|
||||
dashboard **Messenger → «Messenger — обзор (lab6)»**. Правила — `infra/prometheus/rules/messenger.yml`,
|
||||
состояние — Grafana → Alerting → Alert rules (Data source-managed, Prometheus) или панель «Алерты» dashboard.
|
||||
|
||||
Общий порядок: **метрика** говорит, *что* и *насколько* плохо (и с какого момента) → **trace** — *где* в запросе
|
||||
тратится время или возникает ошибка → **лог** (по `trace_id`/`request_id`) — *почему* (текст ошибки, параметры).
|
||||
|
||||
| Алерт | Что означает | Первый вопрос |
|
||||
| --- | --- | --- |
|
||||
| ApiHighErrorRate | > 5% бизнес-запросов — 5xx | какая зависимость: `error.type` в trace |
|
||||
| ApiLatencyHigh | p95 > 250 мс (цель SLO) | БД или обработчик? |
|
||||
| DbSlowQueries | p95 запросов к PostgreSQL > 50 мс | БД медленная сама или перегружена? |
|
||||
| DbPoolSaturated | запросы ждут соединения пула | мало соединений или долгие запросы? |
|
||||
| JobQueueLagGrowing | доступное задание ждёт worker > 30 с | worker живы? заняты? |
|
||||
| WorkerHeartbeatMissing | нет метрик ни одного worker > 45 с | worker остановлены/упали? |
|
||||
| JobsFailing | финальные ошибки обработки | какие error_code? |
|
||||
| TelemetryExportFailing | Collector не может отправить в backend | какой backend недоступен? |
|
||||
| OtelCollectorDown | Collector не отвечает | telemetry не принимается |
|
||||
| TelemetryLostInSdk | SDK потерял spans/logs (после восстановления) | за какой интервал пробел в trace/логах |
|
||||
|
||||
## ApiHighErrorRate
|
||||
|
||||
1. Dashboard → «Ответы по классу статуса»: 5xx растут на всех маршрутах (зависимость) или на одном (код маршрута)?
|
||||
2. Панель «Трассы с ошибками» (TraceQL `{ resource.service.name =~ "messenger-.*" && status = error }`) →
|
||||
открыть trace → атрибут `error.type` server span: `PoolTimeout`/`TooManyRequests` — пул БД не выдаёт
|
||||
соединение (БД недоступна/медленная), `OperationalError`/`QueryCanceled` — ошибка/таймаут запроса,
|
||||
`S3Unavailable` — S3, `RuntimeError` и др. — ошибка кода.
|
||||
3. Loki: `{service_name="messenger-api"} | event="dependency.unavailable"` — поле `error` даёт то же по каждому
|
||||
запросу; `| event="http.unhandled_error"` — необработанные исключения (тип в `exception.type`).
|
||||
4. Проверить зависимость: «Пул БД: занято/максимум/ждут», «PostgreSQL: p95 по операции».
|
||||
5. После устранения 5xx пропадают за ≈ 1 мин (окно rate), алерт — resolved.
|
||||
|
||||
## ApiLatencyHigh
|
||||
|
||||
Главный вопрос — **медленная БД или медленный обработчик**:
|
||||
|
||||
| Наблюдение | Медленная БД | Медленный обработчик (CPU/код) |
|
||||
| --- | --- | --- |
|
||||
| «PostgreSQL: p95 по операции» | растёт вместе с HTTP p95 | без изменений (единицы мс) |
|
||||
| Алерт DbSlowQueries | firing | нет |
|
||||
| Trace медленного запроса | время внутри spans `INSERT …`/`SELECT …`/`pool.check` (db.system.name=postgresql) | время в server span **вне** дочерних spans |
|
||||
| Пул БД | used растёт, могут появиться waiting | без изменений |
|
||||
|
||||
Дальше: «p95 по маршруту» — какой маршрут; в trace — самый длинный дочерний span. `password.verify`/`password.hash`
|
||||
(scrypt, ~0.1–0.3 с) — норма для входа/регистрации, они в SLI задержки не входят. Атрибут `messenger.kdf.wait_ms`
|
||||
показывает очередь к KDF (KDF_CONCURRENCY).
|
||||
|
||||
## DbSlowQueries
|
||||
|
||||
1. «PostgreSQL: p95 по операции»: замедлились все операции (ресурсы БД: CPU/диск/блокировки) или одна (план запроса).
|
||||
2. «CPU контейнеров»/«Память контейнеров» не покрывают PostgreSQL (у него нет SDK) — смотрите `docker stats`
|
||||
или лимиты (`docker inspect … NanoCpus`); на учебном стенде инцидент воспроизводится `docker update --cpus 0.03`.
|
||||
3. Trace медленного запроса: какие именно statements (`db.query.summary`) долгие; `pool.check` долгий —
|
||||
даже пустой запрос медленный → проблема сервера БД, а не SQL.
|
||||
4. Если растут только `UPDATE/SELECT … FOR UPDATE` — блокировки (lock_timeout 2 с даст 503 с `LockNotAvailable`).
|
||||
|
||||
## DbPoolSaturated
|
||||
|
||||
1. «Пул БД»: used = max и waiting > 0 → соединений не хватает. Вместе с DbSlowQueries — запросы долгие (лечить БД);
|
||||
без него — мало соединений для нагрузки (DB_POOL_MAX, но не больше PG max_connections / реплики).
|
||||
2. «Ожидание соединения пула и таймауты»: таймауты → клиенты получают 503 (см. ApiHighErrorRate).
|
||||
3. В trace — span `pool.acquire`: сколько запрос ждал соединение.
|
||||
|
||||
## JobQueueLagGrowing
|
||||
|
||||
1. «Глубина очереди по состоянию»: `ready` растёт — задания есть, но их не забирают.
|
||||
2. «Worker: занятые слоты / ёмкость»: capacity = 0 — worker нет (см. WorkerHeartbeatMissing); busy = capacity —
|
||||
worker перегружены (медленная обработка: «Длительность попытки», trace `imgproc.run`) → масштабировать worker.
|
||||
3. «Брокер и outbox»: `outbox: не опубликовано` растёт — разрыв DB→broker (NATS недоступен; лог
|
||||
`event="outbox publish failed; will retry"` в Loki); `NATS: не выдано` растёт при живых worker — проблема consumer.
|
||||
4. Восстановление: после возврата worker backlog уменьшается, lag → 0, алерт resolved. Потерь нет: задания в
|
||||
PostgreSQL/JetStream (проверка — `make jobs-invariants`).
|
||||
|
||||
## WorkerHeartbeatMissing
|
||||
|
||||
1. Метрики worker не приходят: `docker compose ps worker` (остановлен/перезапускается?), логи
|
||||
`{service_name="messenger-worker"}` — последний `worker stopping`/ошибка конфигурации.
|
||||
2. Если worker работают, а метрик нет — проблема экспорта telemetry (см. OtelCollectorDown).
|
||||
3. `make start-worker` — запустить; backlog разберётся автоматически.
|
||||
|
||||
## JobsFailing
|
||||
|
||||
1. `python -m messenger jobs failed` (или `make jobs-failed`) — реестр failed с error_code.
|
||||
2. Loki: `{service_name="messenger-worker"} | event="job.attempt_failed"` — по каким `error_code`; trace задания
|
||||
(`{ span.messenger.attachment.id = "<id>" }`) показывает все попытки и где упала каждая.
|
||||
3. `invalid_image` — данные клиента (норма); `retry_exhausted`/`storage_unavailable` — зависимость; после
|
||||
устранения — `python -m messenger jobs replay --all-failed --error-code retry_exhausted --reason "…"`.
|
||||
|
||||
## TelemetryExportFailing
|
||||
|
||||
1. Dashboard → «Collector: принято/отправлено/ошибки» и «Очереди экспортёров»: у какого экспортёра
|
||||
(`otlphttp/tempo`, `otlphttp/loki`, `otlphttp/prometheus`) растёт очередь.
|
||||
2. Проверить backend: Grafana → Connections → Data sources → Test.
|
||||
3. Пока backend недоступен, батчи ждут в ограниченной очереди (200 батчей) и повторяются до 120 с; дальше —
|
||||
отбрасываются (`otelcol_exporter_send_failed_*`). Бизнес-API не затронут. После восстановления очередь
|
||||
опустошается, алерт resolved; потерянное за интервал перечислено счётчиками.
|
||||
|
||||
## OtelCollectorDown
|
||||
|
||||
1. `docker compose ps otel-collector`, его логи (stdout контейнера).
|
||||
2. Пока Collector недоступен, SDK отбрасывает пакеты экспорта (очереди 2048 spans/logs на процесс) — память
|
||||
API/worker не растёт, запросы не замедляются (экспорт в фоновом потоке).
|
||||
3. После `docker compose start otel-collector` сработает TelemetryLostInSdk — количество потерянного.
|
||||
|
||||
## TelemetryLostInSdk
|
||||
|
||||
Информационный: за последние 5 мин SDK не смог экспортировать или отбросил spans/logs (`error_type`:
|
||||
`MaxRetryError` — Collector недоступен, `queue_full` — очередь SDK переполнена). Trace/логи этого интервала
|
||||
неполны; метрики RED не потеряны (кумулятивные счётчики восстановятся при следующем экспорте).
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc logs --no-log-prefix broker-init
|
||||
{"ts": "2026-11-21T18:57:54.272Z", "level": "warning", "service": "messenger", "logger": "messenger.broker", "event": "broker disconnected", "msg": "broker disconnected"}
|
||||
{"created": {"stream": true, "consumer": true}, "stream": {"name": "ATTACHMENT_JOBS", "subjects": ["attachments.process.v1"], "storage": "file", "retention": "workqueue", "duplicate_window_s": 120.0, "max_msgs": 100000, "messages": 0}, "consumer": {"durable": "attachment-workers", "ack_policy": "explicit", "ack_wait_s": 20.0, "max_ack_pending": 16, "max_deliver": -1}}
|
||||
exit=0
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-11-21T18:58:16Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml
|
||||
Container mtusi-lab6-otel-collector-run-305dad94c299 Creating
|
||||
Container mtusi-lab6-otel-collector-run-305dad94c299 Created
|
||||
exit=0
|
||||
@@ -0,0 +1,33 @@
|
||||
# 2026-11-21T20:04:22Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/defense_demo.py
|
||||
20:04:24.055 0 chat 4e63a603-914c-4f47-84d9-6f71057ad639, users alice/bob (tokens not shown)
|
||||
20:04:24.835 0 mtusi-lab6-api-1 running started=2026-11-21T19:59:25.880108847Z pid=2790
|
||||
20:04:24.835 0 mtusi-lab6-api-2 running started=2026-11-21T19:59:26.237488123Z pid=2867
|
||||
20:04:24.835 0 mtusi-lab6-worker-1 running started=2026-11-21T19:59:26.716469278Z pid=2986
|
||||
20:04:24.835 0 mtusi-lab6-worker-2 running started=2026-11-21T19:59:27.326051972Z pid=3041
|
||||
20:04:24.835 0 mtusi-lab6-nats-1 running started=2026-11-21T19:22:35.290602429Z pid=17585
|
||||
20:04:24.835 2 stop worker: docker compose --env-file .env stop worker
|
||||
20:04:25.804 2 mtusi-lab6-worker-1 exited started=2026-11-21T19:59:26.716469278Z pid=0
|
||||
20:04:25.804 2 mtusi-lab6-worker-2 exited started=2026-11-21T19:59:27.326051972Z pid=0
|
||||
20:04:25.844 2 POST /chats/4e63a603-914c-4f47-84d9-6f71057ad639/attachments → 202, attachment_id=5b856079-7c1e-4ee6-af16-55ea0fb2ecd4 status=queued
|
||||
20:04:26.655 2 job_id=f921ca14-cc40-4095-b8e2-947cda3536c7 pipeline_version=1 attempt=1 status=queued
|
||||
20:04:26.660 2 GET /attachments/5b856079-7c1e-4ee6-af16-55ea0fb2ecd4/content → 409 (conflict)
|
||||
20:04:26.669 2 POST message with queued attachment → 201, message_id=b5591933-2e47-4a34-ac47-3fc0e74efa09
|
||||
20:04:26.676 2 POST plain message (bob) → 201, message_id=997c604c-7e4e-4905-b77b-1cb751db2d6f; history works while worker is down
|
||||
20:04:27.372 2 job published to JetStream: stream_seq=786 (outbox → relay → publish ack)
|
||||
20:04:27.372 3 restart broker (volume natsdata kept) and API replicas: restart nats; restart api
|
||||
20:04:33.763 3 mtusi-lab6-api-1 running started=2026-11-21T20:04:31.946056134Z pid=25862
|
||||
20:04:33.763 3 mtusi-lab6-api-2 running started=2026-11-21T20:04:31.715486281Z pid=25806
|
||||
20:04:33.763 3 mtusi-lab6-nats-1 running started=2026-11-21T20:04:27.663048481Z pid=25426
|
||||
20:04:33.771 3 after restart: attachment 5b856079-7c1e-4ee6-af16-55ea0fb2ecd4 status=queued (job survived in PostgreSQL + JetStream)
|
||||
20:04:33.771 3 start worker: docker compose --env-file .env start worker
|
||||
20:04:43.551 3 attachment 5b856079-7c1e-4ee6-af16-55ea0fb2ecd4 status=ready 1.6s after worker start; variants=['crop 128x128', 'optimized 320x200', 'thumbnail 256x160']
|
||||
20:04:43.710 3 original sha256=8355144458298115… (= uploaded), thumbnail JPEG (256, 160)
|
||||
20:04:44.426 log 20:04:25.840 enqueued attempt=1 token=None {'outbox_id': 744}
|
||||
20:04:44.426 log 20:04:25.847 published attempt=1 token=None {'relay': 'api-api-a0e7e8a8', 'duplicate': False, 'outbox_id': 744, 'stream_seq': 786}
|
||||
20:04:44.426 log 20:04:43.087 claimed attempt=1 token=779 {'claims': 1}
|
||||
20:04:44.426 log 20:04:43.463 committed attempt=1 token=779 {'variants': ['crop', 'optimized', 'thumbnail']}
|
||||
20:04:44.426 log 20:04:43.463 published_version_changed attempt=1 token=779 {'to': 1, 'from': None}
|
||||
20:04:44.426 log 20:04:43.469 staging_cleaned attempt=1 token=None {'after': 'ready'}
|
||||
PASS: defense scenario (worker down → 202 → 409 → restart API+broker → worker → ready)
|
||||
exit=0
|
||||
@@ -0,0 +1,6 @@
|
||||
# 2026-11-21T19:19:16Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://127.0.0.1:8080
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 131, "failed_attempts": 0, "first_recovery_seconds": 6.14}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
@@ -0,0 +1,6 @@
|
||||
# 2026-11-21T19:19:41Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url http://127.0.0.1:8080
|
||||
Executing explicit failover hook; hook output suppressed to avoid leaking secrets.
|
||||
{"observed_instances_before": 2, "successful_writes": 134, "failed_attempts": 0, "first_recovery_seconds": 6.155}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
@@ -0,0 +1,80 @@
|
||||
== 2026-11-21T19:19:19Z stop-one target=api-e4ae9e90 container=mtusi-lab6-api-2
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662
|
||||
api mtusi-lab6-api-2 status=running started=2026-11-21T18:59:39.827025415Z pid=11715
|
||||
api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265
|
||||
broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0
|
||||
grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695
|
||||
lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973
|
||||
loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940
|
||||
migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0
|
||||
nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466
|
||||
otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597
|
||||
postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614
|
||||
prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552
|
||||
redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550
|
||||
s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960
|
||||
s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0
|
||||
tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112
|
||||
tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0
|
||||
worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409
|
||||
worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486
|
||||
== 2026-11-21T19:19:24Z after stop
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662
|
||||
api mtusi-lab6-api-2 status=exited started=2026-11-21T18:59:39.827025415Z pid=0
|
||||
api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265
|
||||
broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0
|
||||
grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695
|
||||
lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973
|
||||
loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940
|
||||
migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0
|
||||
nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466
|
||||
otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597
|
||||
postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614
|
||||
prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552
|
||||
redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550
|
||||
s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960
|
||||
s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0
|
||||
tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112
|
||||
tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0
|
||||
worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409
|
||||
worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486
|
||||
== 2026-11-21T19:19:44Z stop-one target=api-351cef98 container=mtusi-lab6-api-2
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662
|
||||
api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:34.682252358Z pid=30558
|
||||
api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265
|
||||
broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0
|
||||
grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695
|
||||
lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973
|
||||
loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940
|
||||
migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0
|
||||
nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466
|
||||
otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597
|
||||
postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614
|
||||
prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552
|
||||
redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550
|
||||
s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960
|
||||
s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0
|
||||
tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112
|
||||
tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0
|
||||
worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409
|
||||
worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486
|
||||
== 2026-11-21T19:19:49Z after stop
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662
|
||||
api mtusi-lab6-api-2 status=exited started=2026-11-21T19:19:34.682252358Z pid=0
|
||||
api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265
|
||||
broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0
|
||||
grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695
|
||||
lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973
|
||||
loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940
|
||||
migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0
|
||||
nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466
|
||||
otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597
|
||||
postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614
|
||||
prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552
|
||||
redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550
|
||||
s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960
|
||||
s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0
|
||||
tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112
|
||||
tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0
|
||||
worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409
|
||||
worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 214 KiB |
@@ -0,0 +1,63 @@
|
||||
# 2026-11-21T20:10:18Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/incidents.py collector-down --out evidence/incidents
|
||||
[23:10:32] collector-down: otel-collector stopped (t=13.9s)
|
||||
[23:11:08] FIRING OtelCollectorDown at t=50.3s
|
||||
[23:11:08] collector-down: OtelCollectorDown firing (t=50.3s)
|
||||
[23:12:05] collector-down: otel-collector started (t=107.1s)
|
||||
[23:12:21] FIRING TelemetryLostInSdk at t=122.9s
|
||||
[23:12:21] resolved OtelCollectorDown at t=122.9s
|
||||
[23:12:21] collector-down: collector back; SDK losses reported (t=122.9s)
|
||||
{
|
||||
"scenario": "collector-down",
|
||||
"marks_s": {
|
||||
"otel-collector stopped": 13.9,
|
||||
"OtelCollectorDown firing": 50.3,
|
||||
"otel-collector started": 107.1,
|
||||
"collector back; SDK losses reported": 122.9
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"OtelCollectorDown": 50.3,
|
||||
"TelemetryLostInSdk": 122.9
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"OtelCollectorDown": 122.9
|
||||
},
|
||||
"http_before": {
|
||||
"requests": 108,
|
||||
"ok": 108,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 18.2,
|
||||
"p95_ms": 44.3,
|
||||
"p99_ms": 76.5
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 748,
|
||||
"ok": 748,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 12.5,
|
||||
"p95_ms": 40.4,
|
||||
"p99_ms": 64.8
|
||||
},
|
||||
"api_mem_before": {
|
||||
"8ebba9c6afb2": "46.98MiB",
|
||||
"5444178a6fc3": "47.37MiB"
|
||||
},
|
||||
"api_mem_during": {
|
||||
"8ebba9c6afb2": "53.61MiB",
|
||||
"5444178a6fc3": "54.21MiB"
|
||||
},
|
||||
"sdk_delta": {
|
||||
"spans_export_failed": 5712,
|
||||
"spans_queue_dropped": 0,
|
||||
"logs_export_failed": 715,
|
||||
"logs_queue_dropped": 0,
|
||||
"spans_started": 8311
|
||||
},
|
||||
"sdk_export_errors_by_type_total": {
|
||||
"MaxRetryError": 5712
|
||||
},
|
||||
"detection_s": 36.4
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,53 @@
|
||||
# 2026-11-21T19:08:20Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/incidents.py db-down --out evidence/incidents
|
||||
[22:08:37] db-down: postgres paused (t=16.0s)
|
||||
[22:09:23] FIRING DbPoolSaturated at t=62.2s
|
||||
[22:09:59] FIRING ApiHighErrorRate at t=98.0s
|
||||
[22:09:59] db-down: ApiHighErrorRate firing (t=98.0s)
|
||||
[22:09:59] db-down: postgres unpaused (t=98.0s)
|
||||
[22:10:09] resolved DbPoolSaturated at t=108.5s
|
||||
[22:10:29] FIRING ApiLatencyHigh at t=128.9s
|
||||
[22:11:10] resolved ApiHighErrorRate at t=169.8s
|
||||
[22:11:10] resolved ApiLatencyHigh at t=169.8s
|
||||
[22:11:10] db-down: resolved (t=169.8s)
|
||||
{
|
||||
"scenario": "db-down",
|
||||
"marks_s": {
|
||||
"postgres paused": 16.0,
|
||||
"ApiHighErrorRate firing": 98.0,
|
||||
"postgres unpaused": 98.0,
|
||||
"resolved": 169.8
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"DbPoolSaturated": 62.2,
|
||||
"ApiHighErrorRate": 98.0,
|
||||
"ApiLatencyHigh": 128.9
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"DbPoolSaturated": 108.5,
|
||||
"ApiHighErrorRate": 169.8,
|
||||
"ApiLatencyHigh": 169.8
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 136,
|
||||
"ok": 0,
|
||||
"errors": 136,
|
||||
"error_statuses": [
|
||||
-1,
|
||||
503
|
||||
],
|
||||
"p50_ms": null,
|
||||
"p95_ms": null,
|
||||
"p99_ms": null
|
||||
},
|
||||
"error_traces_error_type": {
|
||||
"PoolTimeout": 20
|
||||
},
|
||||
"dependency_unavailable_logs": 136,
|
||||
"logged_errors": [
|
||||
"PoolTimeout",
|
||||
"TimeoutError"
|
||||
],
|
||||
"detection_s": 82.0
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,83 @@
|
||||
# 2026-11-21T19:02:34Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/incidents.py db-slow --out evidence/incidents
|
||||
[22:03:05] db-slow: postgres limited to 0.03 CPU (t=31.1s)
|
||||
[22:04:02] FIRING DbSlowQueries at t=87.6s
|
||||
[22:04:02] db-slow: DbSlowQueries firing (t=87.6s)
|
||||
[22:04:33] FIRING ApiLatencyHigh at t=118.5s
|
||||
[22:04:34] db-slow: postgres restored to 1.0 CPU (t=119.2s)
|
||||
[22:05:30] resolved DbSlowQueries at t=175.5s
|
||||
[22:05:40] resolved ApiLatencyHigh at t=185.7s
|
||||
[22:05:40] db-slow: resolved (t=185.7s)
|
||||
{
|
||||
"scenario": "db-slow",
|
||||
"marks_s": {
|
||||
"postgres limited to 0.03 CPU": 31.1,
|
||||
"DbSlowQueries firing": 87.6,
|
||||
"postgres restored to 1.0 CPU": 119.2,
|
||||
"resolved": 185.7
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"DbSlowQueries": 87.6,
|
||||
"ApiLatencyHigh": 118.5
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"DbSlowQueries": 175.5,
|
||||
"ApiLatencyHigh": 185.7
|
||||
},
|
||||
"metrics_before": {
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0425,
|
||||
"db_p95_s": 0.0035,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.6914
|
||||
},
|
||||
"metrics_during": {
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.717,
|
||||
"db_p95_s": 0.222,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.6094
|
||||
},
|
||||
"slow_trace": {
|
||||
"trace_id": "0a0efea457d22fb0b498b9fe612a9696",
|
||||
"duration_ms": 702.1,
|
||||
"db_ms": 694.4,
|
||||
"pool_wait_ms": 192.0,
|
||||
"db_share": 0.99,
|
||||
"db_or_pool_share": 1.26,
|
||||
"not_in_child_spans_ms": 7.1,
|
||||
"error_type": null,
|
||||
"slowest_child": [
|
||||
"INSERT messages",
|
||||
300.8
|
||||
]
|
||||
},
|
||||
"http_before": {
|
||||
"requests": 180,
|
||||
"ok": 180,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 11.8,
|
||||
"p95_ms": 37.6,
|
||||
"p99_ms": 80.0
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 516,
|
||||
"ok": 516,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 132.6,
|
||||
"p95_ms": 698.8,
|
||||
"p99_ms": 964.9
|
||||
},
|
||||
"detection_s": 56.5
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,58 @@
|
||||
# 2026-11-21T19:05:40Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/incidents.py handler-slow --out evidence/incidents
|
||||
[22:05:41] handler-slow: 50% of messages carry fault-api-slow-400 (sleep in handler) (t=0.6s)
|
||||
[22:07:08] FIRING ApiLatencyHigh at t=87.8s
|
||||
[22:07:08] handler-slow: ApiLatencyHigh firing (t=87.8s)
|
||||
[22:08:20] resolved ApiLatencyHigh at t=160.2s
|
||||
[22:08:20] handler-slow: resolved (t=160.2s)
|
||||
{
|
||||
"scenario": "handler-slow",
|
||||
"marks_s": {
|
||||
"50% of messages carry fault-api-slow-400 (sleep in handler)": 0.6,
|
||||
"ApiLatencyHigh firing": 87.8,
|
||||
"resolved": 160.2
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"ApiLatencyHigh": 87.8
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"ApiLatencyHigh": 160.2
|
||||
},
|
||||
"metrics_during": {
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0026,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.0938
|
||||
},
|
||||
"db_alert_fired": false,
|
||||
"slow_trace": {
|
||||
"trace_id": "2aa39fd46f97f6a25232626dcb3aa263",
|
||||
"duration_ms": 421.9,
|
||||
"db_ms": 12.2,
|
||||
"pool_wait_ms": 3.8,
|
||||
"db_share": 0.03,
|
||||
"db_or_pool_share": 0.04,
|
||||
"not_in_child_spans_ms": 409.2,
|
||||
"error_type": null,
|
||||
"slowest_child": [
|
||||
"INSERT messages",
|
||||
6.6
|
||||
]
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 526,
|
||||
"ok": 526,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 66.4,
|
||||
"p95_ms": 421.4,
|
||||
"p99_ms": 440.7
|
||||
},
|
||||
"detection_s": 87.8
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,59 @@
|
||||
# 2026-11-21T19:11:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/incidents.py telemetry-down --out evidence/incidents
|
||||
[22:11:33] telemetry-down: tempo and loki stopped (t=21.8s)
|
||||
[22:12:40] FIRING TelemetryExportFailing at t=89.0s
|
||||
[22:12:40] telemetry-down: TelemetryExportFailing firing (t=89.0s)
|
||||
[22:13:42] telemetry-down: tempo and loki started (t=150.2s)
|
||||
[22:13:59] resolved TelemetryExportFailing at t=167.2s
|
||||
[22:14:04] telemetry-down: resolved, queue drained (t=172.3s)
|
||||
{
|
||||
"scenario": "telemetry-down",
|
||||
"marks_s": {
|
||||
"tempo and loki stopped": 21.8,
|
||||
"TelemetryExportFailing firing": 89.0,
|
||||
"tempo and loki started": 150.2,
|
||||
"resolved, queue drained": 172.3
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"TelemetryExportFailing": 89.0
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"TelemetryExportFailing": 167.2
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 772,
|
||||
"ok": 772,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 13.1,
|
||||
"p95_ms": 40.2,
|
||||
"p99_ms": 76.7
|
||||
},
|
||||
"uploads_during": {
|
||||
"requests": 42,
|
||||
"ok": 42,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 26.6,
|
||||
"p95_ms": 48.3,
|
||||
"p99_ms": 217.8
|
||||
},
|
||||
"collector_mem_before": {
|
||||
"ac5a65d675df": "50.21MiB"
|
||||
},
|
||||
"collector_mem_during": {
|
||||
"ac5a65d675df": "54.82MiB"
|
||||
},
|
||||
"exporter_queue_max": 64.0,
|
||||
"exporter_queue_capacity": 200.0,
|
||||
"telemetry_delta": {
|
||||
"accepted_spans": 9907,
|
||||
"send_failed_spans": 275,
|
||||
"enqueue_failed_spans": 0,
|
||||
"send_failed_logs": 30,
|
||||
"enqueue_failed_logs": 0
|
||||
},
|
||||
"traces_from_outage_window_found_after_recovery": 200,
|
||||
"detection_s": 67.2
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,50 @@
|
||||
# 2026-11-21T18:59:53Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/incidents.py worker-stop --out evidence/incidents
|
||||
[22:00:14] worker-stop: worker stopped (t=20.7s)
|
||||
[22:01:31] FIRING JobQueueLagGrowing at t=98.3s
|
||||
[22:01:31] FIRING WorkerHeartbeatMissing at t=98.3s
|
||||
[22:01:31] worker-stop: both alerts firing (t=98.3s)
|
||||
[22:01:46] worker-stop: worker started (t=113.3s)
|
||||
[22:02:11] resolved WorkerHeartbeatMissing at t=138.0s
|
||||
[22:02:32] resolved JobQueueLagGrowing at t=158.5s
|
||||
[22:02:32] worker-stop: alerts resolved, backlog empty (t=158.5s)
|
||||
{
|
||||
"scenario": "worker-stop",
|
||||
"marks_s": {
|
||||
"worker stopped": 20.7,
|
||||
"both alerts firing": 98.3,
|
||||
"worker started": 113.3,
|
||||
"alerts resolved, backlog empty": 158.5
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"JobQueueLagGrowing": 98.3,
|
||||
"WorkerHeartbeatMissing": 98.3
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"WorkerHeartbeatMissing": 138.0,
|
||||
"JobQueueLagGrowing": 158.5
|
||||
},
|
||||
"uploads_accepted": 78,
|
||||
"uploads_not_ready_after_recovery": 0,
|
||||
"queue_ready_peak": 34.0,
|
||||
"api_accepted_logs_during_outage": 46,
|
||||
"worker_logs_during_outage": 0,
|
||||
"detection_s": {
|
||||
"JobQueueLagGrowing": 77.6,
|
||||
"WorkerHeartbeatMissing": 77.6
|
||||
},
|
||||
"recovery_s": {
|
||||
"JobQueueLagGrowing": 45.2,
|
||||
"WorkerHeartbeatMissing": 24.7
|
||||
},
|
||||
"http_during_outage": {
|
||||
"requests": 276,
|
||||
"ok": 276,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 15.4,
|
||||
"p95_ms": 37.4,
|
||||
"p99_ms": 75.3
|
||||
}
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,240 @@
|
||||
{
|
||||
"scenario": "collector-down",
|
||||
"marks_s": {
|
||||
"otel-collector stopped": 13.9,
|
||||
"OtelCollectorDown firing": 50.3,
|
||||
"otel-collector started": 107.1,
|
||||
"collector back; SDK losses reported": 122.9
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"OtelCollectorDown": 50.3,
|
||||
"TelemetryLostInSdk": 122.9
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"OtelCollectorDown": 122.9
|
||||
},
|
||||
"http_before": {
|
||||
"requests": 108,
|
||||
"ok": 108,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 18.2,
|
||||
"p95_ms": 44.3,
|
||||
"p99_ms": 76.5
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 748,
|
||||
"ok": 748,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 12.5,
|
||||
"p95_ms": 40.4,
|
||||
"p99_ms": 64.8
|
||||
},
|
||||
"api_mem_before": {
|
||||
"8ebba9c6afb2": "46.98MiB",
|
||||
"5444178a6fc3": "47.37MiB"
|
||||
},
|
||||
"api_mem_during": {
|
||||
"8ebba9c6afb2": "53.61MiB",
|
||||
"5444178a6fc3": "54.21MiB"
|
||||
},
|
||||
"sdk_delta": {
|
||||
"spans_export_failed": 5712,
|
||||
"spans_queue_dropped": 0,
|
||||
"logs_export_failed": 715,
|
||||
"logs_queue_dropped": 0,
|
||||
"spans_started": 8311
|
||||
},
|
||||
"sdk_export_errors_by_type_total": {
|
||||
"MaxRetryError": 5712
|
||||
},
|
||||
"detection_s": 36.4,
|
||||
"timeline": [
|
||||
{
|
||||
"t": 0.6,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0228,
|
||||
"db_p95_s": 0.0041,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 183.6406
|
||||
},
|
||||
{
|
||||
"t": 14.5,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0231,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 183.6523
|
||||
},
|
||||
{
|
||||
"t": 19.6,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0231,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 183.6523
|
||||
},
|
||||
{
|
||||
"t": 24.7,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0235,
|
||||
"db_p95_s": 0.0042,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": null,
|
||||
"collector_rss_mib": null
|
||||
},
|
||||
{
|
||||
"t": 29.8,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0235,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": null,
|
||||
"collector_rss_mib": null
|
||||
},
|
||||
{
|
||||
"t": 34.9,
|
||||
"alerts": {
|
||||
"OtelCollectorDown": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0213,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": null,
|
||||
"collector_rss_mib": null
|
||||
},
|
||||
{
|
||||
"t": 40.0,
|
||||
"alerts": {
|
||||
"OtelCollectorDown": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0213,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": null,
|
||||
"collector_rss_mib": null
|
||||
},
|
||||
{
|
||||
"t": 45.1,
|
||||
"alerts": {
|
||||
"OtelCollectorDown": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0235,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": null,
|
||||
"collector_queue": null,
|
||||
"collector_rss_mib": null
|
||||
},
|
||||
{
|
||||
"t": 50.3,
|
||||
"alerts": {
|
||||
"OtelCollectorDown": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0235,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": null,
|
||||
"collector_queue": null,
|
||||
"collector_rss_mib": null
|
||||
},
|
||||
{
|
||||
"t": 107.6,
|
||||
"alerts": {
|
||||
"OtelCollectorDown": "firing"
|
||||
},
|
||||
"error_ratio": null,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": null,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": null,
|
||||
"collector_queue": null,
|
||||
"collector_rss_mib": null
|
||||
},
|
||||
{
|
||||
"t": 112.7,
|
||||
"alerts": {
|
||||
"OtelCollectorDown": "firing"
|
||||
},
|
||||
"error_ratio": null,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": null,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 159.4648
|
||||
},
|
||||
{
|
||||
"t": 117.8,
|
||||
"alerts": {
|
||||
"OtelCollectorDown": "firing"
|
||||
},
|
||||
"error_ratio": null,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": null,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 159.4648
|
||||
},
|
||||
{
|
||||
"t": 122.9,
|
||||
"alerts": {
|
||||
"TelemetryLostInSdk": "firing"
|
||||
},
|
||||
"error_ratio": null,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 163.0742
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
{
|
||||
"scenario": "db-down",
|
||||
"marks_s": {
|
||||
"postgres paused": 16.0,
|
||||
"ApiHighErrorRate firing": 98.0,
|
||||
"postgres unpaused": 98.0,
|
||||
"resolved": 169.8
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"DbPoolSaturated": 62.2,
|
||||
"ApiHighErrorRate": 98.0,
|
||||
"ApiLatencyHigh": 128.9
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"DbPoolSaturated": 108.5,
|
||||
"ApiHighErrorRate": 169.8,
|
||||
"ApiLatencyHigh": 169.8
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 136,
|
||||
"ok": 0,
|
||||
"errors": 136,
|
||||
"error_statuses": [
|
||||
-1,
|
||||
503
|
||||
],
|
||||
"p50_ms": null,
|
||||
"p95_ms": null,
|
||||
"p99_ms": null
|
||||
},
|
||||
"error_traces_error_type": {
|
||||
"PoolTimeout": 20
|
||||
},
|
||||
"dependency_unavailable_logs": 136,
|
||||
"logged_errors": [
|
||||
"PoolTimeout",
|
||||
"TimeoutError"
|
||||
],
|
||||
"detection_s": 82.0,
|
||||
"timeline": [
|
||||
{
|
||||
"t": 1.0,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": 0.0022,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.2734
|
||||
},
|
||||
{
|
||||
"t": 16.3,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0236,
|
||||
"db_p95_s": 0.0036,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3008
|
||||
},
|
||||
{
|
||||
"t": 21.4,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0534,
|
||||
"db_p95_s": 0.0036,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3008
|
||||
},
|
||||
{
|
||||
"t": 26.5,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0534,
|
||||
"db_p95_s": 0.0038,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 13.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3008
|
||||
},
|
||||
{
|
||||
"t": 31.6,
|
||||
"alerts": {
|
||||
"DbPoolSaturated": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0459,
|
||||
"db_p95_s": 0.0039,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 13.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3008
|
||||
},
|
||||
{
|
||||
"t": 36.7,
|
||||
"alerts": {
|
||||
"DbPoolSaturated": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0459,
|
||||
"db_p95_s": 0.0041,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 40.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3008
|
||||
},
|
||||
{
|
||||
"t": 41.8,
|
||||
"alerts": {
|
||||
"DbPoolSaturated": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0459,
|
||||
"db_p95_s": 0.0042,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 40.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3203
|
||||
},
|
||||
{
|
||||
"t": 46.9,
|
||||
"alerts": {
|
||||
"DbPoolSaturated": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0459,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 81.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3203
|
||||
},
|
||||
{
|
||||
"t": 52.0,
|
||||
"alerts": {
|
||||
"DbPoolSaturated": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0459,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 81.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3281
|
||||
},
|
||||
{
|
||||
"t": 57.1,
|
||||
"alerts": {
|
||||
"DbPoolSaturated": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0459,
|
||||
"db_p95_s": 0.0045,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 123.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3281
|
||||
},
|
||||
{
|
||||
"t": 62.2,
|
||||
"alerts": {
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 0.2997,
|
||||
"api_p95_s": 2.2498,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 123.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3359
|
||||
},
|
||||
{
|
||||
"t": 67.3,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "pending",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 0.2997,
|
||||
"api_p95_s": 2.2498,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 165.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3359
|
||||
},
|
||||
{
|
||||
"t": 72.4,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "pending",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 0.6868,
|
||||
"api_p95_s": 2.3908,
|
||||
"db_p95_s": 5.0,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 197.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3438
|
||||
},
|
||||
{
|
||||
"t": 77.5,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "pending",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 0.6868,
|
||||
"api_p95_s": 2.3908,
|
||||
"db_p95_s": 5.0,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 205.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.3438
|
||||
},
|
||||
{
|
||||
"t": 82.7,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "pending",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 1.0,
|
||||
"api_p95_s": 2.425,
|
||||
"db_p95_s": 5.0,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 240.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4102
|
||||
},
|
||||
{
|
||||
"t": 87.8,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "pending",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 1.0,
|
||||
"api_p95_s": 2.425,
|
||||
"db_p95_s": null,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 247.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4102
|
||||
},
|
||||
{
|
||||
"t": 92.9,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "pending",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 1.0,
|
||||
"api_p95_s": 2.425,
|
||||
"db_p95_s": null,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 285.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4141
|
||||
},
|
||||
{
|
||||
"t": 98.0,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 1.0,
|
||||
"api_p95_s": 2.425,
|
||||
"db_p95_s": null,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 294.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4141
|
||||
},
|
||||
{
|
||||
"t": 98.3,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 1.0,
|
||||
"api_p95_s": 2.425,
|
||||
"db_p95_s": null,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": null,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 294.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4805
|
||||
},
|
||||
{
|
||||
"t": 103.4,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbPoolSaturated": "firing"
|
||||
},
|
||||
"error_ratio": 1.0,
|
||||
"api_p95_s": 2.425,
|
||||
"db_p95_s": 5.0,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 60.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4805
|
||||
},
|
||||
{
|
||||
"t": 108.5,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.7833,
|
||||
"api_p95_s": 2.4348,
|
||||
"db_p95_s": 0.0444,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4883
|
||||
},
|
||||
{
|
||||
"t": 113.6,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.7833,
|
||||
"api_p95_s": 2.4348,
|
||||
"db_p95_s": 0.0057,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.4883
|
||||
},
|
||||
{
|
||||
"t": 118.7,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.4654,
|
||||
"api_p95_s": 2.376,
|
||||
"db_p95_s": 0.005,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5039
|
||||
},
|
||||
{
|
||||
"t": 123.8,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.4654,
|
||||
"api_p95_s": 2.376,
|
||||
"db_p95_s": 0.0048,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5039
|
||||
},
|
||||
{
|
||||
"t": 128.9,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.2822,
|
||||
"api_p95_s": 2.2791,
|
||||
"db_p95_s": 0.0048,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5078
|
||||
},
|
||||
{
|
||||
"t": 134.0,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.2822,
|
||||
"api_p95_s": 2.2791,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5078
|
||||
},
|
||||
{
|
||||
"t": 139.1,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.1529,
|
||||
"api_p95_s": 2.0672,
|
||||
"db_p95_s": 0.0045,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5117
|
||||
},
|
||||
{
|
||||
"t": 144.2,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.1529,
|
||||
"api_p95_s": 2.0672,
|
||||
"db_p95_s": 0.0042,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5117
|
||||
},
|
||||
{
|
||||
"t": 149.3,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0636,
|
||||
"api_p95_s": 1.361,
|
||||
"db_p95_s": 0.0042,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5781
|
||||
},
|
||||
{
|
||||
"t": 154.5,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0636,
|
||||
"api_p95_s": 1.361,
|
||||
"db_p95_s": 0.0037,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5781
|
||||
},
|
||||
{
|
||||
"t": 159.6,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0376,
|
||||
"db_p95_s": 0.0036,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.582
|
||||
},
|
||||
{
|
||||
"t": 164.7,
|
||||
"alerts": {
|
||||
"ApiHighErrorRate": "firing",
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0376,
|
||||
"db_p95_s": 0.0034,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.582
|
||||
},
|
||||
{
|
||||
"t": 169.8,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.025,
|
||||
"db_p95_s": 0.0034,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.5898
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,595 @@
|
||||
{
|
||||
"scenario": "db-slow",
|
||||
"marks_s": {
|
||||
"postgres limited to 0.03 CPU": 31.1,
|
||||
"DbSlowQueries firing": 87.6,
|
||||
"postgres restored to 1.0 CPU": 119.2,
|
||||
"resolved": 185.7
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"DbSlowQueries": 87.6,
|
||||
"ApiLatencyHigh": 118.5
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"DbSlowQueries": 175.5,
|
||||
"ApiLatencyHigh": 185.7
|
||||
},
|
||||
"metrics_before": {
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0425,
|
||||
"db_p95_s": 0.0035,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.6914
|
||||
},
|
||||
"metrics_during": {
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.717,
|
||||
"db_p95_s": 0.222,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.6094
|
||||
},
|
||||
"slow_trace": {
|
||||
"trace_id": "0a0efea457d22fb0b498b9fe612a9696",
|
||||
"duration_ms": 702.1,
|
||||
"db_ms": 694.4,
|
||||
"pool_wait_ms": 192.0,
|
||||
"db_share": 0.99,
|
||||
"db_or_pool_share": 1.26,
|
||||
"not_in_child_spans_ms": 7.1,
|
||||
"error_type": null,
|
||||
"slowest_child": [
|
||||
"INSERT messages",
|
||||
300.8
|
||||
]
|
||||
},
|
||||
"http_before": {
|
||||
"requests": 180,
|
||||
"ok": 180,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 11.8,
|
||||
"p95_ms": 37.6,
|
||||
"p99_ms": 80.0
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 516,
|
||||
"ok": 516,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 132.6,
|
||||
"p95_ms": 698.8,
|
||||
"p99_ms": 964.9
|
||||
},
|
||||
"detection_s": 56.5,
|
||||
"timeline": [
|
||||
{
|
||||
"t": 1.0,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0544,
|
||||
"db_p95_s": 0.005,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.4531
|
||||
},
|
||||
{
|
||||
"t": 31.2,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0425,
|
||||
"db_p95_s": 0.0035,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.6914
|
||||
},
|
||||
{
|
||||
"t": 36.4,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0269,
|
||||
"db_p95_s": 0.0035,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.7148
|
||||
},
|
||||
{
|
||||
"t": 41.5,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0269,
|
||||
"db_p95_s": 0.0047,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.7148
|
||||
},
|
||||
{
|
||||
"t": 46.6,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.2729,
|
||||
"db_p95_s": 0.005,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.7266
|
||||
},
|
||||
{
|
||||
"t": 51.9,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.2729,
|
||||
"db_p95_s": 0.0726,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.7266
|
||||
},
|
||||
{
|
||||
"t": 57.0,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.5339,
|
||||
"db_p95_s": 0.0791,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.8438
|
||||
},
|
||||
{
|
||||
"t": 62.1,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.5339,
|
||||
"db_p95_s": 0.1444,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.8438
|
||||
},
|
||||
{
|
||||
"t": 67.2,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.6597,
|
||||
"db_p95_s": 0.1504,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.9023
|
||||
},
|
||||
{
|
||||
"t": 72.3,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.6597,
|
||||
"db_p95_s": 0.1842,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.9023
|
||||
},
|
||||
{
|
||||
"t": 77.4,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.6884,
|
||||
"db_p95_s": 0.1885,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.2773
|
||||
},
|
||||
{
|
||||
"t": 82.5,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.6884,
|
||||
"db_p95_s": 0.2102,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.2773
|
||||
},
|
||||
{
|
||||
"t": 87.6,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7136,
|
||||
"db_p95_s": 0.2115,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.2969
|
||||
},
|
||||
{
|
||||
"t": 87.7,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7136,
|
||||
"db_p95_s": 0.2145,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.2969
|
||||
},
|
||||
{
|
||||
"t": 92.8,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7136,
|
||||
"db_p95_s": 0.2277,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.2969
|
||||
},
|
||||
{
|
||||
"t": 97.9,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7451,
|
||||
"db_p95_s": 0.2309,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.3086
|
||||
},
|
||||
{
|
||||
"t": 103.0,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7451,
|
||||
"db_p95_s": 0.2263,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.3086
|
||||
},
|
||||
{
|
||||
"t": 108.1,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7562,
|
||||
"db_p95_s": 0.2251,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.3164
|
||||
},
|
||||
{
|
||||
"t": 113.2,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7562,
|
||||
"db_p95_s": 0.2219,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.3164
|
||||
},
|
||||
{
|
||||
"t": 118.5,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.717,
|
||||
"db_p95_s": 0.2241,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.6094
|
||||
},
|
||||
{
|
||||
"t": 119.3,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.717,
|
||||
"db_p95_s": 0.222,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 176.6094
|
||||
},
|
||||
{
|
||||
"t": 124.4,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.717,
|
||||
"db_p95_s": 0.2215,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 179.6484
|
||||
},
|
||||
{
|
||||
"t": 129.5,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7344,
|
||||
"db_p95_s": 0.208,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 179.6484
|
||||
},
|
||||
{
|
||||
"t": 134.6,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7082,
|
||||
"db_p95_s": 0.2056,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0391
|
||||
},
|
||||
{
|
||||
"t": 139.7,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.7082,
|
||||
"db_p95_s": 0.1648,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0391
|
||||
},
|
||||
{
|
||||
"t": 144.8,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.5781,
|
||||
"db_p95_s": 0.1538,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0508
|
||||
},
|
||||
{
|
||||
"t": 149.9,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.5781,
|
||||
"db_p95_s": 0.1125,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0508
|
||||
},
|
||||
{
|
||||
"t": 155.1,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.55,
|
||||
"db_p95_s": 0.0996,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0703
|
||||
},
|
||||
{
|
||||
"t": 160.2,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.55,
|
||||
"db_p95_s": 0.0728,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0703
|
||||
},
|
||||
{
|
||||
"t": 165.3,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.425,
|
||||
"db_p95_s": 0.0652,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0703
|
||||
},
|
||||
{
|
||||
"t": 170.4,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing",
|
||||
"DbSlowQueries": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.425,
|
||||
"db_p95_s": 0.0035,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.0703
|
||||
},
|
||||
{
|
||||
"t": 175.5,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0273,
|
||||
"db_p95_s": 0.0031,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.168
|
||||
},
|
||||
{
|
||||
"t": 180.6,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0273,
|
||||
"db_p95_s": 0.0028,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.168
|
||||
},
|
||||
{
|
||||
"t": 185.7,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0241,
|
||||
"db_p95_s": 0.0028,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.4141
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,533 @@
|
||||
{
|
||||
"scenario": "handler-slow",
|
||||
"marks_s": {
|
||||
"50% of messages carry fault-api-slow-400 (sleep in handler)": 0.6,
|
||||
"ApiLatencyHigh firing": 87.8,
|
||||
"resolved": 160.2
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"ApiLatencyHigh": 87.8
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"ApiLatencyHigh": 160.2
|
||||
},
|
||||
"metrics_during": {
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0026,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.0938
|
||||
},
|
||||
"db_alert_fired": false,
|
||||
"slow_trace": {
|
||||
"trace_id": "2aa39fd46f97f6a25232626dcb3aa263",
|
||||
"duration_ms": 421.9,
|
||||
"db_ms": 12.2,
|
||||
"pool_wait_ms": 3.8,
|
||||
"db_share": 0.03,
|
||||
"db_or_pool_share": 0.04,
|
||||
"not_in_child_spans_ms": 409.2,
|
||||
"error_type": null,
|
||||
"slowest_child": [
|
||||
"INSERT messages",
|
||||
6.6
|
||||
]
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 526,
|
||||
"ok": 526,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 66.4,
|
||||
"p95_ms": 421.4,
|
||||
"p99_ms": 440.7
|
||||
},
|
||||
"detection_s": 87.8,
|
||||
"timeline": [
|
||||
{
|
||||
"t": 0.8,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0241,
|
||||
"db_p95_s": 0.0028,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.4141
|
||||
},
|
||||
{
|
||||
"t": 5.9,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0241,
|
||||
"db_p95_s": 0.003,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.4141
|
||||
},
|
||||
{
|
||||
"t": 11.0,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0252,
|
||||
"db_p95_s": 0.003,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.4219
|
||||
},
|
||||
{
|
||||
"t": 16.2,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0252,
|
||||
"db_p95_s": 0.0031,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.4219
|
||||
},
|
||||
{
|
||||
"t": 21.2,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.3904,
|
||||
"db_p95_s": 0.0031,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.4922
|
||||
},
|
||||
{
|
||||
"t": 26.3,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.3904,
|
||||
"db_p95_s": 0.0031,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.4922
|
||||
},
|
||||
{
|
||||
"t": 31.4,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4418,
|
||||
"db_p95_s": 0.0031,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.5508
|
||||
},
|
||||
{
|
||||
"t": 36.5,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4418,
|
||||
"db_p95_s": 0.0028,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.5508
|
||||
},
|
||||
{
|
||||
"t": 41.6,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4604,
|
||||
"db_p95_s": 0.0028,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.6172
|
||||
},
|
||||
{
|
||||
"t": 46.7,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4604,
|
||||
"db_p95_s": 0.0028,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.6172
|
||||
},
|
||||
{
|
||||
"t": 51.8,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.47,
|
||||
"db_p95_s": 0.0029,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.707
|
||||
},
|
||||
{
|
||||
"t": 56.9,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.47,
|
||||
"db_p95_s": 0.0026,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 180.707
|
||||
},
|
||||
{
|
||||
"t": 62.1,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0025,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 1.0,
|
||||
"collector_rss_mib": 181.0078
|
||||
},
|
||||
{
|
||||
"t": 67.1,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0028,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 1.0,
|
||||
"collector_rss_mib": 181.0078
|
||||
},
|
||||
{
|
||||
"t": 72.2,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0027,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 1.0,
|
||||
"collector_rss_mib": 181.0234
|
||||
},
|
||||
{
|
||||
"t": 77.4,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0026,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 1.0,
|
||||
"collector_rss_mib": 181.0234
|
||||
},
|
||||
{
|
||||
"t": 82.6,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0026,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.0938
|
||||
},
|
||||
{
|
||||
"t": 87.8,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0026,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.0938
|
||||
},
|
||||
{
|
||||
"t": 88.5,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0026,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.0938
|
||||
},
|
||||
{
|
||||
"t": 93.6,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.475,
|
||||
"db_p95_s": 0.0025,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 1.0,
|
||||
"collector_rss_mib": 181.1016
|
||||
},
|
||||
{
|
||||
"t": 98.7,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4752,
|
||||
"db_p95_s": 0.0025,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1055
|
||||
},
|
||||
{
|
||||
"t": 103.8,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4752,
|
||||
"db_p95_s": 0.0025,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1055
|
||||
},
|
||||
{
|
||||
"t": 108.9,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4752,
|
||||
"db_p95_s": 0.0025,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1055
|
||||
},
|
||||
{
|
||||
"t": 114.0,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4752,
|
||||
"db_p95_s": 0.0024,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1055
|
||||
},
|
||||
{
|
||||
"t": 119.2,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4753,
|
||||
"db_p95_s": 0.0023,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1055
|
||||
},
|
||||
{
|
||||
"t": 124.3,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4753,
|
||||
"db_p95_s": 0.0023,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1055
|
||||
},
|
||||
{
|
||||
"t": 129.4,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4755,
|
||||
"db_p95_s": 0.0023,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1094
|
||||
},
|
||||
{
|
||||
"t": 134.5,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4755,
|
||||
"db_p95_s": 0.0022,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1094
|
||||
},
|
||||
{
|
||||
"t": 139.6,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4762,
|
||||
"db_p95_s": 0.0021,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1133
|
||||
},
|
||||
{
|
||||
"t": 144.7,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.4762,
|
||||
"db_p95_s": 0.0021,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1133
|
||||
},
|
||||
{
|
||||
"t": 149.8,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": 0.002,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1289
|
||||
},
|
||||
{
|
||||
"t": 155.1,
|
||||
"alerts": {
|
||||
"ApiLatencyHigh": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": 0.0021,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.1289
|
||||
},
|
||||
{
|
||||
"t": 160.2,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": 0.0022,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 181.2734
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
{
|
||||
"scenario": "telemetry-down",
|
||||
"marks_s": {
|
||||
"tempo and loki stopped": 21.8,
|
||||
"TelemetryExportFailing firing": 89.0,
|
||||
"tempo and loki started": 150.2,
|
||||
"resolved, queue drained": 172.3
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"TelemetryExportFailing": 89.0
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"TelemetryExportFailing": 167.2
|
||||
},
|
||||
"http_during": {
|
||||
"requests": 772,
|
||||
"ok": 772,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 13.1,
|
||||
"p95_ms": 40.2,
|
||||
"p99_ms": 76.7
|
||||
},
|
||||
"uploads_during": {
|
||||
"requests": 42,
|
||||
"ok": 42,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 26.6,
|
||||
"p95_ms": 48.3,
|
||||
"p99_ms": 217.8
|
||||
},
|
||||
"collector_mem_before": {
|
||||
"ac5a65d675df": "50.21MiB"
|
||||
},
|
||||
"collector_mem_during": {
|
||||
"ac5a65d675df": "54.82MiB"
|
||||
},
|
||||
"exporter_queue_max": 64.0,
|
||||
"exporter_queue_capacity": 200.0,
|
||||
"telemetry_delta": {
|
||||
"accepted_spans": 9907,
|
||||
"send_failed_spans": 275,
|
||||
"enqueue_failed_spans": 0,
|
||||
"send_failed_logs": 30,
|
||||
"enqueue_failed_logs": 0
|
||||
},
|
||||
"traces_from_outage_window_found_after_recovery": 200,
|
||||
"detection_s": 67.2,
|
||||
"timeline": [
|
||||
{
|
||||
"t": 27.5,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0384,
|
||||
"db_p95_s": 0.0041,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 4.0,
|
||||
"collector_rss_mib": 181.6172
|
||||
},
|
||||
{
|
||||
"t": 32.6,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0384,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 4.0,
|
||||
"collector_rss_mib": 181.6172
|
||||
},
|
||||
{
|
||||
"t": 37.7,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0388,
|
||||
"db_p95_s": 0.0043,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 14.0,
|
||||
"collector_rss_mib": 181.6875
|
||||
},
|
||||
{
|
||||
"t": 42.8,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0388,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 14.0,
|
||||
"collector_rss_mib": 181.6875
|
||||
},
|
||||
{
|
||||
"t": 47.9,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0403,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 24.0,
|
||||
"collector_rss_mib": 181.7656
|
||||
},
|
||||
{
|
||||
"t": 53.0,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0403,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 24.0,
|
||||
"collector_rss_mib": 181.7656
|
||||
},
|
||||
{
|
||||
"t": 58.1,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0423,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 34.0,
|
||||
"collector_rss_mib": 181.7695
|
||||
},
|
||||
{
|
||||
"t": 63.2,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0423,
|
||||
"db_p95_s": 0.0048,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 34.0,
|
||||
"collector_rss_mib": 181.7695
|
||||
},
|
||||
{
|
||||
"t": 68.4,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0458,
|
||||
"db_p95_s": 0.0048,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 44.0,
|
||||
"collector_rss_mib": 181.7695
|
||||
},
|
||||
{
|
||||
"t": 73.7,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0458,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 44.0,
|
||||
"collector_rss_mib": 181.7695
|
||||
},
|
||||
{
|
||||
"t": 78.8,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0435,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 54.0,
|
||||
"collector_rss_mib": 181.7695
|
||||
},
|
||||
{
|
||||
"t": 83.9,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0435,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 54.0,
|
||||
"collector_rss_mib": 181.7695
|
||||
},
|
||||
{
|
||||
"t": 89.0,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0406,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 64.0,
|
||||
"collector_rss_mib": 182.1641
|
||||
},
|
||||
{
|
||||
"t": 151.9,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0423,
|
||||
"db_p95_s": 0.0042,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 120.0,
|
||||
"collector_rss_mib": 186.1523
|
||||
},
|
||||
{
|
||||
"t": 157.0,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0423,
|
||||
"db_p95_s": 0.0042,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 120.0,
|
||||
"collector_rss_mib": 186.1523
|
||||
},
|
||||
{
|
||||
"t": 162.1,
|
||||
"alerts": {
|
||||
"TelemetryExportFailing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.042,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 1.0,
|
||||
"collector_rss_mib": 190.9453
|
||||
},
|
||||
{
|
||||
"t": 167.2,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.042,
|
||||
"db_p95_s": 0.0047,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 1.0,
|
||||
"collector_rss_mib": 190.9453
|
||||
},
|
||||
{
|
||||
"t": 172.3,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0435,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 192.2148
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,414 @@
|
||||
{
|
||||
"scenario": "worker-stop",
|
||||
"marks_s": {
|
||||
"worker stopped": 20.7,
|
||||
"both alerts firing": 98.3,
|
||||
"worker started": 113.3,
|
||||
"alerts resolved, backlog empty": 158.5
|
||||
},
|
||||
"alerts_first_firing_s": {
|
||||
"JobQueueLagGrowing": 98.3,
|
||||
"WorkerHeartbeatMissing": 98.3
|
||||
},
|
||||
"alerts_resolved_s": {
|
||||
"WorkerHeartbeatMissing": 138.0,
|
||||
"JobQueueLagGrowing": 158.5
|
||||
},
|
||||
"uploads_accepted": 78,
|
||||
"uploads_not_ready_after_recovery": 0,
|
||||
"queue_ready_peak": 34.0,
|
||||
"api_accepted_logs_during_outage": 46,
|
||||
"worker_logs_during_outage": 0,
|
||||
"detection_s": {
|
||||
"JobQueueLagGrowing": 77.6,
|
||||
"WorkerHeartbeatMissing": 77.6
|
||||
},
|
||||
"recovery_s": {
|
||||
"JobQueueLagGrowing": 45.2,
|
||||
"WorkerHeartbeatMissing": 24.7
|
||||
},
|
||||
"http_during_outage": {
|
||||
"requests": 276,
|
||||
"ok": 276,
|
||||
"errors": 0,
|
||||
"error_statuses": [],
|
||||
"p50_ms": 15.4,
|
||||
"p95_ms": 37.4,
|
||||
"p99_ms": 75.3
|
||||
},
|
||||
"timeline": [
|
||||
{
|
||||
"t": 0.7,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": null,
|
||||
"db_p95_s": 0.0025,
|
||||
"queue_lag_s": null,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 159.8984
|
||||
},
|
||||
{
|
||||
"t": 21.6,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.131,
|
||||
"db_p95_s": 0.0049,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 166.1602
|
||||
},
|
||||
{
|
||||
"t": 26.6,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0483,
|
||||
"db_p95_s": 0.0049,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 167.8047
|
||||
},
|
||||
{
|
||||
"t": 31.7,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0483,
|
||||
"db_p95_s": 0.0047,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 2.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 167.8047
|
||||
},
|
||||
{
|
||||
"t": 36.8,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0436,
|
||||
"db_p95_s": 0.0047,
|
||||
"queue_lag_s": 7.0425,
|
||||
"queue_ready": 4.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 168.8203
|
||||
},
|
||||
{
|
||||
"t": 41.9,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0436,
|
||||
"db_p95_s": 0.0045,
|
||||
"queue_lag_s": 7.0425,
|
||||
"queue_ready": 7.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 168.8203
|
||||
},
|
||||
{
|
||||
"t": 47.0,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0433,
|
||||
"db_p95_s": 0.0045,
|
||||
"queue_lag_s": 17.0557,
|
||||
"queue_ready": 9.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 169.0859
|
||||
},
|
||||
{
|
||||
"t": 52.1,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0433,
|
||||
"db_p95_s": 0.0045,
|
||||
"queue_lag_s": 17.0557,
|
||||
"queue_ready": 12.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 169.0859
|
||||
},
|
||||
{
|
||||
"t": 57.2,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0408,
|
||||
"db_p95_s": 0.0045,
|
||||
"queue_lag_s": 27.0656,
|
||||
"queue_ready": 14.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 171.043
|
||||
},
|
||||
{
|
||||
"t": 62.3,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0408,
|
||||
"db_p95_s": 0.004,
|
||||
"queue_lag_s": 27.0656,
|
||||
"queue_ready": 17.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 171.043
|
||||
},
|
||||
{
|
||||
"t": 67.6,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0393,
|
||||
"db_p95_s": 0.004,
|
||||
"queue_lag_s": 37.0758,
|
||||
"queue_ready": 19.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 173.8867
|
||||
},
|
||||
{
|
||||
"t": 72.8,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0393,
|
||||
"db_p95_s": 0.0037,
|
||||
"queue_lag_s": 37.0758,
|
||||
"queue_ready": 22.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 173.8867
|
||||
},
|
||||
{
|
||||
"t": 77.9,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "pending",
|
||||
"WorkerHeartbeatMissing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0342,
|
||||
"db_p95_s": 0.0037,
|
||||
"queue_lag_s": 47.1036,
|
||||
"queue_ready": 24.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 174.7188
|
||||
},
|
||||
{
|
||||
"t": 83.0,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "pending",
|
||||
"WorkerHeartbeatMissing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0342,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 47.1036,
|
||||
"queue_ready": 27.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 174.7188
|
||||
},
|
||||
{
|
||||
"t": 88.1,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "pending",
|
||||
"WorkerHeartbeatMissing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.045,
|
||||
"db_p95_s": 0.0044,
|
||||
"queue_lag_s": 57.1166,
|
||||
"queue_ready": 29.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 174.9297
|
||||
},
|
||||
{
|
||||
"t": 93.2,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "pending",
|
||||
"WorkerHeartbeatMissing": "pending"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.045,
|
||||
"db_p95_s": 0.0046,
|
||||
"queue_lag_s": 57.1166,
|
||||
"queue_ready": 32.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 174.9297
|
||||
},
|
||||
{
|
||||
"t": 98.3,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing",
|
||||
"WorkerHeartbeatMissing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0488,
|
||||
"db_p95_s": 0.0045,
|
||||
"queue_lag_s": 67.1494,
|
||||
"queue_ready": 34.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 174.9727
|
||||
},
|
||||
{
|
||||
"t": 117.5,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing",
|
||||
"WorkerHeartbeatMissing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0491,
|
||||
"db_p95_s": 0.0047,
|
||||
"queue_lag_s": 87.1689,
|
||||
"queue_ready": 43.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.1758
|
||||
},
|
||||
{
|
||||
"t": 122.6,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing",
|
||||
"WorkerHeartbeatMissing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0491,
|
||||
"db_p95_s": 0.0048,
|
||||
"queue_lag_s": 87.1689,
|
||||
"queue_ready": 46.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.1758
|
||||
},
|
||||
{
|
||||
"t": 127.7,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing",
|
||||
"WorkerHeartbeatMissing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0557,
|
||||
"db_p95_s": 0.0048,
|
||||
"queue_lag_s": 97.1806,
|
||||
"queue_ready": 48.0,
|
||||
"workers_capacity": null,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.3164
|
||||
},
|
||||
{
|
||||
"t": 132.8,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing",
|
||||
"WorkerHeartbeatMissing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0557,
|
||||
"db_p95_s": 0.0054,
|
||||
"queue_lag_s": 97.1806,
|
||||
"queue_ready": 48.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.3164
|
||||
},
|
||||
{
|
||||
"t": 138.0,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.055,
|
||||
"db_p95_s": 0.0054,
|
||||
"queue_lag_s": 56.1344,
|
||||
"queue_ready": 28.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.3711
|
||||
},
|
||||
{
|
||||
"t": 143.2,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.055,
|
||||
"db_p95_s": 0.0068,
|
||||
"queue_lag_s": 56.1344,
|
||||
"queue_ready": 14.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.3711
|
||||
},
|
||||
{
|
||||
"t": 148.3,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.055,
|
||||
"db_p95_s": 0.007,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.4375
|
||||
},
|
||||
{
|
||||
"t": 153.4,
|
||||
"alerts": {
|
||||
"JobQueueLagGrowing": "firing"
|
||||
},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.055,
|
||||
"db_p95_s": 0.0061,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.4375
|
||||
},
|
||||
{
|
||||
"t": 158.5,
|
||||
"alerts": {},
|
||||
"error_ratio": 0.0,
|
||||
"api_p95_s": 0.0544,
|
||||
"db_p95_s": 0.0061,
|
||||
"queue_lag_s": 0.0,
|
||||
"queue_ready": 0.0,
|
||||
"workers_capacity": 4.0,
|
||||
"db_pool_waiting_api": 0.0,
|
||||
"collector_queue": 0.0,
|
||||
"collector_rss_mib": 175.4531
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
# 2026-11-21T20:01:39Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc exec -T api python -m messenger jobs failed --limit 20
|
||||
{
|
||||
"failed": [
|
||||
{
|
||||
"job_id": "7e27c9a9-3142-404f-9bcb-2a10665b3aec",
|
||||
"attachment_id": "ba26c359-2438-45eb-a463-68caec1cff88",
|
||||
"pipeline_version": 1,
|
||||
"error_code": "invalid_image",
|
||||
"error_detail": "OSError: broken data stream when reading image file",
|
||||
"attempt": 1,
|
||||
"claims": 1,
|
||||
"replays": 0,
|
||||
"failed_at": "2026-11-21 19:27:10.802973+00:00",
|
||||
"replayable": false
|
||||
},
|
||||
{
|
||||
"job_id": "00a3a193-62a9-4bd4-8f88-8af124640677",
|
||||
"attachment_id": "901dd139-d599-4177-bad1-afd7bae63828",
|
||||
"pipeline_version": 1,
|
||||
"error_code": "invalid_image",
|
||||
"error_detail": "OSError: broken data stream when reading image file",
|
||||
"attempt": 2,
|
||||
"claims": 1,
|
||||
"replays": 1,
|
||||
"failed_at": "2026-11-21 19:21:16.636634+00:00",
|
||||
"replayable": true
|
||||
},
|
||||
{
|
||||
"job_id": "da0acd1e-ac00-40e5-9351-0a5abd717d40",
|
||||
"attachment_id": "fee90bba-4e47-4779-98ce-c506f351f6f7",
|
||||
"pipeline_version": 1,
|
||||
"error_code": "invalid_image",
|
||||
"error_detail": "OSError: broken data stream when reading image file",
|
||||
"attempt": 1,
|
||||
"claims": 1,
|
||||
"replays": 0,
|
||||
"failed_at": "2026-11-21 19:21:04.496141+00:00",
|
||||
"replayable": true
|
||||
}
|
||||
],
|
||||
"count": 3
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,24 @@
|
||||
# 2026-11-21T20:01:40Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc exec -T api python -m messenger jobs invariants --settled --verify-bytes
|
||||
{
|
||||
"ok": true,
|
||||
"violations": {},
|
||||
"violation_counts": {},
|
||||
"stats": {
|
||||
"attachments": 696,
|
||||
"jobs": 701,
|
||||
"variants": 2091,
|
||||
"events": 4394,
|
||||
"job_status": {
|
||||
"failed": 3,
|
||||
"ready": 696,
|
||||
"superseded": 2
|
||||
},
|
||||
"attachment_status": {
|
||||
"failed": 3,
|
||||
"ready": 693
|
||||
},
|
||||
"s3_objects": 2786
|
||||
}
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 6,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.062,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 5438,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 180.893,
|
||||
"successful_latency_ms": {
|
||||
"p50": 16.941,
|
||||
"p95": 53.059,
|
||||
"p99": 107.154
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
# 2026-11-21T20:01:49Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 tests/load.py --base-url http://127.0.0.1:8080 --duration 30 --concurrency 4 --output evidence/load.json
|
||||
{
|
||||
"lab": 6,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.062,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 5438,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 180.893,
|
||||
"successful_latency_ms": {
|
||||
"p50": 16.941,
|
||||
"p95": 53.059,
|
||||
"p99": 107.154
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-11-21T18:58:12Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ make check
|
||||
python3 scripts/check_contract.py
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
exit=0
|
||||
@@ -0,0 +1,6 @@
|
||||
# 2026-11-21T20:01:47Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc run --rm --no-deps migrate
|
||||
Container mtusi-lab6-migrate-run-08460db58929 Creating
|
||||
Container mtusi-lab6-migrate-run-08460db58929 Created
|
||||
{"applied": []}
|
||||
exit=0
|
||||
@@ -0,0 +1,20 @@
|
||||
# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ sh -c docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version'; docker compose --env-file .env logs --no-log-prefix migrate
|
||||
version | checksum | applied_at
|
||||
--------------------------------+--------------+-------------------------------
|
||||
0001_init | 64c1576d88cc | 2026-11-21 18:57:54.841805+00
|
||||
0002_cache_invalidation_outbox | fcebf1c9345a | 2026-11-21 18:57:54.850032+00
|
||||
0003_idempotency_keys | e2564612d780 | 2026-11-21 18:57:54.856713+00
|
||||
0004_attachments | 52090521af1b | 2026-11-21 18:57:54.880215+00
|
||||
0005_jobs | 34e5b9a70f4d | 2026-11-21 18:57:54.906048+00
|
||||
0006_observability | b56c84655e84 | 2026-11-21 18:57:54.909758+00
|
||||
(6 rows)
|
||||
|
||||
{"ts": "2026-11-21T18:57:54.844Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0001_init"}
|
||||
{"ts": "2026-11-21T18:57:54.850Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0002_cache_invalidation_outbox"}
|
||||
{"ts": "2026-11-21T18:57:54.858Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0003_idempotency_keys"}
|
||||
{"ts": "2026-11-21T18:57:54.881Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0004_attachments"}
|
||||
{"ts": "2026-11-21T18:57:54.907Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0005_jobs"}
|
||||
{"ts": "2026-11-21T18:57:54.910Z", "level": "info", "service": "messenger", "logger": "messenger.db", "event": "migration applied", "msg": "migration applied", "version": "0006_observability"}
|
||||
{"applied": ["0001_init", "0002_cache_invalidation_outbox", "0003_idempotency_keys", "0004_attachments", "0005_jobs", "0006_observability"]}
|
||||
exit=0
|
||||
@@ -0,0 +1,7 @@
|
||||
# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ sh -c for c in $(docker compose --env-file .env ps -q api worker); do docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' $c; done
|
||||
/mtusi-lab6-api-1 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/cache_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key
|
||||
/mtusi-lab6-api-2 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/cache_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key
|
||||
/mtusi-lab6-worker-1 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key
|
||||
/mtusi-lab6-worker-2 ReadonlyRootfs=true Tmpfs={"/tmp":""} Mounts=bind:/run/secrets/broker_url bind:/run/secrets/database_url bind:/run/secrets/s3_access_key_id bind:/run/secrets/s3_secret_access_key
|
||||
exit=0
|
||||
@@ -0,0 +1,79 @@
|
||||
# 2026-11-21T20:13:05Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/obs_snapshot.py
|
||||
== Grafana 13.3.1
|
||||
datasource uid=loki type=loki url=http://loki:3100 readOnly=True health=OK
|
||||
datasource uid=prometheus type=prometheus url=http://prometheus:9090 readOnly=True health=OK
|
||||
datasource uid=tempo type=tempo url=http://tempo:3200 readOnly=True health=OK
|
||||
dashboard uid=messenger-overview provisioned=True panels=33 folder=Messenger
|
||||
|
||||
== Prometheus: правила и состояние
|
||||
alerting ApiHighErrorRate health=ok state=inactive
|
||||
alerting ApiLatencyHigh health=ok state=inactive
|
||||
alerting DbSlowQueries health=ok state=inactive
|
||||
alerting DbPoolSaturated health=ok state=inactive
|
||||
alerting JobQueueLagGrowing health=ok state=inactive
|
||||
alerting WorkerHeartbeatMissing health=ok state=inactive
|
||||
alerting JobsFailing health=ok state=inactive
|
||||
alerting TelemetryExportFailing health=ok state=inactive
|
||||
alerting OtelCollectorDown health=ok state=inactive
|
||||
alerting TelemetryLostInSdk health=ok state=firing
|
||||
recording sli:api_requests:rate1m health=ok state=-
|
||||
recording sli:api_errors:rate1m health=ok state=-
|
||||
recording sli:api_error_ratio:rate1m health=ok state=-
|
||||
recording sli:api_latency_p95:1m health=ok state=-
|
||||
recording sli:api_fast_ratio:rate5m health=ok state=-
|
||||
recording sli:time_to_ready_fast_ratio:rate15m health=ok state=-
|
||||
recording sli:queue_lag_seconds:max health=ok state=-
|
||||
recording sli:queue_oldest_age_seconds:max health=ok state=-
|
||||
|
||||
== Метрики приложения (Prometheus, имя → labels кроме ресурсных)
|
||||
container_cpu_time_seconds_total series=90 labels=
|
||||
container_memory_usage_bytes series=90 labels=
|
||||
db_client_connection_max series=90 labels=db_client_connection_pool_name
|
||||
db_client_connection_pending_requests series=90 labels=db_client_connection_pool_name
|
||||
db_client_connection_timeouts_total series=90 labels=db_client_connection_pool_name
|
||||
db_client_operation_duration_seconds_bucket series=8148 labels=db_operation_name,db_system_name,error_type
|
||||
http_server_active_requests series=77 labels=http_request_method
|
||||
http_server_request_duration_seconds_bucket series=5325 labels=http_request_method,http_response_status_class,http_response_status_code,http_route
|
||||
messenger_attachment_time_to_ready_seconds_bucket series=630 labels=job_type
|
||||
messenger_broker_ack_pending series=39 labels=queue
|
||||
messenger_broker_pending series=39 labels=queue
|
||||
messenger_container_cpu_limit series=90 labels=
|
||||
messenger_container_memory_limit_bytes series=90 labels=
|
||||
messenger_db_pool_wait_time_seconds_total series=90 labels=db_client_connection_pool_name
|
||||
messenger_job_duration_seconds_bucket series=804 labels=job_type,outcome
|
||||
messenger_job_queue_wait_seconds_bucket series=644 labels=job_type
|
||||
messenger_jobs_processed_total series=93 labels=job_type,messenger_pipeline_version,outcome
|
||||
messenger_outbox_lag_seconds series=39 labels=queue
|
||||
messenger_outbox_pending series=39 labels=queue
|
||||
messenger_outbox_publish_total series=46 labels=messaging_destination_name,outcome
|
||||
messenger_queue_depth series=156 labels=queue,state
|
||||
messenger_queue_lag_seconds series=39 labels=queue
|
||||
messenger_queue_oldest_age_seconds series=39 labels=queue
|
||||
messenger_uploads_total series=34 labels=outcome
|
||||
messenger_worker_busy series=48 labels=
|
||||
messenger_worker_capacity series=51 labels=
|
||||
otel_sdk_exporter_span_exported_total series=86 labels=error_type,otel_component_name,otel_component_type,server_address,server_port
|
||||
otel_sdk_exporter_span_inflight series=82 labels=otel_component_name,otel_component_type,server_address,server_port
|
||||
otel_sdk_processor_log_processed_total series=90 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_log_queue_capacity series=90 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_log_queue_size series=90 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_span_processed_total series=82 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_span_queue_capacity series=90 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_span_queue_size series=90 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_span_live series=82 labels=otel_span_sampling_result
|
||||
otel_sdk_span_started_total series=212 labels=otel_span_parent_origin,otel_span_sampling_result
|
||||
process_cpu_time_seconds_total series=180 labels=cpu_mode
|
||||
process_memory_usage_bytes series=90 labels=
|
||||
|
||||
== Loki labels (index): deployment_environment_name,service_instance_id,service_name,service_namespace
|
||||
пример записи messenger-api: поля=deployment_environment_name,detected_level,duration_ms,event,flags,logger,method,observed_timestamp,request_id,route,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,status,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id
|
||||
пример записи messenger-worker: поля=attachment_id,attempt,claims,deployment_environment_name,detected_level,duration_ms,event,flags,job_id,lease_token,logger,observed_timestamp,outcome,pipeline_version,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id
|
||||
|
||||
== Tempo
|
||||
{ resource.service.name = "messenger-api" && kind = server } traces(1h, limit 20)=20
|
||||
{ span.messaging.operation.type = "process" } traces(1h, limit 20)=20
|
||||
{ status = error } traces(1h, limit 20)=20
|
||||
|
||||
== Активные алерты: [["TelemetryLostInSdk", "firing"]]
|
||||
exit=0
|
||||
@@ -0,0 +1,79 @@
|
||||
# 2026-11-21T18:58:47Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/obs_snapshot.py
|
||||
== Grafana 13.3.1
|
||||
datasource uid=loki type=loki url=http://loki:3100 readOnly=True health=OK
|
||||
datasource uid=prometheus type=prometheus url=http://prometheus:9090 readOnly=True health=OK
|
||||
datasource uid=tempo type=tempo url=http://tempo:3200 readOnly=True health=OK
|
||||
dashboard uid=messenger-overview provisioned=True panels=33 folder=Messenger
|
||||
|
||||
== Prometheus: правила и состояние
|
||||
alerting ApiHighErrorRate health=ok state=inactive
|
||||
alerting ApiLatencyHigh health=ok state=inactive
|
||||
alerting DbSlowQueries health=ok state=inactive
|
||||
alerting DbPoolSaturated health=ok state=inactive
|
||||
alerting JobQueueLagGrowing health=ok state=inactive
|
||||
alerting WorkerHeartbeatMissing health=ok state=inactive
|
||||
alerting JobsFailing health=ok state=inactive
|
||||
alerting TelemetryExportFailing health=ok state=inactive
|
||||
alerting OtelCollectorDown health=ok state=inactive
|
||||
alerting TelemetryLostInSdk health=ok state=inactive
|
||||
recording sli:api_requests:rate1m health=ok state=-
|
||||
recording sli:api_errors:rate1m health=ok state=-
|
||||
recording sli:api_error_ratio:rate1m health=ok state=-
|
||||
recording sli:api_latency_p95:1m health=ok state=-
|
||||
recording sli:api_fast_ratio:rate5m health=ok state=-
|
||||
recording sli:time_to_ready_fast_ratio:rate15m health=ok state=-
|
||||
recording sli:queue_lag_seconds:max health=ok state=-
|
||||
recording sli:queue_oldest_age_seconds:max health=ok state=-
|
||||
|
||||
== Метрики приложения (Prometheus, имя → labels кроме ресурсных)
|
||||
container_cpu_time_seconds_total series=5 labels=
|
||||
container_memory_usage_bytes series=5 labels=
|
||||
db_client_connection_max series=5 labels=db_client_connection_pool_name
|
||||
db_client_connection_pending_requests series=5 labels=db_client_connection_pool_name
|
||||
db_client_connection_timeouts_total series=5 labels=db_client_connection_pool_name
|
||||
db_client_operation_duration_seconds_bucket series=406 labels=db_operation_name,db_system_name
|
||||
http_server_active_requests series=6 labels=http_request_method
|
||||
http_server_request_duration_seconds_bucket series=525 labels=http_request_method,http_response_status_class,http_response_status_code,http_route
|
||||
messenger_attachment_time_to_ready_seconds_bucket series=14 labels=job_type
|
||||
messenger_broker_ack_pending series=3 labels=queue
|
||||
messenger_broker_pending series=3 labels=queue
|
||||
messenger_container_cpu_limit series=5 labels=
|
||||
messenger_container_memory_limit_bytes series=5 labels=
|
||||
messenger_db_pool_wait_time_seconds_total series=5 labels=db_client_connection_pool_name
|
||||
messenger_job_duration_seconds_bucket series=36 labels=job_type,outcome
|
||||
messenger_job_queue_wait_seconds_bucket series=28 labels=job_type
|
||||
messenger_jobs_processed_total series=3 labels=job_type,messenger_pipeline_version,outcome
|
||||
messenger_outbox_lag_seconds series=3 labels=queue
|
||||
messenger_outbox_pending series=3 labels=queue
|
||||
messenger_outbox_publish_total series=1 labels=messaging_destination_name,outcome
|
||||
messenger_queue_depth series=12 labels=queue,state
|
||||
messenger_queue_lag_seconds series=3 labels=queue
|
||||
messenger_queue_oldest_age_seconds series=3 labels=queue
|
||||
messenger_uploads_total series=1 labels=outcome
|
||||
messenger_worker_busy series=2 labels=
|
||||
messenger_worker_capacity series=2 labels=
|
||||
otel_sdk_exporter_span_exported_total series=4 labels=otel_component_name,otel_component_type,server_address,server_port
|
||||
otel_sdk_exporter_span_inflight series=4 labels=otel_component_name,otel_component_type,server_address,server_port
|
||||
otel_sdk_processor_log_processed_total series=5 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_log_queue_capacity series=5 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_log_queue_size series=5 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_span_processed_total series=4 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_span_queue_capacity series=5 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_processor_span_queue_size series=5 labels=otel_component_name,otel_component_type
|
||||
otel_sdk_span_live series=4 labels=otel_span_sampling_result
|
||||
otel_sdk_span_started_total series=9 labels=otel_span_parent_origin,otel_span_sampling_result
|
||||
process_cpu_time_seconds_total series=10 labels=cpu_mode
|
||||
process_memory_usage_bytes series=5 labels=
|
||||
|
||||
== Loki labels (index): deployment_environment_name,service_instance_id,service_name,service_namespace
|
||||
пример записи messenger-api: поля=deployment_environment_name,detected_level,duration_ms,event,flags,logger,method,observed_timestamp,request_id,route,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,status,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id
|
||||
пример записи messenger-worker: поля=attachment_id,attempt,claims,deployment_environment_name,detected_level,duration_ms,event,flags,job_id,lease_token,logger,observed_timestamp,outcome,pipeline_version,scope_name,service_instance_id,service_name,service_namespace,service_version,severity_number,severity_text,span_id,telemetry_sdk_language,telemetry_sdk_name,telemetry_sdk_version,trace_id
|
||||
|
||||
== Tempo
|
||||
{ resource.service.name = "messenger-api" && kind = server } traces(1h, limit 20)=20
|
||||
{ span.messaging.operation.type = "process" } traces(1h, limit 20)=3
|
||||
{ status = error } traces(1h, limit 20)=1
|
||||
|
||||
== Активные алерты: []
|
||||
exit=0
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-11-21T19:20:06Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url http://127.0.0.1:8080
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
exit=0
|
||||
@@ -0,0 +1,16 @@
|
||||
# 2026-11-21T18:58:12Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ sh -c docker compose --env-file .env ps --format '{{.Service}} {{.Ports}}' | sort -u
|
||||
api 8080/tcp
|
||||
api-ttl 8080/tcp
|
||||
grafana 127.0.0.1:3000->3000/tcp
|
||||
lb 127.0.0.1:8080-8082->8080-8082/tcp, 127.0.0.1:8404->8404/tcp
|
||||
loki
|
||||
nats
|
||||
otel-collector
|
||||
postgres
|
||||
prometheus
|
||||
redis
|
||||
s3
|
||||
tempo
|
||||
worker 8080/tcp
|
||||
exit=0
|
||||
@@ -0,0 +1,54 @@
|
||||
== 2026-11-21T19:20:09Z before restart
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662
|
||||
api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:59.867932045Z pid=1029
|
||||
api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:59:43.740476992Z pid=12265
|
||||
broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:01:47.611250271Z pid=0
|
||||
grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:59:16.762720587Z pid=9695
|
||||
lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:59:47.866767668Z pid=12973
|
||||
loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:13:42.511623661Z pid=4940
|
||||
migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:01:47.4337162Z pid=0
|
||||
nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:59:16.3703735Z pid=9466
|
||||
otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:15:52.258053507Z pid=14597
|
||||
postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:59:16.571171922Z pid=9614
|
||||
prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:59:16.516798581Z pid=9552
|
||||
redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:59:16.497489889Z pid=9550
|
||||
s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:59:17.609330359Z pid=9960
|
||||
s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:01:47.210074838Z pid=0
|
||||
tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:13:43.331107648Z pid=5112
|
||||
tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0
|
||||
worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:01:50.433806313Z pid=21409
|
||||
worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:01:50.6995321Z pid=21486
|
||||
volume mtusi-lab6_grafanadata
|
||||
volume mtusi-lab6_lokidata
|
||||
volume mtusi-lab6_natsdata
|
||||
volume mtusi-lab6_pgdata
|
||||
volume mtusi-lab6_promdata
|
||||
volume mtusi-lab6_s3data
|
||||
volume mtusi-lab6_tempodata
|
||||
== 2026-11-21T19:20:55Z after restart
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T19:20:45.594915217Z pid=5946
|
||||
api mtusi-lab6-api-2 status=running started=2026-11-21T19:20:45.815634018Z pid=6024
|
||||
api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T19:20:50.234402807Z pid=6546
|
||||
broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T19:20:51.342250944Z pid=0
|
||||
grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T19:20:19.771295996Z pid=3701
|
||||
lb mtusi-lab6-lb-1 status=running started=2026-11-21T19:20:55.229584398Z pid=7289
|
||||
loki mtusi-lab6-loki-1 status=running started=2026-11-21T19:20:19.87079258Z pid=3749
|
||||
migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T19:20:51.055582073Z pid=0
|
||||
nats mtusi-lab6-nats-1 status=running started=2026-11-21T19:20:19.345071566Z pid=3471
|
||||
otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T19:20:19.600339631Z pid=3638
|
||||
postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T19:20:19.616612332Z pid=3639
|
||||
prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T19:20:19.559626741Z pid=3550
|
||||
redis mtusi-lab6-redis-1 status=running started=2026-11-21T19:20:19.354224044Z pid=3469
|
||||
s3 mtusi-lab6-s3-1 status=running started=2026-11-21T19:20:20.685593694Z pid=3974
|
||||
s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T19:20:50.778768419Z pid=0
|
||||
tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T19:20:24.235289508Z pid=4214
|
||||
tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T19:13:42.682492554Z pid=0
|
||||
worker mtusi-lab6-worker-1 status=running started=2026-11-21T19:20:54.082584884Z pid=7103
|
||||
worker mtusi-lab6-worker-2 status=running started=2026-11-21T19:20:54.275306102Z pid=7184
|
||||
volume mtusi-lab6_grafanadata
|
||||
volume mtusi-lab6_lokidata
|
||||
volume mtusi-lab6_natsdata
|
||||
volume mtusi-lab6_pgdata
|
||||
volume mtusi-lab6_promdata
|
||||
volume mtusi-lab6_s3data
|
||||
volume mtusi-lab6_tempodata
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-11-21T19:19:34Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ ./scripts/start-replicas.sh
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662
|
||||
api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:34.682252358Z pid=30558
|
||||
exit=0
|
||||
@@ -0,0 +1,5 @@
|
||||
# 2026-11-21T19:19:59Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ ./scripts/start-replicas.sh
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:59:39.635658169Z pid=11662
|
||||
api mtusi-lab6-api-2 status=running started=2026-11-21T19:19:59.867932045Z pid=1029
|
||||
exit=0
|
||||
@@ -0,0 +1,4 @@
|
||||
# 2026-11-21T18:58:11Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc logs --no-log-prefix s3-init
|
||||
{"bucket": "messenger-attachments", "created": true, "checks": {"anonymous ListObjects": ["403", 403, true], "anonymous GetObject": ["403", 403, true], "anonymous PutObject": ["403", 403, true], "anonymous ListBuckets": ["403", 403, true], "api ListObjects own bucket": ["allowed", "allowed", true], "api CreateBucket": ["AccessDenied", "AccessDenied", true]}}
|
||||
exit=0
|
||||
@@ -0,0 +1,4 @@
|
||||
# 2026-11-21T18:58:12Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 tests/smoke.py --base-url http://127.0.0.1:8080
|
||||
PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.
|
||||
exit=0
|
||||
@@ -0,0 +1,62 @@
|
||||
# 2026-11-21T18:58:09Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
docker 29.10.0
|
||||
Docker Compose version v5.7.1
|
||||
CONTAINER REPOSITORY TAG PLATFORM IMAGE ID SIZE CREATED
|
||||
mtusi-lab6-api-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
mtusi-lab6-api-2 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
mtusi-lab6-api-ttl-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
mtusi-lab6-broker-init-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
mtusi-lab6-grafana-1 mtusi-local/grafana 13.3.1 linux/amd64 e5dc6fd6c2e0 2.03GB About an hour ago
|
||||
mtusi-lab6-lb-1 mtusi-local/haproxy 3.0 linux/amd64 4e29ffb6122e 76.2MB About an hour ago
|
||||
mtusi-lab6-loki-1 mtusi-local/loki 3.5.3 linux/amd64 4249c0ad0211 208MB About an hour ago
|
||||
mtusi-lab6-migrate-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
mtusi-lab6-nats-1 mtusi-local/nats 2.11.9 linux/amd64 03b922ee87f1 75MB About an hour ago
|
||||
mtusi-lab6-otel-collector-1 mtusi-local/otelcol-contrib 0.130.0 linux/amd64 03c06afb86eb 439MB About an hour ago
|
||||
mtusi-lab6-postgres-1 mtusi-local/postgres 16 linux/amd64 c0a1aa3931fd 595MB About an hour ago
|
||||
mtusi-lab6-prometheus-1 mtusi-local/prometheus v3.5.0 linux/amd64 b78824a4b58b 487MB About an hour ago
|
||||
mtusi-lab6-redis-1 mtusi-local/redis 7 linux/amd64 5c0e94c0d499 68.8MB About an hour ago
|
||||
mtusi-lab6-s3-1 mtusi-local/seaweedfs 4.52 linux/amd64 cec1afdfce84 258MB About an hour ago
|
||||
mtusi-lab6-s3-init-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
mtusi-lab6-tempo-1 mtusi-local/tempo 2.8.2 linux/amd64 68657d08d39e 183MB About an hour ago
|
||||
mtusi-lab6-tempo-init-1 mtusi-local/tempo 2.8.2 linux/amd64 68657d08d39e 183MB About an hour ago
|
||||
mtusi-lab6-worker-1 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
mtusi-lab6-worker-2 mtusi-lab6-api local linux/amd64 757903805f05 224MB 4 minutes ago
|
||||
NAME IMAGE COMMAND SERVICE CREATED STATUS PORTS
|
||||
mtusi-lab6-api-1 mtusi-lab6-api:local "python -m messenger…" api 23 seconds ago Up 8 seconds (healthy) 8080/tcp
|
||||
mtusi-lab6-api-2 mtusi-lab6-api:local "python -m messenger…" api 23 seconds ago Up 8 seconds (healthy) 8080/tcp
|
||||
mtusi-lab6-api-ttl-1 mtusi-lab6-api:local "python -m messenger…" api-ttl 23 seconds ago Up 7 seconds (healthy) 8080/tcp
|
||||
mtusi-lab6-broker-init-1 mtusi-lab6-api:local "python -m messenger…" broker-init 23 seconds ago Exited (0) 15 seconds ago
|
||||
mtusi-lab6-grafana-1 mtusi-local/grafana:13.3.1 "/run.sh" grafana 23 seconds ago Up 20 seconds (healthy) 127.0.0.1:3000->3000/tcp
|
||||
mtusi-lab6-lb-1 mtusi-local/haproxy:3.0 "haproxy -W -db -f /…" lb 23 seconds ago Up 21 seconds (healthy) 127.0.0.1:8080-8082->8080-8082/tcp, 127.0.0.1:8404->8404/tcp
|
||||
mtusi-lab6-loki-1 mtusi-local/loki:3.5.3 "/usr/bin/loki -conf…" loki 23 seconds ago Up 22 seconds
|
||||
mtusi-lab6-migrate-1 mtusi-lab6-api:local "python -m messenger…" migrate 23 seconds ago Exited (0) 15 seconds ago
|
||||
mtusi-lab6-nats-1 mtusi-local/nats:2.11.9 "nats-server --confi…" nats 23 seconds ago Up 22 seconds (healthy)
|
||||
mtusi-lab6-otel-collector-1 mtusi-local/otelcol-contrib:0.130.0 "/otelcol-contrib --…" otel-collector 23 seconds ago Up 22 seconds
|
||||
mtusi-lab6-postgres-1 mtusi-local/postgres:16 "docker-entrypoint.s…" postgres 23 seconds ago Up 21 seconds (healthy)
|
||||
mtusi-lab6-prometheus-1 mtusi-local/prometheus:v3.5.0 "/bin/prometheus --c…" prometheus 23 seconds ago Up 21 seconds (healthy)
|
||||
mtusi-lab6-redis-1 mtusi-local/redis:7 "sh -c 'umask 077\npr…" redis 23 seconds ago Up 21 seconds (healthy)
|
||||
mtusi-lab6-s3-1 mtusi-local/seaweedfs:4.52 "/usr/bin/weed -logt…" s3 23 seconds ago Up 21 seconds (healthy)
|
||||
mtusi-lab6-s3-init-1 mtusi-lab6-api:local "python -m messenger…" s3-init 23 seconds ago Exited (0) 8 seconds ago
|
||||
mtusi-lab6-tempo-1 mtusi-local/tempo:2.8.2 "/tempo -config.file…" tempo 23 seconds ago Up 20 seconds
|
||||
mtusi-lab6-tempo-init-1 mtusi-local/tempo:2.8.2 "chown -R 10001:1000…" tempo-init 23 seconds ago Exited (0) 20 seconds ago
|
||||
mtusi-lab6-worker-1 mtusi-lab6-api:local "python -m messenger…" worker 23 seconds ago Up 7 seconds (healthy) 8080/tcp
|
||||
mtusi-lab6-worker-2 mtusi-lab6-api:local "python -m messenger…" worker 23 seconds ago Up 7 seconds (healthy) 8080/tcp
|
||||
api mtusi-lab6-api-1 status=running started=2026-11-21T18:58:01.681543345Z pid=2776
|
||||
api mtusi-lab6-api-2 status=running started=2026-11-21T18:58:01.947852642Z pid=2855
|
||||
api-ttl mtusi-lab6-api-ttl-1 status=running started=2026-11-21T18:58:02.666248948Z pid=2971
|
||||
broker-init mtusi-lab6-broker-init-1 status=exited started=2026-11-21T18:57:53.028494218Z pid=0
|
||||
grafana mtusi-lab6-grafana-1 status=running started=2026-11-21T18:57:49.836736597Z pid=1843
|
||||
lb mtusi-lab6-lb-1 status=running started=2026-11-21T18:57:49.184169334Z pid=1608
|
||||
loki mtusi-lab6-loki-1 status=running started=2026-11-21T18:57:47.68953579Z pid=1092
|
||||
migrate mtusi-lab6-migrate-1 status=exited started=2026-11-21T18:57:53.925170786Z pid=0
|
||||
nats mtusi-lab6-nats-1 status=running started=2026-11-21T18:57:47.848213347Z pid=1158
|
||||
otel-collector mtusi-lab6-otel-collector-1 status=running started=2026-11-21T18:57:48.026547716Z pid=1224
|
||||
postgres mtusi-lab6-postgres-1 status=running started=2026-11-21T18:57:48.243808659Z pid=1284
|
||||
prometheus mtusi-lab6-prometheus-1 status=running started=2026-11-21T18:57:48.434191714Z pid=1353
|
||||
redis mtusi-lab6-redis-1 status=running started=2026-11-21T18:57:48.594620877Z pid=1422
|
||||
s3 mtusi-lab6-s3-1 status=running started=2026-11-21T18:57:48.791431799Z pid=1488
|
||||
s3-init mtusi-lab6-s3-init-1 status=exited started=2026-11-21T18:57:58.961524292Z pid=0
|
||||
tempo mtusi-lab6-tempo-1 status=running started=2026-11-21T18:57:49.684613781Z pid=1776
|
||||
tempo-init mtusi-lab6-tempo-init-1 status=exited started=2026-11-21T18:57:48.960422533Z pid=0
|
||||
worker mtusi-lab6-worker-1 status=running started=2026-11-21T18:58:02.221002868Z pid=2912
|
||||
worker mtusi-lab6-worker-2 status=running started=2026-11-21T18:58:03.071993847Z pid=3046
|
||||
@@ -0,0 +1,23 @@
|
||||
# 2026-11-21T19:21:35Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_api.py
|
||||
## API, auth, validation, ACL, transactions (http://127.0.0.1:8080)
|
||||
PASS password stored only as scrypt KDF hash; User has no secret fields 0.81s
|
||||
PASS wrong password and unknown user: identical 401 + Basic challenge 0.79s
|
||||
PASS malformed Basic / Bearer on /auth/sessions / body on login 0.04s
|
||||
PASS password with ':' and non-ASCII UTF-8 works (RFC 7617) 0.71s
|
||||
PASS opaque 256-bit token, unique per login, DB stores only SHA-256 1.19s
|
||||
PASS only Bearer accepted; Basic and X-User-Id never authenticate 0.02s
|
||||
PASS logout revokes only the current session; repeat -> 401 1.22s
|
||||
PASS strict JSON validation -> 400 0.03s
|
||||
PASS message text: 4000 code points OK, 4001 / whitespace / sender_id -> 400 0.03s
|
||||
PASS SQL is parameterized: injection payloads stored verbatim 0.02s
|
||||
PASS ACL: outsider gets 404 everywhere (even for invalid body) 0.03s
|
||||
PASS create chat validation: duplicates, caller missing, unknown member 0.01s
|
||||
PASS compound create-chat rolls back on FK failure (no orphan chat) 0.84s chats before=16, failed insert left 0 rows
|
||||
PASS registration race: 20 parallel same username -> exactly one 201 3.90s 201x1, 409x19, rows=1
|
||||
PASS keyset pagination: 120 msgs, varying limit, no gaps/duplicates 1.03s 4 pages
|
||||
PASS chat list: only own chats, ordered, cursor bound to user 0.55s
|
||||
PASS read-after-write: confirmed message visible to next read 0.01s
|
||||
PASS unknown route 404 / wrong method 405 in error format 0.00s
|
||||
summary: 18 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,18 @@
|
||||
# 2026-11-21T20:04:44Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_attachments.py
|
||||
## attachments (http://127.0.0.1:8080)
|
||||
PASS valid PNG and JPEG: 202 queued → ready, byte-exact download by other member 0.74s
|
||||
PASS exactly-near limit (~10 MiB) accepted, Content-Length > limit -> 413 0.54s 10.00 MiB accepted
|
||||
PASS oversize rejected BEFORE body is read (early 413, socket) 0.02s HTTP/1.1 413 Content Too Large in 0.016s, 50 MiB never sent
|
||||
PASS pixel limit: 8000x6000 header -> 413 without decoding 0.09s 0.092s
|
||||
PASS decompression bomb: IDAT inflates beyond declared size -> 415 0.32s 65295-byte file claiming 64 MiB raw, rejected in 0.046s
|
||||
PASS corrupted images -> 415 (truncated, bad CRC, no EOI, garbage, empty) 0.29s 9 variants
|
||||
PASS MIME spoofing by Content-Type/filename -> 415 0.37s
|
||||
PASS dangerous/invalid filenames -> 400; filename never becomes a path 0.19s
|
||||
PASS missing/invalid Content-Length -> 400 (chunked upload is not accepted) 0.00s HTTP/1.1 400 Bad Request
|
||||
PASS ACL: outsider gets 404 for upload/metadata/content; anonymous 401 0.47s outsider 10 MiB upload rejected in 0.33s
|
||||
PASS variants (lab5): original/thumbnail/crop/optimized OK after ready, unknown -> 400 0.76s
|
||||
PASS message: foreign/unknown attachment_id -> 404, file of other chat -> 404, limits -> 400 0.15s
|
||||
PASS idempotency includes attachment_ids (replay same, conflict on change) 0.19s
|
||||
summary: 13 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,15 @@
|
||||
# 2026-11-21T19:22:05Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc run --rm --no-deps -T -v /home/claude/work6/mtusi2026lab6/student-tests:/app/student-tests:ro --entrypoint python api student-tests/test_cache_race.py
|
||||
Container mtusi-lab6-api-run-b1fb72351b97 Creating
|
||||
Container mtusi-lab6-api-run-b1fb72351b97 Created
|
||||
PASS read-through put makes entry readable
|
||||
PASS entry TTL capped by SESSION_CACHE_TTL_SECONDS pttl=60000ms
|
||||
PASS invalidate removes entry
|
||||
PASS late put after logout is refused by tombstone
|
||||
PASS tombstone outlives any cache entry pttl=75000ms
|
||||
PASS entry never outlives session expiry pttl=1199ms
|
||||
PASS expired session not served from cache
|
||||
cache unavailable; falling back to PostgreSQL
|
||||
PASS degraded mode: cache is not read until outbox drained
|
||||
summary: all passed
|
||||
exit=0
|
||||
@@ -0,0 +1,8 @@
|
||||
# 2026-11-21T19:21:55Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_expiry.py
|
||||
## session expiry, SESSION_TTL_SECONDS=2 (http://127.0.0.1:8081)
|
||||
PASS expires_at = now + SESSION_TTL_SECONDS 0.97s remaining 2.00s
|
||||
PASS token valid before expiry, 401 Bearer after (cache warmed) 4.50s
|
||||
PASS re-login after expiry issues a new valid session 4.60s
|
||||
summary: 3 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,7 @@
|
||||
# 2026-11-21T19:28:40Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_failures.py
|
||||
## dependency failures (http://127.0.0.1:8080)
|
||||
PASS Redis down: API bypasses cache via PostgreSQL, no anonymous trust 6.96s fallback latency 0.013s; outbox rows during outage=1, drained after recovery
|
||||
PASS PostgreSQL down: bounded 503 in error format; anonymous still 401 14.93s latency(s)={'ready': 1.51, 'post_message': 2.02, 'history': 2.02, 'login': 2.02, 'register': 2.02}; ready again in 2.2s
|
||||
summary: 2 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,14 @@
|
||||
# 2026-11-21T19:21:49Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_idempotency.py
|
||||
## idempotency across replicas (http://127.0.0.1:8080)
|
||||
PASS sequential replays: same 201 + same Message from different replicas 0.39s replicas=2, rows=1
|
||||
PASS 30 concurrent POSTs, same key + body, via LB -> exactly one message 1.76s per-replica responses {'api-778c97df': 16, 'api-7c6946d6': 14}, rows=1
|
||||
PASS concurrent same key, two different bodies -> one message, others 201-same or 409 1.05s 201x10, 409x10
|
||||
PASS after commit: different body -> 409; reordered/whitespace JSON -> replay 0.03s
|
||||
PASS scope: user + chat + key (same key elsewhere is independent) 0.03s
|
||||
PASS key format: missing/empty/129 chars/invalid -> 400; 128 chars ok 0.04s
|
||||
PASS failed attempt does not claim the key (400/404 not recorded) 0.03s
|
||||
PASS replay re-checks session and access 0.36s
|
||||
PASS key older than IDEMPOTENCY_TTL_SECONDS is reusable (24 h window) 0.59s
|
||||
summary: 9 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,14 @@
|
||||
# 2026-11-21T19:21:17Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ dc run --rm --no-deps -T -v /home/claude/work6/mtusi2026lab6/student-tests:/app/student-tests:ro --entrypoint python worker student-tests/test_imgproc.py
|
||||
Container mtusi-lab6-worker-run-9cf4e4401d71 Creating
|
||||
Container mtusi-lab6-worker-run-9cf4e4401d71 Created
|
||||
PASS fixture 320×200 → thumbnail 256×160, crop 128×128, optimized WebP 320×200 0.81s
|
||||
PASS rounding down and minimum 1 px: 3000×10 → 256×1, 1280×4 0.26s
|
||||
PASS EXIF orientation 6 applied (400×200 stored → 128×256); orientation tag not copied 0.26s
|
||||
PASS alpha composited on white for JPEG variants; WebP keeps alpha 0.26s
|
||||
PASS metadata removed: EXIF/XMP/ICC of the source are not in any variant 0.29s
|
||||
PASS deterministic output (same bytes on re-run) — basis of idempotent effect; v2 differs 0.98s
|
||||
PASS limits: pixels by header (413-class), memory (RLIMIT_AS), undecodable → permanent 0.78s too_large / resource_limit / invalid_image
|
||||
PASS worker wall-clock timeout kills the subprocess → transient (retry), not a hang 0.25s killed after 0.05s; undecodable → Permanent(invalid_image)
|
||||
summary: 8 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,19 @@
|
||||
# 2026-11-21T20:04:50Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_jobs_failures.py
|
||||
## pipeline failures (http://127.0.0.1:8080)
|
||||
PASS defense: worker stopped → 202 → 409 → message ok → restart API+broker (volumes kept) → worker → ready 28.39s attachment 8fdfa0e4: stream held 1→1 msgs across restart; ready 1.9s after worker start
|
||||
PASS broker down: upload still 202 (job durable in outbox), ready after broker returns 10.26s 202 with broker stopped; events ['enqueued', 'published', 'claimed']
|
||||
PASS crash between COMMIT and publish: relay of another process publishes, job reaches ready 23.31s api-fault (api-876964dc) died after COMMIT; published by relay api-api-2ba718cd; events ['enqueued', 'published', 'claimed', 'committed', 'published_version_changed', 'staging_cleaned']
|
||||
PASS crash between publish ack and outbox mark: duplicate publish dropped by Nats-Msg-Id 24.24s second publish: duplicate=true, stream_seq=800; processed once
|
||||
PASS worker crash after claim, before any side effect → lease takeover → ready 23.62s ['enqueued', 'published', 'claimed', 'lease_takeover', 'committed', 'published_version_changed', 'staging_cleaned'] in 23.6s
|
||||
PASS worker crash after S3 writes, before COMMIT → takeover rewrites the same keys, one result 24.04s ['enqueued', 'published', 'claimed', 'lease_takeover', 'committed', 'published_version_changed', 'staging_cleaned'] in 23.6s; keys deterministic: ['crop.jpg', 'optimized.webp', 'thumbnail.jpg']
|
||||
PASS worker crash after COMMIT, before ack → redelivery is a no-op (duplicate_ignored) 22.52s ['enqueued', 'published', 'claimed', 'committed', 'published_version_changed', 'staging_cleaned', 'duplicate_ignored']
|
||||
PASS hung worker (event loop blocked 45 s) loses lease; takeover commits; zombie commit is fenced 47.14s claimed t799 → takeover t800 → committed t800; zombie (t799) → lease_lost
|
||||
PASS long but alive job (35 s > lease 20 s): heartbeat keeps the lease, no takeover, no duplicate 36.32s ready after 36.3s, ['enqueued', 'published', 'claimed', 'committed', 'published_version_changed', 'staging_cleaned']
|
||||
PASS transient errors: retry with backoff + jitter (2 failures), then ready 7.10s delays 1.56s, 3.97s (windows [1,2], [2,4]); actual gaps [1.7, 4.01]; attempts [1, 2, 3]
|
||||
PASS retries exhausted → failed retry_exhausted (in registry) → operator replay → ready 28.29s 5 attempts → retry_exhausted; replay (attempt 6) → ready
|
||||
PASS processing with expired lease and LOST message → reaper requeues → ready 15.50s purged 1 stream msgs; ['claimed', 'committed', 'published_version_changed', 'staging_cleaned']
|
||||
PASS bounded concurrency: never more than replicas × WORKER_CONCURRENCY jobs in processing 18.46s 8 jobs × ~4 s: peak concurrency 4 (limit 4), wall 10.0s
|
||||
PASS staging removed after ready; failed staging kept until retention, then replay refuses honestly 17.37s ready: staging gone, originals/ present; failed: staging kept, removed after retention; replay refused
|
||||
summary: 14 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,15 @@
|
||||
# 2026-11-21T20:12:41Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_observability.py
|
||||
## lab6: наблюдаемость — provisioning, сигналы, корреляция, безопасность telemetry
|
||||
PASS provisioning: Prometheus/Loki/Tempo из Git, health OK 0.05s health OK: prometheus, loki, tempo
|
||||
PASS provisioning: dashboard импортирован, все запросы панелей выполняются 3.08s 33 панелей, 60 запросов без ошибок, с данными 57
|
||||
PASS HTTP: X-Request-Id → структурный лог → trace (server + DB spans) 1.69s request_id → trace 28b17ed52654…, 8 spans (5 DB)
|
||||
PASS безопасность: пароль, токен, тело сообщения не попадают в логи/трассы 3.81s проверено в Loki и 2 trace: пароль, токен, текст сообщения, Authorization
|
||||
PASS upload → create → send → process → S3/DB: один trace; лог worker с тем же trace_id 5.56s 55 spans: SERVER→create→send→process(messenger-worker)→S3×4; queue -0.00 с
|
||||
PASS retry: 2 временные ошибки + успех — три попытки в одном trace 9.66s попытки 1→2→3: ['retry', 'retry', 'ready']; паузы backoff 1.7 с и 3.7 с
|
||||
PASS метрики контракта: имена, низкая кардинальность, шаблоны маршрутов 0.23s 20 метрик; серий 5254 (HTTP count — 100); маршрутов 12; запрещённых labels нет
|
||||
PASS метрики отражают обработку: jobs, retry, time-to-ready, p95 из histogram 0.04s ready=16 retry=8 time_to_ready count=16; p95 HTTP 37 мс, p95 ready 2.77 с
|
||||
PASS алерты: правила загружены и вычисляются без ошибок 0.01s 18 правил (10 алертов), firing сейчас: ['TelemetryLostInSdk']
|
||||
PASS SDK: spans/logs не отбрасываются при работающем Collector 0.02s обработано spans 13125, отброшено 0
|
||||
summary: 10 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,15 @@
|
||||
# 2026-11-21T18:58:16Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_observability.py
|
||||
## lab6: наблюдаемость — provisioning, сигналы, корреляция, безопасность telemetry
|
||||
PASS provisioning: Prometheus/Loki/Tempo из Git, health OK 0.07s health OK: prometheus, loki, tempo
|
||||
PASS provisioning: dashboard импортирован, все запросы панелей выполняются 1.23s 33 панелей, 60 запросов без ошибок, с данными 3
|
||||
PASS HTTP: X-Request-Id → структурный лог → trace (server + DB spans) 2.75s request_id → trace 2e5e8df8dff7…, 8 spans (5 DB)
|
||||
PASS безопасность: пароль, токен, тело сообщения не попадают в логи/трассы 2.42s проверено в Loki и 2 trace: пароль, токен, текст сообщения, Authorization
|
||||
PASS upload → create → send → process → S3/DB: один trace; лог worker с тем же trace_id 11.88s 55 spans: SERVER→create→send→process(messenger-worker)→S3×4; queue 0.00 с
|
||||
PASS retry: 2 временные ошибки + успех — три попытки в одном trace 9.72s попытки 1→2→3: ['retry', 'retry', 'ready']; паузы backoff 2.0 с и 3.0 с
|
||||
PASS метрики контракта: имена, низкая кардинальность, шаблоны маршрутов 0.24s 20 метрик; серий 1180 (HTTP count — 35); маршрутов 12; запрещённых labels нет
|
||||
PASS метрики отражают обработку: jobs, retry, time-to-ready, p95 из histogram 2.12s ready=3 retry=2 time_to_ready count=3; p95 HTTP 466 мс, p95 ready 9.75 с
|
||||
PASS алерты: правила загружены и вычисляются без ошибок 0.02s 18 правил (10 алертов), firing сейчас: нет
|
||||
PASS SDK: spans/logs не отбрасываются при работающем Collector 0.02s обработано spans 577, отброшено 0
|
||||
summary: 10 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,13 @@
|
||||
# 2026-11-21T19:20:57Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_pipeline.py
|
||||
## attachment pipeline (http://127.0.0.1:8080)
|
||||
PASS upload → 202 queued snapshot, then ready; original byte-exact; three variants by contract 1.20s ready 0.94s after 202; thumbnail 256×160, crop 128×128, optimized 320×200 WebP
|
||||
PASS big image: optimized fits 1280 without upscale, thumbnail rounds down 1.15s thumbnail 256x170, optimized 1280x852
|
||||
PASS EXIF orientation applied (stored 400×200, orientation 6 → 200×400); tiny image not upscaled 2.10s
|
||||
PASS variant parameter: unknown → 400; default original; outsider → 404 0.67s
|
||||
PASS undecodable image → failed with safe error_code, no retries; content 409; cannot attach (409) 2.54s events ['enqueued', 'published', 'claimed', 'failed']; listed in failed registry
|
||||
PASS queued/processing attachment can be attached to a message right away 0.69s
|
||||
PASS duplicate deliveries of a finished job are no-ops (5 raw duplicates) 6.57s committed ×1, duplicate_ignored ×5, metadata unchanged
|
||||
PASS replay is safe: ready → noop; failed (permanent) → re-executed once, failed again 3.48s ready: noop; failed: replayed (audit by student) → failed again (permanent error)
|
||||
summary: 8 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,10 @@
|
||||
# 2026-11-21T19:27:17Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_storage_failures.py
|
||||
## object storage failures (http://127.0.0.1:8080)
|
||||
PASS bucket is private outside API: anonymous GET/LIST/PUT denied, API key limited 5.14s anon GET 403; s3-check 6/6 PASS
|
||||
PASS S3 down: upload/download 503 fast, text messages and readiness keep working 30.19s 503 in 0.03s/0.02s; after start: reads 4.3s, writes 23.5s
|
||||
PASS interrupted upload: no object and no intent left behind 10.15s objects 2, intents 1 — unchanged
|
||||
PASS uploads rejected at the very end (truncated PNG) leave no staging object (race regression) 9.18s 30 × 415 at finish(); staging objects 2 → 2
|
||||
PASS crash between staging PUT and DB COMMIT: intent recorded, janitor removes object after grace 26.63s orphan staging/a0244d5cebee… removed 11.2s after crash (grace 10 s)
|
||||
summary: 5 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,9 @@
|
||||
# 2026-11-21T18:58:48Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_telemetry_persistence.py
|
||||
## lab6: сохранность истории telemetry после перезапуска
|
||||
PASS до рестарта: лог, trace и метрика контрольного запроса сохранены 17.70s request_id → trace e7fcbc6308a9…, счётчик POST messages = 13
|
||||
PASS перезапуск всех сервисов и хранилищ (volumes сохраняются) 43.11s hook scripts/restart.sh + готовность за 43 с
|
||||
PASS после рестарта: тот же лог, тот же trace, то же значение метрики в прошлом 0.19s лог, trace (8 spans), метрика (13) и dashboard на месте
|
||||
PASS после рестарта: новые данные доходят во все три хранилища 3.82s новый trace 1bd7c465a6c1…, текущий RPS API 0.98
|
||||
summary: 4 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,12 @@
|
||||
# 2026-11-21T19:29:03Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 student-tests/test_pipeline_idempotency.py
|
||||
## track 2: pipeline idempotency (http://127.0.0.1:8080)
|
||||
PASS D: 8 duplicate copies of one job delivered concurrently → one claim, one commit 32.45s 9 deliveries: claimed 1, committed 1, duplicate_ignored 8
|
||||
PASS R: reorder — stale attempts (1, 2) and a future one arrive DURING attempt 3 → ignored 22.85s during attempt 3: attempts 2, 1 → stale_ignored; 9 → stale_ignored(future) + term; one commit
|
||||
PASS C: crash before/after side effect, after COMMIT, hung worker — all reach one result 46.64s {'crash-before-s3': 'takeover', 'crash-after-s3': 'takeover', 'crash-after-commit': 'dup_ignored', 'hang-40': 'takeover'}
|
||||
PASS V1: stale v1 job after v2 is published → superseded, no v1 side effects 22.25s v2 ready first; v1 → superseded at claim; variants only v2, pointer 2
|
||||
PASS V2: version race — slow v1 commits after v2 → pointer stays on v2 (no overwrite by older) 16.43s v1 finished after v2 → superseded at commit; pointer history [(None, 2)]
|
||||
PASS V3: redelivered v1 after v2 rollout and repeated reprocess are no-ops 7.65s v1 ready → v2 ready (pointer 1→2); 3 v1 duplicates ignored; reprocess v1/v2 again → noop
|
||||
PASS invariants I1–I7 hold for everything this suite produced (settled, bytes verified) 3.37s attachments 9, jobs 12 {'ready': 10, 'superseded': 2}, variants 33, events 91
|
||||
summary: 7 passed, 0 failed
|
||||
exit=0
|
||||
@@ -0,0 +1,283 @@
|
||||
# 2026-11-21T19:33:37Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1
|
||||
[22:33:37] run off: apply config
|
||||
[22:35:47] run off: {"ok_rps": 58.8, "lat_p50_ms": 6.3, "lat_p95_ms": 27.2, "lat_p99_ms": 56.5}
|
||||
[22:35:47] run full: apply config
|
||||
[22:38:01] run full: {"ok_rps": 58.8, "lat_p50_ms": 8.6, "lat_p95_ms": 43.2, "lat_p99_ms": 106.8, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]}
|
||||
[22:38:01] run head10: apply config
|
||||
[22:40:16] run head10: {"ok_rps": 58.8, "lat_p50_ms": 7.1, "lat_p95_ms": 29.2, "lat_p99_ms": 68.5, "errors_found_in_tempo": [2, 45], "slow_found_in_tempo": [2, 45]}
|
||||
[22:40:16] run tail: apply config
|
||||
[22:42:44] run tail: {"ok_rps": 58.8, "lat_p50_ms": 9.7, "lat_p95_ms": 67.0, "lat_p99_ms": 243.0, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]}
|
||||
[22:42:44] run off: apply config
|
||||
[22:45:07] run off: {"ok_rps": 58.8, "lat_p50_ms": 6.2, "lat_p95_ms": 21.5, "lat_p99_ms": 41.5}
|
||||
[22:45:07] run full: apply config
|
||||
[22:47:22] run full: {"ok_rps": 58.8, "lat_p50_ms": 9.8, "lat_p95_ms": 50.5, "lat_p99_ms": 113.0, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]}
|
||||
[22:47:22] run head10: apply config
|
||||
[22:49:40] run head10: {"ok_rps": 58.8, "lat_p50_ms": 6.7, "lat_p95_ms": 24.6, "lat_p99_ms": 53.6, "errors_found_in_tempo": [1, 45], "slow_found_in_tempo": [4, 45]}
|
||||
[22:49:40] run tail: apply config
|
||||
[22:52:07] run tail: {"ok_rps": 58.8, "lat_p50_ms": 9.1, "lat_p95_ms": 55.7, "lat_p99_ms": 140.1, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]}
|
||||
[22:52:07] run off: apply config
|
||||
[22:54:29] run off: {"ok_rps": 58.8, "lat_p50_ms": 5.5, "lat_p95_ms": 18.7, "lat_p99_ms": 40.4}
|
||||
[22:54:29] run full: apply config
|
||||
[22:56:45] run full: {"ok_rps": 58.8, "lat_p50_ms": 8.7, "lat_p95_ms": 42.8, "lat_p99_ms": 132.1, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]}
|
||||
[22:56:45] run head10: apply config
|
||||
[22:59:01] run head10: {"ok_rps": 58.8, "lat_p50_ms": 5.9, "lat_p95_ms": 22.2, "lat_p99_ms": 51.5, "errors_found_in_tempo": [2, 45], "slow_found_in_tempo": [3, 45]}
|
||||
[22:59:01] run tail: apply config
|
||||
[23:01:31] run tail: {"ok_rps": 58.8, "lat_p50_ms": 7.6, "lat_p95_ms": 37.8, "lat_p99_ms": 97.0, "errors_found_in_tempo": [45, 45], "slow_found_in_tempo": [45, 45]}
|
||||
[23:01:31] restore config full
|
||||
{
|
||||
"meta": {
|
||||
"rate_rps": 60.0,
|
||||
"window_s": 60,
|
||||
"warmup_s": 15,
|
||||
"reps": 3,
|
||||
"configs": {
|
||||
"off": {
|
||||
"OTEL_SDK_DISABLED": "true",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "1.0",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector.yaml"
|
||||
},
|
||||
"full": {
|
||||
"OTEL_SDK_DISABLED": "false",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "1.0",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector.yaml"
|
||||
},
|
||||
"head10": {
|
||||
"OTEL_SDK_DISABLED": "false",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "0.1",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector.yaml"
|
||||
},
|
||||
"tail": {
|
||||
"OTEL_SDK_DISABLED": "false",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "1.0",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector-tail.yaml"
|
||||
}
|
||||
},
|
||||
"host_cpus": 2,
|
||||
"date": "2026-11-21T20:01:39Z"
|
||||
},
|
||||
"table": {
|
||||
"off": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 6.2,
|
||||
"p95_ms": 21.5,
|
||||
"p99_ms": 41.5,
|
||||
"p95_ms_runs": [
|
||||
27.2,
|
||||
21.5,
|
||||
18.7
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 30.5,
|
||||
"mem_api_mib": 106.4,
|
||||
"cpu_worker_pct": 52.3,
|
||||
"mem_worker_mib": 87.2,
|
||||
"cpu_collector_pct": 0.1,
|
||||
"mem_collector_mib": 31.2,
|
||||
"cpu_backends_pct": 2.5,
|
||||
"mem_backends_mib": 362.6,
|
||||
"cpu_postgres_pct": 8.0,
|
||||
"mem_postgres_mib": 73.1
|
||||
},
|
||||
"full": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 8.7,
|
||||
"p95_ms": 43.2,
|
||||
"p99_ms": 113.0,
|
||||
"p95_ms_runs": [
|
||||
43.2,
|
||||
50.5,
|
||||
42.8
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 43.4,
|
||||
"mem_api_mib": 124.0,
|
||||
"cpu_worker_pct": 39.0,
|
||||
"mem_worker_mib": 97.1,
|
||||
"cpu_collector_pct": 1.3,
|
||||
"mem_collector_mib": 45.8,
|
||||
"cpu_backends_pct": 4.6,
|
||||
"mem_backends_mib": 373.4,
|
||||
"cpu_postgres_pct": 8.7,
|
||||
"mem_postgres_mib": 89.1,
|
||||
"col_spans_in_per_s": 482.8,
|
||||
"col_spans_out_per_s": 482.8,
|
||||
"tempo_bytes_per_s": 147204.9,
|
||||
"tempo_spans_per_s": 482.8,
|
||||
"loki_bytes_per_s": 18815.5,
|
||||
"loki_lines_per_s": 62.2,
|
||||
"col_points_in_per_s": 35.8,
|
||||
"prom_samples_per_s": 1274.8,
|
||||
"sdk_lost": 0,
|
||||
"col_refused": 0,
|
||||
"col_send_failed": 0,
|
||||
"sdk_sampled_share": 1.0,
|
||||
"red_5xx_vs_injected": [
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
]
|
||||
],
|
||||
"spanmetrics_vs_sdk_calls": [
|
||||
[
|
||||
4500.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
4500.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
4500.0,
|
||||
4500.0
|
||||
]
|
||||
],
|
||||
"errors_found_in_tempo": "135/135",
|
||||
"slow_found_in_tempo": "135/135",
|
||||
"natural_slow_found_in_tempo": "12/12"
|
||||
},
|
||||
"head10": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 6.7,
|
||||
"p95_ms": 24.6,
|
||||
"p99_ms": 53.6,
|
||||
"p95_ms_runs": [
|
||||
29.2,
|
||||
24.6,
|
||||
22.2
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 32.2,
|
||||
"mem_api_mib": 116.0,
|
||||
"cpu_worker_pct": 28.1,
|
||||
"mem_worker_mib": 97.5,
|
||||
"cpu_collector_pct": 0.6,
|
||||
"mem_collector_mib": 51.4,
|
||||
"cpu_backends_pct": 3.4,
|
||||
"mem_backends_mib": 349.7,
|
||||
"cpu_postgres_pct": 7.7,
|
||||
"mem_postgres_mib": 78.7,
|
||||
"col_spans_in_per_s": 48.2,
|
||||
"col_spans_out_per_s": 48.2,
|
||||
"tempo_bytes_per_s": 15248.0,
|
||||
"tempo_spans_per_s": 48.2,
|
||||
"loki_bytes_per_s": 18812.7,
|
||||
"loki_lines_per_s": 62.3,
|
||||
"col_points_in_per_s": 36.6,
|
||||
"prom_samples_per_s": 1253.6,
|
||||
"sdk_lost": 0,
|
||||
"col_refused": 0,
|
||||
"col_send_failed": 0,
|
||||
"sdk_sampled_share": 0.4533439069521544,
|
||||
"red_5xx_vs_injected": [
|
||||
[
|
||||
7.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
]
|
||||
],
|
||||
"spanmetrics_vs_sdk_calls": [
|
||||
[
|
||||
406.0,
|
||||
4492.0
|
||||
],
|
||||
[
|
||||
483.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
431.0,
|
||||
4500.0
|
||||
]
|
||||
],
|
||||
"errors_found_in_tempo": "5/135",
|
||||
"slow_found_in_tempo": "9/135",
|
||||
"natural_slow_found_in_tempo": "0/3"
|
||||
},
|
||||
"tail": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 9.1,
|
||||
"p95_ms": 55.7,
|
||||
"p99_ms": 140.1,
|
||||
"p95_ms_runs": [
|
||||
67.0,
|
||||
55.7,
|
||||
37.8
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 42.8,
|
||||
"mem_api_mib": 123.5,
|
||||
"cpu_worker_pct": 30.2,
|
||||
"mem_worker_mib": 97.3,
|
||||
"cpu_collector_pct": 1.4,
|
||||
"mem_collector_mib": 50.2,
|
||||
"cpu_backends_pct": 5.4,
|
||||
"mem_backends_mib": 574.7,
|
||||
"cpu_postgres_pct": 8.6,
|
||||
"mem_postgres_mib": 91.3,
|
||||
"col_spans_in_per_s": 482.8,
|
||||
"col_spans_out_per_s": 79.6,
|
||||
"tempo_bytes_per_s": 27868.7,
|
||||
"tempo_spans_per_s": 79.6,
|
||||
"loki_bytes_per_s": 18806.3,
|
||||
"loki_lines_per_s": 62.2,
|
||||
"col_points_in_per_s": 36.1,
|
||||
"prom_samples_per_s": 1269.0,
|
||||
"sdk_lost": 0,
|
||||
"col_refused": 0,
|
||||
"col_send_failed": 0,
|
||||
"sdk_sampled_share": 1.0,
|
||||
"red_5xx_vs_injected": [
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
]
|
||||
],
|
||||
"spanmetrics_vs_sdk_calls": [
|
||||
[
|
||||
539.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
543.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
584.0,
|
||||
4500.0
|
||||
]
|
||||
],
|
||||
"errors_found_in_tempo": "135/135",
|
||||
"slow_found_in_tempo": "135/135",
|
||||
"natural_slow_found_in_tempo": "15/34"
|
||||
}
|
||||
}
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,857 @@
|
||||
[
|
||||
{
|
||||
"config": "off",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 6.3,
|
||||
"lat_p95_ms": 27.2,
|
||||
"lat_p99_ms": 56.5,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 31.1,
|
||||
"mem_mib_avg": 107.4,
|
||||
"mem_mib_max": 152.6
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 52.3,
|
||||
"mem_mib_avg": 87.2,
|
||||
"mem_mib_max": 119.8
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 0.1,
|
||||
"mem_mib_avg": 50.3,
|
||||
"mem_mib_max": 50.7
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 2.4,
|
||||
"mem_mib_avg": 406.2,
|
||||
"mem_mib_max": 510.0
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 8.8,
|
||||
"mem_mib_avg": 64.5,
|
||||
"mem_mib_max": 66.7
|
||||
}
|
||||
},
|
||||
"rep": 1
|
||||
},
|
||||
{
|
||||
"config": "full",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 8.6,
|
||||
"lat_p95_ms": 43.2,
|
||||
"lat_p99_ms": 106.8,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 43.4,
|
||||
"mem_mib_avg": 124.0,
|
||||
"mem_mib_max": 166.6
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 36.6,
|
||||
"mem_mib_avg": 97.1,
|
||||
"mem_mib_max": 116.1
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 1.3,
|
||||
"mem_mib_avg": 52.3,
|
||||
"mem_mib_max": 53.1
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 4.6,
|
||||
"mem_mib_avg": 355.3,
|
||||
"mem_mib_max": 450.9
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 8.3,
|
||||
"mem_mib_avg": 71.1,
|
||||
"mem_mib_max": 81.3
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 36443.0,
|
||||
"col_spans_out": 36443.0,
|
||||
"col_logs_in": 4696.0,
|
||||
"col_points_in": 2681.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 11113140.0,
|
||||
"tempo_spans": 36443.0,
|
||||
"loki_bytes": 1420263.0,
|
||||
"loki_lines": 4696.0,
|
||||
"prom_samples": 96969.0,
|
||||
"sdk_started": 35147.0,
|
||||
"sdk_sampled": 35147.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 4500.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 482.8,
|
||||
"col_spans_out": 482.8,
|
||||
"col_logs_in": 62.2,
|
||||
"col_points_in": 35.5,
|
||||
"tempo_bytes": 147225.6,
|
||||
"tempo_spans": 482.8,
|
||||
"loki_bytes": 18815.5,
|
||||
"loki_lines": 62.2,
|
||||
"prom_samples": 1284.6
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 0,
|
||||
"natural_slow_found_in_tempo": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"rep": 1
|
||||
},
|
||||
{
|
||||
"config": "head10",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 7.1,
|
||||
"lat_p95_ms": 29.2,
|
||||
"lat_p99_ms": 68.5,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 34.2,
|
||||
"mem_mib_avg": 116.7,
|
||||
"mem_mib_max": 147.4
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 39.0,
|
||||
"mem_mib_avg": 97.5,
|
||||
"mem_mib_max": 150.7
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 0.6,
|
||||
"mem_mib_avg": 52.9,
|
||||
"mem_mib_max": 53.1
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 3.4,
|
||||
"mem_mib_avg": 326.1,
|
||||
"mem_mib_max": 329.5
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 7.7,
|
||||
"mem_mib_avg": 72.9,
|
||||
"mem_mib_max": 82.3
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 3487.0,
|
||||
"col_spans_out": 3487.0,
|
||||
"col_logs_in": 4696.0,
|
||||
"col_points_in": 2765.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 1106907.0,
|
||||
"tempo_spans": 3487.0,
|
||||
"loki_bytes": 1418988.0,
|
||||
"loki_lines": 4696.0,
|
||||
"prom_samples": 99872.0,
|
||||
"sdk_started": 1637.0,
|
||||
"sdk_sampled": -2521.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 7.0,
|
||||
"red_all": 4492.0,
|
||||
"spanmetrics_calls": 406.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 46.2,
|
||||
"col_spans_out": 46.2,
|
||||
"col_logs_in": 62.2,
|
||||
"col_points_in": 36.6,
|
||||
"tempo_bytes": 14664.2,
|
||||
"tempo_spans": 46.2,
|
||||
"loki_bytes": 18798.6,
|
||||
"loki_lines": 62.2,
|
||||
"prom_samples": 1323.1
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
2,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
2,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 3,
|
||||
"natural_slow_found_in_tempo": [
|
||||
0,
|
||||
3
|
||||
],
|
||||
"rep": 1
|
||||
},
|
||||
{
|
||||
"config": "tail",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 9.7,
|
||||
"lat_p95_ms": 67.0,
|
||||
"lat_p99_ms": 243.0,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 43.4,
|
||||
"mem_mib_avg": 124.0,
|
||||
"mem_mib_max": 165.8
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 30.2,
|
||||
"mem_mib_avg": 97.3,
|
||||
"mem_mib_max": 134.9
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 1.5,
|
||||
"mem_mib_avg": 49.7,
|
||||
"mem_mib_max": 56.8
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 5.4,
|
||||
"mem_mib_avg": 576.7,
|
||||
"mem_mib_max": 599.4
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 8.6,
|
||||
"mem_mib_avg": 89.9,
|
||||
"mem_mib_max": 101.1
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 36443.0,
|
||||
"col_spans_out": 5964.0,
|
||||
"col_logs_in": 4696.0,
|
||||
"col_points_in": 2696.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 2095361.0,
|
||||
"tempo_spans": 5964.0,
|
||||
"loki_bytes": 1420629.0,
|
||||
"loki_lines": 4696.0,
|
||||
"prom_samples": 108641.0,
|
||||
"sdk_started": 35147.0,
|
||||
"sdk_sampled": 35147.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 539.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 482.8,
|
||||
"col_spans_out": 79.0,
|
||||
"col_logs_in": 62.2,
|
||||
"col_points_in": 35.7,
|
||||
"tempo_bytes": 27759.1,
|
||||
"tempo_spans": 79.0,
|
||||
"loki_bytes": 18820.3,
|
||||
"loki_lines": 62.2,
|
||||
"prom_samples": 1439.3
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 35,
|
||||
"natural_slow_found_in_tempo": [
|
||||
15,
|
||||
30
|
||||
],
|
||||
"rep": 1
|
||||
},
|
||||
{
|
||||
"config": "off",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 6.2,
|
||||
"lat_p95_ms": 21.5,
|
||||
"lat_p99_ms": 41.5,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 30.5,
|
||||
"mem_mib_avg": 106.4,
|
||||
"mem_mib_max": 128.4
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 54.2,
|
||||
"mem_mib_avg": 88.9,
|
||||
"mem_mib_max": 128.2
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 0.1,
|
||||
"mem_mib_avg": 30.7,
|
||||
"mem_mib_max": 32.1
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 2.5,
|
||||
"mem_mib_avg": 322.0,
|
||||
"mem_mib_max": 323.7
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 8.0,
|
||||
"mem_mib_avg": 73.1,
|
||||
"mem_mib_max": 75.3
|
||||
}
|
||||
},
|
||||
"rep": 2
|
||||
},
|
||||
{
|
||||
"config": "full",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 9.8,
|
||||
"lat_p95_ms": 50.5,
|
||||
"lat_p99_ms": 113.0,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 43.4,
|
||||
"mem_mib_avg": 122.4,
|
||||
"mem_mib_max": 146.8
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 39.0,
|
||||
"mem_mib_avg": 98.3,
|
||||
"mem_mib_max": 138.6
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 1.3,
|
||||
"mem_mib_avg": 45.5,
|
||||
"mem_mib_max": 50.6
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 4.6,
|
||||
"mem_mib_avg": 373.4,
|
||||
"mem_mib_max": 478.6
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 9.6,
|
||||
"mem_mib_avg": 89.1,
|
||||
"mem_mib_max": 98.7
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 36443.0,
|
||||
"col_spans_out": 36443.0,
|
||||
"col_logs_in": 4696.0,
|
||||
"col_points_in": 2701.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 11111565.0,
|
||||
"tempo_spans": 36443.0,
|
||||
"loki_bytes": 1420353.0,
|
||||
"loki_lines": 4696.0,
|
||||
"prom_samples": 96223.0,
|
||||
"sdk_started": 35147.0,
|
||||
"sdk_sampled": 35147.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 4500.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 482.8,
|
||||
"col_spans_out": 482.8,
|
||||
"col_logs_in": 62.2,
|
||||
"col_points_in": 35.8,
|
||||
"tempo_bytes": 147204.9,
|
||||
"tempo_spans": 482.8,
|
||||
"loki_bytes": 18816.7,
|
||||
"loki_lines": 62.2,
|
||||
"prom_samples": 1274.8
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 9,
|
||||
"natural_slow_found_in_tempo": [
|
||||
9,
|
||||
9
|
||||
],
|
||||
"rep": 2
|
||||
},
|
||||
{
|
||||
"config": "head10",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 6.7,
|
||||
"lat_p95_ms": 24.6,
|
||||
"lat_p99_ms": 53.6,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 32.2,
|
||||
"mem_mib_avg": 116.0,
|
||||
"mem_mib_max": 157.4
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 28.1,
|
||||
"mem_mib_avg": 98.5,
|
||||
"mem_mib_max": 129.1
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 0.7,
|
||||
"mem_mib_avg": 50.6,
|
||||
"mem_mib_max": 50.9
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 3.4,
|
||||
"mem_mib_avg": 349.7,
|
||||
"mem_mib_max": 358.4
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 8.1,
|
||||
"mem_mib_avg": 78.7,
|
||||
"mem_mib_max": 85.7
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 3777.0,
|
||||
"col_spans_out": 3777.0,
|
||||
"col_logs_in": 4701.0,
|
||||
"col_points_in": 2761.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 1183927.0,
|
||||
"tempo_spans": 3777.0,
|
||||
"loki_bytes": 1421285.0,
|
||||
"loki_lines": 4701.0,
|
||||
"prom_samples": 94630.0,
|
||||
"sdk_started": 7835.0,
|
||||
"sdk_sampled": 3742.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 483.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 50.0,
|
||||
"col_spans_out": 50.0,
|
||||
"col_logs_in": 62.3,
|
||||
"col_points_in": 36.6,
|
||||
"tempo_bytes": 15684.5,
|
||||
"tempo_spans": 50.0,
|
||||
"loki_bytes": 18829.0,
|
||||
"loki_lines": 62.3,
|
||||
"prom_samples": 1253.6
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
1,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
4,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 0,
|
||||
"natural_slow_found_in_tempo": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"rep": 2
|
||||
},
|
||||
{
|
||||
"config": "tail",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 9.1,
|
||||
"lat_p95_ms": 55.7,
|
||||
"lat_p99_ms": 140.1,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 42.8,
|
||||
"mem_mib_avg": 123.5,
|
||||
"mem_mib_max": 147.6
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 42.0,
|
||||
"mem_mib_avg": 98.3,
|
||||
"mem_mib_max": 148.3
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 1.3,
|
||||
"mem_mib_avg": 50.2,
|
||||
"mem_mib_max": 56.9
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 4.8,
|
||||
"mem_mib_avg": 574.7,
|
||||
"mem_mib_max": 623.5
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 8.3,
|
||||
"mem_mib_avg": 91.3,
|
||||
"mem_mib_max": 98.9
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 36443.0,
|
||||
"col_spans_out": 6008.0,
|
||||
"col_logs_in": 4696.0,
|
||||
"col_points_in": 2790.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 2103644.0,
|
||||
"tempo_spans": 6008.0,
|
||||
"loki_bytes": 1419168.0,
|
||||
"loki_lines": 4696.0,
|
||||
"prom_samples": 95678.0,
|
||||
"sdk_started": 35148.0,
|
||||
"sdk_sampled": 35148.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 543.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 482.8,
|
||||
"col_spans_out": 79.6,
|
||||
"col_logs_in": 62.2,
|
||||
"col_points_in": 37.0,
|
||||
"tempo_bytes": 27868.7,
|
||||
"tempo_spans": 79.6,
|
||||
"loki_bytes": 18800.9,
|
||||
"loki_lines": 62.2,
|
||||
"prom_samples": 1267.5
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 4,
|
||||
"natural_slow_found_in_tempo": [
|
||||
0,
|
||||
4
|
||||
],
|
||||
"rep": 2
|
||||
},
|
||||
{
|
||||
"config": "off",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 5.5,
|
||||
"lat_p95_ms": 18.7,
|
||||
"lat_p99_ms": 40.4,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 26.3,
|
||||
"mem_mib_avg": 106.4,
|
||||
"mem_mib_max": 128.5
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 35.0,
|
||||
"mem_mib_avg": 85.7,
|
||||
"mem_mib_max": 128.9
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 0.1,
|
||||
"mem_mib_avg": 31.2,
|
||||
"mem_mib_max": 33.3
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 2.5,
|
||||
"mem_mib_avg": 362.6,
|
||||
"mem_mib_max": 364.8
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 7.6,
|
||||
"mem_mib_avg": 79.3,
|
||||
"mem_mib_max": 82.8
|
||||
}
|
||||
},
|
||||
"rep": 3
|
||||
},
|
||||
{
|
||||
"config": "full",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 8.7,
|
||||
"lat_p95_ms": 42.8,
|
||||
"lat_p99_ms": 132.1,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 43.2,
|
||||
"mem_mib_avg": 125.1,
|
||||
"mem_mib_max": 165.3
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 39.2,
|
||||
"mem_mib_avg": 93.4,
|
||||
"mem_mib_max": 149.7
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 1.3,
|
||||
"mem_mib_avg": 45.8,
|
||||
"mem_mib_max": 51.2
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 4.7,
|
||||
"mem_mib_avg": 377.6,
|
||||
"mem_mib_max": 541.6
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 8.7,
|
||||
"mem_mib_avg": 93.0,
|
||||
"mem_mib_max": 103.1
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 36443.0,
|
||||
"col_spans_out": 36443.0,
|
||||
"col_logs_in": 4696.0,
|
||||
"col_points_in": 2781.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 11109054.0,
|
||||
"tempo_spans": 36443.0,
|
||||
"loki_bytes": 1418209.0,
|
||||
"loki_lines": 4693.0,
|
||||
"prom_samples": 94986.0,
|
||||
"sdk_started": 35148.0,
|
||||
"sdk_sampled": 35148.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 4500.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 482.8,
|
||||
"col_spans_out": 482.8,
|
||||
"col_logs_in": 62.2,
|
||||
"col_points_in": 36.8,
|
||||
"tempo_bytes": 147171.3,
|
||||
"tempo_spans": 482.8,
|
||||
"loki_bytes": 18788.2,
|
||||
"loki_lines": 62.2,
|
||||
"prom_samples": 1258.4
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 3,
|
||||
"natural_slow_found_in_tempo": [
|
||||
3,
|
||||
3
|
||||
],
|
||||
"rep": 3
|
||||
},
|
||||
{
|
||||
"config": "head10",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 5.9,
|
||||
"lat_p95_ms": 22.2,
|
||||
"lat_p99_ms": 51.5,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 31.2,
|
||||
"mem_mib_avg": 115.8,
|
||||
"mem_mib_max": 136.8
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 21.6,
|
||||
"mem_mib_avg": 93.7,
|
||||
"mem_mib_max": 123.9
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 0.6,
|
||||
"mem_mib_avg": 51.4,
|
||||
"mem_mib_max": 52.0
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 3.3,
|
||||
"mem_mib_avg": 391.0,
|
||||
"mem_mib_max": 396.0
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 7.4,
|
||||
"mem_mib_avg": 86.1,
|
||||
"mem_mib_max": 93.3
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 3640.0,
|
||||
"col_spans_out": 3640.0,
|
||||
"col_logs_in": 4700.0,
|
||||
"col_points_in": 2745.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 1150983.0,
|
||||
"tempo_spans": 3640.0,
|
||||
"loki_bytes": 1420061.0,
|
||||
"loki_lines": 4700.0,
|
||||
"prom_samples": 94420.0,
|
||||
"sdk_started": 7566.0,
|
||||
"sdk_sampled": 3430.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 431.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 48.2,
|
||||
"col_spans_out": 48.2,
|
||||
"col_logs_in": 62.3,
|
||||
"col_points_in": 36.4,
|
||||
"tempo_bytes": 15248.0,
|
||||
"tempo_spans": 48.2,
|
||||
"loki_bytes": 18812.7,
|
||||
"loki_lines": 62.3,
|
||||
"prom_samples": 1250.9
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
2,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
3,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 0,
|
||||
"natural_slow_found_in_tempo": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"rep": 3
|
||||
},
|
||||
{
|
||||
"config": "tail",
|
||||
"window_s": 60.0,
|
||||
"requests": 3600,
|
||||
"ok_rps": 58.8,
|
||||
"unexpected_errors": 0,
|
||||
"injected_errors": 45,
|
||||
"lat_p50_ms": 7.6,
|
||||
"lat_p95_ms": 37.8,
|
||||
"lat_p99_ms": 97.0,
|
||||
"resources": {
|
||||
"api": {
|
||||
"cpu_pct_avg": 37.6,
|
||||
"mem_mib_avg": 123.3,
|
||||
"mem_mib_max": 157.3
|
||||
},
|
||||
"worker": {
|
||||
"cpu_pct_avg": 25.5,
|
||||
"mem_mib_avg": 86.5,
|
||||
"mem_mib_max": 107.2
|
||||
},
|
||||
"collector": {
|
||||
"cpu_pct_avg": 1.4,
|
||||
"mem_mib_avg": 50.7,
|
||||
"mem_mib_max": 57.6
|
||||
},
|
||||
"backends": {
|
||||
"cpu_pct_avg": 6.0,
|
||||
"mem_mib_avg": 496.0,
|
||||
"mem_mib_max": 703.4
|
||||
},
|
||||
"postgres": {
|
||||
"cpu_pct_avg": 9.6,
|
||||
"mem_mib_avg": 97.7,
|
||||
"mem_mib_max": 102.6
|
||||
}
|
||||
},
|
||||
"telemetry_delta": {
|
||||
"col_spans_in": 36451.0,
|
||||
"col_spans_out": 6298.0,
|
||||
"col_logs_in": 4696.0,
|
||||
"col_points_in": 2728.0,
|
||||
"col_refused": 0.0,
|
||||
"col_send_failed": 0.0,
|
||||
"tempo_bytes": 2200416.0,
|
||||
"tempo_spans": 6298.0,
|
||||
"loki_bytes": 1419574.0,
|
||||
"loki_lines": 4696.0,
|
||||
"prom_samples": 95786.0,
|
||||
"sdk_started": 35155.0,
|
||||
"sdk_sampled": 35155.0,
|
||||
"sdk_lost": 0.0,
|
||||
"red_5xx": 45.0,
|
||||
"red_all": 4500.0,
|
||||
"spanmetrics_calls": 584.0
|
||||
},
|
||||
"per_second": {
|
||||
"col_spans_in": 482.9,
|
||||
"col_spans_out": 83.4,
|
||||
"col_logs_in": 62.2,
|
||||
"col_points_in": 36.1,
|
||||
"tempo_bytes": 29150.7,
|
||||
"tempo_spans": 83.4,
|
||||
"loki_bytes": 18806.3,
|
||||
"loki_lines": 62.2,
|
||||
"prom_samples": 1269.0
|
||||
},
|
||||
"errors_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"slow_found_in_tempo": [
|
||||
45,
|
||||
45
|
||||
],
|
||||
"natural_slow_requests": 0,
|
||||
"natural_slow_found_in_tempo": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"rep": 3
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,255 @@
|
||||
{
|
||||
"meta": {
|
||||
"rate_rps": 60.0,
|
||||
"window_s": 60,
|
||||
"warmup_s": 15,
|
||||
"reps": 3,
|
||||
"configs": {
|
||||
"off": {
|
||||
"OTEL_SDK_DISABLED": "true",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "1.0",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector.yaml"
|
||||
},
|
||||
"full": {
|
||||
"OTEL_SDK_DISABLED": "false",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "1.0",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector.yaml"
|
||||
},
|
||||
"head10": {
|
||||
"OTEL_SDK_DISABLED": "false",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "0.1",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector.yaml"
|
||||
},
|
||||
"tail": {
|
||||
"OTEL_SDK_DISABLED": "false",
|
||||
"OTEL_TRACES_SAMPLER_ARG": "1.0",
|
||||
"OTEL_COLLECTOR_CONFIG": "collector-tail.yaml"
|
||||
}
|
||||
},
|
||||
"host_cpus": 2,
|
||||
"date": "2026-11-21T20:01:39Z"
|
||||
},
|
||||
"table": {
|
||||
"off": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 6.2,
|
||||
"p95_ms": 21.5,
|
||||
"p99_ms": 41.5,
|
||||
"p95_ms_runs": [
|
||||
27.2,
|
||||
21.5,
|
||||
18.7
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 30.5,
|
||||
"mem_api_mib": 106.4,
|
||||
"cpu_worker_pct": 52.3,
|
||||
"mem_worker_mib": 87.2,
|
||||
"cpu_collector_pct": 0.1,
|
||||
"mem_collector_mib": 31.2,
|
||||
"cpu_backends_pct": 2.5,
|
||||
"mem_backends_mib": 362.6,
|
||||
"cpu_postgres_pct": 8.0,
|
||||
"mem_postgres_mib": 73.1
|
||||
},
|
||||
"full": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 8.7,
|
||||
"p95_ms": 43.2,
|
||||
"p99_ms": 113.0,
|
||||
"p95_ms_runs": [
|
||||
43.2,
|
||||
50.5,
|
||||
42.8
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 43.4,
|
||||
"mem_api_mib": 124.0,
|
||||
"cpu_worker_pct": 39.0,
|
||||
"mem_worker_mib": 97.1,
|
||||
"cpu_collector_pct": 1.3,
|
||||
"mem_collector_mib": 45.8,
|
||||
"cpu_backends_pct": 4.6,
|
||||
"mem_backends_mib": 373.4,
|
||||
"cpu_postgres_pct": 8.7,
|
||||
"mem_postgres_mib": 89.1,
|
||||
"col_spans_in_per_s": 482.8,
|
||||
"col_spans_out_per_s": 482.8,
|
||||
"tempo_bytes_per_s": 147204.9,
|
||||
"tempo_spans_per_s": 482.8,
|
||||
"loki_bytes_per_s": 18815.5,
|
||||
"loki_lines_per_s": 62.2,
|
||||
"col_points_in_per_s": 35.8,
|
||||
"prom_samples_per_s": 1274.8,
|
||||
"sdk_lost": 0,
|
||||
"col_refused": 0,
|
||||
"col_send_failed": 0,
|
||||
"sdk_sampled_share": 1.0,
|
||||
"red_5xx_vs_injected": [
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
]
|
||||
],
|
||||
"spanmetrics_vs_sdk_calls": [
|
||||
[
|
||||
4500.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
4500.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
4500.0,
|
||||
4500.0
|
||||
]
|
||||
],
|
||||
"errors_found_in_tempo": "135/135",
|
||||
"slow_found_in_tempo": "135/135",
|
||||
"natural_slow_found_in_tempo": "12/12"
|
||||
},
|
||||
"head10": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 6.7,
|
||||
"p95_ms": 24.6,
|
||||
"p99_ms": 53.6,
|
||||
"p95_ms_runs": [
|
||||
29.2,
|
||||
24.6,
|
||||
22.2
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 32.2,
|
||||
"mem_api_mib": 116.0,
|
||||
"cpu_worker_pct": 28.1,
|
||||
"mem_worker_mib": 97.5,
|
||||
"cpu_collector_pct": 0.6,
|
||||
"mem_collector_mib": 51.4,
|
||||
"cpu_backends_pct": 3.4,
|
||||
"mem_backends_mib": 349.7,
|
||||
"cpu_postgres_pct": 7.7,
|
||||
"mem_postgres_mib": 78.7,
|
||||
"col_spans_in_per_s": 48.2,
|
||||
"col_spans_out_per_s": 48.2,
|
||||
"tempo_bytes_per_s": 15248.0,
|
||||
"tempo_spans_per_s": 48.2,
|
||||
"loki_bytes_per_s": 18812.7,
|
||||
"loki_lines_per_s": 62.3,
|
||||
"col_points_in_per_s": 36.6,
|
||||
"prom_samples_per_s": 1253.6,
|
||||
"sdk_lost": 0,
|
||||
"col_refused": 0,
|
||||
"col_send_failed": 0,
|
||||
"sdk_sampled_share": 0.4533439069521544,
|
||||
"red_5xx_vs_injected": [
|
||||
[
|
||||
7.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
]
|
||||
],
|
||||
"spanmetrics_vs_sdk_calls": [
|
||||
[
|
||||
406.0,
|
||||
4492.0
|
||||
],
|
||||
[
|
||||
483.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
431.0,
|
||||
4500.0
|
||||
]
|
||||
],
|
||||
"errors_found_in_tempo": "5/135",
|
||||
"slow_found_in_tempo": "9/135",
|
||||
"natural_slow_found_in_tempo": "0/3"
|
||||
},
|
||||
"tail": {
|
||||
"runs": 3,
|
||||
"ok_rps": 58.8,
|
||||
"p50_ms": 9.1,
|
||||
"p95_ms": 55.7,
|
||||
"p99_ms": 140.1,
|
||||
"p95_ms_runs": [
|
||||
67.0,
|
||||
55.7,
|
||||
37.8
|
||||
],
|
||||
"unexpected_errors": 0,
|
||||
"cpu_api_pct": 42.8,
|
||||
"mem_api_mib": 123.5,
|
||||
"cpu_worker_pct": 30.2,
|
||||
"mem_worker_mib": 97.3,
|
||||
"cpu_collector_pct": 1.4,
|
||||
"mem_collector_mib": 50.2,
|
||||
"cpu_backends_pct": 5.4,
|
||||
"mem_backends_mib": 574.7,
|
||||
"cpu_postgres_pct": 8.6,
|
||||
"mem_postgres_mib": 91.3,
|
||||
"col_spans_in_per_s": 482.8,
|
||||
"col_spans_out_per_s": 79.6,
|
||||
"tempo_bytes_per_s": 27868.7,
|
||||
"tempo_spans_per_s": 79.6,
|
||||
"loki_bytes_per_s": 18806.3,
|
||||
"loki_lines_per_s": 62.2,
|
||||
"col_points_in_per_s": 36.1,
|
||||
"prom_samples_per_s": 1269.0,
|
||||
"sdk_lost": 0,
|
||||
"col_refused": 0,
|
||||
"col_send_failed": 0,
|
||||
"sdk_sampled_share": 1.0,
|
||||
"red_5xx_vs_injected": [
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
],
|
||||
[
|
||||
45.0,
|
||||
45
|
||||
]
|
||||
],
|
||||
"spanmetrics_vs_sdk_calls": [
|
||||
[
|
||||
539.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
543.0,
|
||||
4500.0
|
||||
],
|
||||
[
|
||||
584.0,
|
||||
4500.0
|
||||
]
|
||||
],
|
||||
"errors_found_in_tempo": "135/135",
|
||||
"slow_found_in_tempo": "135/135",
|
||||
"natural_slow_found_in_tempo": "15/34"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
# 2026-11-21T19:31:36Z commit=n/a host=Linux 6.18.44-fc-v726 x86_64 cpus=2
|
||||
$ python3 research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json
|
||||
{
|
||||
"seed": 1,
|
||||
"uploads_requested": 60,
|
||||
"counters": {
|
||||
"uploads_202": 60,
|
||||
"upload_errors": 0,
|
||||
"kills": 2,
|
||||
"duplicates_sent": 19,
|
||||
"stale_sent": 0,
|
||||
"reprocess_v2": 2,
|
||||
"v1_after_v2_sent": 4
|
||||
},
|
||||
"planned_faults": {
|
||||
"fault-crash-after-commit": 4,
|
||||
"fault-crash-after-s3": 6,
|
||||
"fault-crash-before-s3": 7,
|
||||
"fault-hang-30": 3,
|
||||
"fault-slow-3": 2,
|
||||
"fault-transient-1": 7,
|
||||
"fault-transient-2": 8,
|
||||
"none": 23
|
||||
},
|
||||
"chaos_seconds": 50.4,
|
||||
"settle_seconds": 46.9,
|
||||
"accepted_202": 60,
|
||||
"accepted_not_terminal": 0,
|
||||
"attachment_status": {
|
||||
"ready": "60"
|
||||
},
|
||||
"job_status": {
|
||||
"1:ready": "60",
|
||||
"2:ready": "2"
|
||||
},
|
||||
"events": {
|
||||
"claimed": "87",
|
||||
"committed": "62",
|
||||
"duplicate_ignored": "26",
|
||||
"enqueued": "62",
|
||||
"lease_lost": "2",
|
||||
"lease_takeover": "29",
|
||||
"published": "87",
|
||||
"published_version_changed": "62",
|
||||
"retry_scheduled": "25",
|
||||
"staging_cleaned": "60"
|
||||
},
|
||||
"enqueue_to_commit_seconds_v1": {
|
||||
"p50": 44.09,
|
||||
"p95": 64.59,
|
||||
"max": 79.28
|
||||
},
|
||||
"invariants": {
|
||||
"ok": true,
|
||||
"violations": {},
|
||||
"violation_counts": {},
|
||||
"stats": {
|
||||
"attachments": 60,
|
||||
"jobs": 62,
|
||||
"variants": 186,
|
||||
"events": 502,
|
||||
"job_status": {
|
||||
"ready": 62
|
||||
},
|
||||
"attachment_status": {
|
||||
"ready": 60
|
||||
},
|
||||
"s3_objects": 990
|
||||
}
|
||||
}
|
||||
}
|
||||
exit=0
|
||||
@@ -0,0 +1,69 @@
|
||||
{
|
||||
"seed": 1,
|
||||
"uploads_requested": 60,
|
||||
"counters": {
|
||||
"uploads_202": 60,
|
||||
"upload_errors": 0,
|
||||
"kills": 2,
|
||||
"duplicates_sent": 19,
|
||||
"stale_sent": 0,
|
||||
"reprocess_v2": 2,
|
||||
"v1_after_v2_sent": 4
|
||||
},
|
||||
"planned_faults": {
|
||||
"fault-crash-after-commit": 4,
|
||||
"fault-crash-after-s3": 6,
|
||||
"fault-crash-before-s3": 7,
|
||||
"fault-hang-30": 3,
|
||||
"fault-slow-3": 2,
|
||||
"fault-transient-1": 7,
|
||||
"fault-transient-2": 8,
|
||||
"none": 23
|
||||
},
|
||||
"chaos_seconds": 50.4,
|
||||
"settle_seconds": 46.9,
|
||||
"accepted_202": 60,
|
||||
"accepted_not_terminal": 0,
|
||||
"attachment_status": {
|
||||
"ready": "60"
|
||||
},
|
||||
"job_status": {
|
||||
"1:ready": "60",
|
||||
"2:ready": "2"
|
||||
},
|
||||
"events": {
|
||||
"claimed": "87",
|
||||
"committed": "62",
|
||||
"duplicate_ignored": "26",
|
||||
"enqueued": "62",
|
||||
"lease_lost": "2",
|
||||
"lease_takeover": "29",
|
||||
"published": "87",
|
||||
"published_version_changed": "62",
|
||||
"retry_scheduled": "25",
|
||||
"staging_cleaned": "60"
|
||||
},
|
||||
"enqueue_to_commit_seconds_v1": {
|
||||
"p50": 44.09,
|
||||
"p95": 64.59,
|
||||
"max": 79.28
|
||||
},
|
||||
"invariants": {
|
||||
"ok": true,
|
||||
"violations": {},
|
||||
"violation_counts": {},
|
||||
"stats": {
|
||||
"attachments": 60,
|
||||
"jobs": 62,
|
||||
"variants": 186,
|
||||
"events": 502,
|
||||
"job_status": {
|
||||
"ready": 62
|
||||
},
|
||||
"attachment_status": {
|
||||
"ready": 60
|
||||
},
|
||||
"s3_objects": 990
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
# Grafana-managed alert rules не используются: алерты — правила Prometheus (infra/prometheus/rules).
|
||||
@@ -0,0 +1,16 @@
|
||||
# Dashboards из Git: файлы JSON в /etc/grafana/dashboards импортируются автоматически
|
||||
# (ручной набор не нужен; изменения в UI не сохраняются поверх файла).
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: Messenger
|
||||
folderUid: messenger
|
||||
type: file
|
||||
disableDeletion: true
|
||||
allowUiUpdates: false
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /etc/grafana/dashboards
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,75 @@
|
||||
# Источники данных Grafana (импортируются при старте; править в UI нельзя — источник истины в Git).
|
||||
# Grafana — только интерфейс и запросы; данные хранят Prometheus, Loki и Tempo.
|
||||
apiVersion: 1
|
||||
|
||||
deleteDatasources: []
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
httpMethod: POST
|
||||
prometheusType: Prometheus
|
||||
prometheusVersion: 3.5.0
|
||||
timeInterval: 10s # = scrape/экспорт метрик: минимальный шаг $__rate_interval
|
||||
manageAlerts: true # правила Prometheus из Git видны в Grafana Alerting (Data source-managed, read-only)
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
maxLines: 1000
|
||||
# trace_id хранится в structured metadata записи → ссылка «открыть trace» прямо из строки лога.
|
||||
derivedFields:
|
||||
- name: trace_id
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
urlDisplayLabel: Открыть trace
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
# Из span — к логам того же trace (structured metadata trace_id в Loki).
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-5m'
|
||||
spanEndTimeShift: '5m'
|
||||
filterByTraceID: false
|
||||
filterBySpanID: false
|
||||
customQuery: true
|
||||
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"'
|
||||
tracesToMetrics:
|
||||
datasourceUid: prometheus
|
||||
spanStartTimeShift: '-5m'
|
||||
spanEndTimeShift: '5m'
|
||||
tags:
|
||||
- {key: service.name, value: service_name}
|
||||
queries:
|
||||
- name: p95 HTTP по сервису
|
||||
query: 'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{$$__tags}[1m])))'
|
||||
serviceMap:
|
||||
datasourceUid: prometheus
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
search:
|
||||
hide: false
|
||||
lokiSearch:
|
||||
datasourceUid: loki
|
||||
traceQuery:
|
||||
timeShiftEnabled: true
|
||||
spanStartTimeShift: '-30m'
|
||||
spanEndTimeShift: '30m'
|
||||
@@ -0,0 +1 @@
|
||||
# Плагины не устанавливаются (стенд без доступа в интернет; GF_PLUGINS_PREINSTALL_DISABLED=true).
|
||||
@@ -0,0 +1,100 @@
|
||||
# HAProxy 3.0 — единственная публичная точка входа lab3.
|
||||
# Бэкенды находятся через DNS Docker (имя сервиса `api` → IP всех реплик), без sticky sessions.
|
||||
#
|
||||
# Обнаружение отказа реплики:
|
||||
# * активная проверка GET /health/ready: inter 1s, после первой ошибки fastinter 500ms, fall 2,
|
||||
# timeout check 300ms → худший случай обнаружения ≈ 1 + 0.3 + 0.5 + 0.3 ≈ 2.1 с;
|
||||
# * пассивно: соединение отвергнуто → retry-on conn-failure + redispatch на другую реплику
|
||||
# (только если запрос ещё не отправлен — безопасно и для неидемпотентных POST).
|
||||
# * graceful shutdown реплики: SIGTERM → /health/ready = 503 на SHUTDOWN_DRAIN_SECONDS=3 с
|
||||
# (> fall × fastinter) → LB выводит реплику до того, как она закроет listener.
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 4096
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
timeout connect 300ms # сеть Docker: connect < 1 мс; к «мёртвому» IP (kill) нет RST — ждём не дольше 300 мс
|
||||
timeout check 300ms # проверка не висит 1 с на убитой реплике → быстрее fall
|
||||
timeout client 60s # lab4: загрузка до 10 МиБ медленным клиентом
|
||||
timeout server 60s # бездействие сервера; > REQUEST_TIMEOUT_SECONDS (10 с); upload/download — потоки
|
||||
timeout http-request 10s
|
||||
timeout http-keep-alive 10s
|
||||
timeout queue "${LB_QUEUE_TIMEOUT}" # сколько запрос может ждать свободный слот maxconn в очереди LB
|
||||
retries 2
|
||||
option redispatch 1
|
||||
retry-on conn-failure # НЕ empty-response/response-timeout: иначе возможен повтор выполненного POST
|
||||
unique-id-format %[uuid()] # request_id ответов самого LB: случайный, без IP/портов
|
||||
default-server inter 1s fastinter 500ms downinter 2s fall 2 rise 2 init-addr none resolvers docker
|
||||
# Ответы, созданные самим LB, — в формате ошибок API (X-Instance-Id у них нет, это допустимо).
|
||||
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Нет доступных реплик API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr Retry-After 1
|
||||
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Реплика API недоступна","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
|
||||
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Таймаут реплики API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
|
||||
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 2s
|
||||
hold obsolete 5s # исчезнувший из DNS контейнер убирается из слота через 5 с
|
||||
accepted_payload_size 8192
|
||||
|
||||
frontend api
|
||||
bind :8080
|
||||
# Внутренняя диагностика реплик снаружи недоступна.
|
||||
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
|
||||
default_backend api
|
||||
|
||||
frontend api_ttl
|
||||
bind :8081
|
||||
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
|
||||
default_backend api_ttl
|
||||
|
||||
frontend api_fault
|
||||
bind :8082
|
||||
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
|
||||
default_backend api_fault
|
||||
|
||||
frontend stats
|
||||
bind :8404
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 2s
|
||||
stats show-legends
|
||||
|
||||
backend api
|
||||
balance roundrobin # без stickiness: состояние не хранится в реплике
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
http-reuse safe
|
||||
# maxconn: не больше LB_SERVER_MAXCONN одновременных запросов на реплику, излишек ждёт в очереди LB
|
||||
# (0 = без ограничения). Обоснование значения — трек 5.1 в REPORT.md.
|
||||
server-template api 8 api:8080 check maxconn "${LB_SERVER_MAXCONN}"
|
||||
# «Panic mode»: если readiness не проходит НИ У ОДНОЙ реплики (например, упала БД), запросы всё
|
||||
# равно идут в живые процессы, и клиент получает ответ приложения (401 анониму, 503 unavailable
|
||||
# в формате API, /health/live = 200), а не безликий 503 LB. Мёртвый процесс → conn-failure → 503 LB.
|
||||
option allbackups
|
||||
server-template apibk 8 api:8080 backup resolve-opts allow-dup-ip
|
||||
|
||||
backend api_ttl
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
server-template ttl 2 api-ttl:8080 check
|
||||
option allbackups
|
||||
server-template ttlbk 2 api-ttl:8080 backup resolve-opts allow-dup-ip
|
||||
|
||||
# Только для теста компенсации (профиль fault). Без сервиса api-fault слоты пусты — бэкенд DOWN.
|
||||
backend api_fault
|
||||
balance roundrobin
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
server-template fault 1 api-fault:8080 check
|
||||
@@ -0,0 +1,66 @@
|
||||
# Loki 3.5 — хранилище логов (single binary, файловая система на volume lokidata).
|
||||
# Логи приходят по native OTLP (/otlp/v1/logs) из Collector. Ресурсные атрибуты service.name,
|
||||
# service.instance.id, deployment.environment.name → index labels (низкая кардинальность);
|
||||
# атрибуты записи (event, request_id, job_id, trace_id, span_id …) → structured metadata
|
||||
# (не индексируются как labels, но фильтруются: {service_name="messenger-api"} | request_id="…").
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_port: 9096
|
||||
log_level: warn
|
||||
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
volume_enabled: true
|
||||
retention_period: 168h # 7 дней учебной истории
|
||||
ingestion_rate_mb: 8
|
||||
ingestion_burst_size_mb: 16
|
||||
max_label_names_per_series: 15
|
||||
otlp_config:
|
||||
resource_attributes:
|
||||
attributes_config:
|
||||
- action: index_label
|
||||
attributes: [deployment.environment.name]
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
compaction_interval: 10m
|
||||
|
||||
ingester:
|
||||
chunk_idle_period: 5m
|
||||
max_chunk_age: 1h
|
||||
|
||||
query_range:
|
||||
results_cache:
|
||||
cache:
|
||||
embedded_cache:
|
||||
enabled: true
|
||||
max_size_mb: 50
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false # без отправки статистики во внешний интернет
|
||||
@@ -0,0 +1,122 @@
|
||||
# OpenTelemetry Collector (contrib 0.130.0) — получатель/обработчик/экспортёр, НЕ хранилище.
|
||||
# API и worker → OTLP/HTTP :4318 (сеть telemetry, наружу не публикуется) → три pipeline:
|
||||
# traces → Tempo (OTLP/HTTP http://tempo:4318)
|
||||
# metrics → Prometheus (OTLP receiver http://prometheus:9090/api/v1/otlp)
|
||||
# logs → Loki (native OTLP http://loki:3100/otlp)
|
||||
# Защита памяти и поведение при недоступном backend:
|
||||
# * memory_limiter — первым в каждой pipeline: при росте RAM выше limit-spike Collector отклоняет приём
|
||||
# (SDK получает 503/429, повторяет и затем отбрасывает — потери считаются на стороне SDK);
|
||||
# * sending_queue каждого экспортёра — ограниченная очередь в памяти (queue_size батчей); при переполнении
|
||||
# новые данные отбрасываются (otelcol_exporter_enqueue_failed_*), а не накапливаются бесконечно;
|
||||
# * retry_on_failure — повтор с экспоненциальной паузой, не дольше max_elapsed_time, затем батч отбрасывается
|
||||
# (otelcol_exporter_send_failed_*). Telemetry — «best effort»: бизнес-запросы от неё не зависят.
|
||||
# ВАРИАНТ ТРЕКА 1 «сбалансированный»: SDK отправляет 100% spans, решение о хранении trace принимает
|
||||
# Collector ПОСЛЕ завершения trace (tail sampling): все ошибки, все медленные, все trace pipeline вложений
|
||||
# и 10% остальных. Метрики RED считаются в SDK по всем запросам и от sampling не зависят.
|
||||
# Ограничение: один экземпляр Collector (все spans trace приходят в один процесс); для нескольких —
|
||||
# loadbalancing exporter по trace_id. Включение: OTEL_COLLECTOR_CONFIG=collector-tail.yaml.
|
||||
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133 # внутренняя сеть observability; на хост не публикуется
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
max_request_body_size: 8388608 # 8 MiB на запрос экспорта
|
||||
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 200 # контейнер ограничен 256 MiB
|
||||
spike_limit_mib: 50 # мягкий порог 150 MiB: дальше приём отклоняется
|
||||
tail_sampling:
|
||||
decision_wait: 10s # ждать spans trace (worker завершает задание через секунды)
|
||||
num_traces: 20000 # предел trace в памяти; старые решения вытесняются
|
||||
expected_new_traces_per_sec: 200
|
||||
decision_cache:
|
||||
sampled_cache_size: 20000 # поздние spans (повтор задания) получают то же решение
|
||||
non_sampled_cache_size: 20000
|
||||
policies:
|
||||
- name: errors
|
||||
type: status_code
|
||||
status_code: {status_codes: [ERROR]}
|
||||
- name: slow
|
||||
type: latency
|
||||
latency: {threshold_ms: 250}
|
||||
- name: attachment-pipeline # upload → worker: редкие и дорогие операции храним все
|
||||
type: string_attribute
|
||||
string_attribute: {key: messaging.system, values: [nats]}
|
||||
- name: baseline
|
||||
type: probabilistic
|
||||
probabilistic: {sampling_percentage: 10}
|
||||
batch:
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
timeout: 2s
|
||||
# Защита «в глубину»: даже если код по ошибке положит такой атрибут, в хранилища он не уйдёт.
|
||||
attributes/scrub:
|
||||
actions:
|
||||
- pattern: '(?i)^(.*\.)?(password|passwd|token|access_token|session_token|authorization|cookie|secret|api_key)$'
|
||||
action: delete
|
||||
- pattern: '(?i)^http\.request\.header\.(authorization|cookie|x-api-key)$'
|
||||
action: delete
|
||||
- key: db.query.parameters
|
||||
action: delete
|
||||
|
||||
exporters:
|
||||
otlphttp/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
compression: gzip
|
||||
timeout: 5s
|
||||
sending_queue: &queue
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 200 # батчей (≤ 2048 элементов каждый) — предел RAM очереди
|
||||
retry_on_failure: &retry
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 120s
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
compression: gzip
|
||||
timeout: 5s
|
||||
sending_queue: *queue
|
||||
retry_on_failure: *retry
|
||||
otlphttp/prometheus:
|
||||
endpoint: http://prometheus:9090/api/v1/otlp
|
||||
compression: gzip
|
||||
timeout: 5s
|
||||
sending_queue: *queue
|
||||
retry_on_failure: *retry
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
metrics:
|
||||
level: detailed # otelcol_* метрики самого Collector: принято/отклонено/отправлено/очереди
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888 # скрейпит Prometheus (сеть observability)
|
||||
without_units: true # классические имена: otelcol_exporter_sent_spans_total (без «_{spans}»)
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, attributes/scrub, tail_sampling, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, attributes/scrub, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,98 @@
|
||||
# OpenTelemetry Collector (contrib 0.130.0) — получатель/обработчик/экспортёр, НЕ хранилище.
|
||||
# API и worker → OTLP/HTTP :4318 (сеть telemetry, наружу не публикуется) → три pipeline:
|
||||
# traces → Tempo (OTLP/HTTP http://tempo:4318)
|
||||
# metrics → Prometheus (OTLP receiver http://prometheus:9090/api/v1/otlp)
|
||||
# logs → Loki (native OTLP http://loki:3100/otlp)
|
||||
# Защита памяти и поведение при недоступном backend:
|
||||
# * memory_limiter — первым в каждой pipeline: при росте RAM выше limit-spike Collector отклоняет приём
|
||||
# (SDK получает 503/429, повторяет и затем отбрасывает — потери считаются на стороне SDK);
|
||||
# * sending_queue каждого экспортёра — ограниченная очередь в памяти (queue_size батчей); при переполнении
|
||||
# новые данные отбрасываются (otelcol_exporter_enqueue_failed_*), а не накапливаются бесконечно;
|
||||
# * retry_on_failure — повтор с экспоненциальной паузой, не дольше max_elapsed_time, затем батч отбрасывается
|
||||
# (otelcol_exporter_send_failed_*). Telemetry — «best effort»: бизнес-запросы от неё не зависят.
|
||||
# Конфигурация трека 1 со сбалансированным tail sampling — collector-tail.yaml (OTEL_COLLECTOR_CONFIG).
|
||||
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133 # внутренняя сеть observability; на хост не публикуется
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
max_request_body_size: 8388608 # 8 MiB на запрос экспорта
|
||||
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 200 # контейнер ограничен 256 MiB
|
||||
spike_limit_mib: 50 # мягкий порог 150 MiB: дальше приём отклоняется
|
||||
batch:
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
timeout: 2s
|
||||
# Защита «в глубину»: даже если код по ошибке положит такой атрибут, в хранилища он не уйдёт.
|
||||
attributes/scrub:
|
||||
actions:
|
||||
- pattern: '(?i)^(.*\.)?(password|passwd|token|access_token|session_token|authorization|cookie|secret|api_key)$'
|
||||
action: delete
|
||||
- pattern: '(?i)^http\.request\.header\.(authorization|cookie|x-api-key)$'
|
||||
action: delete
|
||||
- key: db.query.parameters
|
||||
action: delete
|
||||
|
||||
exporters:
|
||||
otlphttp/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
compression: gzip
|
||||
timeout: 5s
|
||||
sending_queue: &queue
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 200 # батчей (≤ 2048 элементов каждый) — предел RAM очереди
|
||||
retry_on_failure: &retry
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 120s
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
compression: gzip
|
||||
timeout: 5s
|
||||
sending_queue: *queue
|
||||
retry_on_failure: *retry
|
||||
otlphttp/prometheus:
|
||||
endpoint: http://prometheus:9090/api/v1/otlp
|
||||
compression: gzip
|
||||
timeout: 5s
|
||||
sending_queue: *queue
|
||||
retry_on_failure: *retry
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
metrics:
|
||||
level: detailed # otelcol_* метрики самого Collector: принято/отклонено/отправлено/очереди
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888 # скрейпит Prometheus (сеть observability)
|
||||
without_units: true # классические имена: otelcol_exporter_sent_spans_total (без «_{spans}»)
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, attributes/scrub, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, attributes/scrub, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,34 @@
|
||||
# Prometheus 3.5 LTS — хранилище метрик. Метрики приложения приходят PUSH через Collector на OTLP receiver
|
||||
# (--web.enable-otlp-receiver); метрики самих компонентов наблюдаемости — обычный scrape.
|
||||
global:
|
||||
scrape_interval: 10s
|
||||
evaluation_interval: 10s # правила алертов/записи проверяются каждые 10 с
|
||||
|
||||
# Ресурсные атрибуты OTel → labels каждой серии (иначе они только в target_info).
|
||||
# service.instance.id — низкокардинальный: число реплик × перезапуски (случайный alias процесса).
|
||||
otlp:
|
||||
promote_resource_attributes:
|
||||
- service.name
|
||||
- service.namespace
|
||||
- service.instance.id
|
||||
- deployment.environment.name
|
||||
translation_strategy: UnderscoreEscapingWithSuffixes # http.server.request.duration → http_server_request_duration_seconds
|
||||
|
||||
storage:
|
||||
tsdb:
|
||||
out_of_order_time_window: 10m # повторная отправка Collector после восстановления backend
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
static_configs: [{targets: ['localhost:9090']}]
|
||||
- job_name: otel-collector # otelcol_*: принято/отклонено/отправлено/очереди экспортёров
|
||||
static_configs: [{targets: ['otel-collector:8888']}]
|
||||
- job_name: loki
|
||||
static_configs: [{targets: ['loki:3100']}]
|
||||
- job_name: tempo
|
||||
static_configs: [{targets: ['tempo:3200']}]
|
||||
- job_name: grafana
|
||||
static_configs: [{targets: ['grafana:3000']}]
|
||||
@@ -0,0 +1,138 @@
|
||||
# Правила записи (SLI) и алерты мессенджера. Окна сжаты под учебный стенд (минуты вместо часов/дней):
|
||||
# цель — проверяемо увидеть firing → resolved за время защиты. Runbook: docs/runbooks.md.
|
||||
#
|
||||
# SLI/SLO (обоснование — REPORT.md, раздел «SLI/SLO»):
|
||||
# * доступность API: доля НЕ-5xx среди бизнес-запросов (без /health/* и /internal/*), SLO 99.5% за 1 ч;
|
||||
# 4xx (неверный пароль, 404 чужого чата) — ошибки клиента и в бюджет НЕ входят;
|
||||
# * задержка API: доля бизнес-запросов быстрее 250 мс, SLO 95% за 1 ч. Не входят upload (время передачи
|
||||
# файла клиентом) и регистрация/вход (KDF scrypt намеренно медленный, ~0.1–0.3 с);
|
||||
# * time to ready: доля вложений, ставших ready быстрее 10 с после 202, SLO 95% за 1 ч.
|
||||
groups:
|
||||
- name: messenger-sli
|
||||
interval: 10s
|
||||
rules:
|
||||
- record: sli:api_requests:rate1m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*|/internal/.*"}[1m]))
|
||||
- record: sli:api_errors:rate1m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*|/internal/.*",http_response_status_class="5xx"}[1m])) or vector(0)
|
||||
- record: sli:api_error_ratio:rate1m
|
||||
expr: sli:api_errors:rate1m / clamp_min(sli:api_requests:rate1m, 1e-9)
|
||||
- record: sli:api_latency_p95:1m
|
||||
expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api",http_route!~"/health/.*|/internal/.*|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[1m])))
|
||||
- record: sli:api_fast_ratio:rate5m
|
||||
expr: |
|
||||
sum(rate(http_server_request_duration_seconds_bucket{service_name="messenger-api",le="0.25",http_route!~"/health/.*|/internal/.*|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[5m]))
|
||||
/ clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*|/internal/.*|/api/v1/chats/\\{chat_id\\}/attachments|/api/v1/users|/api/v1/auth/sessions"}[5m])), 1e-9)
|
||||
- record: sli:time_to_ready_fast_ratio:rate15m
|
||||
expr: |
|
||||
sum(rate(messenger_attachment_time_to_ready_seconds_bucket{le="10"}[15m]))
|
||||
/ clamp_min(sum(rate(messenger_attachment_time_to_ready_seconds_count[15m])), 1e-9)
|
||||
- record: sli:queue_lag_seconds:max
|
||||
expr: max(last_over_time(messenger_queue_lag_seconds{queue="attachments.process.v1"}[30s]))
|
||||
- record: sli:queue_oldest_age_seconds:max
|
||||
expr: max(last_over_time(messenger_queue_oldest_age_seconds{queue="attachments.process.v1"}[30s]))
|
||||
|
||||
- name: messenger-alerts
|
||||
interval: 10s
|
||||
rules:
|
||||
- alert: ApiHighErrorRate
|
||||
# Условие: > 5% ответов 5xx за 1 мин при ≥ 0.2 запроса/с (иначе один сбой из 3 запросов = 33%).
|
||||
expr: sli:api_error_ratio:rate1m > 0.05 and sli:api_requests:rate1m > 0.2
|
||||
for: 30s
|
||||
labels: {severity: critical, service: messenger-api}
|
||||
annotations:
|
||||
summary: "Доля 5xx API {{ $value | humanizePercentage }} > 5% (окно 1 мин)"
|
||||
description: "Бизнес-запросы (без /health, /internal) завершаются 5xx. Сначала — trace с error.type в Tempo и логи event=dependency.unavailable в Loki."
|
||||
runbook_url: "docs/runbooks.md#apihigherrorrate"
|
||||
- alert: ApiLatencyHigh
|
||||
# Порог = цель SLO задержки (250 мс): p95 выше — SLO нарушается прямо сейчас.
|
||||
expr: sli:api_latency_p95:1m > 0.25 and sli:api_requests:rate1m > 0.2
|
||||
for: 1m
|
||||
labels: {severity: warning, service: messenger-api}
|
||||
annotations:
|
||||
summary: "p95 API {{ $value | humanizeDuration }} > 250 мс (окно 1 мин)"
|
||||
description: "Медленный API. Сравните p95 db.client.operation.duration (БД) с HTTP p95 (обработчик/CPU)."
|
||||
runbook_url: "docs/runbooks.md#apilatencyhigh"
|
||||
- alert: DbSlowQueries
|
||||
# Обычно p95 запроса ≈ 2–5 мс: 50 мс — на порядок медленнее нормы.
|
||||
expr: histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket[1m]))) > 0.05
|
||||
for: 30s
|
||||
labels: {severity: warning, service: postgres}
|
||||
annotations:
|
||||
summary: "p95 запросов к PostgreSQL {{ $value | humanizeDuration }} > 50 мс"
|
||||
description: "Медленная БД (не обработчик): растёт время execute по client spans/метрике всех сервисов."
|
||||
runbook_url: "docs/runbooks.md#dbslowqueries"
|
||||
- alert: DbPoolSaturated
|
||||
expr: max by (service_name) (last_over_time(db_client_connection_pending_requests[30s])) > 0
|
||||
for: 30s
|
||||
labels: {severity: warning}
|
||||
annotations:
|
||||
summary: "{{ $labels.service_name }}: запросы ждут соединения пула БД"
|
||||
description: "Все соединения заняты: БД медленная или пул мал. Смотрите db_client_connection_count{state=used} и p95 БД."
|
||||
runbook_url: "docs/runbooks.md#dbpoolsaturated"
|
||||
- alert: JobQueueLagGrowing
|
||||
# queue lag = сколько ждёт самое старое задание, уже доступное worker (backoff повторов не считается).
|
||||
expr: sli:queue_lag_seconds:max > 30
|
||||
for: 20s
|
||||
labels: {severity: critical, service: messenger-worker}
|
||||
annotations:
|
||||
summary: "Задания ждут worker уже {{ $value | humanizeDuration }} (> 30 с)"
|
||||
description: "Backlog не разбирается: worker остановлены/перегружены/не получают сообщения. Сравните messenger_queue_depth{state=ready} и messenger_worker_busy/capacity."
|
||||
runbook_url: "docs/runbooks.md#jobqueuelaggrowing"
|
||||
- alert: WorkerHeartbeatMissing
|
||||
# Метрики worker приходят каждые 10 с. Нет свежих — ни один worker не работает (или не экспортирует).
|
||||
# Подавляется, если Collector был недоступен последние 2 мин: тогда метрик нет у ВСЕХ сервисов —
|
||||
# это OtelCollectorDown, а не смерть worker.
|
||||
expr: ((time() - max(timestamp(messenger_worker_capacity))) > 45 or absent(messenger_worker_capacity))
|
||||
unless on() (min_over_time(up{job="otel-collector"}[2m]) == 0)
|
||||
for: 15s
|
||||
labels: {severity: critical, service: messenger-worker}
|
||||
annotations:
|
||||
summary: "Нет метрик ни одного worker дольше 45 с"
|
||||
description: "Все worker остановлены, упали или не могут экспортировать telemetry. Проверьте docker compose ps worker и логи."
|
||||
runbook_url: "docs/runbooks.md#workerheartbeatmissing"
|
||||
- alert: JobsFailing
|
||||
expr: sum(increase(messenger_jobs_processed_total{outcome="failed"}[5m])) > 0
|
||||
labels: {severity: warning, service: messenger-worker}
|
||||
annotations:
|
||||
summary: "За 5 мин {{ $value }} заданий завершились failed"
|
||||
description: "Финальные ошибки обработки (invalid_image/retry_exhausted…). Реестр: python -m messenger jobs failed."
|
||||
runbook_url: "docs/runbooks.md#jobsfailing"
|
||||
- alert: TelemetryExportFailing
|
||||
# Мета-мониторинг: Collector не может отправить данные в backend (или отбрасывает из-за очереди).
|
||||
expr: |
|
||||
sum(rate(otelcol_exporter_send_failed_spans_total[1m])) + sum(rate(otelcol_exporter_send_failed_log_records_total[1m]))
|
||||
+ sum(rate(otelcol_exporter_enqueue_failed_spans_total[1m])) + sum(rate(otelcol_exporter_enqueue_failed_log_records_total[1m])) > 0
|
||||
or sum(otelcol_exporter_queue_size) > 20
|
||||
for: 30s
|
||||
labels: {severity: warning, service: otel-collector}
|
||||
annotations:
|
||||
summary: "Collector не доставляет telemetry в backend"
|
||||
description: "Tempo/Loki/Prometheus недоступен: очередь экспортёра растёт или батчи отбрасываются. Бизнес-API от этого не зависит."
|
||||
runbook_url: "docs/runbooks.md#telemetryexportfailing"
|
||||
- alert: OtelCollectorDown
|
||||
# Collector не отвечает на scrape: telemetry всех сервисов не принимается (SDK отбрасывает и считает).
|
||||
expr: up{job="otel-collector"} == 0
|
||||
for: 20s
|
||||
labels: {severity: warning, service: otel-collector}
|
||||
annotations:
|
||||
summary: "OTel Collector недоступен"
|
||||
description: "Новые метрики/логи/трассы приложения не поступают; API работает. Потери видны после восстановления в otel_sdk_exporter_*_exported_total{error_type}."
|
||||
runbook_url: "docs/runbooks.md#otelcollectordown"
|
||||
- alert: TelemetryLostInSdk
|
||||
# Сообщает ПОСЛЕ восстановления канала (счётчики SDK доставляются тем же Collector): сколько spans/logs
|
||||
# не удалось экспортировать или пришлось отбросить из-за переполнения очереди SDK. Серия с error_type
|
||||
# появляется впервые уже со значением N, поэтому не increase() (он не видит первого значения новой
|
||||
# серии), а разность «сейчас − 5 мин назад» (отсутствие серии = 0).
|
||||
expr: |
|
||||
((sum(otel_sdk_exporter_span_exported_total{error_type!=""}) or vector(0))
|
||||
- (sum(otel_sdk_exporter_span_exported_total{error_type!=""} offset 5m) or vector(0)))
|
||||
+ ((sum(otel_sdk_processor_span_processed_total{error_type!=""}) or vector(0))
|
||||
- (sum(otel_sdk_processor_span_processed_total{error_type!=""} offset 5m) or vector(0)))
|
||||
+ ((sum(otel_sdk_exporter_log_exported_total{error_type!=""}) or vector(0))
|
||||
- (sum(otel_sdk_exporter_log_exported_total{error_type!=""} offset 5m) or vector(0))) > 0
|
||||
labels: {severity: info, service: telemetry}
|
||||
annotations:
|
||||
summary: "SDK потерял {{ $value | humanize }} spans/logs за 5 мин"
|
||||
description: "Collector был недоступен или очередь SDK переполнилась. В trace/логах за этот интервал есть пропуски; метрики RED не потеряны (кумулятивные счётчики)."
|
||||
runbook_url: "docs/runbooks.md#telemetrylostinsdk"
|
||||
@@ -0,0 +1,58 @@
|
||||
# Tempo 2.8 — хранилище трасс (monolithic, локальный диск на volume tempodata).
|
||||
# Spans приходят по OTLP/HTTP из Collector. metrics_generator строит из spans service graph и
|
||||
# span-метрики и пишет их в Prometheus (remote write) — для карты сервисов в Grafana.
|
||||
# ВАЖНО (трек 1): span-метрики считаются по СОХРАНЁННЫМ spans и при sampling занижены; RED API берётся
|
||||
# из метрик SDK, которые от sampling не зависят.
|
||||
stream_over_http_enabled: true
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
grpc_listen_port: 9097
|
||||
log_level: warn
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
ingester:
|
||||
max_block_duration: 5m # блоки чаще сбрасываются на диск (учебная нагрузка невелика)
|
||||
trace_idle_period: 10s
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 168h # 7 дней
|
||||
|
||||
metrics_generator:
|
||||
registry:
|
||||
external_labels:
|
||||
source: tempo
|
||||
storage:
|
||||
path: /var/tempo/generator/wal
|
||||
remote_write:
|
||||
- url: http://prometheus:9090/api/v1/write
|
||||
send_exemplars: false
|
||||
traces_storage:
|
||||
path: /var/tempo/generator/traces
|
||||
processor:
|
||||
service_graphs:
|
||||
dimensions: []
|
||||
span_metrics:
|
||||
dimensions: []
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
|
||||
overrides:
|
||||
defaults:
|
||||
metrics_generator:
|
||||
processors: [service-graphs, span-metrics]
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,63 @@
|
||||
-- 0001: базовая схема lab2. Источник истины — PostgreSQL.
|
||||
-- Миграция выполняется раннером в одной транзакции и регистрируется в schema_migrations.
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT users_username_key UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_len CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
CONSTRAINT users_password_hash_kdf CHECK (password_hash LIKE '$scrypt$%')
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title text NOT NULL,
|
||||
created_by uuid NOT NULL REFERENCES users (id),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT chats_title_len CHECK (char_length(title) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
-- Состав участников неизменен в обязательном API; position сохраняет порядок member_ids из запроса.
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
position smallint NOT NULL,
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_position_key UNIQUE (chat_id, position),
|
||||
CONSTRAINT chat_members_position_range CHECK (position BETWEEN 0 AND 99)
|
||||
);
|
||||
-- GET /chats: «чаты пользователя» — поиск по user_id.
|
||||
CREATE INDEX chat_members_user_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
chat_id uuid NOT NULL,
|
||||
sender_id uuid NOT NULL,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
-- Отправитель обязан быть участником этого чата: инвариант защищён на уровне БД.
|
||||
CONSTRAINT messages_sender_is_member FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id),
|
||||
CONSTRAINT messages_text_len CHECK (char_length(text) BETWEEN 1 AND 4000)
|
||||
);
|
||||
-- История: WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT n.
|
||||
-- Обоснование и EXPLAIN — REPORT.md и evidence/track2/.
|
||||
CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id);
|
||||
|
||||
-- Серверные сессии. Хранится только SHA-256 от токена (токен — 256 бит случайности),
|
||||
-- поэтому утечка дампа не даёт готовых Bearer-токенов.
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
revoked_at timestamptz,
|
||||
CONSTRAINT sessions_token_hash_len CHECK (octet_length(token_hash) = 32),
|
||||
CONSTRAINT sessions_expiry_after_creation CHECK (expires_at > created_at)
|
||||
);
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expires_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- 0002: транзакционный outbox инвалидации кэша сессий (уровень 4).
|
||||
-- Строка пишется в той же транзакции, что и revoked_at. Если Redis недоступен в момент logout,
|
||||
-- фоновый процесс API повторит инвалидацию после восстановления Redis и только затем снова
|
||||
-- начнёт читать сессии из кэша.
|
||||
CREATE TABLE session_cache_invalidations (
|
||||
token_hash bytea PRIMARY KEY REFERENCES sessions (token_hash) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
@@ -0,0 +1,17 @@
|
||||
-- 0003 (lab3): общая идемпотентность POST /chats/{chat_id}/messages.
|
||||
-- Область ключа = пользователь + метод + путь чата + ключ. Единственный идемпотентный endpoint
|
||||
-- обязательного API — POST сообщения, поэтому метод и шаблон пути фиксированы, а «путь» = chat_id.
|
||||
-- Миграция аддитивна (expand): код lab2 её не использует и продолжает работать при rolling update.
|
||||
CREATE TABLE idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users (id),
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
request_hash bytea NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
PRIMARY KEY (user_id, chat_id, key),
|
||||
CONSTRAINT idempotency_key_format CHECK (key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
CONSTRAINT idempotency_request_hash_len CHECK (octet_length(request_hash) = 32)
|
||||
);
|
||||
-- Очистка ключей старше IDEMPOTENCY_TTL_SECONDS.
|
||||
CREATE INDEX idempotency_keys_created_idx ON idempotency_keys (created_at);
|
||||
@@ -0,0 +1,62 @@
|
||||
-- 0004 (lab4): вложения. Метаданные — здесь, байты — в приватном S3 bucket (ключ назначает сервер).
|
||||
|
||||
-- С lab4 текст может быть пустым, если у сообщения есть вложения (правило «пустой текст только с
|
||||
-- вложениями» проверяет приложение: связь в другой таблице). Expand-изменение: старый код его не нарушает.
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_len;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_len CHECK (char_length(text) <= 4000);
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL REFERENCES users (id),
|
||||
filename text NOT NULL, -- только для отображения, НЕ путь и НЕ ключ
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
width integer NOT NULL,
|
||||
height integer NOT NULL,
|
||||
object_key text NOT NULL,
|
||||
status text NOT NULL DEFAULT 'ready',
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
|
||||
CONSTRAINT attachments_filename_len CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
CONSTRAINT attachments_content_type CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
CONSTRAINT attachments_size CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
CONSTRAINT attachments_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
CONSTRAINT attachments_dims CHECK (width > 0 AND height > 0 AND width::bigint * height <= 40000000),
|
||||
CONSTRAINT attachments_status CHECK (status IN ('ready')) -- lab5 расширит (queued/processing/failed)
|
||||
);
|
||||
CREATE INDEX attachments_chat_idx ON attachments (chat_id, created_at);
|
||||
CREATE INDEX attachments_created_idx ON attachments (created_at);
|
||||
|
||||
-- Связь сообщение ↔ вложения (порядок attachment_ids из запроса сохраняется).
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id),
|
||||
position smallint NOT NULL,
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_position_key UNIQUE (message_id, position),
|
||||
CONSTRAINT message_attachments_position_range CHECK (position BETWEEN 0 AND 9)
|
||||
);
|
||||
CREATE INDEX message_attachments_attachment_idx ON message_attachments (attachment_id);
|
||||
|
||||
-- Журнал намерений загрузки (компенсация S3 ↔ PostgreSQL). Строка фиксируется ДО записи в S3 и
|
||||
-- удаляется в той же транзакции, что создаёт attachments. Осталась дольше grace period — значит,
|
||||
-- процесс упал между S3 PUT и COMMIT (или во время загрузки): объект по ключу удаляется очисткой.
|
||||
CREATE TABLE upload_intents (
|
||||
object_key text PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL,
|
||||
chat_id uuid NOT NULL,
|
||||
owner_id uuid NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE INDEX upload_intents_created_idx ON upload_intents (created_at);
|
||||
|
||||
-- Результаты проверки целостности (reconciler): проблемы, которые нельзя безопасно исправить
|
||||
-- автоматически (например, утрачен объект вложения, на которое ссылаются сообщения).
|
||||
CREATE TABLE attachment_integrity (
|
||||
attachment_id uuid PRIMARY KEY REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
problem text NOT NULL,
|
||||
detected_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT attachment_integrity_problem CHECK (problem IN ('missing_object', 'size_mismatch', 'checksum_mismatch'))
|
||||
);
|
||||
@@ -0,0 +1,118 @@
|
||||
-- 0005 (lab5): асинхронная обработка вложений. Expand-only: код lab4 продолжает работать со схемой
|
||||
-- (новые столбцы допускают NULL/имеют DEFAULT, старые значения ограничений по-прежнему допустимы).
|
||||
|
||||
-- Вложение: статусы queued/processing/ready/failed. object_key — КОНЕЧНЫЙ ключ оригинала
|
||||
-- (originals/<id>), он заполняется заранее, но объект появляется там только при переходе в ready.
|
||||
-- staging_key — ключ устойчивого staging (staging/<id>): полный проверенный оригинал, записанный ДО 202.
|
||||
-- published_version — версия pipeline, чьи варианты отдаёт API; меняется только вверх.
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status
|
||||
CHECK (status IN ('queued', 'processing', 'ready', 'failed'));
|
||||
ALTER TABLE attachments ADD COLUMN staging_key text;
|
||||
ALTER TABLE attachments ADD COLUMN error_code text;
|
||||
ALTER TABLE attachments ADD COLUMN published_version integer;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_staging_key_key UNIQUE (staging_key);
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_published_version CHECK (published_version IS NULL OR published_version >= 1);
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_error_code
|
||||
CHECK (error_code IS NULL OR error_code ~ '^[a-z_]{1,40}$');
|
||||
CREATE INDEX attachments_status_idx ON attachments (status, updated_at) WHERE status <> 'ready';
|
||||
|
||||
-- Логическая работа: одна на (вложение, версия pipeline). job_id не меняется при redelivery.
|
||||
-- attempt — управляемая попытка (поле attempt сообщения); растёт при retry/replay/восстановлении
|
||||
-- после истёкшего lease. Сообщение с attempt < текущего — устаревшее (ack без действий).
|
||||
-- claims — сколько раз работу захватывали на выполнение (включая перехват после смерти worker);
|
||||
-- ограничено max_attempts — так ограничен и «немой» цикл падений на ядовитом файле.
|
||||
-- lease_token — fencing-токен: растёт при каждом захвате; результат фиксируется, только если токен
|
||||
-- в БД всё ещё мой (ожившая «зомби»-попытка не перезапишет состояние).
|
||||
CREATE SEQUENCE job_lease_token_seq;
|
||||
CREATE TABLE attachment_jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL,
|
||||
status text NOT NULL DEFAULT 'queued',
|
||||
attempt integer NOT NULL DEFAULT 1,
|
||||
claims integer NOT NULL DEFAULT 0,
|
||||
max_attempts integer NOT NULL,
|
||||
lease_owner text,
|
||||
lease_token bigint NOT NULL DEFAULT 0,
|
||||
lease_until timestamptz,
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
error_code text,
|
||||
error_detail text,
|
||||
replays integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
finished_at timestamptz,
|
||||
CONSTRAINT attachment_jobs_effect_key UNIQUE (attachment_id, pipeline_version),
|
||||
CONSTRAINT attachment_jobs_status CHECK (status IN ('queued', 'processing', 'ready', 'failed', 'superseded')),
|
||||
CONSTRAINT attachment_jobs_version CHECK (pipeline_version >= 1),
|
||||
CONSTRAINT attachment_jobs_attempt CHECK (attempt >= 1 AND claims >= 0 AND max_attempts BETWEEN 1 AND 100),
|
||||
CONSTRAINT attachment_jobs_error_code CHECK (error_code IS NULL OR error_code ~ '^[a-z_]{1,40}$'),
|
||||
CONSTRAINT attachment_jobs_detail_len CHECK (char_length(error_detail) <= 300)
|
||||
);
|
||||
CREATE INDEX attachment_jobs_processing_idx ON attachment_jobs (lease_until) WHERE status = 'processing';
|
||||
CREATE INDEX attachment_jobs_queued_idx ON attachment_jobs (next_attempt_at) WHERE status = 'queued';
|
||||
CREATE INDEX attachment_jobs_failed_idx ON attachment_jobs (updated_at) WHERE status = 'failed';
|
||||
|
||||
-- Transactional outbox: строка пишется в ТОЙ ЖЕ транзакции, что и изменение состояния job. Relay
|
||||
-- публикует её в JetStream (Nats-Msg-Id = outbox-<id>: повторная публикация после сбоя relay
|
||||
-- отбрасывается брокером в окне дедупликации) и только после publish ack отмечает published_at.
|
||||
-- available_at — не раньше этого момента (backoff повторов реализован здесь, а не в брокере).
|
||||
CREATE TABLE job_outbox (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
|
||||
subject text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
available_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
published_at timestamptz,
|
||||
publish_attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text
|
||||
);
|
||||
CREATE INDEX job_outbox_pending_idx ON job_outbox (available_at, id) WHERE published_at IS NULL;
|
||||
CREATE INDEX job_outbox_job_idx ON job_outbox (job_id);
|
||||
|
||||
-- Результат обработки. Первичный ключ = ключ эффекта (attachment_id, pipeline_version, variant):
|
||||
-- повтор той же работы не может создать второй набор вариантов. object_key детерминирован тем же
|
||||
-- ключом (variants/<id>/v<version>/<name>.<ext>), поэтому и в S3 повтор перезаписывает тот же объект.
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL,
|
||||
name text NOT NULL,
|
||||
object_key text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
width integer NOT NULL,
|
||||
height integer NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
job_id uuid NOT NULL,
|
||||
lease_token bigint NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name),
|
||||
CONSTRAINT attachment_variants_object_key_key UNIQUE (object_key),
|
||||
CONSTRAINT attachment_variants_name CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
CONSTRAINT attachment_variants_type CHECK (content_type IN ('image/jpeg', 'image/png', 'image/webp')),
|
||||
CONSTRAINT attachment_variants_size CHECK (size_bytes >= 1 AND width >= 1 AND height >= 1),
|
||||
CONSTRAINT attachment_variants_sha256 CHECK (sha256 ~ '^[a-f0-9]{64}$')
|
||||
);
|
||||
|
||||
-- Журнал переходов: аудит (кто/когда/почему), реестр failed для оператора и данные для проверки
|
||||
-- инвариантов (трек 2). Без секретов: только ID, коды и короткие безопасные пояснения.
|
||||
CREATE TABLE job_events (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
pipeline_version integer NOT NULL,
|
||||
event text NOT NULL,
|
||||
attempt integer,
|
||||
lease_token bigint,
|
||||
worker text,
|
||||
detail jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT job_events_event CHECK (event IN (
|
||||
'enqueued', 'published', 'claimed', 'lease_takeover', 'lease_lost', 'retry_scheduled', 'committed',
|
||||
'failed', 'replayed', 'superseded', 'duplicate_ignored', 'stale_ignored', 'requeued_expired_lease',
|
||||
'republished_stuck', 'staging_cleaned', 'published_version_changed', 'deferred'))
|
||||
);
|
||||
CREATE INDEX job_events_job_idx ON job_events (job_id, id);
|
||||
CREATE INDEX job_events_attachment_idx ON job_events (attachment_id, id);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- 0006 (lab6): наблюдаемость. Expand-only: код lab5 продолжает работать (новый столбец допускает NULL,
|
||||
-- индексы не меняют семантику).
|
||||
|
||||
-- W3C trace context последней попытки задания ({"traceparent": "...", "tracestate": "..."}). Нужен,
|
||||
-- чтобы восстановление (истёкший lease, «застрявшее» задание, операторский replay) продолжало trace
|
||||
-- исходной загрузки, а не начинало новый. Это технические идентификаторы трассировки, не секреты.
|
||||
ALTER TABLE attachment_jobs ADD COLUMN trace_context jsonb;
|
||||
ALTER TABLE attachment_jobs ADD CONSTRAINT attachment_jobs_trace_context_size
|
||||
CHECK (trace_context IS NULL OR pg_column_size(trace_context) <= 1024);
|
||||
|
||||
-- Метрики очереди (messenger.queue.oldest_age) раз в несколько секунд ищут самое старое незавершённое
|
||||
-- задание: частичный индекс по created_at незавершённых работ держит этот запрос дешёвым.
|
||||
CREATE INDEX attachment_jobs_unfinished_created_idx ON attachment_jobs (created_at)
|
||||
WHERE status IN ('queued', 'processing');
|
||||
@@ -0,0 +1,30 @@
|
||||
# Runtime-зависимости API (точные версии, проверенные на стенде; см. REPORT.md).
|
||||
starlette==1.7.0
|
||||
anyio==4.15.1
|
||||
idna==3.20
|
||||
typing_extensions==4.16.0
|
||||
uvicorn==0.54.0
|
||||
h11==0.16.0
|
||||
click==8.5.0
|
||||
psycopg[binary]==3.2.10
|
||||
psycopg-binary==3.2.10
|
||||
psycopg-pool==3.2.6
|
||||
redis==5.2.1
|
||||
# lab4: асинхронный HTTP-клиент для S3 (SigV4 реализован в src/messenger/s3.py)
|
||||
httpx==0.28.1
|
||||
httpcore==1.0.9
|
||||
certifi==2026.10.18
|
||||
# lab5: клиент NATS JetStream (чистый Python, без обязательных зависимостей) и обработка изображений
|
||||
nats-py==2.11.0
|
||||
Pillow==12.3.0
|
||||
# lab6: OpenTelemetry SDK и OTLP/HTTP-экспортёр (protobuf). Версии SDK/semconv/proto согласованы (1.45.0 / 0.66b0).
|
||||
opentelemetry-api==1.45.0
|
||||
opentelemetry-sdk==1.45.0
|
||||
opentelemetry-semantic-conventions==0.66b0
|
||||
opentelemetry-proto==1.45.0
|
||||
opentelemetry-exporter-otlp-proto-common==1.45.0
|
||||
opentelemetry-exporter-otlp-common==0.66b0
|
||||
opentelemetry-exporter-http-transport==0.66b0
|
||||
opentelemetry-exporter-otlp-proto-http==1.45.0
|
||||
googleapis-common-protos==1.75.5
|
||||
protobuf==7.36.1
|
||||
@@ -0,0 +1,459 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Контролируемые инциденты lab6 (уровень 4): воздействие под нагрузкой → обнаружение ТОЛЬКО по сохранённым
|
||||
наблюдениям (Prometheus/Loki/Tempo через Grafana API) → восстановление → resolved.
|
||||
|
||||
python3 research/incidents.py worker-stop # остановка worker: растёт queue lag, алерты, затем backlog разбирается
|
||||
python3 research/incidents.py db-slow # PostgreSQL ограничен 0.03 CPU: медленная БД
|
||||
python3 research/incidents.py handler-slow # медленный обработчик (fault-api-slow) при быстрой БД — контраст
|
||||
python3 research/incidents.py db-down # PostgreSQL заморожен (pause): 503, error.type в trace
|
||||
python3 research/incidents.py telemetry-down # Tempo+Loki остановлены: API работает, очередь Collector ограничена
|
||||
python3 research/incidents.py collector-down # Collector остановлен: SDK ограничивает очередь и считает потери
|
||||
python3 research/incidents.py all --out evidence/incidents
|
||||
|
||||
Вывод: таймлайн (время от воздействия до firing/resolved), значения метрик, найденные trace/логи.
|
||||
Требует FAULT_HOOKS=lab для handler-slow. Volumes не трогаются.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from common import BASE_URL, Client, Failure, login, make_png, new_user # noqa: E402
|
||||
from obs import Grafana, ObsError # noqa: E402
|
||||
|
||||
DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env"))
|
||||
g = Grafana()
|
||||
DB_SLOW_CPUS = os.environ.get("DB_SLOW_CPUS", "0.03") # «медленная БД»: квота CPU контейнера PostgreSQL
|
||||
|
||||
|
||||
def dc(*args, check=True, timeout=180):
|
||||
return subprocess.run(DC + list(args), cwd=ROOT, check=check, timeout=timeout, capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def container_ids(service):
|
||||
return dc("ps", "-q", service).split()
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.run(["docker"] + list(args), check=True, capture_output=True, text=True, timeout=60).stdout
|
||||
|
||||
|
||||
def log(msg):
|
||||
print("[%s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- нагрузка
|
||||
class Load:
|
||||
"""Фоновая нагрузка: сообщения (rate/с) и, опционально, загрузки картинок (раз в upload_every с)."""
|
||||
|
||||
def __init__(self, rate=6.0, upload_every=None, slow_share=0.0, threads=4):
|
||||
self.c = Client(BASE_URL, timeout=15)
|
||||
self.actor = new_user(self.c, "inc")
|
||||
login(self.c, self.actor)
|
||||
self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.actor, schema="Chat",
|
||||
body={"title": "incident", "member_ids": [self.actor["id"]]})["json"]
|
||||
self.rate, self.upload_every, self.slow_share, self.threads = rate, upload_every, slow_share, threads
|
||||
self.stop = threading.Event()
|
||||
self.results = [] # (t, kind, status, latency_s)
|
||||
self.uploads = [] # attachment ids
|
||||
self.lock = threading.Lock()
|
||||
self._n = 0
|
||||
|
||||
def _msg(self):
|
||||
period = self.threads / self.rate
|
||||
while not self.stop.is_set():
|
||||
t0 = time.monotonic()
|
||||
with self.lock:
|
||||
self._n += 1
|
||||
n = self._n
|
||||
slow = self.slow_share and (n % round(1 / self.slow_share) == 0)
|
||||
text = "incident load %d%s" % (n, " fault-api-slow-400" if slow else "")
|
||||
status = 0
|
||||
try:
|
||||
r = self.c.call("POST", "/api/v1/chats/%s/messages" % self.chat["id"], [201, 500, 502, 503, 504],
|
||||
actor=self.actor, body={"text": text}, headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
status = r["status"]
|
||||
except Failure:
|
||||
status = -1
|
||||
with self.lock:
|
||||
self.results.append((time.time(), "msg", status, time.monotonic() - t0))
|
||||
self.stop.wait(max(0.0, period - (time.monotonic() - t0)))
|
||||
|
||||
def _upload(self):
|
||||
while not self.stop.is_set():
|
||||
t0 = time.monotonic()
|
||||
try:
|
||||
r = self.c.call("POST", "/api/v1/chats/%s/attachments?filename=inc.png" % self.chat["id"], [202, 503],
|
||||
actor=self.actor, raw=make_png(), headers={"Content-Type": "image/png"})
|
||||
if r["status"] == 202:
|
||||
self.uploads.append(json.loads(r["bytes"])["id"])
|
||||
status = r["status"]
|
||||
except Failure:
|
||||
status = -1
|
||||
with self.lock:
|
||||
self.results.append((time.time(), "upload", status, time.monotonic() - t0))
|
||||
self.stop.wait(self.upload_every)
|
||||
|
||||
def __enter__(self):
|
||||
self.ts = [threading.Thread(target=self._msg, daemon=True) for _ in range(self.threads)]
|
||||
if self.upload_every:
|
||||
self.ts.append(threading.Thread(target=self._upload, daemon=True))
|
||||
for t in self.ts:
|
||||
t.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
self.stop.set()
|
||||
for t in self.ts:
|
||||
t.join(20)
|
||||
|
||||
def window(self, t0, t1, kind="msg"):
|
||||
with self.lock:
|
||||
rows = [r for r in self.results if t0 <= r[0] < t1 and r[1] == kind]
|
||||
ok = [r for r in rows if r[2] in (201, 202)]
|
||||
lat = sorted(r[3] for r in ok)
|
||||
pct = lambda p: round(lat[min(len(lat) - 1, int(p * len(lat)))] * 1000, 1) if lat else None # noqa: E731
|
||||
return {"requests": len(rows), "ok": len(ok), "errors": len(rows) - len(ok),
|
||||
"error_statuses": sorted({r[2] for r in rows if r[2] not in (201, 202)}),
|
||||
"p50_ms": pct(0.5), "p95_ms": pct(0.95), "p99_ms": pct(0.99)}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- наблюдение
|
||||
WATCH = {
|
||||
"error_ratio": "sli:api_error_ratio:rate1m",
|
||||
"api_p95_s": "sli:api_latency_p95:1m",
|
||||
"db_p95_s": "histogram_quantile(0.95, sum by (le) (rate(db_client_operation_duration_seconds_bucket[1m])))",
|
||||
"queue_lag_s": "sli:queue_lag_seconds:max",
|
||||
"queue_ready": 'max(last_over_time(messenger_queue_depth{state="ready"}[30s]))',
|
||||
"workers_capacity": "sum(last_over_time(messenger_worker_capacity[20s]))",
|
||||
"db_pool_waiting_api": 'sum(last_over_time(db_client_connection_pending_requests{service_name="messenger-api"}[30s]))',
|
||||
"collector_queue": "sum(otelcol_exporter_queue_size)",
|
||||
"collector_rss_mib": "max(otelcol_process_memory_rss) / 1048576",
|
||||
}
|
||||
|
||||
|
||||
def snapshot():
|
||||
out = {}
|
||||
for k, q in WATCH.items():
|
||||
try:
|
||||
v = g.prom_value(q)
|
||||
out[k] = None if v is None or v != v else round(v, 4)
|
||||
except ObsError:
|
||||
out[k] = None
|
||||
return out
|
||||
|
||||
|
||||
def firing():
|
||||
try:
|
||||
return {a["labels"]["alertname"]: a["state"] for a in g.alerts()}
|
||||
except ObsError:
|
||||
return None
|
||||
|
||||
|
||||
class Timeline:
|
||||
def __init__(self, name):
|
||||
self.name, self.t0, self.rows, self.marks = name, time.time(), [], {}
|
||||
self.first = {} # alert -> первое время firing (с от t0)
|
||||
self.resolved = {}
|
||||
|
||||
def mark(self, label):
|
||||
self.marks[label] = round(time.time() - self.t0, 1)
|
||||
log("%s: %s (t=%.1fs)" % (self.name, label, self.marks[label]))
|
||||
|
||||
def poll(self):
|
||||
a = firing()
|
||||
s = snapshot()
|
||||
t = round(time.time() - self.t0, 1)
|
||||
self.rows.append({"t": t, "alerts": a, **s})
|
||||
for name, st in (a or {}).items():
|
||||
if st == "firing" and name not in self.first:
|
||||
self.first[name] = t
|
||||
log(" FIRING %s at t=%.1fs" % (name, t))
|
||||
for name in list(self.first):
|
||||
if a is not None and name not in a and name not in self.resolved:
|
||||
self.resolved[name] = t
|
||||
log(" resolved %s at t=%.1fs" % (name, t))
|
||||
return a or {}, s
|
||||
|
||||
def wait(self, cond, timeout, every=5):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
a, s = self.poll()
|
||||
if cond(a, s):
|
||||
return True
|
||||
time.sleep(every)
|
||||
return False
|
||||
|
||||
def summary(self, extra=None):
|
||||
return {"scenario": self.name, "marks_s": self.marks, "alerts_first_firing_s": self.first,
|
||||
"alerts_resolved_s": self.resolved, **(extra or {}), "timeline": self.rows}
|
||||
|
||||
|
||||
def quiet(a, _s, names):
|
||||
return not any(n in a for n in names)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------------------- сценарии
|
||||
def worker_stop():
|
||||
tl = Timeline("worker-stop")
|
||||
names = ("JobQueueLagGrowing", "WorkerHeartbeatMissing")
|
||||
with Load(rate=3, upload_every=2) as load:
|
||||
tl.wait(lambda a, s: quiet(a, s, names), 120)
|
||||
time.sleep(20)
|
||||
tl.mark("worker stopped")
|
||||
stop_at = time.time()
|
||||
dc("stop", "worker")
|
||||
ok = tl.wait(lambda a, s: all(a.get(n) == "firing" for n in names), 240)
|
||||
tl.mark("both alerts firing" if ok else "alerts NOT firing in time")
|
||||
peak = max((r.get("queue_ready") or 0) for r in tl.rows)
|
||||
time.sleep(15)
|
||||
tl.mark("worker started")
|
||||
start_at = time.time()
|
||||
dc("start", "worker")
|
||||
ok2 = tl.wait(lambda a, s: quiet(a, s, names) and (s.get("queue_ready") or 0) == 0, 300)
|
||||
tl.mark("alerts resolved, backlog empty" if ok2 else "NOT recovered in time")
|
||||
load.stop.set()
|
||||
# все принятые во время остановки загрузки обработаны (без потерь)
|
||||
c, actor = load.c, load.actor
|
||||
deadline = time.time() + 120
|
||||
pending = list(load.uploads)
|
||||
while pending and time.time() < deadline:
|
||||
pending = [a for a in pending if c.call("GET", "/api/v1/attachments/" + a, actor=actor, schema="Attachment")["json"]["status"] != "ready"]
|
||||
time.sleep(2)
|
||||
logs = g.loki('{service_name="messenger-api"} | event="attachment.accepted"', start=stop_at, end=start_at, limit=1000)
|
||||
wlogs = g.loki('{service_name="messenger-worker"}', start=stop_at + 15, end=start_at, limit=50)
|
||||
res = tl.summary({"uploads_accepted": len(load.uploads), "uploads_not_ready_after_recovery": len(pending),
|
||||
"queue_ready_peak": peak, "api_accepted_logs_during_outage": len(logs),
|
||||
"worker_logs_during_outage": len(wlogs),
|
||||
"detection_s": {n: round(tl.first.get(n, -1) - tl.marks["worker stopped"], 1) for n in names},
|
||||
"recovery_s": {n: round(tl.resolved.get(n, -1) - tl.marks["worker started"], 1) for n in names},
|
||||
"http_during_outage": load.window(stop_at, start_at)})
|
||||
return res
|
||||
|
||||
|
||||
def _slow_trace(route, since=240, min_ms=150):
|
||||
"""Самый медленный server span маршрута за окно; доля времени в DB spans внутри него."""
|
||||
traces = g.search('{ span.http.route = "%s" && kind = server && duration > %dms }' % (route, min_ms), since=since, limit=20)
|
||||
best = None
|
||||
for tr in traces[:10]:
|
||||
spans = g.trace(tr["traceID"]) or []
|
||||
srv = [s for s in spans if s["kind"] == "SERVER"]
|
||||
if not srv:
|
||||
continue
|
||||
sv = srv[0]
|
||||
dur = sv["end"] - sv["start"]
|
||||
db = sum(s["end"] - s["start"] for s in spans if s["attrs"].get("db.system.name") == "postgresql")
|
||||
pool_ids = {s["span_id"] for s in spans if s["name"] == "pool.acquire"}
|
||||
pool = sum(s["end"] - s["start"] for s in spans if s["name"] == "pool.acquire")
|
||||
# pool.check внутри pool.acquire уже учтён в db — не считать дважды
|
||||
pool -= sum(s["end"] - s["start"] for s in spans if s["parent"] in pool_ids and s["attrs"].get("db.system.name"))
|
||||
other = dur - sum(s["end"] - s["start"] for s in spans if s["parent"] == sv["span_id"])
|
||||
item = {"trace_id": sv["trace_id"], "duration_ms": round(dur * 1000, 1), "db_ms": round(db * 1000, 1),
|
||||
"pool_wait_ms": round(pool * 1000, 1),
|
||||
"db_share": round(db / dur, 2) if dur else None,
|
||||
"db_or_pool_share": round((db + pool) / dur, 2) if dur else None,
|
||||
"not_in_child_spans_ms": round(other * 1000, 1),
|
||||
"error_type": sv["attrs"].get("error.type"),
|
||||
"slowest_child": max(((s["name"], round((s["end"] - s["start"]) * 1000, 1)) for s in spans
|
||||
if s["parent"] == sv["span_id"]), key=lambda x: x[1], default=None)}
|
||||
if best is None or item["duration_ms"] > best["duration_ms"]:
|
||||
best = item
|
||||
return best
|
||||
|
||||
|
||||
def db_slow():
|
||||
tl = Timeline("db-slow")
|
||||
names = ("DbSlowQueries",)
|
||||
pg = container_ids("postgres")[0]
|
||||
with Load(rate=6) as load:
|
||||
tl.wait(lambda a, s: quiet(a, s, names + ("ApiLatencyHigh",)), 120)
|
||||
time.sleep(30)
|
||||
base = dict(snapshot())
|
||||
tl.mark("postgres limited to %s CPU" % DB_SLOW_CPUS)
|
||||
t1 = time.time()
|
||||
docker("update", "--cpus", DB_SLOW_CPUS, pg)
|
||||
ok = tl.wait(lambda a, s: a.get("DbSlowQueries") == "firing", 240)
|
||||
tl.mark("DbSlowQueries firing" if ok else "DbSlowQueries NOT firing")
|
||||
# держим деградацию, пока не сработает и пользовательский симптом (p95 API > SLO), не дольше 2 мин
|
||||
tl.wait(lambda a, s: a.get("ApiLatencyHigh") == "firing", 120)
|
||||
during = dict(snapshot())
|
||||
trace = _slow_trace("/api/v1/chats/{chat_id}/messages", since=int(time.time() - t1) + 30)
|
||||
tl.mark("postgres restored to 1.0 CPU")
|
||||
t2 = time.time()
|
||||
docker("update", "--cpus", os.environ.get("PG_CPUS", "1.0"), pg)
|
||||
ok2 = tl.wait(lambda a, s: quiet(a, s, names + ("ApiLatencyHigh", "ApiHighErrorRate")), 300)
|
||||
tl.mark("resolved" if ok2 else "NOT resolved in time")
|
||||
load.stop.set()
|
||||
return tl.summary({"metrics_before": base, "metrics_during": during, "slow_trace": trace,
|
||||
"http_before": load.window(t1 - 30, t1), "http_during": load.window(t1, t2),
|
||||
"detection_s": round(tl.first.get("DbSlowQueries", -1) - tl.marks["postgres limited to %s CPU" % DB_SLOW_CPUS], 1)})
|
||||
|
||||
|
||||
def handler_slow():
|
||||
tl = Timeline("handler-slow")
|
||||
with Load(rate=6, slow_share=0.5) as load:
|
||||
t1 = time.time()
|
||||
tl.mark("50% of messages carry fault-api-slow-400 (sleep in handler)")
|
||||
ok = tl.wait(lambda a, s: a.get("ApiLatencyHigh") == "firing", 240)
|
||||
tl.mark("ApiLatencyHigh firing" if ok else "ApiLatencyHigh NOT firing")
|
||||
during = dict(snapshot())
|
||||
db_alert = "DbSlowQueries" in (firing() or {})
|
||||
trace = _slow_trace("/api/v1/chats/{chat_id}/messages", since=int(time.time() - t1) + 30, min_ms=350)
|
||||
t2 = time.time()
|
||||
load.stop.set()
|
||||
ok2 = tl.wait(lambda a, s: quiet(a, s, ("ApiLatencyHigh",)), 300)
|
||||
tl.mark("resolved" if ok2 else "NOT resolved in time")
|
||||
return tl.summary({"metrics_during": during, "db_alert_fired": db_alert, "slow_trace": trace,
|
||||
"http_during": load.window(t1, t2),
|
||||
"detection_s": round(tl.first.get("ApiLatencyHigh", -1), 1)})
|
||||
|
||||
|
||||
def db_down():
|
||||
tl = Timeline("db-down")
|
||||
with Load(rate=6) as load:
|
||||
tl.wait(lambda a, s: quiet(a, s, ("ApiHighErrorRate",)), 120)
|
||||
time.sleep(15)
|
||||
tl.mark("postgres paused")
|
||||
t1 = time.time()
|
||||
dc("pause", "postgres")
|
||||
ok = tl.wait(lambda a, s: a.get("ApiHighErrorRate") == "firing", 180)
|
||||
tl.mark("ApiHighErrorRate firing" if ok else "ApiHighErrorRate NOT firing")
|
||||
tl.mark("postgres unpaused")
|
||||
t2 = time.time()
|
||||
dc("unpause", "postgres")
|
||||
ok2 = tl.wait(lambda a, s: quiet(a, s, ("ApiHighErrorRate",)), 300)
|
||||
tl.mark("resolved" if ok2 else "NOT resolved in time")
|
||||
load.stop.set()
|
||||
errs = g.search('{ resource.service.name = "messenger-api" && kind = server && status = error }', since=int(time.time() - t1) + 30)
|
||||
etypes = {}
|
||||
for tr in errs[:20]:
|
||||
for s in g.trace(tr["traceID"]) or []:
|
||||
if s["kind"] == "SERVER":
|
||||
etypes[s["attrs"].get("error.type")] = etypes.get(s["attrs"].get("error.type"), 0) + 1
|
||||
logs = g.loki('{service_name="messenger-api"} | event="dependency.unavailable"', start=t1, end=t2 + 30, limit=1000)
|
||||
return tl.summary({"http_during": load.window(t1, t2), "error_traces_error_type": etypes,
|
||||
"dependency_unavailable_logs": len(logs),
|
||||
"logged_errors": sorted({r.get("error") for r in logs}),
|
||||
"detection_s": round(tl.first.get("ApiHighErrorRate", -1) - tl.marks["postgres paused"], 1)})
|
||||
|
||||
|
||||
def _cstats(service):
|
||||
out = {}
|
||||
for cid in container_ids(service):
|
||||
line = docker("stats", "--no-stream", "--format", "{{.MemUsage}}", cid).strip()
|
||||
out[cid[:12]] = line.split("/")[0].strip()
|
||||
return out
|
||||
|
||||
|
||||
def telemetry_down():
|
||||
tl = Timeline("telemetry-down")
|
||||
q = lambda e: g.prom_value(e, 0) # noqa: E731
|
||||
with Load(rate=6, upload_every=3) as load:
|
||||
time.sleep(20)
|
||||
before = {"accepted_spans": q("sum(otelcol_receiver_accepted_spans_total)"),
|
||||
"send_failed_spans": q("sum(otelcol_exporter_send_failed_spans_total)"),
|
||||
"enqueue_failed_spans": q("sum(otelcol_exporter_enqueue_failed_spans_total)"),
|
||||
"send_failed_logs": q("sum(otelcol_exporter_send_failed_log_records_total)"),
|
||||
"enqueue_failed_logs": q("sum(otelcol_exporter_enqueue_failed_log_records_total)")}
|
||||
rss0 = _cstats("otel-collector")
|
||||
tl.mark("tempo and loki stopped")
|
||||
t1 = time.time()
|
||||
dc("stop", "tempo", "loki")
|
||||
ok = tl.wait(lambda a, s: a.get("TelemetryExportFailing") == "firing", 180)
|
||||
tl.mark("TelemetryExportFailing firing" if ok else "TelemetryExportFailing NOT firing")
|
||||
time.sleep(60)
|
||||
rss1 = _cstats("otel-collector")
|
||||
qmax = max((r.get("collector_queue") or 0) for r in tl.rows)
|
||||
cap = q("max(otelcol_exporter_queue_capacity)")
|
||||
tl.mark("tempo and loki started")
|
||||
t2 = time.time()
|
||||
dc("start", "tempo", "loki")
|
||||
ok2 = tl.wait(lambda a, s: quiet(a, s, ("TelemetryExportFailing",)) and (s.get("collector_queue") or 0) == 0, 360)
|
||||
tl.mark("resolved, queue drained" if ok2 else "NOT resolved in time")
|
||||
load.stop.set()
|
||||
after = {k: q(e) for k, e in (("accepted_spans", "sum(otelcol_receiver_accepted_spans_total)"),
|
||||
("send_failed_spans", "sum(otelcol_exporter_send_failed_spans_total)"),
|
||||
("enqueue_failed_spans", "sum(otelcol_exporter_enqueue_failed_spans_total)"),
|
||||
("send_failed_logs", "sum(otelcol_exporter_send_failed_log_records_total)"),
|
||||
("enqueue_failed_logs", "sum(otelcol_exporter_enqueue_failed_log_records_total)"))}
|
||||
lost = {k: round(after[k] - before[k]) for k in before}
|
||||
# trace, начатый во время простоя Tempo, но доставленный после восстановления из очереди Collector
|
||||
during_traces = g.search('{ resource.service.name = "messenger-api" && kind = server }', since=int(time.time() - t1) + 10, limit=200)
|
||||
in_outage = [t for t in during_traces if t1 * 1e9 <= int(t.get("startTimeUnixNano", 0)) <= t2 * 1e9]
|
||||
return tl.summary({"http_during": load.window(t1, t2), "uploads_during": load.window(t1, t2, "upload"),
|
||||
"collector_mem_before": rss0, "collector_mem_during": rss1, "exporter_queue_max": qmax,
|
||||
"exporter_queue_capacity": cap, "telemetry_delta": lost,
|
||||
"traces_from_outage_window_found_after_recovery": len(in_outage),
|
||||
"detection_s": round(tl.first.get("TelemetryExportFailing", -1) - tl.marks["tempo and loki stopped"], 1)})
|
||||
|
||||
|
||||
def collector_down():
|
||||
tl = Timeline("collector-down")
|
||||
q = lambda e: g.prom_value(e, 0) # noqa: E731
|
||||
lost_q = {"spans_export_failed": 'sum(otel_sdk_exporter_span_exported_total{error_type!=""})',
|
||||
"spans_queue_dropped": 'sum(otel_sdk_processor_span_processed_total{error_type!=""})',
|
||||
"logs_export_failed": 'sum(otel_sdk_exporter_log_exported_total{error_type!=""})',
|
||||
"logs_queue_dropped": 'sum(otel_sdk_processor_log_processed_total{error_type!=""})',
|
||||
"spans_started": 'sum(otel_sdk_span_started_total)'}
|
||||
with Load(rate=8) as load:
|
||||
tl.wait(lambda a, s: quiet(a, s, ("OtelCollectorDown", "TelemetryLostInSdk")), 400)
|
||||
time.sleep(10)
|
||||
before = {k: q(e) for k, e in lost_q.items()}
|
||||
mem0 = _cstats("api")
|
||||
tl.mark("otel-collector stopped")
|
||||
t1 = time.time()
|
||||
dc("stop", "otel-collector")
|
||||
ok = tl.wait(lambda a, s: a.get("OtelCollectorDown") == "firing", 120)
|
||||
tl.mark("OtelCollectorDown firing" if ok else "OtelCollectorDown NOT firing")
|
||||
time.sleep(max(0, 90 - (time.time() - t1)))
|
||||
mem1 = _cstats("api")
|
||||
tl.mark("otel-collector started")
|
||||
t2 = time.time()
|
||||
dc("start", "otel-collector")
|
||||
ok2 = tl.wait(lambda a, s: "OtelCollectorDown" not in a and a.get("TelemetryLostInSdk") == "firing", 180)
|
||||
tl.mark("collector back; SDK losses reported" if ok2 else "SDK losses NOT reported")
|
||||
time.sleep(20)
|
||||
load.stop.set()
|
||||
after = {k: q(e) for k, e in lost_q.items()}
|
||||
delta = {k: round(after[k] - before[k]) for k in lost_q}
|
||||
by_type = {r["metric"].get("error_type"): round(float(r["value"][1])) for r in
|
||||
g.prom('sum by (error_type) (otel_sdk_exporter_span_exported_total{error_type!=""})')}
|
||||
return tl.summary({"http_before": load.window(t1 - 20, t1), "http_during": load.window(t1, t2),
|
||||
"api_mem_before": mem0, "api_mem_during": mem1, "sdk_delta": delta,
|
||||
"sdk_export_errors_by_type_total": by_type,
|
||||
"detection_s": round(tl.first.get("OtelCollectorDown", -1) - tl.marks["otel-collector stopped"], 1)})
|
||||
|
||||
|
||||
SCENARIOS = {"worker-stop": worker_stop, "db-slow": db_slow, "handler-slow": handler_slow, "db-down": db_down,
|
||||
"telemetry-down": telemetry_down, "collector-down": collector_down}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("scenario", choices=list(SCENARIOS) + ["all"])
|
||||
ap.add_argument("--out", help="каталог для JSON-результатов")
|
||||
a = ap.parse_args()
|
||||
names = list(SCENARIOS) if a.scenario == "all" else [a.scenario]
|
||||
rc = 0
|
||||
for n in names:
|
||||
res = SCENARIOS[n]()
|
||||
short = {k: v for k, v in res.items() if k != "timeline"}
|
||||
print(json.dumps(short, ensure_ascii=False, indent=1))
|
||||
if a.out:
|
||||
Path(a.out).mkdir(parents=True, exist_ok=True)
|
||||
(Path(a.out) / (n + ".json")).write_text(json.dumps(res, ensure_ascii=False, indent=1))
|
||||
if any("NOT" in k for k in res["marks_s"]):
|
||||
rc = 1
|
||||
return rc
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Снимок конфигурации и состояния наблюдаемости (для evidence/observability.txt): datasources, dashboard,
|
||||
правила/алерты Prometheus, фактические имена метрик приложения с labels, labels Loki, примеры TraceQL.
|
||||
Секретов не выводит (пароль Grafana читается из файла и не печатается)."""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests"))
|
||||
from obs import Grafana # noqa: E402
|
||||
|
||||
g = Grafana()
|
||||
|
||||
|
||||
def main():
|
||||
print("== Grafana", g.get("/api/health").get("version"))
|
||||
for d in g.get("/api/datasources"):
|
||||
h = g.get("/api/datasources/uid/%s/health" % d["uid"])
|
||||
print("datasource uid=%-10s type=%-10s url=%-24s readOnly=%s health=%s" % (
|
||||
d["uid"], d["type"], d["url"], d["readOnly"], h.get("status")))
|
||||
dash = g.get("/api/dashboards/uid/messenger-overview")
|
||||
panels = [p for p in dash["dashboard"]["panels"] if p.get("type") != "row"]
|
||||
print("dashboard uid=messenger-overview provisioned=%s panels=%d folder=%s" % (
|
||||
dash["meta"].get("provisioned"), len(panels), dash["meta"].get("folderTitle")))
|
||||
print("\n== Prometheus: правила и состояние")
|
||||
for grp in g.rules():
|
||||
for r in grp["rules"]:
|
||||
print("%-9s %-26s health=%-3s state=%s" % (r["type"], r["name"], r.get("health"), r.get("state", "-")))
|
||||
print("\n== Метрики приложения (Prometheus, имя → labels кроме ресурсных)")
|
||||
names = g.get("/api/datasources/proxy/uid/prometheus/api/v1/label/__name__/values")["data"]
|
||||
res_labels = {"__name__", "service_name", "service_namespace", "service_instance_id", "deployment_environment_name",
|
||||
"job", "instance", "otel_scope_name", "otel_scope_version", "le", "otel_scope_schema_url"}
|
||||
for n in names:
|
||||
if not n.startswith(("http_server_", "db_client_", "messenger_", "container_", "process_cpu_time",
|
||||
"process_memory_usage", "otel_sdk_processor", "otel_sdk_exporter_span", "otel_sdk_span")):
|
||||
continue
|
||||
if n.endswith(("_sum", "_count")):
|
||||
continue
|
||||
ser = g.series(n, since=3600)
|
||||
labels = sorted(set().union(*(s.keys() for s in ser)) - res_labels) if ser else []
|
||||
print("%-58s series=%-4d labels=%s" % (n, len(ser), ",".join(labels)))
|
||||
print("\n== Loki labels (index):", ",".join(g.get("/api/datasources/proxy/uid/loki/loki/api/v1/labels")["data"]))
|
||||
for svc in ("messenger-api", "messenger-worker"):
|
||||
recs = g.loki('{service_name="%s"}' % svc, since=3600, limit=1)
|
||||
if recs:
|
||||
rec = {k: v for k, v in recs[-1].items() if k not in ("line", "ts")}
|
||||
print("пример записи %s: поля=%s" % (svc, ",".join(sorted(rec))))
|
||||
print("\n== Tempo")
|
||||
for q in ('{ resource.service.name = "messenger-api" && kind = server }',
|
||||
'{ span.messaging.operation.type = "process" }', '{ status = error }'):
|
||||
print("%-62s traces(1h, limit 20)=%d" % (q, len(g.search(q, since=3600, limit=20))))
|
||||
print("\n== Активные алерты:", json.dumps([(a["labels"]["alertname"], a["state"]) for a in g.alerts()], ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,355 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 1 «Цена наблюдаемости»: одинаковая open-loop нагрузка при разных настройках telemetry.
|
||||
|
||||
Конфигурации (переключаются пересозданием api/worker/otel-collector с переменными окружения Compose):
|
||||
off OTEL_SDK_DISABLED=true — telemetry выключена целиком (база)
|
||||
full SDK 100% trace, Collector хранит всё — максимум данных
|
||||
head10 SDK head sampling 10% (parentbased_traceidratio) — дёшево, но решение принято ДО исхода запроса
|
||||
tail SDK 100% → Collector tail sampling (collector-tail.yaml): все ошибки, все > 250 мс,
|
||||
все trace pipeline вложений и 10% остальных — предлагаемая сбалансированная конфигурация
|
||||
Метрики RED во всех «on»-вариантах считаются SDK по всем запросам (sampling на них не влияет).
|
||||
|
||||
Нагрузка (одинакова для всех): open-loop R запросов/с (латентность от ЗАПЛАНИРОВАННОГО момента — без
|
||||
coordinated omission): 85% POST сообщения, 15% GET истории; 1% запросов — редкие ошибки (fault-api-error →
|
||||
500), 1% — редкие медленные (fault-api-slow-300); upload картинки раз в 2 с (spans worker). Прогрев 15 с,
|
||||
измерение WINDOW с, повторы — чередованием конфигураций (A B C D A B C D …).
|
||||
|
||||
Измеряется: успешные RPS, p50/p95/p99 (без намеренно медленных), CPU/RAM контейнеров (docker stats, среднее
|
||||
и максимум), ingest (spans/logs/metric points в Collector; байты и spans в Tempo, байты и строки в Loki;
|
||||
samples в Prometheus), потери spans (SDK: очередь/экспорт; Collector: отказ/ошибки отправки) и доля
|
||||
найденных в Tempo trace редких ошибок и медленных запросов (по request_id).
|
||||
|
||||
python3 research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1
|
||||
Требует FAULT_HOOKS=lab. Стенд в конце возвращается к конфигурации full.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from common import BASE_URL, Client, Failure, login, make_png, new_user # noqa: E402
|
||||
from obs import Grafana, ObsError # noqa: E402
|
||||
|
||||
DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env"))
|
||||
CONFIGS = {
|
||||
"off": {"OTEL_SDK_DISABLED": "true", "OTEL_TRACES_SAMPLER_ARG": "1.0", "OTEL_COLLECTOR_CONFIG": "collector.yaml"},
|
||||
"full": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "OTEL_COLLECTOR_CONFIG": "collector.yaml"},
|
||||
"head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "0.1", "OTEL_COLLECTOR_CONFIG": "collector.yaml"},
|
||||
"tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "OTEL_COLLECTOR_CONFIG": "collector-tail.yaml"},
|
||||
}
|
||||
GROUPS = {"api": ["api"], "worker": ["worker"], "collector": ["otel-collector"],
|
||||
"backends": ["prometheus", "loki", "tempo"], "postgres": ["postgres"]}
|
||||
g = Grafana()
|
||||
|
||||
|
||||
def log(msg):
|
||||
print("[%s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True)
|
||||
|
||||
|
||||
def dc(*args, env=None, timeout=300):
|
||||
e = dict(os.environ, **(env or {}))
|
||||
return subprocess.run(DC + list(args), cwd=ROOT, env=e, check=True, capture_output=True, text=True, timeout=timeout).stdout
|
||||
|
||||
|
||||
def apply(name):
|
||||
dc("up", "-d", "--wait", "api", "worker", "otel-collector", env=CONFIGS[name], timeout=600)
|
||||
# все реплики за LB снова ready
|
||||
c = Client(BASE_URL)
|
||||
deadline = time.time() + 120
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if c.call("GET", "/health/ready", [200, 503])["status"] == 200:
|
||||
break
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------- ресурсы
|
||||
def _mem(s):
|
||||
v, unit = s.strip(), 1
|
||||
for suf, mul in (("GiB", 1024 ** 3), ("MiB", 1024 ** 2), ("KiB", 1024), ("kB", 1000), ("MB", 1e6), ("GB", 1e9), ("B", 1)):
|
||||
if v.endswith(suf):
|
||||
return float(v[:-len(suf)]) * mul
|
||||
return float(v) * unit
|
||||
|
||||
|
||||
class Stats(threading.Thread):
|
||||
"""Сэмплы docker stats (CPU %, память) по группам сервисов каждые ~2 с."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(daemon=True)
|
||||
self.ids = {}
|
||||
for gname, svcs in GROUPS.items():
|
||||
for s in svcs:
|
||||
for cid in dc("ps", "-q", s).split():
|
||||
self.ids[cid[:12]] = gname
|
||||
self.samples = {k: [] for k in GROUPS}
|
||||
self.stop = threading.Event()
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.ID}};{{.CPUPerc}};{{.MemUsage}}"]
|
||||
+ list(self.ids), capture_output=True, text=True, timeout=30).stdout
|
||||
agg = {k: [0.0, 0.0] for k in GROUPS}
|
||||
for line in out.splitlines():
|
||||
cid, cpu, mem = line.split(";")
|
||||
gname = self.ids.get(cid[:12])
|
||||
if gname:
|
||||
agg[gname][0] += float(cpu.rstrip("%") or 0)
|
||||
agg[gname][1] += _mem(mem.split("/")[0])
|
||||
for k, (cpu, mem) in agg.items():
|
||||
self.samples[k].append((cpu, mem))
|
||||
self.stop.wait(1.0)
|
||||
|
||||
def summary(self):
|
||||
out = {}
|
||||
for k, v in self.samples.items():
|
||||
if v:
|
||||
out[k] = {"cpu_pct_avg": round(statistics.mean(c for c, _ in v), 1),
|
||||
"mem_mib_avg": round(statistics.mean(m for _, m in v) / 2 ** 20, 1),
|
||||
"mem_mib_max": round(max(m for _, m in v) / 2 ** 20, 1)}
|
||||
return out
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------- нагрузка
|
||||
class OpenLoop:
|
||||
def __init__(self, rate, seconds, warmup):
|
||||
self.c = Client(BASE_URL, timeout=15)
|
||||
self.actor = new_user(self.c, "cost")
|
||||
login(self.c, self.actor)
|
||||
self.chat = self.c.call("POST", "/api/v1/chats", 201, actor=self.actor, schema="Chat",
|
||||
body={"title": "cost", "member_ids": [self.actor["id"]]})["json"]
|
||||
self.rate, self.seconds, self.warmup = rate, seconds, warmup
|
||||
self.rows = []
|
||||
self.lock = threading.Lock()
|
||||
|
||||
def one(self, i, sched, measured):
|
||||
kind = "error" if i % 100 == 37 else "slow" if i % 100 == 73 else "read" if i % 100 < 15 else "write"
|
||||
start = time.monotonic()
|
||||
status, rid = 0, None
|
||||
try:
|
||||
if kind == "read":
|
||||
r = self.c.call("GET", "/api/v1/chats/%s/messages?limit=20" % self.chat["id"], [200, 500, 502, 503, 504],
|
||||
actor=self.actor)
|
||||
else:
|
||||
text = "cost %d%s" % (i, {"error": " fault-api-error", "slow": " fault-api-slow-300"}.get(kind, ""))
|
||||
r = self.c.call("POST", "/api/v1/chats/%s/messages" % self.chat["id"], [201, 500, 502, 503, 504],
|
||||
actor=self.actor, body={"text": text}, headers={"Idempotency-Key": uuid.uuid4().hex})
|
||||
status, rid = r["status"], r["headers"].get("X-Request-Id")
|
||||
except Failure:
|
||||
status = -1
|
||||
end = time.monotonic()
|
||||
with self.lock:
|
||||
self.rows.append({"kind": kind, "status": status, "rid": rid, "lat": end - sched, "measured": measured,
|
||||
"svc": end - start, "t": time.time()})
|
||||
|
||||
def uploads(self, stop):
|
||||
while not stop.is_set():
|
||||
try:
|
||||
self.c.call("POST", "/api/v1/chats/%s/attachments?filename=cost.png" % self.chat["id"], [202, 503],
|
||||
actor=self.actor, raw=make_png(), headers={"Content-Type": "image/png"})
|
||||
except Failure:
|
||||
pass
|
||||
stop.wait(2.0)
|
||||
|
||||
def run(self):
|
||||
stop = threading.Event()
|
||||
up = threading.Thread(target=self.uploads, args=(stop,), daemon=True)
|
||||
up.start()
|
||||
total = self.warmup + self.seconds
|
||||
n = int(total * self.rate)
|
||||
t0 = time.monotonic() + 0.5
|
||||
self.window = None
|
||||
with ThreadPoolExecutor(max_workers=64) as ex:
|
||||
for i in range(n):
|
||||
sched = t0 + i / self.rate
|
||||
delay = sched - time.monotonic()
|
||||
if delay > 0:
|
||||
time.sleep(delay)
|
||||
measured = i >= self.warmup * self.rate
|
||||
if measured and self.window is None:
|
||||
self.window = [time.time(), None]
|
||||
ex.submit(self.one, i, sched, measured)
|
||||
self.window[1] = time.time()
|
||||
stop.set()
|
||||
up.join(5)
|
||||
return self.window
|
||||
|
||||
|
||||
def pct(xs, p):
|
||||
xs = sorted(xs)
|
||||
return round(xs[min(len(xs) - 1, int(p * len(xs)))] * 1000, 1) if xs else None
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------------------------- telemetry
|
||||
COUNTERS = { # селекторы счётчиков; суммы — по экземплярам (см. counters())
|
||||
"col_spans_in": "otelcol_receiver_accepted_spans_total",
|
||||
"col_spans_out": "otelcol_exporter_sent_spans_total",
|
||||
"col_logs_in": "otelcol_receiver_accepted_log_records_total",
|
||||
"col_points_in": "otelcol_receiver_accepted_metric_points_total",
|
||||
"col_refused": "otelcol_receiver_refused_spans_total",
|
||||
"col_send_failed": '{__name__=~"otelcol_exporter_send_failed_spans_total|otelcol_exporter_enqueue_failed_spans_total"}',
|
||||
"tempo_bytes": "tempo_distributor_bytes_received_total",
|
||||
"tempo_spans": "tempo_distributor_spans_received_total",
|
||||
"loki_bytes": "loki_distributor_bytes_received_total",
|
||||
"loki_lines": "loki_distributor_lines_received_total",
|
||||
"prom_samples": "prometheus_tsdb_head_samples_appended_total",
|
||||
"sdk_started": 'otel_sdk_span_started_total{service_name="messenger-api"}',
|
||||
"sdk_sampled": 'otel_sdk_span_started_total{service_name="messenger-api",otel_span_sampling_result="RECORD_AND_SAMPLE"}',
|
||||
"sdk_lost": '{__name__=~"otel_sdk_processor_span_processed_total|otel_sdk_exporter_span_exported_total",error_type!=""}',
|
||||
"red_5xx": 'http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_class="5xx"}',
|
||||
"red_all": 'http_server_request_duration_seconds_count{service_name="messenger-api",http_route="/api/v1/chats/{chat_id}/messages"}',
|
||||
"spanmetrics_calls": 'traces_spanmetrics_calls_total{service="messenger-api",span_kind="SPAN_KIND_SERVER",span_name=~".*/messages"}',
|
||||
}
|
||||
|
||||
|
||||
def counters(at):
|
||||
"""Значения счётчиков в момент at ПО ЭКЗЕМПЛЯРАМ (instance / service_instance_id). Дельта считается только
|
||||
по экземплярам, живым в конце прогона: «устаревшие» серии пересозданных контейнеров (Prometheus держит их
|
||||
5 мин) не искажают сумму, а новый экземпляр без значения в начале считается от 0."""
|
||||
out = {}
|
||||
for k, q in COUNTERS.items():
|
||||
try:
|
||||
res = g.prom("sum by (instance, service_instance_id) (%s)" % q, at=at)
|
||||
out[k] = {(r["metric"].get("instance", ""), r["metric"].get("service_instance_id", "")): float(r["value"][1])
|
||||
for r in res}
|
||||
except ObsError:
|
||||
out[k] = None
|
||||
return out
|
||||
|
||||
|
||||
def delta(a, b):
|
||||
if a is None or b is None:
|
||||
return None
|
||||
return sum(v - a.get(key, 0.0) for key, v in b.items())
|
||||
|
||||
|
||||
def found_in_tempo(rows, kind):
|
||||
rids = [r["rid"] for r in rows if r["kind"] == kind and r["rid"]]
|
||||
found = 0
|
||||
for rid in rids:
|
||||
try:
|
||||
if g.search('{ span.messenger.request_id = "%s" }' % rid, since=1200, limit=1):
|
||||
found += 1
|
||||
except ObsError:
|
||||
pass
|
||||
return found, len(rids)
|
||||
|
||||
|
||||
def one_run(name, rate, window, warmup):
|
||||
log("run %s: apply config" % name)
|
||||
apply(name)
|
||||
time.sleep(10)
|
||||
load = OpenLoop(rate, window, warmup)
|
||||
st = Stats()
|
||||
st.start()
|
||||
a = counters(time.time()) if name != "off" else None # до нагрузки: дельты счётчиков покрывают весь прогон
|
||||
t_start = time.time()
|
||||
w0, w1 = load.run()
|
||||
st.stop.set()
|
||||
st.join(10)
|
||||
time.sleep(25) # экспорт SDK (10 с) + batch Collector + scrape (10 с)
|
||||
all_rows = load.rows
|
||||
rows = [r for r in all_rows if r["measured"]]
|
||||
normal = [r for r in rows if r["kind"] in ("write", "read") and r["status"] in (200, 201)]
|
||||
res = {"config": name, "window_s": round(w1 - w0, 1), "requests": len(rows),
|
||||
"ok_rps": round(len(normal) / (w1 - w0), 1),
|
||||
"unexpected_errors": sum(1 for r in rows if r["kind"] in ("write", "read", "slow") and r["status"] not in (200, 201)),
|
||||
"injected_errors": sum(1 for r in all_rows if r["kind"] == "error"),
|
||||
"lat_p50_ms": pct([r["lat"] for r in normal], 0.5), "lat_p95_ms": pct([r["lat"] for r in normal], 0.95),
|
||||
"lat_p99_ms": pct([r["lat"] for r in normal], 0.99), "resources": st.summary()}
|
||||
if name != "off":
|
||||
b = counters(time.time())
|
||||
d = {k: (round(delta(a[k], b[k]), 1) if delta(a[k], b[k]) is not None else None) for k in COUNTERS}
|
||||
span = w1 - t_start # прогрев + окно (дельты — за весь прогон)
|
||||
res["telemetry_delta"] = d
|
||||
res["per_second"] = {k: (round(v / span, 1) if v is not None else None) for k, v in d.items()
|
||||
if k in ("col_spans_in", "col_spans_out", "col_logs_in", "col_points_in", "tempo_bytes",
|
||||
"tempo_spans", "loki_bytes", "loki_lines", "prom_samples")}
|
||||
res["errors_found_in_tempo"] = found_in_tempo(all_rows, "error")
|
||||
res["slow_found_in_tempo"] = found_in_tempo(all_rows, "slow")
|
||||
natural_slow = [r for r in normal if r["svc"] > 0.25]
|
||||
res["natural_slow_requests"] = len(natural_slow)
|
||||
res["natural_slow_found_in_tempo"] = found_in_tempo([dict(r, kind="nat") for r in natural_slow[:30]], "nat")
|
||||
log("run %s: %s" % (name, json.dumps({k: v for k, v in res.items() if k in ("ok_rps", "lat_p50_ms", "lat_p95_ms", "lat_p99_ms",
|
||||
"errors_found_in_tempo", "slow_found_in_tempo")})))
|
||||
return res
|
||||
|
||||
|
||||
def aggregate(results):
|
||||
by = {}
|
||||
for r in results:
|
||||
by.setdefault(r["config"], []).append(r)
|
||||
table = {}
|
||||
for name, runs in by.items():
|
||||
med = lambda f: statistics.median([f(r) for r in runs if f(r) is not None]) if any(f(r) is not None for r in runs) else None # noqa: E731
|
||||
row = {"runs": len(runs), "ok_rps": med(lambda r: r["ok_rps"]), "p50_ms": med(lambda r: r["lat_p50_ms"]),
|
||||
"p95_ms": med(lambda r: r["lat_p95_ms"]), "p99_ms": med(lambda r: r["lat_p99_ms"]),
|
||||
"p95_ms_runs": [r["lat_p95_ms"] for r in runs],
|
||||
"unexpected_errors": sum(r["unexpected_errors"] for r in runs)}
|
||||
for grp in GROUPS:
|
||||
row["cpu_%s_pct" % grp] = med(lambda r, gg=grp: r["resources"].get(gg, {}).get("cpu_pct_avg"))
|
||||
row["mem_%s_mib" % grp] = med(lambda r, gg=grp: r["resources"].get(gg, {}).get("mem_mib_avg"))
|
||||
if name != "off":
|
||||
for k in ("col_spans_in", "col_spans_out", "tempo_bytes", "tempo_spans", "loki_bytes", "loki_lines",
|
||||
"col_points_in", "prom_samples"):
|
||||
row[k + "_per_s"] = med(lambda r, kk=k: r["per_second"].get(kk))
|
||||
for k in ("sdk_lost", "col_refused", "col_send_failed"):
|
||||
row[k] = sum((r["telemetry_delta"].get(k) or 0) for r in runs)
|
||||
row["sdk_sampled_share"] = med(lambda r: (r["telemetry_delta"]["sdk_sampled"] / r["telemetry_delta"]["sdk_started"])
|
||||
if r["telemetry_delta"].get("sdk_started") else None)
|
||||
row["red_5xx_vs_injected"] = [(r["telemetry_delta"].get("red_5xx"), r["injected_errors"]) for r in runs]
|
||||
row["spanmetrics_vs_sdk_calls"] = [(r["telemetry_delta"].get("spanmetrics_calls"), r["telemetry_delta"].get("red_all"))
|
||||
for r in runs]
|
||||
for k in ("errors_found_in_tempo", "slow_found_in_tempo", "natural_slow_found_in_tempo"):
|
||||
f = sum(r[k][0] for r in runs)
|
||||
n = sum(r[k][1] for r in runs)
|
||||
row[k] = "%d/%d" % (f, n)
|
||||
table[name] = row
|
||||
return table
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--reps", type=int, default=3)
|
||||
ap.add_argument("--rate", type=float, default=60)
|
||||
ap.add_argument("--window", type=int, default=60)
|
||||
ap.add_argument("--warmup", type=int, default=15)
|
||||
ap.add_argument("--configs", default="off,full,head10,tail")
|
||||
ap.add_argument("--out", default="evidence/track1")
|
||||
a = ap.parse_args()
|
||||
out = Path(a.out)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
names = a.configs.split(",")
|
||||
results = []
|
||||
try:
|
||||
for rep in range(a.reps):
|
||||
for name in names:
|
||||
r = one_run(name, a.rate, a.window, a.warmup)
|
||||
r["rep"] = rep + 1
|
||||
results.append(r)
|
||||
(out / "runs.json").write_text(json.dumps(results, ensure_ascii=False, indent=1))
|
||||
finally:
|
||||
log("restore config full")
|
||||
apply("full")
|
||||
table = aggregate(results)
|
||||
meta = {"rate_rps": a.rate, "window_s": a.window, "warmup_s": a.warmup, "reps": a.reps, "configs": CONFIGS,
|
||||
"host_cpus": os.cpu_count(), "date": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
|
||||
(out / "summary.json").write_text(json.dumps({"meta": meta, "table": table}, ensure_ascii=False, indent=1))
|
||||
print(json.dumps({"meta": meta, "table": table}, ensure_ascii=False, indent=1))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,83 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Демонстрация на защите: один upload → trace от HTTP до worker/S3/DB, логи API и worker того же trace,
|
||||
ссылка для Grafana Explore. С --retry имя файла содержит fault-transient-1 (FAULT_HOOKS=lab): первая попытка
|
||||
падает «временно», вторая проходит — обе в одном trace.
|
||||
|
||||
python3 research/trace_demo.py [--retry]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests"))
|
||||
from common import BASE_URL, Client, login, new_user, upload, wait_status # noqa: E402
|
||||
from obs import GRAFANA_URL, Grafana, wait_for # noqa: E402
|
||||
|
||||
|
||||
def explore_link(trace_id):
|
||||
panes = {"a": {"datasource": "tempo", "queries": [{"refId": "A", "datasource": {"type": "tempo", "uid": "tempo"},
|
||||
"queryType": "traceql", "query": trace_id}],
|
||||
"range": {"from": "now-6h", "to": "now"}}}
|
||||
return GRAFANA_URL + "/explore?schemaVersion=1&orgId=1&panes=" + urllib.parse.quote(json.dumps(panes, separators=(",", ":")))
|
||||
|
||||
|
||||
def tree(spans):
|
||||
kids = {}
|
||||
for s in spans:
|
||||
kids.setdefault(s["parent"], []).append(s)
|
||||
ids = {s["span_id"] for s in spans}
|
||||
lines = []
|
||||
|
||||
def walk(pid, d):
|
||||
for s in sorted(kids.get(pid, []), key=lambda x: x["start"]):
|
||||
extra = []
|
||||
for k in ("messenger.job.attempt", "messenger.job.outcome", "error.type", "http.response.status_code"):
|
||||
if k in s["attrs"]:
|
||||
extra.append("%s=%s" % (k.split(".")[-1], s["attrs"][k]))
|
||||
lines.append("%s%-40s %-17s %-8s %8.1f мс %s" % (" " * d, s["name"][:40], s["service"], s["kind"],
|
||||
(s["end"] - s["start"]) * 1000, " ".join(extra)))
|
||||
walk(s["span_id"], d + 1)
|
||||
for root in [p for p in kids if p not in ids]:
|
||||
walk(root, 0)
|
||||
return lines
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--retry", action="store_true")
|
||||
a = ap.parse_args()
|
||||
c, g = Client(BASE_URL), Grafana()
|
||||
u = new_user(c, "demo")
|
||||
login(c, u)
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=u, schema="Chat", body={"title": "demo", "member_ids": [u["id"]]})["json"]
|
||||
t0 = time.time()
|
||||
att, _ = upload(c, u, chat, filename="demo-fault-transient-1.png" if a.retry else "demo.png")
|
||||
print("upload: 202, attachment_id=%s, status=%s" % (att["id"], att["status"]))
|
||||
ready = wait_status(c, u, att["id"], "ready", timeout=90)
|
||||
print("ready через %.1f с, варианты: %s" % (time.time() - t0, [v["name"] for v in ready["variants"]]))
|
||||
|
||||
def find():
|
||||
tr = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=900)
|
||||
spans = g.trace(tr[0]["traceID"]) if tr else None
|
||||
return spans if spans and any(s["attrs"].get("messenger.job.outcome") == "ready" for s in spans) else None
|
||||
spans = wait_for(find, 60, what="trace")
|
||||
tid = spans[0]["trace_id"]
|
||||
print("\nTraceQL: { span.messenger.attachment.id = \"%s\" }\ntrace_id: %s (%d spans)\n" % (att["id"], tid, len(spans)))
|
||||
print("\n".join(tree(spans)))
|
||||
print("\nЛоги того же trace (Loki: {service_name=~\"messenger-.*\"} | trace_id=\"%s\"):" % tid)
|
||||
q = '{service_name=~"messenger-api|messenger-worker"} | trace_id="%s"' % tid
|
||||
# логи доходят батчами (SDK 1 с + Collector 2 с): ждём записи обоих сервисов, не дольше 20 с
|
||||
recs = wait_for(lambda: (lambda rs: rs if {r["service_name"] for r in rs} >= {"messenger-api", "messenger-worker"}
|
||||
else None)(g.loki(q, since=900)), 20, what="logs of both services")
|
||||
for r in recs:
|
||||
fields = {k: r[k] for k in ("event", "attempt", "outcome", "error_code", "route", "status") if k in r}
|
||||
print(" %s %-16s %-5s %s" % (time.strftime("%H:%M:%S", time.localtime(r["ts"])), r["service_name"],
|
||||
r.get("severity_text", ""), json.dumps(fields, ensure_ascii=False)))
|
||||
print("\nGrafana Explore (после входа admin):\n" + explore_link(tid))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Трек 2: рандомизированный хаос-прогон pipeline с проверкой инвариантов (повторяемо по --seed).
|
||||
|
||||
Гипотеза: при at-least-once доставке, повторах, переупорядочивании, падениях worker в любой точке
|
||||
(до/после побочного эффекта, после COMMIT до ack), зависаниях и выкатке новой версии pipeline
|
||||
(а) ни одна принятая (202) работа не теряется, (б) у каждой пары (вложение, версия) ровно один
|
||||
набор вариантов и ровно один COMMIT, (в) опубликованная версия не откатывается назад.
|
||||
|
||||
Во время прогона одновременно работают:
|
||||
uploader — N загрузок; каждой с вероятностью задаётся точка отказа (маркер в имени файла);
|
||||
duplicator — каждые ~2 с публикует 1–3 копии сообщения случайной работы (текущая/устаревшая попытка);
|
||||
killer — каждые --kill-every с SIGKILL случайного worker (docker kill) и старт через 2–5 с;
|
||||
versioner — для части готовых вложений ставит pipeline v2, затем снова шлёт им сообщения v1.
|
||||
После — ждёт завершения всех работ и запускает `jobs invariants --settled --verify-bytes`.
|
||||
|
||||
python3 research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import shlex
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from common import DC, Client, Failure, jobs_cli, login, make_png, new_user, sql, upload # noqa: E402
|
||||
|
||||
FAULTS = [("", 45), ("fault-crash-before-s3", 10), ("fault-crash-after-s3", 10), ("fault-crash-after-commit", 10),
|
||||
("fault-transient-1", 10), ("fault-transient-2", 5), ("fault-slow-3", 5), ("fault-hang-30", 5)]
|
||||
|
||||
|
||||
def worker_containers():
|
||||
out = subprocess.run(shlex.split(DC) + ["ps", "-a", "-q", "worker"], cwd=ROOT, capture_output=True, text=True)
|
||||
return out.stdout.split()
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
|
||||
ap.add_argument("--seed", type=int, default=1)
|
||||
ap.add_argument("--uploads", type=int, default=60)
|
||||
ap.add_argument("--kill-every", type=float, default=12.0)
|
||||
ap.add_argument("--settle-timeout", type=float, default=300)
|
||||
ap.add_argument("--output")
|
||||
a = ap.parse_args()
|
||||
rnd = random.Random(a.seed)
|
||||
c = Client(a.base_url, timeout=30)
|
||||
actor = new_user(c, "chaos")
|
||||
login(c, actor)
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
|
||||
body={"title": "chaos %d" % a.seed, "member_ids": [actor["id"]]})["json"]
|
||||
start = sql("SELECT to_char(clock_timestamp() AT TIME ZONE 'UTC', 'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"')")[0]
|
||||
accepted, lock, stop = [], threading.Lock(), threading.Event()
|
||||
counters = {"uploads_202": 0, "upload_errors": 0, "kills": 0, "duplicates_sent": 0, "stale_sent": 0,
|
||||
"reprocess_v2": 0, "v1_after_v2_sent": 0}
|
||||
planned = {}
|
||||
|
||||
def uploader():
|
||||
names, weights = zip(*FAULTS)
|
||||
for i in range(a.uploads):
|
||||
fault = rnd.choices(names, weights)[0]
|
||||
fname = "%s-chaos-%d.png" % (fault or "clean", i)
|
||||
try:
|
||||
att, _ = upload(c, actor, chat, make_png(40 + i % 50, 30 + i % 40), filename=fname)
|
||||
with lock:
|
||||
accepted.append(att["id"])
|
||||
planned[att["id"]] = fault or "none"
|
||||
counters["uploads_202"] += 1
|
||||
except Failure:
|
||||
counters["upload_errors"] += 1 # отказ ДО 202 — работа не принята, это не потеря
|
||||
time.sleep(rnd.uniform(0.2, 0.8))
|
||||
|
||||
def duplicator():
|
||||
while not stop.is_set():
|
||||
time.sleep(rnd.uniform(1.0, 3.0))
|
||||
with lock:
|
||||
if not accepted:
|
||||
continue
|
||||
aid = rnd.choice(accepted)
|
||||
try:
|
||||
jobs = jobs_cli("status", aid)["jobs"]
|
||||
job = rnd.choice(jobs)
|
||||
attempt = job["attempt"] if rnd.random() < 0.6 or job["attempt"] == 1 else rnd.randint(1, job["attempt"] - 1)
|
||||
n = rnd.randint(1, 3)
|
||||
jobs_cli("publish-raw", "--job", job["job_id"], "--attempt", attempt, "--count", n)
|
||||
counters["duplicates_sent" if attempt == job["attempt"] else "stale_sent"] += n
|
||||
except Failure:
|
||||
pass
|
||||
|
||||
def killer():
|
||||
while not stop.is_set():
|
||||
time.sleep(rnd.uniform(a.kill_every * 0.5, a.kill_every * 1.5))
|
||||
if stop.is_set():
|
||||
break
|
||||
ids = worker_containers()
|
||||
if not ids:
|
||||
continue
|
||||
victim = rnd.choice(ids)
|
||||
subprocess.run(["docker", "kill", "-s", "KILL", victim], capture_output=True)
|
||||
counters["kills"] += 1
|
||||
time.sleep(rnd.uniform(2, 5)) # «супервизор» поднимает процесс заново
|
||||
subprocess.run(["docker", "start", victim], capture_output=True)
|
||||
|
||||
def versioner():
|
||||
done = set()
|
||||
while not stop.is_set():
|
||||
time.sleep(rnd.uniform(3, 6))
|
||||
with lock:
|
||||
cands = [x for x in accepted if x not in done]
|
||||
if not cands:
|
||||
continue
|
||||
aid = rnd.choice(cands)
|
||||
try:
|
||||
st = jobs_cli("status", aid)
|
||||
if st["attachment"]["status"] != "ready":
|
||||
continue
|
||||
if jobs_cli("reprocess", "--attachment", aid, "--pipeline-version", 2)["result"] == "enqueued":
|
||||
counters["reprocess_v2"] += 1
|
||||
done.add(aid)
|
||||
time.sleep(rnd.uniform(0.5, 4))
|
||||
v1 = [j for j in jobs_cli("status", aid)["jobs"] if j["pipeline_version"] == 1][0]
|
||||
jobs_cli("publish-raw", "--job", v1["job_id"], "--count", 2)
|
||||
counters["v1_after_v2_sent"] += 2
|
||||
except Failure:
|
||||
pass
|
||||
|
||||
t0 = time.monotonic()
|
||||
threads = [threading.Thread(target=f, daemon=True) for f in (duplicator, killer, versioner)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
up = threading.Thread(target=uploader)
|
||||
up.start()
|
||||
up.join()
|
||||
time.sleep(10) # хаос продолжается ещё немного после последней загрузки
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join(timeout=60)
|
||||
for cid in worker_containers(): # все worker'ы снова в строю
|
||||
subprocess.run(["docker", "start", cid], capture_output=True)
|
||||
chaos_seconds = time.monotonic() - t0
|
||||
|
||||
deadline = time.monotonic() + a.settle_timeout
|
||||
inv = None
|
||||
while time.monotonic() < deadline:
|
||||
inv = jobs_cli("invariants", "--settled", "--since", start, expect=(0, 1))
|
||||
if inv["ok"]:
|
||||
break
|
||||
time.sleep(3)
|
||||
settle_seconds = time.monotonic() - t0 - chaos_seconds
|
||||
inv = jobs_cli("invariants", "--settled", "--verify-bytes", "--since", start, expect=(0, 1))
|
||||
|
||||
def q(query):
|
||||
return sql(query.replace("{S}", "'%s'" % start))
|
||||
events = dict(r.split("|") for r in q(
|
||||
"SELECT event, count(*) FROM job_events e JOIN attachments a ON a.id = e.attachment_id"
|
||||
" WHERE a.created_at >= {S} GROUP BY event ORDER BY event"))
|
||||
statuses = dict(r.split("|") for r in q(
|
||||
"SELECT j.pipeline_version || ':' || j.status, count(*) FROM attachment_jobs j JOIN attachments a"
|
||||
" ON a.id = j.attachment_id WHERE a.created_at >= {S} GROUP BY 1 ORDER BY 1"))
|
||||
latency = [float(x) for x in q(
|
||||
"SELECT extract(epoch FROM (c.created_at - e.created_at)) FROM job_events e JOIN job_events c"
|
||||
" ON c.job_id = e.job_id AND c.event = 'committed' JOIN attachments a ON a.id = e.attachment_id"
|
||||
" WHERE e.event = 'enqueued' AND a.created_at >= {S} AND e.pipeline_version = 1")]
|
||||
att_status = dict(r.split("|") for r in q(
|
||||
"SELECT status, count(*) FROM attachments WHERE created_at >= {S} GROUP BY status"))
|
||||
lost = [x for x in accepted if x not in set(q("SELECT id FROM attachments WHERE created_at >= {S}"
|
||||
" AND status IN ('ready', 'failed')"))]
|
||||
report = {
|
||||
"seed": a.seed, "uploads_requested": a.uploads, "counters": counters,
|
||||
"planned_faults": {k: list(planned.values()).count(k) for k in sorted(set(planned.values()))},
|
||||
"chaos_seconds": round(chaos_seconds, 1), "settle_seconds": round(settle_seconds, 1),
|
||||
"accepted_202": len(accepted), "accepted_not_terminal": len(lost), "attachment_status": att_status,
|
||||
"job_status": statuses, "events": events,
|
||||
"enqueue_to_commit_seconds_v1": {
|
||||
"p50": round(statistics.median(latency), 2) if latency else None,
|
||||
"p95": round(sorted(latency)[int(0.95 * (len(latency) - 1))], 2) if latency else None,
|
||||
"max": round(max(latency), 2) if latency else None},
|
||||
"invariants": inv,
|
||||
}
|
||||
text = json.dumps(report, ensure_ascii=False, indent=1)
|
||||
print(text)
|
||||
if a.output:
|
||||
Path(a.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(a.output).write_text(text + "\n", encoding="utf-8")
|
||||
sys.exit(0 if inv["ok"] and not lost else 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Эксперимент (уровень 4): пик RSS API при N одновременных загрузках ~10 МиБ.
|
||||
|
||||
Гипотеза: upload потоковый (кусок ≈64 КиБ → валидатор/SHA-256 → S3 PUT), поэтому пик RSS реплики
|
||||
растёт на O(N × буфер), а не на O(N × размер файла). Если бы тело буферизовалось целиком, 20 загрузок
|
||||
по 10 МиБ на одной реплике дали бы ≥ +200 МиБ (и упёрлись бы в лимит контейнера 256 МиБ).
|
||||
|
||||
Методика (повторяемая): для каждого сценария сбрасываем VmHWM обеих API-реплик
|
||||
(`python -m messenger stats --reset-peak` внутри контейнера), запускаем N параллельных загрузок
|
||||
несжимаемого PNG через LB, затем читаем VmHWM/VmRSS. Сценарии: fast (клиент шлёт без пауз) и slow
|
||||
(клиент шлёт кусками по 64 КиБ со скоростью ~2 МиБ/с — соединения долго держат слот).
|
||||
|
||||
python3 research/upload_memory.py --output evidence/upload-memory.json
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
from common import DC, Client, login, new_user # noqa: E402
|
||||
|
||||
|
||||
def big_png(target):
|
||||
side = int(((target - 4096) / 3) ** 0.5)
|
||||
rows = b"".join(b"\x00" + os.urandom(side * 3) for _ in range(side))
|
||||
|
||||
def chunk(t, d):
|
||||
return len(d).to_bytes(4, "big") + t + d + zlib.crc32(t + d).to_bytes(4, "big")
|
||||
ihdr = side.to_bytes(4, "big") + side.to_bytes(4, "big") + bytes([8, 2, 0, 0, 0])
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(rows, 1)) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def replicas():
|
||||
out = subprocess.run(shlex.split(DC + " ps -q api"), cwd=ROOT, capture_output=True, text=True, check=True)
|
||||
return [c for c in out.stdout.split() if c]
|
||||
|
||||
|
||||
def stats(cid, reset=False):
|
||||
cmd = ["docker", "exec", cid, "python", "-m", "messenger", "stats"] + (["--reset-peak"] if reset else [])
|
||||
return json.loads(subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=30).stdout)
|
||||
|
||||
|
||||
def send(base, token, chat_id, data, rate, results):
|
||||
u = urlsplit(base)
|
||||
head = ("POST /api/v1/chats/%s/attachments?filename=%s HTTP/1.1\r\nHost: %s\r\nAuthorization: Bearer %s\r\n"
|
||||
"Content-Type: image/png\r\nContent-Length: %d\r\nConnection: close\r\n\r\n"
|
||||
% (chat_id, quote("mem.png"), u.netloc, token, len(data))).encode()
|
||||
t = time.monotonic()
|
||||
try:
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=120)
|
||||
s.sendall(head)
|
||||
step = 65536
|
||||
for i in range(0, len(data), step):
|
||||
s.sendall(data[i:i + step])
|
||||
if rate:
|
||||
time.sleep(step / rate)
|
||||
resp = b""
|
||||
while b"\r\n" not in resp:
|
||||
part = s.recv(4096)
|
||||
if not part:
|
||||
break
|
||||
resp += part
|
||||
s.close()
|
||||
status = int(resp.split(b" ", 2)[1]) if resp else 0
|
||||
except OSError as exc:
|
||||
status = type(exc).__name__
|
||||
results.append({"status": status, "seconds": round(time.monotonic() - t, 3)})
|
||||
|
||||
|
||||
def s3_memory_sampler(stop, samples):
|
||||
"""Пик анонимной памяти контейнера s3 (cgroup memory.stat) — опрос каждые 0.2 с во время сценария."""
|
||||
cid = subprocess.run(shlex.split(DC + " ps -q s3"), cwd=ROOT, capture_output=True, text=True).stdout.strip()
|
||||
while not stop.is_set() and cid:
|
||||
# cgroup v2 (Docker Desktop) или v1 (старые Linux-хосты)
|
||||
# Анонимная память (без page cache): cgroup v2 memory.stat «anon» (Docker Desktop) или v1 «total_rss».
|
||||
r = subprocess.run(["docker", "exec", cid, "sh", "-c", "cat /sys/fs/cgroup/memory.stat 2>/dev/null"
|
||||
" || cat /sys/fs/cgroup/memory/memory.stat"], capture_output=True, text=True)
|
||||
for line in r.stdout.splitlines():
|
||||
name, _, value = line.partition(" ")
|
||||
if name in ("anon", "total_rss") and value.strip().isdigit():
|
||||
samples.append(int(value))
|
||||
break
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def scenario(base, actor, chat, data, n, rate):
|
||||
ids = replicas()
|
||||
stop, s3mem = threading.Event(), []
|
||||
sampler = threading.Thread(target=s3_memory_sampler, args=(stop, s3mem))
|
||||
sampler.start()
|
||||
before = {cid[:12]: stats(cid, reset=True)["memory"] for cid in ids}
|
||||
results, threads = [], []
|
||||
for _ in range(n):
|
||||
threads.append(threading.Thread(target=send, args=(base, actor["token"], chat["id"], data, rate, results)))
|
||||
t = time.monotonic()
|
||||
for th in threads:
|
||||
th.start()
|
||||
for th in threads:
|
||||
th.join()
|
||||
wall = time.monotonic() - t
|
||||
stop.set(); sampler.join()
|
||||
after = {cid[:12]: stats(cid)["memory"] for cid in ids}
|
||||
per = {k: {"rss_before_kib": before[k]["rss_kib"], "peak_kib": after[k]["peak_rss_kib"],
|
||||
"peak_delta_mib": round((after[k]["peak_rss_kib"] - before[k]["rss_kib"]) / 1024, 1)} for k in after}
|
||||
ok = sum(1 for r in results if r["status"] == 202) # lab5: upload → 202
|
||||
return {"concurrency": n, "client_rate_bytes_per_s": rate or "unlimited", "file_bytes": len(data),
|
||||
"ok_202": ok, "statuses": sorted({str(r["status"]) for r in results}), "wall_seconds": round(wall, 2),
|
||||
"upload_seconds_max": max(r["seconds"] for r in results), "replicas": per,
|
||||
"max_peak_delta_mib": max(v["peak_delta_mib"] for v in per.values()),
|
||||
"s3_anon_peak_mib": round(max(s3mem) / 2**20, 1) if s3mem else None,
|
||||
"if_buffered_mib_per_replica": round(n / max(1, len(per)) * len(data) / 2**20, 1)}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
|
||||
ap.add_argument("--size", type=int, default=10 * 2**20 - 64 * 1024)
|
||||
ap.add_argument("--levels", default="1,10,20,32")
|
||||
ap.add_argument("--slow-levels", default="10,20")
|
||||
ap.add_argument("--slow-rate", type=int, default=2 * 2**20)
|
||||
ap.add_argument("--output")
|
||||
a = ap.parse_args()
|
||||
c = Client(a.base_url, timeout=30)
|
||||
actor = new_user(c, "mem"); login(c, actor)
|
||||
chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
|
||||
body={"title": "memory", "member_ids": [actor["id"]]})["json"]
|
||||
data = big_png(a.size)
|
||||
runs = []
|
||||
for n in [int(x) for x in a.levels.split(",") if x]:
|
||||
runs.append(scenario(a.base_url, actor, chat, data, n, 0))
|
||||
print(json.dumps(runs[-1], ensure_ascii=False))
|
||||
for n in [int(x) for x in a.slow_levels.split(",") if x]:
|
||||
runs.append(scenario(a.base_url, actor, chat, data, n, a.slow_rate))
|
||||
print(json.dumps(runs[-1], ensure_ascii=False))
|
||||
report = {"hypothesis": "peak RSS grows by O(N*chunk), not O(N*file)", "file_mib": round(len(data) / 2**20, 2),
|
||||
"limits": {"UPLOAD_CONCURRENCY_per_replica": 16, "api_memory_limit": "256M", "s3_memory_limit": "1G",
|
||||
"s3_concurrentUploadLimitMB": 96}, "runs": runs}
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(report, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,140 @@
|
||||
# Windows PowerShell 5.1+ equivalent of scripts/collect-evidence.sh (lab6).
|
||||
# Starts the Compose stand (LB + API replicas + workers + one-shot bootstrap + PostgreSQL + Redis + SeaweedFS S3 +
|
||||
# NATS JetStream + OTel Collector + Prometheus + Loki + Tempo + Grafana), runs every check and writes outputs to
|
||||
# evidence\ (no tokens/passwords/keys). Stops/restarts containers (worker, DB, Collector, Tempo, Loki, API
|
||||
# replicas); volumes are never removed. Takes ~90 minutes (-SkipRegression: ~60, -SkipResearch: -35 more).
|
||||
# powershell -NoProfile -ExecutionPolicy Bypass -File scripts\collect-evidence.ps1 [-SkipRegression] [-SkipResearch]
|
||||
param([switch]$SkipRegression, [switch]$SkipResearch)
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$env:PYTHONUTF8 = '1'
|
||||
$env:PYTHONIOENCODING = 'utf-8'
|
||||
# IPv4 explicitly: on Windows 'localhost' resolves to ::1 first; the LB listens on 127.0.0.1 only.
|
||||
$env:NO_PROXY = '127.0.0.1,localhost'
|
||||
$B = 'http://127.0.0.1:8080'
|
||||
$env:BASE_URL = $B
|
||||
$env:TTL_BASE_URL = 'http://127.0.0.1:8081'
|
||||
$ev = Join-Path $root 'evidence'
|
||||
New-Item -ItemType Directory -Force -Path $ev, (Join-Path $ev 'track1'), (Join-Path $ev 'track2'), (Join-Path $ev 'incidents') | Out-Null
|
||||
|
||||
# Full path of the Python APPLICATION: a bare 'py' would resolve to a PowerShell function first.
|
||||
$pyApp = Get-Command py -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
$pythonApp = Get-Command python -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
|
||||
if ($pyApp) { $script:PyExe = $pyApp.Source; $script:PyPre = @('-3') }
|
||||
elseif ($pythonApp) { $script:PyExe = $pythonApp.Source; $script:PyPre = @() }
|
||||
else { throw 'Python 3.9+ not found (install from python.org, enable "Add to PATH")' }
|
||||
function Invoke-Python { & $script:PyExe @script:PyPre @args }
|
||||
function Dc { & docker compose --env-file .env @args }
|
||||
$hookStop = if ($IsLinux -or $IsMacOS) { 'scripts/stop-one.sh' } else { 'scripts\stop-one.cmd' }
|
||||
$hookRestart = if ($IsLinux -or $IsMacOS) { 'scripts/restart.sh' } else { 'scripts\restart.cmd' }
|
||||
$startReplicas = Join-Path $PSScriptRoot 'start-replicas.ps1'
|
||||
|
||||
function Get-Stamp {
|
||||
$commit = 'n/a'
|
||||
if (Get-Command git -ErrorAction SilentlyContinue) {
|
||||
$c = (& git rev-parse --short HEAD 2>$null)
|
||||
if ($LASTEXITCODE -eq 0 -and $c) { $commit = $c }
|
||||
}
|
||||
'# ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' commit=' + $commit + ' host=' + [Environment]::OSVersion.VersionString + ' cpus=' + [Environment]::ProcessorCount
|
||||
}
|
||||
function Invoke-Step([string]$name, [string]$title, [scriptblock]$block) {
|
||||
Write-Host ('>>> ' + $name) -ForegroundColor Cyan
|
||||
$global:LASTEXITCODE = 0
|
||||
$lines = @(& $block 2>&1 | ForEach-Object { "$_" })
|
||||
$code = $global:LASTEXITCODE
|
||||
Set-Content -Path (Join-Path $ev ($name + '.txt')) -Encoding UTF8 -Value (@((Get-Stamp), ('$ ' + $title)) + $lines + @('exit=' + $code))
|
||||
$lines | Select-Object -Last 2 | ForEach-Object { Write-Host (' ' + $_) }
|
||||
if ($code -ne 0) { Write-Host (' exit=' + $code + ' (see evidence\' + $name + '.txt)') -ForegroundColor Yellow }
|
||||
}
|
||||
|
||||
& docker version --format '{{.Server.Version}}' *> $null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Docker is not running: start Docker Desktop first' }
|
||||
& (Join-Path $PSScriptRoot 'init-secrets.ps1')
|
||||
Set-Location $root
|
||||
Write-Host '>>> docker compose up (build, wait for healthchecks)' -ForegroundColor Cyan
|
||||
Dc --profile ttl up -d --build --wait
|
||||
if ($LASTEXITCODE -ne 0) { Dc logs --tail=80; throw 'docker compose up failed' }
|
||||
$mount = (Join-Path $root 'student-tests') + ':/app/student-tests:ro'
|
||||
|
||||
Invoke-Step 'stack' 'docker version; compose images; ps' { & docker version --format 'docker {{.Server.Version}}'; Dc version; Dc --profile ttl images; Dc --profile ttl ps -a }
|
||||
Invoke-Step 'migrations' 'schema_migrations; docker compose logs migrate' {
|
||||
Dc exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version'
|
||||
Dc logs --no-log-prefix migrate
|
||||
}
|
||||
Invoke-Step 'broker-bootstrap' 'docker compose logs broker-init' { Dc logs --no-log-prefix broker-init }
|
||||
Invoke-Step 's3-bootstrap' 'docker compose logs s3-init' { Dc logs --no-log-prefix s3-init }
|
||||
Invoke-Step 'no-local-files' 'docker inspect api/worker: ReadonlyRootfs, tmpfs, mounts' {
|
||||
foreach ($cid in @(Dc ps -q api worker)) {
|
||||
& docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' $cid
|
||||
}
|
||||
}
|
||||
Invoke-Step 'published-ports' 'docker compose ps: published ports' { Dc ps --format '{{.Service}} {{.Ports}}' | Sort-Object -Unique }
|
||||
Invoke-Step 'make-check' 'python scripts/check_contract.py' { Invoke-Python scripts/check_contract.py }
|
||||
Invoke-Step 'smoke' "python tests/smoke.py --base-url $B" { Invoke-Python tests/smoke.py --base-url $B }
|
||||
# ---------------------------------------------------------------- lab6: observability
|
||||
Invoke-Step 'collector-config-validate' 'otelcol-contrib validate --config=collector.yaml' {
|
||||
Dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml
|
||||
}
|
||||
Invoke-Step 'test-observability' 'python student-tests/test_observability.py' { Invoke-Python student-tests/test_observability.py }
|
||||
Invoke-Step 'observability' 'python research/obs_snapshot.py' { Invoke-Python research/obs_snapshot.py }
|
||||
Set-Content -Path (Join-Path $ev 'restart-hook.txt') -Encoding UTF8 -Value @()
|
||||
Invoke-Step 'test-telemetry-persistence' 'python student-tests/test_telemetry_persistence.py # restarts everything' {
|
||||
Invoke-Python student-tests/test_telemetry_persistence.py
|
||||
}
|
||||
foreach ($sc in 'worker-stop', 'db-slow', 'handler-slow', 'db-down', 'telemetry-down', 'collector-down') {
|
||||
Invoke-Step ('incident-' + $sc) ('python research/incidents.py ' + $sc) {
|
||||
Invoke-Python research/incidents.py $sc --out evidence/incidents
|
||||
}
|
||||
}
|
||||
# ---------------------------------------------------------------- public failover / persistence checks
|
||||
Set-Content -Path (Join-Path $ev 'failover-hook.txt') -Encoding UTF8 -Value @()
|
||||
foreach ($i in 1, 2) {
|
||||
Invoke-Step ('failover-' + $i) ('python tests/resilience.py --mode failover --action-script ' + $hookStop) {
|
||||
Invoke-Python tests/resilience.py --mode failover --action-script $hookStop --base-url $B
|
||||
}
|
||||
Invoke-Step ('restore-' + $i) 'scripts\start-replicas.ps1' { & $startReplicas }
|
||||
}
|
||||
Set-Content -Path (Join-Path $ev 'restart-hook.txt') -Encoding UTF8 -Value @()
|
||||
Invoke-Step 'persistence' ('python tests/resilience.py --mode persistence --action-script ' + $hookRestart) {
|
||||
Invoke-Python tests/resilience.py --mode persistence --action-script $hookRestart --base-url $B
|
||||
}
|
||||
# ---------------------------------------------------------------- lab2-lab5 regression with telemetry enabled
|
||||
if (-not $SkipRegression) {
|
||||
Invoke-Step 'test-pipeline' 'python student-tests/test_pipeline.py' { Invoke-Python student-tests/test_pipeline.py }
|
||||
Invoke-Step 'test-imgproc' 'docker compose run worker: python student-tests/test_imgproc.py' {
|
||||
Dc run --rm --no-deps -T -v $mount --entrypoint python worker student-tests/test_imgproc.py
|
||||
}
|
||||
Invoke-Step 'defense-demo' 'python student-tests/defense_demo.py' { Invoke-Python student-tests/defense_demo.py }
|
||||
Invoke-Step 'test-attachments' 'python student-tests/test_attachments.py' { Invoke-Python student-tests/test_attachments.py }
|
||||
Invoke-Step 'test-api' 'python student-tests/test_api.py' { Invoke-Python student-tests/test_api.py }
|
||||
Invoke-Step 'test-idempotency' 'python student-tests/test_idempotency.py' { Invoke-Python student-tests/test_idempotency.py }
|
||||
Invoke-Step 'test-expiry' 'python student-tests/test_expiry.py # api-ttl via LB :8081' { Invoke-Python student-tests/test_expiry.py }
|
||||
Invoke-Step 'test-cache-race' 'docker compose run api: python student-tests/test_cache_race.py' {
|
||||
Dc run --rm --no-deps -T -v $mount --entrypoint python api student-tests/test_cache_race.py
|
||||
}
|
||||
Invoke-Step 'test-jobs-failures' 'python student-tests/test_jobs_failures.py' { Invoke-Python student-tests/test_jobs_failures.py }
|
||||
Invoke-Step 'test-storage-failures' 'python student-tests/test_storage_failures.py' { Invoke-Python student-tests/test_storage_failures.py }
|
||||
Invoke-Step 'test-failures' 'python student-tests/test_failures.py' { Invoke-Python student-tests/test_failures.py }
|
||||
Invoke-Step 'test-track2-lab5' 'python student-tests/test_pipeline_idempotency.py' { Invoke-Python student-tests/test_pipeline_idempotency.py }
|
||||
Invoke-Step 'track2-chaos-seed1' 'python research/track2_chaos.py --seed 1' {
|
||||
Invoke-Python research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json
|
||||
}
|
||||
}
|
||||
# ---------------------------------------------------------------- track 1
|
||||
if (-not $SkipResearch) {
|
||||
Invoke-Step 'track1-telemetry-cost' 'python research/telemetry_cost.py --reps 3 --rate 60 --window 60' {
|
||||
Invoke-Python research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1
|
||||
}
|
||||
}
|
||||
Invoke-Step 'jobs-failed' 'docker compose exec api python -m messenger jobs failed --limit 20' { Dc exec -T api python -m messenger jobs failed --limit 20 }
|
||||
Invoke-Step 'jobs-invariants' 'docker compose exec api python -m messenger jobs invariants --settled --verify-bytes' {
|
||||
Dc exec -T api python -m messenger jobs invariants --settled --verify-bytes
|
||||
}
|
||||
Invoke-Step 'migrations-rerun' 'docker compose run --rm --no-deps migrate' { Dc run --rm --no-deps migrate }
|
||||
Invoke-Step 'load' 'python tests/load.py --duration 30 --concurrency 4' {
|
||||
Invoke-Python tests/load.py --base-url $B --duration 30 --concurrency 4 --output evidence/load.json
|
||||
}
|
||||
Invoke-Step 'test-observability-final' 'python student-tests/test_observability.py' { Invoke-Python student-tests/test_observability.py }
|
||||
Invoke-Step 'observability-final' 'python research/obs_snapshot.py' { Invoke-Python research/obs_snapshot.py }
|
||||
Write-Host 'Done: evidence collected in evidence\' -ForegroundColor Green
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/bin/sh
|
||||
# Полный прогон доказательств lab6 на Compose-стенде; вывод — evidence/ (без токенов, паролей и ключей).
|
||||
# Останавливает/перезапускает контейнеры стенда (worker, БД, Collector, Tempo, Loki, реплики API …).
|
||||
# Volumes не удаляются. Длительность ≈ 90 мин; SKIP_REGRESSION=1 (без тестов lab2–lab5) — ≈ 60 мин,
|
||||
# SKIP_RESEARCH=1 (без трека 1) — ещё −35 мин.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
. scripts/lib.sh
|
||||
PY=${PYTHON:-python3}
|
||||
B=${BASE_URL:-http://127.0.0.1:8080}
|
||||
export BASE_URL=$B TTL_BASE_URL=${TTL_BASE_URL:-http://127.0.0.1:8081} NO_PROXY=127.0.0.1,localhost no_proxy=127.0.0.1,localhost
|
||||
mkdir -p evidence evidence/incidents evidence/track1 evidence/track2
|
||||
stamp() { echo "# $(now) commit=$(git rev-parse --short HEAD 2>/dev/null || echo n/a) host=$(uname -srm) cpus=$(getconf _NPROCESSORS_ONLN)"; }
|
||||
run() { name=$1; shift; { stamp; echo "\$ $*"; "$@" 2>&1; echo "exit=$?"; } > "evidence/$name.txt" || true; tail -2 "evidence/$name.txt"; }
|
||||
IN_WORKER="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python worker"
|
||||
IN_API="dc run --rm --no-deps -T -v $PWD/student-tests:/app/student-tests:ro --entrypoint python api"
|
||||
|
||||
./scripts/init-secrets.sh
|
||||
dc --profile ttl up -d --build --wait
|
||||
{ stamp; docker version --format 'docker {{.Server.Version}}'; dc version; dc --profile ttl images; dc --profile ttl ps -a; state; } > evidence/stack.txt 2>&1
|
||||
run migrations sh -c "docker compose --env-file .env exec -T postgres psql -U messenger -d messenger -c 'SELECT version, left(checksum,12) AS checksum, applied_at FROM schema_migrations ORDER BY version'; docker compose --env-file .env logs --no-log-prefix migrate"
|
||||
run broker-bootstrap dc logs --no-log-prefix broker-init
|
||||
run s3-bootstrap dc logs --no-log-prefix s3-init
|
||||
run no-local-files sh -c "for c in \$(docker compose --env-file .env ps -q api worker); do docker inspect -f '{{.Name}} ReadonlyRootfs={{.HostConfig.ReadonlyRootfs}} Tmpfs={{json .HostConfig.Tmpfs}} Mounts={{range .Mounts}}{{.Type}}:{{.Destination}} {{end}}' \$c; done"
|
||||
run published-ports sh -c "docker compose --env-file .env ps --format '{{.Service}} {{.Ports}}' | sort -u"
|
||||
run make-check make check
|
||||
run smoke $PY tests/smoke.py --base-url "$B"
|
||||
# ---------------------------------------------------------------- lab6: наблюдаемость
|
||||
run collector-config-validate dc run --rm --no-deps otel-collector validate --config=/etc/otelcol-contrib/collector.yaml
|
||||
run test-observability $PY student-tests/test_observability.py
|
||||
run observability $PY research/obs_snapshot.py
|
||||
: > evidence/restart-hook.txt
|
||||
run test-telemetry-persistence $PY student-tests/test_telemetry_persistence.py
|
||||
for s in worker-stop db-slow handler-slow db-down telemetry-down collector-down; do
|
||||
run incident-$s $PY research/incidents.py $s --out evidence/incidents
|
||||
done
|
||||
# ---------------------------------------------------------------- публичные проверки отказа и сохранности
|
||||
: > evidence/failover-hook.txt
|
||||
run failover-1 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B"
|
||||
run restore-1 ./scripts/start-replicas.sh
|
||||
run failover-2 $PY tests/resilience.py --mode failover --action-script scripts/stop-one.sh --base-url "$B"
|
||||
run restore-2 ./scripts/start-replicas.sh
|
||||
: > evidence/restart-hook.txt
|
||||
run persistence $PY tests/resilience.py --mode persistence --action-script scripts/restart.sh --base-url "$B"
|
||||
# ---------------------------------------------------------------- регрессия lab2–lab5 (make test при включённой telemetry)
|
||||
if [ "${SKIP_REGRESSION:-0}" != 1 ]; then
|
||||
run test-pipeline $PY student-tests/test_pipeline.py
|
||||
run test-imgproc $IN_WORKER student-tests/test_imgproc.py
|
||||
run defense-demo $PY student-tests/defense_demo.py
|
||||
run test-attachments $PY student-tests/test_attachments.py
|
||||
run test-api $PY student-tests/test_api.py
|
||||
run test-idempotency $PY student-tests/test_idempotency.py
|
||||
run test-expiry $PY student-tests/test_expiry.py
|
||||
run test-cache-race $IN_API student-tests/test_cache_race.py
|
||||
run test-jobs-failures $PY student-tests/test_jobs_failures.py
|
||||
run test-storage-failures $PY student-tests/test_storage_failures.py
|
||||
run test-failures $PY student-tests/test_failures.py
|
||||
run test-track2-lab5 $PY student-tests/test_pipeline_idempotency.py
|
||||
run track2-chaos-seed1 $PY research/track2_chaos.py --seed 1 --uploads 60 --output evidence/track2/chaos-seed1.json
|
||||
fi
|
||||
# ---------------------------------------------------------------- трек 1
|
||||
if [ "${SKIP_RESEARCH:-0}" != 1 ]; then
|
||||
run track1-telemetry-cost $PY research/telemetry_cost.py --reps 3 --rate 60 --window 60 --out evidence/track1
|
||||
fi
|
||||
run jobs-failed dc exec -T api python -m messenger jobs failed --limit 20
|
||||
run jobs-invariants dc exec -T api python -m messenger jobs invariants --settled --verify-bytes
|
||||
run migrations-rerun dc run --rm --no-deps migrate
|
||||
run load $PY tests/load.py --base-url "$B" --duration 30 --concurrency 4 --output evidence/load.json
|
||||
run test-observability-final $PY student-tests/test_observability.py
|
||||
run observability-final $PY research/obs_snapshot.py
|
||||
echo "evidence collected in evidence/"
|
||||
@@ -0,0 +1,88 @@
|
||||
# Windows PowerShell 5.1+ version of scripts/init-secrets.sh.
|
||||
# Creates local synthetic secrets in secrets\ and .env (both git-ignored).
|
||||
# Idempotent: existing files are NOT overwritten. Values are never printed.
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $root 'secrets'), (Join-Path $root 'backups') | Out-Null
|
||||
$ascii = New-Object System.Text.ASCIIEncoding
|
||||
|
||||
function New-Hex {
|
||||
$bytes = New-Object byte[] 24
|
||||
$rng = [System.Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
$rng.GetBytes($bytes)
|
||||
($bytes | ForEach-Object { $_.ToString('x2') }) -join ''
|
||||
}
|
||||
function Set-SecretFile([string]$name, [string]$value) {
|
||||
$path = Join-Path (Join-Path $root 'secrets') $name
|
||||
if (-not (Test-Path $path)) {
|
||||
# No BOM, no trailing CR/LF: the value is read verbatim inside Linux containers.
|
||||
[System.IO.File]::WriteAllText($path, $value, $ascii)
|
||||
}
|
||||
}
|
||||
function Get-SecretFile([string]$name) {
|
||||
([System.IO.File]::ReadAllText((Join-Path (Join-Path $root 'secrets') $name))).Trim()
|
||||
}
|
||||
|
||||
Set-SecretFile 'postgres_password' (New-Hex)
|
||||
Set-SecretFile 'redis_password' (New-Hex)
|
||||
$pg = Get-SecretFile 'postgres_password'
|
||||
$rd = Get-SecretFile 'redis_password'
|
||||
Set-SecretFile 'database_url' ("postgresql://messenger:" + $pg + "@postgres:5432/messenger")
|
||||
Set-SecretFile 'cache_url' ("redis://:" + $rd + "@redis:6379/0")
|
||||
# S3 (SeaweedFS): two identities. admin - only for bucket bootstrap (s3-init service);
|
||||
# messenger-api - Read/Write/List ONLY on the attachments bucket (cannot create/delete buckets).
|
||||
function New-KeyId {
|
||||
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
|
||||
$bytes = New-Object byte[] 20
|
||||
[System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($bytes)
|
||||
($bytes | ForEach-Object { $chars[$_ % $chars.Length] }) -join ''
|
||||
}
|
||||
Set-SecretFile 's3_admin_access_key_id' (New-KeyId)
|
||||
Set-SecretFile 's3_admin_secret_access_key' (New-Hex)
|
||||
Set-SecretFile 's3_access_key_id' (New-KeyId)
|
||||
Set-SecretFile 's3_secret_access_key' (New-Hex)
|
||||
$bucket = 'messenger-attachments'
|
||||
$envPath = Join-Path $root '.env'
|
||||
if (Test-Path $envPath) {
|
||||
$line = Select-String -Path $envPath -Pattern '^S3_BUCKET=(.+)$' | Select-Object -First 1
|
||||
if ($line) { $bucket = $line.Matches[0].Groups[1].Value.Trim() }
|
||||
}
|
||||
$cfgPath = Join-Path (Join-Path $root 'secrets') 's3_config.json'
|
||||
if (-not (Test-Path $cfgPath)) {
|
||||
$cfg = [ordered]@{ identities = @(
|
||||
[ordered]@{ name = 'admin'; credentials = @([ordered]@{ accessKey = (Get-SecretFile 's3_admin_access_key_id'); secretKey = (Get-SecretFile 's3_admin_secret_access_key') });
|
||||
actions = @('Admin', 'Read', 'List', 'Tagging', 'Write') },
|
||||
[ordered]@{ name = 'messenger-api'; credentials = @([ordered]@{ accessKey = (Get-SecretFile 's3_access_key_id'); secretKey = (Get-SecretFile 's3_secret_access_key') });
|
||||
actions = @(('Read:' + $bucket), ('Write:' + $bucket), ('List:' + $bucket)) }
|
||||
) }
|
||||
[System.IO.File]::WriteAllText($cfgPath, ($cfg | ConvertTo-Json -Depth 6), $ascii)
|
||||
}
|
||||
# NATS JetStream: service password (API, worker, bootstrap) and the server config that holds it.
|
||||
Set-SecretFile 'nats_password' (New-Hex)
|
||||
$np = Get-SecretFile 'nats_password'
|
||||
Set-SecretFile 'broker_url' ('nats://messenger:' + $np + '@nats:4222')
|
||||
$natsConf = @(
|
||||
'# nats-server (lab5): JetStream on disk with fsync on every write, password auth,',
|
||||
'# monitoring (healthcheck) only on 127.0.0.1 inside the container.',
|
||||
'server_name: nats-lab6',
|
||||
'listen: "0.0.0.0:4222"',
|
||||
'http: "127.0.0.1:8222"',
|
||||
'max_payload: 65536',
|
||||
'jetstream {',
|
||||
' store_dir: "/data"',
|
||||
' max_memory_store: 64MB',
|
||||
' max_file_store: 2GB',
|
||||
' sync_interval: always',
|
||||
'}',
|
||||
'authorization {',
|
||||
(' users = [ { user: "messenger", password: "' + $np + '" } ]'),
|
||||
'}'
|
||||
) -join "`n"
|
||||
Set-SecretFile 'nats.conf' ($natsConf + "`n")
|
||||
# lab6: Grafana admin password (UI on 127.0.0.1:3000; tests read it locally and never print it).
|
||||
Set-SecretFile 'grafana_admin_password' (New-Hex)
|
||||
if (-not (Test-Path (Join-Path $root '.env'))) {
|
||||
Copy-Item (Join-Path $root '.env.example') (Join-Path $root '.env')
|
||||
}
|
||||
Write-Output 'secrets\ and .env are ready (values not shown).'
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
# Создаёт локальные синтетические secrets для стенда (каталог secrets/ в .gitignore).
|
||||
# Идемпотентно: существующие файлы НЕ перезаписываются (иначе пароль разойдётся с уже
|
||||
# инициализированным volume PostgreSQL). Значения не печатаются.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
mkdir -p secrets backups
|
||||
chmod 700 secrets
|
||||
gen() { python3 -c 'import secrets; print(secrets.token_hex(24))'; }
|
||||
if [ ! -f secrets/postgres_password ]; then gen > secrets/postgres_password; fi
|
||||
if [ ! -f secrets/redis_password ]; then gen > secrets/redis_password; fi
|
||||
PG=$(cat secrets/postgres_password)
|
||||
RD=$(cat secrets/redis_password)
|
||||
[ -f secrets/database_url ] || printf 'postgresql://messenger:%s@postgres:5432/messenger\n' "$PG" > secrets/database_url
|
||||
[ -f secrets/cache_url ] || printf 'redis://:%s@redis:6379/0\n' "$RD" > secrets/cache_url
|
||||
# S3 (SeaweedFS): две identity. admin — только для bootstrap bucket (сервис s3-init);
|
||||
# api — права Read/Write/List ТОЛЬКО на bucket вложений (не может создавать/удалять бакеты).
|
||||
keyid() { python3 -c 'import secrets,string; print("".join(secrets.choice(string.ascii_uppercase+string.digits) for _ in range(20)))'; }
|
||||
[ -f secrets/s3_admin_access_key_id ] || keyid > secrets/s3_admin_access_key_id
|
||||
[ -f secrets/s3_admin_secret_access_key ] || gen > secrets/s3_admin_secret_access_key
|
||||
[ -f secrets/s3_access_key_id ] || keyid > secrets/s3_access_key_id
|
||||
[ -f secrets/s3_secret_access_key ] || gen > secrets/s3_secret_access_key
|
||||
BUCKET=$(grep -E '^S3_BUCKET=' .env 2>/dev/null | cut -d= -f2); BUCKET=${BUCKET:-messenger-attachments}
|
||||
[ -f secrets/s3_config.json ] || python3 - "$BUCKET" > secrets/s3_config.json <<'PY'
|
||||
import json, sys
|
||||
b = sys.argv[1]
|
||||
r = lambda n: open("secrets/" + n).read().strip()
|
||||
print(json.dumps({"identities": [
|
||||
{"name": "admin", "credentials": [{"accessKey": r("s3_admin_access_key_id"), "secretKey": r("s3_admin_secret_access_key")}],
|
||||
"actions": ["Admin", "Read", "List", "Tagging", "Write"]},
|
||||
{"name": "messenger-api", "credentials": [{"accessKey": r("s3_access_key_id"), "secretKey": r("s3_secret_access_key")}],
|
||||
"actions": ["Read:" + b, "Write:" + b, "List:" + b]}]}, indent=1))
|
||||
PY
|
||||
# NATS JetStream: пароль сервисов (API, worker, bootstrap) и конфигурация сервера с ним.
|
||||
[ -f secrets/nats_password ] || gen > secrets/nats_password
|
||||
NP=$(cat secrets/nats_password)
|
||||
[ -f secrets/broker_url ] || printf 'nats://messenger:%s@nats:4222\n' "$NP" > secrets/broker_url
|
||||
[ -f secrets/nats.conf ] || cat > secrets/nats.conf <<NATS
|
||||
# nats-server (lab5+): JetStream на диске с fsync каждой записи, доступ по паролю,
|
||||
# мониторинг (healthcheck) — только 127.0.0.1 внутри контейнера.
|
||||
server_name: nats-lab6
|
||||
listen: "0.0.0.0:4222"
|
||||
http: "127.0.0.1:8222"
|
||||
max_payload: 65536
|
||||
jetstream {
|
||||
store_dir: "/data"
|
||||
max_memory_store: 64MB
|
||||
max_file_store: 2GB
|
||||
sync_interval: always
|
||||
}
|
||||
authorization {
|
||||
users = [ { user: "messenger", password: "$NP" } ]
|
||||
}
|
||||
NATS
|
||||
# lab6: пароль admin Grafana (вход в UI на 127.0.0.1:3000; тесты читают его локально, не печатая).
|
||||
[ -f secrets/grafana_admin_password ] || gen > secrets/grafana_admin_password
|
||||
# Файлы монтируются в контейнеры как /run/secrets/*; процесс API работает под uid 10001,
|
||||
# поэтому файл должен быть читаем внутри контейнера. Каталог secrets/ закрыт (700) на хосте.
|
||||
chmod 644 secrets/*
|
||||
[ -f .env ] || cp .env.example .env
|
||||
mkdir -p backups
|
||||
echo "secrets/ and .env are ready (values not shown)."
|
||||
@@ -0,0 +1,26 @@
|
||||
# Общие функции хуков (POSIX sh). Подключается: . "$(dirname "$0")/lib.sh"
|
||||
cd "$(dirname "$0")/.."
|
||||
ENV_FILE=${ENV_FILE:-.env}
|
||||
dc() { docker compose --env-file "$ENV_FILE" "$@"; }
|
||||
now() { date -u +%FT%TZ; }
|
||||
# Состояние всех контейнеров проекта: сервис, имя, статус, StartedAt, PID, alias реплики API.
|
||||
state() {
|
||||
for cid in $(dc ps -a -q); do
|
||||
docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' "$cid" |
|
||||
sed 's# /# #'
|
||||
done | sort
|
||||
}
|
||||
# Контейнер API-реплики по её X-Instance-Id (alias пишется репликой в /tmp/instance-id).
|
||||
container_of() {
|
||||
for cid in $(dc ps -q api); do
|
||||
if [ "$(docker exec "$cid" cat /tmp/instance-id 2>/dev/null)" = "$1" ]; then echo "$cid"; return 0; fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
# Ждать healthy у всех контейнеров сервиса (не дольше 60 с).
|
||||
wait_healthy() {
|
||||
for cid in $(dc ps -q "$1"); do
|
||||
i=0
|
||||
until [ "$(docker inspect -f '{{.State.Health.Status}}' "$cid")" = healthy ] || [ $i -ge 120 ]; do i=$((i + 1)); sleep 0.5; done
|
||||
done
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
# Defense scenario step 3: restart NATS (volume natsdata kept) and all API replicas; workers are NOT started.
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
|
||||
function Wait-Healthy([string]$svc) {
|
||||
foreach ($cid in (& docker compose --env-file $envFile ps -q $svc)) {
|
||||
for ($i = 0; $i -lt 120; $i++) {
|
||||
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
}
|
||||
}
|
||||
& docker compose --env-file $envFile restart nats 2>$null | Out-Null
|
||||
Wait-Healthy 'nats'
|
||||
& docker compose --env-file $envFile restart api 2>$null | Out-Null
|
||||
Wait-Healthy 'api'
|
||||
& docker compose --env-file $envFile ps -a nats api --format '{{.Name}} {{.State}} {{.Health}}'
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
# Сценарий защиты, шаг 3: перезапустить брокер (NATS, volume natsdata сохраняется) и все реплики API.
|
||||
# Worker НЕ запускает (если остановлены — остаются остановленными). Volumes не удаляются.
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
{ echo "== $(now) before"; state; } | grep -E '^(==|nats|api) '
|
||||
dc restart nats >/dev/null 2>&1
|
||||
wait_healthy nats
|
||||
dc restart api >/dev/null 2>&1
|
||||
wait_healthy api
|
||||
{ echo "== $(now) after"; state; } | grep -E '^(==|nats|api) '
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
rem Windows wrapper: tests\resilience.py starts the hook directly; .cmd runs without a shell.
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0restart.ps1"
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -0,0 +1,41 @@
|
||||
# Windows PowerShell version of scripts/restart.sh (persistence hook): restart LB, ALL API replicas, workers,
|
||||
# PostgreSQL, Redis, S3, NATS JetStream and observability (Collector, Prometheus, Loki, Tempo, Grafana) keeping volumes. State before/after -> evidence\restart-hook.txt
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
Set-Location $root
|
||||
$envFile = if ($env:ENV_FILE) { $env:ENV_FILE } else { '.env' }
|
||||
$log = Join-Path $root 'evidence\restart-hook.txt'
|
||||
function Dc { & docker compose --env-file $envFile @args 2>$null | Out-Null; if ($LASTEXITCODE -ne 0) { throw ('docker compose ' + ($args -join ' ') + ' failed') } }
|
||||
function Get-State {
|
||||
foreach ($cid in (& docker compose --env-file $envFile ps -a -q)) {
|
||||
& docker inspect -f '{{index .Config.Labels "com.docker.compose.service"}} {{.Name}} status={{.State.Status}} started={{.State.StartedAt}} pid={{.State.Pid}}' $cid
|
||||
}
|
||||
& docker volume ls --filter label=com.docker.compose.project=mtusi-lab6 --format 'volume {{.Name}}'
|
||||
}
|
||||
try {
|
||||
Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' before restart')
|
||||
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
|
||||
$ttl = @(& docker compose --env-file $envFile ps -q api-ttl 2>$null).Count -gt 0
|
||||
$workers = @(& docker compose --env-file $envFile ps -q worker 2>$null).Count -gt 0
|
||||
Dc stop lb api worker
|
||||
if ($ttl) { Dc stop api-ttl }
|
||||
Dc restart postgres redis s3 nats otel-collector prometheus loki tempo grafana
|
||||
# Wait for healthy storages (S3: gateway + master leader + writes; NATS: JetStream) before API/worker/LB.
|
||||
foreach ($svc in 'postgres', 'redis', 's3', 'nats', 'prometheus') {
|
||||
$cid = (& docker compose --env-file $envFile ps -q $svc | Select-Object -First 1)
|
||||
for ($i = 0; $i -lt 120; $i++) {
|
||||
if ((& docker inspect -f '{{.State.Health.Status}}' $cid) -eq 'healthy') { break }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
}
|
||||
Dc start api
|
||||
if ($ttl) { Dc start api-ttl }
|
||||
if ($workers) { Dc start worker }
|
||||
Dc start lb
|
||||
Add-Content -Path $log -Encoding UTF8 -Value ('== ' + (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ') + ' after restart')
|
||||
Add-Content -Path $log -Encoding UTF8 -Value (Get-State)
|
||||
exit 0
|
||||
} catch {
|
||||
[Console]::Error.WriteLine($_.Exception.Message)
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
# Persistence hook: перезапускает LB, ВСЕ API-реплики, worker и все хранилища (PostgreSQL, Redis, S3,
|
||||
# NATS JetStream) и всю наблюдаемость (Collector, Prometheus, Loki, Tempo, Grafana), сохраняя volumes. Никаких down -v / FLUSH / повторного seed. Миграции повторно не нужны.
|
||||
# Состояние контейнеров до/после (StartedAt, PID) — в evidence/restart-hook.txt.
|
||||
set -eu
|
||||
. "$(dirname "$0")/lib.sh"
|
||||
LOG=${RESTART_EVIDENCE:-evidence/restart-hook.txt}
|
||||
vols() { docker volume ls --filter label=com.docker.compose.project=mtusi-lab6 --format 'volume {{.Name}}'; }
|
||||
{ echo "== $(now) before restart"; state; vols; } >> "$LOG"
|
||||
running_ttl=$(dc ps -q api-ttl 2>/dev/null || true)
|
||||
running_worker=$(dc ps -q worker 2>/dev/null || true)
|
||||
dc stop lb api worker >/dev/null 2>&1
|
||||
[ -z "$running_ttl" ] || dc stop api-ttl >/dev/null 2>&1
|
||||
dc restart postgres redis s3 nats otel-collector prometheus loki tempo grafana >/dev/null 2>&1
|
||||
# Дождаться healthy хранилищ (S3: шлюз + лидер master + запись; NATS: JetStream), затем API/worker/LB.
|
||||
for svc in postgres redis s3 nats prometheus; do wait_healthy "$svc"; done
|
||||
dc start api >/dev/null 2>&1
|
||||
[ -z "$running_ttl" ] || dc start api-ttl >/dev/null 2>&1
|
||||
[ -z "$running_worker" ] || dc start worker >/dev/null 2>&1
|
||||
dc start lb >/dev/null 2>&1
|
||||
{ echo "== $(now) after restart"; state; vols; } >> "$LOG"
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user