Подключить OpenTelemetry, Collector и Grafana для оценки 5.

API и worker отдают метрики, логи и трассы. Правила SLO записаны, прогон инцидентов ещё впереди.
This commit is contained in:
2026-11-17 15:23:33 +03:00
parent 14ab803529
commit baee48072c
26 changed files with 1279 additions and 113 deletions
+156
View File
@@ -0,0 +1,156 @@
{
"uid": "messenger-lab6",
"title": "Messenger observability",
"tags": ["messenger", "lab6"],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"time": {"from": "now-1h", "to": "now"},
"description": "RPS and errors use messenger_http_requests_total. Durations are histogram_quantile over buckets, in seconds. Queue age is seconds. API error ratio excludes health.",
"panels": [
{
"id": 1,
"type": "timeseries",
"title": "API RPS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
"fieldConfig": {"defaults": {"unit": "reqps", "custom": {"drawStyle": "line"}}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum by (method, route) (rate(messenger_http_requests_total[1m]))",
"legendFormat": "{{method}} {{route}}"
}
]
},
{
"id": 2,
"type": "timeseries",
"title": "API error ratio (5xx / business)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])), 1e-9)",
"legendFormat": "5xx ratio"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "API duration p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_request_duration_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 4,
"type": "timeseries",
"title": "Jobs by outcome",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Worker duration p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 16},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Time to ready p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 16},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[1m])))", "legendFormat": "p99"}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Queue depth and oldest job age",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 24},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max(messenger_queue_depth)", "legendFormat": "depth (jobs)"},
{"refId": "B", "expr": "max(messenger_queue_oldest_age_seconds)", "legendFormat": "oldest age (seconds)"}
]
},
{
"id": 8,
"type": "timeseries",
"title": "DB pool used and waiting",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 24},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max by (service_name, service_instance_id) (messenger_db_pool_used)", "legendFormat": "used {{service_name}} {{service_instance_id}}"},
{"refId": "B", "expr": "max by (service_name, service_instance_id) (messenger_db_pool_waiting)", "legendFormat": "waiting {{service_name}} {{service_instance_id}}"}
]
},
{
"id": 9,
"type": "timeseries",
"title": "Worker busy / capacity",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 32},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max(messenger_worker_busy)", "legendFormat": "busy"},
{"refId": "B", "expr": "max(messenger_worker_capacity)", "legendFormat": "capacity"}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Process CPU and RSS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 32},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max by (service_name, service_instance_id) (process_cpu_percent)", "legendFormat": "cpu % {{service_name}} {{service_instance_id}}"},
{"refId": "B", "expr": "max by (service_name, service_instance_id) (process_memory_rss_bytes)", "legendFormat": "rss {{service_name}} {{service_instance_id}}"}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Firing alerts",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 40},
"fieldConfig": {"defaults": {"unit": "none"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "ALERTS{alertstate=\"firing\"}", "legendFormat": "{{alertname}}"}
]
}
]
}
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,38 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 15s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- datasourceUid: tempo
matcherRegex: '"trace_id":"([0-9a-f]+)"'
name: trace_id
url: "$${__value.raw}"
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
@@ -0,0 +1,9 @@
# High API error rate
Signal: `messenger_http_requests_total`. Numerator is `status_class="5xx"`. Denominator is every instrumented business request. `/health/*`, `/docs` and `/openapi.json` are not in this ratio, so a bad password (401) is not an incident.
1. Open the Messenger dashboard and compare the 5xx ratio with p95 duration.
2. In Tempo, open a server span with `http.response.status_code >= 500`. The span attribute `http.route` is the template, not a user id.
3. In Loki, query `{service_name="messenger-api"}` and match `trace_id` from that span. The log line has `event`, `severity`, `trace_id` and `span_id`.
4. If the span stops inside the database client or the pool-used gauge is at `DB_POOL_MAX` with waiters, the cause is Postgres, not the HTTP handler itself.
5. After the dependency recovers, the 5m ratio falls and `HighApiErrorRate` leaves `firing`.
+8
View File
@@ -0,0 +1,8 @@
# Queue lag
Signal: `messenger_queue_oldest_age_seconds` is `now() - min(created_at)` for rows still `queued`. `messenger_queue_depth` counts `queued` and `processing`. Age is not the same number as worker duration.
1. If age grows and `messenger_worker_busy` is 0, the worker process is stopped or not consuming. Messages stay in RabbitMQ and in `attachment_jobs`.
2. If busy equals capacity and age still grows, the worker is saturated. Look at `messenger_job_duration_seconds` and the consumer span.
3. A consumer span's parent is the producer span, whose parent is the API server span that accepted the upload (`traceparent` stored on the job row).
4. Start the worker again. Depth and age return toward zero, then `QueueLagHigh` resolves. Do not delete the RabbitMQ volume.
+13
View File
@@ -0,0 +1,13 @@
# SLO burn
Two SLOs, each with a 1% error budget over 30 days.
- API availability: business requests that are not 5xx. Fast burn pages when both the 5 minute and 1 hour windows exceed 14.4% errors (14.4x budget). Slow burn warns when both 30 minutes and 6 hours exceed 6% (6x budget).
- Time to ready: jobs whose ready time is at most 30 seconds, read from the `le="30"` histogram bucket, not from an average. The same 14.4x and 6x windows apply.
A short spike can trip only the fast pair. A long degradation keeps the slow pair firing after the spike is gone. Both windows must agree, so one noisy minute does not page by itself.
1. Read which alert is firing and which SLO label it has.
2. For `api-availability`, follow `high-error-rate.md`. Separate 4xx from 5xx before calling it an incident.
3. For `time-to-ready`, follow `queue-lag.md`, then open the worker trace and see whether time is in `s3.get`, `image.render`, `s3.put` or `db.complete`.
4. Record the first firing timestamp and the first resolved timestamp. That pair is time-to-detect and time-to-recover for the experiment.
+30
View File
@@ -0,0 +1,30 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
+8 -4
View File
@@ -1,7 +1,11 @@
# Конфигурация наблюдаемости — реализовать
# Collector
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
`collector.yaml` — OTel Collector Contrib 0.128.0. Принимает OTLP/HTTP `:4318` и OTLP/gRPC `:4317` только внутри сети Compose.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
- traces → Tempo `http://tempo:4318/v1/traces`
- metrics → Prometheus remote write `http://prometheus:9090/api/v1/write`
- logs → Loki OTLP `http://loki:3100/otlp/v1/logs`
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
`memory_limiter` (192 MiB) и очереди exporter ограничены. Если backend недоступен, collector сбрасывает телеметрию после повторных попыток и не хранит её вечно. API от этого не зависит: SDK тоже пишет в ограниченную очередь и продолжает отвечать на запросы.
Grafana provisioning и dashboard лежат в `infra/grafana`. Правила Prometheus — в `infra/prometheus/alerts.yml`. SLO — в `infra/slo.md`.
+89
View File
@@ -0,0 +1,89 @@
# Collector 0.128.0. It forwards signals and is not a database.
# memory_limiter refuses data before the process grows without bound.
# Exporter queues are capped; a dead backend drops telemetry after retry, the API keeps serving.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
batch:
timeout: 5s
send_batch_size: 256
send_batch_max_size: 512
exporters:
otlphttp/tempo:
traces_endpoint: http://tempo:4318/v1/traces
tls:
insecure: true
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 1000
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
prometheusremotewrite:
endpoint: http://prometheus:9090/api/v1/write
tls:
insecure: true
resource_to_telemetry_conversion:
enabled: true
remote_write_queue:
enabled: true
queue_size: 1000
num_consumers: 2
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
otlphttp/loki:
logs_endpoint: http://loki:3100/otlp/v1/logs
tls:
insecure: true
timeout: 5s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 1000
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
telemetry:
logs:
level: info
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
+112
View File
@@ -0,0 +1,112 @@
groups:
- name: messenger
rules:
- alert: HighApiErrorRate
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
/
clamp_min(sum(rate(messenger_http_requests_total[5m])), 1e-9)
) > 0.05
for: 1m
labels:
severity: warning
slo: api-availability
annotations:
summary: API 5xx ratio is above 5% over 5 minutes
description: Numerator is status_class=5xx. Denominator is instrumented business requests. Health, docs and openapi are excluded.
runbook: infra/grafana/runbooks/high-error-rate.md
- alert: QueueLagHigh
expr: max(messenger_queue_oldest_age_seconds) > 30
for: 30s
labels:
severity: warning
slo: time-to-ready
annotations:
summary: Oldest queued job is older than 30 seconds
description: Age is now minus created_at of jobs still in status queued. Depth is a separate gauge.
runbook: infra/grafana/runbooks/queue-lag.md
- alert: ApiAvailabilityFastBurn
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
/ clamp_min(sum(rate(messenger_http_requests_total[5m])), 1e-9)
) > 0.144
and
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[1h]))
/ clamp_min(sum(rate(messenger_http_requests_total[1h])), 1e-9)
) > 0.144
for: 2m
labels:
severity: critical
slo: api-availability
window: fast
annotations:
summary: API error budget burn rate is above 14.4x on both 5m and 1h
runbook: infra/grafana/runbooks/slo-burn.md
- alert: ApiAvailabilitySlowBurn
expr: |
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[30m]))
/ clamp_min(sum(rate(messenger_http_requests_total[30m])), 1e-9)
) > 0.06
and
(
sum(rate(messenger_http_requests_total{status_class="5xx"}[6h]))
/ clamp_min(sum(rate(messenger_http_requests_total[6h])), 1e-9)
) > 0.06
for: 15m
labels:
severity: warning
slo: api-availability
window: slow
annotations:
summary: API error budget burn rate is above 6x on both 30m and 6h
runbook: infra/grafana/runbooks/slo-burn.md
- alert: TimeToReadyFastBurn
expr: |
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[5m]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[5m])), 1e-9)
)
) > 0.144
and
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[1h]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[1h])), 1e-9)
)
) > 0.144
for: 2m
labels:
severity: critical
slo: time-to-ready
window: fast
annotations:
summary: Share of jobs slower than 30s is burning the ready-time budget (5m and 1h)
runbook: infra/grafana/runbooks/slo-burn.md
- alert: TimeToReadySlowBurn
expr: |
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[30m]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[30m])), 1e-9)
)
) > 0.06
and
(
1 - (
sum(rate(messenger_time_to_ready_seconds_bucket{le=~"30|30\\.0"}[6h]))
/ clamp_min(sum(rate(messenger_time_to_ready_seconds_count[6h])), 1e-9)
)
) > 0.06
for: 15m
labels:
severity: warning
slo: time-to-ready
window: slow
annotations:
summary: Share of jobs slower than 30s is burning the ready-time budget (30m and 6h)
runbook: infra/grafana/runbooks/slo-burn.md
+6
View File
@@ -0,0 +1,6 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
+12
View File
@@ -0,0 +1,12 @@
# SLI и SLO
Окно цели: 30 суток. Бюджет ошибок: 1% у каждого SLO. Пороги burn rate — 14.4x (быстрое выгорание, окна 5 минут и 1 час) и 6x (медленное, окна 30 минут и 6 часов). Оба окна пары должны выполниться одновременно.
| SLI | Хорошее событие | SLO | Единица |
| --- | --- | --- | --- |
| Доступность API | бизнес-запрос со `status_class` не `5xx` | 99% | доля запросов |
| Время до ready | job, у которой `messenger_time_to_ready_seconds` попала в bucket `le=30` | 99% готовы не дольше 30 секунд | секунды от durable acceptance до `ready` |
Health, `/docs` и `/openapi.json` в SLI API не входят. 401 и 404 остаются в знаменателе, но не в числителе ошибок: это не отказ сервиса. Процентили дашборда считаются `histogram_quantile` по bucket, не средним значений и не средним p99 реплик.
Правила лежат в `infra/prometheus/alerts.yml`. Runbook: `infra/grafana/runbooks/`.
+28
View File
@@ -0,0 +1,28 @@
stream_over_http_enabled: true
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
grpc:
endpoint: 0.0.0.0:4317
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks