forked from mtusi2026/mtusi2026lab6
4 grade_and_report
This commit is contained in:
@@ -1,37 +1,53 @@
|
||||
# Отчёт — лабораторная 6
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- **Автор, группа:** Бахаева Лиана, БПИ2302
|
||||
- **Целевая оценка:** 4
|
||||
- **Commit/PR:** (укажи ссылку на свой PR после пуша)
|
||||
- **Использованные источники:** OpenTelemetry Docs, Grafana Provisioning Docs, Prometheus Histograms.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
1. **Prerequisites:** Docker Desktop (Compose v2), Python 3.9+ (для тестов).
|
||||
2. **Создание `.env`:** Скопировать `.env.example` в `.env` и заполнить локальные переменные (секреты не коммитятся).
|
||||
3. **Запуск:**
|
||||
```sh
|
||||
docker compose --env-file .env up -d --build
|
||||
```
|
||||
4. **Ожидание готовности:** Дождаться статуса `healthy` у `postgres` и `minio`, и `{"status":"ok"}` на `curl http://localhost:8080/health/ready`.
|
||||
5. **Тесты:** `make test` (или `python tests/smoke.py`).
|
||||
6. **Остановка:** `docker compose down`.
|
||||
7. **Удаление данных:** `docker compose down -v` (удаляет volumes с БД, S3, метриками).
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab5, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
- **Схема:** Клиент → Nginx (LB) → API-реплики (api1, api2) → OTel Collector → (Prometheus, Loki, Tempo) → Grafana. Worker получает задачи через RabbitMQ (Transactional Outbox), обрабатывает и пишет в S3/БД.
|
||||
- **Источник истины:** PostgreSQL (пользователи, чаты, сообщения, вложения).
|
||||
- **Транзакционные границы:** Сохранение вложения в S3 и запись в БД в одной транзакции (с компенсацией S3 при ошибке БД). Outbox-паттерн для отправки в RabbitMQ.
|
||||
- **Что перенесено из lab5:** Весь бизнес-код (FastAPI, psycopg, boto3, Pillow, aio-pika), миграции, Nginx-конфиг.
|
||||
- **Что изменено:** Добавлен OTel SDK (трейсы, метрики, логи), OTel Collector, Prometheus, Loki, Tempo, Grafana, provisioning в Git, W3C trace context между API и Worker.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Публичный smoke | `make test` | `PASS: lab6 public API scenario` | Лог консоли |
|
||||
| Уровень 3: Метрики API | Открыть дашборд Lab6 API | RPS, Error Rate, Duration (p50/p95/p99) | `evidence/api_dashboard.png` |
|
||||
| Уровень 3: Логи | Loki: `{application="messenger-api"}` | JSON-логи с `trace_id` | `evidence/loki_logs.png` |
|
||||
| Уровень 3: Трейсы | Tempo: поиск по `service.name="messenger-api"` | Дерево спанов | `evidence/tempo_trace.png` |
|
||||
| Уровень 4: W3C trace context | Tempo: поиск по `trace_id` из воркера | Спаны `worker.process_attachment` и `outbox.publish` в одном трейсе | `evidence/w3c_trace.png` |
|
||||
| Уровень 4: Дашборды p50/p95/p99 | Открыть дашборды Lab6 API и Lab6 Worker | Видны p99, Saturation (worker_in_flight) | `evidence/worker_dashboard.png` |
|
||||
| Уровень 4: Отказоустойчивость | Остановить Tempo/Loki, сделать запрос к API | API отвечает `{"status":"ok"}`, память OTel Collector не растет (40 MiB) | `evidence/resilience.png` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Остановка API (`docker compose stop api1 api2`) | Nginx вернет 502/503, RPS упадет до 0, алерт `HighErrorRate` сработает | API недоступен, метрики показывают 0, Nginx отдает 502 | Восстановление после `start` — 5 сек. Потерь данных нет. |
|
||||
| Остановка Tempo/Loki (`docker compose stop tempo loki`) | API продолжает работать, OTel Collector буферизует данные, память не растет | API вернул `{"status":"ok"}`, память коллектора 40 MiB | Восстановление после `start` — 10 сек. Логи/трейсы за время простоя потеряны (ограниченная буферизация), но бизнес-данные сохранены. |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- **Учебное упрощение:** Вместо полноценного SLO с burn-rate используются статические пороги (5% ошибок, 500 мс).
|
||||
- **Алерты:** Alert Rules настроены в Git (`alerts.yml`, `alerts.yaml`), в среде Linux они успешно переходят в статус Firing при искусственных отказах.
|
||||
- **Улучшение:** В будущем можно добавить OpenTelemetry Collector с балансировкой нагрузки (loadbalancing exporter) для масштабирования.
|
||||
|
||||
|
||||
@@ -1,87 +1,40 @@
|
||||
{
|
||||
"annotations": {"list": []},
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 0,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps"}},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 0},
|
||||
"id": 1,
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(http_requests_total[1m])) by (handler)",
|
||||
"legendFormat": "{{handler}}",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"targets": [{"expr": "sum(rate(http_requests_total[1m])) by (handler)", "legendFormat": "{{handler}}"}],
|
||||
"title": "API RPS",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit"}},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 0},
|
||||
"id": 2,
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(http_requests_total{status=~\"5..\"}[1m])) / sum(rate(http_requests_total[1m]))",
|
||||
"legendFormat": "5xx ratio",
|
||||
"refId": "A"
|
||||
}
|
||||
],
|
||||
"targets": [{"expr": "sum(rate(http_requests_total{status=~\"5..\"}[1m])) / sum(rate(http_requests_total[1m]))", "legendFormat": "5xx ratio"}],
|
||||
"title": "API Error Rate (5xx)",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 8},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 0},
|
||||
"id": 3,
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, handler))",
|
||||
"legendFormat": "p95 {{handler}}",
|
||||
"refId": "A"
|
||||
},
|
||||
{
|
||||
"expr": "histogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, handler))",
|
||||
"legendFormat": "p50 {{handler}}",
|
||||
"refId": "B"
|
||||
}
|
||||
{"expr": "histogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p50"},
|
||||
{"expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p95"},
|
||||
{"expr": "histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p99"}
|
||||
],
|
||||
"title": "API Duration p50/p95",
|
||||
"title": "API Duration (p50/p95/p99)",
|
||||
"type": "timeseries"
|
||||
}
|
||||
],
|
||||
"schemaVersion": 39,
|
||||
"tags": ["lab6"],
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"current": {},
|
||||
"hide": 0,
|
||||
"includeAll": false,
|
||||
"label": "Prometheus",
|
||||
"multi": false,
|
||||
"name": "DS_PROMETHEUS",
|
||||
"options": [],
|
||||
"query": "prometheus",
|
||||
"refresh": 1,
|
||||
"regex": "",
|
||||
"skipUrlSync": false,
|
||||
"type": "datasource"
|
||||
}
|
||||
]
|
||||
},
|
||||
"time": {"from": "now-15m", "to": "now"},
|
||||
"title": "Lab6 API",
|
||||
"uid": "lab6-api",
|
||||
"version": 1
|
||||
"uid": "lab6-api"
|
||||
}
|
||||
@@ -1,66 +1,52 @@
|
||||
{
|
||||
"annotations": {"list": []},
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 0,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"},
|
||||
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"fieldConfig": {"defaults": {"unit": "short"}},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
|
||||
"id": 1,
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "sum(rate(worker_processed_total[1m])) by (result)",
|
||||
"legendFormat": "{{result}}",
|
||||
"refId": "A"
|
||||
}
|
||||
{"expr": "sum(rate(worker_processed_total{result=\"success\"}[1m]))", "legendFormat": "Success"},
|
||||
{"expr": "sum(rate(worker_processed_total{result=\"error\"}[1m]))", "legendFormat": "Error"}
|
||||
],
|
||||
"title": "Worker Jobs (success/fail)",
|
||||
"title": "Worker Jobs (Success/Error)",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
|
||||
"id": 2,
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}},
|
||||
"targets": [
|
||||
{
|
||||
"expr": "histogram_quantile(0.95, sum(rate(worker_duration_seconds_bucket[5m])) by (le))",
|
||||
"legendFormat": "p95 duration",
|
||||
"refId": "A"
|
||||
}
|
||||
{"expr": "histogram_quantile(0.50, sum(rate(worker_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p50"},
|
||||
{"expr": "histogram_quantile(0.95, sum(rate(worker_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p95"},
|
||||
{"expr": "histogram_quantile(0.99, sum(rate(worker_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p99"}
|
||||
],
|
||||
"title": "Worker Duration p95",
|
||||
"title": "Worker Duration (p50/p95/p99)",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"fieldConfig": {"defaults": {"unit": "short"}},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
|
||||
"id": 3,
|
||||
"targets": [{"expr": "sum(worker_in_flight)", "legendFormat": "In Flight"}],
|
||||
"title": "Worker Saturation (In Flight Jobs)",
|
||||
"type": "timeseries"
|
||||
},
|
||||
{
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"fieldConfig": {"defaults": {"unit": "short"}},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
|
||||
"id": 4,
|
||||
"targets": [{"expr": "sum(rabbitmq_queue_depth)", "legendFormat": "Queue Depth"}],
|
||||
"title": "Queue Depth",
|
||||
"type": "timeseries"
|
||||
}
|
||||
],
|
||||
"schemaVersion": 39,
|
||||
"tags": ["lab6"],
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"current": {},
|
||||
"hide": 0,
|
||||
"includeAll": false,
|
||||
"label": "Prometheus",
|
||||
"multi": false,
|
||||
"name": "DS_PROMETHEUS",
|
||||
"options": [],
|
||||
"query": "prometheus",
|
||||
"refresh": 1,
|
||||
"regex": "",
|
||||
"skipUrlSync": false,
|
||||
"type": "datasource"
|
||||
}
|
||||
]
|
||||
},
|
||||
"time": {"from": "now-15m", "to": "now"},
|
||||
"title": "Lab6 Worker",
|
||||
"uid": "lab6-worker",
|
||||
"version": 1
|
||||
"uid": "lab6-worker"
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
apiVersion: 1
|
||||
|
||||
groups:
|
||||
- orgId: 1
|
||||
name: "worker_alerts"
|
||||
folder: "Lab6 Alerts"
|
||||
interval: 1m
|
||||
rules:
|
||||
- uid: worker-errors
|
||||
title: "Worker Errors Detected"
|
||||
condition: C
|
||||
data:
|
||||
# A: Запрос в Prometheus
|
||||
- refId: A
|
||||
datasourceUid: "prometheus"
|
||||
model:
|
||||
expr: 'worker_processed_total{result="error"}'
|
||||
instant: true
|
||||
# B: Берем последнее значение (Reduce)
|
||||
- refId: B
|
||||
datasourceUid: "__expr__"
|
||||
model:
|
||||
expression: "A"
|
||||
reducer: "last"
|
||||
# C: Порог (Threshold) — если больше 0, то Firing
|
||||
- refId: C
|
||||
datasourceUid: "__expr__"
|
||||
model:
|
||||
expression: "B"
|
||||
type: "threshold"
|
||||
conditions:
|
||||
- evaluator:
|
||||
type: "gt"
|
||||
params: [0]
|
||||
noDataState: "NoData"
|
||||
execErrState: "Error"
|
||||
for: "0m"
|
||||
labels:
|
||||
severity: "critical"
|
||||
annotations:
|
||||
summary: "Worker has encountered errors!"
|
||||
@@ -6,6 +6,7 @@ datasources:
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
uid: prometheus
|
||||
editable: false
|
||||
|
||||
- name: Loki
|
||||
|
||||
@@ -17,13 +17,6 @@ processors:
|
||||
resourcedetection:
|
||||
detectors: [env, system]
|
||||
timeout: 2s
|
||||
# ГЛАВНОЕ: Добавляем хинт для Loki через атрибуты
|
||||
attributes:
|
||||
actions:
|
||||
# Говорим Loki: "эй, возьми ресурсный атрибут service.name и сделай из него метку"
|
||||
- key: loki.resource.labels
|
||||
value: service.name
|
||||
action: insert
|
||||
|
||||
exporters:
|
||||
prometheus:
|
||||
@@ -34,7 +27,6 @@ exporters:
|
||||
endpoint: http://loki:3100/loki/api/v1/push
|
||||
tls:
|
||||
insecure: true
|
||||
# Убираем labels, так как их больше нет в 0.95.0
|
||||
otlp/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
@@ -57,5 +49,5 @@ service:
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch, resourcedetection, attributes]
|
||||
processors: [memory_limiter, batch, resourcedetection]
|
||||
exporters: [loki]
|
||||
@@ -0,0 +1,20 @@
|
||||
groups:
|
||||
- name: lab6_alerts
|
||||
rules:
|
||||
# Правило 1: Высокий процент ошибок 5xx на API
|
||||
- alert: HighErrorRate
|
||||
expr: sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) > 0.05
|
||||
for: 2m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "High 5xx error rate detected"
|
||||
|
||||
# Правило 2: Ошибки в воркере
|
||||
- alert: WorkerErrors
|
||||
expr: worker_processed_total{result="error"} > 0
|
||||
for: 0m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Worker errors detected"
|
||||
@@ -2,16 +2,23 @@ global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
|
||||
|
||||
rule_files:
|
||||
- "alerts.yml"
|
||||
|
||||
scrape_configs:
|
||||
|
||||
- job_name: "prometheus"
|
||||
static_configs:
|
||||
- targets: ["localhost:9090"]
|
||||
|
||||
|
||||
- job_name: "otel-collector"
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8889"]
|
||||
|
||||
|
||||
- job_name: "api"
|
||||
metrics_path: /metrics
|
||||
static_configs:
|
||||
- targets: ["api1:8080", "api2:8080"]
|
||||
|
||||
- job_name: "prometheus"
|
||||
static_configs:
|
||||
- targets: ["localhost:9090"]
|
||||
- targets: ["api1:8080", "api2:8080"]
|
||||
+86
-43
@@ -4,17 +4,27 @@ import json
|
||||
import logging
|
||||
import hashlib
|
||||
import random
|
||||
import time
|
||||
|
||||
import aio_pika
|
||||
from PIL import Image
|
||||
from psycopg.rows import dict_row
|
||||
from opentelemetry import trace
|
||||
from opentelemetry import trace, context as otel_context
|
||||
from opentelemetry.propagate import extract
|
||||
|
||||
# Импорты для метрик
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry import metrics as otel_metrics
|
||||
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import init_pool, transaction
|
||||
from src.app.s3 import download_fileobj, upload_fileobj
|
||||
from src.app.otel import setup_otel
|
||||
from src.app.logging_config import setup_logging
|
||||
from worker.metrics import worker_duration, worker_processed, worker_in_flight
|
||||
|
||||
from worker.outbox_publisher import publish_loop
|
||||
|
||||
@@ -58,27 +68,31 @@ def generate_variants(img: Image.Image):
|
||||
return variants
|
||||
|
||||
|
||||
async def _re_publish(body: bytes):
|
||||
async def _re_publish(body: bytes, headers: dict):
|
||||
settings = get_settings()
|
||||
connection = await aio_pika.connect_robust(settings.broker_url)
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
await channel.declare_queue(settings.broker_queue, durable=True)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT, headers=headers)
|
||||
await channel.default_exchange.publish(msg, routing_key=settings.broker_queue)
|
||||
|
||||
|
||||
async def _send_to_dlq(body: bytes):
|
||||
async def _send_to_dlq(body: bytes, headers: dict):
|
||||
settings = get_settings()
|
||||
connection = await aio_pika.connect_robust(settings.broker_url)
|
||||
async with connection:
|
||||
channel = await connection.channel()
|
||||
await channel.declare_queue("dead_letters", durable=True)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT)
|
||||
msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT, headers=headers)
|
||||
await channel.default_exchange.publish(msg, routing_key="dead_letters")
|
||||
|
||||
|
||||
async def process_message(message: aio_pika.IncomingMessage):
|
||||
headers = message.headers or {}
|
||||
ctx = extract(headers)
|
||||
token = otel_context.attach(ctx)
|
||||
|
||||
async with message.process(requeue=False, reject_on_redelivered=False):
|
||||
data = json.loads(message.body)
|
||||
att_id = data["attachment_id"]
|
||||
@@ -86,41 +100,51 @@ async def process_message(message: aio_pika.IncomingMessage):
|
||||
|
||||
with tracer.start_as_current_span("worker.process_attachment") as span:
|
||||
span.set_attribute("attachment.id", att_id)
|
||||
worker_in_flight.add(1)
|
||||
start_time = time.time()
|
||||
result = "error"
|
||||
attempts = 0
|
||||
|
||||
logger.info("Processing attachment %s", att_id)
|
||||
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"SELECT attempts FROM attachment_retries WHERE attachment_id = %s",
|
||||
(att_id,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
attempts = row["attempts"] if row else 0
|
||||
|
||||
if attempts >= 5:
|
||||
logger.error("Max retries (5) reached for %s. Sending to DLQ.", att_id)
|
||||
try:
|
||||
with transaction() as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s",
|
||||
"SELECT attempts FROM attachment_retries WHERE attachment_id = %s",
|
||||
(att_id,),
|
||||
)
|
||||
await _send_to_dlq(message.body)
|
||||
span.set_attribute("worker.result", "max_retries")
|
||||
return
|
||||
row = cur.fetchone()
|
||||
attempts = row["attempts"] if row else 0
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachment_retries (attachment_id, attempts)
|
||||
VALUES (%s, 1)
|
||||
ON CONFLICT (attachment_id) DO UPDATE SET attempts = attachment_retries.attempts + 1
|
||||
""",
|
||||
(att_id,),
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s",
|
||||
(att_id,),
|
||||
)
|
||||
if attempts >= 5:
|
||||
logger.error("Max retries (5) reached for %s. Sending to DLQ.", att_id)
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s",
|
||||
(att_id,),
|
||||
)
|
||||
await _send_to_dlq(message.body, headers)
|
||||
span.set_attribute("worker.result", "max_retries")
|
||||
result = "error_max_retries"
|
||||
worker_duration.record(time.time() - start_time)
|
||||
worker_processed.add(1, {"result": result})
|
||||
worker_in_flight.add(-1)
|
||||
otel_context.detach(token)
|
||||
return
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO attachment_retries (attachment_id, attempts)
|
||||
VALUES (%s, 1)
|
||||
ON CONFLICT (attachment_id) DO UPDATE SET attempts = attachment_retries.attempts + 1
|
||||
""",
|
||||
(att_id,),
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s",
|
||||
(att_id,),
|
||||
)
|
||||
|
||||
try:
|
||||
body = download_fileobj(obj_key)
|
||||
img = Image.open(body)
|
||||
|
||||
@@ -162,6 +186,7 @@ async def process_message(message: aio_pika.IncomingMessage):
|
||||
|
||||
span.set_attribute("worker.result", "ready")
|
||||
logger.info("Successfully processed %s", att_id)
|
||||
result = "success"
|
||||
|
||||
except PermanentError as e:
|
||||
logger.error("Permanent error for %s: %s", att_id, e)
|
||||
@@ -172,24 +197,42 @@ async def process_message(message: aio_pika.IncomingMessage):
|
||||
("invalid_image", att_id),
|
||||
)
|
||||
span.set_attribute("worker.result", "permanent_error")
|
||||
result = "error_permanent"
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Temporary error for %s: %s", att_id, e)
|
||||
span.set_attribute("worker.result", "retry")
|
||||
delay = min(2 ** attempts, 60)
|
||||
jitter = random.uniform(0, 3)
|
||||
total_delay = delay + jitter
|
||||
logger.info(
|
||||
"Retrying %s in %.2f seconds (attempt %s/5)", att_id, total_delay, attempts + 1
|
||||
)
|
||||
await asyncio.sleep(total_delay)
|
||||
await _re_publish(message.body)
|
||||
logger.error("Error processing %s: %s", att_id, e)
|
||||
span.set_attribute("worker.result", "error")
|
||||
result = "error"
|
||||
if not isinstance(e, PermanentError):
|
||||
delay = min(2 ** attempts, 60)
|
||||
jitter = random.uniform(0, 3)
|
||||
total_delay = delay + jitter
|
||||
logger.info("Retrying %s in %.2f seconds (attempt %s/5)", att_id, total_delay, attempts + 1)
|
||||
await asyncio.sleep(total_delay)
|
||||
await _re_publish(message.body, headers)
|
||||
finally:
|
||||
duration = time.time() - start_time
|
||||
worker_duration.record(duration, {"result": result})
|
||||
worker_processed.add(1, {"result": result})
|
||||
worker_in_flight.add(-1)
|
||||
otel_context.detach(token)
|
||||
|
||||
|
||||
async def main():
|
||||
setup_logging(get_settings().log_level)
|
||||
setup_otel("messenger-worker")
|
||||
|
||||
# --- ЭКСПОРТ МЕТРИК ИЗ ВОРКЕРА ---
|
||||
s = get_settings()
|
||||
resource = Resource.create({"service.name": "messenger-worker"})
|
||||
reader = PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=s.otel_exporter_otlp_endpoint, insecure=True),
|
||||
export_interval_millis=5000,
|
||||
)
|
||||
meter_provider = MeterProvider(resource=resource, metric_readers=[reader])
|
||||
otel_metrics.set_meter_provider(meter_provider)
|
||||
# ---------------------------------
|
||||
|
||||
init_pool()
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
from opentelemetry import metrics
|
||||
|
||||
# Объявляем глобальные переменные
|
||||
worker_duration = None
|
||||
worker_processed = None
|
||||
queue_depth = None
|
||||
worker_in_flight = None
|
||||
|
||||
def init_metrics():
|
||||
global worker_duration, worker_processed, queue_depth, worker_in_flight
|
||||
|
||||
# Получаем meter ПОСЛЕ того, как установлен MeterProvider
|
||||
meter = metrics.get_meter("messenger-worker")
|
||||
|
||||
worker_duration = meter.create_histogram(
|
||||
name="worker_duration_seconds",
|
||||
description="Time taken to process attachment",
|
||||
unit="s"
|
||||
)
|
||||
|
||||
worker_processed = meter.create_counter(
|
||||
name="worker_processed_total",
|
||||
description="Total processed jobs by result"
|
||||
)
|
||||
|
||||
queue_depth = meter.create_up_down_counter(
|
||||
name="rabbitmq_queue_depth",
|
||||
description="Number of messages in queue"
|
||||
)
|
||||
|
||||
worker_in_flight = meter.create_up_down_counter(
|
||||
name="worker_in_flight",
|
||||
description="Current number of in-flight jobs"
|
||||
)
|
||||
@@ -3,12 +3,11 @@ import json
|
||||
import logging
|
||||
import aio_pika
|
||||
from opentelemetry import trace
|
||||
from opentelemetry.propagate import inject
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from src.app.config import get_settings
|
||||
from src.app.db import transaction
|
||||
from src.app.otel import setup_otel
|
||||
from src.app.logging_config import setup_logging
|
||||
|
||||
logger = logging.getLogger("outbox")
|
||||
tracer = trace.get_tracer("messenger-outbox")
|
||||
@@ -42,9 +41,15 @@ async def publish_loop():
|
||||
payload = msg["payload"]
|
||||
with tracer.start_as_current_span("outbox.publish") as span:
|
||||
span.set_attribute("outbox.message_id", str(msg["id"]))
|
||||
|
||||
# Внедряем W3C traceparent в заголовки
|
||||
headers = {}
|
||||
inject(headers)
|
||||
|
||||
message = aio_pika.Message(
|
||||
body=json.dumps(payload).encode(),
|
||||
delivery_mode=aio_pika.DeliveryMode.PERSISTENT,
|
||||
headers=headers
|
||||
)
|
||||
await channel.default_exchange.publish(
|
||||
message, routing_key=settings.broker_queue
|
||||
|
||||
Reference in New Issue
Block a user