feat: core func lab6, loki, prometeus etc

This commit is contained in:
Enterxx2
2026-11-24 10:50:49 +03:00
parent 60a71dc839
commit 0011b3aabb
47 changed files with 2598 additions and 94 deletions
+675
View File
@@ -0,0 +1,675 @@
{
"uid": "messenger-lab6",
"title": "Messenger · наблюдаемость",
"tags": [
"lab6",
"messenger"
],
"schemaVersion": 41,
"timezone": "browser",
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"type": "timeseries",
"title": "HTTP — запросы в секунду",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (method, route) (rate(messenger_http_requests_total[1m]))",
"legendFormat": "{{method}} {{route}}"
}
]
},
{
"id": 2,
"type": "timeseries",
"title": "HTTP — длительность",
"description": "Перцентили из суммарных histogram buckets всех API-реплик за 2 минуты.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"legendFormat": "p99"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "HTTP — доля 5xx",
"description": "Только /api/v1. Health и Swagger исключены. 4xx входят в знаменатель.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "messenger:http_error_ratio:30s",
"legendFormat": "5xx / все запросы"
}
]
},
{
"id": 4,
"type": "timeseries",
"title": "SLO доступности API за 15 минут",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "messenger:http_availability:15m",
"legendFormat": "SLI"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "vector(0.99)",
"legendFormat": "SLO 99%"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Worker — исходы обработки",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Worker — время обработки",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[2m])))",
"legendFormat": "p99"
}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Очередь — ожидающие задания",
"description": "Устойчивый backlog в PostgreSQL включает задачи до publish и после publish, пока worker их не захватил.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(messenger_queue_depth)",
"legendFormat": "queued"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max(messenger_outbox_pending)",
"legendFormat": "не отправлено в RabbitMQ"
}
]
},
{
"id": 8,
"type": "timeseries",
"title": "Очередь — возраст старейшей job",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "max by (queue) (messenger_queue_oldest_age_seconds)",
"legendFormat": "{{queue}}"
}
]
},
{
"id": 9,
"type": "timeseries",
"title": "Время от 202 до ready",
"description": "От создания job в транзакции принятия до COMMIT готового вложения.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[2m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[2m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_ready_duration_seconds_bucket[2m])))",
"legendFormat": "p99"
}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Worker — занятые слоты",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(messenger_worker_busy) / sum(messenger_worker_capacity)",
"legendFormat": "busy / capacity"
}
]
},
{
"id": 11,
"type": "timeseries",
"title": "PostgreSQL — пул соединений",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name, state) (messenger_db_pool{state=~\"used|waiting|capacity\"})",
"legendFormat": "{{service_name}} {{state}}"
}
]
},
{
"id": 12,
"type": "timeseries",
"title": "CPU — ядра",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "cores"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name) (rate(messenger_process_cpu_seconds_total[1m]))",
"legendFormat": "процесс {{service_name}}"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name) (rate(messenger_container_cpu_seconds_total[1m]))",
"legendFormat": "контейнер {{service_name}}"
}
]
},
{
"id": 13,
"type": "timeseries",
"title": "RAM — процесс и контейнер",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name) (messenger_process_memory_bytes)",
"legendFormat": "RSS {{service_name}}"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum by (service_name) (messenger_container_memory_bytes)",
"legendFormat": "cgroup {{service_name}}"
}
]
},
{
"id": 14,
"type": "timeseries",
"title": "Алерты",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "ALERTS",
"legendFormat": "{{alertname}} {{alertstate}}"
}
]
},
{
"id": 15,
"type": "timeseries",
"title": "Collector — потери записей",
"description": "",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(increase(otelcol_exporter_send_failed_log_records_total[1m])) + sum(increase(otelcol_exporter_enqueue_failed_log_records_total[1m]))",
"legendFormat": "логи {{exporter}}"
},
{
"refId": "B",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "sum(increase(otelcol_exporter_send_failed_spans_total[1m])) + sum(increase(otelcol_exporter_enqueue_failed_spans_total[1m]))",
"legendFormat": "спаны {{exporter}}"
}
]
},
{
"id": 16,
"type": "timeseries",
"title": "Collector — память",
"description": "RSS процесса Collector. Лимит контейнера 256 MiB.",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"expr": "otelcol_process_memory_rss_bytes",
"legendFormat": "RSS"
}
]
},
{
"id": 17,
"type": "logs",
"title": "API, dispatcher и worker",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 64,
"w": 24,
"h": 12
},
"targets": [
{
"refId": "A",
"datasource": {
"type": "loki",
"uid": "loki"
},
"expr": "{service_name=~\"messenger-api|messenger-worker|messenger-dispatcher\"} | event=~\"http.response|job.processed|job.processing_error|postgres.unavailable\""
}
],
"options": {
"showTime": true,
"showLabels": true,
"enableLogDetails": true
}
}
]
}
@@ -0,0 +1,7 @@
apiVersion: 1
providers:
- name: Messenger
folder: Lab6
type: file
options:
path: /etc/grafana/dashboards
@@ -0,0 +1,39 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 2s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- 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
spanStartTimeShift: '-2m'
spanEndTimeShift: '2m'
filterByTraceID: true
tags:
- key: service.name
value: service_name
+39
View File
@@ -0,0 +1,39 @@
auth_enabled: false
server:
http_listen_port: 3100
analytics:
reporting_enabled: false
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
discover_log_levels: true
retention_period: 168h
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- action: index_label
attributes: [service.name, deployment.environment.name]
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
+4 -4
View File
@@ -1,7 +1,7 @@
# Конфигурация наблюдаемости — реализовать
# Наблюдаемость Messenger
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
API, dispatcher и worker отправляют метрики, логи и трассы по OTLP/HTTP в `otel-collector`. Collector отдаёт метрики на scrape Prometheus и отправляет логи в Loki, трассы в Tempo. Grafana получает все три источника и дашборд из `infra/grafana`.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Collector использует memory limiter и batch. Экспортёры Loki/Tempo имеют отдельные очереди и ограниченный повтор. Порты OTLP, Prometheus, Loki и Tempo доступны в сетях Compose. Grafana доступна только через loopback хоста на порту 3006.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Конфиги лежат в `infra/otel`, `infra/prometheus`, `infra/loki`, `infra/tempo`. Сценарии диагностики описаны в [runbook.md](runbook.md).
+72
View File
@@ -0,0 +1,72 @@
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
max_request_body_size: 4194304
processors:
memory_limiter:
check_interval: 1s
limit_mib: 160
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 128
send_batch_max_size: 128
exporters:
prometheus:
endpoint: 0.0.0.0:9464
metric_expiration: 30s
resource_to_telemetry_conversion:
enabled: true
otlp_http/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue:
num_consumers: 1
queue_size: 16
retry_on_failure:
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 8s
otlp_http/tempo:
endpoint: http://tempo:4318
timeout: 2s
sending_queue:
num_consumers: 1
queue_size: 16
retry_on_failure:
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 8s
service:
extensions: [health_check]
telemetry:
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/tempo]
+19
View File
@@ -0,0 +1,19 @@
# Диагностика стенда Lab6
Откройте дашборд **Messenger · наблюдаемость** в Grafana на порту 3006. В Explore доступны Prometheus, Loki и Tempo. Для перехода от HTTP-ответа к трассе возьмите `X-Trace-Id` и найдите Trace ID в Tempo. Связанный лог в Loki находится запросом `{service_name="messenger-api"} | trace_id="<id>"`. Для worker замените имя сервиса на `messenger-worker`.
## Queue lag
1. Проверьте `max(messenger_queue_oldest_age_seconds)`, `max(messenger_queue_depth)` и `max(messenger_outbox_pending)`.
2. Если возраст растёт, outbox пуст, а актуальный ряд `messenger_worker_capacity` исчез, проверяйте запущен ли worker. Если worker работает, сравните `messenger_worker_busy` с его capacity и разберите ошибки `job.processed` в Loki.
3. После запуска worker убедитесь, что глубина очереди вернулась к нулю, `MessengerQueueLag` снялся и вложение стало ready. В Tempo проследите publish, consume, запись S3 и фиксацию результата PostgreSQL.
## Error rate
1. Проверьте `messenger:http_error_ratio:30s` и разложите запросы по статусам и маршрутам. Алерт `MessengerHighErrorRate` реагирует на 5xx.
2. Откройте лог `{service_name="messenger-api"} | event="http.response" | status_code>=500` и перейдите в Tempo по Trace ID. Ошибка в спане `postgres.pool.acquire` или репозитории и событие `postgres.unavailable` в той же трассе указывают на PostgreSQL.
3. После восстановления проверьте успешную запись сообщения и дождитесь выхода 5xx из окна алерта.
## Экспорт телеметрии
Проверьте `otelcol_exporter_send_failed_log_records_total`, `otelcol_exporter_send_failed_spans_total`, `otelcol_exporter_queue_size` и `otelcol_process_memory_rss_bytes`. При недоступности Loki или Tempo возможна потеря пакетов после исчерпания очереди и времени повтора. После восстановления отправьте новый запрос и проверьте наличие лога и трассы. Сценарии воспроизводятся командой `make test-observability-incidents` на локальном стенде lab6.
+15
View File
@@ -0,0 +1,15 @@
global:
scrape_interval: 2s
scrape_timeout: 1s
evaluation_interval: 2s
rule_files:
- /etc/prometheus/rules.yaml
scrape_configs:
- job_name: messenger
static_configs:
- targets: [otel-collector:9464]
- job_name: collector
static_configs:
- targets: [otel-collector:8888]
+31
View File
@@ -0,0 +1,31 @@
groups:
- name: messenger
rules:
- record: messenger:http_error_ratio:30s
expr: |
(sum(rate(messenger_http_requests_total{status_class="5xx"}[30s])) or vector(0))
/ sum(rate(messenger_http_requests_total[30s]))
- record: messenger:http_availability:15m
expr: |
1 - (sum(increase(messenger_http_requests_total{status_class="5xx"}[15m])) or vector(0))
/ sum(increase(messenger_http_requests_total[15m]))
- alert: MessengerHighErrorRate
expr: messenger:http_error_ratio:30s > 0.05 and sum(increase(messenger_http_requests_total[30s])) >= 5
for: 6s
labels:
severity: warning
annotations:
summary: API возвращает более 5% ответов 5xx
description: За 30 секунд наблюдалось минимум 5 бизнес-запросов.
runbook: infra/otel/runbook.md#error-rate
- alert: MessengerQueueLag
expr: |
max(messenger_queue_oldest_age_seconds) > 10
and max(messenger_queue_depth) > 0
for: 6s
labels:
severity: warning
annotations:
summary: Старейшее ожидающее вложение в очереди более 10 секунд
description: Проверьте worker capacity, backlog и ожидающие события outbox.
runbook: infra/otel/runbook.md#queue-lag
+35
View File
@@ -0,0 +1,35 @@
server:
http_listen_port: 3200
usage_report:
reporting_enabled: false
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
metrics_generator:
storage:
path: /var/tempo/generator/wal
traces_storage:
path: /var/tempo/generator/traces
processor:
local_blocks:
filter_server_spans: false
flush_to_storage: true
overrides:
defaults:
metrics_generator:
processors: [local-blocks]
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks