ЛР6: OTel SDK, Collector, Prometheus/Loki/Tempo, Grafana, alerts, dashboard, тесты инцидентов

This commit is contained in:
2026-11-16 22:14:42 +03:00
commit e617ce2caa
87 changed files with 8695 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
+44
View File
@@ -0,0 +1,44 @@
groups:
- name: messenger-api
interval: 15s
rules:
# Доля 5xx среди бизнес-запросов (health исключён) > 5% за 2 минуты.
- alert: ApiHighErrorRate
expr: |
(
sum(rate(http_server_duration_milliseconds_count{
http_status_code=~"5..",
http_target!~"/health/.*"
}[2m]))
/
sum(rate(http_server_duration_milliseconds_count{
http_target!~"/health/.*"
}[2m]))
) > 0.05
for: 2m
labels:
severity: warning
annotations:
summary: "API error rate > 5% за 2 минуты"
description: "5xx доля бизнес-запросов превысила 5% в течение 2 минут."
runbook: "Проверить /api/v1 logs в Loki по trace_id из ошибки; проверить health БД/S3/broker."
- alert: QueueLagHigh
expr: messenger_queue_oldest_job_age_seconds > 60
for: 2m
labels:
severity: warning
annotations:
summary: "Очередь обработки отстаёт > 60s"
description: "Самая старая задача в queued старше 60 секунд."
runbook: "Проверить worker (docker compose ps worker, logs worker); проверить RabbitMQ; проверить S3/DB latency."
- alert: QueueLagCritical
expr: messenger_queue_oldest_job_age_seconds > 300
for: 1m
labels:
severity: critical
annotations:
summary: "Очередь обработки отстаёт > 5 минут"
description: "Обработка не продвигается; возможен отказ worker."
runbook: "Остановить worker → проверить логи; проверить RabbitMQ; replay failed."
+64
View File
@@ -0,0 +1,64 @@
{
"annotations": {"list": []},
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"links": [],
"panels": [
{"type":"row","title":"API HTTP","gridPos":{"h":1,"w":24,"x":0,"y":0},"collapsed":false,"panels":[]},
{"type":"timeseries","title":"RPS по route template","gridPos":{"h":8,"w":12,"x":0,"y":1},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"reqps","custom":{"drawStyle":"line","fillOpacity":10}},"overrides":[]},
"targets":[{"expr":"sum by (http_target) (rate(http_server_duration_milliseconds_count{http_target!~\"/health/.*\"}[1m]))","legendFormat":"{{http_target}}"}]},
{"type":"timeseries","title":"Error ratio (5xx / всё, health исключён)","gridPos":{"h":8,"w":12,"x":12,"y":1},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"percentunit","custom":{"drawStyle":"line","fillOpacity":10}},"overrides":[]},
"targets":[{"expr":"(sum(rate(http_server_duration_milliseconds_count{http_status_code=~\"5..\",http_target!~\"/health/.*\"}[2m])) or vector(0)) / sum(rate(http_server_duration_milliseconds_count{http_target!~\"/health/.*\"}[2m]))","legendFormat":"5xx ratio"}]},
{"type":"timeseries","title":"Latency p50/p95/p99 (API, ms)","gridPos":{"h":8,"w":24,"x":0,"y":9},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"ms","custom":{"drawStyle":"line","fillOpacity":0}},"overrides":[]},
"targets":[
{"expr":"histogram_quantile(0.50, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))","legendFormat":"p50"},
{"expr":"histogram_quantile(0.95, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))","legendFormat":"p95"},
{"expr":"histogram_quantile(0.99, sum by (le) (rate(http_server_duration_milliseconds_bucket{http_target!~\"/health/.*\"}[2m])))","legendFormat":"p99"}
]},
{"type":"row","title":"Worker / Queue","gridPos":{"h":1,"w":24,"x":0,"y":17},"collapsed":false,"panels":[]},
{"type":"timeseries","title":"Jobs по outcome (rate, 1m)","gridPos":{"h":8,"w":12,"x":0,"y":18},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"ops","custom":{"drawStyle":"line","fillOpacity":10}},"overrides":[]},
"targets":[{"expr":"sum by (outcome) (rate(messenger_jobs_processed_total[1m]))","legendFormat":"{{outcome}}"}]},
{"type":"timeseries","title":"Job processing duration p50/p95/p99 (s)","gridPos":{"h":8,"w":12,"x":12,"y":18},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"s","custom":{"drawStyle":"line","fillOpacity":0}},"overrides":[]},
"targets":[
{"expr":"histogram_quantile(0.50, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))","legendFormat":"p50"},
{"expr":"histogram_quantile(0.95, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))","legendFormat":"p95"},
{"expr":"histogram_quantile(0.99, sum by (le) (rate(messenger_job_processing_duration_seconds_bucket[5m])))","legendFormat":"p99"}
]},
{"type":"timeseries","title":"Queue depth (queued)","gridPos":{"h":8,"w":8,"x":0,"y":26},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"short","custom":{"drawStyle":"line","fillOpacity":10}},"overrides":[]},
"targets":[{"expr":"sum(messenger_queue_depth)","legendFormat":"depth"}]},
{"type":"timeseries","title":"Oldest job age (s)","gridPos":{"h":8,"w":8,"x":8,"y":26},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"s","custom":{"drawStyle":"line","fillOpacity":10},"thresholds":{"mode":"absolute","steps":[{"color":"green","value":null},{"color":"yellow","value":60},{"color":"red","value":300}]}},"overrides":[]},
"targets":[{"expr":"max(messenger_queue_oldest_job_age_seconds)","legendFormat":"oldest age"}]},
{"type":"timeseries","title":"Time to ready p50/p95 (s)","gridPos":{"h":8,"w":8,"x":16,"y":26},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"s","custom":{"drawStyle":"line","fillOpacity":0}},"overrides":[]},
"targets":[
{"expr":"histogram_quantile(0.50, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))","legendFormat":"p50"},
{"expr":"histogram_quantile(0.95, sum by (le) (rate(messenger_time_to_ready_seconds_bucket[5m])))","legendFormat":"p95"}
]},
{"type":"row","title":"Saturation","gridPos":{"h":1,"w":24,"x":0,"y":34},"collapsed":false,"panels":[]},
{"type":"timeseries","title":"Worker busy slots (capacity 2)","gridPos":{"h":8,"w":8,"x":0,"y":35},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"short","custom":{"drawStyle":"line","fillOpacity":10},"max":2},"overrides":[]},
"targets":[{"expr":"sum(messenger_worker_busy)","legendFormat":"busy"}]},
{"type":"timeseries","title":"DB pool (available / waiting)","gridPos":{"h":8,"w":8,"x":8,"y":35},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"short","custom":{"drawStyle":"line","fillOpacity":10}},"overrides":[]},
"targets":[{"expr":"sum by (state) (messenger_db_pool)","legendFormat":"{{state}}"}]},
{"type":"timeseries","title":"Active HTTP requests","gridPos":{"h":8,"w":8,"x":16,"y":35},"datasource":{"type":"prometheus","uid":"PBFA97CFB590B2093"},
"fieldConfig":{"defaults":{"unit":"short","custom":{"drawStyle":"line","fillOpacity":10}},"overrides":[]},
"targets":[{"expr":"sum(http_server_active_requests)","legendFormat":"active"}]}
],
"refresh": "10s",
"schemaVersion": 39,
"tags": ["messenger","lab6"],
"templating": {"list": []},
"time": {"from": "now-15m", "to": "now"},
"timezone": "browser",
"title": "Messenger — lab6",
"uid": "messenger-lab6"
}
@@ -0,0 +1,12 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,31 @@
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 10s
- name: Loki
type: loki
access: proxy
url: http://loki:3100
jsonData:
derivedFields:
- datasourceUid: tempo
matcherRegex: '"trace_id":"([a-f0-9]+)"'
name: TraceID
url: "$${__value.raw}"
- name: Tempo
type: tempo
access: proxy
url: http://tempo:3200
uid: tempo
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
serviceMap:
datasourceUid: prometheus
+38
View File
@@ -0,0 +1,38 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
log_level: warn
common:
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
instance_addr: 127.0.0.1
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
retention_period: 24h
reject_old_samples: false
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
+61
View File
@@ -0,0 +1,61 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
grpc:
endpoint: 0.0.0.0:4317
processors:
# Ограничивает RAM коллектора: если превысили — начинает отбрасывать данные,
# а не падает по OOM. Это требование lab6 уровня 4.
memory_limiter:
check_interval: 1s
limit_mib: 200
spike_limit_mib: 50
# Батчинг: уменьшает число запросов к backend.
batch:
timeout: 5s
send_batch_size: 1024
# Ограничивает кардинальность метрик: удаляет потенциально опасные атрибуты.
attributes/scrub:
actions:
- key: http.request.header.authorization
action: delete
- key: http.request.header.cookie
action: delete
exporters:
# Метрики — в формате Prometheus. Prometheus сам scrape'ит :8889.
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
# Логи — в Loki через OTLP endpoint (Loki 3.x умеет /otlp).
otlphttp/loki:
endpoint: http://loki:3100/otlp
tls:
insecure: true
# Трассы — в Tempo через OTLP gRPC.
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch, attributes/scrub]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch, attributes/scrub]
exporters: [otlphttp/loki]
telemetry:
logs:
level: info
+7
View File
@@ -0,0 +1,7 @@
# Конфигурация наблюдаемости — реализовать
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
+16
View File
@@ -0,0 +1,16 @@
global:
scrape_interval: 10s
evaluation_interval: 10s
rule_files:
- /etc/prometheus/alert-rules.yml
scrape_configs:
# Метрики от OTel Collector (он в формате Prometheus на :8889).
- job_name: otel-collector
static_configs:
- targets: ['otel-collector:8889']
# Сам Prometheus — для наблюдения за собой.
- job_name: prometheus
static_configs:
- targets: ['localhost:9090']
+35
View File
@@ -0,0 +1,35 @@
server:
http_listen_port: 3200
grpc_listen_port: 9095
log_level: warn
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 24h
storage:
trace:
backend: local
local:
path: /var/tempo/traces
wal:
path: /var/tempo/wal
metrics_generator:
registry:
external_labels:
source: tempo
storage:
path: /var/tempo/generator/wal