Собрать наблюдаемый стенд, чтобы причину деградации API и worker было видно по метрикам, логам и трассам.

This commit is contained in:
2026-11-07 01:36:19 +03:00
parent 470d9d6f1e
commit 7d4e1237a3
56 changed files with 4419 additions and 53 deletions
+18 -4
View File
@@ -1,7 +1,21 @@
# Инфраструктура студента
# Инфраструктура
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Топология — корневой `compose.yaml`. `compose.example.yaml` остаётся worksheet курса и не запускается.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
| Роль | Сервис | Образ | Порт на хосте | Том |
| --- | --- | --- | --- | --- |
| PostgreSQL | postgres | postgres:16.6-alpine | нет | pg-data |
| S3 | s3 | chrislusf/seaweedfs:4.51 | нет | s3-data, плюс gitignored `infra/seaweed/s3.json` |
| Брокер | rabbitmq | rabbitmq:3.13.7-management-alpine | нет | rabbit-data |
| API | api-1, api-2 | сборка из Dockerfile | нет | `./faults` |
| Worker | worker | та же сборка | нет | `./faults` |
| Балансировщик | nginx | nginx:1.27.4-alpine | 127.0.0.1:8080 | — |
| Collector | otel-collector | otel/opentelemetry-collector-contrib:0.120.0 | нет | — |
| Метрики | prometheus | prom/prometheus:v2.55.1 | 127.0.0.1:9090 | prometheus-data |
| Логи | loki | grafana/loki:3.3.2 | 127.0.0.1:3100 | loki-data |
| Трассы | tempo | grafana/tempo:2.7.2 | 127.0.0.1:3200 | tempo-data |
| UI | grafana | grafana/grafana:11.5.2 | 127.0.0.1:3000 | grafana-data |
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
Секреты приходят из `.env` (БД, S3, RabbitMQ, пароль Grafana). Идентичность SeaweedFS генерируется `python scripts/render-s3-config.py` и не коммитится. Схема БД — `app/schema.sql`. Бакет и очередь создают приложения при старте.
Grafana не хранит метрики, логи и трассы. Datasources и дашборд `messenger-overview` импортируются из `infra/grafana/provisioning` и `infra/grafana/dashboards`. Правила алертов — `infra/prometheus/rules.yml`.
+187
View File
@@ -0,0 +1,187 @@
{
"uid": "messenger-overview",
"title": "Messenger observability",
"timezone": "utc",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"tags": ["messenger", "lab6"],
"time": {"from": "now-1h", "to": "now"},
"panels": [
{
"id": 1,
"type": "text",
"title": "Signal stores",
"gridPos": {"h": 4, "w": 24, "x": 0, "y": 0},
"options": {
"mode": "markdown",
"content": "Prometheus stores metrics (rates, histograms, gauges). Loki stores structured logs. Tempo stores traces. The collector is not a database: it receives OTLP, redacts, batches, and exports. Grafana only queries those stores. Percentiles use `histogram_quantile` on cumulative buckets, summed across API replicas before the quantile."
}
},
{
"id": 2,
"type": "timeseries",
"title": "API RPS by route",
"description": "Unit: requests per second. Sum of rates across replicas.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 4},
"fieldConfig": {"defaults": {"unit": "reqps", "custom": {"drawStyle": "line"}}, "overrides": []},
"targets": [
{
"refId": "A",
"expr": "sum by (http_route) (rate(http_server_requests_total{service_name=\"messenger-api\"}[1m]))",
"legendFormat": "{{http_route}}"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "API error ratio (5xx / business)",
"description": "Unit: fraction 0-1. Numerator is status class 5xx. Denominator is business routes, excluding /health and unmatched. 4xx is not an error for this SLI.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 4},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"targets": [
{"refId": "A", "expr": "messenger:api_error_ratio:rate5m", "legendFormat": "5m"},
{"refId": "B", "expr": "messenger:api_error_ratio:rate1m", "legendFormat": "1m"}
]
},
{
"id": 4,
"type": "timeseries",
"title": "API duration p50/p95/p99",
"description": "Unit: seconds. histogram_quantile over the sum of bucket rates. Not an average of per-replica quantiles.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 12},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*|unmatched\"}[5m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*|unmatched\"}[5m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*|unmatched\"}[5m])))", "legendFormat": "p99"}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Jobs by outcome",
"description": "Unit: jobs per second. outcome is success, failed, or retry. job_type is attachment.process.v1.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 12},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))", "legendFormat": "{{outcome}}"}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Worker job duration p95",
"description": "Unit: seconds, from the job histogram.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 20},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_duration_seconds_bucket[5m])))", "legendFormat": "{{outcome}}"}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Queue depth and oldest age",
"description": "Depth is a count of queued+processing attachments. Age is seconds since the oldest of those rows was accepted. max() avoids double-counting the two API replicas.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 20},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": [{"matcher": {"id": "byName", "options": "age"}, "properties": [{"id": "unit", "value": "s"}]}]},
"targets": [
{"refId": "A", "expr": "max(messenger_queue_depth{queue=\"attachment.process.v1\"})", "legendFormat": "depth"},
{"refId": "B", "expr": "max(messenger_queue_oldest_age_seconds{queue=\"attachment.process.v1\"})", "legendFormat": "age"}
]
},
{
"id": 8,
"type": "timeseries",
"title": "Time to ready p95",
"description": "Unit: seconds from durable acceptance to ready. Completed jobs only.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 20},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[15m])))", "legendFormat": "p95"}
]
},
{
"id": 9,
"type": "timeseries",
"title": "DB pool used and waiting",
"description": "Unit: connections. Summed across processes. waiting is requests blocked on the pool.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 28},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "sum(messenger_db_pool_used)", "legendFormat": "used"},
{"refId": "B", "expr": "sum(messenger_db_pool_waiting)", "legendFormat": "waiting"}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Worker saturation and consumers",
"description": "busy/capacity are counts inside the worker. consumers is the RabbitMQ consumer count observed by the API.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 28},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max(messenger_worker_busy)", "legendFormat": "busy"},
{"refId": "B", "expr": "max(messenger_worker_capacity)", "legendFormat": "capacity"},
{"refId": "C", "expr": "max(messenger_worker_consumers{service_name=\"messenger-api\"})", "legendFormat": "consumers"}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Process CPU and memory",
"description": "CPU unit is process CPU-seconds per wall second (can exceed 1). Memory unit is bytes of RSS.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 28},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "max by (service_name) (messenger_process_cpu_utilization)", "legendFormat": "cpu {{service_name}}"},
{"refId": "B", "expr": "max by (service_name) (messenger_process_memory_bytes)", "legendFormat": "rss {{service_name}}"}
]
},
{
"id": 12,
"type": "timeseries",
"title": "DB duration p95",
"description": "Unit: seconds. Includes an injected db_slow fault. Compare with the server span to separate a slow database from a slow handler.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 36},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_db_duration_seconds_bucket[5m])))", "legendFormat": "db p95"}
]
},
{
"id": 13,
"type": "table",
"title": "Prometheus alert state",
"description": "Local firing/pending state. No external notification channel is configured.",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 36},
"targets": [
{"refId": "A", "expr": "ALERTS{alertstate=~\"firing|pending\"}", "instant": true, "format": "table"}
]
},
{
"id": 14,
"type": "logs",
"title": "API and worker logs",
"datasource": {"type": "loki", "uid": "loki"},
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 44},
"targets": [
{"refId": "A", "expr": "{service_name=~\"messenger-api|messenger-worker\"}"}
]
}
]
}
@@ -0,0 +1,12 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,41 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 5s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherRegex: "\"trace_id\":\"([0-9a-f]+)\""
url: "$${__value.raw}"
datasourceUid: tempo
urlDisplayLabel: View trace
- 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
lokiSearch:
datasourceUid: loki
+39
View File
@@ -0,0 +1,39 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
log_level: warn
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
volume_enabled: true
reject_old_samples: false
ingestion_rate_mb: 8
ingestion_burst_size_mb: 16
max_query_series: 500
analytics:
reporting_enabled: false
+22
View File
@@ -0,0 +1,22 @@
upstream messenger_api {
server api-1:8080 max_fails=1 fail_timeout=5s;
server api-2:8080 max_fails=1 fail_timeout=5s;
}
server {
listen 80;
client_max_body_size 12m;
proxy_http_version 1.1;
proxy_connect_timeout 1s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
proxy_next_upstream error timeout http_502 http_503 non_idempotent;
proxy_next_upstream_tries 2;
location / {
proxy_pass http://messenger_api;
proxy_set_header Host $host;
proxy_set_header Connection "";
}
}
+12 -4
View File
@@ -1,7 +1,15 @@
# Конфигурация наблюдаемости — реализовать
# Collector
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
`collector.yaml` принимает OTLP gRPC `:4317` и HTTP `:4318` только внутри сети Compose.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Процессоры на всех трёх pipeline: memory limiter (192 MiB, spike 48 MiB), удаление URL, SQL и заголовков Authorization/Cookie, batch.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Экспорт:
- трассы — OTLP gRPC в Tempo, очередь 200, retry не дольше 30 с;
- логи — OTLP HTTP в Loki `/otlp/v1/logs`, та же очередь и retry;
- метрики — Prometheus exporter `:8889`, его скрейпит Prometheus.
Внутренние метрики Collector — `:8888`. Health — `:13133`. Эти порты наружу не опубликованы.
Если Tempo или Loki недоступны, очередь exporter ограничена 200, retry обрывается через 30 с, memory limiter не даёт процессу расти до лимита контейнера 320 MiB. Приложение при этом отвечает: экспорт не блокирует приём сообщений.
+95
View File
@@ -0,0 +1,95 @@
extensions:
health_check:
endpoint: 0.0.0.0:13133
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
attributes/redact:
actions:
- key: url.full
action: delete
- key: url.query
action: delete
- key: url.path
action: delete
- key: http.url
action: delete
- key: http.target
action: delete
- key: db.statement
action: delete
- key: db.query.text
action: delete
- key: http.request.header.authorization
action: delete
- key: http.request.header.cookie
action: delete
batch:
timeout: 2s
send_batch_size: 256
send_batch_max_size: 512
exporters:
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 200
otlphttp/loki:
logs_endpoint: http://loki:3100/otlp/v1/logs
tls:
insecure: true
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 15s
max_elapsed_time: 30s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 200
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
metric_expiration: 180s
service:
extensions: [health_check]
telemetry:
metrics:
address: 0.0.0.0:8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlphttp/loki]
+15
View File
@@ -0,0 +1,15 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
scrape_timeout: 4s
rule_files:
- /etc/prometheus/rules.yml
scrape_configs:
- job_name: otel-collector
static_configs:
- targets: ["otel-collector:8889"]
- job_name: otel-collector-internal
static_configs:
- targets: ["otel-collector:8888"]
+96
View File
@@ -0,0 +1,96 @@
groups:
- name: messenger-sli
interval: 5s
rules:
- record: messenger:api_requests:rate1m
expr: sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*|unmatched"}[1m]))
- record: messenger:api_5xx:rate1m
expr: sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*|unmatched",http_response_status_class="5xx"}[1m]))
- record: messenger:api_error_ratio:rate1m
expr: messenger:api_5xx:rate1m / clamp_min(messenger:api_requests:rate1m, 1e-9)
- record: messenger:api_requests:rate5m
expr: sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*|unmatched"}[5m]))
- record: messenger:api_5xx:rate5m
expr: sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*|unmatched",http_response_status_class="5xx"}[5m]))
- record: messenger:api_error_ratio:rate5m
expr: messenger:api_5xx:rate5m / clamp_min(messenger:api_requests:rate5m, 1e-9)
- record: messenger:api_requests:rate15m
expr: sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*|unmatched"}[15m]))
- record: messenger:api_5xx:rate15m
expr: sum(rate(http_server_requests_total{service_name="messenger-api",http_route!~"/health/.*|unmatched",http_response_status_class="5xx"}[15m]))
- record: messenger:api_error_ratio:rate15m
expr: messenger:api_5xx:rate15m / clamp_min(messenger:api_requests:rate15m, 1e-9)
- name: messenger-alerts
interval: 5s
rules:
- alert: ApiHighErrorRate
expr: messenger:api_error_ratio:rate5m > 0.05 and messenger:api_requests:rate5m > 0.2
for: 1m
labels:
severity: page
slo: api-availability
annotations:
summary: API business 5xx ratio is above 5%
description: Numerator is 5xx on business routes. Denominator is all business requests. Health checks and 4xx are excluded. Window 5m, for 1m.
runbook: docs/runbooks/api-error-budget.md
- alert: ApiErrorBudgetFastBurn
expr: messenger:api_error_ratio:rate1m > 0.144 and messenger:api_error_ratio:rate5m > 0.144 and messenger:api_requests:rate1m > 0.2
for: 30s
labels:
severity: page
slo: api-availability
burn: fast
annotations:
summary: Fast multi-window burn of the 1% API error budget
description: Both the 1m and 5m error ratios exceed 14.4% (14.4x a 1% budget). A sub-minute spike does not satisfy the 5m window when healthy traffic is present.
runbook: docs/runbooks/api-error-budget.md
- alert: ApiErrorBudgetSlowBurn
expr: messenger:api_error_ratio:rate5m > 0.06 and messenger:api_error_ratio:rate15m > 0.06 and messenger:api_requests:rate5m > 0.2
for: 1m
labels:
severity: ticket
slo: api-availability
burn: slow
annotations:
summary: Slow multi-window burn of the API error budget
description: 5m and 15m error ratios exceed 6% (6x a 1% budget). This catches a long mild degradation that the fast burn may miss.
runbook: docs/runbooks/api-error-budget.md
- alert: QueueLagHigh
expr: max(messenger_queue_oldest_age_seconds{queue="attachment.process.v1"}) > 30
for: 1m
labels:
severity: page
slo: time-to-ready
annotations:
summary: Oldest attachment job is older than 30s
description: Backlog age is not processing latency. It grows when the worker is stopped or cannot finish jobs. Unit is seconds.
runbook: docs/runbooks/queue-lag.md
- alert: WorkerConsumersZero
expr: max(messenger_worker_consumers{service_name="messenger-api",queue="attachment.process.v1"}) == 0
for: 1m
labels:
severity: page
annotations:
summary: RabbitMQ has no attachment consumers
description: The API polls the RabbitMQ management API, so this series stays fresh after the worker process stops.
runbook: docs/runbooks/queue-lag.md
- alert: AttachmentReadyLatencyHigh
expr: histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[15m]))) > 10
for: 2m
labels:
severity: ticket
slo: time-to-ready
annotations:
summary: p95 time to ready is above 10s
description: Histogram of completed jobs only. A stalled queue does not move this SLO; use QueueLagHigh for that.
runbook: docs/runbooks/time-to-ready.md
- alert: DatabaseUnready
expr: min(messenger_db_up) == 0
for: 30s
labels:
severity: page
annotations:
summary: An API or worker process cannot use PostgreSQL
description: Distinguish this from a slow handler by comparing the db.transaction span with the server span.
runbook: docs/runbooks/db-latency.md
+9
View File
@@ -0,0 +1,9 @@
# SeaweedFS S3 identity
`s3.json` is generated locally and is not committed:
```
python scripts/render-s3-config.py
```
The script reads `S3_ACCESS_KEY` and `S3_SECRET_KEY` from `.env` and writes this directory's identity file. Compose mounts it read-only at `/etc/seaweed/s3.json`.
+34
View File
@@ -0,0 +1,34 @@
stream_over_http_enabled: true
server:
http_listen_port: 3200
grpc_listen_port: 9096
log_level: warn
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
ingester:
trace_idle_period: 10s
max_block_duration: 5m
compactor:
compaction:
block_retention: 48h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/traces
querier:
max_concurrent_queries: 4