created tasks for grade 4
This commit is contained in:
+1
-1
@@ -32,7 +32,7 @@ coverage/
|
|||||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||||
|
|
||||||
# Перенесённые исключения lab5
|
# Перенесённые исключения lab5
|
||||||
venv/
|
.venv/
|
||||||
.pytest_cache/
|
.pytest_cache/
|
||||||
.ruff_cache/
|
.ruff_cache/
|
||||||
/docs/
|
/docs/
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ SERVICE ?=
|
|||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
COMPOSE = docker compose --env-file .env
|
COMPOSE = docker compose --env-file .env
|
||||||
|
LOCAL_COMPOSE = $(COMPOSE) -f compose.yaml -f compose.local.yml
|
||||||
|
|
||||||
TEST_PROJECT ?= messenger-test
|
TEST_PROJECT ?= messenger-test
|
||||||
TEST_LB_PORT ?= 28080
|
TEST_LB_PORT ?= 28080
|
||||||
@@ -27,13 +28,14 @@ TEST_REDIS_PASSWORD ?= $(if $(wildcard secrets/redis_password),$(file <secrets/r
|
|||||||
TEST_REDIS_DB ?= 15
|
TEST_REDIS_DB ?= 15
|
||||||
export TEST_DATABASE_URL TEST_REDIS_HOST TEST_REDIS_PORT TEST_REDIS_PASSWORD TEST_REDIS_DB
|
export TEST_DATABASE_URL TEST_REDIS_HOST TEST_REDIS_PORT TEST_REDIS_PASSWORD TEST_REDIS_DB
|
||||||
|
|
||||||
.PHONY: help init up down restart ps logs migrate migration worker-stop worker-start \
|
.PHONY: help init up up-local down restart ps logs migrate migration worker-stop worker-start \
|
||||||
cleanup-dry-run cleanup-apply check validate test load test-unit test-pipeline \
|
cleanup-dry-run cleanup-apply check validate test load test-unit test-pipeline \
|
||||||
test-nginx test-storage test-outbox test-jobs test-persistence test-failover \
|
test-nginx test-storage test-outbox test-jobs test-persistence test-failover \
|
||||||
test-suite test-stand-up test-stand-destroy test-telemetry test-observability verify clean-stands
|
test-suite test-stand-up test-stand-destroy test-telemetry test-observability verify clean-stands
|
||||||
|
|
||||||
help:
|
help:
|
||||||
@echo "Запуск: init | up | down | restart | ps | logs SERVICE=worker"
|
@echo "Запуск: init | up | down | restart | ps | logs SERVICE=worker"
|
||||||
|
@echo "Локальные порты и веб-панели: up-local"
|
||||||
@echo "Обслуживание: migrate | migration m='описание' | worker-stop | worker-start"
|
@echo "Обслуживание: migrate | migration m='описание' | worker-stop | worker-start"
|
||||||
@echo "Очистка объектов: cleanup-dry-run | cleanup-apply"
|
@echo "Очистка объектов: cleanup-dry-run | cleanup-apply"
|
||||||
@echo "Проверки: check | validate | test | test-pipeline | test-unit PYTEST_ARGS=..."
|
@echo "Проверки: check | validate | test | test-pipeline | test-unit PYTEST_ARGS=..."
|
||||||
@@ -49,6 +51,9 @@ init:
|
|||||||
up:
|
up:
|
||||||
$(COMPOSE) up -d --build --wait --wait-timeout 180
|
$(COMPOSE) up -d --build --wait --wait-timeout 180
|
||||||
|
|
||||||
|
up-local:
|
||||||
|
$(LOCAL_COMPOSE) up -d --build --wait --wait-timeout 180
|
||||||
|
|
||||||
down:
|
down:
|
||||||
$(COMPOSE) down
|
$(COMPOSE) down
|
||||||
|
|
||||||
@@ -94,11 +99,11 @@ load:
|
|||||||
test-telemetry:
|
test-telemetry:
|
||||||
$(PYTHON) -m pytest -q student-tests/test_telemetry.py
|
$(PYTHON) -m pytest -q student-tests/test_telemetry.py
|
||||||
|
|
||||||
# Проверка на уже запущенном стенде; явно включает два ограниченных отказа.
|
# Проверка на уже запущенном стенде; включает сценарии отказа и восстановления.
|
||||||
test-observability:
|
test-observability:
|
||||||
$(PYTHON) -m scripts.check_observability --base-url "$(BASE_URL)" --grafana-url "$(GRAFANA_URL)" --incidents --restart-telemetry
|
$(PYTHON) -m scripts.check_observability --base-url "$(BASE_URL)" --grafana-url "$(GRAFANA_URL)" --incidents --restart-telemetry
|
||||||
|
|
||||||
# Один стенд, один прогон, удаление контейнеров/томов/образов даже при ошибке.
|
# Один прогон на отдельном стенде, удаление его контейнеров/сети/томов при завершении.
|
||||||
verify:
|
verify:
|
||||||
$(PYTHON) -m scripts.deployment verify
|
$(PYTHON) -m scripts.deployment verify
|
||||||
|
|
||||||
|
|||||||
@@ -1,15 +1,14 @@
|
|||||||
# Отчёт
|
# Отчёт
|
||||||
|
|
||||||
- Автор: Григорян Илья Мурадович, БПИ2303.
|
- Автор: Григорян Илья Мурадович, БПИ2303.
|
||||||
- Цель: **оценка 4**. Расширения, которые ещё предстоит выполнить, отмечены TODO.
|
- Цель: оценка **4**, лабораторная «Наблюдаемость».
|
||||||
- Commit/PR: TODO после публикации.
|
- Источники: OpenTelemetry SDK 1.45.1, FastAPI, SQLAlchemy 2.1.4,
|
||||||
- Источники и помощь: OpenTelemetry SDK 1.45.1, FastAPI, SQLAlchemy, Grafana;
|
[внутренние метрики Collector](https://opentelemetry.io/docs/collector/internal-telemetry/),
|
||||||
официальная документация компонентов, помощь Codex.
|
[контракт наблюдаемости](contracts/observability.md). Помощь Codex.
|
||||||
|
|
||||||
## Запуск
|
## Запуск
|
||||||
|
|
||||||
Python 3.12 и Docker Compose v2. Зависимости закреплены в `requirements.txt`,
|
Python 3.12 и Docker Compose. Зависимости и образы закреплены в репозитории.
|
||||||
версии образов — в Dockerfile/Compose. Подробности: [RUNNING.md](RUNNING.md).
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
python3 -m venv .venv
|
python3 -m venv .venv
|
||||||
@@ -20,71 +19,149 @@ make test
|
|||||||
make down
|
make down
|
||||||
```
|
```
|
||||||
|
|
||||||
API: http://localhost:18081. Grafana: http://localhost:13000/d/messenger-overview.
|
API доступен на http://localhost:18081, дашборд — на
|
||||||
`make init` создаёт отсутствующие `.env`/`secrets/`, миграции и MinIO bootstrap
|
http://localhost:13000/d/messenger-overview. Для подключения к хранилищам с
|
||||||
выполняются при запуске. `make down` сохраняет данные; `make clean-stands` намеренно
|
компьютера используйте [локальный режим](LOCAL_CONNECTIONS.md).
|
||||||
удаляет контейнеры, сети, тома и образы приложения, сохраняя настройки и базовые образы.
|
Инициализация создаёт только отсутствующие настройки и секреты. Миграции и
|
||||||
|
настройка приватного bucket выполняются при запуске. `make down` сохраняет тома.
|
||||||
|
|
||||||
## Реализация
|
## Архитектура и трассировка
|
||||||
|
|
||||||
Две API-реплики за nginx, PostgreSQL, Redis-сессии, приватный MinIO, RabbitMQ,
|
Две реплики API за nginx, PostgreSQL для сообщений и состояния заданий, Redis
|
||||||
outbox publisher, отдельный worker и cleanup. Сохранены thumbnail/crop/WebP,
|
для сессий, MinIO для файлов, RabbitMQ для доставки, отдельные publisher,
|
||||||
ограниченные повторы, идемпотентность, failed registry и ручной replay.
|
worker и cleanup. HTTP 202 возвращается после устойчивого приёма вложения.
|
||||||
PostgreSQL — источник истины для metadata/заданий, S3 — для файлов.
|
Publisher отмечает доставку после подтверждения RabbitMQ, worker подтверждает
|
||||||
HTTP 202 возвращается после устойчивого приёма, ack — после фиксации результата.
|
попытку после устойчивой фиксации исхода.
|
||||||
|
|
||||||
API/worker → OTLP HTTP/protobuf → Collector → Prometheus / Loki / Tempo → Grafana.
|
| Роль | Сервис и версия | Готовность, данные |
|
||||||
Prometheus хранит метрики, Loki — структурные логи, Tempo — реальные spans;
|
| --- | --- | --- |
|
||||||
Grafana читает эти хранилища. История находится в named volumes, retention — 3 дня.
|
| Балансировщик | nginx 1.28.0 | `/lb-health`, публикует API на `LB_HOST_PORT` |
|
||||||
Collector: 0.165.0, Prometheus: 3.16.0, Loki: 3.7.10, Tempo: 2.9.0, Grafana: 13.3.1.
|
| HTTP API | api, Python 3.12 | `/health/ready`, две реплики, `api:8080` |
|
||||||
|
| База | postgres 16.10 | `pg_isready`, `pgdata`, `postgres:5432` |
|
||||||
|
| Сессии | redis 7.4.2 | аутентифицированный `PING`, `redisdata`, `redis:6379` |
|
||||||
|
| Файлы | minio RELEASE.2025-10-15T17-29-55Z | `/minio/health/ready`, `miniodata`, `minio:9000` в сети `objects` |
|
||||||
|
| Очередь | broker, RabbitMQ 4.4.0 | `rabbitmq-diagnostics ping`, `rabbitmqdata`, `broker:5672` |
|
||||||
|
|
||||||
Dashboard и datasources импортируются из `infra/otel/grafana/`. HTTP:
|
Учётные данные PostgreSQL, Redis, MinIO и RabbitMQ передаются через файловые
|
||||||
`messenger_http_requests_total`, `messenger_http_duration_seconds_*`; worker:
|
секреты Compose. Схему создаёт migrate, bucket и права — minio-bootstrap,
|
||||||
`messenger_job_attempts_total`, `messenger_job_duration_seconds_*`.
|
устойчивую очередь объявляют publisher и worker.
|
||||||
`outcome` относится к фактической попытке, а не уникальной job. Histogram — в секундах;
|
|
||||||
p50/p95/p99 считаются по buckets всех реплик. Error ratio: 5xx / бизнес-запросы без health.
|
|
||||||
Точные PromQL, единицы и остальные сигналы заданы в dashboard JSON.
|
|
||||||
|
|
||||||
Resource fields: service.name/version/instance.id и deployment.environment.name из
|
API, publisher и worker отправляют OTLP HTTP/protobuf в Collector 0.165.0.
|
||||||
APP_ENV. Метрики используют шаблоны маршрутов, method/status class, job type/outcome;
|
Prometheus 3.16.0 собирает метрики, Loki 3.7.10 хранит структурные логи,
|
||||||
пользовательские ID не становятся labels. Логи содержат timestamp, severity, event,
|
Tempo 2.9.0 хранит трассы. Grafana 13.3.1 читает три источника и загружает
|
||||||
trace/span ID; X-Request-Id связывает HTTP-ответ с логом. Тела, credentials, filename,
|
дашборд из репозитория. История хранится в именованных томах, срок хранения 72 ч.
|
||||||
SQL и тексты исключений не отправляются в OTLP. Readiness API не зависит от telemetry.
|
`deployment.environment.name` берётся из `APP_ENV`. В проверенном стенде
|
||||||
|
использовано значение `development`.
|
||||||
|
|
||||||
## Проверки и наблюдения
|
При приёме вложения в транзакции сохраняются только W3C `traceparent` и
|
||||||
|
`tracestate` из текущего контекста. Publisher создаёт producer span как
|
||||||
|
потомка HTTP upload и переносит его контекст в заголовки AMQP. Каждая попытка,
|
||||||
|
в том числе после retry или replay, получает собственный дочерний consumer
|
||||||
|
span со своим номером и исходом. Успешная попытка показывает чтение staging,
|
||||||
|
запись объектов S3 и фиксацию ready в PostgreSQL. У старых строк контекст
|
||||||
|
может отсутствовать, обработка сохраняется.
|
||||||
|
|
||||||
`make verify` один раз поднимает отдельный стенд, выполняет регрессию, публичный smoke,
|
В логах есть timestamp, severity, event и trace/span ID. HTTP-ответ и лог
|
||||||
проверяет dashboard, корреляцию логов/traces, privacy, сохранность истории и отказы,
|
связаны через X-Request-Id, лог и трасса — через TraceID. У метрик только
|
||||||
затем обязательно удаляет стенды и образы приложения. Нагрузка: 10 сообщений/с,
|
ограниченные значения route template, method, status class, queue, job type
|
||||||
10 секунд, до 2 одновременных запросов. Результаты — в `evidence/verification.json`
|
и outcome. Идентификаторы файлов используются в логах получения задания
|
||||||
и `evidence/observability.json`, без привязки к учебным критериям.
|
для поиска нужной попытки. Тексты сообщений, пароли, токены, URL с
|
||||||
|
подписью, SQL и содержимое файлов в телеметрию не передаются.
|
||||||
|
|
||||||
Проверенные инциденты: остановка PostgreSQL → 503 и ERROR span со связанным логом;
|
## Метрики и цели
|
||||||
постоянная ошибка обработки → failed, счётчик ошибки, затем replay → ready.
|
|
||||||
Диагностика: метрики → Loki event/request ID → trace ID → Tempo status/duration.
|
|
||||||
Точные результаты последнего прогона и CPU/RAM находятся в evidence.
|
|
||||||
Последний прогон: 206 passed in 112.44s (0:01:52); API/наблюдаемость/persistence/failover — PASS.
|
|
||||||
Нагрузка: 100 успешных запросов, 0 ошибок; p50/p95/p99 —
|
|
||||||
31.394 / 63.623 / 70.12 мс. Стенды, тома и образы приложения удалены.
|
|
||||||
|
|
||||||
|
| Что смотрим | Запрос или метрика | Единица |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Частота HTTP | `sum by (http_request_method,http_route)(rate(messenger_http_requests_total{http_route!~"/health/.*"}[1m]))` | запросы/с |
|
||||||
|
| Доля ошибок | Сумма rate для класса 5xx / сумма rate всех бизнес-запросов, без health | доля |
|
||||||
|
| HTTP p50/p95/p99 | `histogram_quantile(q, sum by(le)(rate(messenger_http_duration_seconds_bucket{http_route!~"/health/.*"}[1m])))` | с |
|
||||||
|
| Worker | `messenger_job_attempts_total` по outcome и `messenger_job_duration_seconds_bucket` | попытки, с |
|
||||||
|
| Очередь | `max by(queue_name)(messenger_queue_depth_ratio)`, `max by(queue_name)(messenger_queue_oldest_seconds)` | задания, с |
|
||||||
|
| Пул PostgreSQL | `sum by(service_name)(messenger_db_pool_used_ratio)` и аналогично `messenger_db_pool_waiting_ratio` | соединения, ожидающие |
|
||||||
|
| Загрузка worker | `sum(messenger_worker_busy_ratio) / sum(messenger_worker_capacity_ratio)` | доля |
|
||||||
|
| CPU и память | `rate(messenger_process_cpu_seconds_total[1m])`, `messenger_process_rss_bytes` | ядра, байты |
|
||||||
|
| До готовности вложения | `histogram_quantile(0.95, sum by(le)(rate(messenger_job_time_to_ready_seconds_bucket[5m])))` | с |
|
||||||
|
| Экспорт Collector | `otelcol_exporter_queue_size`, `otelcol_exporter_queue_capacity` | пакеты |
|
||||||
|
|
||||||
## TODO для завершения
|
Очередь измеряется по устойчивому состоянию `queued` в PostgreSQL, включая
|
||||||
|
ещё не опубликованные и отложенные попытки. Возраст считается от первичного
|
||||||
|
принятия. Время до ready измеряется для успешных заданий от записи принятия
|
||||||
|
до фиксации ready, включая ожидание и повторы. Гистограммы объединяются по
|
||||||
|
границам buckets перед вычислением процентиля. CPU и RSS относятся к процессу
|
||||||
|
Python и не включают подпроцесс resize.
|
||||||
|
Суффикс `_ratio` добавляет экспортёр Prometheus для безразмерного unit `1`.
|
||||||
|
Для глубины очереди и пула эти ряды содержат абсолютные количества.
|
||||||
|
|
||||||
- TODO: перенос W3C context API → outbox/broker → worker; producer/consumer spans,
|
SLI доступности — доля бизнес-запросов без 5xx. SLO — ≥99% за скользящие
|
||||||
DB/S3 spans и цепочка upload → результат с retry.
|
24 часа. Для проверки используйте отношение сумм `increase(...[24h])`,
|
||||||
- TODO: queue depth/возраст старейшей job, DB pool, worker saturation и время до ready;
|
исключив health из числителя и знаменателя. Окно без трафика не оценивается.
|
||||||
добавить запросы и единицы в dashboard.
|
Короткие оповещения для стенда заданы в [alerts.yaml](infra/otel/alerts.yaml).
|
||||||
- TODO: определить SLI/SLO и окно; alert rules для error rate и queue lag,
|
`MessengerHighErrorRate` срабатывает при >5% 5xx за 30 с с выдержкой 5 с.
|
||||||
проверить firing/resolved и написать краткий runbook.
|
`MessengerQueueLag` срабатывает, если очередь непуста и возраст старейшего
|
||||||
- TODO: проверить недоступность telemetry backend под нагрузкой: бизнес-путь,
|
задания >15 с с выдержкой 5 с. Состояние доступно в Prometheus через
|
||||||
ограниченность RAM/очередей и потери telemetry; оформить два разбора инцидентов
|
`ALERTS{alertstate="firing"}`. Внешняя доставка отключена.
|
||||||
с остановкой worker и деградацией БД.
|
|
||||||
|
## Диагностика инцидентов
|
||||||
|
|
||||||
|
1. **Рост 5xx.** В Grafana сопоставить частоту запросов, долю 5xx и задержку.
|
||||||
|
По X-Request-Id найти связанный лог и открыть TraceID. Ошибка на
|
||||||
|
`postgres.checkout` вместе с событием `dependency.unavailable`
|
||||||
|
указывает на проблему получения соединения с БД. После восстановления
|
||||||
|
проверить `/health/ready` и исчезновение firing.
|
||||||
|
2. **Растёт очередь.** Сверить глубину, возраст и занятость worker. При
|
||||||
|
остановленном worker задания принимаются, а новые попытки не появляются.
|
||||||
|
После восстановления проверить уменьшение очереди и исчезновение firing.
|
||||||
|
В Tempo открыть трассу upload и сравнить исходы отдельных попыток, затем
|
||||||
|
проверить spans S3/БД и состояние ready.
|
||||||
|
3. **Недоступен Loki.** Prometheus продолжает собирать бизнес-метрики и
|
||||||
|
внутренние метрики Collector. Сравнить число успешных сообщений, RSS,
|
||||||
|
размер экспортной очереди и прирост счётчиков отказа экспорта/постановки
|
||||||
|
в очередь. После старта Loki проверить появление новых связанных логов.
|
||||||
|
|
||||||
|
Collector использует memory limiter 192 MiB со spike 32 MiB, пакетирование до
|
||||||
|
256 записей, очередь 256 пакетов на экспортёр, по два потребителя
|
||||||
|
на очередь и до 30 с повторов доставки. Контейнер ограничен 256 MiB. SDK
|
||||||
|
имеет ограниченные очереди span/log и таймауты. Потери считаются по
|
||||||
|
счётчикам Collector для остановленного Loki. Общие потери вне Collector
|
||||||
|
этими счётчиками не измеряются.
|
||||||
|
|
||||||
|
## Полный прогон
|
||||||
|
|
||||||
|
`make verify` поднимает один отдельный стенд с телеметрией, выполняет регрессию,
|
||||||
|
smoke, нагрузку, проверку сквозных трасс, оповещений и восстановления после
|
||||||
|
отказов, а также persistence/failover. В конце удаляются контейнеры, сеть и
|
||||||
|
тома только проверочного проекта. Настройки, общий кэш образов и данные
|
||||||
|
основного стенда сохраняются.
|
||||||
|
|
||||||
|
Результаты прогона от 19.11.2026 сохранены в [журнале проверок](evidence/verification.json)
|
||||||
|
и [доказательствах наблюдаемости](evidence/observability.json).
|
||||||
|
Итог **PASS**, с 18:50 до 19:03 МСК. Контракт, OpenAPI, конфигурация и запуск
|
||||||
|
Compose, публичный smoke, наблюдаемость, persistence и failover прошли.
|
||||||
|
Регрессия: 206 тестов за 98,89 с. Инвентаризация после очистки показала
|
||||||
|
0 контейнеров, 0 сетей и 0 томов проверочного проекта.
|
||||||
|
|
||||||
|
Нагрузка: 100 успешных сообщений, 0 ошибок, 10,078 запроса/с. Клиентские
|
||||||
|
p50/p95/p99 — 18,036 / 39,623 / 45,954 мс. Проверены все запросы панелей,
|
||||||
|
корреляция логов и трасс, отсутствие запрещённых полей и сохранение истории
|
||||||
|
после перезапуска хранилищ. В выборке приватности 413 логов.
|
||||||
|
|
||||||
|
| Сценарий | Что зафиксировал прогон |
|
||||||
|
| --- | --- |
|
||||||
|
| PostgreSQL остановлен | HTTP 503, связанный ERROR span `postgres.checkout` и `dependency.unavailable` с `TimeoutError`. Firing замечен через 32,4 с от начала сценария, снятие — через 67,5 с. Trace ID `020e820d68045ad3195e842244670b11`. |
|
||||||
|
| Worker остановлен | Глубина 1, возраст 25,6 с на момент проверки. Firing замечен через 28,6 с после приёма задания. После исчерпания пяти инъецированных временных ошибок оператор выполнил replay, шестая попытка завершилась `ready`, глубина вернулась к 0, оповещение снялось. |
|
||||||
|
| Loki остановлен | 204 сообщения записаны при недоступных логах. За 51 с измерено 6 записей, потерянных после повторов экспорта, и 0 отказов постановки в очередь. Пик очереди 48 из 256 пакетов, RSS 228–231 MiB при лимите 256 MiB. После запуска Loki найден новый лог со связанной трассой. |
|
||||||
|
|
||||||
|
Трасса повтора в Tempo — `ff8352e27270fbc16fea7216c3ff45c0`. В ней проверены
|
||||||
|
родительские связи HTTP upload → `rabbitmq.publish` → `attachment.process.v1`
|
||||||
|
для всех попыток и spans `s3.read_staging`, `s3.write_result`,
|
||||||
|
`postgres.commit_ready` успешной попытки. Контрольная трасса без инъекции —
|
||||||
|
`ad41b35e5e8b02c32f7a7b74d7b6278a`. После очистки их идентификаторы и дерево
|
||||||
|
spans остаются в JSON с доказательствами.
|
||||||
|
|
||||||
## Ограничения
|
## Ограничения
|
||||||
|
|
||||||
Один Docker-host, без HA и защиты от потери диска. HTTP и анонимный Grafana Viewer —
|
Один Docker-host без высокой доступности и защиты от потери диска.
|
||||||
только для локального стенда; Tempo использует root для записи в volume.
|
Контролируемая нагрузка проверяет сценарии и пригодность диагностики.
|
||||||
Сейчас API/worker traces независимы, alerts и сквозная связь ещё не реализованы.
|
Долговременное соблюдение SLO требует наблюдения за полным 24-часовым окном.
|
||||||
SDK и Collector имеют ограниченные очереди, но длительный отказ backend пока не измерялся.
|
В сценарии Loki измерен краткий отказ. Замеры RSS показывают небольшой рост,
|
||||||
По наблюдению автора, долгий запуск контейнеров нагревает CPU примерно до 80 °C и выше:
|
а верхняя граница памяти обеспечивается настройками очередей и лимитом контейнера.
|
||||||
проверки выполняются последовательно на одном стенде с немедленной очисткой.
|
|
||||||
|
|||||||
@@ -1,3 +1,6 @@
|
|||||||
|
from contextlib import nullcontext
|
||||||
|
|
||||||
|
from sqlalchemy.pool import AsyncAdaptedQueuePool
|
||||||
from sqlalchemy.ext.asyncio import (
|
from sqlalchemy.ext.asyncio import (
|
||||||
AsyncEngine,
|
AsyncEngine,
|
||||||
AsyncSession,
|
AsyncSession,
|
||||||
@@ -8,9 +11,31 @@ from sqlalchemy.ext.asyncio import (
|
|||||||
from app.core.config import Settings
|
from app.core.config import Settings
|
||||||
|
|
||||||
|
|
||||||
|
class ObservedPool(AsyncAdaptedQueuePool):
|
||||||
|
telemetry = None
|
||||||
|
waiting = 0
|
||||||
|
|
||||||
|
def __init__(self, *args, pool_size, max_overflow, **kwargs):
|
||||||
|
self.capacity = pool_size + max_overflow if pool_size and max_overflow >= 0 else None
|
||||||
|
super().__init__(*args, pool_size=pool_size, max_overflow=max_overflow, **kwargs)
|
||||||
|
|
||||||
|
def _do_get(self):
|
||||||
|
waiting = self.capacity is not None and self.checkedout() >= self.capacity
|
||||||
|
self.waiting += int(waiting)
|
||||||
|
try:
|
||||||
|
return super()._do_get()
|
||||||
|
finally:
|
||||||
|
self.waiting -= int(waiting)
|
||||||
|
|
||||||
|
def connect(self):
|
||||||
|
with self.telemetry.span("postgres.checkout") if self.telemetry else nullcontext():
|
||||||
|
return super().connect()
|
||||||
|
|
||||||
|
|
||||||
def create_db_engine(settings: Settings) -> AsyncEngine:
|
def create_db_engine(settings: Settings) -> AsyncEngine:
|
||||||
return create_async_engine(
|
return create_async_engine(
|
||||||
settings.get_database_url(),
|
settings.get_database_url(),
|
||||||
|
poolclass=ObservedPool,
|
||||||
pool_size=settings.db_pool_size,
|
pool_size=settings.db_pool_size,
|
||||||
max_overflow=settings.db_max_overflow,
|
max_overflow=settings.db_max_overflow,
|
||||||
pool_timeout=settings.db_pool_timeout_seconds,
|
pool_timeout=settings.db_pool_timeout_seconds,
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ from uuid import UUID, uuid4
|
|||||||
from PIL import features
|
from PIL import features
|
||||||
from opentelemetry.context import Context
|
from opentelemetry.context import Context
|
||||||
from opentelemetry.trace import SpanKind
|
from opentelemetry.trace import SpanKind
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from app.core.background import (
|
from app.core.background import (
|
||||||
@@ -86,10 +87,11 @@ async def consume_connected(
|
|||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
telemetry = telemetry or Telemetry("messenger-worker", enabled=False)
|
telemetry = telemetry or Telemetry("messenger-worker", enabled=False)
|
||||||
with telemetry.tracer.start_as_current_span(
|
parent = TraceContextTextMapPropagator().extract(delivery.id.headers or {}, context=Context())
|
||||||
"attachment.process.v1", context=Context(), kind=SpanKind.CONSUMER,
|
with telemetry.span(
|
||||||
record_exception=False, set_status_on_exception=False,
|
"attachment.process.v1", context=parent, kind=SpanKind.CONSUMER,
|
||||||
attributes={"messaging.system": "rabbitmq", "job.type": message.type},
|
attributes={"messaging.system": "rabbitmq", "job.type": message.type,
|
||||||
|
"job.attempt": message.attempt},
|
||||||
):
|
):
|
||||||
telemetry.event("job.received", job_id=str(message.job_id),
|
telemetry.event("job.received", job_id=str(message.job_id),
|
||||||
attachment_id=str(message.attachment_id))
|
attachment_id=str(message.attachment_id))
|
||||||
@@ -132,6 +134,9 @@ async def run_worker(faults: Faults) -> None:
|
|||||||
raise RuntimeError("WebP codec is unavailable")
|
raise RuntimeError("WebP codec is unavailable")
|
||||||
stop = shutdown_event()
|
stop = shutdown_event()
|
||||||
engine = create_db_engine(settings)
|
engine = create_db_engine(settings)
|
||||||
|
telemetry.observe_pool(engine.pool)
|
||||||
|
telemetry.gauge("messenger.worker.busy", lambda: telemetry.busy)
|
||||||
|
telemetry.gauge("messenger.worker.capacity", lambda: jobs.worker_concurrency)
|
||||||
storage = None
|
storage = None
|
||||||
try:
|
try:
|
||||||
storage = create_s3_storage(settings.s3)
|
storage = create_s3_storage(settings.s3)
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import json
|
|||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
import signal
|
import signal
|
||||||
|
import time
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
from app.core.background import (
|
from app.core.background import (
|
||||||
@@ -19,6 +20,8 @@ from app.core.database import create_db_engine, create_session_factory
|
|||||||
from app.core.jobs import JobSettings
|
from app.core.jobs import JobSettings
|
||||||
from app.domain.attachment_jobs import publish_next_job, recover_expired_jobs
|
from app.domain.attachment_jobs import publish_next_job, recover_expired_jobs
|
||||||
from app.storage.broker import JobBroker
|
from app.storage.broker import JobBroker
|
||||||
|
from app.storage.jobs import queued_backlog
|
||||||
|
from app.core.telemetry import Telemetry
|
||||||
|
|
||||||
|
|
||||||
def crash_before_publish(attachment_id: UUID) -> None:
|
def crash_before_publish(attachment_id: UUID) -> None:
|
||||||
@@ -36,6 +39,13 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None:
|
|||||||
logging.basicConfig(level=settings.log_level)
|
logging.basicConfig(level=settings.log_level)
|
||||||
stop = shutdown_event()
|
stop = shutdown_event()
|
||||||
engine = create_db_engine(settings)
|
engine = create_db_engine(settings)
|
||||||
|
telemetry = Telemetry("messenger-publisher")
|
||||||
|
telemetry.observe_pool(engine.pool)
|
||||||
|
backlog = (0, 0.0)
|
||||||
|
labels = {"queue.name": jobs.broker_queue}
|
||||||
|
telemetry.gauge("messenger.queue.depth", lambda: backlog[0], attributes=labels)
|
||||||
|
telemetry.gauge("messenger.queue.oldest", lambda: backlog[1], unit="s", attributes=labels)
|
||||||
|
next_sample = 0.0
|
||||||
broker = None
|
broker = None
|
||||||
try:
|
try:
|
||||||
broker = JobBroker(jobs)
|
broker = JobBroker(jobs)
|
||||||
@@ -43,12 +53,16 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None:
|
|||||||
while not stop.is_set():
|
while not stop.is_set():
|
||||||
published = False
|
published = False
|
||||||
try:
|
try:
|
||||||
await broker.ensure_ready()
|
|
||||||
async with factory() as session:
|
async with factory() as session:
|
||||||
|
if telemetry.enabled and time.monotonic() >= next_sample:
|
||||||
|
backlog = await queued_backlog(session)
|
||||||
|
next_sample = time.monotonic() + 2
|
||||||
|
await broker.ensure_ready()
|
||||||
await recover_expired_jobs(session, jobs)
|
await recover_expired_jobs(session, jobs)
|
||||||
published = await publish_next_job(
|
published = await publish_next_job(
|
||||||
session,
|
session,
|
||||||
broker,
|
broker,
|
||||||
|
telemetry=telemetry,
|
||||||
attachment_id=crash_attachment_id,
|
attachment_id=crash_attachment_id,
|
||||||
before_publish=(
|
before_publish=(
|
||||||
crash_before_publish
|
crash_before_publish
|
||||||
@@ -64,6 +78,7 @@ async def run_publisher(crash_attachment_id: UUID | None = None) -> None:
|
|||||||
if broker is not None:
|
if broker is not None:
|
||||||
await broker.aclose()
|
await broker.aclose()
|
||||||
await engine.dispose()
|
await engine.dispose()
|
||||||
|
await asyncio.to_thread(telemetry.shutdown)
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
|
|||||||
+38
-1
@@ -4,6 +4,7 @@ from contextlib import contextmanager
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
from pathlib import Path
|
||||||
import socket
|
import socket
|
||||||
import time
|
import time
|
||||||
|
|
||||||
@@ -15,6 +16,7 @@ from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExp
|
|||||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||||
from opentelemetry.sdk._logs import LoggerProvider
|
from opentelemetry.sdk._logs import LoggerProvider
|
||||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||||
|
from opentelemetry.metrics import Observation
|
||||||
from opentelemetry.sdk.metrics import MeterProvider
|
from opentelemetry.sdk.metrics import MeterProvider
|
||||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||||
@@ -32,6 +34,7 @@ class Telemetry:
|
|||||||
self.enabled = (os.getenv("OTEL_ENABLED", "false").lower() == "true"
|
self.enabled = (os.getenv("OTEL_ENABLED", "false").lower() == "true"
|
||||||
if enabled is None else enabled)
|
if enabled is None else enabled)
|
||||||
self.service = service
|
self.service = service
|
||||||
|
self.busy = 0
|
||||||
if not self.enabled:
|
if not self.enabled:
|
||||||
self.tracer = trace.NoOpTracerProvider().get_tracer("messenger")
|
self.tracer = trace.NoOpTracerProvider().get_tracer("messenger")
|
||||||
return
|
return
|
||||||
@@ -61,14 +64,42 @@ class Telemetry:
|
|||||||
)
|
)
|
||||||
], views=[
|
], views=[
|
||||||
View(instrument_name="messenger.http.duration", aggregation=ExplicitBucketHistogramAggregation(HTTP_BUCKETS)),
|
View(instrument_name="messenger.http.duration", aggregation=ExplicitBucketHistogramAggregation(HTTP_BUCKETS)),
|
||||||
|
View(instrument_name="messenger.job.time_to_ready", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)),
|
||||||
View(instrument_name="messenger.job.duration", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)),
|
View(instrument_name="messenger.job.duration", aggregation=ExplicitBucketHistogramAggregation(JOB_BUCKETS)),
|
||||||
])
|
])
|
||||||
meter = self.metrics.get_meter("messenger", "1.6.0")
|
meter = self.meter = self.metrics.get_meter("messenger", "1.6.0")
|
||||||
self.http_requests = meter.create_counter("messenger.http.requests", unit="1")
|
self.http_requests = meter.create_counter("messenger.http.requests", unit="1")
|
||||||
self.http_duration = meter.create_histogram("messenger.http.duration", unit="s")
|
self.http_duration = meter.create_histogram("messenger.http.duration", unit="s")
|
||||||
self.jobs = meter.create_counter("messenger.job.attempts", unit="1")
|
self.jobs = meter.create_counter("messenger.job.attempts", unit="1")
|
||||||
self.job_duration = meter.create_histogram("messenger.job.duration", unit="s")
|
self.job_duration = meter.create_histogram("messenger.job.duration", unit="s")
|
||||||
|
|
||||||
|
self.time_to_ready = meter.create_histogram("messenger.job.time_to_ready", unit="s")
|
||||||
|
self.gauge("messenger.process.cpu", time.process_time, unit="s", counter=True)
|
||||||
|
self.gauge("messenger.process.rss", resident_bytes, unit="By")
|
||||||
|
|
||||||
|
def gauge(self, name, sample, *, unit="1", attributes=None, counter=False):
|
||||||
|
if self.enabled:
|
||||||
|
create = (self.meter.create_observable_counter if counter
|
||||||
|
else self.meter.create_observable_gauge)
|
||||||
|
create(name, callbacks=[lambda _: [Observation(sample(), attributes)]], unit=unit)
|
||||||
|
|
||||||
|
def observe_pool(self, pool):
|
||||||
|
if self.enabled:
|
||||||
|
pool.telemetry = self
|
||||||
|
self.gauge("messenger.db.pool.used", pool.checkedout)
|
||||||
|
self.gauge("messenger.db.pool.waiting", lambda: pool.waiting)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def span(self, name, **kwargs):
|
||||||
|
with self.tracer.start_as_current_span(
|
||||||
|
name, record_exception=False, set_status_on_exception=False, **kwargs,
|
||||||
|
) as span:
|
||||||
|
try:
|
||||||
|
yield span
|
||||||
|
except BaseException:
|
||||||
|
span.set_status(Status(StatusCode.ERROR))
|
||||||
|
raise
|
||||||
|
|
||||||
def event(self, event: str, *, error=False, **fields):
|
def event(self, event: str, *, error=False, **fields):
|
||||||
if not self.enabled:
|
if not self.enabled:
|
||||||
return
|
return
|
||||||
@@ -89,6 +120,7 @@ class Telemetry:
|
|||||||
|
|
||||||
@contextmanager
|
@contextmanager
|
||||||
def job_attempt(self):
|
def job_attempt(self):
|
||||||
|
self.busy += 1
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
result = {"outcome": "success"}
|
result = {"outcome": "success"}
|
||||||
try:
|
try:
|
||||||
@@ -97,6 +129,7 @@ class Telemetry:
|
|||||||
result["outcome"] = "error"
|
result["outcome"] = "error"
|
||||||
raise
|
raise
|
||||||
finally:
|
finally:
|
||||||
|
self.busy -= 1
|
||||||
if self.enabled:
|
if self.enabled:
|
||||||
attrs = {"job.type": "attachment.process.v1", "outcome": result["outcome"]}
|
attrs = {"job.type": "attachment.process.v1", "outcome": result["outcome"]}
|
||||||
elapsed = time.monotonic() - started
|
elapsed = time.monotonic() - started
|
||||||
@@ -115,6 +148,10 @@ class Telemetry:
|
|||||||
self.traces.shutdown()
|
self.traces.shutdown()
|
||||||
|
|
||||||
|
|
||||||
|
def resident_bytes():
|
||||||
|
return int(Path("/proc/self/statm").read_text().split()[1]) * os.sysconf("SC_PAGE_SIZE")
|
||||||
|
|
||||||
|
|
||||||
class HttpTelemetryMiddleware:
|
class HttpTelemetryMiddleware:
|
||||||
def __init__(self, app, telemetry: Telemetry):
|
def __init__(self, app, telemetry: Telemetry):
|
||||||
self.app = app
|
self.app = app
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ from tempfile import TemporaryDirectory
|
|||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from minio.error import MinioException
|
from minio.error import MinioException
|
||||||
|
from opentelemetry.context import Context
|
||||||
|
from opentelemetry.trace import SpanKind
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
from urllib3.exceptions import HTTPError as StorageHTTPError
|
from urllib3.exceptions import HTTPError as StorageHTTPError
|
||||||
|
|
||||||
@@ -44,6 +47,7 @@ async def publish_next_job(
|
|||||||
*,
|
*,
|
||||||
attachment_id: UUID | None = None,
|
attachment_id: UUID | None = None,
|
||||||
before_publish: Callable[[UUID], None] | None = None,
|
before_publish: Callable[[UUID], None] | None = None,
|
||||||
|
telemetry: Telemetry | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""Отметка publish следует за durable publisher confirm; crash допускает тот же job-дубль."""
|
"""Отметка publish следует за durable publisher confirm; crash допускает тот же job-дубль."""
|
||||||
job = await outbox.next_unpublished_job(session, attachment_id=attachment_id)
|
job = await outbox.next_unpublished_job(session, attachment_id=attachment_id)
|
||||||
@@ -51,15 +55,20 @@ async def publish_next_job(
|
|||||||
if job is not None:
|
if job is not None:
|
||||||
if before_publish is not None:
|
if before_publish is not None:
|
||||||
before_publish(job.attachment_id)
|
before_publish(job.attachment_id)
|
||||||
await broker.publish_job(
|
parent = TraceContextTextMapPropagator().extract(job.trace_context or {}, context=Context())
|
||||||
JobMessage(
|
with telemetry.span(
|
||||||
job_id=job.id,
|
"rabbitmq.publish", context=parent, kind=SpanKind.PRODUCER,
|
||||||
attachment_id=job.attachment_id,
|
attributes={"messaging.system": "rabbitmq", "job.attempt": job.attempt + 1},
|
||||||
pipeline_version=job.pipeline_version,
|
) if telemetry else nullcontext():
|
||||||
attempt=job.attempt + 1,
|
await broker.publish_job(
|
||||||
created_at=job.created_at,
|
JobMessage(
|
||||||
|
job_id=job.id,
|
||||||
|
attachment_id=job.attachment_id,
|
||||||
|
pipeline_version=job.pipeline_version,
|
||||||
|
attempt=job.attempt + 1,
|
||||||
|
created_at=job.created_at,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
|
||||||
outbox.mark_published(job)
|
outbox.mark_published(job)
|
||||||
await session.commit()
|
await session.commit()
|
||||||
return published
|
return published
|
||||||
@@ -145,11 +154,13 @@ async def build_result(
|
|||||||
storage: MinioStorage,
|
storage: MinioStorage,
|
||||||
work: JobWork,
|
work: JobWork,
|
||||||
after_object: Callable[[UUID, str], None] | None = None,
|
after_object: Callable[[UUID, str], None] | None = None,
|
||||||
|
telemetry: Telemetry | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
"""Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки."""
|
"""Фиксированные ключи и блокировка job защищают PUT от устаревшей попытки."""
|
||||||
with TemporaryDirectory(prefix="messenger-job-") as directory:
|
with TemporaryDirectory(prefix="messenger-job-") as directory:
|
||||||
source = Path(directory) / "original"
|
source = Path(directory) / "original"
|
||||||
await fetch_original(storage, work, source)
|
with telemetry.span("s3.read_staging") if telemetry else nullcontext():
|
||||||
|
await fetch_original(storage, work, source)
|
||||||
result = await render_variants(storage, work, source, Path(directory))
|
result = await render_variants(storage, work, source, Path(directory))
|
||||||
row = await jobs.lock_job(session, work.job_id)
|
row = await jobs.lock_job(session, work.job_id)
|
||||||
if row is None:
|
if row is None:
|
||||||
@@ -165,33 +176,39 @@ async def build_result(
|
|||||||
return False
|
return False
|
||||||
# Блокировка остаётся до завершения PUT/COMMIT; reaper использует SKIP LOCKED.
|
# Блокировка остаётся до завершения PUT/COMMIT; reaper использует SKIP LOCKED.
|
||||||
# При отмене S3 adapter дожидается SDK-потока до освобождения блокировки.
|
# При отмене S3 adapter дожидается SDK-потока до освобождения блокировки.
|
||||||
await storage.put_file(
|
with telemetry.span("s3.write_result") if telemetry else nullcontext():
|
||||||
work.original_key,
|
|
||||||
source,
|
|
||||||
size_bytes=work.size_bytes,
|
|
||||||
content_type=work.content_type,
|
|
||||||
sha256=work.sha256,
|
|
||||||
)
|
|
||||||
if after_object is not None:
|
|
||||||
after_object(work.attachment_id, "original")
|
|
||||||
for variant in result.variants:
|
|
||||||
await storage.put_file(
|
await storage.put_file(
|
||||||
work.variant_key(variant.name),
|
work.original_key,
|
||||||
Path(directory) / VARIANT_FILENAMES[variant.name],
|
source,
|
||||||
size_bytes=variant.size_bytes,
|
size_bytes=work.size_bytes,
|
||||||
content_type=variant.content_type,
|
content_type=work.content_type,
|
||||||
sha256=variant.sha256,
|
sha256=work.sha256,
|
||||||
)
|
)
|
||||||
if after_object is not None:
|
if after_object is not None:
|
||||||
after_object(work.attachment_id, variant.name)
|
after_object(work.attachment_id, "original")
|
||||||
jobs.complete_job(
|
for variant in result.variants:
|
||||||
job,
|
await storage.put_file(
|
||||||
attachment,
|
work.variant_key(variant.name),
|
||||||
work,
|
Path(directory) / VARIANT_FILENAMES[variant.name],
|
||||||
[variant.model_dump() for variant in result.variants],
|
size_bytes=variant.size_bytes,
|
||||||
await jobs.database_time(session),
|
content_type=variant.content_type,
|
||||||
)
|
sha256=variant.sha256,
|
||||||
await session.commit()
|
)
|
||||||
|
if after_object is not None:
|
||||||
|
after_object(work.attachment_id, variant.name)
|
||||||
|
with telemetry.span("postgres.commit_ready") if telemetry else nullcontext():
|
||||||
|
ready_at = await jobs.database_time(session)
|
||||||
|
accepted_at = job.created_at
|
||||||
|
jobs.complete_job(
|
||||||
|
job,
|
||||||
|
attachment,
|
||||||
|
work,
|
||||||
|
[variant.model_dump() for variant in result.variants],
|
||||||
|
ready_at,
|
||||||
|
)
|
||||||
|
await session.commit()
|
||||||
|
if telemetry and telemetry.enabled:
|
||||||
|
telemetry.time_to_ready.record(max(0, (ready_at - accepted_at).total_seconds()))
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@@ -205,7 +222,8 @@ async def process_attachment_job(
|
|||||||
before_processing: Callable[[UUID], None] | None = None,
|
before_processing: Callable[[UUID], None] | None = None,
|
||||||
telemetry: Telemetry | None = None,
|
telemetry: Telemetry | None = None,
|
||||||
) -> bool:
|
) -> bool:
|
||||||
claim = await claim_job(session, message, settings)
|
with telemetry.span("postgres.claim_job") if telemetry else nullcontext():
|
||||||
|
claim = await claim_job(session, message, settings)
|
||||||
acknowledge = claim.acknowledge
|
acknowledge = claim.acknowledge
|
||||||
if claim.work is not None:
|
if claim.work is not None:
|
||||||
work = claim.work
|
work = claim.work
|
||||||
@@ -214,7 +232,7 @@ async def process_attachment_job(
|
|||||||
async with asyncio.timeout(settings.job_timeout_seconds):
|
async with asyncio.timeout(settings.job_timeout_seconds):
|
||||||
if before_processing is not None:
|
if before_processing is not None:
|
||||||
before_processing(work.attachment_id)
|
before_processing(work.attachment_id)
|
||||||
acknowledge = await build_result(session, storage, work, after_object)
|
acknowledge = await build_result(session, storage, work, after_object, telemetry)
|
||||||
result["outcome"] = "success" if acknowledge else "deferred"
|
result["outcome"] = "success" if acknowledge else "deferred"
|
||||||
except (
|
except (
|
||||||
ProcessingError,
|
ProcessingError,
|
||||||
|
|||||||
@@ -61,6 +61,7 @@ def create_app(settings: Settings | None = None) -> FastAPI:
|
|||||||
application.state.request_capacity = create_request_capacity(settings.max_in_flight)
|
application.state.request_capacity = create_request_capacity(settings.max_in_flight)
|
||||||
application.state.instance_id = resolve_instance_id(settings.instance_id)
|
application.state.instance_id = resolve_instance_id(settings.instance_id)
|
||||||
telemetry = Telemetry("messenger-api", application.state.instance_id)
|
telemetry = Telemetry("messenger-api", application.state.instance_id)
|
||||||
|
telemetry.observe_pool(engine.pool)
|
||||||
application.state.telemetry = telemetry
|
application.state.telemetry = telemetry
|
||||||
application.state.lifecycle = Lifecycle()
|
application.state.lifecycle = Lifecycle()
|
||||||
application.add_middleware(RequestIdMiddleware)
|
application.add_middleware(RequestIdMiddleware)
|
||||||
|
|||||||
+2
-1
@@ -3,7 +3,7 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from uuid import UUID, uuid4
|
from uuid import UUID, uuid4
|
||||||
|
|
||||||
from sqlalchemy import CheckConstraint, ForeignKey, Index, String, func
|
from sqlalchemy import JSON, CheckConstraint, ForeignKey, Index, String, func
|
||||||
from sqlalchemy.orm import Mapped, mapped_column
|
from sqlalchemy.orm import Mapped, mapped_column
|
||||||
|
|
||||||
from app.models.base import Base
|
from app.models.base import Base
|
||||||
@@ -23,6 +23,7 @@ class AttachmentJob(Base):
|
|||||||
ForeignKey("attachments.id"),
|
ForeignKey("attachments.id"),
|
||||||
unique=True,
|
unique=True,
|
||||||
)
|
)
|
||||||
|
trace_context: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||||
staging_key: Mapped[str | None] = mapped_column(String(128))
|
staging_key: Mapped[str | None] = mapped_column(String(128))
|
||||||
pipeline_version: Mapped[int] = mapped_column(server_default="1")
|
pipeline_version: Mapped[int] = mapped_column(server_default="1")
|
||||||
attempt: Mapped[int] = mapped_column(server_default="0")
|
attempt: Mapped[int] = mapped_column(server_default="0")
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ from dataclasses import dataclass
|
|||||||
|
|
||||||
import aio_pika
|
import aio_pika
|
||||||
from aio_pika.abc import AbstractIncomingMessage
|
from aio_pika.abc import AbstractIncomingMessage
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
|
|
||||||
from app.core.jobs import JobSettings
|
from app.core.jobs import JobSettings
|
||||||
from app.schemas.job import JobMessage
|
from app.schemas.job import JobMessage
|
||||||
@@ -54,10 +55,13 @@ class JobBroker:
|
|||||||
|
|
||||||
async def publish_job(self, message: JobMessage) -> None:
|
async def publish_job(self, message: JobMessage) -> None:
|
||||||
await self.ensure_ready()
|
await self.ensure_ready()
|
||||||
|
headers = {}
|
||||||
|
TraceContextTextMapPropagator().inject(headers)
|
||||||
await self.channel.default_exchange.publish(
|
await self.channel.default_exchange.publish(
|
||||||
aio_pika.Message(
|
aio_pika.Message(
|
||||||
body=message.model_dump_json(exclude_none=True).encode(),
|
body=message.model_dump_json(exclude_none=True).encode(),
|
||||||
content_type="application/json",
|
content_type="application/json",
|
||||||
|
headers=headers,
|
||||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||||
message_id=f"{message.job_id}:{message.attempt}",
|
message_id=f"{message.job_id}:{message.attempt}",
|
||||||
),
|
),
|
||||||
|
|||||||
+14
-1
@@ -4,6 +4,7 @@ from dataclasses import dataclass
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
from uuid import UUID
|
from uuid import UUID
|
||||||
|
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
from sqlalchemy import and_, or_, func, select
|
from sqlalchemy import and_, or_, func, select
|
||||||
from sqlalchemy.ext.asyncio import AsyncSession
|
from sqlalchemy.ext.asyncio import AsyncSession
|
||||||
|
|
||||||
@@ -35,7 +36,10 @@ class JobWork:
|
|||||||
async def create_job(
|
async def create_job(
|
||||||
session: AsyncSession, attachment_id: UUID, staging_key: str
|
session: AsyncSession, attachment_id: UUID, staging_key: str
|
||||||
) -> UUID:
|
) -> UUID:
|
||||||
job = AttachmentJob(attachment_id=attachment_id, staging_key=staging_key)
|
carrier = {}
|
||||||
|
TraceContextTextMapPropagator().inject(carrier)
|
||||||
|
job = AttachmentJob(attachment_id=attachment_id, staging_key=staging_key,
|
||||||
|
trace_context=carrier or None)
|
||||||
session.add(job)
|
session.add(job)
|
||||||
await session.flush()
|
await session.flush()
|
||||||
return job.id
|
return job.id
|
||||||
@@ -56,6 +60,15 @@ async def database_time(session: AsyncSession) -> datetime:
|
|||||||
return await session.scalar(select(func.clock_timestamp()))
|
return await session.scalar(select(func.clock_timestamp()))
|
||||||
|
|
||||||
|
|
||||||
|
async def queued_backlog(session: AsyncSession) -> tuple[int, float]:
|
||||||
|
count, oldest = (await session.execute(
|
||||||
|
select(func.count(), func.min(AttachmentJob.created_at))
|
||||||
|
.join(Attachment, Attachment.id == AttachmentJob.attachment_id)
|
||||||
|
.where(Attachment.status == "queued")
|
||||||
|
)).one()
|
||||||
|
return count, max(0, ((await database_time(session)) - oldest).total_seconds()) if oldest else 0.0
|
||||||
|
|
||||||
|
|
||||||
async def expired_jobs(session: AsyncSession, limit: int = 20):
|
async def expired_jobs(session: AsyncSession, limit: int = 20):
|
||||||
result = await session.execute(
|
result = await session.execute(
|
||||||
select(AttachmentJob, Attachment)
|
select(AttachmentJob, Attachment)
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Локальный доступ к сервисам из VS Code и браузера.
|
||||||
|
# docker compose -f compose.yaml -f compose.local.yml up -d --wait
|
||||||
|
# Все опубликованные порты доступны только с этого компьютера.
|
||||||
|
services:
|
||||||
|
api:
|
||||||
|
# Docker выделяет каждой реплике отдельный свободный порт диапазона.
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:8081-8090:8080"
|
||||||
|
postgres:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${POSTGRES_LOCAL_PORT:-5432}:5432"
|
||||||
|
redis:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${REDIS_LOCAL_PORT:-6379}:6379"
|
||||||
|
minio:
|
||||||
|
command: ["server", "/data", "--console-address", "0.0.0.0:9001"]
|
||||||
|
environment:
|
||||||
|
MINIO_BROWSER: "on"
|
||||||
|
# Добавляем обычную сеть для доступа через опубликованные порты;
|
||||||
|
# внутренняя objects сохраняется для приложения и bootstrap.
|
||||||
|
networks: [default, objects]
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${MINIO_LOCAL_PORT:-9000}:9000"
|
||||||
|
- "127.0.0.1:${MINIO_CONSOLE_LOCAL_PORT:-9001}:9001"
|
||||||
|
broker:
|
||||||
|
volumes:
|
||||||
|
- ./infra/broker/enabled_plugins.local:/etc/rabbitmq/enabled_plugins:ro
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${BROKER_LOCAL_PORT:-5672}:5672"
|
||||||
|
- "127.0.0.1:${BROKER_MANAGEMENT_LOCAL_PORT:-15672}:15672"
|
||||||
|
prometheus:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${PROMETHEUS_LOCAL_PORT:-9090}:9090"
|
||||||
|
loki:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${LOKI_LOCAL_PORT:-3100}:3100"
|
||||||
|
tempo:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${TEMPO_LOCAL_PORT:-3200}:3200"
|
||||||
|
- "127.0.0.1:${TEMPO_OTLP_LOCAL_PORT:-14318}:4318"
|
||||||
|
otel-collector:
|
||||||
|
ports:
|
||||||
|
- "127.0.0.1:${OTEL_HTTP_LOCAL_PORT:-4318}:4318"
|
||||||
|
- "127.0.0.1:${OTEL_METRICS_LOCAL_PORT:-8889}:8889"
|
||||||
|
- "127.0.0.1:${OTEL_HEALTH_LOCAL_PORT:-13133}:13133"
|
||||||
@@ -409,6 +409,7 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
volumes:
|
volumes:
|
||||||
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- ./infra/otel/alerts.yaml:/etc/prometheus/alerts.yaml:ro
|
||||||
- prometheusdata:/prometheus
|
- prometheusdata:/prometheus
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"]
|
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9090/-/ready"]
|
||||||
|
|||||||
+650
-160
File diff suppressed because it is too large
Load Diff
+14
-346
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"date_utc": "2026-11-14T01:50:28.592547+00:00",
|
"date_utc": "2026-11-19T15:50:02.598982+00:00",
|
||||||
"checks": [
|
"checks": [
|
||||||
{
|
{
|
||||||
"name": "contract",
|
"name": "contract",
|
||||||
@@ -8,7 +8,7 @@
|
|||||||
"scripts/check_contract.py"
|
"scripts/check_contract.py"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 0.101,
|
"duration_seconds": 0.112,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
"scripts/validate_openapi.py"
|
"scripts/validate_openapi.py"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 1.111,
|
"duration_seconds": 1.068,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -32,7 +32,7 @@
|
|||||||
"--quiet"
|
"--quiet"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 0.131,
|
"duration_seconds": 0.113,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -43,7 +43,7 @@
|
|||||||
"test-stand-up"
|
"test-stand-up"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 77.116,
|
"duration_seconds": 70.403,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -54,9 +54,9 @@
|
|||||||
"test-unit"
|
"test-unit"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 115.183,
|
"duration_seconds": 322.597,
|
||||||
"result": "PASS",
|
"result": "PASS",
|
||||||
"summary": "206 passed in 112.44s (0:01:52)"
|
"summary": "206 passed in 98.89s (0:01:38)"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "api",
|
"name": "api",
|
||||||
@@ -67,7 +67,7 @@
|
|||||||
"http://localhost:28080"
|
"http://localhost:28080"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 8.349,
|
"duration_seconds": 4.112,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -84,7 +84,7 @@
|
|||||||
"--restart-telemetry"
|
"--restart-telemetry"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 79.231,
|
"duration_seconds": 292.686,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -100,7 +100,7 @@
|
|||||||
"http://localhost:28080"
|
"http://localhost:28080"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 62.485,
|
"duration_seconds": 61.526,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -116,7 +116,7 @@
|
|||||||
"http://localhost:28080"
|
"http://localhost:28080"
|
||||||
],
|
],
|
||||||
"exit_code": 0,
|
"exit_code": 0,
|
||||||
"duration_seconds": 17.998,
|
"duration_seconds": 19.039,
|
||||||
"result": "PASS"
|
"result": "PASS"
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -128,345 +128,13 @@
|
|||||||
},
|
},
|
||||||
"result": "PASS",
|
"result": "PASS",
|
||||||
"cleanup": {
|
"cleanup": {
|
||||||
"projects": [
|
"project": "messenger-test",
|
||||||
"messenger",
|
|
||||||
"messenger-test"
|
|
||||||
],
|
|
||||||
"resources": {
|
|
||||||
"containers": [
|
|
||||||
"062d88c22d6c",
|
|
||||||
"5653c0121264",
|
|
||||||
"6e2b3ca3c86c",
|
|
||||||
"ac60f4044ea7",
|
|
||||||
"e633226993b5",
|
|
||||||
"1e21fe44a453",
|
|
||||||
"126c76cff388",
|
|
||||||
"76901c1e8b60",
|
|
||||||
"85731e19d4c6",
|
|
||||||
"79077e49c5ee",
|
|
||||||
"80a7e7e36fd1",
|
|
||||||
"69f42359b3e3",
|
|
||||||
"1a3d86fafd53",
|
|
||||||
"9f00acc93186",
|
|
||||||
"bd366e53bf42",
|
|
||||||
"b4f81e6b52c3",
|
|
||||||
"a9f375b0b17b"
|
|
||||||
],
|
|
||||||
"networks": [
|
|
||||||
"04eba990b02c",
|
|
||||||
"ff8d81906905"
|
|
||||||
],
|
|
||||||
"volumes": [
|
|
||||||
"messenger-test_grafanadata",
|
|
||||||
"messenger-test_lokidata",
|
|
||||||
"messenger-test_miniodata",
|
|
||||||
"messenger-test_pgdata",
|
|
||||||
"messenger-test_prometheusdata",
|
|
||||||
"messenger-test_rabbitmqdata",
|
|
||||||
"messenger-test_redisdata",
|
|
||||||
"messenger-test_tempodata"
|
|
||||||
]
|
|
||||||
},
|
|
||||||
"application_image_ids": [
|
|
||||||
"490c0e5b26df",
|
|
||||||
"669227412939",
|
|
||||||
"af2ab3c10330"
|
|
||||||
],
|
|
||||||
"local_settings_preserved": true,
|
|
||||||
"remaining": {
|
"remaining": {
|
||||||
"containers": [],
|
"containers": [],
|
||||||
"networks": [],
|
"networks": [],
|
||||||
"volumes": []
|
"volumes": []
|
||||||
},
|
},
|
||||||
"application_images_remaining": [],
|
"result": "PASS"
|
||||||
"result": "PASS",
|
|
||||||
"verified": {
|
|
||||||
"containers_remaining": 0,
|
|
||||||
"volumes_remaining": 0,
|
|
||||||
"application_images_remaining": 0,
|
|
||||||
"local_settings_preserved": true
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
"finished_at_utc": "2026-11-14T01:56:33.228789+00:00",
|
"finished_at_utc": "2026-11-19T16:03:05.425775+00:00"
|
||||||
"source": {
|
|
||||||
"base_commit": "498ce1e0d20c7ffc45ef71b81f5ce3cfa56208ec",
|
|
||||||
"working_tree_modified": true
|
|
||||||
},
|
|
||||||
"runtime": {
|
|
||||||
"python": "3.12.14",
|
|
||||||
"docker_engine": "29.9.3",
|
|
||||||
"compose": "5.7.0"
|
|
||||||
},
|
|
||||||
"container_lifecycle": [
|
|
||||||
{
|
|
||||||
"time_unix": 1794621212,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "redis"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621212,
|
|
||||||
"action": "start",
|
|
||||||
"service": "redis"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621251,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "postgres"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621251,
|
|
||||||
"action": "start",
|
|
||||||
"service": "publisher"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621254,
|
|
||||||
"action": "start",
|
|
||||||
"service": "postgres"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621255,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621256,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621267,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621269,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621271,
|
|
||||||
"action": "start",
|
|
||||||
"service": "minio-bootstrap"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621272,
|
|
||||||
"action": "start",
|
|
||||||
"service": "migrate"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621275,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621281,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621284,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621292,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621295,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "prometheus"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621295,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "grafana"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621295,
|
|
||||||
"action": "start",
|
|
||||||
"service": "prometheus"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621295,
|
|
||||||
"action": "start",
|
|
||||||
"service": "grafana"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621295,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "loki"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621296,
|
|
||||||
"action": "start",
|
|
||||||
"service": "loki"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621305,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "tempo"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621305,
|
|
||||||
"action": "start",
|
|
||||||
"service": "tempo"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621314,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621314,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "publisher"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621324,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "cleanup"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621324,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "otel-collector"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "minio"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "prometheus"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "grafana"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "broker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "redis"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "postgres"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "loki"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "minio"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "otel-collector"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "prometheus"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "grafana"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "broker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "redis"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "postgres"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621325,
|
|
||||||
"action": "start",
|
|
||||||
"service": "loki"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621334,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "tempo"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621335,
|
|
||||||
"action": "start",
|
|
||||||
"service": "tempo"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621335,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "nginx"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621336,
|
|
||||||
"action": "start",
|
|
||||||
"service": "nginx"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621337,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "api"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621337,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "api"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621337,
|
|
||||||
"action": "start",
|
|
||||||
"service": "api"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621337,
|
|
||||||
"action": "start",
|
|
||||||
"service": "api"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621344,
|
|
||||||
"action": "start",
|
|
||||||
"service": "cleanup"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621344,
|
|
||||||
"action": "start",
|
|
||||||
"service": "publisher"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621345,
|
|
||||||
"action": "start",
|
|
||||||
"service": "worker"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"time_unix": 1794621377,
|
|
||||||
"action": "stop",
|
|
||||||
"service": "api"
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Наблюдаемость Messenger
|
# Наблюдаемость Messenger
|
||||||
|
|
||||||
API и worker экспортируют OTLP HTTP/protobuf в Collector (:4318).
|
API, publisher и worker экспортируют OTLP HTTP/protobuf в Collector (:4318).
|
||||||
Метрики выдаются Prometheus на :8889, логи отправляются в native OTLP Loki,
|
Метрики выдаются Prometheus на :8889, логи отправляются в native OTLP Loki,
|
||||||
traces — в Tempo. Grafana читает три хранилища через provisioned datasources.
|
traces — в Tempo. Grafana читает три хранилища через provisioned datasources.
|
||||||
|
|
||||||
@@ -15,6 +15,6 @@ grafanadata содержит настройки Grafana. Внешний порт
|
|||||||
по умолчанию 127.0.0.1:13000. Её healthcheck проверяет также Loki, Tempo и Collector.
|
по умолчанию 127.0.0.1:13000. Её healthcheck проверяет также Loki, Tempo и Collector.
|
||||||
Бизнес-readiness API от этих сервисов не зависит.
|
Бизнес-readiness API от этих сервисов не зависит.
|
||||||
|
|
||||||
Проверка: `make test-observability`. Полный прогон с очисткой: `make verify`.
|
`make test-observability` запускает контролируемые отказы на указанном стенде.
|
||||||
Инструкция запуска — в [RUNNING.md](../../RUNNING.md), ограничения и планы — в
|
`make verify` создаёт отдельный проект и удаляет его ресурсы после прогона.
|
||||||
[REPORT.md](../../REPORT.md).
|
Правила Prometheus, запуск и порядок диагностики описаны в [REPORT.md](../../REPORT.md).
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger
|
||||||
|
interval: 5s
|
||||||
|
rules:
|
||||||
|
- alert: MessengerHighErrorRate
|
||||||
|
expr: |
|
||||||
|
sum(increase(messenger_http_requests_total{http_response_status_class="5xx",http_route!~"/health/.*"}[30s]))
|
||||||
|
/ clamp_min(sum(increase(messenger_http_requests_total{http_route!~"/health/.*"}[30s])), 1) > 0.05
|
||||||
|
for: 5s
|
||||||
|
annotations:
|
||||||
|
summary: "Более 5% бизнес-запросов завершились HTTP 5xx за 30 секунд"
|
||||||
|
runbook: "REPORT.md#диагностика-инцидентов"
|
||||||
|
- alert: MessengerQueueLag
|
||||||
|
expr: max(messenger_queue_oldest_seconds) > 15 and max(messenger_queue_depth_ratio) > 0
|
||||||
|
for: 5s
|
||||||
|
annotations:
|
||||||
|
summary: "Старейшее ожидающее задание находится в очереди более 15 секунд"
|
||||||
|
runbook: "REPORT.md#диагностика-инцидентов"
|
||||||
@@ -37,6 +37,14 @@ extensions:
|
|||||||
health_check:
|
health_check:
|
||||||
endpoint: 0.0.0.0:13133
|
endpoint: 0.0.0.0:13133
|
||||||
service:
|
service:
|
||||||
|
telemetry:
|
||||||
|
metrics:
|
||||||
|
readers:
|
||||||
|
- pull:
|
||||||
|
exporter:
|
||||||
|
prometheus:
|
||||||
|
host: 0.0.0.0
|
||||||
|
port: 8888
|
||||||
extensions: [health_check]
|
extensions: [health_check]
|
||||||
pipelines:
|
pipelines:
|
||||||
metrics:
|
metrics:
|
||||||
|
|||||||
@@ -332,6 +332,280 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"description": "Накопленное число 5xx: показывает и первую ошибку нового ряда, когда rate ещё не имеет двух разных точек."
|
"description": "Накопленное число 5xx: показывает и первую ошибку нового ряда, когда rate ещё не имеет двух разных точек."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 11,
|
||||||
|
"title": "Очередь: ожидающие задания",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 0,
|
||||||
|
"y": 45
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "max by (queue_name) (messenger_queue_depth_ratio)",
|
||||||
|
"legendFormat": "Глубина {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 12,
|
||||||
|
"title": "Очередь: возраст старейшей задачи",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 12,
|
||||||
|
"y": 45
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "max by (queue_name) (messenger_queue_oldest_seconds)",
|
||||||
|
"legendFormat": "Возраст {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 13,
|
||||||
|
"title": "PostgreSQL: соединения и ожидающие",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 0,
|
||||||
|
"y": 53
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (service_name) (messenger_db_pool_used_ratio)",
|
||||||
|
"legendFormat": "Занято {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "sum by (service_name) (messenger_db_pool_waiting_ratio)",
|
||||||
|
"legendFormat": "Ожидают {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 14,
|
||||||
|
"title": "Worker: доля занятых слотов",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 12,
|
||||||
|
"y": 53
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "percentunit"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum(messenger_worker_busy_ratio) / sum(messenger_worker_capacity_ratio)",
|
||||||
|
"legendFormat": "Загрузка {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 15,
|
||||||
|
"title": "Процессы: CPU в ядрах",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 0,
|
||||||
|
"y": 61
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (service_name) (rate(messenger_process_cpu_seconds_total[1m]))",
|
||||||
|
"legendFormat": "CPU {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 16,
|
||||||
|
"title": "Процессы: резидентная память",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 12,
|
||||||
|
"y": 61
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "bytes"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "sum by (service_name) (messenger_process_rss_bytes)",
|
||||||
|
"legendFormat": "RSS {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 17,
|
||||||
|
"title": "Вложения: p95 времени до ready",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 0,
|
||||||
|
"y": 69
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "s"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
|
||||||
|
"legendFormat": "p95 {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": 18,
|
||||||
|
"title": "Collector: очереди экспорта",
|
||||||
|
"type": "timeseries",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
},
|
||||||
|
"gridPos": {
|
||||||
|
"h": 8,
|
||||||
|
"w": 12,
|
||||||
|
"x": 12,
|
||||||
|
"y": 69
|
||||||
|
},
|
||||||
|
"fieldConfig": {
|
||||||
|
"defaults": {
|
||||||
|
"unit": "short"
|
||||||
|
},
|
||||||
|
"overrides": []
|
||||||
|
},
|
||||||
|
"targets": [
|
||||||
|
{
|
||||||
|
"refId": "A",
|
||||||
|
"expr": "max by (exporter) (otelcol_exporter_queue_size)",
|
||||||
|
"legendFormat": "Размер {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"refId": "B",
|
||||||
|
"expr": "max by (exporter) (otelcol_exporter_queue_capacity)",
|
||||||
|
"legendFormat": "Ёмкость {{service_name}}{{queue_name}}{{exporter}}",
|
||||||
|
"datasource": {
|
||||||
|
"type": "prometheus",
|
||||||
|
"uid": "prometheus"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"annotations": {
|
"annotations": {
|
||||||
|
|||||||
@@ -5,3 +5,7 @@ scrape_configs:
|
|||||||
- job_name: messenger
|
- job_name: messenger
|
||||||
static_configs:
|
static_configs:
|
||||||
- targets: [otel-collector:8889]
|
- targets: [otel-collector:8889]
|
||||||
|
- job_name: collector
|
||||||
|
static_configs:
|
||||||
|
- targets: [otel-collector:8888]
|
||||||
|
rule_files: [/etc/prometheus/alerts.yaml]
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
"""Сохранить W3C context между HTTP-транзакцией и publisher."""
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision = "b55d0c6819ab"
|
||||||
|
down_revision = "a62c950e18b3"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
op.add_column("attachment_jobs", sa.Column("trace_context", sa.JSON(), nullable=True))
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
op.drop_column("attachment_jobs", "trace_context")
|
||||||
@@ -179,7 +179,7 @@ def crash(client, actor, chat, mode):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def retry_replay(client, actor, chat, permanent, on_failed=None):
|
def retry_replay(client, actor, chat, permanent, on_failed=None, on_queued=None):
|
||||||
name = "messenger-retry-fault-" + uuid4().hex
|
name = "messenger-retry-fault-" + uuid4().hex
|
||||||
samples = []
|
samples = []
|
||||||
configuration = ComposeProject().config["services"]["worker"]["environment"]
|
configuration = ComposeProject().config["services"]["worker"]["environment"]
|
||||||
@@ -188,6 +188,8 @@ def retry_replay(client, actor, chat, permanent, on_failed=None):
|
|||||||
try:
|
try:
|
||||||
require_compose("stop", "worker")
|
require_compose("stop", "worker")
|
||||||
attachment, original = client.attachment(actor, chat)
|
attachment, original = client.attachment(actor, chat)
|
||||||
|
if on_queued is not None:
|
||||||
|
on_queued(attachment)
|
||||||
mode = "fail-permanent" if permanent else "fail-transient"
|
mode = "fail-permanent" if permanent else "fail-transient"
|
||||||
require_compose(
|
require_compose(
|
||||||
"run",
|
"run",
|
||||||
|
|||||||
+132
-28
@@ -1,6 +1,6 @@
|
|||||||
"""Проверка наблюдаемости через реальные запросы Grafana к трём backend.
|
"""Проверка наблюдаемости через реальные запросы Grafana к трём backend.
|
||||||
|
|
||||||
--incidents явно разрешает два ограниченных отказа на выбранном Compose-проекте.
|
--incidents явно разрешает ограниченные отказы на выбранном Compose-проекте.
|
||||||
В evidence сохраняются только агрегаты и выбранные технические поля.
|
В evidence сохраняются только агрегаты и выбранные технические поля.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
@@ -168,6 +168,84 @@ def run_load(args):
|
|||||||
return report
|
return report
|
||||||
|
|
||||||
|
|
||||||
|
def metric(grafana, expression):
|
||||||
|
rows = grafana.query(expression)
|
||||||
|
return float(rows[0]['value'][1]) if rows else None
|
||||||
|
|
||||||
|
|
||||||
|
def alert_firing(grafana, name):
|
||||||
|
return bool(grafana.query(f'ALERTS{{alertname="{name}",alertstate="firing"}}'))
|
||||||
|
|
||||||
|
|
||||||
|
def trace_chain(grafana, trace_id, *, retry=False):
|
||||||
|
def inspect():
|
||||||
|
spans = spans_in(grafana.trace(trace_id))
|
||||||
|
by_id = {identifier_hex(span['spanId'], 8): span for span in spans}
|
||||||
|
workers = [span for span in spans if span['name'] == 'attachment.process.v1'
|
||||||
|
and span.get('kind') in ('SPAN_KIND_CONSUMER', 5)]
|
||||||
|
for worker in workers:
|
||||||
|
publisher = by_id.get(identifier_hex(worker.get('parentSpanId', ''), 8), {})
|
||||||
|
if publisher.get('kind') not in ('SPAN_KIND_PRODUCER', 4):
|
||||||
|
return None
|
||||||
|
upload = by_id.get(identifier_hex(publisher.get('parentSpanId', ''), 8), {})
|
||||||
|
if upload.get('name') != 'POST /api/v1/chats/{chat_id}/attachments':
|
||||||
|
return None
|
||||||
|
names = {span['name'] for span in spans}
|
||||||
|
if not workers or not {'s3.read_staging', 's3.write_result', 'postgres.commit_ready'} <= names:
|
||||||
|
return None
|
||||||
|
if retry:
|
||||||
|
outcomes = set()
|
||||||
|
for span in workers:
|
||||||
|
attrs = {row['key']: row['value'] for row in span.get('attributes', [])}
|
||||||
|
outcomes.add((int(attrs['job.attempt']['intValue']), attrs.get('outcome', {}).get('stringValue')))
|
||||||
|
if not {(1, 'error'), (2, 'error')} <= outcomes or not any(n > 2 and outcome == 'success' for n, outcome in outcomes):
|
||||||
|
return None
|
||||||
|
return [{'name': span['name'], 'kind': span.get('kind'),
|
||||||
|
'span_id': identifier_hex(span['spanId'], 8),
|
||||||
|
'parent_span_id': identifier_hex(span.get('parentSpanId', ''), 8),
|
||||||
|
'job': {entry['key']: entry['value'] for entry in span.get('attributes', [])
|
||||||
|
if entry['key'] in {'job.attempt', 'outcome'}}} for span in spans]
|
||||||
|
return eventually(inspect, 'Missing upload -> producer -> consumer -> S3/DB chain')
|
||||||
|
|
||||||
|
|
||||||
|
def telemetry_outage(project, client, grafana, actor, chat):
|
||||||
|
failed = 'sum({__name__=~"otelcol_exporter_send_failed_log_records(_total)?",exporter="otlphttp/loki"}) or vector(0)'
|
||||||
|
refused = 'sum({__name__=~"otelcol_exporter_enqueue_failed_log_records(_total)?",exporter="otlphttp/loki"}) or vector(0)'
|
||||||
|
baseline = [metric(grafana, expr) for expr in (failed, refused)]
|
||||||
|
rss = 'sum({__name__=~"otelcol_process_memory_rss(_bytes)?"})'
|
||||||
|
samples = []
|
||||||
|
successful = 0
|
||||||
|
try:
|
||||||
|
project.run('stop', 'loki')
|
||||||
|
start = time.monotonic()
|
||||||
|
for second in range(51):
|
||||||
|
for index in range(4):
|
||||||
|
client.message(actor, chat, f'outage-{second}-{index}')
|
||||||
|
successful += 1
|
||||||
|
if second % 5 == 0:
|
||||||
|
samples.append({
|
||||||
|
'seconds': round(time.monotonic() - start, 2),
|
||||||
|
'rss_bytes': metric(grafana, rss),
|
||||||
|
'queued_batches': metric(grafana, 'sum(otelcol_exporter_queue_size{exporter="otlphttp/loki"})'),
|
||||||
|
'capacity_batches': metric(grafana, 'sum(otelcol_exporter_queue_capacity{exporter="otlphttp/loki"})'),
|
||||||
|
})
|
||||||
|
time.sleep(max(0, start + second + 1 - time.monotonic()))
|
||||||
|
losses = [metric(grafana, expr) - count for expr, count in zip((failed, refused), baseline)]
|
||||||
|
check(sum(losses) > 0, 'No measured Collector log loss during prolonged outage')
|
||||||
|
check(all(0 <= row['queued_batches'] <= row['capacity_batches'] == 256 for row in samples), 'Unexpected queue bound')
|
||||||
|
check(max(row['rss_bytes'] for row in samples) < 256 * 1024**2, 'Collector crossed container memory limit')
|
||||||
|
finally:
|
||||||
|
project.run('start', 'loki')
|
||||||
|
eventually(lambda: grafana.proxy('loki', '/loki/api/v1/labels').get('status') == 'success',
|
||||||
|
'Loki did not recover')
|
||||||
|
restored = client.message(actor, chat, 'telemetry-backend-restored')
|
||||||
|
correlation(grafana, 'messenger-api', time.time_ns() - 30 * 10**9,
|
||||||
|
trace_id=restored['headers']['X-Trace-Id'])
|
||||||
|
return {'scenario':'loki_unavailable', 'successful_messages': successful,
|
||||||
|
'dropped_after_export_failure': losses[0], 'dropped_at_enqueue': losses[1],
|
||||||
|
'samples': samples, 'log_export_recovered': True}
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
parser.add_argument('--base-url', required=True)
|
parser.add_argument('--base-url', required=True)
|
||||||
@@ -201,6 +279,7 @@ def main():
|
|||||||
client.wait_ready(actor, attachment)
|
client.wait_ready(actor, attachment)
|
||||||
api, api_trace = correlation(grafana, 'messenger-api', start, trace_id=controlled_trace, request_id=response['headers']['X-Request-Id'])
|
api, api_trace = correlation(grafana, 'messenger-api', start, trace_id=controlled_trace, request_id=response['headers']['X-Request-Id'])
|
||||||
worker, worker_trace = correlation(grafana, 'messenger-worker', start, attachment_id=attachment['id'])
|
worker, worker_trace = correlation(grafana, 'messenger-worker', start, attachment_id=attachment['id'])
|
||||||
|
accepted_chain = trace_chain(grafana, worker['trace_id'])
|
||||||
check(api['log']['request_id'] == response['headers']['X-Request-Id'], 'Request id correlation lost')
|
check(api['log']['request_id'] == response['headers']['X-Request-Id'], 'Request id correlation lost')
|
||||||
check(any(span['kind'] in ('SPAN_KIND_SERVER', 2) for span in api['spans']), 'No server span')
|
check(any(span['kind'] in ('SPAN_KIND_SERVER', 2) for span in api['spans']), 'No server span')
|
||||||
check(any(span['kind'] in ('SPAN_KIND_CONSUMER', 5) for span in worker['spans']), 'No consumer span')
|
check(any(span['kind'] in ('SPAN_KIND_CONSUMER', 5) for span in worker['spans']), 'No consumer span')
|
||||||
@@ -225,42 +304,67 @@ def main():
|
|||||||
check(not any(forbidden_labels & set(row['metric']) for row in series), 'High cardinality metric label')
|
check(not any(forbidden_labels & set(row['metric']) for row in series), 'High cardinality metric label')
|
||||||
report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'project': project.name,
|
report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'project': project.name,
|
||||||
'load': load, 'api_replicas': len(aliases), 'dashboard_uid': dashboard['uid'],
|
'load': load, 'api_replicas': len(aliases), 'dashboard_uid': dashboard['uid'],
|
||||||
'api_correlation': api, 'worker_correlation': worker, 'metrics': metrics, 'incidents': []}
|
'api_correlation': api, 'worker_correlation': worker, 'metrics': metrics, 'upload_trace': {'trace_id':worker['trace_id'], 'chain':accepted_chain}, 'incidents': []}
|
||||||
if args.incidents:
|
if args.incidents:
|
||||||
# Восстановление выполняется даже при ошибке проверки.
|
def fail_request():
|
||||||
|
return client.call('POST', '/api/v1/users', expected=503,
|
||||||
|
body={'username':'fault_' + uuid4().hex[:12],
|
||||||
|
'display_name':'Synthetic', 'password':'not-exported-' + uuid4().hex})
|
||||||
|
|
||||||
|
before = time.monotonic()
|
||||||
try:
|
try:
|
||||||
before = time.monotonic()
|
|
||||||
project.run('stop', 'postgres')
|
project.run('stop', 'postgres')
|
||||||
failed = client.call('POST', '/api/v1/users', expected=503,
|
failed = fail_request()
|
||||||
body={'username':'fault_' + uuid4().hex[:12], 'display_name':'Synthetic', 'password':'not-exported-' + uuid4().hex})
|
|
||||||
error_trace = failed['headers'].get('X-Trace-Id')
|
error_trace = failed['headers'].get('X-Trace-Id')
|
||||||
error, _ = correlation(grafana, 'messenger-api', start, trace_id=error_trace, request_id=failed['headers']['X-Request-Id'])
|
error, db_trace = correlation(grafana, 'messenger-api', start, trace_id=error_trace,
|
||||||
diagnostics = eventually(lambda: grafana.logs('{service_name="messenger-api"} | json | event="dependency.unavailable" | trace_id="' + error_trace + '"', start), 'No dependency diagnostic log')
|
request_id=failed['headers']['X-Request-Id'])
|
||||||
check(error['log'].get('status_code') == 503 or any(s['status'].get('code') in ('STATUS_CODE_ERROR', 2) for s in error['spans']), 'DB failure not reflected in trace')
|
diagnostics = eventually(lambda: grafana.logs(
|
||||||
report['incidents'].append({'scenario':'postgres_unavailable','http_status':503,'correlation':error,'diagnostic':diagnostics[0], 'observed_after_seconds':round(time.monotonic()-before,3)})
|
'{service_name="messenger-api"} | json | event="dependency.unavailable" | trace_id="' + error_trace + '"', start),
|
||||||
|
'No dependency diagnostic log')
|
||||||
|
checkout = next(span for span in spans_in(db_trace) if span['name'] == 'postgres.checkout'
|
||||||
|
and span.get('status', {}).get('code') in ('STATUS_CODE_ERROR', 2))
|
||||||
|
|
||||||
|
def db_alert():
|
||||||
|
for _ in range(4):
|
||||||
|
fail_request()
|
||||||
|
return alert_firing(grafana, 'MessengerHighErrorRate')
|
||||||
|
|
||||||
|
eventually(db_alert, 'Error rate alert did not fire', timeout=75)
|
||||||
|
report['incidents'].append({'scenario':'postgres_unavailable','http_status':503,'correlation':error,
|
||||||
|
'diagnostic':diagnostics[0], 'db_span':checkout['name'],
|
||||||
|
'alert':'MessengerHighErrorRate', 'firing_after_seconds':round(time.monotonic()-before,3)})
|
||||||
finally:
|
finally:
|
||||||
project.run('start', 'postgres')
|
project.run('start', 'postgres')
|
||||||
eventually(lambda: _ready(client), 'API did not recover after PostgreSQL')
|
eventually(lambda: _ready(client), 'API did not recover after PostgreSQL')
|
||||||
report['incidents'][-1]['recovery_seconds'] = round(time.monotonic() - before, 3)
|
eventually(lambda: not alert_firing(grafana, 'MessengerHighErrorRate'), 'Error rate alert not resolved')
|
||||||
# Явный fault hook обработки заданий: один permanent processing failure, затем replay.
|
report['incidents'][-1]['resolved_after_seconds'] = round(time.monotonic() - before, 3)
|
||||||
|
|
||||||
from scripts.check_jobs import retry_replay
|
from scripts.check_jobs import retry_replay
|
||||||
failed_instance = []
|
queue = {}
|
||||||
def wait_failed_metric(sample, container_name):
|
|
||||||
instance = project.docker('inspect', '--format', '{{.Config.Hostname}}', container_name)
|
def observe_queue(_):
|
||||||
failed_instance.append(instance)
|
observed = time.monotonic()
|
||||||
expression = 'sum(messenger_job_attempts_total{outcome="error",service_instance_id="' + instance + '"})'
|
eventually(lambda: alert_firing(grafana, 'MessengerQueueLag'), 'Queue lag alert did not fire')
|
||||||
eventually(lambda: grafana.query(expression), 'Failed job metric not exported before recovery')
|
queue.update(depth=metric(grafana, 'max(messenger_queue_depth_ratio)'),
|
||||||
incident = retry_replay(client, actor, chat, permanent=True, on_failed=wait_failed_metric)
|
oldest_seconds=metric(grafana, 'max(messenger_queue_oldest_seconds)'),
|
||||||
error_logs = eventually(lambda: grafana.logs('{service_name="messenger-worker"} | json | event="job.processed" | outcome="error" | error_code="injected_permanent"', start), 'No failed job telemetry')
|
firing_after_seconds=round(time.monotonic()-observed,3))
|
||||||
error_trace = eventually(lambda: grafana.trace(error_logs[-1]['trace_id']), 'No failed job trace')
|
|
||||||
check(any(span.get('status', {}).get('code') in ('STATUS_CODE_ERROR', 2) for span in spans_in(error_trace)), 'Worker error trace status lost')
|
incident = retry_replay(client, actor, chat, permanent=False, on_queued=observe_queue)
|
||||||
expression = 'sum(messenger_job_attempts_total{outcome="error",service_instance_id="' + failed_instance[0] + '"})'
|
retried_worker, retry_trace = correlation(grafana, 'messenger-worker', start,
|
||||||
errors = eventually(lambda: grafana.query(expression), 'No failed jobs counter')
|
attachment_id=incident['attachment_id'])
|
||||||
recovery = (datetime.fromisoformat(incident['after']['updated_at']) - datetime.fromisoformat(incident['samples'][-1]['updated_at'])).total_seconds()
|
chain = trace_chain(grafana, retried_worker['trace_id'], retry=True)
|
||||||
report['incidents'].append({'scenario':'permanent_processing_failure','recovered_status':incident['after']['status'], 'log':error_logs[-1], 'failed_jobs_metric':errors, 'metric_query':expression, 'failure_to_ready_seconds':round(recovery,3)})
|
eventually(lambda: not alert_firing(grafana, 'MessengerQueueLag')
|
||||||
|
and metric(grafana, 'max(messenger_queue_depth_ratio)') == 0, 'Backlog did not drain')
|
||||||
|
queue.update(resolved=True, final_depth=0)
|
||||||
|
report['incidents'].append({'scenario':'worker_stopped_then_transient_retry',
|
||||||
|
'alert':'MessengerQueueLag', 'queue':queue, 'recovered_status':incident['after']['status'],
|
||||||
|
'trace_id':retried_worker['trace_id'], 'chain':chain})
|
||||||
|
report['incidents'].append(telemetry_outage(project, client, grafana, actor, chat))
|
||||||
|
else:
|
||||||
|
retry_trace = {}
|
||||||
# Не сохраняем API bodies или SDK exceptions; проверяем реальные выбранные сигналы.
|
# Не сохраняем API bodies или SDK exceptions; проверяем реальные выбранные сигналы.
|
||||||
logs = grafana.logs('{service_name=~"messenger-api|messenger-worker"}', start)
|
logs = grafana.logs('{service_name=~"messenger-api|messenger-worker"}', start)
|
||||||
exported = json.dumps([logs, api_trace, worker_trace])
|
exported = json.dumps([logs, api_trace, worker_trace, retry_trace])
|
||||||
private = [sentinel, *(person['token'] for person in (actor,bob,eve)), *(person['registration']['password'] for person in (actor,bob,eve))]
|
private = [sentinel, *(person['token'] for person in (actor,bob,eve)), *(person['registration']['password'] for person in (actor,bob,eve))]
|
||||||
private.extend(path.read_text().strip() for path in (ROOT / 'secrets').iterdir() if path.is_file())
|
private.extend(path.read_text().strip() for path in (ROOT / 'secrets').iterdir() if path.is_file())
|
||||||
check(not any(secret and secret in exported for secret in private), 'Private value found in telemetry')
|
check(not any(secret and secret in exported for secret in private), 'Private value found in telemetry')
|
||||||
@@ -280,7 +384,7 @@ def main():
|
|||||||
destination = ROOT / args.output
|
destination = ROOT / args.output
|
||||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||||
destination.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
destination.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||||
print('PASS: telemetry, dashboard, privacy, correlations' + ('; two incidents recovered' if args.incidents else ''))
|
print('PASS: telemetry, dashboard, privacy, correlations' + ('; alerts and outage recovery verified' if args.incidents else ''))
|
||||||
|
|
||||||
|
|
||||||
def _ready(client):
|
def _ready(client):
|
||||||
|
|||||||
+14
-5
@@ -137,20 +137,23 @@ def verify():
|
|||||||
import time
|
import time
|
||||||
|
|
||||||
project_name = os.getenv('TEST_PROJECT', 'messenger-test')
|
project_name = os.getenv('TEST_PROJECT', 'messenger-test')
|
||||||
|
if any(inventory([project_name]).values()):
|
||||||
|
raise RuntimeError(f'Choose an unused TEST_PROJECT; {project_name} already has resources')
|
||||||
os.environ.update(COMPOSE_PROJECT_NAME=project_name,
|
os.environ.update(COMPOSE_PROJECT_NAME=project_name,
|
||||||
COMPOSE_FILE='compose.yaml:compose.test.yaml',
|
COMPOSE_FILE='compose.yaml:compose.test.yaml',
|
||||||
GRAFANA_HOST_PORT='23000', LB_HOST_PORT='28080',
|
GRAFANA_HOST_PORT='23000', LB_HOST_PORT='28080',
|
||||||
DOCKER_TESTS='1')
|
DOCKER_TESTS='1', OTEL_ENABLED='true')
|
||||||
report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'checks': [],
|
report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'checks': [],
|
||||||
'profile': {'single_stack': True, 'load_duration_seconds': 10,
|
'profile': {'single_stack': True, 'load_duration_seconds': 10,
|
||||||
'load_requests_per_second': 10, 'load_concurrency': 2}}
|
'load_requests_per_second': 10, 'load_concurrency': 2}}
|
||||||
destination = ROOT / 'evidence/verification.json'
|
destination = ROOT / 'evidence/verification.json'
|
||||||
destination.parent.mkdir(exist_ok=True)
|
destination.parent.mkdir(exist_ok=True)
|
||||||
|
|
||||||
def run(name, command, timeout=600):
|
def run(name, command, timeout=600, *, env=None):
|
||||||
print('RUN: ' + name, flush=True)
|
print('RUN: ' + name, flush=True)
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
result = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=timeout)
|
result = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=timeout,
|
||||||
|
env={**os.environ, **(env or {})})
|
||||||
executable = Path(command[0])
|
executable = Path(command[0])
|
||||||
display_command = [str(executable.relative_to(ROOT)) if executable.is_relative_to(ROOT)
|
display_command = [str(executable.relative_to(ROOT)) if executable.is_relative_to(ROOT)
|
||||||
else command[0], *command[1:]]
|
else command[0], *command[1:]]
|
||||||
@@ -175,7 +178,9 @@ def verify():
|
|||||||
run('openapi', [sys.executable, 'scripts/validate_openapi.py'])
|
run('openapi', [sys.executable, 'scripts/validate_openapi.py'])
|
||||||
run('compose', ['docker', 'compose', '--env-file', '.env', 'config', '--quiet'])
|
run('compose', ['docker', 'compose', '--env-file', '.env', 'config', '--quiet'])
|
||||||
run('startup', ['make', '--no-print-directory', 'test-stand-up'], timeout=600)
|
run('startup', ['make', '--no-print-directory', 'test-stand-up'], timeout=600)
|
||||||
run('regression', ['make', '--no-print-directory', 'test-unit'])
|
# Локальные ASGI fixtures не находятся в сети Compose. Проверки SDK
|
||||||
|
# используют exporters в памяти, интеграционный стенд экспортирует OTLP.
|
||||||
|
run('regression', ['make', '--no-print-directory', 'test-unit'], env={'OTEL_ENABLED': 'false'})
|
||||||
run('api', [sys.executable, 'tests/smoke.py', '--base-url', 'http://localhost:28080'])
|
run('api', [sys.executable, 'tests/smoke.py', '--base-url', 'http://localhost:28080'])
|
||||||
run('observability', [sys.executable, '-m', 'scripts.check_observability',
|
run('observability', [sys.executable, '-m', 'scripts.check_observability',
|
||||||
'--base-url', 'http://localhost:28080',
|
'--base-url', 'http://localhost:28080',
|
||||||
@@ -192,7 +197,11 @@ def verify():
|
|||||||
finally:
|
finally:
|
||||||
try:
|
try:
|
||||||
print('RUN: cleanup', flush=True)
|
print('RUN: cleanup', flush=True)
|
||||||
report['cleanup'] = clean_stands(apply=True)
|
ComposeProject().run('down', '--volumes', '--remove-orphans', timeout=120)
|
||||||
|
remaining = inventory([project_name])
|
||||||
|
if any(remaining.values()):
|
||||||
|
raise RuntimeError('Verification project cleanup incomplete')
|
||||||
|
report['cleanup'] = {'project': project_name, 'remaining': remaining, 'result': 'PASS'}
|
||||||
print('PASS: cleanup', flush=True)
|
print('PASS: cleanup', flush=True)
|
||||||
finally:
|
finally:
|
||||||
report['finished_at_utc'] = datetime.now(timezone.utc).isoformat()
|
report['finished_at_utc'] = datetime.now(timezone.utc).isoformat()
|
||||||
|
|||||||
Reference in New Issue
Block a user