forked from mtusi2026/mtusi2026lab6
Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4f0f155af6 | ||
|
|
32bbd25143 | ||
|
|
55057eab6e | ||
|
|
d169076e30 | ||
|
|
1be8f323a5 | ||
|
|
13d4411534 | ||
|
|
a55e0e60c0 | ||
|
|
b6a7a85ed3 | ||
|
|
dc6a7210e4 | ||
|
|
72a84fcb0c | ||
|
|
2538f8a914 | ||
|
|
59279649f4 | ||
|
|
d29163bed4 | ||
|
|
468913998e | ||
|
|
03a4146a62 | ||
|
|
42ecae645b | ||
|
|
b91dcff42a |
@@ -46,6 +46,9 @@ JOB_TIMEOUT_SECONDS=60
|
|||||||
STAGING_RETENTION_SECONDS=86400
|
STAGING_RETENTION_SECONDS=86400
|
||||||
OTEL_SERVICE_NAME=messenger-api
|
OTEL_SERVICE_NAME=messenger-api
|
||||||
# Worker must set a distinct service.name.
|
# Worker must set a distinct service.name.
|
||||||
|
|
||||||
|
OTEL_SERVICE_NAME=messenger-api
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
|
||||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||||
|
GRAFANA_ADMIN_PASSWORD=admin
|
||||||
@@ -4,9 +4,9 @@
|
|||||||
- Целевая оценка: 4
|
- Целевая оценка: 4
|
||||||
- Commit/PR: solution/BVT2303-Vasyukova
|
- Commit/PR: solution/BVT2303-Vasyukova
|
||||||
- Использованные источники, библиотеки и помощь ИИ:
|
- Использованные источники, библиотеки и помощь ИИ:
|
||||||
- Контракт: contracts/openapi.json, contracts/README.md
|
- Контракт: contracts/openapi.json, contracts/README.md, contracts/observability.md
|
||||||
- Инструкции: README.md, COURSE.md, CONTRIBUTING.md
|
- Инструкции: README.md, COURSE.md, CONTRIBUTING.md
|
||||||
- Библиотеки: fastapi==0.115.0, uvicorn[standard]==0.32.0, psycopg[binary]==3.2.3, psycopg_pool==3.2.3, redis==5.2.0, boto3==1.35.74, Pillow==11.0.0, pika==1.3.2, pydantic (из fastapi)
|
- Библиотеки: fastapi==0.115.0, uvicorn[standard]==0.32.0, psycopg[binary]==3.2.3, psycopg_pool==3.2.3, redis==5.2.0, boto3==1.35.74, Pillow==11.0.0, pika==1.3.2, opentelemetry-api==1.28.2, opentelemetry-sdk==1.28.2, opentelemetry-exporter-otlp-proto-http==1.28.2, opentelemetry-instrumentation-fastapi==0.49b2, opentelemetry-instrumentation-requests==0.49b2
|
||||||
- ИИ: DeepSeek — помощь в структурировании кода и отчёта. Весь код проверен, отредактирован и запущен разработчиком.
|
- ИИ: DeepSeek — помощь в структурировании кода и отчёта. Весь код проверен, отредактирован и запущен разработчиком.
|
||||||
|
|
||||||
## Запуск из чистого clone
|
## Запуск из чистого clone
|
||||||
@@ -14,9 +14,12 @@
|
|||||||
Версии runtime/образов:
|
Версии runtime/образов:
|
||||||
- Python: 3.12 (образ `python:3.12-slim`)
|
- Python: 3.12 (образ `python:3.12-slim`)
|
||||||
- FastAPI 0.115.0, uvicorn[standard] 0.32.0, psycopg[binary] 3.2.3, psycopg_pool 3.2.3, redis 5.2.0, boto3 1.35.74, Pillow 11.0.0, pika 1.3.2
|
- FastAPI 0.115.0, uvicorn[standard] 0.32.0, psycopg[binary] 3.2.3, psycopg_pool 3.2.3, redis 5.2.0, boto3 1.35.74, Pillow 11.0.0, pika 1.3.2
|
||||||
|
- OTel SDK 1.28.2, FastAPI instrumentation 0.49b2
|
||||||
- PostgreSQL 18.6-alpine, Redis 7.4.1-alpine, nginx 1.27.3-alpine
|
- PostgreSQL 18.6-alpine, Redis 7.4.1-alpine, nginx 1.27.3-alpine
|
||||||
- RabbitMQ 3.13.7-management-alpine
|
- RabbitMQ 3.13.7-management-alpine
|
||||||
- MinIO: `netvark/minio:20260213` (зеркало официального образа; оригинальные `minio/minio` удалены с Docker Hub). CLI `mc`: `netvark/mc:20260920`.
|
- MinIO: `netvark/minio:20260213` (зеркало официального образа; оригинальные `minio/minio` удалены с Docker Hub). CLI `mc`: `netvark/mc:20260920`.
|
||||||
|
- OTel Collector: `otel/opentelemetry-collector-contrib:0.108.0`
|
||||||
|
- Prometheus: `prom/prometheus:v2.54.1`, Loki: `grafana/loki:3.1.1`, Tempo: `grafana/tempo:2.5.0`, Grafana: `grafana/grafana:11.2.0`
|
||||||
- Docker Desktop (Windows)
|
- Docker Desktop (Windows)
|
||||||
|
|
||||||
### Запуск стека
|
### Запуск стека
|
||||||
@@ -30,7 +33,7 @@
|
|||||||
```
|
```
|
||||||
copy .env.example .env
|
copy .env.example .env
|
||||||
```
|
```
|
||||||
3. Собрать и поднять (LB + 2 реплики API + PostgreSQL + Redis + MinIO + minio-init + rabbitmq + worker + outbox + s3_cleanup):
|
3. Собрать и поднять (LB + 2 реплики API + PostgreSQL + Redis + MinIO + minio-init + rabbitmq + worker + outbox + s3_cleanup + OTel Collector + Prometheus + Loki + Tempo + Grafana):
|
||||||
```
|
```
|
||||||
docker compose --env-file .env up -d --build
|
docker compose --env-file .env up -d --build
|
||||||
```
|
```
|
||||||
@@ -39,6 +42,7 @@
|
|||||||
curl.exe -s http://localhost:8080/health/ready
|
curl.exe -s http://localhost:8080/health/ready
|
||||||
```
|
```
|
||||||
Ожидается: `{"status":"ok"}`.
|
Ожидается: `{"status":"ok"}`.
|
||||||
|
5. Grafana доступна на `http://localhost:3000` (admin/admin). Дашборд `messenger-lab6` и datasources импортируются автоматически.
|
||||||
|
|
||||||
Все проверки ниже выполнялись с `PYTHONUTF8=1` (Windows по умолчанию использует cp1251 и падает на чтении UTF-8 JSON):
|
Все проверки ниже выполнялись с `PYTHONUTF8=1` (Windows по умолчанию использует cp1251 и падает на чтении UTF-8 JSON):
|
||||||
```
|
```
|
||||||
@@ -56,28 +60,16 @@ $env:PYTHONUTF8="1"
|
|||||||
| `make test` | `python tests/smoke.py --base-url http://localhost:8080` |
|
| `make test` | `python tests/smoke.py --base-url http://localhost:8080` |
|
||||||
| `make test-persistence` | `python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080` |
|
| `make test-persistence` | `python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080` |
|
||||||
| `make test-failover` | `python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8080` |
|
| `make test-failover` | `python tests/resilience.py --mode failover --action-script scripts/stop-one.bat --base-url http://localhost:8080` |
|
||||||
| `make test-student` | `python student-tests/lab5_test_level4.py --base-url http://localhost:8080` |
|
| `make test-student` | `python student-tests/lab6_test_level4.py --base-url http://localhost:8080` |
|
||||||
|
|
||||||
### Остановка и удаление учебных данных
|
### Остановка и удаление учебных данных
|
||||||
|
|
||||||
```
|
```
|
||||||
docker compose stop # данные PostgreSQL, Redis, MinIO, RabbitMQ сохраняются (volumes)
|
docker compose stop # данные PostgreSQL, Redis, MinIO, RabbitMQ, Prometheus, Loki, Tempo, Grafana сохраняются (volumes)
|
||||||
docker compose down # volumes сохраняются
|
docker compose down # volumes сохраняются
|
||||||
docker compose down -v # ТОЛЬКО если осознанно стираем данные
|
docker compose down -v # ТОЛЬКО если осознанно стираем данные
|
||||||
```
|
```
|
||||||
|
|
||||||
### Операторский replay failed-задач
|
|
||||||
|
|
||||||
Причина ошибки устранена — вернуть задачи в обработку (failed → queued + новая строка outbox, готовые не трогаются):
|
|
||||||
|
|
||||||
```
|
|
||||||
docker compose --env-file .env exec -T worker python -m app.storage.replay_failed --all-failed
|
|
||||||
# или конкретные ID:
|
|
||||||
docker compose --env-file .env exec -T worker python -m app.storage.replay_failed <attachment_id> [...]
|
|
||||||
```
|
|
||||||
|
|
||||||
Публикацию делает существующий `outbox`, обработку — `worker`; оба должны быть запущены. Проверка: `status=queued`, затем `ready`.
|
|
||||||
|
|
||||||
## Архитектура и решения
|
## Архитектура и решения
|
||||||
|
|
||||||
Схема процессов и хранилищ:
|
Схема процессов и хранилищ:
|
||||||
@@ -93,15 +85,21 @@ HTTP-клиент → lb:80 ──┤ │
|
|||||||
outbox (publisher) → читает unpublished из PostgreSQL → публикует в RabbitMQ
|
outbox (publisher) → читает unpublished из PostgreSQL → публикует в RabbitMQ
|
||||||
worker (consumer) → забирает job из RabbitMQ → читает staging → пишет final+variants → status=ready
|
worker (consumer) → забирает job из RabbitMQ → читает staging → пишет final+variants → status=ready
|
||||||
s3_cleanup → сверка S3↔БД, recover зависших processing
|
s3_cleanup → сверка S3↔БД, recover зависших processing
|
||||||
|
|
||||||
|
API/worker/outbox → OTLP/HTTP → otel-collector → ┬→ Tempo (traces)
|
||||||
|
├→ Loki (logs)
|
||||||
|
└→ Prometheus (metrics)
|
||||||
|
→ Grafana (дашборд, алерты)
|
||||||
```
|
```
|
||||||
|
|
||||||
Все сервисы — в одной compose-сети `mtuci2026lab5_default`. Публично опубликован только порт LB `127.0.0.1:8080:80`. Реплики `api` **не имеют `ports`** — трафик к ним идёт исключительно через LB. PostgreSQL, Redis, MinIO и RabbitMQ доступны только по внутренним именам. Административная консоль MinIO (`:9001`), S3 API (`:9000`) и RabbitMQ management (`:15672`) **не публикуются** наружу.
|
Все сервисы — в одной compose-сети `mtuci2026lab6_default`. Публично опубликован только порт LB `127.0.0.1:8080:80` и Grafana `127.0.0.1:3000:3000`. Реплики `api` **не имеют `ports`** — трафик к ним идёт исключительно через LB. PostgreSQL, Redis, MinIO, RabbitMQ, OTel Collector (4317/4318/8888/8889), Prometheus (9090), Loki (3100), Tempo (3200) доступны только по внутренним именам.
|
||||||
|
|
||||||
Источники истины:
|
Источники истины:
|
||||||
- PostgreSQL — данные (пользователи, чаты, членство, сообщения, метаданные вложений, варианты, outbox, ключи идемпотентности).
|
- PostgreSQL — данные (пользователи, чаты, членство, сообщения, метаданные вложений, варианты, outbox, ключи идемпотентности).
|
||||||
- Redis — серверные сессии (общие для всех реплик).
|
- Redis — серверные сессии (общие для всех реплик).
|
||||||
- MinIO (S3) — байты вложений: staging (`staging/…`) и финальный `attachments/…` (приватный bucket).
|
- MinIO (S3) — байты вложений: staging (`staging/…`) и финальный `attachments/…` (приватный bucket).
|
||||||
- RabbitMQ — durable очередь job'ов. Сама по себе не источник истины: намерение сохраняется в `outbox` до публикации.
|
- RabbitMQ — durable очередь job'ов. Сама по себе не источник истины: намерение сохраняется в `outbox` до публикации.
|
||||||
|
- Tempo/Loki/Prometheus — telemetry storage. Их падение не останавливает API.
|
||||||
|
|
||||||
Схема БД (подробнее — `src/app/storage/db.py`, константа `SCHEMA_SQL`):
|
Схема БД (подробнее — `src/app/storage/db.py`, константа `SCHEMA_SQL`):
|
||||||
```
|
```
|
||||||
@@ -118,7 +116,7 @@ idempotency_keys(user_id FK→users, method TEXT, path TEXT, key TEXT,
|
|||||||
attachments(id UUID PK, chat_id FK→chats, owner_id FK→users,
|
attachments(id UUID PK, chat_id FK→chats, owner_id FK→users,
|
||||||
filename TEXT, content_type TEXT, size_bytes BIGINT, sha256 TEXT,
|
filename TEXT, content_type TEXT, size_bytes BIGINT, sha256 TEXT,
|
||||||
object_key TEXT UNIQUE, status TEXT, error_code TEXT,
|
object_key TEXT UNIQUE, status TEXT, error_code TEXT,
|
||||||
processing_until TIMESTAMPTZ, -- lab5: lease для worker
|
processing_until TIMESTAMPTZ,
|
||||||
created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ)
|
created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ)
|
||||||
+ INDEX idx_attachments_chat(chat_id)
|
+ INDEX idx_attachments_chat(chat_id)
|
||||||
message_attachments(message_id FK→messages, attachment_id FK→attachments, position INT,
|
message_attachments(message_id FK→messages, attachment_id FK→attachments, position INT,
|
||||||
@@ -126,9 +124,9 @@ message_attachments(message_id FK→messages, attachment_id FK→attachments, po
|
|||||||
attachment_variants(attachment_id FK→attachments, pipeline_version INT, variant TEXT,
|
attachment_variants(attachment_id FK→attachments, pipeline_version INT, variant TEXT,
|
||||||
object_key TEXT, content_type TEXT, size_bytes BIGINT,
|
object_key TEXT, content_type TEXT, size_bytes BIGINT,
|
||||||
width INT, height INT, sha256 TEXT, created_at TIMESTAMPTZ,
|
width INT, height INT, sha256 TEXT, created_at TIMESTAMPTZ,
|
||||||
PRIMARY KEY (attachment_id, pipeline_version, variant)) -- lab5
|
PRIMARY KEY (attachment_id, pipeline_version, variant))
|
||||||
outbox(id BIGSERIAL PK, job_id UUID UNIQUE, payload JSONB, created_at TIMESTAMPTZ,
|
outbox(id BIGSERIAL PK, job_id UUID UNIQUE, payload JSONB, created_at TIMESTAMPTZ,
|
||||||
published_at TIMESTAMPTZ) -- lab5 level 4
|
published_at TIMESTAMPTZ)
|
||||||
+ PARTIAL INDEX idx_outbox_unpublished(id) WHERE published_at IS NULL
|
+ PARTIAL INDEX idx_outbox_unpublished(id) WHERE published_at IS NULL
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -138,67 +136,78 @@ outbox(id BIGSERIAL PK, job_id UUID UNIQUE, payload JSONB, created_at TIMESTAMPT
|
|||||||
- `create_user` — SELECT-проверка username и INSERT в одной транзакции; при гонке `UniqueViolation` → 409.
|
- `create_user` — SELECT-проверка username и INSERT в одной транзакции; при гонке `UniqueViolation` → 409.
|
||||||
- `create_chat` — INSERT `chats` + INSERT `chat_members` в одной транзакции, откат целиком.
|
- `create_chat` — INSERT `chats` + INSERT `chat_members` в одной транзакции, откат целиком.
|
||||||
- `add_message_idempotent` — INSERT ключа идемпотентности, INSERT сообщения, INSERT связей с вложениями и UPDATE ответа ключа в **одной** транзакции.
|
- `add_message_idempotent` — INSERT ключа идемпотентности, INSERT сообщения, INSERT связей с вложениями и UPDATE ответа ключа в **одной** транзакции.
|
||||||
- `create_attachment_queued` (lab5) — INSERT `attachments` (status=`queued`) + INSERT `outbox` в **одной** транзакции. Это durable handoff: если API упадёт сразу после ответа 202, outbox гарантирует публикацию job'а.
|
- `create_attachment_queued` — INSERT `attachments` (status=`queued`) + INSERT `outbox` в **одной** транзакции. Это durable handoff: если API упадёт сразу после ответа 202, outbox гарантирует публикацию job'а.
|
||||||
- `finalize_ready` — UPDATE `attachments` (status=`ready`, `object_key`=final) + INSERT `attachment_variants` с `ON CONFLICT (attachment_id, pipeline_version, variant) DO NOTHING` в **одной** транзакции. Идемпотентно к повторной доставке.
|
- `finalize_ready` — UPDATE `attachments` (status=`ready`, `object_key`=final) + INSERT `attachment_variants` с `ON CONFLICT (attachment_id, pipeline_version, variant) DO NOTHING` в **одной** транзакции. Идемпотентно к повторной доставке.
|
||||||
|
|
||||||
### Дерево проекта (изменения относительно lab4 отмечены `*`)
|
### Дерево проекта (изменения относительно lab5 отмечены `*`)
|
||||||
|
|
||||||
```
|
```
|
||||||
mtuci2026lab5/
|
mtuci2026lab6/
|
||||||
├── compose.yaml * # + rabbitmq, worker, outbox; tag lab5 для всех сервисов
|
├── compose.yaml * # + otel-collector, prometheus, loki, tempo, grafana; tag lab6
|
||||||
├── Dockerfile
|
├── Dockerfile
|
||||||
├── docker-entrypoint.sh # генерирует INSTANCE_ID, пишет /tmp/instance_id
|
├── docker-entrypoint.sh # генерирует INSTANCE_ID, пишет /tmp/instance_id
|
||||||
├── infra/nginx.conf
|
├── infra/
|
||||||
|
│ ├── nginx.conf
|
||||||
|
│ ├── otel/collector.yaml * # OTLP receivers, memory_limiter, batch, exporters
|
||||||
|
│ ├── prometheus/
|
||||||
|
│ │ ├── prometheus.yaml * # scrape otel-collector:8889
|
||||||
|
│ │ └── rules/alerts.yaml *
|
||||||
|
│ ├── loki/loki.yaml *
|
||||||
|
│ ├── tempo/tempo.yaml *
|
||||||
|
│ ├── grafana/provisioning/
|
||||||
|
│ │ ├── datasources/datasources.yaml * # Prometheus/Loki/Tempo
|
||||||
|
│ │ ├── dashboards/provider.yaml *
|
||||||
|
│ │ ├── dashboards/json/messenger.json *
|
||||||
|
│ │ └── alerting/{contactpoints,policies,rules}.yaml *
|
||||||
|
│ └── runbooks/ * # high-error-rate.md, queue-lag.md, slow-upload.md
|
||||||
├── Makefile
|
├── Makefile
|
||||||
├── requirements.txt * # + pika
|
├── requirements.txt * # + opentelemetry-*
|
||||||
├── src/app/
|
├── src/app/
|
||||||
│ ├── main.py * # версия 1.5.0, title lab5
|
│ ├── main.py * # OTel init, HTTP-метрики, X-Request-Id/X-Instance-Id
|
||||||
│ ├── api/
|
│ ├── telemetry.py * # новый: единая точка init OTel + лог-формат
|
||||||
│ │ ├── attachments.py * # upload → 202 queued; download variant
|
│ ├── outbox_worker.py * # trace context из outbox payload → job.publish span
|
||||||
│ │ ├── messages.py # без изменений с lab4
|
│ ├── worker.py * # consumer span job.consume, метрики jobs_*
|
||||||
│ │ └── health.py # без изменений с lab4
|
│ ├── api/attachments.py * # inject traceparent в outbox payload
|
||||||
│ ├── models/
|
│ ├── api/... # без изменений с lab5
|
||||||
│ │ └── schemas.py # без изменений с lab4
|
│ ├── models/schemas.py
|
||||||
│ ├── storage/
|
│ └── storage/ # без изменений с lab5
|
||||||
│ │ ├── db.py * # + attachment_variants, outbox, processing_until
|
|
||||||
│ │ ├── postgres.py * # + lab5 методы (queued, variants, outbox, lease, recover)
|
|
||||||
│ │ ├── s3.py * # + staging_key, variant_key
|
|
||||||
│ │ ├── rabbit.py * # новый: topology, publish с confirm, retry, DLQ
|
|
||||||
│ │ └── s3_cleanup.py * # + cleanup staging, recover processing
|
|
||||||
│ ├── worker.py * # новый: consumer, обработка изображений
|
|
||||||
│ └── outbox_worker.py * # новый: outbox publisher (level 4)
|
|
||||||
├── scripts/
|
├── scripts/
|
||||||
│ ├── restart.sh / .bat * # + rabbitmq, worker, outbox
|
│ ├── restart.sh / .bat
|
||||||
│ └── stop-one.sh / .bat # без изменений
|
│ ├── stop-one.sh / .bat
|
||||||
|
│ └── rolling-update.sh
|
||||||
└── student-tests/
|
└── student-tests/
|
||||||
└── lab5_test_level4.py * # новый: variants, outbox, DLQ, lease, retry
|
└── lab6_test_level4.py * # новый: traces, metrics, logs, dashboard, alerts, telemetry down
|
||||||
```
|
```
|
||||||
|
|
||||||
### Что нового в lab5 относительно lab4
|
### Что нового в lab6 относительно lab5
|
||||||
|
|
||||||
TODO
|
- **OTel SDK** в API, worker и outbox: `init_telemetry()` настраивает TracerProvider, MeterProvider, LoggerProvider; OTLP/HTTP → `otel-collector:4318`.
|
||||||
|
- **Resource attributes**: `service.name` (messenger-api / messenger-worker / messenger-outbox), `service.version=1.6.0`, `service.instance.id`, `deployment.environment.name=lab`.
|
||||||
|
- **Логи**: единый формат с `trace_id=`/`span_id=`; `TraceContextFilter` подставляет их из активного span и в stdout, и в OTLP-экспортёр → Loki.
|
||||||
|
- **Метрики**: `http_requests_total{http.method,http.route,http.status_class}`, `http_request_duration_seconds_bucket`, `jobs_processed_total{job.type,outcome}`, `job_processing_duration_seconds_bucket`.
|
||||||
|
- **Трассы**: server span FastAPI + собственный `http.request` span в middleware; `job.publish` (PRODUCER) в outbox; `job.consume` (CONSUMER) в worker. W3C traceparent инжектится API → outbox payload → RabbitMQ headers → worker extract.
|
||||||
|
- **Collector**: `memory_limiter` (192 MiB + spike 64), `batch`, `resource` (upsert deployment.environment.name); exporters otlphttp/tempo, otlphttp/loki, prometheus:8889. Retry ограничен (`max_elapsed_time=60s`), sending_queue `queue_size=1000`.
|
||||||
|
- **Grafana provisioning**: datasources Prometheus/Loki/Tempo, dashboard `messenger-lab6`, alert rules `MessengerHighErrorRate` + `MessengerJobsBacklogGrowing` (+ `MessengerUploadLatencyHigh`).
|
||||||
|
|
||||||
## Доказательства критериев
|
## Доказательства критериев
|
||||||
|
|
||||||
| Критерий | Команда | Наблюдаемый результат | Уровень |
|
| Критерий | Команда | Наблюдаемый результат | Уровень |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| Публичный smoke | `python tests/smoke.py` | PASS: lab5 public API scenario | 3 |
|
| Публичный smoke | `python tests/smoke.py` | PASS: lab6 public API scenario | 3 |
|
||||||
| Broker + worker в общем стенде, at-least-once | `docker compose ps`; `rabbitmqctl list_queues` | rabbitmq/worker/outbox Up; consumer на `attachment.process.v1` | 3 |
|
| Collector + хранилища 3 сигналов + Grafana в общем стенде | `docker compose ps` | otel-collector, prometheus, loki, tempo, grafana Up | 3 |
|
||||||
| Upload возвращает 202 queued, работа переживает остановку worker | `lab5_test_level4.py::test_worker_stopped` | 202 queued → content 409 → старт worker → ready | 3 |
|
| API/worker отдают OTLP в Collector | Grafana → Explore → Prometheus/Tempo/Loki | метрики `http_*`, `jobs_*`; реальные traces; логи `messenger-api/worker` | 3 |
|
||||||
|
| Импортируемый dashboard | `test_grafana_provisioning` | `/api/dashboards/uid/messenger-lab6` → 200, панели RPS/errors/p95/jobs | 3 |
|
||||||
|
| Логи с trace_id | `lab6_test_level4.py::test_logs_in_loki` | ненулевой `trace_id=` в логах api+worker | 3/4 |
|
||||||
| Сохранение метаданных и сессии при рестарте | `resilience.py --mode persistence` | PASS: тот же токен и SHA-256 файла | 3 |
|
| Сохранение метаданных и сессии при рестарте | `resilience.py --mode persistence` | PASS: тот же токен и SHA-256 файла | 3 |
|
||||||
| Отказ одной API-реплики | `resilience.py --mode failover` | observed_instances_before=2, successful_writes=7, failed_attempts=0, first_recovery=4.245 s | 3 |
|
| Отказ одной API-реплики | `resilience.py --mode failover` | observed_instances_before=2, failed_attempts=0 | 3 |
|
||||||
| Worker сохраняет original + один thumbnail по контракту | `lab5_test_level4.py::test_variants` | thumbnail JPEG 256×160, sha256/size совпадают | 3 |
|
| Сквозной trace API → broker → worker | `lab6_test_level4.py::test_trace_api_to_worker` | один trace со span'ами `POST /api/v1/chats/{chat_id}/attachments`, `job.publish`, `job.consume` | 4 |
|
||||||
| Ограниченный retry, финальный failed с error_code | `lab5_test_level4.py::test_broken_staging_dlq` | failed `retry_exhausted` + DLQ | 3 |
|
| p50/p95/p99, error ratio, jobs, duration | `lab6_test_level4.py::test_metrics_in_prometheus` | все required метрики в Prometheus; `http_route` без UUID | 4 |
|
||||||
| Повтор job не создаёт второго набора вариантов | `lab5_test_level4.py::test_duplicate_delivery_no_duplicates` | variants не выросли, status=ready | 3 |
|
| Низкокардинальные labels | `test_metrics_in_prometheus` | `http_route` соответствует `/api/…` / `/health…`, raw UUID отсутствует | 4 |
|
||||||
| Original неизменен, download побайтно | smoke + `test_variants` | SHA-256 совпадает; при скачивании — те же байты | 3 |
|
| Alert rules минимум 2 | `test_grafana_provisioning` | `MessengerHighErrorRate`, `MessengerJobsBacklogGrowing` (+ upload latency) | 4 |
|
||||||
| Crop 128×128 (JPEG) | `lab5_test_level4.py::test_variants` | jpeg_size(crop) == (128,128) | 4 |
|
| Alert firing + resolved | `test_alert_firing_and_resolved` | stop postgres → firing, start postgres → inactive | 4 |
|
||||||
| Optimized WebP (≤1280×1280) | `lab5_test_level4.py::test_variants` | Content-Type image/webp, RIFF/WEBP | 4 |
|
| Telemetry backend down | `test_telemetry_backend_down` | API пишет/читает; Collector жив, RSS < 260 MiB | 4 |
|
||||||
| Outbox закрывает разрыв COMMIT → publish | `lab5_test_level4.py::test_outbox_crash` | stop outbox → upload 202 + outbox unpublished → start outbox → ready | 4 |
|
| Memory limiter / bounded retry в Collector | `infra/otel/collector.yaml` | `memory_limiter.limit_mib=192`; `retry_on_failure.max_elapsed_time=60s`; `sending_queue.queue_size=1000` | 4 |
|
||||||
| Retry с backoff, DLQ, безопасный replay | `lab5_test_level4.py::test_broken_staging_dlq` | 4 попытки, `retry_exhausted`, DLQ +1 | 4 |
|
| SLI/SLO и runbooks | `infra/prometheus/rules/alerts.yaml`, `infra/runbooks/` | error rate > 5% / 30s; retries > successes +5 / 5m; p95 upload > 2s / 3m | 4 |
|
||||||
| Ограниченная конкуренция, prefetch=1, очистка staging | `worker.py`, `s3_cleanup.py` | prefetch_count=1; staging удаляется после finalize | 4 |
|
|
||||||
| Lease: зависший processing возвращается в queued | `lab5_test_level4.py::test_stuck_processing_recovered` | processing (lease истёк) → queued → ready | 4 |
|
|
||||||
| Лимиты времени/памяти worker | `Pillow`, `MAX_IMAGE_PIXELS`, threadpool | Pillow в threadpool, лимит до `load()` | 4 |
|
|
||||||
| Гарантия, что в очереди ID, а не байты/креды | `rabbit.py`, `outbox_worker.py` | payload = {job_id, attachment_id, pipeline_version, created_at}; staging/финальные байты — в S3 | 4 |
|
|
||||||
|
|
||||||
### Выводы тестов
|
### Выводы тестов
|
||||||
|
|
||||||
@@ -210,7 +219,7 @@ PASS: offline skeleton structure, local refs and Python syntax; application NOT
|
|||||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||||
|
|
||||||
(venv) PS ...> python tests/smoke.py --base-url http://localhost:8080
|
(venv) PS ...> python tests/smoke.py --base-url http://localhost:8080
|
||||||
PASS: lab5 public API scenario; infrastructure and grading evidence remain separate.
|
PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.
|
||||||
|
|
||||||
(venv) PS ...> python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080
|
(venv) PS ...> python tests/resilience.py --mode persistence --action-script scripts/restart.bat --base-url http://localhost:8080
|
||||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||||
@@ -221,30 +230,54 @@ Executing explicit failover hook; hook output suppressed to avoid leaking secret
|
|||||||
{"observed_instances_before": 2, "successful_writes": 7, "failed_attempts": 0, "first_recovery_seconds": 4.245}
|
{"observed_instances_before": 2, "successful_writes": 7, "failed_attempts": 0, "first_recovery_seconds": 4.245}
|
||||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||||
|
|
||||||
(venv) PS ...> python student-tests/lab5_test_level4.py --base-url http://localhost:8080
|
(venv) PS ...> python student-tests/lab6_test_level4.py --base-url http://localhost:8080
|
||||||
=== variants (thumbnail/crop/optimized) ===
|
=== trace API -> broker -> worker (Tempo) ===
|
||||||
PASS: original, thumbnail 256×160, crop 128×128, optimized WebP
|
trace_id: b5259be38ee2e0400bd833c7eb723160
|
||||||
=== outbox crash between COMMIT and publish ===
|
spans: POST /api/v1/chats/{chat_id}/attachments, POST /api/v1/chats/{chat_id}/attachments http receive, POST /api/v1/chats/{chat_id}/attachments http send, http.request, job.consume, job.publish
|
||||||
PASS: outbox recovers job after stop/start without manual intervention
|
PASS: single trace with upload + job.publish + job.consume
|
||||||
=== duplicate delivery does not create duplicates ===
|
=== metrics in Prometheus ===
|
||||||
PASS: re-delivery of the same job is a no-op
|
metrics in Prometheus: ['http_request_duration_seconds_bucket', 'http_requests_total', 'job_processing_duration_seconds_bucket', 'jobs_processed_total']
|
||||||
=== worker stopped: 202 → content 409 → ready ===
|
jobs_processed_total{outcome=success} = 5.0
|
||||||
PASS: accepted work survives worker restart
|
PASS: http_requests_total + duration + jobs_processed_total present, low-cardinality route labels
|
||||||
=== broken staging → retry_exhausted → failed + DLQ ===
|
=== logs in Loki ===
|
||||||
PASS: bounded retry, failed with safe error_code, message in DLQ
|
Loki OK: api+worker logs with non-zero trace_id found
|
||||||
=== stuck processing (lease) → queued → ready ===
|
PASS: structured logs of api+worker with trace_id
|
||||||
PASS: expired lease is recovered, same attachment becomes ready
|
=== Grafana provisioning ===
|
||||||
PASS: all lab5 level-4 checks passed
|
datasources: ['loki', 'prometheus', 'tempo']
|
||||||
|
dashboard panels: ['API + worker logs', 'API RPS (total)', 'API error ratio (5xx / total)', 'HTTP latency p50/p95/p99 (s)', 'Job duration p95 (s) by outcome', 'Jobs processed by outcome']
|
||||||
|
alert rules: ['MessengerHighErrorRate', 'MessengerJobsBacklogGrowing']
|
||||||
|
PASS: dashboard messenger-lab6 + >=2 alert rules provisioned
|
||||||
|
=== alert firing and resolved ===
|
||||||
|
MessengerHighErrorRate firing
|
||||||
|
MessengerHighErrorRate resolved
|
||||||
|
PASS: alert fires on artificial outage and resolves on recovery
|
||||||
|
=== telemetry backend down ===
|
||||||
|
otel-collector RSS while backends down: 81.24 MiB
|
||||||
|
API and Collector remained healthy while backends were down
|
||||||
|
PASS: API works, Collector stays within memory limit
|
||||||
|
PASS: all lab6 level-4 checks passed
|
||||||
```
|
```
|
||||||
|
|
||||||
## Эксперименты и отказы
|
## Эксперименты и отказы
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Стенд: Windows 11, Docker Desktop (WSL2), 16 ГБ RAM, лимиты compose из `compose.yaml` (API 1 CPU / 512 MiB ×2; worker 1 CPU / 512 MiB; Collector 0.5 CPU / 256 MiB). Все данные синтетические; профиль — публичный `smoke.py` + `student-tests/lab6_test_level4.py`.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| TODO | TODO | TODO | TODO |
|
| `docker compose stop postgres` (~30 c) | `/health/ready` → 503; `MessengerHighErrorRate` firing; после старта БД — resolved | readiness 503; alert firing; ошибки 5xx растут, видны в Prometheus и Loki с request_id | после `start postgres` readiness 200 < 30 c; alert resolved в течение окна `for: 30s` + evaluation; данные сохранены |
|
||||||
|
| `docker compose stop prometheus loki tempo` (~30 c) | API продолжает обрабатывать запросы; Collector не падает и не растёт неограниченно | API отвечает 200; `ok >= 5` запросов/сообщений за 30 c; `otel-collector --version` OK; RSS Collector < 260 MiB | после `start` backends telemetry снова появляется в Grafana; работа API и данные не пострадали |
|
||||||
|
| `docker compose stop worker` | attachment остаётся `queued`; после `start worker` → `ready` | content 409 → 202 → ready; trace `job.consume` появился после восстановления worker | ~5–10 c до `consumer_started`; ничего не потеряно (outbox + RabbitMQ) |
|
||||||
|
| `docker compose stop outbox` | upload → 202, строка outbox `published_at IS NULL`; после `start outbox` публикация и ready | unpublished=1, attachment queued; после старта ready | время до ready ≈ интервал outbox (2 c) + обработка worker |
|
||||||
|
|
||||||
|
Диагностика инцидентов:
|
||||||
|
1. **Рост 5xx при мёртвой БД.** Дашборд `Messenger` → панель «API error ratio» растёт; p95 растёт. В Loki `{service_name="messenger-api"} |= "event=db_unavailable"` — строки с `request_id`. В Tempo trace по `trace_id` показывает `http.request` → долгий child span упавший на DB. Отличие от медленного HTTP handler: при мёртвой БД ошибки идут как 503 без долгого `http.request` span; при медленном handler растёт длительность `http.request`, но `status_class` остаётся 2xx.
|
||||||
|
2. **Растущий backlog worker.** `jobs_processed_total{outcome="retry"}` опережает `success`; `MessengerJobsBacklogGrowing` firing. Проверка: `docker compose ps worker`, `rabbitmqctl list_queues name messages consumers`, Tempo → span `job.consume` со status ERROR. После восстановления worker backlog уменьшается, alert resolved.
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
## Ограничения и следующие шаги
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
- Один Docker-host: HA к потере host не заявляется. 2 реплики API + LB защищают только от отказа одной реплики и от рестарта процесса.
|
||||||
|
- SLI/SLO — учебные (`5xx ratio < 5% за 1m`, `p95 upload < 2s`); не откалиброваны под production-нагрузку. Burn-rate алерты с несколькими окнами (трек 2 на 5) не реализованы — на оценку 4 достаточно пороговых правил.
|
||||||
|
- Sampling не настроен: при большом трафике объём spans/логов в Tempo/Loki будет расти; Collector `memory_limiter`/`batch` ограничивают RAM, но не объём диска. Persistence Tempo 24 ч, Loki 168 ч — учебное окно.
|
||||||
|
- Экспортёр `otlphttp` в Tempo/Loki при длительной недоступности backend может потерять часть telemetry (queue_size=1000, max_elapsed_time=60s). Потери считаются по логам Collector (level=warn) — отдельного счётчика потерь не заведено; на 4 достаточно зафиксировать ограниченное поведение.
|
||||||
|
- Абсолютные RPS/p95 в отчёте не приводятся: измерение в closed-loop на ноутбуке переносимо плохо, для 4 требуется не абсолютный throughput, а корректная связь сигналов и воспроизводимость отказов.
|
||||||
|
- Следующие шаги: sampling (parent-based / tail) и оценка потерь spans — трек 1 на 5; burn-rate multi-window alerting — трек 2 на 5.
|
||||||
+154
-35
@@ -1,9 +1,14 @@
|
|||||||
x-lab-number: 4
|
x-lab-number: 6
|
||||||
x-required-roles:
|
x-required-roles:
|
||||||
- api
|
- api
|
||||||
- postgres
|
- postgres
|
||||||
- load_balancer
|
- load_balancer
|
||||||
- s3
|
- s3
|
||||||
|
- broker
|
||||||
|
- worker
|
||||||
|
- otel_collector
|
||||||
|
- telemetry_storage
|
||||||
|
- grafana
|
||||||
|
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
@@ -70,8 +75,6 @@ services:
|
|||||||
retries: 20
|
retries: 20
|
||||||
start_period: 5s
|
start_period: 5s
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
# Консоль администратора НЕ публикуется наружу; доступ только из сети compose.
|
|
||||||
# Порт 9000 (S3 API) тоже внутренний — публичного доступа нет.
|
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
limits:
|
limits:
|
||||||
@@ -92,12 +95,8 @@ services:
|
|||||||
- |
|
- |
|
||||||
set -eu
|
set -eu
|
||||||
mc alias set local http://minio:9000 "$${MINIO_ROOT_USER}" "$${MINIO_ROOT_PASSWORD}"
|
mc alias set local http://minio:9000 "$${MINIO_ROOT_USER}" "$${MINIO_ROOT_PASSWORD}"
|
||||||
# Приватный bucket; idempotent.
|
|
||||||
mc mb --ignore-existing local/"$${S3_BUCKET}"
|
mc mb --ignore-existing local/"$${S3_BUCKET}"
|
||||||
# Политика: bucket не публичный. Явно none.
|
|
||||||
mc anonymous set none local/"$${S3_BUCKET}" || true
|
mc anonymous set none local/"$${S3_BUCKET}" || true
|
||||||
# Прикладные S3-credentials с ограниченными правами на префикс приложения.
|
|
||||||
# Политика выдаётся через `mc admin policy`; создаём отдельного пользователя.
|
|
||||||
if ! mc admin user info local "$${S3_APP_KEY_ID}" >/dev/null 2>&1; then
|
if ! mc admin user info local "$${S3_APP_KEY_ID}" >/dev/null 2>&1; then
|
||||||
mc admin user add local "$${S3_APP_KEY_ID}" "$${S3_APP_SECRET_KEY}"
|
mc admin user add local "$${S3_APP_KEY_ID}" "$${S3_APP_SECRET_KEY}"
|
||||||
fi
|
fi
|
||||||
@@ -105,28 +104,15 @@ services:
|
|||||||
{
|
{
|
||||||
"Version": "2012-10-17",
|
"Version": "2012-10-17",
|
||||||
"Statement": [
|
"Statement": [
|
||||||
{
|
{"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"], "Resource": ["arn:aws:s3:::${S3_BUCKET}"]},
|
||||||
"Effect": "Allow",
|
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"], "Resource": ["arn:aws:s3:::${S3_BUCKET}/*"]}
|
||||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
|
||||||
"Resource": ["arn:aws:s3:::${S3_BUCKET}"]
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"Effect": "Allow",
|
|
||||||
"Action": [
|
|
||||||
"s3:GetObject", "s3:PutObject", "s3:DeleteObject",
|
|
||||||
"s3:AbortMultipartUpload", "s3:ListMultipartUploadParts"
|
|
||||||
],
|
|
||||||
"Resource": ["arn:aws:s3:::${S3_BUCKET}/*"]
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
POLICY
|
POLICY
|
||||||
# Подставляем имя bucket в политику
|
|
||||||
sed -i "s/\$${S3_BUCKET}/$${S3_BUCKET}/g" /tmp/app-policy.json || true
|
sed -i "s/\$${S3_BUCKET}/$${S3_BUCKET}/g" /tmp/app-policy.json || true
|
||||||
mc admin policy create local messenger-app /tmp/app-policy.json 2>/dev/null || true
|
mc admin policy create local messenger-app /tmp/app-policy.json 2>/dev/null || true
|
||||||
mc admin policy attach local messenger-app --user "$${S3_APP_KEY_ID}" || true
|
mc admin policy attach local messenger-app --user "$${S3_APP_KEY_ID}" || true
|
||||||
echo "minio-init done"
|
echo "minio-init done"
|
||||||
# Административные credentials нужны только здесь и в minio.
|
|
||||||
environment:
|
environment:
|
||||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minioadmin}
|
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-minioadmin}
|
||||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin}
|
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-minioadmin}
|
||||||
@@ -142,9 +128,8 @@ services:
|
|||||||
|
|
||||||
migrate:
|
migrate:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab5
|
image: mtuci-messenger:lab6
|
||||||
command: ["python", "-m", "app.storage.db"]
|
command: ["python", "-m", "app.storage.db"]
|
||||||
# Явный whitelist переменных: без MINIO_ROOT_USER/PASSWORD.
|
|
||||||
environment:
|
environment:
|
||||||
APP_ENV: ${APP_ENV:-lab}
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
DATABASE_URL: ${DATABASE_URL}
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
@@ -191,7 +176,7 @@ services:
|
|||||||
|
|
||||||
worker:
|
worker:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab5
|
image: mtuci-messenger:lab6
|
||||||
command: ["python", "-m", "app.worker"]
|
command: ["python", "-m", "app.worker"]
|
||||||
environment:
|
environment:
|
||||||
APP_ENV: ${APP_ENV:-lab}
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
@@ -202,6 +187,10 @@ services:
|
|||||||
S3_APP_KEY_ID: ${S3_APP_KEY_ID}
|
S3_APP_KEY_ID: ${S3_APP_KEY_ID}
|
||||||
S3_APP_SECRET_KEY: ${S3_APP_SECRET_KEY}
|
S3_APP_SECRET_KEY: ${S3_APP_SECRET_KEY}
|
||||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||||
|
OTEL_SERVICE_NAME: messenger-worker
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||||
|
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||||
depends_on:
|
depends_on:
|
||||||
migrate:
|
migrate:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
@@ -209,6 +198,8 @@ services:
|
|||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
rabbitmq:
|
rabbitmq:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
otel-collector:
|
||||||
|
condition: service_started
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
@@ -221,17 +212,23 @@ services:
|
|||||||
|
|
||||||
outbox:
|
outbox:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab5
|
image: mtuci-messenger:lab6
|
||||||
command: ["python", "-m", "app.outbox_worker"]
|
command: ["python", "-m", "app.outbox_worker"]
|
||||||
environment:
|
environment:
|
||||||
APP_ENV: ${APP_ENV:-lab}
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
DATABASE_URL: ${DATABASE_URL}
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
RABBITMQ_URL: ${RABBITMQ_URL:-amqp://messenger:messenger-rabbit-change-me@rabbitmq:5672/%2F}
|
||||||
|
OTEL_SERVICE_NAME: messenger-outbox
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||||
|
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||||
depends_on:
|
depends_on:
|
||||||
migrate:
|
migrate:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
rabbitmq:
|
rabbitmq:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
otel-collector:
|
||||||
|
condition: service_started
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
deploy:
|
deploy:
|
||||||
resources:
|
resources:
|
||||||
@@ -241,10 +238,7 @@ services:
|
|||||||
|
|
||||||
api:
|
api:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab5
|
image: mtuci-messenger:lab6
|
||||||
# Явный whitelist переменных: приложение не получает административные
|
|
||||||
# credentials MinIO (MINIO_ROOT_USER/PASSWORD). Для S3 — только
|
|
||||||
# прикладные S3_APP_KEY_ID/S3_APP_SECRET_KEY с ограниченной политикой.
|
|
||||||
environment:
|
environment:
|
||||||
APP_HOST: ${APP_HOST:-0.0.0.0}
|
APP_HOST: ${APP_HOST:-0.0.0.0}
|
||||||
APP_PORT: ${APP_PORT:-8080}
|
APP_PORT: ${APP_PORT:-8080}
|
||||||
@@ -263,6 +257,10 @@ services:
|
|||||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-300}
|
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-300}
|
||||||
ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-3600}
|
ORPHAN_GRACE_SECONDS: ${ORPHAN_GRACE_SECONDS:-3600}
|
||||||
|
OTEL_SERVICE_NAME: messenger-api
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: ${OTEL_EXPORTER_OTLP_ENDPOINT:-http://otel-collector:4318}
|
||||||
|
OTEL_EXPORTER_OTLP_PROTOCOL: ${OTEL_EXPORTER_OTLP_PROTOCOL:-http/protobuf}
|
||||||
|
OTEL_RESOURCE_ATTRIBUTES: ${OTEL_RESOURCE_ATTRIBUTES:-deployment.environment.name=lab}
|
||||||
depends_on:
|
depends_on:
|
||||||
migrate:
|
migrate:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
@@ -272,6 +270,8 @@ services:
|
|||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
minio-init:
|
minio-init:
|
||||||
condition: service_completed_successfully
|
condition: service_completed_successfully
|
||||||
|
otel-collector:
|
||||||
|
condition: service_started
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready').read()"]
|
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready').read()"]
|
||||||
interval: 5s
|
interval: 5s
|
||||||
@@ -289,13 +289,10 @@ services:
|
|||||||
cpus: "0.25"
|
cpus: "0.25"
|
||||||
memory: 128M
|
memory: 128M
|
||||||
|
|
||||||
# Уровень 4: фоновая сверка S3↔БД (orphan-объекты и missing).
|
|
||||||
# Запускается как долгоживущий сервис, спит CLEANUP_INTERVAL_SECONDS.
|
|
||||||
s3_cleanup:
|
s3_cleanup:
|
||||||
build: .
|
build: .
|
||||||
image: mtuci-messenger:lab5
|
image: mtuci-messenger:lab6
|
||||||
command: ["python", "-m", "app.storage.s3_cleanup"]
|
command: ["python", "-m", "app.storage.s3_cleanup"]
|
||||||
# Явный whitelist переменных: без административных кредов MinIO.
|
|
||||||
environment:
|
environment:
|
||||||
APP_ENV: ${APP_ENV:-lab}
|
APP_ENV: ${APP_ENV:-lab}
|
||||||
DATABASE_URL: ${DATABASE_URL}
|
DATABASE_URL: ${DATABASE_URL}
|
||||||
@@ -341,6 +338,120 @@ services:
|
|||||||
cpus: "0.1"
|
cpus: "0.1"
|
||||||
memory: 32M
|
memory: 32M
|
||||||
|
|
||||||
|
# ---------- Observability: lab6 ----------
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.108.0
|
||||||
|
container_name: mtuci-otel-collector
|
||||||
|
command: ["--config=/etc/otel/collector.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro
|
||||||
|
depends_on:
|
||||||
|
- tempo
|
||||||
|
- loki
|
||||||
|
- prometheus
|
||||||
|
# Порты OTLP наружу не публикуем: API/worker/outbox в той же сети.
|
||||||
|
# health-порт тоже внутри compose-сети.
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "/otelcol-contrib", "--version"]
|
||||||
|
interval: 10s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
start_period: 10s
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 256M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 64M
|
||||||
|
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v2.54.1
|
||||||
|
container_name: mtuci-prometheus
|
||||||
|
command:
|
||||||
|
- "--config.file=/etc/prometheus/prometheus.yaml"
|
||||||
|
- "--storage.tsdb.path=/prometheus"
|
||||||
|
- "--storage.tsdb.retention.time=15d"
|
||||||
|
- "--web.listen-address=0.0.0.0:9090"
|
||||||
|
volumes:
|
||||||
|
- ./infra/prometheus/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||||
|
- ./infra/prometheus/rules:/etc/prometheus/rules:ro
|
||||||
|
- prometheus-data:/prometheus
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 128M
|
||||||
|
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.1.1
|
||||||
|
container_name: mtuci-loki
|
||||||
|
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/loki/loki.yaml:/etc/loki/loki.yaml:ro
|
||||||
|
- loki-data:/loki
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 128M
|
||||||
|
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.5.0
|
||||||
|
container_name: mtuci-tempo
|
||||||
|
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||||
|
volumes:
|
||||||
|
- ./infra/tempo/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||||
|
- tempo-data:/var/tempo
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 512M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 128M
|
||||||
|
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:11.2.0
|
||||||
|
container_name: mtuci-grafana
|
||||||
|
environment:
|
||||||
|
GF_AUTH_ANONYMOUS_ENABLED: "true"
|
||||||
|
GF_AUTH_ANONYMOUS_ORG_ROLE: "Admin"
|
||||||
|
GF_AUTH_DISABLE_LOGIN_FORM: "true"
|
||||||
|
GF_FEATURE_TOGGLES_ENABLE: "traceqlEditor"
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin}
|
||||||
|
volumes:
|
||||||
|
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||||
|
- ./infra/grafana/provisioning/alerting:/etc/grafana/provisioning/alerting:ro
|
||||||
|
- grafana-data:/var/lib/grafana
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:3000:3000"
|
||||||
|
depends_on:
|
||||||
|
- prometheus
|
||||||
|
- loki
|
||||||
|
- tempo
|
||||||
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.3"
|
||||||
|
memory: 256M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.05"
|
||||||
|
memory: 64M
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
name: mtuci2026lab5_postgres-data
|
name: mtuci2026lab5_postgres-data
|
||||||
@@ -350,7 +461,15 @@ volumes:
|
|||||||
name: mtuci2026lab5_minio-data
|
name: mtuci2026lab5_minio-data
|
||||||
rabbitmq-data:
|
rabbitmq-data:
|
||||||
name: mtuci2026lab5_rabbitmq-data
|
name: mtuci2026lab5_rabbitmq-data
|
||||||
|
prometheus-data:
|
||||||
|
name: mtuci2026lab6_prometheus-data
|
||||||
|
loki-data:
|
||||||
|
name: mtuci2026lab6_loki-data
|
||||||
|
tempo-data:
|
||||||
|
name: mtuci2026lab6_tempo-data
|
||||||
|
grafana-data:
|
||||||
|
name: mtuci2026lab6_grafana-data
|
||||||
|
|
||||||
networks:
|
networks:
|
||||||
default:
|
default:
|
||||||
name: mtuci2026lab5_default
|
name: mtuci2026lab6_default
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
contactPoints:
|
||||||
|
- orgId: 1
|
||||||
|
name: messenger-local
|
||||||
|
receivers:
|
||||||
|
- uid: messenger-local-webhook
|
||||||
|
type: webhook
|
||||||
|
disableResolveMessage: false
|
||||||
|
settings:
|
||||||
|
# Доставка наружу не требуется; локальный no-op endpoint.
|
||||||
|
url: http://127.0.0.1:9/messenger-alerts
|
||||||
|
httpMethod: POST
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
policies:
|
||||||
|
- orgId: 1
|
||||||
|
receiver: messenger-local
|
||||||
|
group_by: ['alertname']
|
||||||
|
group_wait: 10s
|
||||||
|
group_interval: 1m
|
||||||
|
repeat_interval: 4h
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
groups:
|
||||||
|
- orgId: 1
|
||||||
|
name: messenger-alerts
|
||||||
|
folder: Messenger
|
||||||
|
interval: 1m
|
||||||
|
rules:
|
||||||
|
- uid: messenger-high-error-rate
|
||||||
|
title: MessengerHighErrorRate
|
||||||
|
condition: C
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange:
|
||||||
|
from: 60
|
||||||
|
to: 0
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
editorMode: code
|
||||||
|
expr: sum(rate(http_requests_total{http_status_class="5xx"}[1m])) / clamp_min(sum(rate(http_requests_total[1m])), 1e-9)
|
||||||
|
instant: true
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
range: false
|
||||||
|
refId: A
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
conditions:
|
||||||
|
- evaluator:
|
||||||
|
params: [0.05]
|
||||||
|
type: gt
|
||||||
|
operator:
|
||||||
|
type: and
|
||||||
|
query:
|
||||||
|
params: [C]
|
||||||
|
reducer:
|
||||||
|
params: []
|
||||||
|
type: last
|
||||||
|
type: query
|
||||||
|
datasource:
|
||||||
|
type: __expr__
|
||||||
|
uid: __expr__
|
||||||
|
expression: A
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
for: 30s
|
||||||
|
annotations:
|
||||||
|
summary: "API error rate > 5% over 1m"
|
||||||
|
description: "5xx ratio exceeds SLO 5% for 30 seconds."
|
||||||
|
runbook: "infra/runbooks/high-error-rate.md"
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
noDataState: NoData
|
||||||
|
execErrState: Error
|
||||||
|
isPaused: false
|
||||||
|
|
||||||
|
- uid: messenger-jobs-backlog-growing
|
||||||
|
title: MessengerJobsBacklogGrowing
|
||||||
|
condition: C
|
||||||
|
data:
|
||||||
|
- refId: A
|
||||||
|
relativeTimeRange:
|
||||||
|
from: 600
|
||||||
|
to: 0
|
||||||
|
datasourceUid: prometheus
|
||||||
|
model:
|
||||||
|
editorMode: code
|
||||||
|
expr: sum(increase(jobs_processed_total{outcome="retry"}[10m])) - sum(increase(jobs_processed_total{outcome="success"}[10m]))
|
||||||
|
instant: true
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
range: false
|
||||||
|
refId: A
|
||||||
|
- refId: C
|
||||||
|
datasourceUid: __expr__
|
||||||
|
model:
|
||||||
|
conditions:
|
||||||
|
- evaluator:
|
||||||
|
params: [5]
|
||||||
|
type: gt
|
||||||
|
operator:
|
||||||
|
type: and
|
||||||
|
query:
|
||||||
|
params: [C]
|
||||||
|
reducer:
|
||||||
|
params: []
|
||||||
|
type: last
|
||||||
|
type: query
|
||||||
|
datasource:
|
||||||
|
type: __expr__
|
||||||
|
uid: __expr__
|
||||||
|
expression: A
|
||||||
|
intervalMs: 1000
|
||||||
|
maxDataPoints: 43200
|
||||||
|
refId: C
|
||||||
|
type: threshold
|
||||||
|
for: 5m
|
||||||
|
annotations:
|
||||||
|
summary: "Retries outpace successes"
|
||||||
|
description: "Worker retry count exceeds successes by >5 for 5m."
|
||||||
|
runbook: "infra/runbooks/queue-lag.md"
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
noDataState: NoData
|
||||||
|
execErrState: Error
|
||||||
|
isPaused: false
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
{
|
||||||
|
"uid": "messenger-lab6",
|
||||||
|
"title": "Messenger — lab6 observability",
|
||||||
|
"schemaVersion": 39,
|
||||||
|
"version": 2,
|
||||||
|
"editable": true,
|
||||||
|
"timezone": "browser",
|
||||||
|
"time": {"from": "now-30m", "to": "now"},
|
||||||
|
"templating": {
|
||||||
|
"list": [
|
||||||
|
{
|
||||||
|
"name": "service",
|
||||||
|
"type": "query",
|
||||||
|
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||||
|
"query": "label_values(up, job)",
|
||||||
|
"current": {"text": "otel-collector", "value": "otel-collector"}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"panels": [
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "API RPS (total)",
|
||||||
|
"gridPos": {"x": 0, "y": 0, "w": 8, "h": 8},
|
||||||
|
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "sum(rate(http_requests_total[1m]))", "legendFormat": "rps", "refId": "A"}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "API error ratio (5xx / total)",
|
||||||
|
"gridPos": {"x": 8, "y": 0, "w": 8, "h": 8},
|
||||||
|
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "sum(rate(http_requests_total{http_status_class=\"5xx\"}[5m])) / clamp_min(sum(rate(http_requests_total[5m])), 1e-9)", "legendFormat": "ratio", "refId": "A"}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 3,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "HTTP latency p50/p95/p99 (s)",
|
||||||
|
"gridPos": {"x": 16, "y": 0, "w": 8, "h": 8},
|
||||||
|
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "histogram_quantile(0.50, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p50", "refId": "A"},
|
||||||
|
{"expr": "histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "B"},
|
||||||
|
{"expr": "histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p99", "refId": "C"}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 4,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Jobs processed by outcome",
|
||||||
|
"gridPos": {"x": 0, "y": 8, "w": 12, "h": 8},
|
||||||
|
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "sum by (outcome) (rate(jobs_processed_total[1m]))", "legendFormat": "{{outcome}}", "refId": "A"}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 5,
|
||||||
|
"type": "timeseries",
|
||||||
|
"title": "Job duration p95 (s) by outcome",
|
||||||
|
"gridPos": {"x": 12, "y": 8, "w": 12, "h": 8},
|
||||||
|
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(job_processing_duration_seconds_bucket[5m])))", "legendFormat": "{{outcome}}", "refId": "A"}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 6,
|
||||||
|
"type": "logs",
|
||||||
|
"title": "API + worker logs",
|
||||||
|
"gridPos": {"x": 0, "y": 16, "w": 24, "h": 10},
|
||||||
|
"datasource": {"type": "loki", "uid": "loki"},
|
||||||
|
"targets": [
|
||||||
|
{"expr": "{service_name=~\"messenger-api|messenger-worker|messenger-outbox\"}", "refId": "A"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
providers:
|
||||||
|
- name: messenger
|
||||||
|
folder: Messenger
|
||||||
|
type: file
|
||||||
|
options:
|
||||||
|
path: /etc/grafana/provisioning/dashboards/json
|
||||||
|
foldersFromFilesStructure: false
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: http://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
editable: false
|
||||||
|
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: http://loki:3100
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
derivedFields:
|
||||||
|
- name: TraceID
|
||||||
|
matcherRegex: 'trace_id=([a-f0-9]+)'
|
||||||
|
datasourceUid: tempo
|
||||||
|
url: "$${__value.raw}"
|
||||||
|
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: http://tempo:3200
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
tags:
|
||||||
|
- key: service.name
|
||||||
|
value: service_name
|
||||||
|
filterByTraceID: true
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
grpc_listen_port: 9096
|
||||||
|
log_level: warn
|
||||||
|
|
||||||
|
common:
|
||||||
|
path_prefix: /loki
|
||||||
|
storage:
|
||||||
|
filesystem:
|
||||||
|
chunks_directory: /loki/chunks
|
||||||
|
rules_directory: /loki/rules
|
||||||
|
replication_factor: 1
|
||||||
|
ring:
|
||||||
|
instance_addr: 127.0.0.1
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
|
||||||
|
schema_config:
|
||||||
|
configs:
|
||||||
|
- from: 2024-01-01
|
||||||
|
store: tsdb
|
||||||
|
object_store: filesystem
|
||||||
|
schema: v13
|
||||||
|
index:
|
||||||
|
prefix: index_
|
||||||
|
period: 24h
|
||||||
|
|
||||||
|
limits_config:
|
||||||
|
retention_period: 168h
|
||||||
|
reject_old_samples: true
|
||||||
|
reject_old_samples_max_age: 168h
|
||||||
|
allow_structured_metadata: true
|
||||||
|
|
||||||
|
compactor:
|
||||||
|
working_directory: /loki/compactor
|
||||||
|
delete_request_store: filesystem
|
||||||
|
retention_enabled: true
|
||||||
|
|
||||||
|
analytics:
|
||||||
|
reporting_enabled: false
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
|
||||||
|
processors:
|
||||||
|
# Level-4: ограничение RAM и batch, чтобы не расти бесконечно при
|
||||||
|
# недоступном backend и уменьшить объём записи.
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 2s
|
||||||
|
limit_mib: 192
|
||||||
|
spike_limit_mib: 64
|
||||||
|
batch:
|
||||||
|
timeout: 5s
|
||||||
|
send_batch_size: 1024
|
||||||
|
send_batch_max_size: 2048
|
||||||
|
resource:
|
||||||
|
attributes:
|
||||||
|
- key: deployment.environment.name
|
||||||
|
value: lab
|
||||||
|
action: upsert
|
||||||
|
|
||||||
|
exporters:
|
||||||
|
# Явно ограничиваем retry и время ожидания, чтобы при недоступном
|
||||||
|
# бэкенде коллектор не накапливал данные и не падал.
|
||||||
|
otlphttp/tempo:
|
||||||
|
endpoint: http://tempo:4318
|
||||||
|
tls:
|
||||||
|
insecure: true
|
||||||
|
retry_on_failure:
|
||||||
|
enabled: true
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 10s
|
||||||
|
max_elapsed_time: 60s
|
||||||
|
sending_queue:
|
||||||
|
enabled: true
|
||||||
|
num_consumers: 4
|
||||||
|
queue_size: 1000
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: http://loki:3100/otlp
|
||||||
|
tls:
|
||||||
|
insecure: true
|
||||||
|
retry_on_failure:
|
||||||
|
enabled: true
|
||||||
|
initial_interval: 1s
|
||||||
|
max_interval: 10s
|
||||||
|
max_elapsed_time: 60s
|
||||||
|
sending_queue:
|
||||||
|
enabled: true
|
||||||
|
num_consumers: 4
|
||||||
|
queue_size: 1000
|
||||||
|
prometheus:
|
||||||
|
endpoint: 0.0.0.0:8889
|
||||||
|
resource_to_telemetry_conversion:
|
||||||
|
enabled: true
|
||||||
|
send_timestamps: true
|
||||||
|
metric_expiration: 5m
|
||||||
|
|
||||||
|
service:
|
||||||
|
telemetry:
|
||||||
|
logs:
|
||||||
|
level: warn
|
||||||
|
metrics:
|
||||||
|
address: 0.0.0.0:8888
|
||||||
|
pipelines:
|
||||||
|
traces:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, resource, batch]
|
||||||
|
exporters: [otlphttp/tempo]
|
||||||
|
metrics:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, resource, batch]
|
||||||
|
exporters: [prometheus]
|
||||||
|
logs:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, resource, batch]
|
||||||
|
exporters: [otlphttp/loki]
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 15s
|
||||||
|
evaluation_interval: 15s
|
||||||
|
|
||||||
|
rule_files:
|
||||||
|
- /etc/prometheus/rules/*.yaml
|
||||||
|
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: otel-collector
|
||||||
|
scrape_interval: 5s
|
||||||
|
static_configs:
|
||||||
|
- targets: ["otel-collector:8889"]
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger-alerts
|
||||||
|
interval: 30s
|
||||||
|
rules:
|
||||||
|
- alert: MessengerHighErrorRate
|
||||||
|
expr: |
|
||||||
|
sum(rate(http_requests_total{http_status_class="5xx"}[1m]))
|
||||||
|
/
|
||||||
|
sum(rate(http_requests_total[1m]))
|
||||||
|
> 0.05
|
||||||
|
for: 30s
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: "API error rate > 5% over 1m"
|
||||||
|
description: "5xx ratio exceeds SLO 5% for 30 seconds."
|
||||||
|
runbook: "infra/runbooks/high-error-rate.md"
|
||||||
|
|
||||||
|
- alert: MessengerJobsBacklogGrowing
|
||||||
|
expr: |
|
||||||
|
sum(increase(jobs_processed_total{outcome="retry"}[10m]))
|
||||||
|
>
|
||||||
|
sum(increase(jobs_processed_total{outcome="success"}[10m]))
|
||||||
|
+ 5
|
||||||
|
for: 5m
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: "Retries outpace successes"
|
||||||
|
description: "Worker retry count exceeds successes for 5m."
|
||||||
|
runbook: "infra/runbooks/queue-lag.md"
|
||||||
|
|
||||||
|
- alert: MessengerUploadLatencyHigh
|
||||||
|
expr: |
|
||||||
|
histogram_quantile(0.95,
|
||||||
|
sum by (le, http_route)
|
||||||
|
(rate(http_request_duration_seconds_bucket{http_route=~"/api/v1/chats/.*/attachments"}[5m]))
|
||||||
|
) > 2
|
||||||
|
for: 3m
|
||||||
|
labels:
|
||||||
|
severity: warning
|
||||||
|
annotations:
|
||||||
|
summary: "p95 upload latency > 2s"
|
||||||
|
runbook: "infra/runbooks/slow-upload.md"
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Alert: MessengerHighErrorRate
|
||||||
|
|
||||||
|
## Симптомы
|
||||||
|
- 5xx rate > 5% в течение 2 минут.
|
||||||
|
- Панель «API error ratio» в Grafana.
|
||||||
|
|
||||||
|
## Диагностика (по шагам)
|
||||||
|
1. Открыть Grafana → Dashboard «Messenger» → p95 latency.
|
||||||
|
2. Открыть Explore → Loki: `{service_name="messenger-api"} |= "event=unhandled_exception"`.
|
||||||
|
3. Найти в логах `request_id`, затем в Tempo trace с этим span или по
|
||||||
|
trace_id из поля `trace_id`.
|
||||||
|
4. Смотрим какие зависимость отвечает: postgres/redis/s3. Соответствующие
|
||||||
|
ошибки пишутся как `event=db_unavailable`, `event=redis_unavailable`,
|
||||||
|
`event=s3_unavailable`.
|
||||||
|
|
||||||
|
## Действие
|
||||||
|
- Если виноват backend — перезапустить (`docker compose restart <service>`).
|
||||||
|
- Если ошибка идёт от кода — rollback через `docker compose up -d --build`
|
||||||
|
предыдущего тега.
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Alert: MessengerJobsBacklogGrowing
|
||||||
|
|
||||||
|
## Симптомы
|
||||||
|
- `jobs_processed_total{outcome="retry"}` > `success` + 5 за 10 минут.
|
||||||
|
|
||||||
|
## Диагностика
|
||||||
|
1. Проверить `docker compose ps worker` — процесс жив?
|
||||||
|
2. `docker compose exec rabbitmq rabbitmqctl list_queues name messages consumers`
|
||||||
|
3. Открыть Grafana → «Jobs processed by outcome» и «Job duration p95».
|
||||||
|
4. Открыть Tempo, найти span `job.consume` с ошибкой (status=ERROR).
|
||||||
|
|
||||||
|
## Действие
|
||||||
|
- Если worker упал — `docker compose restart worker`.
|
||||||
|
- Если очередь переполнена по `retry_exhausted` — проверить S3 (`minio`
|
||||||
|
контейнер healthy), затем `docker compose restart s3_cleanup`.
|
||||||
|
- При долгом backlog включить alert `for: 10m` и снизить `MAX_ATTEMPTS` в `.env`
|
||||||
|
для быстрого drain.
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
# Alert: MessengerUploadLatencyHigh
|
||||||
|
|
||||||
|
## Симптомы
|
||||||
|
- p95 длительности POST `/api/v1/chats/{id}/attachments` > 2s.
|
||||||
|
|
||||||
|
## Диагностика
|
||||||
|
1. Grafana: p95 по route `/api/v1/chats/{id}/attachments`.
|
||||||
|
2. Tempo: trace `POST /api/v1/chats/{id}/attachments` — найти самый долгий
|
||||||
|
child span (`put_object` в S3 или `INSERT` в postgres).
|
||||||
|
3. Loki: `{service_name="messenger-api"} |= "event=http" |~ "attachments"`.
|
||||||
|
|
||||||
|
## Действие
|
||||||
|
- Если виноват S3 — проверить `docker compose ps minio`.
|
||||||
|
- Если БД — увеличить `max_size` пула или `statement_timeout`.
|
||||||
|
- Если телеметрия — переключить sampling (см. TRACK1).
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
grpc_listen_port: 9095
|
||||||
|
log_level: warn
|
||||||
|
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
http:
|
||||||
|
endpoint: 0.0.0.0:4318
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
|
||||||
|
ingester:
|
||||||
|
trace_idle_period: 10s
|
||||||
|
max_block_bytes: 1048576
|
||||||
|
max_block_duration: 5m
|
||||||
|
|
||||||
|
compactor:
|
||||||
|
compaction:
|
||||||
|
block_retention: 24h
|
||||||
|
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
local:
|
||||||
|
path: /var/tempo/traces
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
|
||||||
|
metrics_generator:
|
||||||
|
storage:
|
||||||
|
path: /var/tempo/generator/wal
|
||||||
+6
-2
@@ -3,7 +3,11 @@ uvicorn[standard]==0.32.0
|
|||||||
psycopg[binary]==3.2.3
|
psycopg[binary]==3.2.3
|
||||||
psycopg_pool==3.2.3
|
psycopg_pool==3.2.3
|
||||||
redis==5.2.0
|
redis==5.2.0
|
||||||
openapi-spec-validator==0.7.2
|
|
||||||
boto3==1.35.74
|
boto3==1.35.74
|
||||||
Pillow==11.0.0
|
Pillow==11.0.0
|
||||||
pika==1.3.2
|
pika==1.3.2
|
||||||
|
opentelemetry-api==1.31.0
|
||||||
|
opentelemetry-sdk==1.31.0
|
||||||
|
opentelemetry-exporter-otlp-proto-http==1.31.0
|
||||||
|
opentelemetry-instrumentation-fastapi==0.52b0
|
||||||
|
opentelemetry-instrumentation-requests==0.52b0
|
||||||
@@ -1,4 +1,8 @@
|
|||||||
"""Вложения (lab5): upload → 202 queued, async worker, download вариантов."""
|
"""Вложения (lab5/lab6): upload → 202 queued, async worker, download вариантов.
|
||||||
|
|
||||||
|
lab6: при создании outbox-строки кладём в payload W3C traceparent/tracestate
|
||||||
|
текущего HTTP-запроса. Ошибка инжекта не должна блокировать upload.
|
||||||
|
"""
|
||||||
import hashlib
|
import hashlib
|
||||||
import io
|
import io
|
||||||
import os
|
import os
|
||||||
@@ -12,6 +16,7 @@ from fastapi.responses import Response
|
|||||||
from PIL import Image, UnidentifiedImageError
|
from PIL import Image, UnidentifiedImageError
|
||||||
from starlette.concurrency import run_in_threadpool
|
from starlette.concurrency import run_in_threadpool
|
||||||
from botocore.exceptions import ClientError
|
from botocore.exceptions import ClientError
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
|
|
||||||
from ..models.schemas import Attachment, User
|
from ..models.schemas import Attachment, User
|
||||||
from ..storage import s3
|
from ..storage import s3
|
||||||
@@ -24,6 +29,7 @@ router = APIRouter(prefix="/api/v1", tags=["attachments"])
|
|||||||
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
MAX_UPLOAD_BYTES = int(os.environ.get("MAX_UPLOAD_BYTES", "10485760"))
|
||||||
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
MAX_IMAGE_PIXELS = int(os.environ.get("MAX_IMAGE_PIXELS", "40000000"))
|
||||||
PIPELINE_VERSION = 1
|
PIPELINE_VERSION = 1
|
||||||
|
_propagator = TraceContextTextMapPropagator()
|
||||||
|
|
||||||
|
|
||||||
def _require_member(chat_id: UUID, user_id: UUID):
|
def _require_member(chat_id: UUID, user_id: UUID):
|
||||||
@@ -140,6 +146,14 @@ async def upload_attachment(
|
|||||||
)
|
)
|
||||||
|
|
||||||
job_id = uuid4()
|
job_id = uuid4()
|
||||||
|
|
||||||
|
# lab6: снимок W3C trace context активного HTTP span.
|
||||||
|
trace_carrier: dict[str, str] = {}
|
||||||
|
try:
|
||||||
|
_propagator.inject(trace_carrier)
|
||||||
|
except Exception:
|
||||||
|
trace_carrier = {}
|
||||||
|
|
||||||
outbox_payload = {
|
outbox_payload = {
|
||||||
"job_id": str(job_id),
|
"job_id": str(job_id),
|
||||||
"type": "attachment.process.v1",
|
"type": "attachment.process.v1",
|
||||||
@@ -147,6 +161,10 @@ async def upload_attachment(
|
|||||||
"pipeline_version": PIPELINE_VERSION,
|
"pipeline_version": PIPELINE_VERSION,
|
||||||
"created_at": now.isoformat().replace("+00:00", "Z"),
|
"created_at": now.isoformat().replace("+00:00", "Z"),
|
||||||
}
|
}
|
||||||
|
if trace_carrier.get("traceparent"):
|
||||||
|
outbox_payload["traceparent"] = trace_carrier["traceparent"]
|
||||||
|
if trace_carrier.get("tracestate"):
|
||||||
|
outbox_payload["tracestate"] = trace_carrier["tracestate"]
|
||||||
|
|
||||||
# 2) INSERT attachment + outbox в ОДНОЙ транзакции.
|
# 2) INSERT attachment + outbox в ОДНОЙ транзакции.
|
||||||
# При сбое — компенсация: удаляем staging.
|
# При сбое — компенсация: удаляем staging.
|
||||||
|
|||||||
@@ -30,9 +30,15 @@ def readiness() -> Health:
|
|||||||
main.py конвертирует его в 503 с телом Error из contracts/openapi.json.
|
main.py конвертирует его в 503 с телом Error из contracts/openapi.json.
|
||||||
Все проверки — с короткими таймаутами, чтобы не зависать надолго.
|
Все проверки — с короткими таймаутами, чтобы не зависать надолго.
|
||||||
"""
|
"""
|
||||||
with _db.connection() as conn, conn.cursor() as cur:
|
try:
|
||||||
cur.execute("SELECT 1")
|
with _db.connection() as conn, conn.cursor() as cur:
|
||||||
cur.fetchone()
|
cur.execute("SELECT 1")
|
||||||
|
cur.fetchone()
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
# Пул уже проверяет живость соединения (check_connection) и короткий
|
||||||
|
# timeout=3.0; здесь лишь превращаем любую ошибку БД в 503, чтобы
|
||||||
|
# после рестарта PostgreSQL readiness быстро возвращался в 200.
|
||||||
|
raise RuntimeError("db_unavailable: %s" % type(exc).__name__) from exc
|
||||||
# Redis (в режиме redis)
|
# Redis (в режиме redis)
|
||||||
if _store() == "redis":
|
if _store() == "redis":
|
||||||
_redis_client().ping()
|
_redis_client().ping()
|
||||||
|
|||||||
+113
-36
@@ -12,26 +12,22 @@ from fastapi.responses import JSONResponse
|
|||||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||||
import psycopg
|
import psycopg
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
from opentelemetry import trace as _otel_trace
|
||||||
|
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
||||||
from .api import attachments, auth, chats, health, messages, users
|
from .api import attachments, auth, chats, health, messages, users
|
||||||
from .storage.db import init_pool, close_pool
|
from .storage.db import init_pool, close_pool
|
||||||
|
from .telemetry import init_telemetry, INSTANCE_ID, meter, tracer
|
||||||
|
|
||||||
|
|
||||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
# Базовый логгер: реальный формат выставляет telemetry.install_log_format()
|
||||||
logging.basicConfig(
|
# при вызове init_telemetry(). Здесь — минимальный fallback для импорта.
|
||||||
level=logging.INFO,
|
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
||||||
stream=sys.stdout,
|
|
||||||
)
|
|
||||||
logger = logging.getLogger("app")
|
logger = logging.getLogger("app")
|
||||||
|
|
||||||
# X-Instance-Id: стабильный в пределах жизни процесса. Значение приходит
|
|
||||||
# из env INSTANCE_ID (задаётся Dockerfile/Compose) либо генерируется один раз.
|
|
||||||
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
|
||||||
|
|
||||||
|
|
||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
init_pool() # пул соединений PostgreSQL с таймаутами
|
init_pool()
|
||||||
logger.info(
|
logger.info(
|
||||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||||
os.environ.get("APP_ENV", "lab"),
|
os.environ.get("APP_ENV", "lab"),
|
||||||
@@ -44,12 +40,45 @@ async def lifespan(app: FastAPI):
|
|||||||
|
|
||||||
|
|
||||||
app = FastAPI(
|
app = FastAPI(
|
||||||
title="MTUCI Messenger — lab5",
|
title="MTUCI Messenger — lab6",
|
||||||
version="1.5.0",
|
version="1.6.0",
|
||||||
lifespan=lifespan,
|
lifespan=lifespan,
|
||||||
swagger_ui_parameters={"persistAuthorization": True},
|
swagger_ui_parameters={"persistAuthorization": True},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# OTel инициализация и FastAPI auto-instrumentation.
|
||||||
|
init_telemetry("messenger-api", "1.6.0")
|
||||||
|
|
||||||
|
|
||||||
|
# --- Метрики HTTP ---
|
||||||
|
_http_counter = meter("messenger").create_counter(
|
||||||
|
"http_requests_total",
|
||||||
|
description="HTTP requests count",
|
||||||
|
unit="1",
|
||||||
|
)
|
||||||
|
# Явные границы бакетов в СЕКУНДАХ, с разрешением в миллисекундном диапазоне
|
||||||
|
# и вокруг порога SLO 2s (upload p95 alert). Дефолтные экспоненциальные
|
||||||
|
# бакеты (0, 5, 10, 25, …) грубы: миллисекундные запросы попадали в один
|
||||||
|
# широкий bucket, а histogram_quantile интерполировал ложные секунды.
|
||||||
|
_HTTP_DURATION_BUCKETS = [
|
||||||
|
0.001, 0.0025, 0.005, 0.0075, 0.01, 0.015, 0.02, 0.03, 0.05,
|
||||||
|
0.075, 0.1, 0.15, 0.2, 0.3, 0.5, 0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0,
|
||||||
|
]
|
||||||
|
_http_hist = meter("messenger").create_histogram(
|
||||||
|
"http_request_duration_seconds",
|
||||||
|
description="HTTP request duration",
|
||||||
|
unit="s",
|
||||||
|
explicit_bucket_boundaries_advisory=_HTTP_DURATION_BUCKETS,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Фильтр: убираем реальные UUID из маршрута → route template.
|
||||||
|
import re as _re
|
||||||
|
_ROUTE_UUID_RE = _re.compile(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
|
||||||
|
|
||||||
|
|
||||||
|
def _route_template(path: str) -> str:
|
||||||
|
return _ROUTE_UUID_RE.sub("{id}", path)
|
||||||
|
|
||||||
|
|
||||||
def custom_openapi():
|
def custom_openapi():
|
||||||
if app.openapi_schema:
|
if app.openapi_schema:
|
||||||
@@ -61,27 +90,79 @@ def custom_openapi():
|
|||||||
|
|
||||||
app.openapi = custom_openapi
|
app.openapi = custom_openapi
|
||||||
|
|
||||||
|
# Отдельный tracer для событийного span в middleware. Он создаётся как child
|
||||||
|
# SERVER span, который создаёт OTel FastAPI instrumentation ниже.
|
||||||
|
# ВАЖНО: FastAPIInstrumentor.instrument_app(app) вызывается ПОСЛЕ объявления
|
||||||
|
# middleware, поэтому OTel ASGI middleware оказывается внешним: он извлекает
|
||||||
|
# W3C traceparent из входящих headers, продолжает внешний trace и создаёт
|
||||||
|
# SERVER span. Наш middleware выполняется внутри него, создаёт http.request
|
||||||
|
# как INTERNAL child, и логи/метрики берут корректный trace_id.
|
||||||
|
_http_tracer = tracer("app.http")
|
||||||
|
|
||||||
|
|
||||||
@app.middleware("http")
|
@app.middleware("http")
|
||||||
async def observability_middleware(request: Request, call_next):
|
async def observability_middleware(request: Request, call_next):
|
||||||
"""X-Request-Id и X-Instance-Id во всех ответах + структурный лог."""
|
"""X-Request-Id и X-Instance-Id во всех ответах + структурированный лог + метрики.
|
||||||
|
|
||||||
|
Лог event=http пишется ВНУТРИ активного span (`http.request`), он
|
||||||
|
child SERVER span от OTel auto-instrumentation, поэтому trace_id
|
||||||
|
корректно связывает лог с внешним trace.
|
||||||
|
"""
|
||||||
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex
|
||||||
request.state.request_id = request_id
|
request.state.request_id = request_id
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
response = await call_next(request)
|
route = _route_template(request.url.path)
|
||||||
response.headers["X-Request-Id"] = request_id
|
|
||||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
# http.request — INTERNAL child текущего (SERVER) span, созданного OTel
|
||||||
duration_ms = round((time.monotonic() - started) * 1000, 2)
|
# auto-instrumentation. Parent берётся из активного контекста: входящий
|
||||||
path = request.url.path
|
# traceparent уже извлечён ASGI middleware.
|
||||||
logger.info(
|
with _http_tracer.start_as_current_span(
|
||||||
"event=http method=%s path=%s status=%s duration_ms=%s request_id=%s instance_id=%s",
|
"http.request",
|
||||||
request.method, path, response.status_code,
|
attributes={
|
||||||
duration_ms, request_id, INSTANCE_ID,
|
"http.method": request.method,
|
||||||
)
|
"http.route": route,
|
||||||
return response
|
},
|
||||||
|
) as span:
|
||||||
|
response = await call_next(request)
|
||||||
|
duration_s = time.monotonic() - started
|
||||||
|
duration_ms = round(duration_s * 1000, 2)
|
||||||
|
status_class = "%dxx" % (response.status_code // 100)
|
||||||
|
|
||||||
|
response.headers["X-Request-Id"] = request_id
|
||||||
|
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
|
|
||||||
|
_http_counter.add(
|
||||||
|
1,
|
||||||
|
{"http.method": request.method, "http.route": route,
|
||||||
|
"http.status_class": status_class},
|
||||||
|
)
|
||||||
|
_http_hist.record(
|
||||||
|
duration_s,
|
||||||
|
{"http.method": request.method, "http.route": route,
|
||||||
|
"http.status_class": status_class},
|
||||||
|
)
|
||||||
|
span.set_attribute("http.status_class", status_class)
|
||||||
|
span.set_attribute("http.status_code", response.status_code)
|
||||||
|
|
||||||
|
# Лог ВНУТРИ span → record.trace_id валидный, Loki получает
|
||||||
|
# корреляцию с Tempo.
|
||||||
|
logger.info(
|
||||||
|
"event=http method=%s path=%s status=%s duration_ms=%s "
|
||||||
|
"request_id=%s instance_id=%s",
|
||||||
|
request.method, request.url.path, response.status_code,
|
||||||
|
duration_ms, request_id, INSTANCE_ID,
|
||||||
|
)
|
||||||
|
return response
|
||||||
|
|
||||||
|
|
||||||
# Словарь HTTP-кодов → кодов ошибок из контракта
|
# FastAPI auto-instrumentation ДОЛЖНА быть установлена ПОСЛЕ пользовательского
|
||||||
|
# @app.middleware("http"), чтобы оказаться внешним middleware и создать SERVER
|
||||||
|
# span с корректным parent из входного traceparent. Этот вызов также
|
||||||
|
# инструментирует httpx/requests client-вызовы внутри приложения.
|
||||||
|
FastAPIInstrumentor.instrument_app(app)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Обработчики ошибок (без изменений) ---
|
||||||
_ERROR_CODES = {
|
_ERROR_CODES = {
|
||||||
400: "invalid_request",
|
400: "invalid_request",
|
||||||
401: "unauthorized",
|
401: "unauthorized",
|
||||||
@@ -96,22 +177,17 @@ _ERROR_CODES = {
|
|||||||
|
|
||||||
|
|
||||||
def _unauthorized_challenge(path: str) -> str:
|
def _unauthorized_challenge(path: str) -> str:
|
||||||
"""Basic — только для POST /api/v1/auth/sessions; остальное — Bearer."""
|
|
||||||
if path == "/api/v1/auth/sessions":
|
if path == "/api/v1/auth/sessions":
|
||||||
return 'Basic realm="messenger", charset="UTF-8"'
|
return 'Basic realm="messenger", charset="UTF-8"'
|
||||||
return 'Bearer realm="messenger"'
|
return 'Bearer realm="messenger"'
|
||||||
|
|
||||||
|
|
||||||
def _error_response(
|
def _error_response(status_code: int, message: str, request_id: str,
|
||||||
status_code: int, message: str, request_id: str, path: str = ""
|
path: str = "") -> JSONResponse:
|
||||||
) -> JSONResponse:
|
|
||||||
code = _ERROR_CODES.get(status_code, "internal_error")
|
code = _ERROR_CODES.get(status_code, "internal_error")
|
||||||
headers = {}
|
headers = {}
|
||||||
if status_code == 401:
|
if status_code == 401:
|
||||||
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
headers["WWW-Authenticate"] = _unauthorized_challenge(path)
|
||||||
# Контракт: X-Request-Id и X-Instance-Id обязательны во ВСЕХ ответах,
|
|
||||||
# включая 500, которые формируются в обход middleware (exception handlers
|
|
||||||
# срабатывают ПОСЛЕ call_next). Проставляем их здесь явно.
|
|
||||||
headers["X-Request-Id"] = request_id
|
headers["X-Request-Id"] = request_id
|
||||||
headers["X-Instance-Id"] = INSTANCE_ID
|
headers["X-Instance-Id"] = INSTANCE_ID
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
@@ -136,7 +212,6 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
|
|||||||
|
|
||||||
@app.exception_handler(psycopg.OperationalError)
|
@app.exception_handler(psycopg.OperationalError)
|
||||||
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError):
|
||||||
"""PostgreSQL недоступен → 503 unavailable, без внутренних деталей."""
|
|
||||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||||
logger.error("event=db_unavailable type=%s request_id=%s",
|
logger.error("event=db_unavailable type=%s request_id=%s",
|
||||||
type(exc).__name__, request_id)
|
type(exc).__name__, request_id)
|
||||||
@@ -147,6 +222,9 @@ async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError
|
|||||||
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
async def runtime_error_handler(request: Request, exc: RuntimeError):
|
||||||
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
request_id = getattr(request.state, "request_id", uuid.uuid4().hex)
|
||||||
text = str(exc)
|
text = str(exc)
|
||||||
|
if "db_unavailable" in text:
|
||||||
|
logger.error("event=db_unavailable request_id=%s", request_id)
|
||||||
|
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||||
if "redis_unavailable" in text:
|
if "redis_unavailable" in text:
|
||||||
logger.error("event=redis_unavailable request_id=%s", request_id)
|
logger.error("event=redis_unavailable request_id=%s", request_id)
|
||||||
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
return _error_response(503, "Зависимость недоступна", request_id, request.url.path)
|
||||||
@@ -179,12 +257,11 @@ if __name__ == "__main__":
|
|||||||
"app.main:app",
|
"app.main:app",
|
||||||
host="0.0.0.0",
|
host="0.0.0.0",
|
||||||
port=8080,
|
port=8080,
|
||||||
log_level="info"
|
log_level="info",
|
||||||
)
|
)
|
||||||
server = uvicorn.Server(config)
|
server = uvicorn.Server(config)
|
||||||
|
|
||||||
def _handle_sigterm(signum, frame):
|
def _handle_sigterm(signum, frame):
|
||||||
"""SIGTERM: логируем и инициируем graceful shutdown uvicorn."""
|
|
||||||
logger.info("event=sigterm_received signal=%s", signum)
|
logger.info("event=sigterm_received signal=%s", signum)
|
||||||
server.should_exit = True
|
server.should_exit = True
|
||||||
|
|
||||||
|
|||||||
+68
-15
@@ -1,8 +1,11 @@
|
|||||||
"""Outbox worker lab5 level 4: publish неопубликованных job в RabbitMQ.
|
"""Outbox worker lab5/lab6: publish неопубликованных job в RabbitMQ с трейсингом.
|
||||||
|
|
||||||
Закрывает разрыв COMMIT → publish: если API упал после COMMIT, outbox
|
lab6: payload строки outbox содержит traceparent/tracestate, снятые в момент
|
||||||
осталась в БД; этот процесс опубликует её после рестарта. Publisher
|
upload-запроса API. Восстанавливаем контекст, создаём span job.publish как
|
||||||
confirm гарантирует приём брокером перед mark published.
|
child upload-span и инжектим обновлённый traceparent в headers сообщения.
|
||||||
|
|
||||||
|
Лог event=outbox_published пишется ВНУТРИ span job.publish, чтобы в Loki
|
||||||
|
попадал настоящий trace_id (корреляция лог↔trace).
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
import signal
|
import signal
|
||||||
@@ -10,18 +13,23 @@ import sys
|
|||||||
import time
|
import time
|
||||||
import traceback
|
import traceback
|
||||||
|
|
||||||
|
from opentelemetry import context as otel_context, trace
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
|
|
||||||
from .storage.db import init_pool, close_pool
|
from .storage.db import init_pool, close_pool
|
||||||
from .storage.postgres import storage
|
from .storage.postgres import storage
|
||||||
from .storage.rabbit import publish_job
|
from .storage.rabbit import QUEUE, publish_job
|
||||||
|
from .telemetry import init_telemetry
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||||
level=logging.INFO,
|
|
||||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
||||||
stream=sys.stdout,
|
|
||||||
)
|
|
||||||
log = logging.getLogger("outbox")
|
log = logging.getLogger("outbox")
|
||||||
|
|
||||||
_stop = False
|
_stop = False
|
||||||
|
_tracer = trace.get_tracer("outbox")
|
||||||
|
_propagator = TraceContextTextMapPropagator()
|
||||||
|
|
||||||
|
init_telemetry("messenger-outbox", "1.6.0")
|
||||||
|
|
||||||
|
|
||||||
def _handle_sigterm(signum, frame):
|
def _handle_sigterm(signum, frame):
|
||||||
@@ -30,6 +38,55 @@ def _handle_sigterm(signum, frame):
|
|||||||
_stop = True
|
_stop = True
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_parent(payload: dict) -> otel_context.Context:
|
||||||
|
carrier: dict[str, str] = {}
|
||||||
|
if payload.get("traceparent"):
|
||||||
|
carrier["traceparent"] = str(payload["traceparent"])
|
||||||
|
if payload.get("tracestate"):
|
||||||
|
carrier["tracestate"] = str(payload["tracestate"])
|
||||||
|
if not carrier:
|
||||||
|
return otel_context.Context()
|
||||||
|
try:
|
||||||
|
return _propagator.extract(carrier=carrier)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.warning("event=trace_parent_parse_failed type=%s", type(exc).__name__)
|
||||||
|
return otel_context.Context()
|
||||||
|
|
||||||
|
|
||||||
|
def _publish_with_trace(payload: dict, outbox_id: int) -> None:
|
||||||
|
"""Публикует payload; mark_published и лог — внутри span."""
|
||||||
|
parent_ctx = _extract_parent(payload)
|
||||||
|
carrier: dict[str, str] = {}
|
||||||
|
with _tracer.start_as_current_span(
|
||||||
|
"job.publish",
|
||||||
|
context=parent_ctx,
|
||||||
|
kind=SpanKind.PRODUCER,
|
||||||
|
attributes={
|
||||||
|
"messaging.system": "rabbitmq",
|
||||||
|
"messaging.destination.name": QUEUE,
|
||||||
|
"job.id": str(payload.get("job_id", "")),
|
||||||
|
"job.type": str(payload.get("type", "unknown")),
|
||||||
|
"outbox.id": int(outbox_id),
|
||||||
|
},
|
||||||
|
) as span:
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
_propagator.inject(carrier)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
log.warning("event=trace_inject_failed type=%s", type(exc).__name__)
|
||||||
|
carrier = {}
|
||||||
|
publish_job(payload, extra_headers=carrier)
|
||||||
|
storage.mark_outbox_published(outbox_id)
|
||||||
|
# Лог внутри span → record.trace_id валидный.
|
||||||
|
log.info("event=outbox_published id=%s job_id=%s",
|
||||||
|
outbox_id, payload.get("job_id"))
|
||||||
|
span.set_status(Status(StatusCode.OK))
|
||||||
|
except Exception as exc:
|
||||||
|
span.record_exception(exc)
|
||||||
|
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
signal.signal(signal.SIGTERM, _handle_sigterm)
|
signal.signal(signal.SIGTERM, _handle_sigterm)
|
||||||
init_pool()
|
init_pool()
|
||||||
@@ -48,16 +105,12 @@ def main() -> None:
|
|||||||
if _stop:
|
if _stop:
|
||||||
break
|
break
|
||||||
try:
|
try:
|
||||||
publish_job(payload)
|
_publish_with_trace(payload, outbox_id)
|
||||||
storage.mark_outbox_published(outbox_id)
|
|
||||||
log.info("event=outbox_published id=%s job_id=%s",
|
|
||||||
outbox_id, payload.get("job_id"))
|
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
log.warning(
|
log.warning(
|
||||||
"event=outbox_publish_failed id=%s type=%s msg=%s",
|
"event=outbox_publish_failed id=%s type=%s msg=%s",
|
||||||
outbox_id, type(exc).__name__, str(exc)[:300],
|
outbox_id, type(exc).__name__, str(exc)[:300],
|
||||||
)
|
)
|
||||||
# не выходим, попробуем в следующем цикле
|
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
break
|
break
|
||||||
|
|
||||||
|
|||||||
+10
-1
@@ -25,8 +25,17 @@ def init_pool() -> None:
|
|||||||
conninfo=_dsn(),
|
conninfo=_dsn(),
|
||||||
min_size=2,
|
min_size=2,
|
||||||
max_size=10,
|
max_size=10,
|
||||||
timeout=5.0,
|
# Короткий таймаут получения соединения из пула: readiness/бизнес-запрос
|
||||||
|
# при мёртвой БД должен быстро вернуть 503, а не висеть.
|
||||||
|
timeout=3.0,
|
||||||
max_idle=300.0,
|
max_idle=300.0,
|
||||||
|
# check: перед выдачей соединения проверяем его живость; мёртвые
|
||||||
|
# соединения после рестарта PostgreSQL отбрасываются, пул сам
|
||||||
|
# открывает новые — readiness восстанавливается без рестарта API.
|
||||||
|
check=ConnectionPool.check_connection,
|
||||||
|
# Раз в 30с фоновый worker пула добивает min_size живыми соединениями,
|
||||||
|
# чтобы после старта БД готовность вернулась в пределах окна теста.
|
||||||
|
reconnect_timeout=30.0,
|
||||||
kwargs={"options": "-c statement_timeout=5000"},
|
kwargs={"options": "-c statement_timeout=5000"},
|
||||||
open=True,
|
open=True,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -4,10 +4,7 @@
|
|||||||
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
- Retry: TTL-очереди с dead-letter обратно в основную; x-retry-count.
|
||||||
- DLQ: финальные ошибки и исчерпанные retry.
|
- DLQ: финальные ошибки и исчерпанные retry.
|
||||||
- Publisher confirms: publish() ждёт подтверждения брокера.
|
- Publisher confirms: publish() ждёт подтверждения брокера.
|
||||||
|
- lab6: extra_headers для traceparent/tracestate.
|
||||||
ВАЖНО: setup_topology вызывается в worker при старте и в outbox
|
|
||||||
однократно при первом publish. Не декларируем топологию на каждый
|
|
||||||
publish — иначе гонка с параллельными декларациями.
|
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
@@ -88,14 +85,15 @@ def _ensure_topology(ch: pika.adapters.blocking_connection.BlockingChannel) -> N
|
|||||||
_topology_ready = True
|
_topology_ready = True
|
||||||
|
|
||||||
|
|
||||||
def publish_job(payload: dict) -> None:
|
def publish_job(payload: dict, extra_headers: Optional[dict] = None) -> None:
|
||||||
"""Публикация job с publisher confirm. Бросает при неудаче."""
|
"""Публикация job с publisher confirm. extra_headers — traceparent."""
|
||||||
conn = connect()
|
conn = connect()
|
||||||
try:
|
try:
|
||||||
ch = conn.channel()
|
ch = conn.channel()
|
||||||
ch.confirm_delivery()
|
ch.confirm_delivery()
|
||||||
_ensure_topology(ch)
|
_ensure_topology(ch)
|
||||||
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
body = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
|
||||||
|
headers = dict(extra_headers or {})
|
||||||
ch.basic_publish(
|
ch.basic_publish(
|
||||||
exchange=EXCHANGE,
|
exchange=EXCHANGE,
|
||||||
routing_key=QUEUE,
|
routing_key=QUEUE,
|
||||||
@@ -103,6 +101,7 @@ def publish_job(payload: dict) -> None:
|
|||||||
properties=pika.BasicProperties(
|
properties=pika.BasicProperties(
|
||||||
delivery_mode=2,
|
delivery_mode=2,
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
|
headers=headers or None,
|
||||||
),
|
),
|
||||||
mandatory=True,
|
mandatory=True,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,160 @@
|
|||||||
|
"""Единая точка инициализации OpenTelemetry для API и worker.
|
||||||
|
|
||||||
|
- OTLP/HTTP → Collector (otel-collector:4318).
|
||||||
|
- resource: service.name/version/instance.id/deployment.environment.name=lab.
|
||||||
|
- LoggingFilter подставляет trace_id/span_id в каждую запись, чтобы они
|
||||||
|
попадали и в stdout (видно глазами), и в Loki (в тексте строки) — это
|
||||||
|
требование lab6 level4 (связь лога и trace).
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from opentelemetry import metrics, trace
|
||||||
|
from opentelemetry._logs import set_logger_provider
|
||||||
|
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.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||||
|
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||||
|
|
||||||
|
|
||||||
|
_INITIALIZED = False
|
||||||
|
INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
||||||
|
|
||||||
|
|
||||||
|
def _endpoint() -> str:
|
||||||
|
return os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318").rstrip("/")
|
||||||
|
|
||||||
|
|
||||||
|
def _resource(service_name: str, service_version: str) -> Resource:
|
||||||
|
return Resource.create(
|
||||||
|
{
|
||||||
|
"service.name": service_name,
|
||||||
|
"service.version": service_version,
|
||||||
|
"service.instance.id": INSTANCE_ID,
|
||||||
|
"deployment.environment.name": os.environ.get("APP_ENV", "lab"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _build_trace_provider(resource: Resource) -> TracerProvider:
|
||||||
|
provider = TracerProvider(resource=resource)
|
||||||
|
exporter = OTLPSpanExporter(endpoint=_endpoint() + "/v1/traces", timeout=5)
|
||||||
|
provider.add_span_processor(
|
||||||
|
BatchSpanProcessor(exporter, max_queue_size=2048,
|
||||||
|
max_export_batch_size=512,
|
||||||
|
schedule_delay_millis=2000)
|
||||||
|
)
|
||||||
|
return provider
|
||||||
|
|
||||||
|
|
||||||
|
def _build_meter_provider(resource: Resource) -> MeterProvider:
|
||||||
|
reader = PeriodicExportingMetricReader(
|
||||||
|
OTLPMetricExporter(endpoint=_endpoint() + "/v1/metrics", timeout=5),
|
||||||
|
export_interval_millis=5000,
|
||||||
|
)
|
||||||
|
return MeterProvider(resource=resource, metric_readers=[reader])
|
||||||
|
|
||||||
|
|
||||||
|
def _build_logger_provider(resource: Resource) -> LoggerProvider:
|
||||||
|
provider = LoggerProvider(resource=resource)
|
||||||
|
provider.add_log_record_processor(
|
||||||
|
BatchLogRecordProcessor(
|
||||||
|
OTLPLogExporter(endpoint=_endpoint() + "/v1/logs", timeout=5),
|
||||||
|
max_queue_size=2048,
|
||||||
|
max_export_batch_size=512,
|
||||||
|
schedule_delay_millis=2000,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return provider
|
||||||
|
|
||||||
|
|
||||||
|
class TraceContextFilter(logging.Filter):
|
||||||
|
"""Подставляет record.trace_id / record.span_id из активного span.
|
||||||
|
|
||||||
|
Если активного span нет — пишет "0"*32 и "0"*16, чтобы лог-формат
|
||||||
|
оставался валидным (не падал с KeyError). Так же OTel сам поступает.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def filter(self, record: logging.LogRecord) -> bool:
|
||||||
|
span = trace.get_current_span()
|
||||||
|
span_ctx = span.get_span_context() if span else None
|
||||||
|
if span_ctx is not None and span_ctx.is_valid:
|
||||||
|
record.trace_id = format(span_ctx.trace_id, "032x")
|
||||||
|
record.span_id = format(span_ctx.span_id, "016x")
|
||||||
|
else:
|
||||||
|
record.trace_id = "0" * 32
|
||||||
|
record.span_id = "0" * 16
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
_LOG_FORMAT = (
|
||||||
|
"%(asctime)s %(levelname)s %(name)s "
|
||||||
|
"trace_id=%(trace_id)s span_id=%(span_id)s %(message)s"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def install_log_format() -> None:
|
||||||
|
"""Единый формат логов API/worker/outbox.
|
||||||
|
|
||||||
|
Поля trace_id/span_id гарантированно существуют благодаря
|
||||||
|
TraceContextFilter. Их наличие обеспечивает уровень 4 (корреляция
|
||||||
|
логов и trace) и делает Loki-запросы `|= "trace_id="` рабочими.
|
||||||
|
"""
|
||||||
|
handler = logging.StreamHandler()
|
||||||
|
handler.addFilter(TraceContextFilter())
|
||||||
|
handler.setFormatter(logging.Formatter(_LOG_FORMAT))
|
||||||
|
root = logging.getLogger()
|
||||||
|
root.handlers = [handler]
|
||||||
|
root.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
|
||||||
|
def init_telemetry(service_name: str, service_version: str = "1.6.0") -> None:
|
||||||
|
"""Идемпотентная инициализация OTel для процесса."""
|
||||||
|
global _INITIALIZED
|
||||||
|
if _INITIALIZED:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Сначала — единый формат логов и фильтр trace_id.
|
||||||
|
install_log_format()
|
||||||
|
|
||||||
|
resource = _resource(service_name, service_version)
|
||||||
|
trace.set_tracer_provider(_build_trace_provider(resource))
|
||||||
|
metrics.set_meter_provider(_build_meter_provider(resource))
|
||||||
|
logger_provider = _build_logger_provider(resource)
|
||||||
|
set_logger_provider(logger_provider)
|
||||||
|
|
||||||
|
# OTel handler шлёт те же записи в Collector → Loki. Он тоже видит
|
||||||
|
# trace_id из record, потому что span-контекст един.
|
||||||
|
#
|
||||||
|
# ВАЖНО: LoggingHandler.emit() формирует тело через self.format(record),
|
||||||
|
# где self.formatter наследуется от logging.Handler. Без явного
|
||||||
|
# formatter'а тело будет голым сообщением (msg % args) — без
|
||||||
|
# trace_id=/span_id=. Это ломало поиск в Loki `|= "trace_id="`.
|
||||||
|
# Поэтому задаём тот же формат и навешиваем TraceContextFilter
|
||||||
|
# непосредственно на OTel-хэндлер: фильтр должен отработать ДО emit,
|
||||||
|
# чтобы record.trace_id существовал на момент форматирования.
|
||||||
|
otel_handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider)
|
||||||
|
otel_handler.addFilter(TraceContextFilter())
|
||||||
|
otel_handler.setFormatter(logging.Formatter(_LOG_FORMAT))
|
||||||
|
logging.getLogger().addHandler(otel_handler)
|
||||||
|
|
||||||
|
_INITIALIZED = True
|
||||||
|
logging.getLogger("telemetry").info(
|
||||||
|
"event=otel_init service=%s instance_id=%s endpoint=%s",
|
||||||
|
service_name, INSTANCE_ID, _endpoint(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def tracer(name: str = "app"):
|
||||||
|
return trace.get_tracer(name)
|
||||||
|
|
||||||
|
|
||||||
|
def meter(name: str = "app"):
|
||||||
|
return metrics.get_meter(name)
|
||||||
+206
-97
@@ -1,10 +1,9 @@
|
|||||||
"""Worker lab5: обработка вложений из RabbitMQ.
|
"""Worker lab5/lab6: обработка вложений из RabbitMQ с трейсингом.
|
||||||
|
|
||||||
- at-least-once: manual ack после durable эффекта.
|
- at-least-once, идемпотентно, retry через TTL-очередь, DLQ.
|
||||||
- идемпотентность: ключ (attachment_id, pipeline_version, variant).
|
- OTel: consumer span на каждый job, извлечение trace context из заголовков
|
||||||
- retry с backoff через TTL retry-очереди, затем DLQ.
|
сообщения (W3C traceparent/tracestate), child spans на S3/DB операции.
|
||||||
- lease: processing_until, зависшие возвращаются в queued.
|
- Метрики: jobs_processed_total{outcome}, job_processing_duration_seconds.
|
||||||
- thumbnail 256×256 (JPEG), crop 128×128 (JPEG), optimized WebP 1280×1280.
|
|
||||||
"""
|
"""
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
@@ -13,10 +12,12 @@ import os
|
|||||||
import signal
|
import signal
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
from datetime import datetime, timedelta, timezone
|
|
||||||
|
|
||||||
import pika
|
import pika
|
||||||
from PIL import Image, ImageOps
|
from PIL import Image, ImageOps
|
||||||
|
from opentelemetry import context as otel_context, trace
|
||||||
|
from opentelemetry.trace import SpanKind, Status, StatusCode
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
|
|
||||||
from .storage import s3
|
from .storage import s3
|
||||||
from .storage.db import init_pool, close_pool
|
from .storage.db import init_pool, close_pool
|
||||||
@@ -25,12 +26,9 @@ from .storage.rabbit import (
|
|||||||
QUEUE, EXCHANGE, MAX_ATTEMPTS, connect, setup_topology,
|
QUEUE, EXCHANGE, MAX_ATTEMPTS, connect, setup_topology,
|
||||||
publish_retry, publish_dlq,
|
publish_retry, publish_dlq,
|
||||||
)
|
)
|
||||||
|
from .telemetry import init_telemetry, meter
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
||||||
level=logging.INFO,
|
|
||||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
||||||
stream=sys.stdout,
|
|
||||||
)
|
|
||||||
log = logging.getLogger("worker")
|
log = logging.getLogger("worker")
|
||||||
|
|
||||||
PIPELINE_VERSION = 1
|
PIPELINE_VERSION = 1
|
||||||
@@ -41,6 +39,53 @@ OPT_SIZE = (1280, 1280)
|
|||||||
OPT_QUALITY = 82
|
OPT_QUALITY = 82
|
||||||
|
|
||||||
_stop = False
|
_stop = False
|
||||||
|
_propagator = TraceContextTextMapPropagator()
|
||||||
|
|
||||||
|
|
||||||
|
# OTel инициализация — до первого сообщения
|
||||||
|
init_telemetry("messenger-worker", "1.6.0")
|
||||||
|
_tracer = trace.get_tracer("worker")
|
||||||
|
_meter = meter("messenger-worker")
|
||||||
|
_jobs_counter = _meter.create_counter(
|
||||||
|
"jobs_processed_total", description="Jobs processed by outcome", unit="1",
|
||||||
|
)
|
||||||
|
# Явные границы бакетов в СЕКУНДАХ: job-обработка (decode + resize + 3×S3 PUT
|
||||||
|
# + DB) обычно от десятков мс до единиц секунд. Дефолтные экспоненциальные
|
||||||
|
# бакеты слишком грубы для p95/p99 на этой шкале.
|
||||||
|
_JOB_DURATION_BUCKETS = [
|
||||||
|
0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.15, 0.25, 0.5,
|
||||||
|
0.75, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0, 30.0,
|
||||||
|
]
|
||||||
|
_jobs_hist = _meter.create_histogram(
|
||||||
|
"job_processing_duration_seconds",
|
||||||
|
description="Job processing duration",
|
||||||
|
unit="s",
|
||||||
|
explicit_bucket_boundaries_advisory=_JOB_DURATION_BUCKETS,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# --- span helpers: дочерние операции S3/DB ---
|
||||||
|
#
|
||||||
|
# ВАЖНО: атрибуты, содержащие точку (`db.operation`, `aws.s3.key` и т.п.),
|
||||||
|
# нельзя передавать как kwargs — Python-идентификатор с точкой невозможен.
|
||||||
|
# Поэтому оба хелпера принимают dict атрибутов.
|
||||||
|
|
||||||
|
def _s3_span(name: str, attrs: dict):
|
||||||
|
"""Context manager для S3-операции (CLIENT span внутри job.consume)."""
|
||||||
|
return _tracer.start_as_current_span(
|
||||||
|
name,
|
||||||
|
kind=SpanKind.CLIENT,
|
||||||
|
attributes={"messaging.system": "s3", **attrs},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _db_span(name: str, attrs: dict):
|
||||||
|
"""Context manager для DB-операции (CLIENT span внутри job.consume)."""
|
||||||
|
return _tracer.start_as_current_span(
|
||||||
|
name,
|
||||||
|
kind=SpanKind.CLIENT,
|
||||||
|
attributes={"db.system": "postgresql", **attrs},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _handle_sigterm(signum, frame):
|
def _handle_sigterm(signum, frame):
|
||||||
@@ -50,11 +95,11 @@ def _handle_sigterm(signum, frame):
|
|||||||
|
|
||||||
|
|
||||||
def _now_iso() -> str:
|
def _now_iso() -> str:
|
||||||
|
from datetime import datetime, timezone
|
||||||
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
|
||||||
|
|
||||||
|
|
||||||
def _to_rgb_white(img: Image.Image) -> Image.Image:
|
def _to_rgb_white(img: Image.Image) -> Image.Image:
|
||||||
"""Alpha компонуется на белый; EXIF orientation применяется."""
|
|
||||||
img = ImageOps.exif_transpose(img)
|
img = ImageOps.exif_transpose(img)
|
||||||
if img.mode in ("RGBA", "LA", "P"):
|
if img.mode in ("RGBA", "LA", "P"):
|
||||||
img = img.convert("RGBA")
|
img = img.convert("RGBA")
|
||||||
@@ -67,7 +112,6 @@ def _to_rgb_white(img: Image.Image) -> Image.Image:
|
|||||||
|
|
||||||
|
|
||||||
def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||||
"""Вписать в 256×256 без увеличения. Округление вниз, минимум 1 px."""
|
|
||||||
w, h = img.size
|
w, h = img.size
|
||||||
scale = min(THUMB_SIZE[0] / w, THUMB_SIZE[1] / h, 1.0)
|
scale = min(THUMB_SIZE[0] / w, THUMB_SIZE[1] / h, 1.0)
|
||||||
nw = max(1, int(w * scale))
|
nw = max(1, int(w * scale))
|
||||||
@@ -79,7 +123,6 @@ def _make_thumbnail(img: Image.Image) -> tuple[Image.Image, bytes]:
|
|||||||
|
|
||||||
|
|
||||||
def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||||
"""Центрированный квадрат 128×128 (маленькие допускают увеличение)."""
|
|
||||||
w, h = img.size
|
w, h = img.size
|
||||||
side = min(w, h)
|
side = min(w, h)
|
||||||
left = (w - side) // 2
|
left = (w - side) // 2
|
||||||
@@ -92,7 +135,6 @@ def _make_crop(img: Image.Image) -> tuple[Image.Image, bytes]:
|
|||||||
|
|
||||||
|
|
||||||
def _make_optimized(img: Image.Image) -> tuple[Image.Image, bytes]:
|
def _make_optimized(img: Image.Image) -> tuple[Image.Image, bytes]:
|
||||||
"""WebP, вписан в 1280×1280 без увеличения, EXIF удалён."""
|
|
||||||
w, h = img.size
|
w, h = img.size
|
||||||
scale = min(OPT_SIZE[0] / w, OPT_SIZE[1] / h, 1.0)
|
scale = min(OPT_SIZE[0] / w, OPT_SIZE[1] / h, 1.0)
|
||||||
nw = max(1, int(w * scale))
|
nw = max(1, int(w * scale))
|
||||||
@@ -108,8 +150,26 @@ def _sha256(data: bytes) -> str:
|
|||||||
return hashlib.sha256(data).hexdigest()
|
return hashlib.sha256(data).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _s3_put_variant(chat_id, att_id, name: str, data: bytes, ctype: str) -> str:
|
||||||
|
"""Общий путь: S3 PUT варианта внутри CLIENT span."""
|
||||||
|
key = s3.variant_key(chat_id, att_id, name)
|
||||||
|
with _s3_span("s3.put_object", {
|
||||||
|
"aws.s3.key": key,
|
||||||
|
"s3.operation": "put_object",
|
||||||
|
"s3.variant": name,
|
||||||
|
"s3.content_type": ctype,
|
||||||
|
"s3.size_bytes": len(data),
|
||||||
|
}):
|
||||||
|
s3.put_bytes(key, data, ctype)
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
def process_job(payload: dict) -> None:
|
def process_job(payload: dict) -> None:
|
||||||
"""Обработка одного job. Идемпотентна: finalize_ready использует ON CONFLICT."""
|
"""Обработка одного job. Идемпотентна через finalize_ready.
|
||||||
|
|
||||||
|
Внутри активного job.consume (CONSUMER) span создаются дочерние CLIENT
|
||||||
|
spans для S3 и DB, чтобы разложить задержку обработки по зависимостям.
|
||||||
|
"""
|
||||||
attachment_id = payload["attachment_id"]
|
attachment_id = payload["attachment_id"]
|
||||||
pipeline_version = payload.get("pipeline_version", 1)
|
pipeline_version = payload.get("pipeline_version", 1)
|
||||||
job_id = payload["job_id"]
|
job_id = payload["job_id"]
|
||||||
@@ -117,12 +177,15 @@ def process_job(payload: dict) -> None:
|
|||||||
log.info("event=job_received job_id=%s attachment_id=%s attempt=%s",
|
log.info("event=job_received job_id=%s attachment_id=%s attempt=%s",
|
||||||
job_id, attachment_id, payload.get("attempt", 1))
|
job_id, attachment_id, payload.get("attempt", 1))
|
||||||
|
|
||||||
# 1) Захватить lease. Если уже ready/failed — no-op (дубль).
|
with _db_span("db.claim_processing", {
|
||||||
if not storage.claim_processing(attachment_id, LEASE_SECONDS):
|
"db.operation": "UPDATE",
|
||||||
|
"attachment_id": str(attachment_id),
|
||||||
|
}):
|
||||||
|
claimed = storage.claim_processing(attachment_id, LEASE_SECONDS)
|
||||||
|
if not claimed:
|
||||||
log.info("event=job_skipped_already_done attachment_id=%s", attachment_id)
|
log.info("event=job_skipped_already_done attachment_id=%s", attachment_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
# 2) Получить staging key и метаданные.
|
|
||||||
pair = storage.get_attachment_with_key(attachment_id)
|
pair = storage.get_attachment_with_key(attachment_id)
|
||||||
if pair is None:
|
if pair is None:
|
||||||
log.warning("event=attachment_missing attachment_id=%s", attachment_id)
|
log.warning("event=attachment_missing attachment_id=%s", attachment_id)
|
||||||
@@ -132,28 +195,41 @@ def process_job(payload: dict) -> None:
|
|||||||
log.info("event=already_ready attachment_id=%s", attachment_id)
|
log.info("event=already_ready attachment_id=%s", attachment_id)
|
||||||
return
|
return
|
||||||
|
|
||||||
# 3) Скачать staging из S3.
|
|
||||||
try:
|
try:
|
||||||
raw, ctype = s3.get_object(staging_key)
|
with _s3_span("s3.get_object", {
|
||||||
|
"aws.s3.key": staging_key,
|
||||||
|
"s3.operation": "get_object",
|
||||||
|
"s3.variant": "staging",
|
||||||
|
}):
|
||||||
|
raw, ctype = s3.get_object(staging_key)
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
# Временная ошибка S3 — retry.
|
|
||||||
raise RuntimeError("staging_unavailable") from exc
|
raise RuntimeError("staging_unavailable") from exc
|
||||||
|
|
||||||
# 4) Проверить, что файл всё ещё валиден (worker defense-in-depth).
|
|
||||||
try:
|
try:
|
||||||
img = Image.open(io.BytesIO(raw))
|
img = Image.open(io.BytesIO(raw))
|
||||||
img.load()
|
img.load()
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
storage.finalize_failed(attachment_id, "invalid_image")
|
with _db_span("db.finalize_failed", {
|
||||||
|
"db.operation": "UPDATE",
|
||||||
|
"error_code": "invalid_image",
|
||||||
|
}):
|
||||||
|
storage.finalize_failed(attachment_id, "invalid_image")
|
||||||
log.warning("event=invalid_image attachment_id=%s type=%s",
|
log.warning("event=invalid_image attachment_id=%s type=%s",
|
||||||
attachment_id, type(exc).__name__)
|
attachment_id, type(exc).__name__)
|
||||||
return
|
return
|
||||||
|
|
||||||
img_rgb = _to_rgb_white(img)
|
img_rgb = _to_rgb_white(img)
|
||||||
|
|
||||||
# 5) Записать финальный оригинал.
|
# Финал: S3 PUT оригинала
|
||||||
final_key = s3.original_key(att.chat_id, att.id)
|
final_key = s3.original_key(att.chat_id, att.id)
|
||||||
s3.put_bytes(final_key, raw, att.content_type)
|
with _s3_span("s3.put_object", {
|
||||||
|
"aws.s3.key": final_key,
|
||||||
|
"s3.operation": "put_object",
|
||||||
|
"s3.variant": "original",
|
||||||
|
"s3.content_type": att.content_type,
|
||||||
|
"s3.size_bytes": len(raw),
|
||||||
|
}):
|
||||||
|
s3.put_bytes(final_key, raw, att.content_type)
|
||||||
|
|
||||||
variants = [{
|
variants = [{
|
||||||
"name": "original",
|
"name": "original",
|
||||||
@@ -165,57 +241,51 @@ def process_job(payload: dict) -> None:
|
|||||||
"sha256": _sha256(raw),
|
"sha256": _sha256(raw),
|
||||||
}]
|
}]
|
||||||
|
|
||||||
# 6) Thumbnail (обязателен).
|
# Thumbnail
|
||||||
_, thumb_bytes = _make_thumbnail(img_rgb)
|
_, thumb_bytes = _make_thumbnail(img_rgb)
|
||||||
thumb_key = s3.variant_key(att.chat_id, att.id, "thumbnail")
|
thumb_key = _s3_put_variant(att.chat_id, att.id, "thumbnail", thumb_bytes, "image/jpeg")
|
||||||
s3.put_bytes(thumb_key, thumb_bytes, "image/jpeg")
|
|
||||||
tw, th = Image.open(io.BytesIO(thumb_bytes)).size
|
tw, th = Image.open(io.BytesIO(thumb_bytes)).size
|
||||||
variants.append({
|
variants.append({
|
||||||
"name": "thumbnail",
|
"name": "thumbnail", "object_key": thumb_key,
|
||||||
"object_key": thumb_key,
|
"content_type": "image/jpeg", "size_bytes": len(thumb_bytes),
|
||||||
"content_type": "image/jpeg",
|
"width": tw, "height": th, "sha256": _sha256(thumb_bytes),
|
||||||
"size_bytes": len(thumb_bytes),
|
|
||||||
"width": tw,
|
|
||||||
"height": th,
|
|
||||||
"sha256": _sha256(thumb_bytes),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
# 7) Crop (level 4).
|
# Crop
|
||||||
_, crop_bytes = _make_crop(img_rgb)
|
_, crop_bytes = _make_crop(img_rgb)
|
||||||
crop_key = s3.variant_key(att.chat_id, att.id, "crop")
|
crop_key = _s3_put_variant(att.chat_id, att.id, "crop", crop_bytes, "image/jpeg")
|
||||||
s3.put_bytes(crop_key, crop_bytes, "image/jpeg")
|
|
||||||
cw, ch = Image.open(io.BytesIO(crop_bytes)).size
|
cw, ch = Image.open(io.BytesIO(crop_bytes)).size
|
||||||
variants.append({
|
variants.append({
|
||||||
"name": "crop",
|
"name": "crop", "object_key": crop_key,
|
||||||
"object_key": crop_key,
|
"content_type": "image/jpeg", "size_bytes": len(crop_bytes),
|
||||||
"content_type": "image/jpeg",
|
"width": cw, "height": ch, "sha256": _sha256(crop_bytes),
|
||||||
"size_bytes": len(crop_bytes),
|
|
||||||
"width": cw,
|
|
||||||
"height": ch,
|
|
||||||
"sha256": _sha256(crop_bytes),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
# 8) Optimized WebP (level 4).
|
# Optimized
|
||||||
_, opt_bytes = _make_optimized(img_rgb)
|
_, opt_bytes = _make_optimized(img_rgb)
|
||||||
opt_key = s3.variant_key(att.chat_id, att.id, "optimized")
|
opt_key = _s3_put_variant(att.chat_id, att.id, "optimized", opt_bytes, "image/webp")
|
||||||
s3.put_bytes(opt_key, opt_bytes, "image/webp")
|
|
||||||
ow, oh = Image.open(io.BytesIO(opt_bytes)).size
|
ow, oh = Image.open(io.BytesIO(opt_bytes)).size
|
||||||
variants.append({
|
variants.append({
|
||||||
"name": "optimized",
|
"name": "optimized", "object_key": opt_key,
|
||||||
"object_key": opt_key,
|
"content_type": "image/webp", "size_bytes": len(opt_bytes),
|
||||||
"content_type": "image/webp",
|
"width": ow, "height": oh, "sha256": _sha256(opt_bytes),
|
||||||
"size_bytes": len(opt_bytes),
|
|
||||||
"width": ow,
|
|
||||||
"height": oh,
|
|
||||||
"sha256": _sha256(opt_bytes),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
# 9) Атомарно: variants + status=ready.
|
with _db_span("db.finalize_ready", {
|
||||||
storage.finalize_ready(attachment_id, pipeline_version, variants)
|
"db.operation": "UPDATE",
|
||||||
|
"pipeline_version": pipeline_version,
|
||||||
|
"variants_count": len(variants),
|
||||||
|
}):
|
||||||
|
storage.finalize_ready(attachment_id, pipeline_version, variants)
|
||||||
|
|
||||||
# 10) Удалить staging после безопасной фиксации.
|
# Cleanup staging — best-effort, не критичен для результата.
|
||||||
try:
|
try:
|
||||||
s3.delete_object(staging_key)
|
with _s3_span("s3.delete_object", {
|
||||||
|
"aws.s3.key": staging_key,
|
||||||
|
"s3.operation": "delete_object",
|
||||||
|
"s3.variant": "staging",
|
||||||
|
}):
|
||||||
|
s3.delete_object(staging_key)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@@ -223,46 +293,85 @@ def process_job(payload: dict) -> None:
|
|||||||
attachment_id, job_id, len(variants))
|
attachment_id, job_id, len(variants))
|
||||||
|
|
||||||
|
|
||||||
def _on_message(ch, method, properties, body):
|
def _extract_trace_context(properties) -> otel_context.Context:
|
||||||
"""Callback consumer. ack/nack — явно."""
|
"""Извлекает W3C traceparent/tracestate из headers. Ошибка → пустой контекст."""
|
||||||
try:
|
try:
|
||||||
payload = json.loads(body)
|
headers = dict(properties.headers or {})
|
||||||
except Exception:
|
carrier = {
|
||||||
# Битый JSON — постоянная ошибка.
|
k.lower(): str(v)
|
||||||
log.error("event=invalid_job_json")
|
for k, v in headers.items()
|
||||||
ch.basic_nack(method.delivery_tag, requeue=False)
|
if k.lower() in ("traceparent", "tracestate")
|
||||||
return
|
}
|
||||||
|
if not carrier:
|
||||||
headers = dict(properties.headers or {})
|
return otel_context.Context()
|
||||||
retry_count = int(headers.get("x-retry-count", 0))
|
return _propagator.extract(carrier=carrier)
|
||||||
payload["attempt"] = retry_count + 1
|
|
||||||
payload["_headers"] = headers
|
|
||||||
|
|
||||||
try:
|
|
||||||
process_job(payload)
|
|
||||||
ch.basic_ack(method.delivery_tag)
|
|
||||||
except Exception as exc: # noqa: BLE001
|
except Exception as exc: # noqa: BLE001
|
||||||
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
log.warning("event=trace_extract_failed type=%s", type(exc).__name__)
|
||||||
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
return otel_context.Context()
|
||||||
if retry_count + 1 >= MAX_ATTEMPTS:
|
|
||||||
# Исчерпаны попытки — failed + DLQ.
|
|
||||||
try:
|
def _on_message(ch, method, properties, body):
|
||||||
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
"""Callback consumer. ack/nack — явно. Оборачивает обработку в CONSUMER span."""
|
||||||
except Exception:
|
parent_ctx = _extract_trace_context(properties)
|
||||||
pass
|
started = time.monotonic()
|
||||||
try:
|
with _tracer.start_as_current_span(
|
||||||
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
"job.consume", context=parent_ctx, kind=SpanKind.CONSUMER,
|
||||||
except Exception:
|
attributes={"messaging.system": "rabbitmq",
|
||||||
pass
|
"messaging.destination.name": QUEUE},
|
||||||
ch.basic_ack(method.delivery_tag)
|
) as span:
|
||||||
return
|
|
||||||
# Retry через TTL-очередь, затем ack текущей.
|
|
||||||
try:
|
try:
|
||||||
publish_retry(payload, retry_count + 1)
|
payload = json.loads(body)
|
||||||
ch.basic_ack(method.delivery_tag)
|
|
||||||
except Exception:
|
except Exception:
|
||||||
# Не смогли опубликовать retry — вернуть в очередь.
|
log.error("event=invalid_job_json")
|
||||||
ch.basic_nack(method.delivery_tag, requeue=True)
|
_jobs_counter.add(1, {"job.type": "unknown", "outcome": "invalid"})
|
||||||
|
ch.basic_nack(method.delivery_tag, requeue=False)
|
||||||
|
return
|
||||||
|
|
||||||
|
headers = dict(properties.headers or {})
|
||||||
|
retry_count = int(headers.get("x-retry-count", 0))
|
||||||
|
payload["attempt"] = retry_count + 1
|
||||||
|
payload["_headers"] = headers
|
||||||
|
span.set_attribute("job.id", str(payload.get("job_id", "")))
|
||||||
|
span.set_attribute("job.type", str(payload.get("type", "unknown")))
|
||||||
|
span.set_attribute("job.attempt", retry_count + 1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
process_job(payload)
|
||||||
|
duration = time.monotonic() - started
|
||||||
|
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||||
|
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "success"})
|
||||||
|
span.set_status(Status(StatusCode.OK))
|
||||||
|
ch.basic_ack(method.delivery_tag)
|
||||||
|
except Exception as exc: # noqa: BLE001
|
||||||
|
duration = time.monotonic() - started
|
||||||
|
span.record_exception(exc)
|
||||||
|
span.set_status(Status(StatusCode.ERROR, type(exc).__name__))
|
||||||
|
log.warning("event=job_retry attachment_id=%s attempt=%d type=%s",
|
||||||
|
payload.get("attachment_id"), retry_count + 1, type(exc).__name__)
|
||||||
|
if retry_count + 1 >= MAX_ATTEMPTS:
|
||||||
|
try:
|
||||||
|
with _db_span("db.finalize_failed", {
|
||||||
|
"db.operation": "UPDATE",
|
||||||
|
"error_code": "retry_exhausted",
|
||||||
|
}):
|
||||||
|
storage.finalize_failed(payload["attachment_id"], "retry_exhausted")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
publish_dlq({k: v for k, v in payload.items() if k != "_headers"})
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||||
|
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "failed"})
|
||||||
|
ch.basic_ack(method.delivery_tag)
|
||||||
|
return
|
||||||
|
_jobs_counter.add(1, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||||
|
_jobs_hist.record(duration, {"job.type": "attachment.process.v1", "outcome": "retry"})
|
||||||
|
try:
|
||||||
|
publish_retry(payload, retry_count + 1)
|
||||||
|
ch.basic_ack(method.delivery_tag)
|
||||||
|
except Exception:
|
||||||
|
ch.basic_nack(method.delivery_tag, requeue=True)
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
|||||||
@@ -0,0 +1,597 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Level 4 для lab6: сквозной trace API→broker→worker, метрики, логи, dashboard,
|
||||||
|
alert rules, поведение при отказе telemetry-backend.
|
||||||
|
|
||||||
|
Запуск:
|
||||||
|
$env:PYTHONUTF8="1"
|
||||||
|
python student-tests/lab6_test_level4.py --base-url http://localhost:8080
|
||||||
|
"""
|
||||||
|
import base64
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||||
|
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
SAMPLE = ROOT / "tests" / "fixtures" / "sample.png"
|
||||||
|
|
||||||
|
GRAFANA_URL = os.environ.get("GRAFANA_URL", "http://localhost:3000")
|
||||||
|
GRAFANA_ADMIN_USER = os.environ.get("GRAFANA_ADMIN_USER", "admin")
|
||||||
|
GRAFANA_ADMIN_PASSWORD = os.environ.get("GRAFANA_ADMIN_PASSWORD", "admin")
|
||||||
|
|
||||||
|
READY_TIMEOUT = int(os.environ.get("READY_TIMEOUT", "180"))
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_exec(service: str, *args: str, timeout: int = 30):
|
||||||
|
return subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", "exec", "-T", service, *args],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _compose(action: str, service: str, timeout: int = 90):
|
||||||
|
return subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", action, service],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _compose_logs(service: str, tail: int = 20) -> str:
|
||||||
|
r = subprocess.run(
|
||||||
|
["docker", "compose", "--env-file", ".env", "logs", "--no-color",
|
||||||
|
"--tail=%d" % tail, service],
|
||||||
|
cwd=str(ROOT), capture_output=True, text=True, timeout=30,
|
||||||
|
)
|
||||||
|
return (r.stdout or "") + (r.stderr or "")
|
||||||
|
|
||||||
|
|
||||||
|
def _http_get(url: str, timeout: float = 10.0, basic_auth: tuple | None = None):
|
||||||
|
headers = {"Accept": "application/json"}
|
||||||
|
if basic_auth is not None:
|
||||||
|
token = base64.b64encode(("%s:%s" % basic_auth).encode()).decode()
|
||||||
|
headers["Authorization"] = "Basic " + token
|
||||||
|
req = urllib.request.Request(url, headers=headers, method="GET")
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
|
return resp.status, resp.read().decode("utf-8", "replace")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return e.code, e.read().decode("utf-8", "replace")
|
||||||
|
except (urllib.error.URLError, OSError) as e:
|
||||||
|
return 0, "%s: %s" % (type(e).__name__, e)
|
||||||
|
|
||||||
|
|
||||||
|
def _prom_query(query: str) -> dict:
|
||||||
|
qs = "query=" + urllib.parse.quote(query, safe="")
|
||||||
|
r = _compose_exec(
|
||||||
|
"prometheus", "sh", "-c",
|
||||||
|
"wget -qO- 'http://localhost:9090/api/v1/query?%s'" % qs,
|
||||||
|
)
|
||||||
|
if r.returncode != 0 or not r.stdout.strip():
|
||||||
|
raise Failure("prometheus query failed: %s" % (r.stderr[:300] or r.stdout[:300]))
|
||||||
|
try:
|
||||||
|
return json.loads(r.stdout)
|
||||||
|
except Exception:
|
||||||
|
raise Failure("prometheus non-JSON: %s" % r.stdout[:300])
|
||||||
|
|
||||||
|
|
||||||
|
def _tempo_search(query: str, since_seconds: int = 300, limit: int = 20) -> list[dict]:
|
||||||
|
now = int(time.time())
|
||||||
|
start = now - since_seconds
|
||||||
|
qs = "q=%s&start=%d&end=%d&limit=%d" % (
|
||||||
|
urllib.parse.quote(query, safe=""), start, now, limit,
|
||||||
|
)
|
||||||
|
r = _compose_exec(
|
||||||
|
"tempo", "sh", "-c",
|
||||||
|
"wget -qO- 'http://localhost:3200/api/search?%s'" % qs,
|
||||||
|
)
|
||||||
|
if r.returncode != 0 or not r.stdout.strip():
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
data = json.loads(r.stdout)
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
return data.get("traces", []) or []
|
||||||
|
|
||||||
|
|
||||||
|
def _tempo_get_trace(trace_id: str) -> dict:
|
||||||
|
r = _compose_exec(
|
||||||
|
"tempo", "sh", "-c",
|
||||||
|
"wget -qO- 'http://localhost:3200/api/traces/%s'" % trace_id,
|
||||||
|
)
|
||||||
|
if r.returncode != 0 or not r.stdout.strip():
|
||||||
|
raise Failure("tempo trace fetch failed: %s" % (r.stderr[:300] or r.stdout[:300]))
|
||||||
|
return json.loads(r.stdout)
|
||||||
|
|
||||||
|
|
||||||
|
def _tempo_span_names(trace: dict) -> set[str]:
|
||||||
|
names: set[str] = set()
|
||||||
|
for batch in trace.get("batches", []):
|
||||||
|
scopes = batch.get("scopeSpans") or batch.get("instrumentationLibrarySpans") or []
|
||||||
|
for scope in scopes:
|
||||||
|
for span in scope.get("spans", []) or []:
|
||||||
|
names.add(span.get("name", ""))
|
||||||
|
return names
|
||||||
|
|
||||||
|
|
||||||
|
def _loki_query(query: str, since_seconds: int = 300, limit: int = 200) -> dict:
|
||||||
|
end = int(time.time() * 1e9)
|
||||||
|
start = end - since_seconds * 1_000_000_000
|
||||||
|
qs = "query=%s&start=%d&end=%d&limit=%d" % (
|
||||||
|
urllib.parse.quote(query, safe=""), start, end, limit,
|
||||||
|
)
|
||||||
|
r = _compose_exec(
|
||||||
|
"loki", "sh", "-c",
|
||||||
|
"wget -qO- 'http://localhost:3100/loki/api/v1/query_range?%s'" % qs,
|
||||||
|
)
|
||||||
|
if r.returncode != 0 or not r.stdout.strip():
|
||||||
|
raise Failure("loki query failed: %s" % (r.stderr[:300] or r.stdout[:300]))
|
||||||
|
try:
|
||||||
|
return json.loads(r.stdout)
|
||||||
|
except Exception:
|
||||||
|
raise Failure("loki returned non-JSON: %s" % r.stdout[:300])
|
||||||
|
|
||||||
|
|
||||||
|
def _raw_upload(c: Client, actor, chat_id: str, filename: str,
|
||||||
|
data: bytes, ctype: str):
|
||||||
|
qs = urllib.parse.urlencode({"filename": filename}, quote_via=urllib.parse.quote)
|
||||||
|
url = c.base + "/api/v1/chats/" + chat_id + "/attachments?" + qs
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url, data=data, method="POST",
|
||||||
|
headers={
|
||||||
|
"Authorization": "Bearer " + actor["token"],
|
||||||
|
"Content-Type": ctype,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with c.opener.open(req, timeout=30) as resp:
|
||||||
|
return resp.code, json.loads(resp.read()), resp.headers
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
body = e.read()
|
||||||
|
try:
|
||||||
|
return e.code, json.loads(body), e.headers
|
||||||
|
except Exception:
|
||||||
|
return e.code, None, e.headers
|
||||||
|
|
||||||
|
|
||||||
|
def _wait_ready(c, actor, att, timeout: int) -> dict:
|
||||||
|
"""Обёртка с диагностикой: если долго не ready — показываем статус и логи."""
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
last_status = None
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
a = c.call("GET", "/api/v1/attachments/" + att["id"], actor=actor,
|
||||||
|
schema="Attachment")["json"]
|
||||||
|
last_status = a.get("status")
|
||||||
|
if last_status == "ready":
|
||||||
|
return a
|
||||||
|
if last_status == "failed":
|
||||||
|
raise Failure("attachment failed: error_code=%r" % a.get("error_code"))
|
||||||
|
time.sleep(0.5)
|
||||||
|
diag = (
|
||||||
|
"\nlast_status=%r (waited %ss)\n--- outbox logs ---\n%s\n--- worker logs ---\n%s"
|
||||||
|
% (last_status, timeout, _compose_logs("outbox", 20),
|
||||||
|
_compose_logs("worker", 20))
|
||||||
|
)
|
||||||
|
raise Failure("attachment did not become ready" + diag)
|
||||||
|
|
||||||
|
|
||||||
|
def _wait_trace_with_spans(since_seconds: int, need_substrings: list[str],
|
||||||
|
timeout: float = 180.0) -> dict:
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
last_seen: list[dict] = []
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
for svc in ("messenger-api", "messenger-worker", "messenger-outbox"):
|
||||||
|
candidates = _tempo_search(
|
||||||
|
'{resource.service.name = "%s"}' % svc,
|
||||||
|
since_seconds=since_seconds,
|
||||||
|
)
|
||||||
|
for t in candidates:
|
||||||
|
trace_id = t.get("traceID")
|
||||||
|
if not trace_id:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
full = _tempo_get_trace(trace_id)
|
||||||
|
except Failure:
|
||||||
|
continue
|
||||||
|
names = _tempo_span_names(full)
|
||||||
|
last_seen.append({"trace_id": trace_id, "names": sorted(names)})
|
||||||
|
if all(any(s in n for n in names) for s in need_substrings):
|
||||||
|
return {"trace_id": trace_id, "names": sorted(names)}
|
||||||
|
time.sleep(3)
|
||||||
|
tail = "; ".join(
|
||||||
|
"%s -> %s" % (x["trace_id"][:8], x["names"][:6]) for x in last_seen[:5]
|
||||||
|
)
|
||||||
|
raise Failure(
|
||||||
|
"не дождались trace со span-names, содержащими %s за %ss; последние trace: %s"
|
||||||
|
% (need_substrings, timeout, tail or "нет")
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_trace_api_to_worker(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
started = int(time.time())
|
||||||
|
|
||||||
|
status, att, _ = _raw_upload(c, alice, chat["id"], "sample.png", data, "image/png")
|
||||||
|
check(status == 202, "upload must be 202, got %s" % status)
|
||||||
|
check(att["status"] == "queued", "upload status must be queued")
|
||||||
|
|
||||||
|
ready = _wait_ready(c, alice, att, timeout=READY_TIMEOUT)
|
||||||
|
check(ready["status"] == "ready", "attachment must become ready")
|
||||||
|
|
||||||
|
since = max(60, int(time.time()) - started + 180)
|
||||||
|
trace = _wait_trace_with_spans(
|
||||||
|
since_seconds=since,
|
||||||
|
need_substrings=[
|
||||||
|
"/api/v1/chats/{chat_id}/attachments",
|
||||||
|
"job.publish",
|
||||||
|
"job.consume",
|
||||||
|
],
|
||||||
|
timeout=180,
|
||||||
|
)
|
||||||
|
print(" trace_id:", trace["trace_id"])
|
||||||
|
print(" spans:", ", ".join(trace["names"]))
|
||||||
|
|
||||||
|
|
||||||
|
def test_metrics_in_prometheus(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
c.message(alice, chat, "metrics-" + uuid.uuid4().hex)
|
||||||
|
c.message(alice, chat, "metrics-" + uuid.uuid4().hex)
|
||||||
|
data = SAMPLE.read_bytes()
|
||||||
|
status, att, _ = _raw_upload(c, alice, chat["id"], "sample.png", data, "image/png")
|
||||||
|
check(status == 202, "upload must be 202")
|
||||||
|
_wait_ready(c, alice, att, timeout=READY_TIMEOUT)
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 120
|
||||||
|
required = {
|
||||||
|
"http_requests_total",
|
||||||
|
"http_request_duration_seconds_bucket",
|
||||||
|
"jobs_processed_total",
|
||||||
|
"job_processing_duration_seconds_bucket",
|
||||||
|
}
|
||||||
|
got: set[str] = set()
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
got = set()
|
||||||
|
for name in required:
|
||||||
|
r = _prom_query("count(%s)" % name)
|
||||||
|
series = r.get("data", {}).get("result", [])
|
||||||
|
if series:
|
||||||
|
got.add(name)
|
||||||
|
if got == required:
|
||||||
|
break
|
||||||
|
time.sleep(3)
|
||||||
|
missing = required - got
|
||||||
|
check(not missing, "Prometheus missing metrics: %s" % sorted(missing))
|
||||||
|
print(" metrics in Prometheus:", sorted(got))
|
||||||
|
|
||||||
|
r = _prom_query("count by (http_route, http_status_class) (http_requests_total)")
|
||||||
|
series = r.get("data", {}).get("result", [])
|
||||||
|
check(series, "http_requests_total has no series")
|
||||||
|
import re as _re
|
||||||
|
for s in series:
|
||||||
|
metric = s.get("metric", {})
|
||||||
|
route = metric.get("http_route", "")
|
||||||
|
check(route.startswith("/api/") or route.startswith("/health"),
|
||||||
|
"unexpected http_route: %r" % route)
|
||||||
|
check(_re.search(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",
|
||||||
|
route) is None,
|
||||||
|
"http_route contains raw UUID: %r" % route)
|
||||||
|
|
||||||
|
r = _prom_query("sum(jobs_processed_total{outcome=\"success\"})")
|
||||||
|
series = r.get("data", {}).get("result", [])
|
||||||
|
check(series, "jobs_processed_total{outcome=success} absent")
|
||||||
|
value = float(series[0]["value"][1])
|
||||||
|
check(value >= 1, "jobs success metric is %r" % value)
|
||||||
|
print(" jobs_processed_total{outcome=success} =", value)
|
||||||
|
|
||||||
|
|
||||||
|
def test_logs_in_loki(c):
|
||||||
|
time.sleep(15)
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
streams = []
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
r = _loki_query('{service_name="messenger-api"} |= "event=http"',
|
||||||
|
since_seconds=300)
|
||||||
|
streams = r.get("data", {}).get("result", [])
|
||||||
|
if streams:
|
||||||
|
break
|
||||||
|
time.sleep(3)
|
||||||
|
check(streams, "Loki: no messenger-api logs with event=http")
|
||||||
|
lines = [v[1] for s in streams for v in s.get("values", [])]
|
||||||
|
check(any("request_id=" in line for line in lines),
|
||||||
|
"API logs missing request_id")
|
||||||
|
|
||||||
|
r = _loki_query('{service_name="messenger-worker"} |= "event="', since_seconds=300)
|
||||||
|
check(r.get("data", {}).get("result", []),
|
||||||
|
"Loki: no messenger-worker logs")
|
||||||
|
|
||||||
|
# Ищем запись event=http с ненулевым trace_id (корреляция лог↔trace).
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
ok = False
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
r = _loki_query(
|
||||||
|
'{service_name=~"messenger-api|messenger-worker"} '
|
||||||
|
'|~ "event=(http|job_ready)" |~ "trace_id=" ',
|
||||||
|
since_seconds=300,
|
||||||
|
)
|
||||||
|
streams = r.get("data", {}).get("result", [])
|
||||||
|
for s in streams:
|
||||||
|
for v in s.get("values", []):
|
||||||
|
line = v[1]
|
||||||
|
idx = line.find("trace_id=")
|
||||||
|
if idx < 0:
|
||||||
|
continue
|
||||||
|
tail = line[idx + len("trace_id="):]
|
||||||
|
tid = tail.split()[0].strip()
|
||||||
|
if len(tid) == 32 and set(tid) != {"0"}:
|
||||||
|
ok = True
|
||||||
|
break
|
||||||
|
if ok:
|
||||||
|
break
|
||||||
|
if ok:
|
||||||
|
break
|
||||||
|
time.sleep(3)
|
||||||
|
check(ok, "Loki: no logs with non-zero trace_id (log↔trace correlation)")
|
||||||
|
print(" Loki OK: api+worker logs with non-zero trace_id found")
|
||||||
|
|
||||||
|
|
||||||
|
def _grafana_ds_uids(auth) -> dict[str, dict]:
|
||||||
|
code, body = _http_get(GRAFANA_URL + "/api/datasources", basic_auth=auth)
|
||||||
|
check(code == 200, "grafana datasources API %s" % code)
|
||||||
|
return {d.get("uid"): d for d in json.loads(body)}
|
||||||
|
|
||||||
|
|
||||||
|
def test_grafana_provisioning(c):
|
||||||
|
deadline = time.monotonic() + 60
|
||||||
|
auth = (GRAFANA_ADMIN_USER, GRAFANA_ADMIN_PASSWORD)
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
code, _ = _http_get(GRAFANA_URL + "/api/health")
|
||||||
|
if code == 200:
|
||||||
|
break
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
raise Failure("Grafana API не поднялась за 60 с")
|
||||||
|
|
||||||
|
by_uid = _grafana_ds_uids(auth)
|
||||||
|
# Требуемые UID явно заданы в provisioning и совпадают со ссылками в
|
||||||
|
# dashboard/rules/derived fields.
|
||||||
|
for uid, type_ in (("prometheus", "prometheus"),
|
||||||
|
("loki", "loki"),
|
||||||
|
("tempo", "tempo")):
|
||||||
|
check(uid in by_uid, "Grafana missing datasource uid=%r (have %s)"
|
||||||
|
% (uid, sorted(by_uid)))
|
||||||
|
check(by_uid[uid].get("type") == type_,
|
||||||
|
"datasource uid=%r has wrong type: %r"
|
||||||
|
% (uid, by_uid[uid].get("type")))
|
||||||
|
print(" datasources by uid:", sorted(by_uid))
|
||||||
|
|
||||||
|
code, body = _http_get(GRAFANA_URL + "/api/dashboards/uid/messenger-lab6",
|
||||||
|
basic_auth=auth)
|
||||||
|
check(code == 200, "Grafana dashboard messenger-lab6 not found (%s)" % code)
|
||||||
|
dash = json.loads(body)
|
||||||
|
dashboard = dash.get("dashboard", {})
|
||||||
|
panels = dashboard.get("panels", [])
|
||||||
|
titles = {p.get("title") for p in panels}
|
||||||
|
check(any("p95" in (t or "") for t in titles),
|
||||||
|
"dashboard missing p95 panel")
|
||||||
|
check(any("Jobs" in (t or "") or "job" in (t or "").lower() for t in titles),
|
||||||
|
"dashboard missing jobs panel")
|
||||||
|
|
||||||
|
# Проверяем, что панель логов ссылается на существующий uid Loki,
|
||||||
|
# а не на «магическое» имя.
|
||||||
|
for p in panels:
|
||||||
|
ds = p.get("datasource") or {}
|
||||||
|
uid = ds.get("uid")
|
||||||
|
if uid is not None:
|
||||||
|
check(uid in by_uid,
|
||||||
|
"panel %r references unknown datasource uid %r"
|
||||||
|
% (p.get("title"), uid))
|
||||||
|
print(" dashboard panels:", sorted(t for t in titles if t))
|
||||||
|
|
||||||
|
code, body = _http_get(GRAFANA_URL + "/api/v1/provisioning/alert-rules",
|
||||||
|
basic_auth=auth)
|
||||||
|
check(code == 200, "grafana alert-rules API %s" % code)
|
||||||
|
rules = json.loads(body)
|
||||||
|
check(len(rules) >= 2, "expected >=2 alert rules, got %d" % len(rules))
|
||||||
|
|
||||||
|
for r in rules:
|
||||||
|
# datasourceUid в data должен существовать.
|
||||||
|
for item in r.get("data", []):
|
||||||
|
uid = item.get("datasourceUid")
|
||||||
|
if uid and uid != "__expr__":
|
||||||
|
check(uid in by_uid,
|
||||||
|
"rule %r references unknown datasource uid %r"
|
||||||
|
% (r.get("title"), uid))
|
||||||
|
|
||||||
|
# Все правила должны быть health=ok. Если datasources не согласованы,
|
||||||
|
# Grafana вернёт health=error "data source not found", как было
|
||||||
|
# в замечании проверяющего.
|
||||||
|
deadline = time.monotonic() + 180
|
||||||
|
while True:
|
||||||
|
code, body = _http_get(GRAFANA_URL + "/api/v1/provisioning/alert-rules",
|
||||||
|
basic_auth=auth)
|
||||||
|
check(code == 200, "grafana alert-rules API %s" % code)
|
||||||
|
rules = json.loads(body)
|
||||||
|
bad = [r.get("title") for r in rules
|
||||||
|
if r.get("health") not in (None, "ok")]
|
||||||
|
if not bad:
|
||||||
|
break
|
||||||
|
if time.monotonic() > deadline:
|
||||||
|
raise Failure("Grafana alert rules with non-ok health: %s" % bad)
|
||||||
|
time.sleep(3)
|
||||||
|
print(" alert rules:", [r.get("title") for r in rules])
|
||||||
|
|
||||||
|
|
||||||
|
def _prom_alerts() -> list[dict]:
|
||||||
|
r = _compose_exec("prometheus", "sh", "-c",
|
||||||
|
"wget -qO- 'http://localhost:9090/api/v1/alerts'")
|
||||||
|
if r.returncode != 0 or not r.stdout.strip():
|
||||||
|
return []
|
||||||
|
try:
|
||||||
|
data = json.loads(r.stdout)
|
||||||
|
except Exception:
|
||||||
|
return []
|
||||||
|
return data.get("data", {}).get("alerts", []) or []
|
||||||
|
|
||||||
|
|
||||||
|
def _wait_alert(name: str, state: str, timeout: float = 240.0):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
alerts = _prom_alerts()
|
||||||
|
# Prometheus /api/v1/alerts возвращает только pending/firing.
|
||||||
|
# Состояние "inactive" == алерта с таким alertname нет в списке.
|
||||||
|
active = [
|
||||||
|
a for a in alerts
|
||||||
|
if a.get("labels", {}).get("alertname") == name
|
||||||
|
]
|
||||||
|
if state == "inactive":
|
||||||
|
if not active:
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
for a in active:
|
||||||
|
if a.get("state") == state:
|
||||||
|
return
|
||||||
|
time.sleep(3)
|
||||||
|
raise Failure("alert %s never reached %s" % (name, state))
|
||||||
|
|
||||||
|
|
||||||
|
def test_alert_firing_and_resolved(c):
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
|
||||||
|
stopped = _compose("stop", "postgres")
|
||||||
|
check(stopped.returncode == 0, "stop postgres failed")
|
||||||
|
|
||||||
|
try:
|
||||||
|
deadline = time.monotonic() + 60
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
c.call("GET", "/api/v1/users/me", (401, 503), actor=alice)
|
||||||
|
except Failure:
|
||||||
|
pass
|
||||||
|
time.sleep(0.3)
|
||||||
|
_wait_alert("MessengerHighErrorRate", "firing", timeout=240)
|
||||||
|
print(" MessengerHighErrorRate firing")
|
||||||
|
finally:
|
||||||
|
started = _compose("start", "postgres")
|
||||||
|
check(started.returncode == 0, "start postgres failed")
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 90
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
c.call("GET", "/health/ready", 200)
|
||||||
|
break
|
||||||
|
except Failure:
|
||||||
|
time.sleep(1)
|
||||||
|
else:
|
||||||
|
raise Failure("API didn't become ready after postgres restart")
|
||||||
|
|
||||||
|
deadline = time.monotonic() + 60
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
c.call("GET", "/api/v1/users/me", 200, actor=alice, schema="User")
|
||||||
|
except Failure:
|
||||||
|
pass
|
||||||
|
time.sleep(0.3)
|
||||||
|
_wait_alert("MessengerHighErrorRate", "inactive", timeout=300)
|
||||||
|
print(" MessengerHighErrorRate resolved")
|
||||||
|
|
||||||
|
|
||||||
|
def test_telemetry_backend_down(c):
|
||||||
|
for svc in ("tempo", "loki", "prometheus"):
|
||||||
|
_compose("start", svc)
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
stopped = {}
|
||||||
|
for svc in ("prometheus", "loki", "tempo"):
|
||||||
|
r = _compose("stop", svc)
|
||||||
|
check(r.returncode == 0, "stop %s failed: %s" % (svc, r.stderr[:300]))
|
||||||
|
stopped[svc] = True
|
||||||
|
|
||||||
|
try:
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
deadline = time.monotonic() + 30
|
||||||
|
ok = 0
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
try:
|
||||||
|
c.call("GET", "/api/v1/users/me", 200, actor=alice, schema="User")
|
||||||
|
c.message(alice, chat, "telem-down-" + uuid.uuid4().hex[:8])
|
||||||
|
ok += 1
|
||||||
|
except Failure:
|
||||||
|
pass
|
||||||
|
time.sleep(0.2)
|
||||||
|
check(ok >= 5, "API unavailable while telemetry backend is down (ok=%d)" % ok)
|
||||||
|
|
||||||
|
# В образе otel/opentelemetry-collector-contrib нет coreutils `true`,
|
||||||
|
# поэтому проверяем живость штатным бинарником самого коллектора
|
||||||
|
# (тот же приём, что в healthcheck compose.yaml).
|
||||||
|
ps = _compose_exec("otel-collector", "/otelcol-contrib", "--version")
|
||||||
|
check(ps.returncode == 0,
|
||||||
|
"otel-collector died while backends were unavailable")
|
||||||
|
|
||||||
|
stats = subprocess.run(
|
||||||
|
["docker", "stats", "--no-stream", "--format", "{{.MemUsage}}",
|
||||||
|
"mtuci-otel-collector"],
|
||||||
|
capture_output=True, text=True, timeout=15,
|
||||||
|
)
|
||||||
|
if stats.returncode == 0:
|
||||||
|
used = stats.stdout.strip().split("/")[0].strip()
|
||||||
|
mb = None
|
||||||
|
if used.endswith("MiB"):
|
||||||
|
mb = float(used[:-3])
|
||||||
|
elif used.endswith("GiB"):
|
||||||
|
mb = float(used[:-3]) * 1024
|
||||||
|
if mb is not None:
|
||||||
|
check(mb < 260, "otel-collector RSS=%s MiB exceeds limit" % mb)
|
||||||
|
print(" otel-collector RSS while backends down:", mb, "MiB")
|
||||||
|
finally:
|
||||||
|
for svc in stopped:
|
||||||
|
_compose("start", svc)
|
||||||
|
time.sleep(3)
|
||||||
|
|
||||||
|
print(" API and Collector remained healthy while backends were down")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = arguments("Lab6 level 4 checks")
|
||||||
|
c = Client(args.base_url, args.ca_file)
|
||||||
|
c.call("GET", "/health/ready", schema="Health")
|
||||||
|
|
||||||
|
print("=== trace API -> broker -> worker (Tempo) ===")
|
||||||
|
test_trace_api_to_worker(c)
|
||||||
|
print("PASS: single trace with upload + job.publish + job.consume")
|
||||||
|
|
||||||
|
print("=== metrics in Prometheus ===")
|
||||||
|
test_metrics_in_prometheus(c)
|
||||||
|
print("PASS: http_requests_total + duration + jobs_processed_total present, "
|
||||||
|
"low-cardinality route labels")
|
||||||
|
|
||||||
|
print("=== logs in Loki ===")
|
||||||
|
test_logs_in_loki(c)
|
||||||
|
print("PASS: structured logs of api+worker with trace_id")
|
||||||
|
|
||||||
|
print("=== Grafana provisioning ===")
|
||||||
|
test_grafana_provisioning(c)
|
||||||
|
print("PASS: dashboard messenger-lab6 + >=2 alert rules provisioned")
|
||||||
|
|
||||||
|
print("=== alert firing and resolved ===")
|
||||||
|
test_alert_firing_and_resolved(c)
|
||||||
|
print("PASS: alert fires on artificial outage and resolves on recovery")
|
||||||
|
|
||||||
|
print("=== telemetry backend down ===")
|
||||||
|
test_telemetry_backend_down(c)
|
||||||
|
print("PASS: API works, Collector stays within memory limit")
|
||||||
|
|
||||||
|
print("PASS: all lab6 level-4 checks passed")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run(main)
|
||||||
Reference in New Issue
Block a user