From a271ddd15670f94fde2a710601ebecf13b20cfd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=BD=D0=B4=D1=80=D0=B5=D0=B9=20=D0=94=D0=B0=D0=B4?= =?UTF-8?q?=D0=B0=D0=B9=D0=BA=D0=B8=D0=BD?= Date: Mon, 23 Nov 2026 14:54:48 +0300 Subject: [PATCH] Lab 6: track - 1 --- .gitattributes | 6 + Dockerfile | 11 + REPORT.md | 119 +++- app/main.py | 512 ++++++++++++++++++ app/migrate.py | 18 + app/telemetry.py | 196 +++++++ app/worker.py | 322 +++++++++++ compose.yaml | 229 ++++++++ evidence/lab6-incidents.json | 38 ++ evidence/lab6-signals.json | 42 ++ evidence/track1-observability-cost.json | 117 ++++ infra/bootstrap-rustfs.sh | 17 + .../dashboards/messenger-observability.json | 181 +++++++ .../grafana/provisioning/alerting/alerts.yaml | 137 +++++ .../provisioning/dashboards/dashboards.yaml | 11 + .../provisioning/datasources/datasources.yaml | 41 ++ infra/haproxy.cfg | 28 + infra/loki/loki.yaml | 30 + infra/otel/RUNBOOKS.md | 24 + infra/otel/collector-tail-sampling.yaml | 100 ++++ infra/otel/collector.yaml | 83 +++ infra/prometheus/alerts.yml | 29 + infra/prometheus/prometheus.yml | 14 + infra/rustfs-policy.json | 1 + infra/tempo/tempo.yaml | 27 + migrations/001_initial.sql | 36 ++ migrations/002_idempotency.sql | 6 + migrations/003_trace_context.sql | 3 + requirements.lock | 31 ++ scripts/bootstrap.py | 53 ++ scripts/replay_failed.py | 18 + scripts/restart.bat | 1 + scripts/restart.sh | 6 + scripts/stop-one.bat | 1 + scripts/stop-one.sh | 16 + student-tests/grafana_helper.py | 54 ++ student-tests/incident_suite.py | 208 +++++++ student-tests/track1_cost_of_observability.py | 250 +++++++++ student-tests/verify_lab6_signals.py | 140 +++++ 39 files changed, 3141 insertions(+), 15 deletions(-) create mode 100644 .gitattributes create mode 100644 Dockerfile create mode 100644 app/main.py create mode 100644 app/migrate.py create mode 100644 app/telemetry.py create mode 100644 app/worker.py create mode 100644 compose.yaml create mode 100644 evidence/lab6-incidents.json create mode 100644 evidence/lab6-signals.json create mode 100644 evidence/track1-observability-cost.json create mode 100644 infra/bootstrap-rustfs.sh create mode 100644 infra/grafana/dashboards/messenger-observability.json create mode 100644 infra/grafana/provisioning/alerting/alerts.yaml create mode 100644 infra/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 infra/grafana/provisioning/datasources/datasources.yaml create mode 100644 infra/haproxy.cfg create mode 100644 infra/loki/loki.yaml create mode 100644 infra/otel/RUNBOOKS.md create mode 100644 infra/otel/collector-tail-sampling.yaml create mode 100644 infra/otel/collector.yaml create mode 100644 infra/prometheus/alerts.yml create mode 100644 infra/prometheus/prometheus.yml create mode 100644 infra/rustfs-policy.json create mode 100644 infra/tempo/tempo.yaml create mode 100644 migrations/001_initial.sql create mode 100644 migrations/002_idempotency.sql create mode 100644 migrations/003_trace_context.sql create mode 100644 requirements.lock create mode 100644 scripts/bootstrap.py create mode 100644 scripts/replay_failed.py create mode 100644 scripts/restart.bat create mode 100644 scripts/restart.sh create mode 100644 scripts/stop-one.bat create mode 100644 scripts/stop-one.sh create mode 100644 student-tests/grafana_helper.py create mode 100644 student-tests/incident_suite.py create mode 100644 student-tests/track1_cost_of_observability.py create mode 100644 student-tests/verify_lab6_signals.py diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..58787eb --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +* text=auto eol=lf +*.sh text eol=lf +*.py text eol=lf +*.yaml text eol=lf +*.yml text eol=lf +*.json text eol=lf diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..25fd186 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,11 @@ +FROM python:3.12.12-slim +WORKDIR /srv +COPY requirements.lock . +RUN pip install --no-cache-dir --timeout 120 --retries 5 -r requirements.lock +COPY app app +COPY migrations migrations +COPY scripts scripts +RUN useradd --uid 10001 --create-home api +USER api +EXPOSE 8080 +CMD ["gunicorn", "--bind", "0.0.0.0:8080", "--workers", "1", "--threads", "2", "--timeout", "35", "--graceful-timeout", "5", "--keep-alive", "1", "app.main:app"] diff --git a/REPORT.md b/REPORT.md index b97ae42..c40f5a2 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,126 @@ # Отчёт — лабораторная 6 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- Автор, группа: Дадайкин Андрей, БВТ2302 +- Целевая оценка: 5; выбранный трек 5: Трек 1 — Цена наблюдаемости +- Commit/PR: локальная работа подготовлена к публикации в форк `dadaykin/mtusi2026lab6` +- Использованные источники, библиотеки и помощь ИИ: контракты курса МТУСИ; Flask, psycopg, Argon2id, boto3, Pillow; OpenTelemetry Python SDK 1.39.1 (`opentelemetry-api`, `opentelemetry-sdk`, `opentelemetry-exporter-otlp-proto-http`); OTel Collector Contrib 0.142.0, Prometheus v3.5.0, Loki 3.5.7, Tempo 2.9.0, Grafana 12.2.1; ИИ (помощник разработки) использован для настройки конфигурации OTLP/Collector, написания скриптов проверки инцидентов/нагрузки и адаптации запуска под Windows 11. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +Требования: Docker Engine / Docker Desktop с Compose v2, Python 3.9+ (для хостовых проверок; на Windows 11 использовать Git Bash и `export PYTHONUTF8=1`). Сборка API/worker выполняется из `Dockerfile` на базе `python:3.12.12-slim` с зафиксированными зависимостями `requirements.lock`. + + export PYTHONUTF8=1 + python scripts/bootstrap.py + python scripts/check_contract.py + docker compose config --quiet + docker compose up -d --build --scale api=2 --wait --wait-timeout 240 + +Обязательные действия оператора перед первым тестом: дождаться ~15 с готовности ingester Tempo (проверяется скриптами автоматически). Grafana доступна по адресу `http://localhost:3000` (логин `admin`, пароль генерируется в `secrets/grafana_admin_password` и не печатается). + +Запуск всех проверок: + + python tests/smoke.py --base-url http://localhost:8081 + python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8081 + python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8081 + docker compose up -d --scale api=2 + python student-tests/verify_lab6_signals.py + python student-tests/incident_suite.py + python student-tests/track1_cost_of_observability.py + +Безопасная остановка с сохранением всех данных и истории телеметрии (volumes сохраняются): + + docker compose down + +Намеренное полное удаление учебных данных и томов: + + docker compose down -v ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +Перенесена вся реализация lab5 (2 реплики Flask/Gunicorn API за HAProxy, PostgreSQL 16 с outbox, Redis кэш, Redis Streams AOF брокер, отдельный worker и приватный S3 RustFS с 3 вариантами изображений). Добавлена миграция `migrations/003_trace_context.sql` для хранения W3C `traceparent` и `tracestate` в таблице `attachment_jobs`. + +Поток наблюдаемости: + + API (x2) / Worker ──OTLP/HTTP (4318)──▶ OTel Collector Contrib (0.142.0) + ├── metrics (pull :8889/:8888) ──▶ Prometheus (v3.5.0) + ├── logs (OTLP/HTTP :3100/otlp) ─▶ Loki (3.5.7) + └── traces (OTLP/gRPC :4317) ────▶ Tempo (2.9.0) + ▲ + Grafana (12.2.1)┘ (Provisioning + Alerts) + +### Топология сервисов (`compose.yaml`) + +| Роль | Service name | Образ / версия | Health / Readiness | Volume | Сеть и порт | Передача credentials | +| --- | --- | --- | --- | --- | --- | --- | +| Load Balancer | `lb` | `haproxy:3.0.11-alpine` | `GET /health/ready` на API | — | `127.0.0.1:8081->8080` | — | +| API (x2) | `api` | `mtusi-lab6-api:local` (`python:3.12.12-slim`) | `GET /health/ready` | — | внутр. `8080/tcp` | `/run/secrets/*` | +| Worker | `worker` | `mtusi-lab6-api:local` | отдельный процесс | — | внутр. (outbox/S3/OTLP) | `/run/secrets/*` | +| PostgreSQL | `postgres` | `postgres:16.10-alpine` | `pg_isready` | `pgdata` | внутр. `5432/tcp` | `POSTGRES_PASSWORD_FILE` | +| Cache | `redis` | `redis:7.4.6-alpine` | `redis-cli ping` | — | внутр. `6379/tcp` | внутр. сеть | +| Broker | `broker` | `redis:7.4.6-alpine` (AOF) | `redis-cli ping` | `brokerdata` | внутр. `6379/tcp` | внутр. сеть | +| S3 Storage | `rustfs` | `rustfs/rustfs:1.0.3-glibc` | `curl -f :9000/health` | `s3data` | внутр. `9000/tcp` | `/run/secrets/rustfs_*` | +| OTel Collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.142.0` | `health_check :13133` | — | внутр. `4317,4318,8888,8889` | — | +| Metrics Store | `prometheus` | `prom/prometheus:v3.5.0` | TSDB scrape 5s | `promdata` | внутр. `9090/tcp` | — | +| Logs Store | `loki` | `grafana/loki:3.5.7` | `:3100` | `lokidata` | внутр. `3100/tcp` | — | +| Traces Store | `tempo` | `grafana/tempo:2.9.0` | `:3200/ready` | `tempodata` | внутр. `3200,4317` | — | +| Grafana | `grafana` | `grafana/grafana:12.2.1` | `/api/health` | `grafanadata` | `127.0.0.1:3000->3000` | `GF_SECURITY_ADMIN_PASSWORD__FILE` | + +### Критические зависимости и изоляция телеметрии + +Для `/health/ready` критичны **PostgreSQL** и **Redis-брокер**: без них синхронный путь записи сообщений и постановки заданий невозможен. Отказ **OTel Collector, Prometheus, Loki, Tempo или Grafana не останавливает API и worker**: в `app/telemetry.py` выставлены ограниченные очереди (`max_queue_size=1024`) и короткий таймаут экспорта (`2.0с`) в фоновых потоках, а в Collector работает `memory_limiter` (`180 MiB`, контейнерный лимит `256 MiB`) и `sending_queue` (`queue_size: 200`, `max_elapsed_time: 15s`). + +### Соответствие сигналов `contracts/observability.md` + +- **Метрики API (Prometheus):** `http_server_requests_total` (counter: `http_request_method`, `http_route` в шаблонном виде `/api/v1/chats/{chat_id}/messages`, `http_response_status_class`), `http_server_request_duration_seconds_bucket` (histogram в секундах). +- **Формула Error Ratio и агрегация p95/p99:** error ratio считается строго по бизнес-маршрутам: `5xx / все запросы (исключая /health/*)`, клиентские `401/404/409` в ошибки сервиса не включаются. Процентили `p50/p95/p99` вычисляются через `histogram_quantile(..., sum by (le) (rate(..._bucket[1m])))` поверх корзин всех реплик, без усреднения готовых квантилей. +- **Метрики Worker и очереди:** `worker_jobs_total`, `worker_job_duration_seconds_bucket`, `attachment_time_to_ready_seconds_bucket`, `worker_queue_depth`, `worker_oldest_job_age_seconds`, `db_pool_connections` (`used`, `idle`, `waiting`, `max`), `worker_threads` (`busy`, `capacity`), `process_memory_rss_bytes`, `process_cpu_time_seconds_total`. +- **Защита кардинальности и секретов:** `user_id`, `chat_id`, `message_id`, `attachment_id`, `request_id`, `filename` и `text` исключены из labels метрик. Логи проходят фильтрацию `REDACTED_KEYS` в SDK и процессор `attributes/redact` в Collector (`authorization` и `db.statement` удаляются). +- **Сквозная трассировка W3C:** HTTP `POST /attachments` внедряет `traceparent/tracestate` в строку `attachment_jobs`; релей `outbox.publish` (`SpanKind.PRODUCER`) пробрасывает контекст в JSON задания в Redis Streams; `worker.process` (`SpanKind.CONSUMER`) восстанавливает единый `trace_id` до завершения записи вариантов в S3 и коммита `ready` в PostgreSQL. +- **Назначение хранилищ:** Prometheus хранит числовые временные ряды и оценивает правила алертов; Loki хранит структурированные JSON-логи (связаны с Tempo через `derivedFields` по `trace_id`); Tempo хранит распределённые спаны и деревья вызовов (связан с Loki через `tracesToLogsV2`). Provisioning и alert rules лежат в `infra/grafana/provisioning/` и `infra/prometheus/alerts.yml`. + +Соответствие `.env.example`: `OTEL_EXPORTER_OTLP_ENDPOINT`, `OTEL_EXPORTER_OTLP_PROTOCOL`, `OTEL_RESOURCE_ATTRIBUTES`, `OTEL_SDK_DISABLED`, `OTEL_TRACES_SAMPLER`, `OTEL_TRACES_SAMPLER_ARG`, `OTEL_COLLECTOR_CONFIG`, `APP_PORT`, `GRAFANA_PORT`, `*_FILE` проброшены в `compose.yaml`. ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. +| Офлайн-структура и JSON/YAML | `python scripts/check_contract.py` и `docker compose config --quiet` | PASS: синтаксис Python, все JSON (включая dashboard) и Compose валидны | вывод CLI | +| Публичный smoke с телеметрией | `python tests/smoke.py --base-url http://localhost:8081` | PASS: сценарий lab1–6 (users, sessions, messages, async 202 -> ready, thumbnail 256x160) при активном OTel | вывод CLI | +| Сохранность и отказ API | `resilience.py --mode persistence` и `--mode failover` | PASS: persistence сохранил данные/сессию; failover восстановился за 2.655 с (99 записей, 4 ошибки перехода) | `scripts/restart.bat`, `scripts/stop-one.bat` | +| Сигналы, отсутствие утечек и E2E trace | `python student-tests/verify_lab6_signals.py` | PASS: все 10 метрик без запрещённых labels; E2E trace `d566508b20e3f80b76a75854dbc2fb3e` через `messenger-api` и `messenger-worker`; 5 связанных логов в Loki; 0 утечек body/token/password | `evidence/lab6-signals.json` | +| Инцидент 1: остановка worker + alert | `python student-tests/incident_suite.py` (Incident 1) | PASS: `GrowingQueueLag` перешёл в `firing`, после запуска worker вложенная задача стала `ready`, алерт вернулся в `inactive` (resolved) | `evidence/lab6-incidents.json` | +| Инцидент 2: медленная БД vs медленный HTTP | `python student-tests/incident_suite.py` (Incident 2) | PASS: `HighApiErrorRatio` сработал на `503` по `lock_timeout`; по трассам Tempo чётко разделены сбой БД (`df2b128057e2b86261978feadf07e3ee`: 2014.8 мс, 99.8% в `db.query`) и тормоз handler (`ecc5ac60ed34681b532c0572b874d4bf`: 674.4 мс, 2.2% в `db.query`) | `evidence/lab6-incidents.json`, `infra/otel/RUNBOOKS.md` | +| Инцидент 3: отказ telemetry-бэкендов | `python student-tests/incident_suite.py` (Incident 3) | PASS: при остановленных `tempo` и `loki` прошли 15 сообщений и обработка вложения; RAM Collector осталась 64.58 -> 65.49 MiB (лимит 256 MiB); учтено `send_failed` (24 спана, 20 логов) | `evidence/lab6-incidents.json` | +| Трек 1: Цена наблюдаемости | `python student-tests/track1_cost_of_observability.py` | PASS: сравнены 4 профиля нагрузки; измерены RPS, p50/p95/p99, CPU/RAM, ingest и процент захвата 10 ошибок и 5 медленных запросов | `evidence/track1-observability-cost.json` | ## Эксперименты и отказы -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. +### Трек 1 — Цена наблюдаемости + +**Гипотеза.** Полная телеметрия (`always_on`) заметно снижает RPS и повышает tail-latency из-за создания и сериализации спанов/логов на каждом запросе. Случайный `head sampling` 10% уменьшает накладные расходы, но теряет ~90% редких ошибок и медленных запросов, так как решение принимается до исхода запроса. Сбалансированный `tail sampling` на стороне Collector (сохранять 100% `ERROR`, 100% запросов `>100 мс` и 10% быстрых) снизит объём записи в Tempo на ~90% при сохранении 100% видимости аномалий. + +**Методика.** Локальный стенд Docker Desktop (Windows 11 / WSL2, 16 vCPU, лимит API по `0.75 CPU / 512 MiB`, Collector `0.50 CPU / 256 MiB`). Для каждого из 4 профилей: прогрев 10 запросов, затем закрытая нагрузка `POST /messages` в 6 потоков длительностью 20 секунд, замер CPU/RAM каждые 5 секунд через `docker stats`, затем инъекция 5 медленных запросов (`200 мс`) и 10 ошибок `503` (блокировка таблицы `messages` в PostgreSQL сверх `lock_timeout=2000ms`), ожидание сброса буферов и проверка захваченных трасс в Tempo. + +| Профиль | Успешных запросов / RPS | Latency p50 / p95 / p99 (мс) | CPU API (1/2) / Collector | RAM Collector | Спаны принято / в Tempo (drop %) | Захвачено 5xx / медленных >150мс | +| --- | ---: | ---: | --- | ---: | ---: | --- | +| `telemetry_off` | 5581 / 276.97 | 15.92 / 44.14 / 88.49 | 69.0% / 70.3% / 0.19% | 37.42 MiB | 0 / 0 (0%) | 0/10 / 0/5 (выкл.) | +| `always_on_100pct` | 3822 / 190.04 | 24.74 / 79.22 / 115.41 | 72.0% / 68.7% / 3.53% | 66.44 MiB | 31 274 / 31 282 (0%) | **9/10** / **5/5** | +| `head_sampling_10pct` | 4624 / 229.43 | 19.70 / 57.33 / 89.03 | 70.3% / 73.5% / 2.24% | 52.97 MiB | 3 608 / 3 608 (0%) | **0/10** / **0/5** | +| `tail_sampling_balanced` | 4160 / 206.60 | 26.06 / 60.45 / 97.63 | 68.6% / 68.4% / 1.91% | 66.11 MiB | 34 046 / 3 390 (**90.04%**) | **7/10** / **5/5** | + +**Анализ и ограничения.** Включение полной телеметрии снизило пропускную способность на 31.4% (276.97 → 190.04 RPS) и подняло p95 с 44.14 до 79.22 мс. `head_sampling_10pct` вернул большую часть RPS (229.43), но на контрольной инъекции пропустил **все 10 ошибок и все 5 медленных запросов**, что делает его непригодным для расследования редких сбоев. `tail_sampling_balanced` отбросил 90.04% быстрых трасс на уровне Collector (`34 046 → 3 390` спанов в Tempo), улучшив p95 на 23.7% относительно `always_on` за счёт разгрузки экспортера и Tempo, и сохранил 5/5 медленных запросов и 7/10 ошибок. Ограничения эксперимента: закрытая (closed-loop) нагрузка длительностью 20 с на одном хосте; 3 ошибочные трассы в burst-пачке на `tail_sampling` (и 1 на `always_on`) не успели отразиться в поисковом индексе Tempo в пределах короткого 10-секундного окна ожидания из-за `trace_idle_period=5s` и буферизации в WAL. + +### Отказы и сохранность | Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | | --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Остановка `worker` при загрузке 202 | Рост `worker_oldest_job_age_seconds`, срабатывание `GrowingQueueLag`, затем resolved | Алерт перешёл в `firing`, после запуска worker задача стала `ready`, алерт `inactive` | Автоматическое после запуска worker; потери 0 | +| Задержка/блокировка БД vs тормоз handler | Различить причину по `db.query` в Tempo, `HighApiErrorRatio` на 503 | БД-трейс: 2014.8 мс (2012.0 мс в `db.query`); handler-трейс: 674.4 мс (14.8 мс в `db.query`); алерт `firing` | 0 потерянных подтверждённых сообщений | +| Остановка `tempo` и `loki` | API/worker продолжают работу, RAM Collector ограничена, потери учтены | 15 сообщений и 1 вложение прошли; RAM Collector 64.58 → 65.49 MiB; `send_failed`: 24 спана, 20 логов | 0 сбоев бизнес-API; потеря телеметрии во время простоя учтена счётчиками | +| Перезапуск стека / падение реплики API | Сессия и данные сохраняются, балансировщик переключается | `persistence` PASS; `failover` 99 записей, 4 ошибки перехода, восстановление 2.655 с | 0 потерь подтверждённых данных | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- Стенд работает на одном узле Docker Desktop под Windows 11; все хранилища (PostgreSQL, Redis, RustFS, Prometheus, Loki, Tempo) единичные и не обеспечивают защиту от физического отказа хоста. +- Tail sampling требует маршрутизации всех спанов одной трассы в один экземпляр Collector; при масштабировании Collector до нескольких реплик потребуется балансировщик по `trace_id` (loadbalancing exporter). +- В качестве сбалансированной конфигурации по умолчанию рекомендуется использовать `infra/otel/collector-tail-sampling.yaml`, так как он сохраняет диагностику ошибок и хвоста задержек при 10-кратной экономии диска Tempo. \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..9c04e9c --- /dev/null +++ b/app/main.py @@ -0,0 +1,512 @@ +import base64 +import datetime as dt +import hashlib +import io +import json +import logging +import os +import re +import secrets +import time +from urllib.parse import quote +import uuid + +from argon2 import PasswordHasher +from argon2.exceptions import VerificationError +import boto3 +from botocore.config import Config +from flask import Flask, g, request +from opentelemetry import context as otel_context, trace +from opentelemetry.metrics import Observation +from opentelemetry.trace import SpanKind, Status, StatusCode +from PIL import Image, UnidentifiedImageError +import psycopg +from psycopg.errors import UniqueViolation +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool +import redis +from werkzeug.exceptions import HTTPException + +from app.migrate import setting +from app.telemetry import Telemetry + +app = Flask(__name__) +MAX_UPLOAD = int(os.getenv('MAX_UPLOAD_BYTES', '10485760')) +MAX_PIXELS = int(os.getenv('MAX_IMAGE_PIXELS', '40000000')) +MAX_QUEUED = int(os.getenv('MAX_QUEUED_JOBS', '500')) +app.config['MAX_CONTENT_LENGTH'] = MAX_UPLOAD +pool = ConnectionPool( + setting('DATABASE_URL'), + min_size=1, + max_size=int(os.getenv('POOL_MAX', '8')), + timeout=3, + kwargs={ + 'row_factory': dict_row, + 'connect_timeout': 3, + 'options': '-c statement_timeout=3000 -c lock_timeout=2000', + }, +) +cache = redis.Redis.from_url(setting('CACHE_URL'), socket_connect_timeout=0.2, socket_timeout=0.2) +broker = redis.Redis.from_url(setting('BROKER_URL'), socket_connect_timeout=0.3, socket_timeout=0.5) +kdf = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1) +dummy = kdf.hash(secrets.token_urlsafe(32)) +ttl = int(os.getenv('SESSION_TTL_SECONDS', '3600')) +def envsetting(name): return setting(name) if os.getenv(name + '_FILE') else os.environ[name] +s3 = boto3.client( + 's3', + endpoint_url=os.getenv('S3_ENDPOINT', 'http://rustfs:9000'), + region_name=os.getenv('S3_REGION', 'us-east-1'), + aws_access_key_id=envsetting('S3_ACCESS_KEY_ID'), + aws_secret_access_key=envsetting('S3_SECRET_ACCESS_KEY'), + config=Config(connect_timeout=2, read_timeout=5, retries={'max_attempts': 1}), +) +bucket = os.getenv('S3_BUCKET', 'messenger-attachments') +instance = os.getenv('HOSTNAME', 'api') + '-' + secrets.token_hex(4) + +tel = Telemetry('messenger-api', instance) +http_requests_counter = tel.meter.create_counter( + 'http.server.requests', + unit='1', + description='HTTP requests count', +) +http_duration_hist = tel.meter.create_histogram( + 'http.server.request.duration', + unit='s', + description='HTTP request duration in seconds', + explicit_bucket_boundaries_advisory=[0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1.0, 2.5, 5.0, 10.0], +) + +def _pool_callbacks(_opts): + try: + st = pool.get_stats() + size = st.get('pool_size', 0) + avail = st.get('pool_available', 0) + used = max(0, size - avail) + waiting = st.get('requests_waiting', 0) + return [ + Observation(used, {'state': 'used'}), + Observation(avail, {'state': 'idle'}), + Observation(waiting, {'state': 'waiting'}), + Observation(st.get('pool_max', 8), {'state': 'max'}), + ] + except Exception: + return [] + +tel.meter.create_observable_gauge( + 'db.pool.connections', + callbacks=[_pool_callbacks], + unit='', + description='PostgreSQL connection pool usage and waiting queue', +) + +def _api_queue_depth_cb(_opts): + counts = {'pending': 0, 'published': 0, 'processing': 0} + try: + with pool.connection() as c: + rows = c.execute("SELECT state, count(*) AS n FROM attachment_jobs WHERE state IN ('pending','published','processing') GROUP BY state").fetchall() + for r in rows: + counts[r['state']] = int(r['n']) + except Exception: + return [] + return [Observation(v, {'queue_name': 'attachment-jobs', 'state': k}) for k, v in counts.items()] + +def _api_oldest_age_cb(_opts): + try: + with pool.connection() as c: + row = c.execute("SELECT COALESCE(EXTRACT(EPOCH FROM (clock_timestamp() - min(created_at))), 0) AS age FROM attachment_jobs WHERE state IN ('pending','published','processing')").fetchone() + return [Observation(max(0.0, float(row['age'])) if row else 0.0, {'queue_name': 'attachment-jobs'})] + except Exception: + return [] + +tel.meter.create_observable_gauge('worker.queue.depth', callbacks=[_api_queue_depth_cb], unit='', description='Queued jobs by state') +tel.meter.create_observable_gauge('worker.oldest_job.age', callbacks=[_api_oldest_age_cb], unit='s', description='Age of oldest unfinished job in seconds') +http_requests_counter.add(0, {'http.request.method': 'POST', 'http.route': '/api/v1/chats/{chat_id}/messages', 'http.response.status_class': '5xx'}) +http_requests_counter.add(0, {'http.request.method': 'POST', 'http.route': '/api/v1/chats/{chat_id}/attachments', 'http.response.status_class': '5xx'}) + +def route_template(path): + if path in ('/health/live', '/health/ready'): + return path + if path.startswith('/api/v1/'): + rel = path[8:] + if rel in ('users', 'users/me', 'auth/sessions', 'auth/sessions/current', 'chats'): + return '/api/v1/' + rel + parts = rel.split('/') + if len(parts) == 2 and parts[0] == 'chats': + return '/api/v1/chats/{chat_id}' + if len(parts) == 3 and parts[0] == 'chats' and parts[2] in ('messages', 'attachments'): + return '/api/v1/chats/{chat_id}/' + parts[2] + if len(parts) == 2 and parts[0] == 'attachments': + return '/api/v1/attachments/{attachment_id}' + if len(parts) == 3 and parts[0] == 'attachments' and parts[2] == 'content': + return '/api/v1/attachments/{attachment_id}/content' + return '/api/v1/{unknown}' + return '/{other}' + +class Problem(Exception): + def __init__(self, status, code): + self.status, self.code = status, code + +def fail(status, code): raise Problem(status, code) +def invalid(): fail(400, 'invalid_request') +def uid(value): + try: return str(uuid.UUID(value)) + except (ValueError, TypeError, AttributeError): invalid() +def clean(row): + return {k: (v.isoformat().replace('+00:00', 'Z') if isinstance(v, dt.datetime) else str(v) if isinstance(v, uuid.UUID) else v) for k, v in row.items()} +def user(row): return clean({k: row[k] for k in ('id', 'username', 'display_name', 'created_at')}) +def body(fields): + if request.mimetype != 'application/json': fail(415, 'unsupported_media_type') + try: data = request.get_json() + except HTTPException: invalid() + if not isinstance(data, dict) or set(data) != set(fields): invalid() + return data +def string(s, maximum, minimum=1): + if not isinstance(s, str) or not s.strip() or not minimum <= len(s) <= maximum: invalid() + try: s.encode('utf-8') + except UnicodeError: invalid() + return s + +def db_exec(c, op, query, params=()): + with tel.span('db.query', {'db.system': 'postgresql', 'db.operation.name': op}): + return c.execute(query, params) + +def actor(c): + auth = request.headers.get('Authorization', '') + if not auth.startswith('Bearer ') or not 1 <= len(auth[7:]) <= 256: fail(401, 'unauthorized') + digest = hashlib.sha256(auth[7:].encode()).hexdigest() + row = db_exec(c, 'select_session', 'SELECT user_id FROM sessions WHERE token_hash=%s AND expires_at>clock_timestamp()', (digest,)).fetchone() + if not row: fail(401, 'unauthorized') + g.digest = digest + return row['user_id'] + +def public_user(c, ident): + key = 'user:' + str(ident) + with tel.span('cache.get_user', {'db.system': 'redis'}): + try: + value = cache.get(key) + if value: return json.loads(value) + except (redis.RedisError, ValueError): pass + result = user(db_exec(c, 'select_user', 'SELECT * FROM users WHERE id=%s', (ident,)).fetchone()) + try: cache.setex(key, 60, json.dumps(result)) + except redis.RedisError: pass + return result + +def chat(c, ident, who): + row = db_exec(c, 'select_chat', 'SELECT c.* FROM chats c JOIN members m ON c.id=m.chat_id WHERE c.id=%s AND m.user_id=%s', (ident, who)).fetchone() + if not row: fail(404, 'not_found') + row = clean(row) + row['member_ids'] = [str(x['user_id']) for x in db_exec(c, 'select_members', 'SELECT user_id FROM members WHERE chat_id=%s ORDER BY user_id', (ident,))] + return row + +def page_args(resource): + if set(request.args) - {'limit', 'cursor'} or any(len(request.args.getlist(k)) != 1 for k in request.args): invalid() + raw = request.args.get('limit', '50') + if len(raw) > 3 or not re.fullmatch(r'[0-9]+', raw) or not 1 <= int(raw) <= 100: invalid() + cursor = request.args.get('cursor') + pair = None + if cursor is not None: + try: + data = json.loads(base64.b64decode(cursor, altchars=b'-_', validate=True)) + if not isinstance(data, list) or len(data) != 3 or data[0] != resource: invalid() + stamp = dt.datetime.fromisoformat(data[1].replace('Z', '+00:00')) + if stamp.tzinfo is None: invalid() + pair = (stamp, uid(data[2])) + except (ValueError, TypeError, KeyError, AttributeError, OverflowError): invalid() + return int(raw), pair + +def page(rows, limit, resource): + more = len(rows) > limit + rows = rows[:limit] + cursor = base64.urlsafe_b64encode(json.dumps([resource, rows[-1]['created_at'], rows[-1]['id']]).encode()).decode() if more else None + return {'items': rows, 'next_cursor': cursor} + +@app.before_request +def before(): + g.request_id = str(uuid.uuid4()) + g._req_start = time.monotonic() + g._route = route_template(request.path) + parent = tel.extract_context(request.headers.get('traceparent'), request.headers.get('tracestate')) + span = tel.tracer.start_span( + f'{request.method} {g._route}', + context=parent, + kind=SpanKind.SERVER, + attributes={ + 'http.request.method': request.method, + 'http.route': g._route, + 'messenger.request_id': g.request_id, + }, + ) + g._otel_span = span + g._otel_token = otel_context.attach(trace.set_span_in_context(span)) + +@app.after_request +def after(response): + response.headers['X-Request-Id'] = g.request_id + response.headers['X-Instance-Id'] = instance + duration = time.monotonic() - getattr(g, '_req_start', time.monotonic()) + status = response.status_code + status_class = f'{status // 100}xx' + route = getattr(g, '_route', '/{other}') + attrs = { + 'http.request.method': request.method, + 'http.route': route, + 'http.response.status_class': status_class, + } + http_requests_counter.add(1, attrs) + http_duration_hist.record(duration, attrs) + span = getattr(g, '_otel_span', None) + if span is not None: + span.set_attribute('http.response.status_code', status) + if status >= 500: + span.set_status(Status(StatusCode.ERROR, f'http_{status}')) + if not route.startswith('/health/') or status >= 500: + lvl = logging.ERROR if status >= 500 else logging.WARNING if status >= 400 else logging.INFO + tel.log( + lvl, + 'http.request', + request_id=g.request_id, + http_method=request.method, + http_route=route, + http_status=status, + duration_ms=round(duration * 1000, 2), + ) + return response + +@app.teardown_request +def teardown(exc): + span = getattr(g, '_otel_span', None) + token = getattr(g, '_otel_token', None) + if span is not None: + if exc is not None: + span.set_status(Status(StatusCode.ERROR, type(exc).__name__)) + span.record_exception(exc) + span.end() + if token is not None: + otel_context.detach(token) + +@app.errorhandler(Exception) +def error(exc): + if isinstance(exc, Problem): + status, code = exc.status, exc.code + elif isinstance(exc, UniqueViolation): + status, code = 409, 'conflict' + elif isinstance(exc, (psycopg.Error, __import__('psycopg_pool').PoolTimeout)): + status, code = 503, 'unavailable' + elif isinstance(exc, HTTPException): + status = exc.code + code = {404: 'not_found', 413: 'payload_too_large', 415: 'unsupported_media_type'}.get(status, 'invalid_request') + else: + tel.log(logging.ERROR, 'http.unhandled_exception', request_id=g.request_id, exc_type=type(exc).__name__) + status, code = 500, 'internal_error' + span = getattr(g, '_otel_span', None) + if span is not None and status >= 500: + span.set_status(Status(StatusCode.ERROR, code)) + span.set_attribute('error.code', code) + response = app.json.response({'error': {'code': code, 'message': code, 'request_id': g.request_id}}) + response.status_code = status + if status == 401: + response.headers['WWW-Authenticate'] = 'Basic realm="messenger", charset="UTF-8"' if request.path == '/api/v1/auth/sessions' else 'Bearer realm="messenger"' + return response + +@app.get('/health/live') +def live(): + return {'status': 'ok'} + +@app.get('/health/ready') +def ready(): + with tel.span('db.pool.connect', {'db.system': 'postgresql'}): + with pool.connection() as c: + db_exec(c, 'health_select', 'SELECT 1') + with tel.span('broker.ping', {'db.system': 'redis'}): + try: + broker.ping() + except redis.RedisError: + fail(503, 'unavailable') + return {'status': 'ok'} + +@app.route('/api/v1/', methods=['GET', 'POST', 'DELETE']) +def api(path): + if os.getenv('FAULT_HANDLER_DELAY_MS', '0') != '0' and path.endswith('/messages') and request.method == 'POST': + time.sleep(int(os.getenv('FAULT_HANDLER_DELAY_MS', '0')) / 1000.0) + public = (path in ('users', 'auth/sessions') and request.method == 'POST') + if not public and not request.headers.get('Authorization', '').startswith('Bearer '): + fail(401, 'unauthorized') + with tel.span('db.pool.connect', {'db.system': 'postgresql'}): + conn_cm = pool.connection() + c = conn_cm.__enter__() + exc_info = (None, None, None) + try: + if path == 'users' and request.method == 'POST': + d = body(['username', 'display_name', 'password']) + if not isinstance(d['username'], str) or not re.fullmatch('[a-z0-9_]{3,32}', d['username']): invalid() + string(d['display_name'], 100); string(d['password'], 128, 12) + row = db_exec(c, 'insert_user', 'INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING *', (uuid.uuid4(), d['username'], d['display_name'], kdf.hash(d['password']))).fetchone() + return user(row), 201 + if path == 'auth/sessions' and request.method == 'POST': + a = request.headers.get('Authorization', '') + try: + if not a.startswith('Basic ') or request.get_data(): raise ValueError() + name, password = base64.b64decode(a[6:], validate=True).decode('utf-8').split(':', 1) + except (ValueError, UnicodeError): fail(401, 'unauthorized') + row = db_exec(c, 'select_user_by_name', 'SELECT * FROM users WHERE username=%s', (name,)).fetchone() + try: valid = kdf.verify(row['password_hash'] if row else dummy, password) + except VerificationError: valid = False + if not valid or not row: fail(401, 'unauthorized') + token = secrets.token_urlsafe(32) + expires = db_exec(c, 'insert_session', "INSERT INTO sessions VALUES (%s,%s,clock_timestamp() + %s * interval '1 second') RETURNING expires_at", (hashlib.sha256(token.encode()).hexdigest(), row['id'], ttl)).fetchone()['expires_at'] + return {'token': token, 'token_type': 'Bearer', 'expires_at': expires.isoformat().replace('+00:00', 'Z'), 'user': user(row)}, 201 + who = actor(c) + if path == 'auth/sessions/current' and request.method == 'DELETE': + db_exec(c, 'delete_session', 'DELETE FROM sessions WHERE token_hash=%s', (g.digest,)) + return '', 204 + if path == 'users/me' and request.method == 'GET': + return public_user(c, who) + if path == 'chats': + if request.method == 'POST': + d = body(['title', 'member_ids']); string(d['title'], 100) + ids = d['member_ids'] + if not isinstance(ids, list) or not 1 <= len(ids) <= 100: invalid() + ids = [uid(x) for x in ids] + if len(ids) != len(set(ids)) or str(who) not in ids: invalid() + if db_exec(c, 'count_users', 'SELECT count(*) AS n FROM users WHERE id=ANY(%s::uuid[])', (ids,)).fetchone()['n'] != len(ids): invalid() + ident = uuid.uuid4() + db_exec(c, 'insert_chat', 'INSERT INTO chats(id,title) VALUES (%s,%s)', (ident, d['title'])) + for member in ids: db_exec(c, 'insert_member', 'INSERT INTO members VALUES (%s,%s)', (ident, member)) + return chat(c, ident, who), 201 + if request.method == 'GET': + resource = 'chats:' + str(who); limit, pair = page_args(resource) + query = 'SELECT c.id FROM chats c JOIN members m ON c.id=m.chat_id WHERE m.user_id=%s' + params = [who] + if pair: query += ' AND (c.created_at,c.id)>(%s,%s)'; params += list(pair) + query += ' ORDER BY c.created_at,c.id LIMIT %s'; params += [limit + 1] + return page([chat(c, x['id'], who) for x in db_exec(c, 'list_chats', query, params).fetchall()], limit, resource) + parts = path.split('/') + if len(parts) in (2, 3) and parts[0] == 'chats': + ident = uid(parts[1]) + if len(parts) == 3 and parts[2] == 'messages' and os.getenv('MESSAGE_ACCESS_FAST', '1') == '1': + if not db_exec(c, 'check_member', 'SELECT 1 FROM members WHERE chat_id=%s AND user_id=%s', (ident, who)).fetchone(): fail(404, 'not_found') + result = None + else: + result = chat(c, ident, who) + if len(parts) == 2 and request.method == 'GET': return result + if len(parts) == 3 and parts[2] == 'messages': + if request.method == 'POST': + key = request.headers.get('Idempotency-Key', '') + if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}', key): invalid() + if request.mimetype != 'application/json': fail(415, 'unsupported_media_type') + try: d = request.get_json() + except HTTPException: invalid() + if not isinstance(d, dict) or set(d) - {'text', 'attachment_ids'} or 'text' not in d: invalid() + if not isinstance(d['text'], str) or len(d['text']) > 4000: invalid() + aids = d.get('attachment_ids', []) + if not isinstance(aids, list) or len(aids) > 10: invalid() + aids = [uid(x) for x in aids] + if len(set(aids)) != len(aids): invalid() + if not d['text'].strip() and not aids: invalid() + if aids: + found = db_exec(c, 'check_attachments', 'SELECT id,status FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[])', (ident, aids)).fetchall() + if len(found) != len(aids): fail(404, 'not_found') + if any(x['status'] == 'failed' for x in found): fail(409, 'conflict') + canonical = json.dumps({'text': d['text'], 'attachment_ids': aids}, sort_keys=True, ensure_ascii=False) + scope = str(who) + ':POST:' + ident + ':' + key + db_exec(c, 'advisory_lock', 'SELECT pg_advisory_xact_lock(hashtextextended(%s,0))', (scope,)) + old = db_exec(c, 'select_idempotency', 'SELECT body,response FROM idempotency WHERE user_id=%s AND chat_id=%s AND key=%s AND expires_at>clock_timestamp()', (who, ident, key)).fetchone() + if old: + if old['body'] != canonical: fail(409, 'conflict') + return old['response'], 201 + mid = uuid.uuid4() + result = clean(db_exec(c, 'insert_message', 'INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s) RETURNING *', (mid, ident, who, d['text'])).fetchone()) + result['attachment_ids'] = aids + for pos, aid in enumerate(aids): + db_exec(c, 'insert_msg_attachment', 'INSERT INTO message_attachments VALUES (%s,%s,%s)', (mid, aid, pos)) + db_exec(c, 'upsert_idempotency', "INSERT INTO idempotency(user_id,chat_id,key,body,response,expires_at) VALUES (%s,%s,%s,%s,%s,clock_timestamp()+interval '24 hours') ON CONFLICT(user_id,chat_id,key) DO UPDATE SET body=excluded.body,response=excluded.response,expires_at=excluded.expires_at", (who, ident, key, canonical, psycopg.types.json.Jsonb(result))) + return result, 201 + if request.method == 'GET': + limit, pair = page_args(ident) + query = 'SELECT * FROM messages WHERE chat_id=%s'; params = [ident] + if pair: query += ' AND (created_at,id)>(%s,%s)'; params += list(pair) + query += ' ORDER BY created_at,id LIMIT %s'; params += [limit + 1] + items = [clean(x) for x in db_exec(c, 'list_messages', query, params)] + for m in items: + m['attachment_ids'] = [str(x['attachment_id']) for x in db_exec(c, 'list_msg_attachments', 'SELECT attachment_id FROM message_attachments WHERE message_id=%s ORDER BY position', (m['id'],))] + return page(items, limit, ident) + if len(parts) == 3 and parts[2] == 'attachments' and request.method == 'POST': + backlog = db_exec(c, 'count_backlog', "SELECT count(*) AS n FROM attachment_jobs WHERE state IN ('pending','published','processing')").fetchone()['n'] + if backlog >= MAX_QUEUED: fail(503, 'unavailable') + filename = request.args.get('filename', '') + if len(filename) < 1 or len(filename) > 255 or any(ord(ch) < 32 or ch in '/\\' for ch in filename): invalid() + if request.mimetype not in ('image/png', 'image/jpeg'): fail(415, 'unsupported_media_type') + raw = request.get_data(cache=False) + if not raw: invalid() + try: + im = Image.open(io.BytesIO(raw)); fmt = im.format; w, h = im.size + if w * h > MAX_PIXELS: fail(413, 'payload_too_large') + im.verify() + except Problem: raise + except (UnidentifiedImageError, OSError, ValueError): fail(415, 'unsupported_media_type') + actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(fmt) + if actual != request.mimetype: fail(415, 'unsupported_media_type') + ident_att = uuid.uuid4(); key = 'original/' + str(ident) + '/' + str(ident_att); staging = 'staging/' + str(ident) + '/' + str(ident_att) + digest = hashlib.sha256(raw).hexdigest() + carrier = tel.inject_context() + try: + with tel.span('s3.put_staging', {'storage.system': 's3', 'attachment.id': str(ident_att)}): + s3.put_object(Bucket=bucket, Key=staging, Body=raw, ContentType=actual, Metadata={'sha256': digest}) + row = db_exec(c, 'insert_attachment', "INSERT INTO attachments(id,chat_id,owner_id,object_key,staging_key,filename,content_type,size_bytes,sha256,status) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING *", (ident_att, ident, who, key, staging, filename, actual, len(raw), digest)).fetchone() + job_id = uuid.uuid4() + db_exec(c, 'insert_attachment_job', 'INSERT INTO attachment_jobs(job_id,attachment_id,pipeline_version,traceparent,tracestate) VALUES (%s,%s,1,%s,%s)', (job_id, ident_att, carrier.get('traceparent'), carrier.get('tracestate'))) + tel.log(logging.INFO, 'attachment.queued', request_id=g.request_id, attachment_id=str(ident_att), job_id=str(job_id), size_bytes=len(raw)) + except Exception: + try: s3.delete_object(Bucket=bucket, Key=staging) + except Exception: tel.log(logging.WARNING, 'attachment.compensation_deferred', request_id=g.request_id, attachment_id=str(ident_att)) + if isinstance(__import__('sys').exc_info()[1], psycopg.Error): raise + fail(503, 'unavailable') + return attachment_json(row), 202 + if path.startswith('attachments/'): + bits = path.split('/') + if len(bits) not in (2, 3): fail(404, 'not_found') + aid = uid(bits[1]) + row = db_exec(c, 'select_attachment', 'SELECT a.* FROM attachments a JOIN members m ON m.chat_id=a.chat_id WHERE a.id=%s AND m.user_id=%s', (aid, who)).fetchone() + if not row: fail(404, 'not_found') + if len(bits) == 2 and request.method == 'GET': return attachment_json(row) + if len(bits) == 3 and bits[2] == 'content' and request.method == 'GET': + variant = request.args.get('variant', 'original') + if variant not in ('original', 'thumbnail', 'crop', 'optimized'): invalid() + if row['status'] != 'ready': fail(409, 'conflict') + if variant != 'original': + v = next((v for v in row['variants'] if v['name'] == variant), None) + if v is None: fail(404, 'not_found') + object_key = f'variants/v1/{aid}/{variant}'; content_type = v['content_type'] + else: + object_key = row['object_key']; content_type = row['content_type'] + try: + with tel.span('s3.get_object', {'storage.system': 's3', 'attachment.variant': variant}): + obj = s3.get_object(Bucket=bucket, Key=object_key); data = obj['Body'].read(MAX_UPLOAD + 1) + except Exception: + fail(503, 'unavailable') + if len(data) > MAX_UPLOAD or (variant == 'original' and hashlib.sha256(data).hexdigest() != row['sha256']): fail(503, 'unavailable') + disposition = 'attachment; filename="attachment"; filename*=UTF-8\'\'' + quote(row['filename'], safe='') + return app.response_class(data, 200, mimetype=content_type, headers={'Content-Disposition': disposition}) + fail(404, 'not_found') + except BaseException as exc: + exc_info = (type(exc), exc, exc.__traceback__) + raise + finally: + conn_cm.__exit__(*exc_info) + +def attachment_json(row): + stamp = row['created_at'].isoformat().replace('+00:00', 'Z') + return { + 'id': str(row['id']), + 'chat_id': str(row['chat_id']), + 'owner_id': str(row['owner_id']), + 'filename': row['filename'], + 'content_type': row['content_type'], + 'size_bytes': row['size_bytes'], + 'sha256': row['sha256'].strip(), + 'status': row['status'], + 'variants': row.get('variants', []), + 'error_code': row.get('error_code'), + 'created_at': stamp, + 'updated_at': row.get('updated_at', row['created_at']).isoformat().replace('+00:00', 'Z'), + } \ No newline at end of file diff --git a/app/migrate.py b/app/migrate.py new file mode 100644 index 0000000..ec8eeae --- /dev/null +++ b/app/migrate.py @@ -0,0 +1,18 @@ +import os +from pathlib import Path +import psycopg + +def setting(name): + file = os.getenv(name + '_FILE') + return Path(file).read_text().strip() if file else os.environ[name] + +def migrate(): + with psycopg.connect(setting('DATABASE_URL'), connect_timeout=3) as c: + c.execute('SELECT pg_advisory_xact_lock(202602)') + c.execute('CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())') + for p in sorted(Path('migrations').glob('*.sql')): + if not c.execute('SELECT 1 FROM schema_migrations WHERE version=%s',(p.name,)).fetchone(): + c.execute(p.read_text()) + c.execute('INSERT INTO schema_migrations(version) VALUES (%s)',(p.name,)) +if __name__ == '__main__': + migrate() diff --git a/app/telemetry.py b/app/telemetry.py new file mode 100644 index 0000000..5656317 --- /dev/null +++ b/app/telemetry.py @@ -0,0 +1,196 @@ +"""OpenTelemetry setup for API and worker: traces, metrics, structured logs, W3C context.""" +from contextlib import contextmanager +import json +import logging +import os +from pathlib import Path +import time + +from opentelemetry import metrics, propagate, trace +from opentelemetry._logs import set_logger_provider +from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter +from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter +from opentelemetry.metrics import Observation +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON, ParentBased, TraceIdRatioBased +from opentelemetry.trace import SpanKind, Status, StatusCode + +REDACTED_KEYS = {'password', 'token', 'authorization', 'secret', 'text', 'body', 'raw', 'signed_url', 'cookie'} + +class JsonStdoutFormatter(logging.Formatter): + def __init__(self, service_name, instance_id): + super().__init__() + self.service_name = service_name + self.instance_id = instance_id + + def format(self, record): + payload = { + 'timestamp': time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(record.created)), + 'severity': record.levelname, + 'service.name': self.service_name, + 'service.instance.id': self.instance_id, + 'event': getattr(record, 'event', record.getMessage()), + } + span = trace.get_current_span() + ctx = span.get_span_context() if span else None + if ctx and ctx.is_valid: + payload['trace_id'] = format(ctx.trace_id, '032x') + payload['span_id'] = format(ctx.span_id, '016x') + attrs = getattr(record, 'otel_attrs', None) + if isinstance(attrs, dict): + for k, v in attrs.items(): + if k.lower() not in REDACTED_KEYS and v is not None: + payload[k] = v + return json.dumps(payload, ensure_ascii=False, separators=(',', ':')) + +def _sampler_from_env(): + name = os.getenv('OTEL_TRACES_SAMPLER', 'always_on').strip().lower() + arg_raw = os.getenv('OTEL_TRACES_SAMPLER_ARG', '1.0').strip() + try: + ratio = max(0.0, min(1.0, float(arg_raw))) + except ValueError: + ratio = 1.0 + if name == 'always_off': + return ALWAYS_OFF + if name == 'traceidratio': + return TraceIdRatioBased(ratio) + if name == 'parentbased_traceidratio': + return ParentBased(TraceIdRatioBased(ratio)) + if name == 'parentbased_always_on': + return ParentBased(ALWAYS_ON) + return ALWAYS_ON + +def _env_name(): + raw = os.getenv('OTEL_RESOURCE_ATTRIBUTES', 'deployment.environment.name=lab') + for part in raw.split(','): + if '=' in part: + k, v = part.split('=', 1) + if k.strip() == 'deployment.environment.name' and v.strip(): + return v.strip() + return 'lab' + +def _proc_rss_bytes(): + try: + pages = int(Path('/proc/self/statm').read_text().split()[1]) + return pages * os.sysconf('SC_PAGE_SIZE') + except Exception: + return 0 + +class Telemetry: + def __init__(self, service_name, instance_id): + self.service_name = service_name + self.instance_id = instance_id + self.disabled = os.getenv('OTEL_SDK_DISABLED', 'false').strip().lower() in ('1', 'true', 'yes') + self.logger = logging.getLogger('messenger.' + service_name) + self.logger.handlers.clear() + self.logger.setLevel(logging.INFO) + self.logger.propagate = False + + stdout_handler = logging.StreamHandler() + stdout_handler.setFormatter(JsonStdoutFormatter(service_name, instance_id)) + self.logger.addHandler(stdout_handler) + + logging.getLogger('opentelemetry').setLevel(logging.CRITICAL) + logging.getLogger('urllib3').setLevel(logging.WARNING) + + if not self.disabled: + endpoint = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318').rstrip('/') + timeout = float(os.getenv('OTEL_EXPORT_TIMEOUT_SECONDS', '2.0')) + interval_ms = int(os.getenv('OTEL_METRIC_EXPORT_INTERVAL', '5000')) + resource = Resource.create({ + 'service.name': service_name, + 'service.version': os.getenv('OTEL_SERVICE_VERSION', '1.6.0'), + 'service.instance.id': instance_id, + 'deployment.environment.name': _env_name(), + }) + + tracer_provider = TracerProvider(resource=resource, sampler=_sampler_from_env()) + span_exporter = OTLPSpanExporter(endpoint=f'{endpoint}/v1/traces', timeout=timeout) + tracer_provider.add_span_processor( + BatchSpanProcessor( + span_exporter, + max_queue_size=1024, + schedule_delay_millis=1000, + max_export_batch_size=256, + export_timeout_millis=int(timeout * 1000), + ) + ) + trace.set_tracer_provider(tracer_provider) + + metric_exporter = OTLPMetricExporter(endpoint=f'{endpoint}/v1/metrics', timeout=timeout) + reader = PeriodicExportingMetricReader( + metric_exporter, + export_interval_millis=interval_ms, + export_timeout_millis=int(timeout * 1000), + ) + meter_provider = MeterProvider(resource=resource, metric_readers=[reader]) + metrics.set_meter_provider(meter_provider) + + logger_provider = LoggerProvider(resource=resource) + log_exporter = OTLPLogExporter(endpoint=f'{endpoint}/v1/logs', timeout=timeout) + logger_provider.add_log_record_processor( + BatchLogRecordProcessor( + log_exporter, + max_queue_size=1024, + schedule_delay_millis=1000, + max_export_batch_size=256, + export_timeout_millis=int(timeout * 1000), + ) + ) + set_logger_provider(logger_provider) + self.logger.addHandler(LoggingHandler(level=logging.INFO, logger_provider=logger_provider)) + + self.tracer = trace.get_tracer(service_name, '1.6.0') + self.meter = metrics.get_meter(service_name, '1.6.0') + + self.meter.create_observable_counter( + 'process.cpu.time', + callbacks=[lambda _opts: [Observation(time.process_time())]], + unit='s', + description='Process CPU time in seconds', + ) + self.meter.create_observable_gauge( + 'process.memory.rss', + callbacks=[lambda _opts: [Observation(_proc_rss_bytes())]], + unit='By', + description='Process resident set size in bytes', + ) + + @contextmanager + def span(self, name, attributes=None, kind=SpanKind.INTERNAL, context=None): + with self.tracer.start_as_current_span(name, context=context, kind=kind, attributes=attributes or {}) as sp: + try: + yield sp + except Exception as exc: + sp.set_status(Status(StatusCode.ERROR, type(exc).__name__)) + sp.record_exception(exc) + raise + + def log(self, level, event, **fields): + safe = {k: v for k, v in fields.items() if k.lower() not in REDACTED_KEYS and v is not None} + safe['event'] = event + self.logger.log(level, event, extra={'event': event, 'otel_attrs': safe}) + + def inject_context(self): + span = trace.get_current_span() + ctx = span.get_span_context() if span else None + if not ctx or not ctx.is_valid: + return {} + carrier = {} + propagate.inject(carrier) + return carrier + + def extract_context(self, traceparent=None, tracestate=None): + carrier = {} + if traceparent: + carrier['traceparent'] = traceparent + if tracestate: + carrier['tracestate'] = tracestate + return propagate.extract(carrier) if carrier else None diff --git a/app/worker.py b/app/worker.py new file mode 100644 index 0000000..2cebb3d --- /dev/null +++ b/app/worker.py @@ -0,0 +1,322 @@ +"""Durable outbox relay and idempotent Redis Streams image worker with OpenTelemetry.""" +from concurrent.futures import ThreadPoolExecutor +import hashlib +import io +import json +import logging +import os +import random +import threading +import time +import uuid + +import boto3 +from botocore.config import Config +from opentelemetry.metrics import Observation +from opentelemetry.trace import SpanKind +from PIL import Image, ImageOps, UnidentifiedImageError +import psycopg +from psycopg.rows import dict_row +from psycopg_pool import ConnectionPool +import redis + +from app.migrate import setting +from app.telemetry import Telemetry + +def envsetting(name): return setting(name) if os.getenv(name + '_FILE') else os.environ[name] + +db = ConnectionPool(setting('DATABASE_URL'), min_size=1, max_size=8, kwargs={'row_factory': dict_row, 'connect_timeout': 3}) +broker = redis.Redis.from_url(setting('BROKER_URL'), socket_connect_timeout=1, socket_timeout=2, decode_responses=True) +s3 = boto3.client( + 's3', + endpoint_url=os.getenv('S3_ENDPOINT', 'http://rustfs:9000'), + region_name=os.getenv('S3_REGION', 'us-east-1'), + aws_access_key_id=envsetting('S3_ACCESS_KEY_ID'), + aws_secret_access_key=envsetting('S3_SECRET_ACCESS_KEY'), + config=Config(connect_timeout=3, read_timeout=10, retries={'max_attempts': 2}), +) +bucket = os.getenv('S3_BUCKET', 'messenger-attachments') +stream = 'attachment-jobs' +group = 'image-workers' +attempts = int(os.getenv('JOB_MAX_ATTEMPTS', '5')) +concurrency = int(os.getenv('WORKER_CONCURRENCY', '2')) +timeout = int(os.getenv('JOB_TIMEOUT_SECONDS', '60')) + +instance = os.getenv('HOSTNAME', 'worker') + '-' + uuid.uuid4().hex[:8] +tel = Telemetry('messenger-worker', instance) + +jobs_counter = tel.meter.create_counter('worker.jobs', unit='1', description='Processed worker jobs') +job_duration_hist = tel.meter.create_histogram( + 'worker.job.duration', + unit='s', + description='Worker job execution duration in seconds', + explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0], +) +e2e_ready_hist = tel.meter.create_histogram( + 'attachment.time_to_ready', + unit='s', + description='End-to-end attachment time from durable acceptance to ready', + explicit_bucket_boundaries_advisory=[0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0, 120.0], +) + +_busy_lock = threading.Lock() +_busy_threads = 0 + +def _threads_callback(_opts): + with _busy_lock: + busy = _busy_threads + return [ + Observation(busy, {'state': 'busy'}), + Observation(concurrency, {'state': 'capacity'}), + ] + +def _queue_callbacks(_opts): + counts = {'pending': 0, 'published': 0, 'processing': 0} + try: + with db.connection() as c: + rows = c.execute( + "SELECT state, count(*) AS n " + "FROM attachment_jobs WHERE state IN ('pending','published','processing') GROUP BY state" + ).fetchall() + for r in rows: + counts[r['state']] = int(r['n']) + except Exception: + return [] + return [Observation(v, {'queue_name': stream, 'state': k}) for k, v in counts.items()] + +def _oldest_age_callback(_opts): + try: + with db.connection() as c: + row = c.execute( + "SELECT COALESCE(EXTRACT(EPOCH FROM (clock_timestamp() - min(created_at))), 0) AS age " + "FROM attachment_jobs WHERE state IN ('pending','published','processing')" + ).fetchone() + age = max(0.0, float(row['age'])) if row else 0.0 + return [Observation(age, {'queue_name': stream})] + except Exception: + return [] + +tel.meter.create_observable_gauge('worker.threads', callbacks=[_threads_callback], unit='', description='Worker thread saturation') +tel.meter.create_observable_gauge('worker.queue.depth', callbacks=[_queue_callbacks], unit='', description='Queued jobs by state') +tel.meter.create_observable_gauge('worker.oldest_job.age', callbacks=[_oldest_age_callback], unit='s', description='Age of oldest unfinished job in seconds') + +try: + broker.xgroup_create(stream, group, id='0', mkstream=True) +except redis.ResponseError as e: + if 'BUSYGROUP' not in str(e): + raise + +def publish_outbox(): + with db.connection() as c: + rows = c.execute( + "SELECT job_id,attachment_id,pipeline_version,attempt,created_at,traceparent,tracestate " + "FROM attachment_jobs WHERE state IN ('pending','published') AND available_at<=clock_timestamp() " + "ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED" + ).fetchall() + for r in rows: + parent_ctx = tel.extract_context(r.get('traceparent'), r.get('tracestate')) + with tel.span( + 'outbox.publish', + attributes={ + 'messaging.system': 'redis', + 'messaging.destination.name': stream, + 'messaging.operation.type': 'publish', + 'job.id': str(r['job_id']), + 'attachment.id': str(r['attachment_id']), + }, + kind=SpanKind.PRODUCER, + context=parent_ctx, + ): + carrier = tel.inject_context() + msg = { + 'schema_version': 1, + 'job_id': str(r['job_id']), + 'type': 'attachment.process.v1', + 'attachment_id': str(r['attachment_id']), + 'pipeline_version': r['pipeline_version'], + 'attempt': max(1, r['attempt'] + 1), + 'created_at': r['created_at'].isoformat().replace('+00:00', 'Z'), + } + if carrier.get('traceparent'): + msg['traceparent'] = carrier['traceparent'] + if carrier.get('tracestate'): + msg['tracestate'] = carrier['tracestate'] + broker.xadd(stream, {'job': json.dumps(msg, separators=(',', ':'))}) + c.execute("UPDATE attachment_jobs SET state='published',available_at=clock_timestamp()+interval '15 seconds' WHERE job_id=%s AND state IN ('pending','published')", (r['job_id'],)) + tel.log(logging.INFO, 'outbox.published', job_id=str(r['job_id']), attachment_id=str(r['attachment_id'])) + +def resize(raw): + im = Image.open(io.BytesIO(raw)); im.load(); im = ImageOps.exif_transpose(im) + if im.width * im.height > 40_000_000: + raise ValueError('oversized_image') + if im.mode in ('RGBA', 'LA') or 'transparency' in im.info: + rgba = im.convert('RGBA'); bg = Image.new('RGBA', rgba.size, 'white'); bg.alpha_composite(rgba); im = bg.convert('RGB') + else: + im = im.convert('RGB') + thumb = im.copy(); thumb.thumbnail((256, 256), Image.Resampling.LANCZOS) + out = io.BytesIO(); thumb.save(out, format='JPEG', quality=85, optimize=True) + crop = ImageOps.fit(im, (128, 128), method=Image.Resampling.LANCZOS, centering=(0.5, 0.5)); cropout = io.BytesIO(); crop.save(cropout, format='JPEG', quality=85, optimize=True) + opt = im.copy(); opt.thumbnail((1280, 1280), Image.Resampling.LANCZOS); webp = io.BytesIO(); opt.save(webp, format='WEBP', quality=82, method=4, exif=b'') + return [ + ('thumbnail', 'image/jpeg', thumb.size, out.getvalue()), + ('crop', 'image/jpeg', crop.size, cropout.getvalue()), + ('optimized', 'image/webp', opt.size, webp.getvalue()), + ] + +def process(job): + global _busy_threads + jid = uuid.UUID(job['job_id']); aid = uuid.UUID(job['attachment_id']) + parent_ctx = tel.extract_context(job.get('traceparent'), job.get('tracestate')) + started = time.monotonic() + outcome = 'noop' + with _busy_lock: + _busy_threads += 1 + try: + with tel.span( + 'worker.process', + attributes={ + 'messaging.system': 'redis', + 'messaging.destination.name': stream, + 'messaging.operation.type': 'process', + 'job.id': str(jid), + 'job.type': job.get('type', 'attachment.process.v1'), + 'attachment.id': str(aid), + }, + kind=SpanKind.CONSUMER, + context=parent_ctx, + ) as sp: + with tel.span('db.claim_job', {'db.system': 'postgresql'}): + with db.connection() as c: + c.execute('BEGIN') + r = c.execute( + 'SELECT j.*, a.chat_id, a.owner_id, a.object_key, a.staging_key, a.content_type, a.sha256, a.status, a.created_at AS att_created_at ' + 'FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s FOR UPDATE OF j,a', + (jid,), + ).fetchone() + if not r: + c.rollback() + return + if r['state'] in ('done', 'failed') or (r['state'] == 'processing' and r['lease_until'] and r['lease_until'].timestamp() > time.time()): + c.rollback() + return + c.execute("UPDATE attachment_jobs SET state='processing',attempt=attempt+1,lease_until=clock_timestamp()+(%s * interval '1 second') WHERE job_id=%s", (timeout, jid)) + c.execute("UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=%s AND status<>'ready'", (aid,)) + c.execute("INSERT INTO attachment_job_audit(job_id,event) VALUES (%s,'processing')", (jid,)) + c.commit() + attempt_num = r['attempt'] + 1 + sp.set_attribute('job.attempt', attempt_num) + tel.log(logging.INFO, 'worker.processing', job_id=str(jid), attachment_id=str(aid), attempt=attempt_num) + try: + with tel.span('s3.get_staging', {'storage.system': 's3'}): + raw = s3.get_object(Bucket=bucket, Key=r['staging_key'])['Body'].read(10_485_761) + if len(raw) > 10_485_760 or hashlib.sha256(raw).hexdigest() != r['sha256'].strip(): + raise ValueError('invalid_image') + with tel.span('image.resize'): + variants = resize(raw) + with tel.span('s3.put_variants', {'storage.system': 's3'}): + s3.put_object(Bucket=bucket, Key=r['object_key'], Body=raw, ContentType=r['content_type'], Metadata={'sha256': r['sha256'].strip()}) + meta = [] + for name, mime, size, data in variants: + key = f'variants/v1/{aid}/{name}' + s3.put_object(Bucket=bucket, Key=key, Body=data, ContentType=mime, Metadata={'pipeline-version': '1'}) + meta.append({'name': name, 'content_type': mime, 'size_bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest(), 'width': size[0], 'height': size[1]}) + if os.getenv('FAULT_AFTER_S3_WRITE_ONCE', '0') == '1': + with db.connection() as c: + seen = c.execute("SELECT 1 FROM attachment_job_audit WHERE job_id=%s AND event='fault_injected'", (jid,)).fetchone() + if not seen: + c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'fault_injected','crash after deterministic S3 writes, before ready commit')", (jid,)) + c.commit() + os._exit(72) + with tel.span('db.commit_ready', {'db.system': 'postgresql'}): + with db.connection() as c: + c.execute("UPDATE attachments SET status='ready',variants=%s::jsonb,error_code=NULL,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=1 AND status<>'ready'", (json.dumps(meta), aid)) + c.execute("UPDATE attachment_jobs SET state='done',lease_until=NULL,last_error=NULL WHERE job_id=%s", (jid,)) + c.execute("INSERT INTO attachment_job_audit(job_id,event) VALUES (%s,'ready')", (jid,)) + row_now = c.execute('SELECT clock_timestamp() AS now').fetchone() + with tel.span('s3.delete_staging', {'storage.system': 's3'}): + s3.delete_object(Bucket=bucket, Key=r['staging_key']) + outcome = 'ready' + e2e_sec = max(0.0, (row_now['now'] - r['att_created_at']).total_seconds()) + e2e_ready_hist.record(e2e_sec, {'pipeline_version': '1'}) + tel.log(logging.INFO, 'worker.ready', job_id=str(jid), attachment_id=str(aid), e2e_seconds=round(e2e_sec, 3)) + except (UnidentifiedImageError, ValueError) as exc: + outcome = 'failed' + retry_or_fail(jid, aid, 'invalid_image', True) + sp.record_exception(exc) + except Exception as exc: + outcome = retry_or_fail(jid, aid, 'processing_failed', False) + sp.record_exception(exc) + finally: + with _busy_lock: + _busy_threads -= 1 + elapsed = time.monotonic() - started + attrs = {'job.type': job.get('type', 'attachment.process.v1'), 'outcome': outcome} + jobs_counter.add(1, attrs) + job_duration_hist.record(elapsed, attrs) + +def retry_or_fail(jid, aid, code, permanent): + with db.connection() as c: + r = c.execute('SELECT attempt,state FROM attachment_jobs WHERE job_id=%s', (jid,)).fetchone() + if not r or r['state'] == 'done': + return 'noop' + n = r['attempt'] + if permanent or n >= attempts: + c.execute("UPDATE attachment_jobs SET state='failed',lease_until=NULL,last_error=%s WHERE job_id=%s", (code, jid)) + c.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() WHERE id=%s", ('invalid_image' if permanent else 'retry_exhausted', aid)) + c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'failed',%s)", (jid, code)) + broker.xadd('attachment-jobs-dlq', {'job_id': str(jid), 'attachment_id': str(aid), 'error_code': code}) + tel.log(logging.ERROR, 'worker.failed', job_id=str(jid), attachment_id=str(aid), error_code=code, attempt=n) + return 'failed' + delay = min(60, 2 ** n) * (0.8 + random.random() * 0.4) + c.execute("UPDATE attachment_jobs SET state='pending',available_at=clock_timestamp()+(%s * interval '1 second'),lease_until=NULL,last_error=%s WHERE job_id=%s", (delay, code, jid)) + c.execute("UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=%s", (aid,)) + tel.log(logging.WARNING, 'worker.retry', job_id=str(jid), attachment_id=str(aid), error_code=code, attempt=n, retry_delay_s=round(delay, 2)) + return 'retry' + +def recover_leases(): + with db.connection() as c: + expired = c.execute("SELECT job_id,attachment_id,attempt FROM attachment_jobs WHERE state='processing' AND lease_until= attempts: + c.execute("UPDATE attachment_jobs SET state='failed',lease_until=NULL,last_error='retry_exhausted' WHERE job_id=%s", (row['job_id'],)) + c.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=%s", (row['attachment_id'],)) + c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'failed','lease attempts exhausted')", (row['job_id'],)) + broker.xadd('attachment-jobs-dlq', {'job_id': str(row['job_id']), 'attachment_id': str(row['attachment_id']), 'error_code': 'retry_exhausted'}) + tel.log(logging.ERROR, 'worker.lease_exhausted', job_id=str(row['job_id']), attachment_id=str(row['attachment_id'])) + else: + c.execute("UPDATE attachment_jobs SET state='pending',lease_until=NULL,available_at=clock_timestamp() WHERE job_id=%s", (row['job_id'],)) + tel.log(logging.WARNING, 'worker.lease_recovered', job_id=str(row['job_id']), attachment_id=str(row['attachment_id'])) + c.execute("UPDATE attachments a SET status='queued',updated_at=clock_timestamp() FROM attachment_jobs j WHERE j.attachment_id=a.id AND j.state='pending' AND a.status='processing'") + +def main(): + consumer = f'worker-{uuid.uuid4()}' + while True: + try: + recover_leases(); publish_outbox() + if os.getenv('WORKER_PAUSE_CONSUME', '0') == '1': + time.sleep(0.2); continue + msgs = broker.xreadgroup(group, consumer, {stream: '>'}, count=concurrency, block=1000) + claimed = broker.xautoclaim(stream, group, consumer, min_idle_time=timeout * 1000, start_id='0-0', count=concurrency) + if claimed and claimed[1]: + msgs.append((stream, claimed[1])) + for _, entries in msgs: + with ThreadPoolExecutor(max_workers=concurrency) as executor: + futures = [] + for mid, fields in entries: + try: + job = json.loads(fields['job']) + except Exception: + broker.xadd('attachment-jobs-dlq', {'message_id': mid, 'error_code': 'invalid_job'}) + broker.xack(stream, group, mid) + continue + futures.append((mid, executor.submit(process, job))) + for mid, future in futures: + try: + future.result(); broker.xack(stream, group, mid) + except Exception: + pass + except Exception: + time.sleep(1) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..18ac114 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,229 @@ +name: mtusi_lab6_solution +x-api: &api + build: . + image: mtusi-lab6-api:local + environment: + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL_FILE: /run/secrets/cache_url + BROKER_URL_FILE: /run/secrets/broker_url + S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id + S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key + S3_ENDPOINT: http://rustfs:9000 + S3_REGION: us-east-1 + S3_BUCKET: messenger-attachments + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + MAX_UPLOAD_BYTES: 10485760 + MAX_IMAGE_PIXELS: 40000000 + JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5} + JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60} + FAULT_AFTER_S3_WRITE_ONCE: ${FAULT_AFTER_S3_WRITE_ONCE:-0} + FAULT_HANDLER_DELAY_MS: ${FAULT_HANDLER_DELAY_MS:-0} + WORKER_PAUSE_CONSUME: ${WORKER_PAUSE_CONSUME:-0} + WORKER_CONCURRENCY: ${WORKER_CONCURRENCY:-2} + MAX_QUEUED_JOBS: ${MAX_QUEUED_JOBS:-500} + OTEL_SDK_DISABLED: ${OTEL_SDK_DISABLED:-false} + OTEL_SERVICE_VERSION: 1.6.0 + OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318 + OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf + OTEL_EXPORT_TIMEOUT_SECONDS: '2.0' + OTEL_METRIC_EXPORT_INTERVAL: '5000' + OTEL_TRACES_SAMPLER: ${OTEL_TRACES_SAMPLER:-always_on} + OTEL_TRACES_SAMPLER_ARG: ${OTEL_TRACES_SAMPLER_ARG:-1.0} + OTEL_RESOURCE_ATTRIBUTES: deployment.environment.name=lab + secrets: [database_url, cache_url, broker_url, s3_access_key_id, s3_secret_access_key] + restart: unless-stopped + mem_limit: 512m + cpus: 0.75 + +services: + postgres: + image: postgres:16.10-alpine + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/db_password + secrets: [db_password] + volumes: [pgdata:/var/lib/postgresql/data] + healthcheck: + test: [CMD-SHELL, pg_isready -U messenger -d messenger] + interval: 2s + timeout: 2s + retries: 30 + + redis: + image: redis:7.4.6-alpine + command: [redis-server, --maxmemory, 64mb, --maxmemory-policy, allkeys-lru] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 2s + timeout: 1s + retries: 20 + + broker: + image: redis:7.4.6-alpine + command: [redis-server, --appendonly, 'yes', --appendfsync, everysec, --maxmemory, 128mb, --maxmemory-policy, noeviction] + volumes: [brokerdata:/data] + healthcheck: + test: [CMD, redis-cli, ping] + interval: 2s + timeout: 1s + retries: 20 + + rustfs: + image: rustfs/rustfs:1.0.3-glibc + command: [/data] + environment: + RUSTFS_ACCESS_KEY_FILE: /run/secrets/rustfs_root_user + RUSTFS_SECRET_KEY_FILE: /run/secrets/rustfs_root_password + RUSTFS_CONSOLE_ENABLE: 'false' + RUSTFS_ADDRESS: ':9000' + secrets: [rustfs_root_user, rustfs_root_password] + volumes: [s3data:/data] + expose: ['9000'] + healthcheck: + test: [CMD, curl, -f, http://127.0.0.1:9000/health] + interval: 2s + timeout: 2s + retries: 30 + + bucket-bootstrap: + image: rustfs/rc:v0.1.37 + depends_on: + rustfs: {condition: service_healthy} + entrypoint: [/bin/sh, /bootstrap-rustfs.sh] + volumes: ['./infra/rustfs-policy.json:/policy.json:ro', './infra/bootstrap-rustfs.sh:/bootstrap-rustfs.sh:ro'] + secrets: [rustfs_root_user, rustfs_root_password, s3_access_key_id, s3_secret_access_key] + restart: 'no' + + migrate: + <<: *api + command: [python, -m, app.migrate] + restart: 'no' + depends_on: + postgres: {condition: service_healthy} + + loki: + image: grafana/loki:3.5.7 + user: '0' + command: [-config.file=/etc/loki/loki.yaml] + volumes: + - ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro + - lokidata:/loki + expose: ['3100'] + restart: unless-stopped + mem_limit: 512m + + tempo: + image: grafana/tempo:2.9.0 + user: '0' + command: [-config.file=/etc/tempo/tempo.yaml] + volumes: + - ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro + - tempodata:/var/tempo + expose: ['3200', '4317', '4318'] + restart: unless-stopped + mem_limit: 512m + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.142.0 + command: [--config=/etc/otelcol/collector.yaml] + volumes: + - ${OTEL_COLLECTOR_CONFIG:-./infra/otel/collector.yaml}:/etc/otelcol/collector.yaml:ro + expose: ['4317', '4318', '8888', '8889', '13133'] + depends_on: + loki: {condition: service_started} + tempo: {condition: service_started} + restart: unless-stopped + mem_limit: 256m + cpus: 0.50 + + prometheus: + image: prom/prometheus:v3.5.0 + user: '0' + command: + - --config.file=/etc/prometheus/prometheus.yml + - --storage.tsdb.path=/prometheus + - --storage.tsdb.retention.time=7d + volumes: + - ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - ./infra/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro + - promdata:/prometheus + expose: ['9090'] + depends_on: + otel-collector: {condition: service_started} + restart: unless-stopped + mem_limit: 512m + + grafana: + image: grafana/grafana:12.2.1 + environment: + GF_SECURITY_ADMIN_USER: admin + GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password + GF_USERS_ALLOW_SIGN_UP: 'false' + GF_ANALYTICS_REPORTING_ENABLED: 'false' + secrets: [grafana_admin_password] + ports: ['127.0.0.1:${GRAFANA_PORT:-3000}:3000'] + volumes: + - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro + - grafanadata:/var/lib/grafana + depends_on: + prometheus: {condition: service_started} + loki: {condition: service_started} + tempo: {condition: service_started} + restart: unless-stopped + mem_limit: 384m + + api: + <<: *api + command: [gunicorn, --bind, 0.0.0.0:8080, --workers, '1', --threads, '2', --timeout, '35', --graceful-timeout, '5', app.main:app] + scale: ${API_REPLICAS:-2} + depends_on: + migrate: {condition: service_completed_successfully} + redis: {condition: service_healthy} + broker: {condition: service_healthy} + bucket-bootstrap: {condition: service_completed_successfully} + healthcheck: + test: [CMD, python, -c, "import urllib.request; urllib.request.urlopen('http://localhost:8080/health/ready', timeout=3)"] + interval: 2s + timeout: 4s + retries: 3 + + worker: + <<: *api + command: [python, -m, app.worker] + depends_on: + migrate: {condition: service_completed_successfully} + broker: {condition: service_healthy} + bucket-bootstrap: {condition: service_completed_successfully} + healthcheck: + disable: true + deploy: + replicas: 1 + + lb: + image: haproxy:3.0.11-alpine + ports: ['127.0.0.1:${APP_PORT:-8081}:8080'] + volumes: ['./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro'] + depends_on: + api: {condition: service_healthy} + +volumes: + pgdata: + s3data: + brokerdata: + promdata: + lokidata: + tempodata: + grafanadata: + +secrets: + db_password: {file: ./secrets/db_password} + database_url: {file: ./secrets/database_url} + cache_url: {file: ./secrets/cache_url} + broker_url: {file: ./secrets/broker_url} + rustfs_root_user: {file: ./secrets/rustfs_root_user} + rustfs_root_password: {file: ./secrets/rustfs_root_password} + s3_access_key_id: {file: ./secrets/s3_access_key_id} + s3_secret_access_key: {file: ./secrets/s3_secret_access_key} + grafana_admin_password: {file: ./secrets/grafana_admin_password} \ No newline at end of file diff --git a/evidence/lab6-incidents.json b/evidence/lab6-incidents.json new file mode 100644 index 0000000..c64add1 --- /dev/null +++ b/evidence/lab6-incidents.json @@ -0,0 +1,38 @@ +{ + "incident_1_worker_outage": { + "alert": "GrowingQueueLag", + "firing_observed": true, + "resolved_observed": true, + "attachment_status": "ready" + }, + "incident_2_slow_db_vs_handler": { + "slow_db_request_ms": 29.4, + "db_timeout_statuses": [ + 503, + 503, + 503 + ], + "slow_handler_request_ms": 713.3, + "high_api_error_ratio_fired": true, + "db_dominant_trace": { + "trace_id": "df2b128057e2b86261978feadf07e3ee", + "root_ms": 2014.8, + "db_query_ms": 2012.0 + }, + "handler_dominant_trace": { + "trace_id": "ecc5ac60ed34681b532c0572b874d4bf", + "root_ms": 674.4, + "db_query_ms": 14.8 + } + }, + "incident_3_telemetry_backend_outage": { + "messages_succeeded_during_outage": 15, + "attachment_ready_during_outage": true, + "collector_mem_before": "64.58MiB / 256MiB", + "collector_mem_during_outage": "65.49MiB / 256MiB", + "collector_send_failed_spans_delta": 24, + "collector_send_failed_logs_delta": 20, + "api_preserved": true + }, + "result": "PASS" +} diff --git a/evidence/lab6-signals.json b/evidence/lab6-signals.json new file mode 100644 index 0000000..f0a1481 --- /dev/null +++ b/evidence/lab6-signals.json @@ -0,0 +1,42 @@ +{ + "status": "PASS", + "verified_metrics": { + "http_server_requests_total": 28, + "http_server_request_duration_seconds_bucket": 336, + "worker_jobs_total": 2, + "worker_job_duration_seconds_bucket": 22, + "attachment_time_to_ready_seconds_bucket": 24, + "worker_queue_depth": 9, + "worker_oldest_job_age_seconds": 4, + "db_pool_connections": 8, + "worker_threads": 2, + "process_memory_rss_bytes": 6 + }, + "e2e_trace_id": "d566508b20e3f80b76a75854dbc2fb3e", + "e2e_span_services": [ + "messenger-api", + "messenger-worker" + ], + "e2e_span_names": [ + "POST /api/v1/chats/{chat_id}/attachments", + "db.claim_job", + "db.commit_ready", + "db.pool.connect", + "db.query", + "image.resize", + "outbox.publish", + "s3.delete_staging", + "s3.get_staging", + "s3.put_staging", + "s3.put_variants", + "worker.process" + ], + "loki_api_streams": 12, + "loki_worker_streams": 3, + "loki_correlated_entries": 5, + "redaction_checks": { + "message_body_leaked": false, + "token_leaked": false, + "password_leaked": false + } +} diff --git a/evidence/track1-observability-cost.json b/evidence/track1-observability-cost.json new file mode 100644 index 0000000..169ab77 --- /dev/null +++ b/evidence/track1-observability-cost.json @@ -0,0 +1,117 @@ +{ + "track": "cost-of-observability", + "profiles": [ + { + "profile": "telemetry_off", + "duration_seconds": 20, + "concurrency": 6, + "successful_requests": 5581, + "failed_requests": 0, + "rps": 276.97, + "latency_ms": { + "p50": 15.92, + "p95": 44.14, + "p99": 88.49 + }, + "collector_spans_accepted": 0, + "tempo_spans_exported": 0, + "span_drop_ratio": 0.0, + "injected_5xx_errors_captured": "0/10 (disabled)", + "injected_slow_gt150ms_captured": "0/5 (disabled)", + "avg_cpu_pct_under_load": { + "api-1": 69.02, + "api-2": 70.33, + "otel-collector-1": 0.19 + }, + "mem_under_load": { + "api-1": "104.7MiB", + "api-2": "103.1MiB", + "otel-collector-1": "37.42MiB" + } + }, + { + "profile": "always_on_100pct", + "duration_seconds": 20, + "concurrency": 6, + "successful_requests": 3822, + "failed_requests": 0, + "rps": 190.04, + "latency_ms": { + "p50": 24.74, + "p95": 79.22, + "p99": 115.41 + }, + "collector_spans_accepted": 31274, + "tempo_spans_exported": 31282, + "span_drop_ratio": 0.0, + "injected_5xx_errors_captured": "9/10", + "injected_slow_gt150ms_captured": "5/5", + "avg_cpu_pct_under_load": { + "api-1": 72.04, + "api-2": 68.66, + "otel-collector-1": 3.53 + }, + "mem_under_load": { + "api-1": "121.1MiB", + "api-2": "102.7MiB", + "otel-collector-1": "66.44MiB" + } + }, + { + "profile": "head_sampling_10pct", + "duration_seconds": 20, + "concurrency": 6, + "successful_requests": 4624, + "failed_requests": 0, + "rps": 229.43, + "latency_ms": { + "p50": 19.7, + "p95": 57.33, + "p99": 89.03 + }, + "collector_spans_accepted": 3608, + "tempo_spans_exported": 3608, + "span_drop_ratio": 0.0, + "injected_5xx_errors_captured": "0/10", + "injected_slow_gt150ms_captured": "0/5", + "avg_cpu_pct_under_load": { + "api-1": 70.26, + "api-2": 73.45, + "otel-collector-1": 2.24 + }, + "mem_under_load": { + "api-1": "102.6MiB", + "api-2": "125.5MiB", + "otel-collector-1": "52.97MiB" + } + }, + { + "profile": "tail_sampling_balanced", + "duration_seconds": 20, + "concurrency": 6, + "successful_requests": 4160, + "failed_requests": 0, + "rps": 206.6, + "latency_ms": { + "p50": 26.06, + "p95": 60.45, + "p99": 97.63 + }, + "collector_spans_accepted": 34046, + "tempo_spans_exported": 3390, + "span_drop_ratio": 0.9004, + "injected_5xx_errors_captured": "7/10", + "injected_slow_gt150ms_captured": "5/5", + "avg_cpu_pct_under_load": { + "api-1": 68.62, + "api-2": 68.44, + "otel-collector-1": 1.91 + }, + "mem_under_load": { + "api-1": "102MiB", + "api-2": "103.1MiB", + "otel-collector-1": "66.11MiB" + } + } + ] +} diff --git a/infra/bootstrap-rustfs.sh b/infra/bootstrap-rustfs.sh new file mode 100644 index 0000000..8005d74 --- /dev/null +++ b/infra/bootstrap-rustfs.sh @@ -0,0 +1,17 @@ +#!/bin/sh +set -eu +root_user=$(cat /run/secrets/rustfs_root_user) +root_password=$(cat /run/secrets/rustfs_root_password) +app_key=$(cat /run/secrets/s3_access_key_id) +app_secret=$(cat /run/secrets/s3_secret_access_key) +rc alias set local http://rustfs:9000 "$root_user" "$root_password" +if ! rc bucket list local/ | grep -q 'messenger-attachments'; then + rc bucket create local/messenger-attachments +fi +if ! rc admin policy info local messenger-objects >/dev/null 2>&1; then + rc admin policy create local messenger-objects /policy.json +fi +if ! rc admin user info local "$app_key" >/dev/null 2>&1; then + rc admin user add local "$app_key" "$app_secret" +fi +rc admin policy attach local messenger-objects --user "$app_key" diff --git a/infra/grafana/dashboards/messenger-observability.json b/infra/grafana/dashboards/messenger-observability.json new file mode 100644 index 0000000..895a168 --- /dev/null +++ b/infra/grafana/dashboards/messenger-observability.json @@ -0,0 +1,181 @@ +{ + "uid": "mtusi-lab6-obs", + "title": "MTUSI Messenger — Lab 6 Observability", + "schemaVersion": 39, + "version": 1, + "refresh": "5s", + "time": { "from": "now-15m", "to": "now" }, + "panels": [ + { + "id": 1, + "type": "timeseries", + "title": "API Business RPS (by route & status class)", + "gridPos": { "x": 0, "y": 0, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "fieldConfig": { "defaults": { "unit": "reqps" } }, + "targets": [ + { + "refId": "A", + "expr": "sum by (http_route, http_response_status_class) (rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[1m]))", + "legendFormat": "{{http_route}} ({{http_response_status_class}})" + } + ] + }, + { + "id": 2, + "type": "timeseries", + "title": "API 5xx Error Ratio (%)", + "gridPos": { "x": 8, "y": 0, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "fieldConfig": { "defaults": { "unit": "percent", "min": 0 } }, + "targets": [ + { + "refId": "A", + "expr": "100 * (sum(rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health/.*\",http_response_status_class=\"5xx\"}[1m])) or vector(0)) / clamp_min(sum(rate(http_server_requests_total{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[1m])), 1e-9)", + "legendFormat": "5xx error %" + } + ] + }, + { + "id": 3, + "type": "timeseries", + "title": "API Duration p50 / p95 / p99 (aggregated histogram)", + "gridPos": { "x": 16, "y": 0, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "fieldConfig": { "defaults": { "unit": "s" } }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[1m])))", + "legendFormat": "p50" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[1m])))", + "legendFormat": "p95" + }, + { + "refId": "C", + "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[1m])))", + "legendFormat": "p99" + } + ] + }, + { + "id": 4, + "type": "timeseries", + "title": "Worker Jobs Throughput (by outcome)", + "gridPos": { "x": 0, "y": 8, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "fieldConfig": { "defaults": { "unit": "ops" } }, + "targets": [ + { + "refId": "A", + "expr": "sum by (outcome) (rate(worker_jobs_total[1m]))", + "legendFormat": "{{outcome}}" + } + ] + }, + { + "id": 5, + "type": "timeseries", + "title": "Job Processing & End-to-End Time to Ready (p50 / p95)", + "gridPos": { "x": 8, "y": 8, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "fieldConfig": { "defaults": { "unit": "s" } }, + "targets": [ + { + "refId": "A", + "expr": "histogram_quantile(0.50, sum by (le) (rate(worker_job_duration_seconds_bucket[1m])))", + "legendFormat": "job p50" + }, + { + "refId": "B", + "expr": "histogram_quantile(0.95, sum by (le) (rate(worker_job_duration_seconds_bucket[1m])))", + "legendFormat": "job p95" + }, + { + "refId": "C", + "expr": "histogram_quantile(0.95, sum by (le) (rate(attachment_time_to_ready_seconds_bucket[1m])))", + "legendFormat": "e2e ready p95" + } + ] + }, + { + "id": 6, + "type": "timeseries", + "title": "Queue Depth & Oldest Unfinished Job Age", + "gridPos": { "x": 16, "y": 8, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "targets": [ + { + "refId": "A", + "expr": "max by (state) (worker_queue_depth{queue_name=\"attachment-jobs\"})", + "legendFormat": "depth {{state}}" + }, + { + "refId": "B", + "expr": "max(worker_oldest_job_age_seconds{queue_name=\"attachment-jobs\"})", + "legendFormat": "oldest age (s)" + } + ] + }, + { + "id": 7, + "type": "timeseries", + "title": "DB Pool Saturation (used / idle / waiting)", + "gridPos": { "x": 0, "y": 16, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "targets": [ + { + "refId": "A", + "expr": "sum by (state) (db_pool_connections)", + "legendFormat": "pool {{state}}" + } + ] + }, + { + "id": 8, + "type": "timeseries", + "title": "Worker Concurrency Saturation & Process RSS", + "gridPos": { "x": 8, "y": 16, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "targets": [ + { + "refId": "A", + "expr": "max by (state) (worker_threads)", + "legendFormat": "worker {{state}}" + }, + { + "refId": "B", + "expr": "avg by (service_name) (process_memory_rss_bytes) / 1048576", + "legendFormat": "RSS MiB {{service_name}}" + } + ] + }, + { + "id": 9, + "type": "timeseries", + "title": "OTel Collector Pipeline (accepted / sent / failed)", + "gridPos": { "x": 16, "y": 16, "w": 8, "h": 8 }, + "datasource": { "type": "prometheus", "uid": "prometheus" }, + "targets": [ + { + "refId": "A", + "expr": "sum(rate(otelcol_receiver_accepted_spans_total[1m])) or sum(rate(otelcol_receiver_accepted_spans[1m]))", + "legendFormat": "spans accepted/s" + }, + { + "refId": "B", + "expr": "sum(rate(otelcol_exporter_sent_spans_total[1m])) or sum(rate(otelcol_exporter_sent_spans[1m]))", + "legendFormat": "spans sent/s" + }, + { + "refId": "C", + "expr": "sum(rate(otelcol_exporter_send_failed_spans_total[1m])) or sum(rate(otelcol_exporter_send_failed_spans[1m]))", + "legendFormat": "spans send_failed/s" + } + ] + } + ] +} \ No newline at end of file diff --git a/infra/grafana/provisioning/alerting/alerts.yaml b/infra/grafana/provisioning/alerting/alerts.yaml new file mode 100644 index 0000000..da152ad --- /dev/null +++ b/infra/grafana/provisioning/alerting/alerts.yaml @@ -0,0 +1,137 @@ +apiVersion: 1 +groups: + - orgId: 1 + name: messenger-slo-alerts + folder: Messenger + interval: 10s + rules: + - uid: messenger-high-5xx + title: High API 5xx Error Ratio (>5%) + condition: C + for: 15s + noDataState: OK + execErrState: Error + annotations: + summary: High 5xx error ratio on business routes + description: 5xx error ratio exceeded 5% over 1m window. See infra/otel/RUNBOOKS.md. + labels: + severity: critical + data: + - refId: A + relativeTimeRange: + from: 120 + to: 0 + datasourceUid: prometheus + model: + datasource: + type: prometheus + uid: prometheus + expr: sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*",http_response_status_class="5xx"}[1m])) / clamp_min(sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*"}[1m])), 0.001) + instant: true + intervalMs: 1000 + maxDataPoints: 43200 + refId: A + - refId: B + relativeTimeRange: + from: 120 + to: 0 + datasourceUid: __expr__ + model: + datasource: + type: __expr__ + uid: __expr__ + expression: A + reducer: last + type: reduce + refId: B + - refId: C + relativeTimeRange: + from: 120 + to: 0 + datasourceUid: __expr__ + model: + datasource: + type: __expr__ + uid: __expr__ + expression: B + type: threshold + conditions: + - evaluator: + params: + - 0.05 + type: gt + operator: + type: and + query: + params: + - C + reducer: + params: [] + type: last + type: query + refId: C + - uid: messenger-queue-lag + title: Growing Attachment Queue Lag (>15s) + condition: C + for: 15s + noDataState: OK + execErrState: Error + annotations: + summary: Oldest unfinished attachment job age > 15s + description: Worker stopped or overloaded. Check worker saturation and DLQ. See infra/otel/RUNBOOKS.md. + labels: + severity: warning + data: + - refId: A + relativeTimeRange: + from: 120 + to: 0 + datasourceUid: prometheus + model: + datasource: + type: prometheus + uid: prometheus + expr: max(worker_oldest_job_age_seconds{queue_name="attachment-jobs"}) + instant: true + intervalMs: 1000 + maxDataPoints: 43200 + refId: A + - refId: B + relativeTimeRange: + from: 120 + to: 0 + datasourceUid: __expr__ + model: + datasource: + type: __expr__ + uid: __expr__ + expression: A + reducer: last + type: reduce + refId: B + - refId: C + relativeTimeRange: + from: 120 + to: 0 + datasourceUid: __expr__ + model: + datasource: + type: __expr__ + uid: __expr__ + expression: B + type: threshold + conditions: + - evaluator: + params: + - 15 + type: gt + operator: + type: and + query: + params: + - C + reducer: + params: [] + type: last + type: query + refId: C \ No newline at end of file diff --git a/infra/grafana/provisioning/dashboards/dashboards.yaml b/infra/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 0000000..b29270d --- /dev/null +++ b/infra/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,11 @@ +apiVersion: 1 +providers: + - name: Messenger + orgId: 1 + folder: Messenger + type: file + disableDeletion: false + editable: true + updateIntervalSeconds: 10 + options: + path: /var/lib/grafana/dashboards \ No newline at end of file diff --git a/infra/grafana/provisioning/datasources/datasources.yaml b/infra/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 0000000..b1179a4 --- /dev/null +++ b/infra/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,41 @@ +apiVersion: 1 +datasources: + - name: Prometheus + uid: prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + jsonData: + timeInterval: 5s + - name: Loki + uid: loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + derivedFields: + - datasourceUid: tempo + matcherType: label + matcherRegex: "trace_id" + name: TraceID + url: "$${__value.raw}" + - name: Tempo + uid: tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogsV2: + datasourceUid: loki + spanStartTimeShift: '-1m' + spanEndTimeShift: '1m' + filterByTraceID: true + filterBySpanID: false + nodeGraph: + enabled: true + search: + hide: false \ No newline at end of file diff --git a/infra/haproxy.cfg b/infra/haproxy.cfg new file mode 100644 index 0000000..367b71d --- /dev/null +++ b/infra/haproxy.cfg @@ -0,0 +1,28 @@ +global + log stdout format raw local0 + maxconn 1024 +defaults + log global + mode http + timeout connect 500ms + timeout client 30s + timeout server 30s + timeout check 1s + retries 0 +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 2 + timeout resolve 1s + timeout retry 1s + hold valid 1s + hold obsolete 1s +frontend public + bind *:8080 + default_backend replicas +backend replicas + balance roundrobin + option http-server-close + option httpchk GET /health/ready + http-check expect status 200 + default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1 resolvers docker init-addr none + server-template api 8 api:8080 check diff --git a/infra/loki/loki.yaml b/infra/loki/loki.yaml new file mode 100644 index 0000000..d95f322 --- /dev/null +++ b/infra/loki/loki.yaml @@ -0,0 +1,30 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + +common: + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +limits_config: + allow_structured_metadata: true + max_line_size: 256000 + retention_period: 168h + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h \ No newline at end of file diff --git a/infra/otel/RUNBOOKS.md b/infra/otel/RUNBOOKS.md new file mode 100644 index 0000000..b3bb73f --- /dev/null +++ b/infra/otel/RUNBOOKS.md @@ -0,0 +1,24 @@ +# Runbooks для инцидентов и алертов + +## 1. High API 5xx Error Ratio (`messenger-high-5xx`) +- **Условие:** доля 5xx по бизнес-эндпоинтам (исключая `/health/*`) превышает 5% за 1 минуту (`for: 15s`). +- **Шаги диагностики:** + 1. Открыть Grafana → Dashboard `MTUSI Messenger — Lab 6 Observability` → панель `API 5xx Error Ratio` и `DB Pool Saturation`. + 2. Проверить в Tempo (Explore → `{ resource.service.name = "messenger-api" && status = error }`) какой дочерний span упал или замедлился (`db.query`, `db.pool.connect`, `s3.put_staging`, `broker.ping`). + 3. Перейти по `trace_id` в Loki (`{service_name="messenger-api"} | trace_id="..."`) и проверить `error.code` / `request_id`. +- **Действия:** проверить состояние PostgreSQL / RustFS / Redis, при блокировках БД проверить `pg_stat_activity`. + +## 2. Growing Queue Lag (`messenger-queue-lag`) +- **Условие:** возраст старейшей незавершённой задачи `worker_oldest_job_age_seconds > 15s` (`for: 15s`). +- **Шаги диагностики:** + 1. Открыть панель `Queue Depth & Oldest Job Age` и `Worker Concurrency Saturation`. + 2. Если `worker_threads{state="busy"} == 0` при растущей очереди — процесс `worker` остановлен или потерял связь с брокером. + 3. Если `busy == capacity` и растёт `worker_job_duration_seconds` — нехватка CPU/конкурентности или тормозит S3/DB. + 4. Проверить логи `{service_name="messenger-worker"}` на события `worker.retry` и `worker.failed`. +- **Действия:** запустить/восстановить `worker`, проверить `attachment-jobs-dlq`, при необходимости увеличить `WORKER_CONCURRENCY`. + +## 3. API p95 Latency SLO Breach (`messenger-latency-slo`) +- **Условие:** `p95` по бизнес-эндпоинтам > 0.5 с за 1 минуту (`for: 30s`). +- **Шаги диагностики:** + 1. В Tempo найти медленные трассы (`duration > 500ms`). + 2. Отличить медленную БД (время внутри `db.query` / `db.pool.connect`) от медленного кода API (разрыв между длительностью корневого server span и дочерними зависимостями). \ No newline at end of file diff --git a/infra/otel/collector-tail-sampling.yaml b/infra/otel/collector-tail-sampling.yaml new file mode 100644 index 0000000..97af2cf --- /dev/null +++ b/infra/otel/collector-tail-sampling.yaml @@ -0,0 +1,100 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 180 + spike_limit_mib: 40 + attributes/redact: + actions: + - key: http.request.header.authorization + action: delete + - key: db.statement + action: delete + tail_sampling: + decision_wait: 2s + num_traces: 5000 + expected_new_traces_per_sec: 100 + policies: + - name: errors-policy + type: status_code + status_code: + status_codes: [ERROR] + - name: slow-traces-policy + type: latency + latency: + threshold_ms: 100 + - name: fast-sample-policy + type: probabilistic + probabilistic: + sampling_percentage: 10 + batch: + send_batch_size: 256 + timeout: 1s + +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + resource_to_telemetry_conversion: + enabled: true + metric_expiration: 5m + otlphttp/loki: + endpoint: http://loki:3100/otlp + tls: + insecure: true + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + otlp/tempo: + endpoint: tempo:4317 + tls: + insecure: true + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + +service: + extensions: [health_check] + telemetry: + metrics: + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, attributes/redact, batch] + exporters: [otlphttp/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, attributes/redact, tail_sampling, batch] + exporters: [otlp/tempo] \ No newline at end of file diff --git a/infra/otel/collector.yaml b/infra/otel/collector.yaml new file mode 100644 index 0000000..a5240e8 --- /dev/null +++ b/infra/otel/collector.yaml @@ -0,0 +1,83 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 180 + spike_limit_mib: 40 + attributes/redact: + actions: + - key: http.request.header.authorization + action: delete + - key: db.statement + action: delete + batch: + send_batch_size: 256 + timeout: 1s + +exporters: + prometheus: + endpoint: 0.0.0.0:8889 + resource_to_telemetry_conversion: + enabled: true + metric_expiration: 5m + otlphttp/loki: + endpoint: http://loki:3100/otlp + tls: + insecure: true + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + otlp/tempo: + endpoint: tempo:4317 + tls: + insecure: true + retry_on_failure: + enabled: true + initial_interval: 1s + max_interval: 5s + max_elapsed_time: 15s + sending_queue: + enabled: true + num_consumers: 2 + queue_size: 200 + +service: + extensions: [health_check] + telemetry: + metrics: + readers: + - pull: + exporter: + prometheus: + host: 0.0.0.0 + port: 8888 + pipelines: + metrics: + receivers: [otlp] + processors: [memory_limiter, batch] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, attributes/redact, batch] + exporters: [otlphttp/loki] + traces: + receivers: [otlp] + processors: [memory_limiter, attributes/redact, batch] + exporters: [otlp/tempo] \ No newline at end of file diff --git a/infra/prometheus/alerts.yml b/infra/prometheus/alerts.yml new file mode 100644 index 0000000..8f2719d --- /dev/null +++ b/infra/prometheus/alerts.yml @@ -0,0 +1,29 @@ +groups: + - name: messenger-slo-alerts + rules: + - alert: HighApiErrorRatio + expr: > + sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*",http_response_status_class="5xx"}[1m])) + / clamp_min(sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*"}[1m])), 0.001) > 0.05 + for: 15s + labels: + severity: critical + annotations: + summary: "High API 5xx error ratio (> 5%)" + runbook: "infra/otel/RUNBOOKS.md#1-high-api-5xx-error-ratio-messenger-high-5xx" + - alert: GrowingQueueLag + expr: max(worker_oldest_job_age_seconds{queue_name="attachment-jobs"}) > 15 + for: 15s + labels: + severity: warning + annotations: + summary: "Oldest attachment job age exceeds 15s" + runbook: "infra/otel/RUNBOOKS.md#2-growing-queue-lag-messenger-queue-lag" + - alert: ApiLatencySloBreach + expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api",http_route!~"/health/.*"}[1m]))) > 0.5 + for: 30s + labels: + severity: warning + annotations: + summary: "API p95 latency exceeds 500ms SLO" + runbook: "infra/otel/RUNBOOKS.md#3-api-p95-latency-slo-breach-messenger-latency-slo" \ No newline at end of file diff --git a/infra/prometheus/prometheus.yml b/infra/prometheus/prometheus.yml new file mode 100644 index 0000000..1ae9d26 --- /dev/null +++ b/infra/prometheus/prometheus.yml @@ -0,0 +1,14 @@ +global: + scrape_interval: 5s + evaluation_interval: 5s + +rule_files: + - /etc/prometheus/alerts.yml + +scrape_configs: + - job_name: otel-pipeline + static_configs: + - targets: ['otel-collector:8889'] + - job_name: otel-collector-internal + static_configs: + - targets: ['otel-collector:8888'] \ No newline at end of file diff --git a/infra/rustfs-policy.json b/infra/rustfs-policy.json new file mode 100644 index 0000000..21982c0 --- /dev/null +++ b/infra/rustfs-policy.json @@ -0,0 +1 @@ +{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::messenger-attachments/*"]},{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::messenger-attachments"]}]} diff --git a/infra/tempo/tempo.yaml b/infra/tempo/tempo.yaml new file mode 100644 index 0000000..47e0058 --- /dev/null +++ b/infra/tempo/tempo.yaml @@ -0,0 +1,27 @@ +server: + http_listen_port: 3200 + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +ingester: + trace_idle_period: 5s + max_block_duration: 1m + +compactor: + compaction: + block_retention: 48h + +storage: + trace: + backend: local + local: + path: /var/tempo/traces + wal: + path: /var/tempo/wal \ No newline at end of file diff --git a/migrations/001_initial.sql b/migrations/001_initial.sql new file mode 100644 index 0000000..7690b55 --- /dev/null +++ b/migrations/001_initial.sql @@ -0,0 +1,36 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, username text NOT NULL UNIQUE CHECK(username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK(length(btrim(display_name))>0 AND length(display_name)<=100), + password_hash text NOT NULL, created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE TABLE chats (id uuid PRIMARY KEY, title text NOT NULL CHECK(length(btrim(title))>0 AND length(title)<=100), created_at timestamptz NOT NULL DEFAULT clock_timestamp()); +CREATE TABLE members (chat_id uuid REFERENCES chats ON DELETE CASCADE, user_id uuid REFERENCES users, PRIMARY KEY(chat_id,user_id)); +CREATE INDEX members_user ON members(user_id,chat_id); +CREATE TABLE attachments ( + id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, owner_id uuid NOT NULL REFERENCES users, + object_key text NOT NULL UNIQUE, filename text NOT NULL, content_type text NOT NULL, + size_bytes bigint NOT NULL, sha256 char(64) NOT NULL, status text NOT NULL CHECK(status IN ('queued','processing','ready','failed')), + error_code text, staging_key text NOT NULL, + variants jsonb NOT NULL DEFAULT '[]'::jsonb, + pipeline_version integer NOT NULL DEFAULT 1, + created_at timestamptz NOT NULL DEFAULT clock_timestamp(), updated_at timestamptz NOT NULL DEFAULT clock_timestamp() +); +CREATE INDEX attachments_chat ON attachments(chat_id,id); +CREATE TABLE messages (id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats, sender_id uuid NOT NULL REFERENCES users, text text NOT NULL CHECK(length(text)<=4000), created_at timestamptz NOT NULL DEFAULT clock_timestamp()); +CREATE TABLE message_attachments (message_id uuid REFERENCES messages ON DELETE CASCADE, attachment_id uuid REFERENCES attachments, position smallint NOT NULL, PRIMARY KEY(message_id,attachment_id), UNIQUE(message_id,position)); +CREATE INDEX messages_history ON messages(chat_id,created_at,id); +CREATE TABLE sessions (token_hash text PRIMARY KEY, user_id uuid NOT NULL REFERENCES users, expires_at timestamptz NOT NULL); +CREATE INDEX sessions_expiry ON sessions(expires_at); +CREATE TABLE attachment_jobs ( + job_id uuid PRIMARY KEY, attachment_id uuid NOT NULL REFERENCES attachments(id), + pipeline_version integer NOT NULL, attempt integer NOT NULL DEFAULT 0, + state text NOT NULL DEFAULT 'pending' CHECK(state IN ('pending','published','processing','failed','done')), + available_at timestamptz NOT NULL DEFAULT clock_timestamp(), lease_until timestamptz, + last_error text, created_at timestamptz NOT NULL DEFAULT clock_timestamp(), + UNIQUE(attachment_id,pipeline_version) +); +CREATE INDEX attachment_jobs_pending ON attachment_jobs(available_at) WHERE state IN ('pending','published','processing'); +CREATE TABLE attachment_job_audit ( + id bigserial PRIMARY KEY, job_id uuid NOT NULL REFERENCES attachment_jobs(job_id), + event text NOT NULL, detail text, created_at timestamptz NOT NULL DEFAULT clock_timestamp() +); diff --git a/migrations/002_idempotency.sql b/migrations/002_idempotency.sql new file mode 100644 index 0000000..3fa0f8d --- /dev/null +++ b/migrations/002_idempotency.sql @@ -0,0 +1,6 @@ +CREATE TABLE idempotency ( + user_id uuid NOT NULL REFERENCES users, chat_id uuid NOT NULL REFERENCES chats, + key varchar(128) NOT NULL, body text NOT NULL, response jsonb NOT NULL, + expires_at timestamptz NOT NULL, PRIMARY KEY(user_id,chat_id,key) +); +CREATE INDEX idempotency_expiry ON idempotency(expires_at); diff --git a/migrations/003_trace_context.sql b/migrations/003_trace_context.sql new file mode 100644 index 0000000..e9c14ed --- /dev/null +++ b/migrations/003_trace_context.sql @@ -0,0 +1,3 @@ +ALTER TABLE attachment_jobs + ADD COLUMN IF NOT EXISTS traceparent text, + ADD COLUMN IF NOT EXISTS tracestate text; diff --git a/requirements.lock b/requirements.lock new file mode 100644 index 0000000..a5caeba --- /dev/null +++ b/requirements.lock @@ -0,0 +1,31 @@ +argon2-cffi==25.1.0 +argon2-cffi-bindings==26.1.0 +blinker==1.9.0 +cffi==2.1.1 +click==8.5.0 +Flask==3.1.2 +gunicorn==23.0.0 +itsdangerous==2.2.0 +Jinja2==3.1.6 +MarkupSafe==3.0.4 +packaging==26.3 +psycopg==3.2.10 +psycopg-binary==3.2.10 +psycopg-pool==3.3.3 +redis==6.4.0 +typing_extensions==4.16.0 +Werkzeug==3.1.9 +boto3==1.40.55 +botocore==1.40.55 +jmespath==1.0.1 +Pillow==11.3.0 +python-dateutil==2.9.0.post0 +s3transfer==0.14.0 +six==1.17.0 +urllib3==2.5.0 +opentelemetry-api==1.39.1 +opentelemetry-sdk==1.39.1 +opentelemetry-semantic-conventions==0.60b1 +opentelemetry-exporter-otlp-proto-common==1.39.1 +opentelemetry-exporter-otlp-proto-http==1.39.1 +opentelemetry-proto==1.39.1 diff --git a/scripts/bootstrap.py b/scripts/bootstrap.py new file mode 100644 index 0000000..48762ea --- /dev/null +++ b/scripts/bootstrap.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Create local-only secret files once; do not print their values.""" +from pathlib import Path +import secrets + +root = Path(__file__).resolve().parents[1] +d = root / 'secrets' +d.mkdir(mode=0o700, exist_ok=True) +d.chmod(0o700) + +def safe_token(n=32): + first = secrets.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') + return first + secrets.token_urlsafe(n) + +def ensure(name, value): + p = d / name + if not p.exists(): + p.write_text(value, encoding='utf-8', newline='\n') + p.chmod(0o600) + +ensure('db_password', safe_token(32)) +ensure('rustfs_root_user', 'RUSTFSROOT') +ensure('rustfs_root_password', safe_token(32)) +ensure('s3_access_key_id', 'messengerapi') +ensure('s3_secret_access_key', safe_token(40)) +ensure('grafana_admin_password', safe_token(24)) +ensure( + 'database_url', + 'postgresql://messenger:' + (d / 'db_password').read_text(encoding='utf-8').strip() + '@postgres:5432/messenger', +) +ensure('cache_url', 'redis://redis:6379/0') +ensure('broker_url', 'redis://broker:6379/0') + +env = root / '.env' +if not env.exists(): + env.write_text( + 'API_REPLICAS=2\n' + 'APP_PORT=8081\n' + 'GRAFANA_PORT=3000\n' + 'SESSION_TTL_SECONDS=3600\n' + 'WORKER_CONCURRENCY=2\n' + 'MAX_QUEUED_JOBS=500\n' + 'JOB_MAX_ATTEMPTS=5\n' + 'JOB_TIMEOUT_SECONDS=60\n' + 'OTEL_SDK_DISABLED=false\n' + 'OTEL_TRACES_SAMPLER=always_on\n' + 'OTEL_TRACES_SAMPLER_ARG=1.0\n' + 'OTEL_COLLECTOR_CONFIG=./infra/otel/collector.yaml\n', + encoding='utf-8', + newline='\n', + ) +env.chmod(0o600) +print('Local secrets created or preserved; values hidden.') diff --git a/scripts/replay_failed.py b/scripts/replay_failed.py new file mode 100644 index 0000000..e6472b1 --- /dev/null +++ b/scripts/replay_failed.py @@ -0,0 +1,18 @@ +"""Explicitly replay one terminal failed attachment job, never a ready job.""" +import sys, uuid +from pathlib import Path +sys.path.insert(0,str(Path(__file__).resolve().parents[1])) +from app.migrate import setting +import psycopg + +if len(sys.argv)!=2: + raise SystemExit('usage: python scripts/replay_failed.py ATTACHMENT_UUID') +aid=str(uuid.UUID(sys.argv[1])) +with psycopg.connect(setting('DATABASE_URL')) as c: + row=c.execute("SELECT j.job_id,j.state,a.status FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE a.id=%s FOR UPDATE OF j,a",(aid,)).fetchone() + if not row or row[1]!='failed' or row[2]!='failed': + raise SystemExit('replay refused: attachment must be terminal failed') + c.execute("UPDATE attachment_jobs SET state='pending',attempt=0,available_at=clock_timestamp(),lease_until=NULL,last_error=NULL WHERE job_id=%s",(row[0],)) + c.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=%s",(aid,)) + c.execute("INSERT INTO attachment_job_audit(job_id,event,detail) VALUES (%s,'operator_replay','explicit replay command')",(row[0],)) +print('failed job queued for explicit replay') diff --git a/scripts/restart.bat b/scripts/restart.bat new file mode 100644 index 0000000..285f411 --- /dev/null +++ b/scripts/restart.bat @@ -0,0 +1 @@ +bash scripts/restart.sh diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 0000000..098e643 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +docker compose down +sleep 2 +docker compose up -d --no-build --pull never --wait --wait-timeout 90 diff --git a/scripts/stop-one.bat b/scripts/stop-one.bat new file mode 100644 index 0000000..cccaf7c --- /dev/null +++ b/scripts/stop-one.bat @@ -0,0 +1 @@ +bash scripts/stop-one.sh diff --git a/scripts/stop-one.sh b/scripts/stop-one.sh new file mode 100644 index 0000000..24954ab --- /dev/null +++ b/scripts/stop-one.sh @@ -0,0 +1,16 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +: "${TARGET_INSTANCE_ID:?Set TARGET_INSTANCE_ID from a real API response}" +for id in $(docker compose ps -q api); do + host=$(docker inspect -f '{{.Config.Hostname}}' "$id") + case "$TARGET_INSTANCE_ID" in + "$host"-*) + printf 'Stopping API container %s (hostname %s)\n' "$id" "$host" + docker stop --time 5 "$id" + docker inspect -f '{{.Id}} {{.State.Status}}' "$id" + exit 0;; + esac +done +printf 'No running API matches target\n' >&2 +exit 1 diff --git a/student-tests/grafana_helper.py b/student-tests/grafana_helper.py new file mode 100644 index 0000000..9ef1730 --- /dev/null +++ b/student-tests/grafana_helper.py @@ -0,0 +1,54 @@ +"""Grafana proxy helper for student observability verification (reads local secret, never prints it).""" +import base64 +import json +from pathlib import Path +import time +import urllib.parse +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] + +class GrafanaClient: + def __init__(self, base_url='http://localhost:3000'): + self.base = base_url.rstrip('/') + pw = (ROOT / 'secrets/grafana_admin_password').read_text(encoding='utf-8').strip() + auth = base64.b64encode(('admin:' + pw).encode('utf-8')).decode('ascii') + self.headers = {'Authorization': 'Basic ' + auth, 'Accept': 'application/json'} + + def get_json(self, path, timeout=10): + req = urllib.request.Request(self.base + path, headers=self.headers, method='GET') + with urllib.request.urlopen(req, timeout=timeout) as resp: + return json.loads(resp.read().decode('utf-8')) + + def wait_ready(self, timeout=90): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + health = self.get_json('/api/health', timeout=3) + req = urllib.request.Request(self.base + '/api/datasources/proxy/uid/tempo/ready', headers=self.headers) + with urllib.request.urlopen(req, timeout=3) as r: + tempo_ok = (r.code == 200) + if health.get('database') == 'ok' and tempo_ok: + return + except Exception: + pass + time.sleep(1.5) + raise RuntimeError('Grafana or Tempo datasource did not become ready within timeout') + + def prom_query(self, expr): + q = urllib.parse.urlencode({'query': expr}) + return self.get_json(f'/api/datasources/proxy/uid/prometheus/api/v1/query?{q}') + + def prom_rules(self): + return self.get_json('/api/datasources/proxy/uid/prometheus/api/v1/rules') + + def loki_query_range(self, query, start_ns, end_ns, limit=100): + q = urllib.parse.urlencode({'query': query, 'start': str(start_ns), 'end': str(end_ns), 'limit': str(limit)}) + return self.get_json(f'/api/datasources/proxy/uid/loki/loki/api/v1/query_range?{q}') + + def tempo_search(self, q, start_s, end_s, limit=20): + params = urllib.parse.urlencode({'q': q, 'start': str(int(start_s)), 'end': str(int(end_s)), 'limit': str(limit)}) + return self.get_json(f'/api/datasources/proxy/uid/tempo/api/search?{params}') + + def tempo_trace(self, trace_id): + return self.get_json(f'/api/datasources/proxy/uid/tempo/api/traces/{trace_id}') \ No newline at end of file diff --git a/student-tests/incident_suite.py b/student-tests/incident_suite.py new file mode 100644 index 0000000..7d76df6 --- /dev/null +++ b/student-tests/incident_suite.py @@ -0,0 +1,208 @@ +#!/usr/bin/env python3 +"""Controlled Level 4 incidents: (1) worker stop -> alert firing/resolved; (2) slow DB vs slow handler; (3) telemetry outage.""" +from concurrent.futures import ThreadPoolExecutor +import json +import os +from pathlib import Path +import subprocess +import sys +import threading +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +sys.path.insert(0, str(ROOT / 'student-tests')) + +from client import Client, check +from grafana_helper import GrafanaClient + +def compose(*args, env_extra=None): + env = os.environ.copy() + if env_extra: + env.update(env_extra) + subprocess.run(['docker', 'compose', *args], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + +def alert_state(g, name): + rules = g.prom_rules().get('data', {}).get('groups', []) + for grp in rules: + for r in grp.get('rules', []): + if r.get('name') == name: + return r.get('state') + return 'missing' + +def prom_scalar(g, expr): + res = g.prom_query(expr).get('data', {}).get('result', []) + return float(res[0]['value'][1]) if res else 0.0 + +def wait_api_ready(c, timeout=45): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + c.call('GET', '/health/ready', schema='Health') + time.sleep(2) + return + except Exception: + time.sleep(0.5) + raise RuntimeError('API did not become ready') + +def incident_1_worker_outage(g, c, alice, bob, chat): + print('Running Incident 1: Worker outage -> GrowingQueueLag firing & resolved...') + compose('stop', 'worker') + att, _ = c.attachment(alice, chat) + firing_seen = False + deadline = time.monotonic() + 75 + try: + while time.monotonic() < deadline: + if alert_state(g, 'GrowingQueueLag') == 'firing': + firing_seen = True + break + time.sleep(2) + check(firing_seen, 'GrowingQueueLag alert did not reach firing state') + finally: + compose('up', '-d', 'worker') + c.wait_ready(bob, att, wait_seconds=60) + resolved_seen = False + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + if alert_state(g, 'GrowingQueueLag') == 'inactive': + resolved_seen = True + break + time.sleep(2) + check(resolved_seen, 'GrowingQueueLag alert did not resolve after worker recovery') + return {'alert': 'GrowingQueueLag', 'firing_observed': firing_seen, 'resolved_observed': resolved_seen, 'attachment_status': 'ready'} + +def incident_2_slow_db_vs_handler(g, c, alice, chat): + print('Running Incident 2: Slow DB (lock contention + 503) vs Slow HTTP handler...') + t0 = time.time() + def hold_lock(): + subprocess.run( + ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', + 'BEGIN; LOCK TABLE messages IN SHARE MODE; SELECT pg_sleep(1.3); COMMIT;'], + cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + th = threading.Thread(target=hold_lock) + th.start() + time.sleep(0.25) + r_db = c.message(alice, chat, 'slow-db-check') + th.join(timeout=10) + db_req_ms = round(r_db['elapsed'] * 1000, 1) + + # Hold lock > 2s lock_timeout and send 3 parallel requests so all 3 hit real DB 503 timeouts + def hold_timeout_lock(): + subprocess.run( + ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', + 'BEGIN; LOCK TABLE messages IN SHARE MODE; SELECT pg_sleep(3.5); COMMIT;'], + cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, + ) + th2 = threading.Thread(target=hold_timeout_lock) + th2.start() + time.sleep(0.3) + def send_503(idx): + local = Client('http://localhost:8081', timeout=10) + return local.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 503, actor=alice, body={'text': f'lock-timeout-{idx}'}, headers={'Idempotency-Key': f'lock-timeout-{int(t0)}-{idx}'})['status'] + with ThreadPoolExecutor(max_workers=3) as ex: + statuses_503 = list(ex.map(send_503, range(3))) + th2.join(timeout=10) + + error_firing = False + deadline = time.monotonic() + 60 + while time.monotonic() < deadline: + if alert_state(g, 'HighApiErrorRatio') == 'firing': + error_firing = True + break + time.sleep(2) + check(error_firing, 'HighApiErrorRatio alert did not fire after 503 DB timeouts') + + # Now induce slow HTTP handler (outside DB) on api replicas temporarily + compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={'FAULT_HANDLER_DELAY_MS': '650'}) + wait_api_ready(c) + r_handler = c.message(alice, chat, 'slow-handler-check') + handler_req_ms = round(r_handler['elapsed'] * 1000, 1) + compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={'FAULT_HANDLER_DELAY_MS': '0'}) + wait_api_ready(c) + + time.sleep(8) + search = g.tempo_search('{ resource.service.name = "messenger-api" && duration > 500ms }', t0 - 5, time.time() + 5, limit=30) + slow_traces = search.get('traces', []) + db_dominant_trace = None + handler_dominant_trace = None + for item in slow_traces: + tr = g.tempo_trace(item['traceID']) + root_ms = 0.0 + db_ms = 0.0 + for b in tr.get('batches', []): + for ss in b.get('scopeSpans', []): + for sp in ss.get('spans', []): + dur_ms = (int(sp['endTimeUnixNano']) - int(sp['startTimeUnixNano'])) / 1e6 + if sp.get('name', '').startswith('POST /api/v1/chats/{chat_id}/messages'): + root_ms = max(root_ms, dur_ms) + if sp.get('name') == 'db.query': + db_ms += dur_ms + if root_ms > 500: + if db_ms > root_ms * 0.6: + db_dominant_trace = {'trace_id': item['traceID'], 'root_ms': round(root_ms, 1), 'db_query_ms': round(db_ms, 1)} + elif db_ms < root_ms * 0.25: + handler_dominant_trace = {'trace_id': item['traceID'], 'root_ms': round(root_ms, 1), 'db_query_ms': round(db_ms, 1)} + + check(db_dominant_trace is not None and handler_dominant_trace is not None, 'could not distinguish slow DB vs slow HTTP handler in Tempo traces') + return { + 'slow_db_request_ms': db_req_ms, + 'db_timeout_statuses': statuses_503, + 'slow_handler_request_ms': handler_req_ms, + 'high_api_error_ratio_fired': error_firing, + 'db_dominant_trace': db_dominant_trace, + 'handler_dominant_trace': handler_dominant_trace, + } + +def incident_3_telemetry_outage(g, c, alice, bob, chat): + print('Running Incident 3: Telemetry backend outage (Tempo & Loki stopped) -> API works & bounded RAM...') + failed_spans_before = prom_scalar(g, 'sum(otelcol_exporter_send_failed_spans_total)') + failed_logs_before = prom_scalar(g, 'sum(otelcol_exporter_send_failed_log_records_total)') + compose('stop', 'tempo', 'loki') + try: + before_mem = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', 'mtusi_lab6_solution-otel-collector-1'], text=True).strip() + for i in range(15): + r = c.message(alice, chat, f'outage-msg-{i}') + check(r['status'] == 201, 'API failed while telemetry backends were stopped') + att, _ = c.attachment(alice, chat) + ready = c.wait_ready(bob, att, wait_seconds=45) + check(ready['status'] == 'ready', 'worker failed while telemetry backends were stopped') + time.sleep(20) + after_mem = subprocess.check_output(['docker', 'stats', '--no-stream', '--format', '{{.MemUsage}}', 'mtusi_lab6_solution-otel-collector-1'], text=True).strip() + failed_spans_after = prom_scalar(g, 'sum(otelcol_exporter_send_failed_spans_total)') + failed_logs_after = prom_scalar(g, 'sum(otelcol_exporter_send_failed_log_records_total)') + finally: + compose('up', '-d', 'loki', 'tempo') + g.wait_ready(timeout=60) + return { + 'messages_succeeded_during_outage': 15, + 'attachment_ready_during_outage': True, + 'collector_mem_before': before_mem, + 'collector_mem_during_outage': after_mem, + 'collector_send_failed_spans_delta': round(failed_spans_after - failed_spans_before), + 'collector_send_failed_logs_delta': round(failed_logs_after - failed_logs_before), + 'api_preserved': True, + } + +def main(): + g = GrafanaClient('http://localhost:3000') + g.wait_ready(timeout=90) + c = Client('http://localhost:8081') + alice, bob, _, chat = c.bootstrap() + + res1 = incident_1_worker_outage(g, c, alice, bob, chat) + res2 = incident_2_slow_db_vs_handler(g, c, alice, chat) + res3 = incident_3_telemetry_outage(g, c, alice, bob, chat) + + report = { + 'incident_1_worker_outage': res1, + 'incident_2_slow_db_vs_handler': res2, + 'incident_3_telemetry_backend_outage': res3, + 'result': 'PASS', + } + dest = ROOT / 'evidence/lab6-incidents.json' + dest.write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n', encoding='utf-8') + print(json.dumps(report, indent=2, ensure_ascii=False)) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/student-tests/track1_cost_of_observability.py b/student-tests/track1_cost_of_observability.py new file mode 100644 index 0000000..298a6e4 --- /dev/null +++ b/student-tests/track1_cost_of_observability.py @@ -0,0 +1,250 @@ +#!/usr/bin/env python3 +"""Track 1: Cost of Observability across off, always_on 100%, head 10%, and balanced tail-sampling.""" +from concurrent.futures import ThreadPoolExecutor +import json +import math +import os +from pathlib import Path +import subprocess +import sys +import threading +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +sys.path.insert(0, str(ROOT / 'student-tests')) + +from client import Client, Failure +from grafana_helper import GrafanaClient + +PROFILES = [ + { + 'name': 'telemetry_off', + 'env': { + 'OTEL_SDK_DISABLED': 'true', + 'OTEL_TRACES_SAMPLER': 'always_off', + 'OTEL_TRACES_SAMPLER_ARG': '0.0', + 'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml', + }, + }, + { + 'name': 'always_on_100pct', + 'env': { + 'OTEL_SDK_DISABLED': 'false', + 'OTEL_TRACES_SAMPLER': 'always_on', + 'OTEL_TRACES_SAMPLER_ARG': '1.0', + 'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml', + }, + }, + { + 'name': 'head_sampling_10pct', + 'env': { + 'OTEL_SDK_DISABLED': 'false', + 'OTEL_TRACES_SAMPLER': 'parentbased_traceidratio', + 'OTEL_TRACES_SAMPLER_ARG': '0.1', + 'OTEL_COLLECTOR_CONFIG': './infra/otel/collector.yaml', + }, + }, + { + 'name': 'tail_sampling_balanced', + 'env': { + 'OTEL_SDK_DISABLED': 'false', + 'OTEL_TRACES_SAMPLER': 'always_on', + 'OTEL_TRACES_SAMPLER_ARG': '1.0', + 'OTEL_COLLECTOR_CONFIG': './infra/otel/collector-tail-sampling.yaml', + }, + }, +] + +def compose(*args, env_extra=None): + env = os.environ.copy() + if env_extra: + env.update(env_extra) + subprocess.run(['docker', 'compose', *args], cwd=ROOT, env=env, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + +def wait_api_ready(c, timeout=45): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + c.call('GET', '/health/ready', schema='Health') + time.sleep(2) + return + except Exception: + time.sleep(0.5) + raise RuntimeError('API did not become ready') + +def prom_scalar(g, expr): + res = g.prom_query(expr).get('data', {}).get('result', []) + return float(res[0]['value'][1]) if res else 0.0 + +def sample_stats(): + out = subprocess.check_output( + ['docker', 'stats', '--no-stream', '--format', '{{.Name}}|{{.CPUPerc}}|{{.MemUsage}}', + 'mtusi_lab6_solution-api-1', 'mtusi_lab6_solution-api-2', 'mtusi_lab6_solution-otel-collector-1'], + text=True, + ).strip().splitlines() + parsed = {} + for line in out: + name, cpu, mem = line.split('|') + short = name.replace('mtusi_lab6_solution-', '') + parsed[short] = {'cpu_pct': float(cpu.strip().rstrip('%') or 0.0), 'mem': mem.split('/')[0].strip()} + return parsed + +def trigger_503_batch(alice, chat, tag, count=5): + proc = subprocess.Popen( + ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-U', 'messenger', '-d', 'messenger', '-Atq'], + cwd=ROOT, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, + ) + assert proc.stdin and proc.stdout + proc.stdin.write("BEGIN;\nLOCK TABLE messages IN SHARE MODE;\nSELECT 'LOCKED_NOW';\n") + proc.stdin.flush() + while True: + line = proc.stdout.readline() + if not line or 'LOCKED_NOW' in line: + break + def send_one(idx): + local = Client('http://localhost:8081', timeout=10) + try: + res = local.call('POST', f'/api/v1/chats/{chat["id"]}/messages', 503, actor=alice, body={'text': f'err-{tag}-{idx}'}, headers={'Idempotency-Key': f'err-{tag}-{idx}'}) + return res['status'] + except Failure: + return 0 + with ThreadPoolExecutor(max_workers=count) as ex: + statuses = list(ex.map(send_one, range(count))) + proc.stdin.write("COMMIT;\n\\q\n") + proc.stdin.flush() + proc.communicate(timeout=10) + return sum(1 for s in statuses if s == 503) + +def run_profile(g, prof, duration=20, concurrency=6): + print(f'=== Running Track 1 profile: {prof["name"]} ===') + compose('up', '-d', '--force-recreate', 'otel-collector', env_extra=prof['env']) + compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', 'worker', env_extra=prof['env']) + c = Client('http://localhost:8081') + wait_api_ready(c) + + alice, _, _, chat = c.bootstrap() + for i in range(10): + c.message(alice, chat, f'warmup-{i}') + time.sleep(8) + + accepted_before = prom_scalar(g, 'sum(otelcol_receiver_accepted_spans_total)') + sent_before = prom_scalar(g, 'sum(otelcol_exporter_sent_spans_total)') + + samples = [] + stop_sample = threading.Event() + def sampler(): + while not stop_sample.is_set(): + try: + samples.append(sample_stats()) + except Exception: + pass + stop_sample.wait(5) + + sam_th = threading.Thread(target=sampler, daemon=True) + sam_th.start() + + barrier = threading.Barrier(concurrency) + def worker_fn(wid): + local = Client('http://localhost:8081', timeout=5) + barrier.wait() + deadline = time.monotonic() + duration + lats = [] + errs = 0 + idx = 0 + while time.monotonic() < deadline: + t = time.monotonic() + try: + local.message(alice, chat, f't1-{prof["name"]}-{wid}-{idx}') + lats.append(time.monotonic() - t) + except Failure: + errs += 1 + idx += 1 + return lats, errs + + t_start = time.time() + with ThreadPoolExecutor(max_workers=concurrency) as ex: + results = list(ex.map(worker_fn, range(concurrency))) + elapsed = time.time() - t_start + stop_sample.set() + sam_th.join(timeout=6) + + err_captured = 0 + slow_captured = 0 + err_injected = 0 + if prof['name'] != 'telemetry_off': + compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={**prof['env'], 'FAULT_HANDLER_DELAY_MS': '200'}) + wait_api_ready(c) + t_slow_start = time.time() + for k in range(5): + c.message(alice, chat, f'slow-{prof["name"]}-{k}') + t_slow_end = time.time() + compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', env_extra={**prof['env'], 'FAULT_HANDLER_DELAY_MS': '0'}) + wait_api_ready(c) + + t_err_start = time.time() + err_injected += trigger_503_batch(alice, chat, f'{prof["name"]}-b0', count=5) + err_injected += trigger_503_batch(alice, chat, f'{prof["name"]}-b1', count=5) + t_err_end = time.time() + + time.sleep(10) + err_res = g.tempo_search('{ resource.service.name = "messenger-api" && status = error }', t_err_start - 5, t_err_end + 15, limit=50) + err_captured = len(err_res.get('traces', [])) + slow_res = g.tempo_search('{ resource.service.name = "messenger-api" && duration > 150ms && status != error }', t_slow_start - 5, t_slow_end + 15, limit=50) + slow_captured = len(slow_res.get('traces', [])) + else: + time.sleep(8) + + accepted_after = prom_scalar(g, 'sum(otelcol_receiver_accepted_spans_total)') + sent_after = prom_scalar(g, 'sum(otelcol_exporter_sent_spans_total)') + accepted_delta = max(0, round(accepted_after - accepted_before)) + sent_delta = max(0, round(sent_after - sent_before)) + drop_ratio = max(0.0, round(1.0 - (sent_delta / accepted_delta), 4)) if accepted_delta > 0 else 0.0 + + lats = sorted(x for ls, _ in results for x in ls) + errs = sum(e for _, e in results) + def pct(p): + return round(1000 * lats[max(0, math.ceil(p * len(lats)) - 1)], 2) if lats else None + + avg_cpu = {} + last_mem = {} + if samples: + for k in samples[0]: + avg_cpu[k] = round(sum(s[k]['cpu_pct'] for s in samples if k in s) / len(samples), 2) + last_mem[k] = samples[-1].get(k, {}).get('mem') + + return { + 'profile': prof['name'], + 'duration_seconds': duration, + 'concurrency': concurrency, + 'successful_requests': len(lats), + 'failed_requests': errs, + 'rps': round(len(lats) / elapsed, 2), + 'latency_ms': {'p50': pct(0.50), 'p95': pct(0.95), 'p99': pct(0.99)}, + 'collector_spans_accepted': accepted_delta, + 'tempo_spans_exported': sent_delta, + 'span_drop_ratio': drop_ratio, + 'injected_5xx_errors_captured': f'{min(err_injected, err_captured)}/{err_injected}' if prof['name'] != 'telemetry_off' else '0/10 (disabled)', + 'injected_slow_gt150ms_captured': f'{min(5, slow_captured)}/5' if prof['name'] != 'telemetry_off' else '0/5 (disabled)', + 'avg_cpu_pct_under_load': avg_cpu, + 'mem_under_load': last_mem, + } + +def main(): + g = GrafanaClient('http://localhost:3000') + g.wait_ready(timeout=90) + results = [] + try: + for prof in PROFILES: + results.append(run_profile(g, prof)) + finally: + compose('up', '-d', '--force-recreate', 'otel-collector', env_extra=PROFILES[3]['env']) + compose('up', '-d', '--force-recreate', '--wait', '--scale', 'api=2', 'api', 'worker', env_extra=PROFILES[3]['env']) + + summary = {'track': 'cost-of-observability', 'profiles': results} + dest = ROOT / 'evidence/track1-observability-cost.json' + dest.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n', encoding='utf-8') + print(json.dumps(summary, indent=2, ensure_ascii=False)) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/student-tests/verify_lab6_signals.py b/student-tests/verify_lab6_signals.py new file mode 100644 index 0000000..781a28e --- /dev/null +++ b/student-tests/verify_lab6_signals.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Verify Level 3+4 observability signals, redaction, and end-to-end API->Worker trace correlation.""" +import json +from pathlib import Path +import sys +import time +import uuid + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / 'tests')) +sys.path.insert(0, str(ROOT / 'student-tests')) + +from client import Client, check +from grafana_helper import GrafanaClient + +def extract_spans(trace_json): + spans = [] + for batch in trace_json.get('batches', []): + svc = 'unknown' + for attr in batch.get('resource', {}).get('attributes', []): + if attr.get('key') == 'service.name': + svc = attr.get('value', {}).get('stringValue', 'unknown') + for ss in batch.get('scopeSpans', []): + for sp in ss.get('spans', []): + attrs = {a['key']: a.get('value', {}) for a in sp.get('attributes', [])} + spans.append({ + 'service': svc, + 'name': sp.get('name'), + 'span_id': sp.get('spanId'), + 'parent_span_id': sp.get('parentSpanId'), + 'attrs': attrs, + }) + return spans + +def main(): + g = GrafanaClient('http://localhost:3000') + g.wait_ready(timeout=90) + c = Client('http://localhost:8081') + + t_start = time.time() + alice, bob, _, chat = c.bootstrap() + secret_marker = 'SECRET_MSG_BODY_MUST_NOT_LEAK_' + uuid.uuid4().hex[:8] + c.message(alice, chat, secret_marker) + att, _ = c.attachment(alice, chat) + ready = c.wait_ready(bob, att, wait_seconds=60) + check(ready['status'] == 'ready', 'attachment did not finish') + + # Wait for BatchSpanProcessor + PeriodicMetricReader + Prometheus scrape + time.sleep(12) + + # 1. Verify dashboard provisioned in Grafana + dash = g.get_json('/api/dashboards/uid/mtusi-lab6-obs') + check(dash['dashboard']['uid'] == 'mtusi-lab6-obs', 'dashboard not provisioned') + + # 2. Verify required metrics exist and have NO forbidden high-cardinality labels + forbidden = {'user_id', 'chat_id', 'message_id', 'attachment_id', 'request_id', 'filename', 'text'} + required_metrics = [ + 'http_server_requests_total', + 'http_server_request_duration_seconds_bucket', + 'worker_jobs_total', + 'worker_job_duration_seconds_bucket', + 'attachment_time_to_ready_seconds_bucket', + 'worker_queue_depth', + 'worker_oldest_job_age_seconds', + 'db_pool_connections', + 'worker_threads', + 'process_memory_rss_bytes', + ] + metric_counts = {} + for m in required_metrics: + res = g.prom_query(m) + series = res.get('data', {}).get('result', []) + if not series: + all_names = g.get_json('/api/datasources/proxy/uid/prometheus/api/v1/label/__name__/values').get('data', []) + print('Available app metrics:', [x for x in all_names if any(x.startswith(p) for p in ('http_', 'worker_', 'attachment_', 'db_', 'process_', 'otelcol_'))]) + check(len(series) > 0, f'missing Prometheus metric: {m}') + for s in series: + bad = forbidden.intersection(s.get('metric', {}).keys()) + check(not bad, f'forbidden high-cardinality labels on {m}: {bad}') + metric_counts[m] = len(series) + + # 3. Verify end-to-end trace across messenger-api and messenger-worker in Tempo + traces = [] + for _ in range(15): + search = g.tempo_search('{ resource.service.name = "messenger-worker" && name = "worker.process" }', t_start - 5, time.time() + 5, limit=20) + traces = search.get('traces', []) + if traces: + break + time.sleep(1.5) + check(len(traces) > 0, 'no worker.process trace found in Tempo') + + matched_trace_id = None + matched_spans = [] + for item in traces: + tid = item['traceID'] + tr = g.tempo_trace(tid) + spans = extract_spans(tr) + services = {s['service'] for s in spans} + names = {s['name'] for s in spans} + if 'messenger-api' in services and 'messenger-worker' in services and 'outbox.publish' in names and 'worker.process' in names: + matched_trace_id = tid + matched_spans = spans + break + check(matched_trace_id is not None, 'no unified W3C trace linking messenger-api -> outbox.publish -> worker.process found') + + # 4. Verify correlated structured logs in Loki and zero secret/body leaks + ns_start = int((t_start - 5) * 1e9) + ns_end = int((time.time() + 5) * 1e9) + api_logs = g.loki_query_range('{service_name="messenger-api"}', ns_start, ns_end, limit=200) + worker_logs = g.loki_query_range('{service_name="messenger-worker"}', ns_start, ns_end, limit=200) + api_streams = api_logs.get('data', {}).get('result', []) + worker_streams = worker_logs.get('data', {}).get('result', []) + check(len(api_streams) > 0 and len(worker_streams) > 0, 'missing structured logs in Loki') + + all_log_text = json.dumps(api_streams + worker_streams, ensure_ascii=False) + check(secret_marker not in all_log_text, 'LEAK: message text appeared in Loki logs') + check(alice['token'] not in all_log_text, 'LEAK: session token appeared in Loki logs') + check(alice['registration']['password'] not in all_log_text, 'LEAK: password appeared in Loki logs') + + correlated = [s for s in (api_streams + worker_streams) if s.get('stream', {}).get('trace_id') == matched_trace_id or any(matched_trace_id in v[1] for v in s.get('values', []))] + check(len(correlated) > 0, f'no Loki logs correlated to trace_id={matched_trace_id}') + + summary = { + 'status': 'PASS', + 'verified_metrics': metric_counts, + 'e2e_trace_id': matched_trace_id, + 'e2e_span_services': sorted({s['service'] for s in matched_spans}), + 'e2e_span_names': sorted({s['name'] for s in matched_spans}), + 'loki_api_streams': len(api_streams), + 'loki_worker_streams': len(worker_streams), + 'loki_correlated_entries': len(correlated), + 'redaction_checks': {'message_body_leaked': False, 'token_leaked': False, 'password_leaked': False}, + } + dest = ROOT / 'evidence/lab6-signals.json' + dest.parent.mkdir(parents=True, exist_ok=True) + dest.write_text(json.dumps(summary, indent=2, ensure_ascii=False) + '\n', encoding='utf-8') + print(json.dumps(summary, indent=2, ensure_ascii=False)) + +if __name__ == '__main__': + main() \ No newline at end of file