forked from mtusi2026/mtusi2026lab7
lab7: базовый коммит из lab6 (bf06167)
Перенесена кодовая база и инфраструктура lab6: NestJS-приложение (API +
worker, RabbitMQ, outbox, S3, OpenTelemetry), Dockerfile, compose.yaml,
infra/{grafana,haproxy,loki,minio,otel/collector.yaml,prometheus,
rabbitmq,tempo}, docs/runbooks, стендовые скрипты, scripts/lab{4,5,6} и
contracts/extensions.openapi.json.
Задание lab7 оставлено своим: README, REPORT, COURSE, CONTRIBUTING,
MAINTAINERS, lab.json, contracts/{openapi,infrastructure,jobs.schema,
attachment-states,examples,observability,trust-matrix,README},
security/THREAT_MODEL.md, tests (включая security.py), compose.example.yaml,
infra/{openbao,otel}/README.md, .github/pull_request_template.md.
Не переносились старые evidence/lab4..lab6 (18 МБ трека lab6) и
неотслеживаемый docs/lab6.html.
Адаптации при переносе:
- docker-проект mtusi-lab6 -> mtusi-lab7, тег образа mtusi-messenger:lab7
и папка Grafana Messenger lab7 (compose.yaml, scripts/stop-one.sh,
.env.example, infra/README.md, infra/grafana/provisioning/dashboards),
чтобы тома и контейнеры не пересекались с lab6;
- Makefile: сохранены BASE_URL=https://localhost:8443 и цель test-security
из skeleton lab7, добавлены стендовые и проверочные цели lab6;
- .env.example: рабочие переменные приложения и стенда lab6 + блок
переменных lab7 (PUBLIC_BASE_URL, TLS_*, BAO_*, ARGON2_*) из skeleton.
This commit is contained in:
@@ -4,4 +4,39 @@
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
## Роли (база lab6)
|
||||
|
||||
| Роль | Service | Образ | Готовность | Volume | Credentials |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| API | `api` | сборка `mtusi-messenger:lab7` | `/health/ready` (PostgreSQL, Redis, S3) | — | `secrets/s3_api_*`, `secrets/broker_url` |
|
||||
| Worker | `worker` | та же сборка, `dist/worker.main.js` | `127.0.0.1:8081/health` (consumer активен) | — | `secrets/s3_worker_*`, `secrets/broker_worker_url` |
|
||||
| Broker | `broker` | `rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e` | `rabbitmq-diagnostics check_port_connectivity` | `broker-data` | `rabbitmq.conf`; `broker-init` — `broker_worker_password` |
|
||||
| PostgreSQL | `postgres` | `postgres:16.4-alpine` | `pg_isready` | `postgres-data` | пароль в `.env` / `DATABASE_URL` |
|
||||
| Redis | `redis` | `redis:7.4.2-alpine` | `redis-cli ping` | `redis-data` | без пароля, только compose-сеть |
|
||||
| Object storage | `s3` | `minio/minio:RELEASE.2025-09-07T16-13-09Z@sha256:14cea493d9a34af32f524e538b8346cf79f3321eff8e708c1e2960462bd8936e` | `mc ready local` | `s3-data` | root — `secrets/minio_root_*` |
|
||||
| S3 bootstrap | `s3-init` | `minio/mc:RELEASE.2025-08-13T08-35-41Z@sha256:a7fe349ef4bd8521fb8497f55c6042871b2ae640607cf99d9bede5e9bdf11727` | завершается 0 | — | root + identities API/worker |
|
||||
| Broker bootstrap | `broker-init` | `rabbitmq:4.1.8-alpine@sha256:153322e3974e6365c50e523e5eadd5a7fae231f0e8c58f67c03bb3e02056e34e` | завершается 0 | `broker-data` (ro, cookie) | `broker_worker_password` |
|
||||
| Load balancer | `haproxy` | `haproxy:3.2-alpine@sha256:254e6370f01cd654e0744edf607c67f33777c1b6a9dc0d4b28bcba7171460122` | зависит от `api` healthy | — | — |
|
||||
| OTel Collector | `otel-collector` | `otel/opentelemetry-collector-contrib:0.128.0@sha256:1ab0baba0ee3695d823c46653d8a6e8894896e668ce8bd7ebe002e948d827bc7` | внутренний OTLP 4318 | — | — |
|
||||
| Prometheus | `prometheus` | `prom/prometheus:v3.4.1@sha256:9abc6cf6aea7710d163dbb28d8eeb7dc5baef01e38fa4cd146a406dd9f07f70d` | loopback `:9090` | `prometheus-data` | — |
|
||||
| Loki | `loki` | `grafana/loki:3.5.1@sha256:a74594532eec4cc313401beedc4dd2708c43674c032084b1aeb87c14a5be1745` | внутренний `:3100` | `loki-data` | — |
|
||||
| Tempo | `tempo` | `grafana/tempo:2.8.1@sha256:bc9245fe3da4e63dc4c6862d9c2dad9bcd8be13d0ba4f7705fa6acda4c904d0e` | внутренний `:3200` | `tempo-data` | — |
|
||||
| Grafana | `grafana` | `grafana/grafana:12.0.2@sha256:b5b59bfc7561634c2d7b136c4543d702ebcc94a3da477f21ff26f89ffd4214fa` | loopback `:3000` | `grafana-data` | `secrets/grafana_admin_password` |
|
||||
| Obs volumes init | `obs-volumes-init` | сборка `mtusi-messenger:lab7` | завершается 0 | `tempo-data`, `loki-data` | — |
|
||||
|
||||
Политики MinIO разделены: API пишет/удаляет только `staging/*`, читает
|
||||
`attachments/*` и удаляет только legacy `attachments/*/original`; worker
|
||||
читает/удаляет `staging/*` и читает/пишет `attachments/*` (без удаления).
|
||||
Обе роли получают `s3:ListBucket`. Пароль брокера генерируется один раз в
|
||||
`scripts/init-env.sh` и попадает и в `secrets/broker_url` (amqplib), и в
|
||||
`secrets/rabbitmq.conf` (сам брокер), поэтому URL и конфигурация не расходятся.
|
||||
|
||||
Bootstrap идемпотентен: `scripts/init-env.sh` создаёт `.env` и секреты, `migrate`
|
||||
применяет SQL-миграции, `s3-init` создаёт bucket/политики/пользователей, а
|
||||
producer и consumer объявляют обменники и quorum-очереди при каждом подключении.
|
||||
Одноразовый `broker-init` (образ RabbitMQ, data volume только для cookie)
|
||||
создаёт `messenger-worker` и сужает права `messenger`: API публикует и объявляет
|
||||
топологию, но не читает основную очередь, worker потребляет её. Так схема
|
||||
сходится и на существующем volume, где `default_permissions` уже не применяются.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,632 @@
|
||||
{
|
||||
"uid": "messenger-telemetry",
|
||||
"title": "Messenger: telemetry pipeline",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"editable": false,
|
||||
"refresh": "10s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"timezone": "utc",
|
||||
"tags": [
|
||||
"messenger",
|
||||
"lab6"
|
||||
],
|
||||
"templating": {
|
||||
"list": []
|
||||
},
|
||||
"annotations": {
|
||||
"list": []
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Collector",
|
||||
"collapsed": false,
|
||||
"id": 1,
|
||||
"panels": [],
|
||||
"gridPos": {
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Collector: принято",
|
||||
"id": 2,
|
||||
"description": "Элементов, принятых OTLP-receiver, в секунду (не байты).",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 1
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "suffix:items/s",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(otelcol_receiver_accepted_spans[1m]))",
|
||||
"legendFormat": "spans"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(otelcol_receiver_accepted_log_records[1m]))",
|
||||
"legendFormat": "log records"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(otelcol_receiver_accepted_metric_points[1m]))",
|
||||
"legendFormat": "metric points"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Collector: отправлено",
|
||||
"id": 3,
|
||||
"description": "Элементов, успешно отправленных exporter-ами в backend.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 1
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "suffix:items/s",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(otelcol_exporter_sent_spans[1m]))",
|
||||
"legendFormat": "spans"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(otelcol_exporter_sent_log_records[1m]))",
|
||||
"legendFormat": "log records"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(otelcol_exporter_sent_metric_points[1m]))",
|
||||
"legendFormat": "metric points"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Collector: ошибки отправки и постановки в очередь",
|
||||
"id": 4,
|
||||
"description": "Потери на выходе Collector. Нулевые серии могут отсутствовать до первой ошибки.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 9
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "suffix:items/s",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum by (exporter)(rate(otelcol_exporter_send_failed_spans[1m]))",
|
||||
"legendFormat": "send_failed spans {{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum by (exporter)(rate(otelcol_exporter_send_failed_log_records[1m]))",
|
||||
"legendFormat": "send_failed logs {{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum by (exporter)(rate(otelcol_exporter_send_failed_metric_points[1m]))",
|
||||
"legendFormat": "send_failed metrics {{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "D",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum by (exporter)(rate(otelcol_exporter_enqueue_failed_spans[1m]))",
|
||||
"legendFormat": "enqueue_failed spans {{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "E",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum by (exporter)(rate(otelcol_exporter_enqueue_failed_log_records[1m]))",
|
||||
"legendFormat": "enqueue_failed logs {{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "F",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum by (exporter)(rate(otelcol_exporter_enqueue_failed_metric_points[1m]))",
|
||||
"legendFormat": "enqueue_failed metrics {{exporter}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Collector: очередь / ёмкость",
|
||||
"id": 5,
|
||||
"description": "Очередь sending_queue в запросах (batch), не в spans.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 9
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "max by (exporter)(otelcol_exporter_queue_size)",
|
||||
"legendFormat": "size {{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "max by (exporter)(otelcol_exporter_queue_capacity)",
|
||||
"legendFormat": "capacity {{exporter}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Collector: RSS",
|
||||
"id": 6,
|
||||
"description": "Resident set size процесса Collector; лимит контейнера 256 MiB, memory_limiter 204 MiB.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 17
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "otelcol_process_memory_rss",
|
||||
"legendFormat": "RSS"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Приложение: экспорт телеметрии (items)",
|
||||
"id": 7,
|
||||
"description": "Элементов, дошедших до OTLP-exporter приложения (traces/logs). Не учёт метрик и не все pre-export drops.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 17
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "suffix:items/s",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum by (signal, outcome)(rate(messenger_telemetry_export_items_total[1m]))",
|
||||
"legendFormat": "{{signal}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Backend-хранилища",
|
||||
"collapsed": false,
|
||||
"id": 8,
|
||||
"panels": [],
|
||||
"gridPos": {
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 25
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Loki / Tempo: up",
|
||||
"id": 9,
|
||||
"description": "1 — scrape успешен.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 26
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "up{job=~\"loki|tempo\"}",
|
||||
"legendFormat": "{{job}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Loki / Tempo: ingest",
|
||||
"id": 10,
|
||||
"description": "Байт, принятых distributor-ами, в секунду.",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 26
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "Bps",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(loki_distributor_bytes_received_total[1m]))",
|
||||
"legendFormat": "loki"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "sum(rate(tempo_distributor_bytes_received_total[1m]))",
|
||||
"legendFormat": "tempo"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Prometheus: размер TSDB",
|
||||
"id": 11,
|
||||
"description": "Блоки и WAL локального TSDB (retention 7d).",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 34
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 8,
|
||||
"showPoints": "never"
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom"
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi"
|
||||
}
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "prometheus_tsdb_storage_blocks_bytes",
|
||||
"legendFormat": "blocks"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "prometheus_tsdb_wal_storage_size_bytes",
|
||||
"legendFormat": "wal"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "table",
|
||||
"title": "Состояние правил (ALERTS)",
|
||||
"id": 12,
|
||||
"description": "Pending/firing alerts из метрики ALERTS. Отсутствие строк означает, что нет pending/firing при загруженных rules (правила проверяются через /api/v1/rules).",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 34
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"showHeader": true
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"expr": "ALERTS{alertname=~\"Messenger.*\"}",
|
||||
"instant": true,
|
||||
"format": "table"
|
||||
}
|
||||
],
|
||||
"transformations": [
|
||||
{
|
||||
"id": "organize",
|
||||
"options": {
|
||||
"excludeByName": {
|
||||
"Time": true,
|
||||
"__name__": true,
|
||||
"job": true,
|
||||
"Value": true
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger-lab7
|
||||
orgId: 1
|
||||
folder: Messenger lab7
|
||||
type: file
|
||||
allowUiUpdates: false
|
||||
disableDeletion: true
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /etc/grafana/dashboards
|
||||
@@ -0,0 +1,48 @@
|
||||
apiVersion: 1
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
manageAlerts: false
|
||||
timeInterval: 10s
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
derivedFields:
|
||||
# trace_id — structured metadata записи (не текст строки).
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
tags:
|
||||
- { key: service.name, value: service_name }
|
||||
spanStartTimeShift: '-2m'
|
||||
spanEndTimeShift: '2m'
|
||||
filterByTraceID: false
|
||||
filterBySpanID: false
|
||||
customQuery: true
|
||||
query: '{$${__tags}} | trace_id="$${__span.traceId}"'
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
@@ -0,0 +1,63 @@
|
||||
# HAProxy — единственная точка входа lab4.
|
||||
#
|
||||
# Проверка готовности backend: GET /health/ready — та же ручка, что у
|
||||
# healthcheck контейнера. Реплика, потерявшая обязательную зависимость (свой
|
||||
# путь к общей БД или Redis), исключается из ротации, и трафик уходит на
|
||||
# здоровые; при отказе общей зависимости неготовыми становятся все реплики, и
|
||||
# клиент получает 503 от балансировщика — это честный признак того, что
|
||||
# готовых узлов нет.
|
||||
# Проба с зависимостями ограничена на стороне API: бюджет пробы 400 ms (общий
|
||||
# дедлайн /health/ready, проверка БД — по отдельному соединению, не из общего
|
||||
# пула) меньше timeout check 500 ms, который равен интервалу inter. Обнаружение
|
||||
# отказа (inter 500 ms × fall 2 ≈ 1 s) короче окна дреина API
|
||||
# (DRAIN_DELAY_MS=3000): узел уходит из ротации раньше, чем перестаёт
|
||||
# обслуживать.
|
||||
#
|
||||
# Реплики не перечислены статически: server-template + DNS Docker обновляет
|
||||
# список адресов при масштабировании (init-addr none — стартовать без адресов
|
||||
# и дождаться DNS, а не падать при пустом ответе).
|
||||
|
||||
global
|
||||
maxconn 8192
|
||||
log stdout format raw local0
|
||||
|
||||
defaults
|
||||
mode http
|
||||
option httplog
|
||||
timeout connect 500ms
|
||||
timeout client 35s
|
||||
timeout server 30s
|
||||
timeout queue 2s
|
||||
retries 3
|
||||
option redispatch
|
||||
retry-on conn-failure
|
||||
|
||||
resolvers docker
|
||||
nameserver dns1 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 500ms
|
||||
hold nx 500ms
|
||||
hold other 1s
|
||||
|
||||
frontend http
|
||||
bind *:8080
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
timeout check 500ms
|
||||
default-server check inter 500ms fastinter 250ms downinter 1s fall 2 rise 2 maxconn 200
|
||||
server-template api 1-8 api:8080 resolvers docker init-addr none
|
||||
|
||||
listen stats
|
||||
bind *:8404
|
||||
stats enable
|
||||
stats uri /stats
|
||||
stats refresh 1s
|
||||
stats show-legends
|
||||
# Prometheus-экспортёр HAProxy (PROMEX); scrape: haproxy:8404/metrics.
|
||||
http-request use-service prometheus-exporter if { path /metrics }
|
||||
@@ -0,0 +1,48 @@
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_port: 9096
|
||||
|
||||
common:
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2025-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
ingester:
|
||||
wal:
|
||||
dir: /loki/wal
|
||||
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 168h
|
||||
|
||||
distributor:
|
||||
otlp_config:
|
||||
default_resource_attributes_as_index_labels:
|
||||
- service.name
|
||||
- deployment.environment.name
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/bin/sh
|
||||
# Идемпотентная инициализация MinIO: приватный bucket, ограниченная политика и
|
||||
# отдельный пользователь API. Выполняется в контейнере minio/mc.
|
||||
set -eu
|
||||
|
||||
IFS= read -r root_user < /run/secrets/minio_root_user || [ -n "$root_user" ]
|
||||
IFS= read -r root_password < /run/secrets/minio_root_password || [ -n "$root_password" ]
|
||||
IFS= read -r api_key < /run/secrets/s3_api_access_key_id || [ -n "$api_key" ]
|
||||
IFS= read -r api_secret < /run/secrets/s3_api_secret_access_key || [ -n "$api_secret" ]
|
||||
IFS= read -r worker_key < /run/secrets/s3_worker_access_key_id || [ -n "$worker_key" ]
|
||||
IFS= read -r worker_secret < /run/secrets/s3_worker_secret_access_key || [ -n "$worker_secret" ]
|
||||
bucket="${S3_BUCKET:?}"
|
||||
|
||||
export MC_CONFIG_DIR=/tmp/.mc
|
||||
export MC_HOST_stand="http://${root_user}:${root_password}@s3:9000"
|
||||
|
||||
mc mb --ignore-existing "stand/$bucket"
|
||||
mc anonymous set none "stand/$bucket"
|
||||
|
||||
# The API owns the staging prefix only: it writes the accepted upload there and
|
||||
# can remove it after the worker commits the result. The final prefix is read
|
||||
# for variant/original downloads and legacy lab4 originals, but never written.
|
||||
printf '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/staging/*"]},{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/attachments/*"]},{"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/attachments/*/original"]},{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::%s"],"Condition":{"StringLike":{"s3:prefix":["staging/*","attachments/*"]}}}]}' "$bucket" "$bucket" "$bucket" "$bucket" > /tmp/messenger-api-policy.json
|
||||
|
||||
# The worker reads staging, writes the final original and variants, and removes
|
||||
# staging after a safe commit. It never deletes the final prefix.
|
||||
printf '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/staging/*"]},{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject"],"Resource":["arn:aws:s3:::%s/attachments/*"]},{"Effect":"Allow","Action":["s3:DeleteObject"],"Resource":["arn:aws:s3:::%s/attachments/*/v*/*"]},{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::%s"],"Condition":{"StringLike":{"s3:prefix":["staging/*","attachments/*"]}}}]}' "$bucket" "$bucket" "$bucket" "$bucket" > /tmp/messenger-worker-policy.json
|
||||
|
||||
ensure_user() {
|
||||
name=$1
|
||||
secret=$2
|
||||
if ! mc admin user info stand "$name" >/dev/null 2>&1; then
|
||||
mc admin user add stand "$name" "$secret"
|
||||
fi
|
||||
}
|
||||
|
||||
# `mc admin policy create` does not overwrite and a policy attached to a user
|
||||
# cannot be removed. Detach, remove and recreate makes the script converge on
|
||||
# the current policy even when the stand volume predates lab5.
|
||||
install_policy() {
|
||||
name=$1
|
||||
file=$2
|
||||
user=$3
|
||||
if mc admin policy info stand "$name" >/dev/null 2>&1; then
|
||||
mc admin policy detach stand "$name" --user "$user" >/dev/null 2>&1 || true
|
||||
mc admin policy remove stand "$name" >/dev/null 2>&1 || true
|
||||
fi
|
||||
mc admin policy create stand "$name" "$file"
|
||||
mc admin policy attach stand "$name" --user "$user"
|
||||
}
|
||||
|
||||
ensure_user "$api_key" "$api_secret"
|
||||
ensure_user "$worker_key" "$worker_secret"
|
||||
|
||||
install_policy messenger-api /tmp/messenger-api-policy.json "$api_key"
|
||||
install_policy messenger-worker /tmp/messenger-worker-policy.json "$worker_key"
|
||||
|
||||
echo "bootstrap ok: bucket=$bucket policies=messenger-api,messenger-worker"
|
||||
@@ -0,0 +1,109 @@
|
||||
# OpenTelemetry Collector (contrib 0.128.0): единственная OTLP-точка входа.
|
||||
# traces -> Tempo, metrics -> Prometheus OTLP receiver, logs -> Loki OTLP.
|
||||
# Порт 4318 доступен только внутри compose-сети (наружу не публикуется).
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
processors:
|
||||
# Бэкпрешер: при приближении к лимиту отказывает приёмнику (SDK ретраит/теряет).
|
||||
# Для контейнера 256 MiB: limit_mib=floor(256*0.8), spike=floor(limit*0.2).
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 204
|
||||
spike_limit_mib: 40
|
||||
# Второй рубеж: секретные атрибуты. Тело лога защищает redaction приложения.
|
||||
attributes/scrub:
|
||||
actions:
|
||||
- { key: authorization, action: delete }
|
||||
- { key: Authorization, action: delete }
|
||||
- { key: http.request.header.authorization, action: delete }
|
||||
- { key: cookie, action: delete }
|
||||
- { key: Cookie, action: delete }
|
||||
- { key: http.request.header.cookie, action: delete }
|
||||
- { key: password, action: delete }
|
||||
- { key: token, action: delete }
|
||||
- { key: session_token, action: delete }
|
||||
- { key: http.request.body, action: delete }
|
||||
- { key: http.response.body, action: delete }
|
||||
- { key: url.full, action: delete }
|
||||
- { key: http.url, action: delete }
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 512
|
||||
send_batch_max_size: 1024
|
||||
|
||||
exporters:
|
||||
otlp/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
insecure: true
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 128
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 128
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
otlphttp/prometheus:
|
||||
# Prometheus сам обслуживает /api/v1/otlp/v1/metrics.
|
||||
endpoint: http://prometheus:9090/api/v1/otlp
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 128
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
telemetry:
|
||||
metrics:
|
||||
level: detailed
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
without_scope_info: true
|
||||
without_units: true
|
||||
without_type_suffix: true
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, attributes/scrub, batch]
|
||||
exporters: [otlp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, attributes/scrub, batch]
|
||||
exporters: [otlphttp/prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, attributes/scrub, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,34 @@
|
||||
global:
|
||||
scrape_interval: 10s
|
||||
evaluation_interval: 10s
|
||||
scrape_timeout: 5s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yml
|
||||
|
||||
# Метрики API/worker приходят только по OTLP (--web.enable-otlp-receiver);
|
||||
# /internal/metrics — legacy JSON, не exposition-формат, и не скрейпится.
|
||||
otlp:
|
||||
translation_strategy: UnderscoreEscapingWithSuffixes
|
||||
promote_resource_attributes:
|
||||
- service.version
|
||||
- deployment.environment.name
|
||||
|
||||
storage:
|
||||
tsdb:
|
||||
out_of_order_time_window: 10m
|
||||
|
||||
scrape_configs:
|
||||
- job_name: prometheus
|
||||
static_configs: [{ targets: ['localhost:9090'] }]
|
||||
- job_name: otel-collector
|
||||
static_configs: [{ targets: ['otel-collector:8888'] }]
|
||||
- job_name: haproxy
|
||||
metrics_path: /metrics
|
||||
static_configs: [{ targets: ['haproxy:8404'] }]
|
||||
- job_name: rabbitmq
|
||||
static_configs: [{ targets: ['broker:15692'] }]
|
||||
- job_name: loki
|
||||
static_configs: [{ targets: ['loki:3100'] }]
|
||||
- job_name: tempo
|
||||
static_configs: [{ targets: ['tempo:3200'] }]
|
||||
@@ -0,0 +1,21 @@
|
||||
groups:
|
||||
- name: messenger-alerts
|
||||
rules:
|
||||
- alert: MessengerApiHighErrorRate
|
||||
expr: messenger:api_errors:rate1m / messenger:api_requests:rate1m > 0.05 and messenger:api_requests:rate1m > 0.1
|
||||
for: 30s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Доля 5xx бизнес-запросов API выше 5% дольше 30 с
|
||||
description: Серверные ошибки (5xx, без 4xx и без /health*, /internal/*) превышают 5% от бизнес-запросов при трафике выше 0.1 rps. Различите БД, балансировщик и handler по трассам и db_client_operation_duration_seconds.
|
||||
runbook_url: docs/runbooks/MessengerApiHighErrorRate.md
|
||||
- alert: MessengerJobsQueueLagGrowing
|
||||
expr: max(messenger_jobs_queue_oldest_age_seconds) > 30 and max(messenger_jobs_queue_depth{state=~"ready|delayed"}) > 0
|
||||
for: 30s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Самая старая необработанная задача ждёт дольше 30 с, очередь не пуста
|
||||
description: Backlog задач вложений устойчиво стареет. Это возраст ожидания, а не время обработки; проверьте worker, брокер, outbox, S3 и БД.
|
||||
runbook_url: docs/runbooks/MessengerJobsQueueLagGrowing.md
|
||||
@@ -0,0 +1,18 @@
|
||||
# SLI доступности API: good = любой бизнес-запрос, кроме 5xx; знаменатель — все
|
||||
# бизнес-запросы (маршруты /health* и /internal/* исключены). 4xx — good.
|
||||
# Учебная цель стенда: availability >= 99.5% в скользящем окне 5m.
|
||||
# Без трафика отношение отсутствует (N/A), а не искусственные 100%.
|
||||
groups:
|
||||
- name: messenger-sli
|
||||
interval: 10s
|
||||
rules:
|
||||
- record: messenger:api_requests:rate1m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*"}[1m]))
|
||||
- record: messenger:api_errors:rate1m
|
||||
expr: (sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*",http_response_status_code=~"5.."}[1m])) or vector(0))
|
||||
- record: messenger:api_requests:rate5m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*"}[5m]))
|
||||
- record: messenger:api_errors:rate5m
|
||||
expr: (sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_route!~"/health.*|/internal/.*",http_response_status_code=~"5.."}[5m])) or vector(0))
|
||||
- record: messenger:api_availability:ratio5m
|
||||
expr: 1 - (messenger:api_errors:rate5m / (messenger:api_requests:rate5m > 0))
|
||||
@@ -0,0 +1,100 @@
|
||||
rule_files:
|
||||
- ../rules/recording.yml
|
||||
- ../rules/alerts.yml
|
||||
|
||||
evaluation_interval: 10s
|
||||
|
||||
tests:
|
||||
# Нормальная нагрузка с 4xx (клиентские ошибки) не поднимает error alert.
|
||||
- interval: 10s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="201"}'
|
||||
values: '0+100x60'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="404"}'
|
||||
values: '0+30x60'
|
||||
alert_rule_test:
|
||||
- eval_time: 3m
|
||||
alertname: MessengerApiHighErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 9m
|
||||
alertname: MessengerApiHighErrorRate
|
||||
exp_alerts: []
|
||||
promql_expr_test:
|
||||
- expr: messenger:api_availability:ratio5m
|
||||
eval_time: 9m
|
||||
exp_samples:
|
||||
- labels: 'messenger:api_availability:ratio5m'
|
||||
value: 1
|
||||
|
||||
# Устойчивые 5xx: pending -> firing -> восстановление снимает alert.
|
||||
- interval: 10s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="201"}'
|
||||
values: '0+100x60'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="500"}'
|
||||
values: '0x12 0+30x18 540x30'
|
||||
# health-пробы с 5xx не считаются.
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a",http_route="/health/ready",http_response_status_code="503"}'
|
||||
values: '0+100x60'
|
||||
alert_rule_test:
|
||||
- eval_time: 90s
|
||||
alertname: MessengerApiHighErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 2m20s
|
||||
alertname: MessengerApiHighErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 3m
|
||||
alertname: MessengerApiHighErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: Доля 5xx бизнес-запросов API выше 5% дольше 30 с
|
||||
description: Серверные ошибки (5xx, без 4xx и без /health*, /internal/*) превышают 5% от бизнес-запросов при трафике выше 0.1 rps. Различите БД, балансировщик и handler по трассам и db_client_operation_duration_seconds.
|
||||
runbook_url: docs/runbooks/MessengerApiHighErrorRate.md
|
||||
- eval_time: 9m
|
||||
alertname: MessengerApiHighErrorRate
|
||||
exp_alerts: []
|
||||
|
||||
# Две реплики публикуют одинаковый snapshot: max(), а не sum(), иначе 2x20=40>30.
|
||||
- interval: 10s
|
||||
input_series:
|
||||
- series: 'messenger_jobs_queue_oldest_age_seconds{job="messenger-api",instance="a"}'
|
||||
values: '20x30'
|
||||
- series: 'messenger_jobs_queue_oldest_age_seconds{job="messenger-api",instance="b"}'
|
||||
values: '20x30'
|
||||
- series: 'messenger_jobs_queue_depth{job="messenger-api",instance="a",state="ready"}'
|
||||
values: '5x30'
|
||||
- series: 'messenger_jobs_queue_depth{job="messenger-api",instance="b",state="ready"}'
|
||||
values: '5x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 4m
|
||||
alertname: MessengerJobsQueueLagGrowing
|
||||
exp_alerts: []
|
||||
|
||||
# Краткий всплеск возраста короче for не даёт firing; устойчивый — даёт и снимается.
|
||||
- interval: 10s
|
||||
input_series:
|
||||
- series: 'messenger_jobs_queue_oldest_age_seconds{job="messenger-api",instance="a"}'
|
||||
values: '5x6 40 40 5x12 40x12 5x30'
|
||||
- series: 'messenger_jobs_queue_depth{job="messenger-api",instance="a",state="ready"}'
|
||||
values: '3x60'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m20s
|
||||
alertname: MessengerJobsQueueLagGrowing
|
||||
exp_alerts: []
|
||||
- eval_time: 3m
|
||||
alertname: MessengerJobsQueueLagGrowing
|
||||
exp_alerts: []
|
||||
- eval_time: 4m30s
|
||||
alertname: MessengerJobsQueueLagGrowing
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: Самая старая необработанная задача ждёт дольше 30 с, очередь не пуста
|
||||
description: Backlog задач вложений устойчиво стареет. Это возраст ожидания, а не время обработки; проверьте worker, брокер, outbox, S3 и БД.
|
||||
runbook_url: docs/runbooks/MessengerJobsQueueLagGrowing.md
|
||||
- eval_time: 7m
|
||||
alertname: MessengerJobsQueueLagGrowing
|
||||
exp_alerts: []
|
||||
@@ -0,0 +1 @@
|
||||
[rabbitmq_prometheus].
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
# Runs as a one-shot sidecar against rabbit@broker. The broker data volume is
|
||||
# mounted read-only only to share the Erlang cookie; no queue data is modified.
|
||||
set -eu
|
||||
|
||||
password=$(cat /run/secrets/broker_worker_password)
|
||||
configure='^(attachments\.jobs|attachments\.process|attachments\.dlx|attachments\.process\.dlq)$'
|
||||
write='^attachments\.(jobs|process|dlx|process\.dlq)$'
|
||||
all_read='^attachments\.(jobs|process|dlx|process\.dlq)$'
|
||||
api_read='^attachments\.(jobs|dlx)$'
|
||||
|
||||
if ! rabbitmqctl -n rabbit@broker -p messenger add_user messenger-worker "$password" 2>/dev/null; then
|
||||
rabbitmqctl -n rabbit@broker -q -p messenger change_password messenger-worker "$password"
|
||||
fi
|
||||
rabbitmqctl -n rabbit@broker -q -p messenger set_permissions messenger-worker \
|
||||
"$configure" "$write" "$all_read"
|
||||
# The API may publish and declare the topology, but must not consume the job
|
||||
# queue. The worker identity is used by the worker process.
|
||||
rabbitmqctl -n rabbit@broker -q -p messenger set_permissions messenger \
|
||||
"$configure" "$write" "$api_read"
|
||||
echo "broker init ok: publisher and consumer identities separated"
|
||||
@@ -0,0 +1,24 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
Reference in New Issue
Block a user