forked from mtusi2026/mtusi2026lab7
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия: - внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial; - TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL), Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA; - OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь; - роли БД, S3-политики и права брокера по принципу минимальных прав; - Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS; - hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия; - отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
112 lines
6.6 KiB
YAML
112 lines
6.6 KiB
YAML
# Recording rules (SLI/SLO) and alert rules. Evaluated by Prometheus every 15 s; state (pending/firing/inactive)
|
|
# is visible in Prometheus /alerts, the API /api/v1/alerts and in Grafana (alert list panel). No external delivery.
|
|
# Runbooks: docs/runbooks.md (anchors in runbook_url).
|
|
#
|
|
# Label mapping (OTLP -> Prometheus 3): service.name -> service_name, service.instance.id -> instance,
|
|
# http.route -> http_route, http.response.status_code -> http_response_status_code, job.type -> job_type.
|
|
# HTTP SLI denominator: every business request of messenger-api (health probes are not instrumented).
|
|
# Numerator of errors: 5xx only. 4xx (wrong password, 404 of a foreign chat, 409) are client outcomes, not failures.
|
|
groups:
|
|
- name: messenger-sli
|
|
interval: 15s
|
|
rules:
|
|
- record: messenger:http_requests:rate2m
|
|
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))
|
|
- record: messenger:http_errors_5xx:rate2m
|
|
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[2m])) or vector(0)
|
|
- record: messenger:http_error_ratio:rate2m
|
|
expr: messenger:http_errors_5xx:rate2m / messenger:http_requests:rate2m
|
|
- record: messenger:http_latency_p95:rate5m
|
|
expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api"}[5m])))
|
|
# SLO window: rolling 30 min (lab-sized; production would use 28-30 days with the same formulas).
|
|
# Availability SLO: 99% of business requests without 5xx.
|
|
- record: messenger:slo_availability:ratio30m
|
|
expr: |
|
|
1 - (
|
|
(sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[30m])) or vector(0))
|
|
/ sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api"}[30m]))
|
|
)
|
|
# Latency SLO: 95% of business requests complete in <= 500 ms (bucket le="0.5").
|
|
- record: messenger:slo_latency:ratio30m
|
|
expr: |
|
|
sum(increase(http_server_request_duration_seconds_bucket{service_name="messenger-api",le="0.5"}[30m]))
|
|
/ sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api"}[30m]))
|
|
- record: messenger:worker_saturation:ratio
|
|
# OTLP-pushed series have no staleness markers: a recreated worker would stay in the denominator for the
|
|
# 5 min lookback. Only samples fresher than 30 s (3 export intervals) are counted.
|
|
expr: |
|
|
sum(messenger_worker_busy and (time() - timestamp(messenger_worker_busy) < 30))
|
|
/ sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 30))
|
|
|
|
- name: messenger-alerts
|
|
rules:
|
|
- alert: MessengerApiHighErrorRate
|
|
expr: messenger:http_error_ratio:rate2m > 0.05 and messenger:http_requests:rate2m > 0.2
|
|
for: 1m
|
|
labels:
|
|
severity: page
|
|
annotations:
|
|
summary: "API: доля 5xx {{ $value | humanizePercentage }} за 2 мин (порог 5%)"
|
|
description: "Больше 5% бизнес-запросов messenger-api завершаются 5xx (окно 2m, держится 1m). Расходуется бюджет SLO доступности 99%."
|
|
runbook_url: "docs/runbooks.md#messengerapihigherrorrate"
|
|
|
|
- alert: MessengerQueueLagGrowing
|
|
expr: max(messenger_queue_oldest_age_seconds{queue="attachments.process"}) > 60
|
|
for: 1m
|
|
labels:
|
|
severity: page
|
|
annotations:
|
|
summary: "Очередь вложений: старейшее задание ждёт {{ $value | humanizeDuration }}"
|
|
description: "Принятое задание не завершено дольше 60 с (порог), условие держится 1m: worker остановлен, перегружен или не может писать в S3/DB."
|
|
runbook_url: "docs/runbooks.md#messengerqueuelaggrowing"
|
|
|
|
- alert: MessengerApiLatencyHigh
|
|
expr: messenger:http_latency_p95:rate5m > 1
|
|
for: 2m
|
|
labels:
|
|
severity: ticket
|
|
annotations:
|
|
summary: "API p95 = {{ $value | humanizeDuration }} (порог 1 s, окно 5m)"
|
|
description: "p95 из histogram buckets всех реплик выше 1 s."
|
|
runbook_url: "docs/runbooks.md#messengerapilatencyhigh"
|
|
|
|
- alert: MessengerDbPoolWaiting
|
|
expr: max(db_client_connection_pending_requests) > 0
|
|
for: 1m
|
|
labels:
|
|
severity: ticket
|
|
annotations:
|
|
summary: "Запросы ждут соединение из пула БД ({{ $value }} в очереди)"
|
|
description: "Пул psycopg исчерпан дольше минуты: БД медленная/блокирована или пул мал."
|
|
runbook_url: "docs/runbooks.md#messengerdbpoolwaiting"
|
|
|
|
- alert: MessengerWorkerSaturated
|
|
expr: messenger:worker_saturation:ratio > 0.9
|
|
for: 5m
|
|
labels:
|
|
severity: ticket
|
|
annotations:
|
|
summary: "Worker занят на {{ $value | humanizePercentage }} ёмкости 5 минут"
|
|
runbook_url: "docs/runbooks.md#messengerworkersaturated"
|
|
|
|
- alert: TelemetryExportFailing
|
|
# Each term has "or vector(0)": the *_failed_* series do not exist until the first failure, and a sum with an
|
|
# empty operand is empty (the alert would never fire). Early signal: exporter queue filling up (backend
|
|
# down, retries in progress); late signal: data dropped (queue full) or retries exhausted.
|
|
expr: |
|
|
(
|
|
(sum(rate(otelcol_exporter_send_failed_spans_total[2m])) or vector(0))
|
|
+ (sum(rate(otelcol_exporter_send_failed_log_records_total[2m])) or vector(0))
|
|
+ (sum(rate(otelcol_exporter_enqueue_failed_spans_total[2m])) or vector(0))
|
|
+ (sum(rate(otelcol_exporter_enqueue_failed_log_records_total[2m])) or vector(0))
|
|
) > 0
|
|
or
|
|
max(max by (exporter) (otelcol_exporter_queue_size) / max by (exporter) (otelcol_exporter_queue_capacity)) > 0.2
|
|
for: 1m
|
|
labels:
|
|
severity: ticket
|
|
annotations:
|
|
summary: "Collector не может доставить telemetry в backend"
|
|
description: "Очередь exporter заполнена >20% или данные отбрасываются: Tempo/Loki/Prometheus недоступен. Бизнес-API не затронут, RAM collector ограничена очередью и memory_limiter."
|
|
runbook_url: "docs/runbooks.md#telemetryexportfailing"
|