forked from mtusi2026/mtusi2026lab7
chore: port lab 6 solution into the lab 7 skeleton
Source: mtusi2026lab6-safronov, solution/bvt2301-safronov, 6c6a065. Files follow AGENTS.md, "Переход в следующую лабу". Contracts, public tests, README, REPORT and evidence of lab 6 are not carried over; infra and scripts of the lab 7 skeleton stay as they are. Makefile is the lab 6 one with the lab 7 skeleton part restored (HTTPS BASE_URL on 8443, test-security); .gitignore and .dockerignore are taken from lab 6 because both skeletons have the same files; .env.example is the lab 6 one without changes. The compose project, image and CI prefix are renamed to lab7, and references to the previous lab now name lab6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,171 @@
|
||||
# Балансировщик стенда (с лабы 3): единственная точка входа перед репликами
|
||||
# сервиса api. Правила — .claude/rules/balancer.md, решения — design
|
||||
# change replicas-lb (решения 1–5) и graceful-failover (цепочка таймаутов,
|
||||
# решения 1–3). Порт приходит переменной окружения API_PORT (= APP__PORT
|
||||
# из .env); секретов LB не получает. Тот же файл использует стенд bench/.
|
||||
|
||||
global
|
||||
# журнал — в stdout контейнера (docker compose logs haproxy)
|
||||
log stdout format raw local0 info
|
||||
maxconn 4096
|
||||
# один поток на лимит 1 CPU: иначе HAProxy создал бы поток на каждый
|
||||
# CPU ВМ и делил между ними одну квоту
|
||||
nbthread 1
|
||||
# runtime API для поочерёдной замены (scripts/rolling-update.sh):
|
||||
# слот уходящей реплики — drain, maint, затем снова ready. Только
|
||||
# loopback внутри контейнера LB: из сети compose и с хоста не
|
||||
# достать, доступ — docker compose exec haproxy (bash /dev/tcp).
|
||||
# Решение 2 design change rolling-update
|
||||
stats socket ipv4@127.0.0.1:9999 level admin
|
||||
# буфер отправки к реплике фиксирован (256 KiB): тело загрузки, которое
|
||||
# реплика не читает (ожидание места, отказ до тела), не копится в
|
||||
# памяти LB целиком (design change upload-memory, решение 6)
|
||||
tune.sndbuf.server 262144
|
||||
# буфер приёма от клиента тоже фиксирован (128 KiB, в ядре — до
|
||||
# 256 KiB на сокет): без него ядро растило его до tcp_rmem ВМ (32 MiB),
|
||||
# и тело, которое LB не может отдать реплике, копилось там — до 9 MiB
|
||||
# на сокет клиента, sock LB до 112 MiB при 40 загрузках по 10 MiB.
|
||||
# Окно 128 KiB даёт ~20 Мбит/с при RTT 50 мс: 10 MiB — за ~4 с, срок
|
||||
# тела 30 с (design change upload-memory, «Уточнения apply», п. 11)
|
||||
tune.rcvbuf.client 131072
|
||||
|
||||
# DNS Docker: имя сервиса api отвечает адресами всех работающих реплик.
|
||||
# Пропавший адрес уходит из слота, новый появляется за 1–2 с без
|
||||
# перезагрузки LB
|
||||
resolvers docker
|
||||
nameserver dns 127.0.0.11:53
|
||||
accepted_payload_size 8192
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold obsolete 1s
|
||||
hold nx 1s
|
||||
hold other 1s
|
||||
hold refused 1s
|
||||
hold timeout 1s
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
# обычные успешные запросы не пишутся; ошибки, таймауты, повторы,
|
||||
# перенаправления и смена состояния реплик — пишутся
|
||||
option dontlog-normal
|
||||
# timeout connect × (retries + 1) = 0,5 × 3 = 1,5 с < 2 с таймаута
|
||||
# клиента tests/resilience.py: перенаправление успевает раньше
|
||||
timeout connect 500ms
|
||||
retries 2
|
||||
# каждый повтор — на другую реплику, а не на ту же
|
||||
option redispatch 1
|
||||
# повтор только если соединение не установлено: запрос до реплики не
|
||||
# дошёл, повтор безопасен для любого метода. Ответ, который реплика
|
||||
# уже начала, не повторяется: POST /users и POST /chats не
|
||||
# идемпотентны, отправку сообщения повторяет клиент с тем же ключом
|
||||
retry-on conn-failure
|
||||
# больше [database] request_timeout_seconds (6 с) и KDF входа; у пути
|
||||
# загрузки вложения — 30 с (backend api, http-request set-timeout)
|
||||
timeout server 10s
|
||||
timeout client 30s
|
||||
timeout http-request 10s
|
||||
# простаивающий сеанс клиента, а с ним и соединение с репликой
|
||||
# (http-reuse never): меньше [app] keep_alive_seconds реплики (60 с)
|
||||
timeout http-keep-alive 10s
|
||||
# больше таймаута проверки внутри /health/ready (2 с) на 0,5 с:
|
||||
# медленный PostgreSQL даёт 503 от реплики (L7STS), а не таймаут
|
||||
# проверки. Худшее обнаружение — в комментарии backend api
|
||||
timeout check 2500ms
|
||||
# request_id ответов, которые создаёт сам LB
|
||||
unique-id-format lb-%{+X}o%ci%cp%Ts%rt%pid
|
||||
# ответы самого LB — в формате ошибки контракта; в перечислении кодов
|
||||
# контракта нет отдельных кодов для 502 и 504, ближайший — unavailable.
|
||||
# X-Instance-Id у них нет: контракт это допускает. 400 — неверный запрос
|
||||
# или клиент замолчал посреди тела дольше timeout client (change
|
||||
# upload-memory). 408 на медленные заголовки HAProxy строит до потока
|
||||
# запроса, http-error его не меняет (KNOWN_ISSUES.md)
|
||||
http-error status 400 content-type application/json lf-string '{"error":{"code":"invalid_request","message":"Invalid request","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
|
||||
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"API replica closed the connection","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
|
||||
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"No API replica is available","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
|
||||
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"API replica did not respond in time","request_id":"%[unique-id]"}}' hdr X-Request-Id "%[unique-id]"
|
||||
|
||||
# точка входа клиентов: на хосте — 127.0.0.1:APP_OUT_PORT (compose)
|
||||
frontend entry
|
||||
bind "*:${API_PORT}"
|
||||
default_backend api
|
||||
|
||||
backend api
|
||||
# по очереди, без cookie и stick-table: sticky session запрещён
|
||||
balance roundrobin
|
||||
# путь загрузки вложения (design change upload-memory, решение 7): срок
|
||||
# ответа реплики 30 с вместо 10, больше самого долгого молчания живой
|
||||
# загрузки:
|
||||
# до тела — 2 × [database] request_timeout_seconds (вход, членство) +
|
||||
# [uploads] wait_timeout_seconds = 2 × 6 + 5 = 17 с;
|
||||
# после тела — проверка (до ~4 с) + pending 6 + PUT 5 + queued 6 = 21 с,
|
||||
# а ветка компенсации после неудачной фиксации queued — ещё DELETE 5,
|
||||
# 26 с: брокера в пути нет (design change pipeline-reliability, решение
|
||||
# 11).
|
||||
# Тело ограничивают [uploads] body_timeout_seconds (30 с) и timeout
|
||||
# client; наибольшая длительность загрузки 17 + 30 + 26 ≈ 73 с <
|
||||
# ROLLOUT_DRAIN_TIMEOUT (90 с, scripts/rolling-update.sh). Остальные
|
||||
# пути — прежние 10 с. Выражение — путь ручки в API
|
||||
# (src/api/routers/v1/attachment.py): при смене префикса менять вместе
|
||||
http-request set-timeout server 30s if METH_POST { path_reg ^/api/v1/chats/[^/]+/attachments$ }
|
||||
# соединение с репликой не переходит в общий пул и не отдаётся другому
|
||||
# клиенту: оно живёт, пока жив сеанс клиента, а простаивающий сеанс LB
|
||||
# закрывает по timeout http-keep-alive (10 с). uvicorn держит
|
||||
# простаивающее соединение [app] keep_alive_seconds = 60 с, дольше —
|
||||
# значит, закрывает LB, и запрос не уходит в соединение, которое
|
||||
# реплика в этот момент закрывает (ответа не было бы, а empty-response
|
||||
# LB не повторяет). С пулом (http-reuse safe) последнее простаивающее
|
||||
# соединение LB держал, пока его не закрывала реплика. Гонку при
|
||||
# SIGTERM (uvicorn сразу закрывает простаивающие соединения) не убирает
|
||||
# ни один режим: одиночный 502 в части фаз stop под нагрузкой (design
|
||||
# change graceful-failover, решение 3; evidence/failover/keep-alive.md).
|
||||
# Плановую остановку scripts/rolling-update.sh делает после вывода
|
||||
# реплики из LB (drain через runtime API в global) — без этой гонки
|
||||
http-reuse never
|
||||
# активная проверка готовности: /health/live для LB не годится,
|
||||
# живой процесс без PostgreSQL запросы не обслуживает
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready
|
||||
http-check expect status 200
|
||||
# реплика исключается после 2 неудачных проверок подряд и
|
||||
# возвращается после 2 успешных; проверка раз в секунду (inter, у
|
||||
# исключённой — downinter = inter), а после первой неудачи и до
|
||||
# возврата — через fastinter. Следующая проверка начинается через
|
||||
# интервал после конца предыдущей, поэтому худшее обнаружение:
|
||||
# зависшая (соединение есть, ответа нет): inter + timeout check +
|
||||
# (fall − 1) × (fastinter + timeout check) = 1 + 2,5 + 0,5 + 2,5
|
||||
# = 6,5 с ≤ 10 с;
|
||||
# адрес пропал (stop после выхода, kill): таймаут соединения
|
||||
# проверки min(timeout connect, inter) = 0,5 с: 1 + 0,5 + 0,5 +
|
||||
# 0,5 = 2,5 с; DNS уводит слот в обслуживание за 1–2 с;
|
||||
# сокет закрыт, адрес жив (окно graceful): 1 + 0,5 = 1,5 с.
|
||||
# Возврат: ≤ downinter + fastinter = 1,5 с после готовности.
|
||||
# init-state down: слот, получивший адрес из DNS (старт LB, новая или
|
||||
# вернувшаяся реплика), начинает DOWN и получает запросы только после
|
||||
# rise проверок, а не сразу — иначе запросы шли бы на процесс, который
|
||||
# ещё не слушает порт
|
||||
default-server check inter 1s fastinter 500ms fall 2 rise 2 resolvers docker init-addr none init-state down resolve-prefer ipv4
|
||||
# 8 слотов — максимум реплик в сериях трека 1; лишние слоты в MAINT,
|
||||
# девятую реплику LB не увидит
|
||||
server-template api- 8 "api:${API_PORT}"
|
||||
|
||||
# мониторинг внутри сети compose, наружу не публикуется:
|
||||
# /lb/ready — healthcheck контейнера LB (200, пока есть готовая реплика),
|
||||
# /stats и /stats;csv — состояние и счётчики каждой реплики (make lb_stats),
|
||||
# /metrics — метрики Prometheus встроенного экспортёра (design change
|
||||
# slo-alerts, решение 2): ответы frontend entry по классам, в том числе 502,
|
||||
# 503 и 504 самого LB, ответы backend и число готовых реплик. Забирает их
|
||||
# только Collector (приёмник prometheus/haproxy, scope frontend и backend):
|
||||
# LB не входит в сеть хранилищ, Prometheus — в сеть приложения
|
||||
frontend monitor
|
||||
bind :8404
|
||||
monitor-uri /lb/ready
|
||||
monitor fail if { nbsrv(api) lt 1 }
|
||||
http-request use-service prometheus-exporter if { path /metrics }
|
||||
stats enable
|
||||
stats uri /stats
|
||||
# адрес реплики в статистике (поле addr): только внутри сети
|
||||
stats show-legends
|
||||
@@ -0,0 +1,134 @@
|
||||
# OTel Collector contrib 0.164.0 (design change otel-telemetry, решения 1, 3,
|
||||
# 14): получатель, обработчик и экспортёр, не хранилище. Три pipeline — каждый
|
||||
# до своего хранилища: метрики — scrape Prometheus с экспортёра prometheus,
|
||||
# логи — Loki (родной OTLP), трассы — Tempo. Расширений нет (pprof, zpages,
|
||||
# health_check образа не берутся). Порты наружу не публикуются: OTLP
|
||||
# слушает сеть приложения, :8888 и :8889 забирает Prometheus в сети
|
||||
# telemetry. Буферизация, повторы, метрики LB и срок рядов — design change
|
||||
# slo-alerts, решения 2, 6, 7.
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
# только OTLP/HTTP: SDK приложения отправляет protobuf по HTTP
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
# метрики LB (решение 2): встроенный экспортёр HAProxy на порту статистики
|
||||
# в сети приложения. LB не входит в сеть хранилищ, Prometheus — в сеть
|
||||
# приложения: метрики идут через Collector, как метрики API. Только уровни
|
||||
# frontend и backend (без рядов по слотам и адресов реплик) и отобранные
|
||||
# имена; на экспортёре — job = haproxy, instance = haproxy:8404, плюс up
|
||||
prometheus/haproxy:
|
||||
config:
|
||||
scrape_configs:
|
||||
- job_name: haproxy
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
metrics_path: /metrics
|
||||
params:
|
||||
scope: [frontend, backend]
|
||||
static_configs:
|
||||
- targets: ["haproxy:8404"]
|
||||
metric_relabel_configs:
|
||||
- source_labels: [__name__]
|
||||
action: keep
|
||||
regex: haproxy_(frontend_http_requests_total|frontend_http_responses_total|backend_http_responses_total|backend_active_servers|backend_connection_errors_total|backend_response_errors_total|backend_retry_warnings_total|backend_redispatch_warnings_total)
|
||||
|
||||
processors:
|
||||
# предел памяти Collector: при 200 МиБ отказ приёма (SDK получает ошибку и
|
||||
# теряет пакет, otelcol_receiver_refused_*), всплеск — 40 МиБ; GOMEMLIMIT
|
||||
# контейнера — 160 МиБ. Худший случай очередей экспорта (обе полны, 24 МиБ
|
||||
# protobuf ≈ 50–75 МиБ в памяти) + основа ~50 МиБ — ниже мягкого предела
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 200
|
||||
spike_limit_mib: 40
|
||||
# пакеты трасс и метрик: не больше 1024 элементов или раз в секунду; пакет
|
||||
# span (≤ 1 МиБ) меньше очереди экспорта Tempo — больший отклоняется целиком
|
||||
batch:
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 1024
|
||||
timeout: 1s
|
||||
# пакеты журнала — не больше 256 записей: запись до 32 КиБ (traceback), и
|
||||
# пакет (≤ 8 МиБ) всегда помещается в очередь экспорта Loki (16 МиБ)
|
||||
batch/logs:
|
||||
send_batch_size: 256
|
||||
send_batch_max_size: 256
|
||||
timeout: 1s
|
||||
|
||||
exporters:
|
||||
# метрики приложения для scrape Prometheus (honor_labels): job =
|
||||
# service.name, instance = service.instance.id, остальной ресурс —
|
||||
# target_info. Ряд, не обновлявшийся минуту (четыре интервала отправки SDK
|
||||
# 15 с), уходит (решение 6): у процесса, запущенного позже, время начала
|
||||
# ряда новее последней точки, и Prometheus пишет ноль — increase() видит и
|
||||
# сброс, и первые события; снимок очереди остановленного relay уходит через
|
||||
# ≤ 75 с, а не 5 мин
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
translation_strategy: UnderscoreEscapingWithSuffixes
|
||||
metric_expiration: 1m
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: false
|
||||
# очередь в памяти с пределом в байтах и повторы с пределом времени
|
||||
# (решение 7): полная очередь отклоняет новое (enqueue_failed), не задерживая
|
||||
# приём; пакет с истёкшими 30 с повторов отбрасывается (send_failed).
|
||||
# Рестарт хранилища на стенде — 5–15 с: короткий отказ потерь не даёт
|
||||
otlp_http/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
sizer: bytes
|
||||
# 16 МиБ записей — ~40–90 с пика (379 записей/с)
|
||||
queue_size: 16777216
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
otlp_http/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
timeout: 5s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
sizer: bytes
|
||||
# 8 МиБ span — ~10–15 с пика (1127 span/с) и минуты обычного трафика
|
||||
queue_size: 8388608
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
encoding: json
|
||||
# собственные метрики Collector — для Prometheus (жив ли конвейер, очереди
|
||||
# экспорта и потери: otelcol_exporter_*, otelcol_receiver_refused_*)
|
||||
metrics:
|
||||
level: normal
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp, prometheus/haproxy]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch/logs]
|
||||
exporters: [otlp_http/loki]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_http/tempo]
|
||||
@@ -0,0 +1,17 @@
|
||||
# Провайдер dashboard из файлов (design change otel-telemetry, решение 16):
|
||||
# JSON из git, правки из интерфейса не сохраняются, удалить нельзя. Каталог
|
||||
# /etc/grafana/dashboards — bind mount файла dashboard (только чтение).
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: Messenger
|
||||
folderUid: messenger
|
||||
type: file
|
||||
disableDeletion: true
|
||||
allowUiUpdates: false
|
||||
updateIntervalSeconds: 60
|
||||
options:
|
||||
path: /etc/grafana/dashboards
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,896 @@
|
||||
{
|
||||
"uid": "messenger-overview",
|
||||
"title": "Messenger overview",
|
||||
"description": "Signals of contracts/observability.md, levels 3 and 4: SLI, SLO and error budget, alert windows and alert states, API RPS, errors and duration, worker jobs and duration, queue depth and age, time to ready, PostgreSQL pools, worker and container saturation, load balancer responses and ready replicas, telemetry pipeline queues and losses, logs and traces (design changes otel-telemetry, decision 16, job-trace-propagation, decision 14, and slo-alerts, decision 10). Provisioned from git, UI changes are not saved.",
|
||||
"tags": ["messenger", "lab6"],
|
||||
"timezone": "utc",
|
||||
"editable": false,
|
||||
"graphTooltip": 1,
|
||||
"schemaVersion": 39,
|
||||
"version": 3,
|
||||
"refresh": "30s",
|
||||
"time": {"from": "now-1h", "to": "now"},
|
||||
"annotations": {"list": []},
|
||||
"templating": {"list": []},
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"id": 25,
|
||||
"type": "row",
|
||||
"title": "SLO and alerts",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 0},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 26,
|
||||
"type": "stat",
|
||||
"title": "SLI over 7 days",
|
||||
"description": "Sums of 5-minute increments of the recording rules (group messenger-slo) over the SLO window of 7 days. Availability: responses of the public LB frontend without 5xx (SLO 99.5 %); latency: light API requests without 5xx not longer than 0.25 s (SLO 99 %); time to ready: attachments ready without replay within 30 s (SLO 99 %).",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 6, "w": 8, "x": 0, "y": 1},
|
||||
"fieldConfig": {
|
||||
"defaults": {"unit": "percentunit", "decimals": 3, "min": 0, "max": 1, "color": {"mode": "thresholds"}, "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.99}]}},
|
||||
"overrides": [
|
||||
{"matcher": {"id": "byFrameRefID", "options": "A"}, "properties": [{"id": "thresholds", "value": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.995}]}}]}
|
||||
]
|
||||
},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": false}, "orientation": "vertical", "textMode": "value_and_name", "colorMode": "value", "graphMode": "none", "justifyMode": "auto"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "1 - sum_over_time(messenger:slo_availability_bad:increase5m[7d]) / sum_over_time(messenger:slo_availability_total:increase5m[7d])",
|
||||
"legendFormat": "availability (SLO 99.5 %)",
|
||||
"instant": true
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum_over_time(messenger:slo_latency_good:increase5m[7d]) / sum_over_time(messenger:slo_latency_total:increase5m[7d])",
|
||||
"legendFormat": "latency ≤ 0.25 s (SLO 99 %)",
|
||||
"instant": true
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum_over_time(messenger:slo_time_to_ready_good:increase5m[7d]) / sum_over_time(messenger:slo_time_to_ready_total:increase5m[7d])",
|
||||
"legendFormat": "time to ready ≤ 30 s (SLO 99 %)",
|
||||
"instant": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 27,
|
||||
"type": "stat",
|
||||
"title": "Error budget left over 7 days",
|
||||
"description": "(SLI − SLO) / (1 − SLO) over 7 days: 100 % — no bad events, 0 — the budget is spent, below zero — the SLO is violated.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 6, "w": 8, "x": 8, "y": 1},
|
||||
"fieldConfig": {
|
||||
"defaults": {"unit": "percentunit", "decimals": 1, "color": {"mode": "thresholds"}, "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "orange", "value": 0}, {"color": "green", "value": 0.25}]}},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": false}, "orientation": "vertical", "textMode": "value_and_name", "colorMode": "value", "graphMode": "none", "justifyMode": "auto"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "((1 - sum_over_time(messenger:slo_availability_bad:increase5m[7d]) / sum_over_time(messenger:slo_availability_total:increase5m[7d])) - 0.995) / (1 - 0.995)",
|
||||
"legendFormat": "availability",
|
||||
"instant": true
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "(sum_over_time(messenger:slo_latency_good:increase5m[7d]) / sum_over_time(messenger:slo_latency_total:increase5m[7d]) - 0.99) / (1 - 0.99)",
|
||||
"legendFormat": "latency",
|
||||
"instant": true
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "(sum_over_time(messenger:slo_time_to_ready_good:increase5m[7d]) / sum_over_time(messenger:slo_time_to_ready_total:increase5m[7d]) - 0.99) / (1 - 0.99)",
|
||||
"legendFormat": "time to ready",
|
||||
"instant": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 28,
|
||||
"type": "stat",
|
||||
"title": "SLI over the dashboard range",
|
||||
"description": "The same SLI over the selected time range: how much an incident or a drill spent.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 6, "w": 8, "x": 16, "y": 1},
|
||||
"fieldConfig": {
|
||||
"defaults": {"unit": "percentunit", "decimals": 3, "min": 0, "max": 1, "color": {"mode": "thresholds"}, "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.99}]}},
|
||||
"overrides": [
|
||||
{"matcher": {"id": "byFrameRefID", "options": "A"}, "properties": [{"id": "thresholds", "value": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.995}]}}]}
|
||||
]
|
||||
},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"], "fields": "", "values": false}, "orientation": "vertical", "textMode": "value_and_name", "colorMode": "value", "graphMode": "none", "justifyMode": "auto"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "1 - sum_over_time(messenger:slo_availability_bad:increase5m[$__range]) / sum_over_time(messenger:slo_availability_total:increase5m[$__range])",
|
||||
"legendFormat": "availability",
|
||||
"instant": true
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum_over_time(messenger:slo_latency_good:increase5m[$__range]) / sum_over_time(messenger:slo_latency_total:increase5m[$__range])",
|
||||
"legendFormat": "latency",
|
||||
"instant": true
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum_over_time(messenger:slo_time_to_ready_good:increase5m[$__range]) / sum_over_time(messenger:slo_time_to_ready_total:increase5m[$__range])",
|
||||
"legendFormat": "time to ready",
|
||||
"instant": true
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 29,
|
||||
"type": "timeseries",
|
||||
"title": "Alert windows: 5xx share on LB and slow light requests (2 min)",
|
||||
"description": "Recording rules of MessengerHighErrorRate (threshold 5 %) and MessengerSlowRequests (threshold 10 %); both also need more than 0.1 request per second.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 7},
|
||||
"fieldConfig": {
|
||||
"defaults": {"unit": "percentunit", "min": 0},
|
||||
"overrides": [
|
||||
{"matcher": {"id": "byFrameRefID", "options": "C"}, "properties": [{"id": "custom.lineStyle", "value": {"fill": "dash", "dash": [10, 10]}}, {"id": "color", "value": {"mode": "fixed", "fixedColor": "red"}}]},
|
||||
{"matcher": {"id": "byFrameRefID", "options": "D"}, "properties": [{"id": "custom.lineStyle", "value": {"fill": "dash", "dash": [10, 10]}}, {"id": "color", "value": {"mode": "fixed", "fixedColor": "orange"}}]}
|
||||
]
|
||||
},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "messenger:lb_http_errors:ratio_rate2m",
|
||||
"legendFormat": "5xx on LB"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "messenger:http_light_slow:ratio_rate2m",
|
||||
"legendFormat": "slow light requests"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "vector(0.05)",
|
||||
"legendFormat": "5xx threshold"
|
||||
},
|
||||
{
|
||||
"refId": "D",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "vector(0.1)",
|
||||
"legendFormat": "slow threshold"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 30,
|
||||
"type": "state-timeline",
|
||||
"title": "Alert states (1 — pending, 2 — firing)",
|
||||
"description": "History of the series ALERTS over the retention of Prometheus (7 days): intervals of pending and firing by alert; 0 — no active alerts.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 7},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"color": {"mode": "thresholds"},
|
||||
"thresholds": {"mode": "absolute", "steps": [{"color": "green", "value": null}, {"color": "yellow", "value": 1}, {"color": "red", "value": 2}]},
|
||||
"mappings": [{"type": "value", "options": {"0": {"text": "none"}, "1": {"text": "pending"}, "2": {"text": "firing"}}}]
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {"showValue": "never", "mergeValues": true, "rowHeight": 0.8, "legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max by (alertname) (ALERTS{alertstate=\"firing\"}) * 2 or max by (alertname) (ALERTS{alertstate=\"pending\"}) or on() vector(0)",
|
||||
"legendFormat": "{{alertname}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 31,
|
||||
"type": "table",
|
||||
"title": "Slow light requests (traces longer than 0.25 s)",
|
||||
"description": "TraceQL: server spans of light API routes longer than the latency SLI threshold; compare the server span with its PostgreSQL spans (slow database) or CPU of replicas (slow handler).",
|
||||
"datasource": {"type": "tempo", "uid": "tempo"},
|
||||
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 15},
|
||||
"options": {"showHeader": true},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "tempo", "uid": "tempo"},
|
||||
"queryType": "traceql",
|
||||
"query": "{ kind = server && resource.service.name = \"messenger-api\" && duration > 250ms && span.http.response.status_code < 500 && span.http.route !~ \"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content\" }",
|
||||
"limit": 20,
|
||||
"tableType": "traces"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1,
|
||||
"type": "row",
|
||||
"title": "API (messenger-api)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 23},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "timeseries",
|
||||
"title": "Requests per second by route and status class",
|
||||
"description": "Count of the http.server.request.duration histogram, all replicas; health is not recorded.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 24},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi", "sort": "desc"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (http_route, status_class) (label_replace(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]), \"status_class\", \"${1}xx\", \"http_response_status_code\", \"([0-9])..\"))",
|
||||
"legendFormat": "{{http_route}} {{status_class}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "timeseries",
|
||||
"title": "Error ratio (5xx of all requests)",
|
||||
"description": "Numerator: API responses 5xx; denominator: all recorded requests. 4xx are shown separately; responses generated by the load balancer are not in API metrics.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 12, "y": 24},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\",http_response_status_code=~\"5..\"}[5m])) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]))",
|
||||
"legendFormat": "5xx ratio"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "timeseries",
|
||||
"title": "Client errors ratio (4xx of all requests)",
|
||||
"description": "Wrong password, foreign chat, validation: not part of the error ratio.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 18, "y": 24},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\",http_response_status_code=~\"4..\"}[5m])) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]))",
|
||||
"legendFormat": "4xx ratio"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "timeseries",
|
||||
"title": "Request duration p50, p95 and p99 (all replicas)",
|
||||
"description": "Quantiles from the sum of buckets of all replicas, not averages of replicas.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 32},
|
||||
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
|
||||
"legendFormat": "p50"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "timeseries",
|
||||
"title": "Request duration p95 by route",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 32},
|
||||
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi", "sort": "desc"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m])))",
|
||||
"legendFormat": "{{http_route}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"type": "row",
|
||||
"title": "Worker (messenger-worker)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 40},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"type": "timeseries",
|
||||
"title": "Jobs per second by outcome",
|
||||
"description": "Count of messenger.job.duration by messenger.job.outcome. Successful: ready; failed: failed, retry, requeued, dropped, error; skipped is neither.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 41},
|
||||
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "bottom", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi", "sort": "desc"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (messenger_job_outcome) (rate(messenger_job_duration_seconds_count{job=\"messenger-worker\"}[5m]))",
|
||||
"legendFormat": "{{messenger_job_outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"type": "timeseries",
|
||||
"title": "Successful and failed jobs per second",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 41},
|
||||
"fieldConfig": {"defaults": {"unit": "ops", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(messenger_job_duration_seconds_count{job=\"messenger-worker\",messenger_job_outcome=\"ready\"}[5m]))",
|
||||
"legendFormat": "successful (ready)"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(messenger_job_duration_seconds_count{job=\"messenger-worker\",messenger_job_outcome=~\"failed|retry|requeued|dropped|error\"}[5m]))",
|
||||
"legendFormat": "failed"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"type": "timeseries",
|
||||
"title": "Job duration p50, p95 and p99 (ready)",
|
||||
"description": "Handling of one delivery after the concurrency slot, outcome ready; quantiles from the sum of buckets of all workers.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 41},
|
||||
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\",messenger_job_outcome=\"ready\"}[5m])))",
|
||||
"legendFormat": "p50"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\",messenger_job_outcome=\"ready\"}[5m])))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\",messenger_job_outcome=\"ready\"}[5m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"type": "row",
|
||||
"title": "Pipeline (messenger-relay, messenger-worker)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 49},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"type": "timeseries",
|
||||
"title": "Queue depth by stage",
|
||||
"description": "Unfinished jobs from one source, the relay snapshot of PostgreSQL every 5 s: scheduled (waits for the next attempt), outbox (due, not published), published (not taken), processing. A snapshot older than 30 s is not reported; the Collector keeps the last point up to 5 min.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 50},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "bottom", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max by (messenger_queue_stage) (messenger_queue_depth{job=\"messenger-relay\"})",
|
||||
"legendFormat": "{{messenger_queue_stage}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"type": "timeseries",
|
||||
"title": "Age of the oldest unfinished job",
|
||||
"description": "Seconds since the oldest unfinished job was accepted (queued with its job, before 202): accumulation, not handling time; 0 without unfinished jobs.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 50},
|
||||
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max(messenger_queue_oldest_age_seconds{job=\"messenger-relay\"})",
|
||||
"legendFormat": "oldest age"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"type": "timeseries",
|
||||
"title": "Time to ready p50, p95 and p99",
|
||||
"description": "From accepted upload (queued with its job) to committed ready, including waiting in the queue, retries and lease returns; jobs after replay are not counted.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 50},
|
||||
"fieldConfig": {"defaults": {"unit": "s", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{job=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "p50"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{job=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket{job=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"type": "row",
|
||||
"title": "Saturation (pools, worker, containers)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 58},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"type": "timeseries",
|
||||
"title": "PostgreSQL pool: used of max",
|
||||
"description": "db.client.connection.count{state=used} to db.client.connection.max per process with the SDK (API replicas, worker, relay); instantaneous value once per export interval.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 0, "y": 59},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (job, instance) (db_client_connection_count{db_client_connection_state=\"used\"}) / sum by (job, instance) (db_client_connection_max)",
|
||||
"legendFormat": "{{job}} {{instance}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"type": "timeseries",
|
||||
"title": "PostgreSQL pool: waiting (left) and timeouts/s (right)",
|
||||
"description": "Left axis, requests: requests waiting for a pool connection (instantaneous). Right axis, per second: pool checkouts that timed out.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 6, "y": 59},
|
||||
"fieldConfig": {
|
||||
"defaults": {"unit": "short", "min": 0, "custom": {"axisLabel": "requests"}},
|
||||
"overrides": [
|
||||
{
|
||||
"matcher": {"id": "byFrameRefID", "options": "B"},
|
||||
"properties": [
|
||||
{"id": "unit", "value": "ops"},
|
||||
{"id": "custom.axisPlacement", "value": "right"},
|
||||
{"id": "custom.axisLabel", "value": "timeouts/s"}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (job, instance) (db_client_connection_pending_requests)",
|
||||
"legendFormat": "waiting {{job}} {{instance}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (job) (rate(db_client_connection_timeouts_total[5m]))",
|
||||
"legendFormat": "timeouts/s {{job}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"type": "timeseries",
|
||||
"title": "Worker saturation",
|
||||
"description": "Busy concurrency slots to capacity of all workers (instantaneous) and the window average: sum of delivery durations per second to capacity.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 12, "y": 59},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(messenger_worker_busy) / sum(messenger_worker_capacity)",
|
||||
"legendFormat": "busy / capacity"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(messenger_job_duration_seconds_sum{job=\"messenger-worker\"}[5m])) / sum(messenger_worker_capacity)",
|
||||
"legendFormat": "average over 5m"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"type": "timeseries",
|
||||
"title": "Worker deliveries waiting for a slot",
|
||||
"description": "Deliveries received from the broker (prefetch) that wait for a concurrency slot.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 18, "y": 59},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(messenger_worker_waiting)",
|
||||
"legendFormat": "waiting"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"type": "timeseries",
|
||||
"title": "Container CPU of limit",
|
||||
"description": "CPU of the container from its cgroup v2 (cpu.stat) to the CPU limit (cpu.max), API replicas, worker with render processes, relay. PostgreSQL, S3, broker, load balancer and cleaner are not in these metrics.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 67},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (job, instance) (rate(container_cpu_time_seconds_total[5m])) / sum by (job, instance) (messenger_container_cpu_limit)",
|
||||
"legendFormat": "{{job}} {{instance}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"type": "timeseries",
|
||||
"title": "Container memory of limit",
|
||||
"description": "memory.current of the container to memory.max, same processes as CPU.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 67},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (job, instance) (container_memory_usage_bytes) / sum by (job, instance) (messenger_container_memory_limit_bytes)",
|
||||
"legendFormat": "{{job}} {{instance}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 32,
|
||||
"type": "row",
|
||||
"title": "Load balancer",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 75},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 33,
|
||||
"type": "timeseries",
|
||||
"title": "LB responses per second by status class",
|
||||
"description": "Responses of the public frontend entry to clients, including 502, 503 and 504 generated by the load balancer itself (HAProxy exporter through the Collector, job haproxy). The availability SLI is counted here.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 76},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}, "tooltip": {"mode": "multi", "sort": "desc"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (code) (rate(haproxy_frontend_http_responses_total{job=\"haproxy\",proxy=\"entry\"}[5m]))",
|
||||
"legendFormat": "{{code}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 34,
|
||||
"type": "timeseries",
|
||||
"title": "5xx on LB and 5xx of API per second",
|
||||
"description": "The difference is responses generated by the load balancer itself: with PostgreSQL down replicas leave the balancer, clients get 503 from it, and API metrics see almost no requests.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 76},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(haproxy_frontend_http_responses_total{job=\"haproxy\",proxy=\"entry\",code=\"5xx\"}[5m]))",
|
||||
"legendFormat": "5xx on LB"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\",http_response_status_code=~\"5..\"}[5m])) or on() vector(0)",
|
||||
"legendFormat": "5xx of API"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 35,
|
||||
"type": "timeseries",
|
||||
"title": "Ready replicas in LB",
|
||||
"description": "API replicas that pass the readiness check of the load balancer (haproxy_backend_active_servers of backend api).",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 84},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0, "decimals": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "single"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max(haproxy_backend_active_servers{job=\"haproxy\",proxy=\"api\"})",
|
||||
"legendFormat": "ready replicas"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 36,
|
||||
"type": "timeseries",
|
||||
"title": "LB retries, redispatches and connection errors per second",
|
||||
"description": "Backend api: retries on connection failure, redispatches to another replica, connection and response errors.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 84},
|
||||
"fieldConfig": {"defaults": {"unit": "ops", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(haproxy_backend_retry_warnings_total{job=\"haproxy\",proxy=\"api\"}[5m]))",
|
||||
"legendFormat": "retries"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(haproxy_backend_redispatch_warnings_total{job=\"haproxy\",proxy=\"api\"}[5m]))",
|
||||
"legendFormat": "redispatches"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(haproxy_backend_connection_errors_total{job=\"haproxy\",proxy=\"api\"}[5m]))",
|
||||
"legendFormat": "connection errors"
|
||||
},
|
||||
{
|
||||
"refId": "D",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum(rate(haproxy_backend_response_errors_total{job=\"haproxy\",proxy=\"api\"}[5m]))",
|
||||
"legendFormat": "response errors"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 37,
|
||||
"type": "row",
|
||||
"title": "Telemetry pipeline",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 92},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 38,
|
||||
"type": "timeseries",
|
||||
"title": "Collector export queues, share of capacity",
|
||||
"description": "Sending queues of the Loki and Tempo exporters in bytes (16 and 8 MiB): a full queue rejects new data (enqueue_failed).",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 93},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max by (exporter) (otelcol_exporter_queue_size{job=\"otel-collector\"}) / max by (exporter) (otelcol_exporter_queue_capacity{job=\"otel-collector\"})",
|
||||
"legendFormat": "{{exporter}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 39,
|
||||
"type": "timeseries",
|
||||
"title": "SDK queues, share of capacity",
|
||||
"description": "Span and log record queues of the SDK processors of API replicas, worker and relay ([telemetry] max_queue_size); the oldest item is dropped when a queue is full (queue_full).",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 93},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max by (job, instance) (otel_sdk_processor_span_queue_size / otel_sdk_processor_span_queue_capacity)",
|
||||
"legendFormat": "spans {{job}} {{instance}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max by (job, instance) (otel_sdk_processor_log_queue_size / otel_sdk_processor_log_queue_capacity)",
|
||||
"legendFormat": "logs {{job}} {{instance}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 40,
|
||||
"type": "timeseries",
|
||||
"title": "Telemetry lost per second by place",
|
||||
"description": "Recording rule telemetry:lost_items:total by process, and its parts: Collector (refused by the memory limiter, queue full, retries expired) and SDK (queue full, failed export). Zero without losses.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 101},
|
||||
"fieldConfig": {"defaults": {"unit": "ops", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (job) (rate(telemetry:lost_items:total[5m])) or on() vector(0)",
|
||||
"legendFormat": "lost {{job}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (metric, receiver, exporter) (rate(label_replace({__name__=~\"otelcol_(receiver_refused|exporter_send_failed|exporter_enqueue_failed)_(spans|log_records|metric_points)\"}, \"metric\", \"$1\", \"__name__\", \"otelcol_(.+)\")[5m:15s])) or on() vector(0)",
|
||||
"legendFormat": "Collector {{metric}} {{receiver}}{{exporter}}"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "sum by (job, otel_component_type, error_type) (rate(label_replace({__name__=~\"otel_sdk_(processor|exporter)_(span|log)_(processed|exported)_total\",error_type!=\"\"}, \"metric\", \"$1\", \"__name__\", \"(.+)\")[5m:15s])) or on() vector(0)",
|
||||
"legendFormat": "SDK {{job}} {{otel_component_type}} {{error_type}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 41,
|
||||
"type": "timeseries",
|
||||
"title": "Collector memory",
|
||||
"description": "Go heap and memory obtained from the system by the Collector; the memory limiter refuses data at 200 MiB, GOMEMLIMIT is 160 MiB. memory_rss includes file pages of the binary and is not used.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 101},
|
||||
"fieldConfig": {"defaults": {"unit": "bytes", "min": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max(otelcol_process_runtime_heap_alloc_bytes{job=\"otel-collector\"})",
|
||||
"legendFormat": "heap"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max(otelcol_process_runtime_total_sys_memory_bytes{job=\"otel-collector\"})",
|
||||
"legendFormat": "from the system"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 42,
|
||||
"type": "timeseries",
|
||||
"title": "Metrics targets up",
|
||||
"description": "1 — Prometheus scrapes the target; haproxy comes through the Collector receiver.",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 109},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0, "max": 1, "decimals": 0}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"expr": "max by (job) (up{job=~\"otel-collector|otel-collector-exporter|loki|tempo|prometheus|haproxy\"})",
|
||||
"legendFormat": "{{job}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"type": "row",
|
||||
"title": "Logs and traces",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 117},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"type": "logs",
|
||||
"title": "API, worker and relay logs",
|
||||
"description": "Records of stdout exported through the Collector; trace_id opens the trace in Tempo.",
|
||||
"datasource": {"type": "loki", "uid": "loki"},
|
||||
"gridPos": {"h": 12, "w": 24, "x": 0, "y": 118},
|
||||
"options": {"showTime": true, "showLabels": false, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true, "dedupStrategy": "none", "prettifyLogMessage": false},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "loki", "uid": "loki"},
|
||||
"expr": "{service_name=~\"messenger-.*\"}",
|
||||
"queryType": "range"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"type": "table",
|
||||
"title": "Recent traces",
|
||||
"description": "TraceQL search of API requests and worker deliveries; an upload trace holds its relay publications and worker deliveries; a trace opens with links to its logs.",
|
||||
"datasource": {"type": "tempo", "uid": "tempo"},
|
||||
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 130},
|
||||
"options": {"showHeader": true},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "tempo", "uid": "tempo"},
|
||||
"queryType": "traceql",
|
||||
"query": "{ resource.service.name =~ \"messenger-.*\" }",
|
||||
"limit": 20,
|
||||
"tableType": "traces"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
# Источники Grafana (design change otel-telemetry, решение 16): постоянные uid,
|
||||
# на которые ссылается dashboard; правка в интерфейсе запрещена. Переходы:
|
||||
# запись Loki → трасса Tempo по полю trace_id (structured metadata OTLP), span
|
||||
# Tempo → записи Loki той же трассы.
|
||||
apiVersion: 1
|
||||
|
||||
prune: true
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
httpMethod: POST
|
||||
timeInterval: 15s
|
||||
# правила записи и оповещения Prometheus видны в Alerting только для
|
||||
# чтения: источник правды — infra/otel/prometheus/rules.yml (design
|
||||
# change slo-alerts, решение 3); правил Grafana и Alertmanager нет
|
||||
manageAlerts: true
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
maxLines: 1000
|
||||
derivedFields:
|
||||
- name: trace_id
|
||||
datasourceUid: tempo
|
||||
# поле записи OTLP, а не текст строки
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
url: "$${__value.raw}"
|
||||
urlDisplayLabel: Trace
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: "-5m"
|
||||
spanEndTimeShift: "5m"
|
||||
filterByTraceID: false
|
||||
filterBySpanID: false
|
||||
customQuery: true
|
||||
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"'
|
||||
serviceMap:
|
||||
datasourceUid: prometheus
|
||||
nodeGraph:
|
||||
enabled: false
|
||||
search:
|
||||
hide: false
|
||||
lokiSearch:
|
||||
datasourceUid: loki
|
||||
@@ -0,0 +1,46 @@
|
||||
# Loki 3.7.9 — хранилище логов (design change otel-telemetry, решение 15).
|
||||
# Монолит из конфигурации образа (/etc/loki/local-config.yaml): filesystem,
|
||||
# inmemory ring, schema v13 tsdb; плюс срок хранения 7 суток, compactor и без
|
||||
# отчётов об использовании. Приём — родной OTLP (/otlp) от Collector, метки
|
||||
# потока по умолчанию — service_name, service_instance_id,
|
||||
# deployment_environment_name; поля записи — structured metadata. Порт не
|
||||
# публикуется: Collector и Grafana ходят в сети telemetry.
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
log_level: info
|
||||
|
||||
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: 2020-10-24
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
# удаление данных старше срока делает compactor
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
|
||||
limits_config:
|
||||
retention_period: 168h
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,52 @@
|
||||
# Prometheus v3.15.1 — хранилище метрик (design change otel-telemetry,
|
||||
# решения 3 и 15). Метрики приложения — scrape экспортёра prometheus
|
||||
# Collector (honor_labels: job = service.name, instance = service.instance.id
|
||||
# из OTLP; там же метрики LB с job = haproxy), плюс собственные метрики
|
||||
# Collector, Loki, Tempo и самого Prometheus: по ним видно, жив ли конвейер.
|
||||
# Срок и предел объёма хранения, путь данных и время начала рядов — флаги
|
||||
# команды в docker-compose.yml. Приёмников remote write и OTLP, admin API и
|
||||
# lifecycle нет; порт не публикуется. Правила записи и оповещения — rules.yml
|
||||
# (design change slo-alerts, решения 1, 3, 4, 9); блока alerting нет:
|
||||
# доставки наружу нет, состояние firing / resolved — API правил, ряды ALERTS и
|
||||
# Grafana.
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
evaluation_interval: 15s
|
||||
# явно прежний текстовый список Prometheus 3 по умолчанию: флаг
|
||||
# created-timestamp-zero-ingestion иначе переводит на protobuf все цели, а
|
||||
# время начала нужно только экспортёру Collector (решение 6)
|
||||
scrape_protocols:
|
||||
- OpenMetricsText1.0.0
|
||||
- OpenMetricsText0.0.1
|
||||
- PrometheusText1.0.0
|
||||
- PrometheusText0.0.4
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules.yml
|
||||
|
||||
scrape_configs:
|
||||
# метрики API, worker и relay, пришедшие в Collector по OTLP, и метрики LB
|
||||
# с приёмника prometheus/haproxy. Protobuf первым: время начала
|
||||
# cumulative-ряда экспортёр Collector отдаёт только в нём, и Prometheus
|
||||
# пишет ноль в момент старта нового процесса (решение 6)
|
||||
- job_name: otel-collector-exporter
|
||||
honor_labels: true
|
||||
scrape_protocols:
|
||||
- PrometheusProto
|
||||
- OpenMetricsText1.0.0
|
||||
- PrometheusText0.0.4
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8889"]
|
||||
- job_name: otel-collector
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8888"]
|
||||
- job_name: loki
|
||||
static_configs:
|
||||
- targets: ["loki:3100"]
|
||||
- job_name: tempo
|
||||
static_configs:
|
||||
- targets: ["tempo:3200"]
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets: ["127.0.0.1:9090"]
|
||||
@@ -0,0 +1,583 @@
|
||||
# Модульные тесты правил (design change slo-alerts, решение 11): promtool test
|
||||
# rules на синтетических рядах, без стенда и без сети — make alerts_test. На
|
||||
# каждое оповещение — срабатывание после for, нет срабатывания ниже порога и
|
||||
# без трафика, снятие после восстановления; правила записи — значения.
|
||||
# Интервал рядов и вычисления — 15 с, как у стенда; шаг i — время 15 × i с.
|
||||
|
||||
rule_files:
|
||||
- rules.yml
|
||||
|
||||
evaluation_interval: 15s
|
||||
|
||||
tests:
|
||||
# --- MessengerHighErrorRate и правила записи окна LB ----------------------
|
||||
# 2xx по 10 за шаг всё время; 5xx — по 10 за шаг с шага 11 (165 с) по шаг
|
||||
# 40 (600 с), дальше не растут: доля 5xx — 50 %, трафик 1,33 запроса/с
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="2xx"}'
|
||||
values: '0+10x60'
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="5xx"}'
|
||||
values: '0x10 10+10x29 300x20'
|
||||
# ответы monitor (health LB) в SLI не входят
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="monitor",code="5xx"}'
|
||||
values: '0+100x60'
|
||||
promql_expr_test:
|
||||
- expr: messenger:lb_http_errors:ratio_rate2m
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: 'messenger:lb_http_errors:ratio_rate2m'
|
||||
value: 0.5
|
||||
- expr: messenger:lb_http_responses:rate2m
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: 'messenger:lb_http_responses:rate2m'
|
||||
value: 1.3333333333333333
|
||||
alert_rule_test:
|
||||
# ошибок ещё нет
|
||||
- eval_time: 2m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
# ошибки идут 15 с: pending, for 1 мин ещё не прошёл
|
||||
- eval_time: 3m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 6m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: critical
|
||||
exp_annotations:
|
||||
summary: High share of 5xx responses to clients on the load balancer
|
||||
description: '50% of responses of the public frontend in the last 2 minutes are 5xx (threshold 5 %, SLO 99.5 %), including responses generated by the load balancer itself. Runbook: infra/otel/runbooks/MessengerHighErrorRate.md'
|
||||
runbook_url: infra/otel/runbooks/MessengerHighErrorRate.md
|
||||
# 5xx не растут с 600 с: окно 2 мин без ошибок — снято
|
||||
- eval_time: 13m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
|
||||
# ниже порога: 1 % 5xx
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="2xx"}'
|
||||
values: '0+99x40'
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="5xx"}'
|
||||
values: '0+1x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
|
||||
# без трафика: все ответы 5xx, но 0,03 запроса/с; и вовсе нет ответов
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="5xx"}'
|
||||
values: '0+0.5x40'
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="2xx"}'
|
||||
values: '0x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="2xx"}'
|
||||
values: '0x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
|
||||
# --- MessengerSlowRequests -----------------------------------------------
|
||||
# «лёгкая» отправка сообщения: 10 запросов за шаг, с шага 11 быстрые —
|
||||
# только 5 из 10 (до шага 40), дальше снова все быстрые
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="201"}'
|
||||
values: '0+10x60'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="201",le="0.25"}'
|
||||
values: '0+10x10 105+5x29 260+10x20'
|
||||
promql_expr_test:
|
||||
- expr: messenger:http_light_slow:ratio_rate2m
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: 'messenger:http_light_slow:ratio_rate2m'
|
||||
value: 0.5
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerSlowRequests
|
||||
exp_alerts: []
|
||||
- eval_time: 3m
|
||||
alertname: MessengerSlowRequests
|
||||
exp_alerts: []
|
||||
- eval_time: 6m
|
||||
alertname: MessengerSlowRequests
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: Many light API requests are slower than 0.25 s
|
||||
description: '50% of light API requests without 5xx in the last 2 minutes took longer than 0.25 s (threshold 10 %, SLO 99 %); login, registration and attachment bytes are not counted. Runbook: infra/otel/runbooks/MessengerSlowRequests.md'
|
||||
runbook_url: infra/otel/runbooks/MessengerSlowRequests.md
|
||||
- eval_time: 13m
|
||||
alertname: MessengerSlowRequests
|
||||
exp_alerts: []
|
||||
|
||||
# тяжёлые ручки и 5xx вне SLI задержки: вход, регистрация, загрузка и
|
||||
# скачивание байтов медленные, у «лёгкой» — медленные только 5xx; плюс
|
||||
# быстрые «лёгкие» запросы без маршрута (404)
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/auth/sessions",http_response_status_code="201"}'
|
||||
values: '0+10x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/auth/sessions",http_response_status_code="201",le="0.25"}'
|
||||
values: '0x40'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/users",http_response_status_code="201"}'
|
||||
values: '0+10x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/users",http_response_status_code="201",le="0.25"}'
|
||||
values: '0x40'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/chats/{chat_id}/attachments",http_response_status_code="202"}'
|
||||
values: '0+10x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/chats/{chat_id}/attachments",http_response_status_code="202",le="0.25"}'
|
||||
values: '0x40'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/attachments/{attachment_id}/content",http_response_status_code="200"}'
|
||||
values: '0+10x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/attachments/{attachment_id}/content",http_response_status_code="200",le="0.25"}'
|
||||
values: '0x40'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="503"}'
|
||||
values: '0+10x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="POST",http_route="/api/v1/chats/{chat_id}/messages",http_response_status_code="503",le="0.25"}'
|
||||
values: '0x40'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="GET",http_response_status_code="404"}'
|
||||
values: '0+10x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="GET",http_response_status_code="404",le="0.25"}'
|
||||
values: '0+10x40'
|
||||
promql_expr_test:
|
||||
- expr: messenger:http_light_slow:ratio_rate2m
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: 'messenger:http_light_slow:ratio_rate2m'
|
||||
value: 0
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerSlowRequests
|
||||
exp_alerts: []
|
||||
|
||||
# ниже порога (5 % медленных) и без трафика (все медленные, 0,03 запроса/с)
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/chats/{chat_id}",http_response_status_code="200"}'
|
||||
values: '0+20x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/chats/{chat_id}",http_response_status_code="200",le="0.25"}'
|
||||
values: '0+19x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerSlowRequests
|
||||
exp_alerts: []
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/chats/{chat_id}",http_response_status_code="200"}'
|
||||
values: '0+0.5x40'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/chats/{chat_id}",http_response_status_code="200",le="0.25"}'
|
||||
values: '0x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerSlowRequests
|
||||
exp_alerts: []
|
||||
|
||||
# --- MessengerNoReadyReplicas --------------------------------------------
|
||||
# готовых реплик 0 с шага 5 (75 с) по шаг 15 (225 с), затем снова 2
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'haproxy_backend_active_servers{job="haproxy",instance="haproxy:8404",proxy="api"}'
|
||||
values: '2x4 0x10 2x10'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerNoReadyReplicas
|
||||
exp_alerts: []
|
||||
# 0 с 75 с: в 90 с — pending, for 30 с прошёл к 105 с
|
||||
- eval_time: 90s
|
||||
alertname: MessengerNoReadyReplicas
|
||||
exp_alerts: []
|
||||
- eval_time: 2m
|
||||
alertname: MessengerNoReadyReplicas
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: critical
|
||||
exp_annotations:
|
||||
summary: No API replica is ready behind the load balancer
|
||||
description: 'The load balancer sees 0 ready API replicas: clients get 503 from the load balancer. Fires without traffic too. Runbook: infra/otel/runbooks/MessengerNoReadyReplicas.md'
|
||||
runbook_url: infra/otel/runbooks/MessengerNoReadyReplicas.md
|
||||
- eval_time: 5m
|
||||
alertname: MessengerNoReadyReplicas
|
||||
exp_alerts: []
|
||||
# одна реплика из двух готова — не оповещение
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'haproxy_backend_active_servers{job="haproxy",instance="haproxy:8404",proxy="api"}'
|
||||
values: '2x4 1x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 4m
|
||||
alertname: MessengerNoReadyReplicas
|
||||
exp_alerts: []
|
||||
|
||||
# --- MessengerQueueLagHigh -----------------------------------------------
|
||||
# worker стоит: возраст растёт на 15 с за шаг с шага 5 (75 с), на шаге 26
|
||||
# (390 с) задания разобраны
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_queue_oldest_age_seconds{job="messenger-relay",instance="r1"}'
|
||||
values: '0x5 15+15x20 0x10'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerQueueLagHigh
|
||||
exp_alerts: []
|
||||
# больше 60 с с шага 10 (150 с): firing с 210 с
|
||||
- eval_time: 3m
|
||||
alertname: MessengerQueueLagHigh
|
||||
exp_alerts: []
|
||||
- eval_time: 4m
|
||||
alertname: MessengerQueueLagHigh
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
exp_annotations:
|
||||
summary: The oldest unfinished attachment job is older than 60 s
|
||||
description: 'The oldest unfinished job waits 2m 45s (threshold 60 s, time to ready SLO 30 s). Runbook: infra/otel/runbooks/MessengerQueueLagHigh.md'
|
||||
runbook_url: infra/otel/runbooks/MessengerQueueLagHigh.md
|
||||
- eval_time: 7m
|
||||
alertname: MessengerQueueLagHigh
|
||||
exp_alerts: []
|
||||
# ниже порога: возраст до 45 с
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_queue_oldest_age_seconds{job="messenger-relay",instance="r1"}'
|
||||
values: '0x5 15 30 45 0x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 4m
|
||||
alertname: MessengerQueueLagHigh
|
||||
exp_alerts: []
|
||||
|
||||
# --- MessengerQueueMetricsMissing ----------------------------------------
|
||||
# relay остановлен: снимок пропал после шага 4 (ряд stale с 75 с), экспортёр
|
||||
# Collector доступен; relay вернулся на шаге 20 (300 с)
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_queue_oldest_age_seconds{job="messenger-relay",instance="r1"}'
|
||||
values: '3x4 stale _x14 3x20'
|
||||
- series: 'up{job="otel-collector-exporter",instance="otel-collector:8889"}'
|
||||
values: '1x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 3m
|
||||
alertname: MessengerQueueMetricsMissing
|
||||
exp_alerts: []
|
||||
- eval_time: 4m
|
||||
alertname: MessengerQueueMetricsMissing
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: messenger-relay
|
||||
exp_annotations:
|
||||
summary: The relay queue snapshot is missing
|
||||
# последний снимок — точка 60 с, вычисление — 240 с
|
||||
description: 'There is no queue depth and age snapshot of the relay while the Collector exporter is up (last snapshot 3m 0s ago): the relay is stopped or cannot read PostgreSQL, and MessengerQueueLagHigh is blind. Runbook: infra/otel/runbooks/MessengerQueueMetricsMissing.md'
|
||||
runbook_url: infra/otel/runbooks/MessengerQueueMetricsMissing.md
|
||||
- eval_time: 6m
|
||||
alertname: MessengerQueueMetricsMissing
|
||||
exp_alerts: []
|
||||
# снимка не было вовсе (за час): описание без возраста
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'up{job="otel-collector-exporter",instance="otel-collector:8889"}'
|
||||
values: '1x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 3m
|
||||
alertname: MessengerQueueMetricsMissing
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: messenger-relay
|
||||
exp_annotations:
|
||||
summary: The relay queue snapshot is missing
|
||||
description: 'There is no queue depth and age snapshot of the relay while the Collector exporter is up (last snapshot more than an hour ago): the relay is stopped or cannot read PostgreSQL, and MessengerQueueLagHigh is blind. Runbook: infra/otel/runbooks/MessengerQueueMetricsMissing.md'
|
||||
runbook_url: infra/otel/runbooks/MessengerQueueMetricsMissing.md
|
||||
# экспортёр Collector недоступен: снимка нет, но молчит (TelemetryTargetDown)
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_queue_oldest_age_seconds{job="messenger-relay",instance="r1"}'
|
||||
values: '3x4 stale'
|
||||
- series: 'up{job="otel-collector-exporter",instance="otel-collector:8889"}'
|
||||
values: '1x4 0x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerQueueMetricsMissing
|
||||
exp_alerts: []
|
||||
# снимок есть — тихо
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_queue_oldest_age_seconds{job="messenger-relay",instance="r1"}'
|
||||
values: '3x40'
|
||||
- series: 'up{job="otel-collector-exporter",instance="otel-collector:8889"}'
|
||||
values: '1x40'
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: MessengerQueueMetricsMissing
|
||||
exp_alerts: []
|
||||
|
||||
# --- TelemetryTargetDown -------------------------------------------------
|
||||
# Tempo недоступен с шага 4 (60 с) по шаг 13 (195 с); Loki — 30 с (короче
|
||||
# for); экспортёр Collector в правило не входит (его закрывает otel-collector)
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'up{job="tempo",instance="tempo:3200"}'
|
||||
values: '1x3 0x9 1x20'
|
||||
- series: 'up{job="loki",instance="loki:3100"}'
|
||||
values: '1x3 0x1 1x20'
|
||||
- series: 'up{job="otel-collector",instance="otel-collector:8888"}'
|
||||
values: '1x30'
|
||||
- series: 'up{job="haproxy",instance="haproxy:8404"}'
|
||||
values: '1x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 90s
|
||||
alertname: TelemetryTargetDown
|
||||
exp_alerts: []
|
||||
- eval_time: 2m
|
||||
alertname: TelemetryTargetDown
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: tempo
|
||||
instance: tempo:3200
|
||||
exp_annotations:
|
||||
summary: Metrics target tempo is down
|
||||
# Loki к 2 мин вернулся: недоступна одна цель
|
||||
description: 'Prometheus cannot scrape tempo (tempo:3200) for a minute (up 0; targets of the rule down now: 1); with job haproxy the load balancer metrics are missing and MessengerHighErrorRate is blind. Runbook: infra/otel/runbooks/TelemetryTargetDown.md'
|
||||
runbook_url: infra/otel/runbooks/TelemetryTargetDown.md
|
||||
- eval_time: 5m
|
||||
alertname: TelemetryTargetDown
|
||||
exp_alerts: []
|
||||
# Loki и Tempo недоступны вместе: по оповещению на цель, недоступны две
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'up{job="tempo",instance="tempo:3200"}'
|
||||
values: '1x3 0x20'
|
||||
- series: 'up{job="loki",instance="loki:3100"}'
|
||||
values: '1x3 0x20'
|
||||
- series: 'up{job="haproxy",instance="haproxy:8404"}'
|
||||
values: '1x23'
|
||||
alert_rule_test:
|
||||
- eval_time: 3m
|
||||
alertname: TelemetryTargetDown
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: loki
|
||||
instance: loki:3100
|
||||
exp_annotations:
|
||||
summary: Metrics target loki is down
|
||||
description: 'Prometheus cannot scrape loki (loki:3100) for a minute (up 0; targets of the rule down now: 2); with job haproxy the load balancer metrics are missing and MessengerHighErrorRate is blind. Runbook: infra/otel/runbooks/TelemetryTargetDown.md'
|
||||
runbook_url: infra/otel/runbooks/TelemetryTargetDown.md
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: tempo
|
||||
instance: tempo:3200
|
||||
exp_annotations:
|
||||
summary: Metrics target tempo is down
|
||||
description: 'Prometheus cannot scrape tempo (tempo:3200) for a minute (up 0; targets of the rule down now: 2); with job haproxy the load balancer metrics are missing and MessengerHighErrorRate is blind. Runbook: infra/otel/runbooks/TelemetryTargetDown.md'
|
||||
runbook_url: infra/otel/runbooks/TelemetryTargetDown.md
|
||||
|
||||
# --- TelemetryDataLoss и сумма потерь -------------------------------------
|
||||
# Collector: ряд отказов очереди Tempo появился на шаге 9 (135 с) сразу со
|
||||
# значением 50 (`_xN` — N пропусков), вырос до 80 на шаге 21 (315 с), рестарт
|
||||
# Collector на шаге 42 (630 с) — 0. SDK реплики: отброшено из-за полной
|
||||
# очереди 36 с шага 5 (75 с); отправленное без ошибки (error_type пуст) — не
|
||||
# потеря
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'otelcol_exporter_enqueue_failed_spans{job="otel-collector",instance="otel-collector:8888",exporter="otlp_http/tempo"}'
|
||||
values: '_x9 50x11 80x20 0x10'
|
||||
- series: 'otel_sdk_processor_span_processed_total{job="messenger-api",instance="a1",otel_component_type="batching_span_processor",otel_component_name="batching_span_processor/0",error_type="queue_full"}'
|
||||
values: '_x5 36x40'
|
||||
- series: 'otel_sdk_processor_span_processed_total{job="messenger-api",instance="a1",otel_component_type="batching_span_processor",otel_component_name="batching_span_processor/0"}'
|
||||
values: '0+100x46'
|
||||
- series: 'otelcol_exporter_sent_spans{job="otel-collector",instance="otel-collector:8888",exporter="otlp_http/tempo"}'
|
||||
values: '0+100x46'
|
||||
promql_expr_test:
|
||||
- expr: telemetry:lost_items:total
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: 'telemetry:lost_items:total{job="otel-collector",instance="otel-collector:8888"}'
|
||||
value: 80
|
||||
- labels: 'telemetry:lost_items:total{job="messenger-api",instance="a1"}'
|
||||
value: 36
|
||||
alert_rule_test:
|
||||
# новый ряд SDK со значением 36 (шаг 6, 90 с) — рост целиком
|
||||
- eval_time: 2m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: messenger-api
|
||||
instance: a1
|
||||
exp_annotations:
|
||||
summary: Telemetry of messenger-api is being lost
|
||||
description: 'messenger-api (a1) lost 36 spans, log records or metric points in the last 2 minutes (full queue, failed export or refused by the memory limiter). Runbook: infra/otel/runbooks/TelemetryDataLoss.md'
|
||||
runbook_url: infra/otel/runbooks/TelemetryDataLoss.md
|
||||
# новый ряд Collector со значением 50 (150 с); у SDK 2 мин без роста
|
||||
- eval_time: 4m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: otel-collector
|
||||
instance: otel-collector:8888
|
||||
exp_annotations:
|
||||
summary: Telemetry of otel-collector is being lost
|
||||
description: 'otel-collector (otel-collector:8888) lost 50 spans, log records or metric points in the last 2 minutes (full queue, failed export or refused by the memory limiter). Runbook: infra/otel/runbooks/TelemetryDataLoss.md'
|
||||
runbook_url: infra/otel/runbooks/TelemetryDataLoss.md
|
||||
# 2 мин без роста — снято
|
||||
- eval_time: 5m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts: []
|
||||
- eval_time: 6m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: otel-collector
|
||||
instance: otel-collector:8888
|
||||
exp_annotations:
|
||||
summary: Telemetry of otel-collector is being lost
|
||||
description: 'otel-collector (otel-collector:8888) lost 30 spans, log records or metric points in the last 2 minutes (full queue, failed export or refused by the memory limiter). Runbook: infra/otel/runbooks/TelemetryDataLoss.md'
|
||||
runbook_url: infra/otel/runbooks/TelemetryDataLoss.md
|
||||
- eval_time: 9m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts: []
|
||||
# сброс суммы (рестарт Collector) — не потеря
|
||||
- eval_time: 11m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts: []
|
||||
# первая потеря процесса SDK видна в increase() панели потерь (verify W1):
|
||||
# ряд ёмкости очереди span есть с запуска процесса — ряд суммы с нуля; ряд
|
||||
# отказов реплики появился на шаге 16 (240 с) сразу со значением 36. relay
|
||||
# без потерь — ноль, оповещения нет
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'otel_sdk_processor_span_queue_capacity{job="messenger-api",instance="a1",otel_component_type="batching_span_processor",otel_component_name="batching_span_processor/0"}'
|
||||
values: '2048x40'
|
||||
- series: 'otel_sdk_processor_span_queue_capacity{job="messenger-relay",instance="r1",otel_component_type="batching_span_processor",otel_component_name="batching_span_processor/0"}'
|
||||
values: '2048x40'
|
||||
- series: 'otel_sdk_processor_span_processed_total{job="messenger-api",instance="a1",otel_component_type="batching_span_processor",otel_component_name="batching_span_processor/0"}'
|
||||
values: '0+100x40'
|
||||
- series: 'otel_sdk_processor_span_processed_total{job="messenger-api",instance="a1",otel_component_type="batching_span_processor",otel_component_name="batching_span_processor/0",error_type="queue_full"}'
|
||||
values: '_x16 36x24'
|
||||
promql_expr_test:
|
||||
- expr: telemetry:lost_items:total
|
||||
eval_time: 3m
|
||||
exp_samples:
|
||||
- labels: 'telemetry:lost_items:total{job="messenger-api",instance="a1"}'
|
||||
value: 0
|
||||
- labels: 'telemetry:lost_items:total{job="messenger-relay",instance="r1"}'
|
||||
value: 0
|
||||
# запрос A панели 40 без суммы по job: приращение за 5 мин — вся потеря
|
||||
- expr: increase(telemetry:lost_items:total[5m])
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: '{job="messenger-api",instance="a1"}'
|
||||
value: 36
|
||||
- labels: '{job="messenger-relay",instance="r1"}'
|
||||
value: 0
|
||||
alert_rule_test:
|
||||
- eval_time: 5m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: warning
|
||||
job: messenger-api
|
||||
instance: a1
|
||||
exp_annotations:
|
||||
summary: Telemetry of messenger-api is being lost
|
||||
description: 'messenger-api (a1) lost 36 spans, log records or metric points in the last 2 minutes (full queue, failed export or refused by the memory limiter). Runbook: infra/otel/runbooks/TelemetryDataLoss.md'
|
||||
runbook_url: infra/otel/runbooks/TelemetryDataLoss.md
|
||||
- eval_time: 9m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts: []
|
||||
|
||||
# без потерь — тихо, сумма потерь пуста
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'otelcol_exporter_sent_spans{job="otel-collector",instance="otel-collector:8888",exporter="otlp_http/tempo"}'
|
||||
values: '0+100x40'
|
||||
promql_expr_test:
|
||||
- expr: telemetry:lost_items:total
|
||||
eval_time: 6m
|
||||
exp_samples: []
|
||||
alert_rule_test:
|
||||
- eval_time: 6m
|
||||
alertname: TelemetryDataLoss
|
||||
exp_alerts: []
|
||||
|
||||
# --- правила SLO: приращения за непересекающиеся 5 мин ----------------------
|
||||
# LB: 2xx по 9 и 5xx по 1 за шаг; «лёгкие» запросы по 10 за шаг, быстрые —
|
||||
# 9; готовые вложения по 2 за шаг, не дольше 30 с — 1
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="2xx"}'
|
||||
values: '0+9x80'
|
||||
- series: 'haproxy_frontend_http_responses_total{job="haproxy",instance="haproxy:8404",proxy="entry",code="5xx"}'
|
||||
values: '0+1x80'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/chats/{chat_id}",http_response_status_code="200"}'
|
||||
values: '0+10x80'
|
||||
- series: 'http_server_request_duration_seconds_bucket{job="messenger-api",instance="a1",http_request_method="GET",http_route="/api/v1/chats/{chat_id}",http_response_status_code="200",le="0.25"}'
|
||||
values: '0+9x80'
|
||||
- series: 'messenger_job_time_to_ready_seconds_count{job="messenger-worker",instance="w1",messenger_job_type="attachment.process"}'
|
||||
values: '0+2x80'
|
||||
- series: 'messenger_job_time_to_ready_seconds_bucket{job="messenger-worker",instance="w1",messenger_job_type="attachment.process",le="30.0"}'
|
||||
values: '0+1x80'
|
||||
promql_expr_test:
|
||||
- expr: messenger:slo_availability_bad:increase5m
|
||||
eval_time: 10m
|
||||
exp_samples:
|
||||
- labels: 'messenger:slo_availability_bad:increase5m'
|
||||
value: 20
|
||||
- expr: messenger:slo_availability_total:increase5m
|
||||
eval_time: 10m
|
||||
exp_samples:
|
||||
- labels: 'messenger:slo_availability_total:increase5m'
|
||||
value: 200
|
||||
- expr: messenger:slo_latency_good:increase5m
|
||||
eval_time: 10m
|
||||
exp_samples:
|
||||
- labels: 'messenger:slo_latency_good:increase5m'
|
||||
value: 180
|
||||
- expr: messenger:slo_latency_total:increase5m
|
||||
eval_time: 10m
|
||||
exp_samples:
|
||||
- labels: 'messenger:slo_latency_total:increase5m'
|
||||
value: 200
|
||||
- expr: messenger:slo_time_to_ready_good:increase5m
|
||||
eval_time: 10m
|
||||
exp_samples:
|
||||
- labels: 'messenger:slo_time_to_ready_good:increase5m'
|
||||
value: 20
|
||||
- expr: messenger:slo_time_to_ready_total:increase5m
|
||||
eval_time: 10m
|
||||
exp_samples:
|
||||
- labels: 'messenger:slo_time_to_ready_total:increase5m'
|
||||
value: 40
|
||||
# SLI окна по рядам правил: доступность 1 − 20 / 200, задержка 180 / 200
|
||||
- expr: 1 - sum_over_time(messenger:slo_availability_bad:increase5m[10m]) / sum_over_time(messenger:slo_availability_total:increase5m[10m])
|
||||
eval_time: 15m
|
||||
exp_samples:
|
||||
- labels: '{}'
|
||||
value: 0.9
|
||||
- expr: sum_over_time(messenger:slo_latency_good:increase5m[10m]) / sum_over_time(messenger:slo_latency_total:increase5m[10m])
|
||||
eval_time: 15m
|
||||
exp_samples:
|
||||
- labels: '{}'
|
||||
value: 0.9
|
||||
- expr: sum_over_time(messenger:slo_time_to_ready_good:increase5m[10m]) / sum_over_time(messenger:slo_time_to_ready_total:increase5m[10m])
|
||||
eval_time: 15m
|
||||
exp_samples:
|
||||
- labels: '{}'
|
||||
value: 0.5
|
||||
@@ -0,0 +1,190 @@
|
||||
# Правила Prometheus стенда (design change slo-alerts): правила записи SLI и
|
||||
# SLO (решение 1), учёт потерь телеметрии (решение 9) и оповещения (решения 3,
|
||||
# 4). Вычисляет Prometheus; доставки наружу нет — состояние firing / resolved:
|
||||
# /api/v1/rules, /api/v1/alerts, ряды ALERTS и Grafana (правила источника
|
||||
# prometheus только для чтения, панель истории). Модульные тесты —
|
||||
# rules.test.yml (make alerts_test). У каждого оповещения — локальный runbook
|
||||
# infra/otel/runbooks/<имя>.md.
|
||||
#
|
||||
# SLI (окно SLO — скользящие 7 суток, срок хранения Prometheus):
|
||||
# доступность — ответы публичного frontend LB (entry) не 5xx, вместе с 502,
|
||||
# 503 и 504 самого LB; SLO 99,5 %;
|
||||
# задержка — «лёгкие» запросы API без 5xx не дольше 0,25 с; SLO 99 %.
|
||||
# Не «лёгкие» — регистрация и вход (KDF, тот же шаблон у DELETE
|
||||
# /api/v1/users), загрузка и скачивание байтов вложения; запросы без
|
||||
# маршрута (404 неизвестного пути) входят;
|
||||
# время до ready — вложение ready без replay не позже 30 с от устойчивого
|
||||
# приёма; SLO 99 %.
|
||||
# SLI окна W — sum_over_time(good[W]) / sum_over_time(total[W]) по рядам
|
||||
# группы messenger-slo (для доступности — 1 − bad / total); остаток бюджета —
|
||||
# (SLI − SLO) / (1 − SLO).
|
||||
|
||||
groups:
|
||||
# окна оповещений и панелей — 2 мин (8 сборов при 15 с)
|
||||
- name: messenger-sli
|
||||
interval: 15s
|
||||
rules:
|
||||
- record: messenger:lb_http_responses:rate2m
|
||||
expr: sum(rate(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry"}[2m]))
|
||||
- record: messenger:lb_http_errors:rate2m
|
||||
expr: sum(rate(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry",code="5xx"}[2m]))
|
||||
- record: messenger:lb_http_errors:ratio_rate2m
|
||||
expr: messenger:lb_http_errors:rate2m / messenger:lb_http_responses:rate2m
|
||||
- record: messenger:http_light_requests:rate2m
|
||||
expr: >-
|
||||
sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[2m]))
|
||||
- record: messenger:http_light_fast:rate2m
|
||||
expr: >-
|
||||
sum(rate(http_server_request_duration_seconds_bucket{job="messenger-api",le="0.25",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[2m]))
|
||||
- record: messenger:http_light_slow:ratio_rate2m
|
||||
expr: 1 - messenger:http_light_fast:rate2m / messenger:http_light_requests:rate2m
|
||||
# потери телеметрии по процессу (решение 9): Collector — отказ приёма
|
||||
# (memory_limiter), очередь экспорта полна, повторы истекли; SDK API,
|
||||
# worker и relay — отброшено из-за полной очереди и неудачные отправки.
|
||||
# Сумма, а не increase(): ряд отказов появляется с первой потерей, у
|
||||
# метрик Collector нет времени начала — первое значение нового ряда
|
||||
# целиком рост. Третья часть — ноль процесса SDK по ряду ёмкости очереди
|
||||
# span (есть с запуска): ряд суммы начинается с нуля, и rate() панели
|
||||
# потерь видит первую потерю (verify W1; у Collector ряды
|
||||
# otelcol_receiver_refused_* есть с нуля с его старта)
|
||||
- record: telemetry:lost_items:total
|
||||
expr: >-
|
||||
sum by (job, instance) ({__name__=~"otelcol_(receiver_refused|exporter_send_failed|exporter_enqueue_failed)_(spans|log_records|metric_points)"})
|
||||
or
|
||||
sum by (job, instance) ({__name__=~"otel_sdk_(processor|exporter)_(span|log)_(processed|exported)_total",error_type!=""})
|
||||
or
|
||||
sum by (job, instance) (otel_sdk_processor_span_queue_capacity) * 0
|
||||
|
||||
# приращения событий SLI за непересекающиеся 5-минутные окна: SLI любого
|
||||
# окна — отношение сумм, без чтения 7 суток histogram на каждое обновление
|
||||
- name: messenger-slo
|
||||
interval: 5m
|
||||
rules:
|
||||
- record: messenger:slo_availability_bad:increase5m
|
||||
expr: sum(increase(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry",code="5xx"}[5m]))
|
||||
- record: messenger:slo_availability_total:increase5m
|
||||
expr: sum(increase(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry"}[5m]))
|
||||
- record: messenger:slo_latency_good:increase5m
|
||||
expr: >-
|
||||
sum(increase(http_server_request_duration_seconds_bucket{job="messenger-api",le="0.25",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[5m]))
|
||||
- record: messenger:slo_latency_total:increase5m
|
||||
expr: >-
|
||||
sum(increase(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code!~"5..",http_route!~"/api/v1/users|/api/v1/auth/sessions|/api/v1/chats/.+/attachments|/api/v1/attachments/.+/content"}[5m]))
|
||||
- record: messenger:slo_time_to_ready_good:increase5m
|
||||
expr: sum(increase(messenger_job_time_to_ready_seconds_bucket{job="messenger-worker",le="30.0"}[5m]))
|
||||
- record: messenger:slo_time_to_ready_total:increase5m
|
||||
expr: sum(increase(messenger_job_time_to_ready_seconds_count{job="messenger-worker"}[5m]))
|
||||
|
||||
# оповещения о сервисе: пороги — 10 × допустимой доли SLO, шум отсекают for
|
||||
# и порог трафика 0,1 запроса/с (не меньше 12 запросов за окно)
|
||||
- name: messenger-alerts
|
||||
interval: 15s
|
||||
rules:
|
||||
- alert: MessengerHighErrorRate
|
||||
expr: messenger:lb_http_errors:ratio_rate2m > 0.05 and messenger:lb_http_responses:rate2m > 0.1
|
||||
for: 1m
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: High share of 5xx responses to clients on the load balancer
|
||||
description: >-
|
||||
{{ $value | humanizePercentage }} of responses of the public frontend
|
||||
in the last 2 minutes are 5xx (threshold 5 %, SLO 99.5 %), including
|
||||
responses generated by the load balancer itself. Runbook:
|
||||
infra/otel/runbooks/MessengerHighErrorRate.md
|
||||
runbook_url: infra/otel/runbooks/MessengerHighErrorRate.md
|
||||
- alert: MessengerSlowRequests
|
||||
expr: messenger:http_light_slow:ratio_rate2m > 0.1 and messenger:http_light_requests:rate2m > 0.1
|
||||
for: 1m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: Many light API requests are slower than 0.25 s
|
||||
description: >-
|
||||
{{ $value | humanizePercentage }} of light API requests without 5xx
|
||||
in the last 2 minutes took longer than 0.25 s (threshold 10 %, SLO
|
||||
99 %); login, registration and attachment bytes are not counted.
|
||||
Runbook: infra/otel/runbooks/MessengerSlowRequests.md
|
||||
runbook_url: infra/otel/runbooks/MessengerSlowRequests.md
|
||||
- alert: MessengerNoReadyReplicas
|
||||
expr: max(haproxy_backend_active_servers{job="haproxy",proxy="api"}) < 1
|
||||
for: 30s
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: No API replica is ready behind the load balancer
|
||||
description: >-
|
||||
The load balancer sees {{ $value }} ready API replicas: clients get
|
||||
503 from the load balancer. Fires without traffic too. Runbook:
|
||||
infra/otel/runbooks/MessengerNoReadyReplicas.md
|
||||
runbook_url: infra/otel/runbooks/MessengerNoReadyReplicas.md
|
||||
- alert: MessengerQueueLagHigh
|
||||
expr: max(messenger_queue_oldest_age_seconds{job="messenger-relay"}) > 60
|
||||
for: 1m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: The oldest unfinished attachment job is older than 60 s
|
||||
description: >-
|
||||
The oldest unfinished job waits {{ $value | humanizeDuration }}
|
||||
(threshold 60 s, time to ready SLO 30 s). Runbook:
|
||||
infra/otel/runbooks/MessengerQueueLagHigh.md
|
||||
runbook_url: infra/otel/runbooks/MessengerQueueLagHigh.md
|
||||
- alert: MessengerQueueMetricsMissing
|
||||
# снимка очереди relay нет (relay остановлен или не читает PostgreSQL),
|
||||
# и MessengerQueueLagHigh слеп; при недоступном экспортёре Collector
|
||||
# молчит — там срабатывает TelemetryTargetDown
|
||||
expr: absent(messenger_queue_oldest_age_seconds{job="messenger-relay"}) unless on() (up{job="otel-collector-exporter"} == 0)
|
||||
for: 2m
|
||||
labels:
|
||||
severity: warning
|
||||
# $value у absent() — всегда 1; текущее значение в описании — возраст
|
||||
# последнего снимка за час (verify S3)
|
||||
annotations:
|
||||
summary: The relay queue snapshot is missing
|
||||
description: >-
|
||||
There is no queue depth and age snapshot of the relay while the
|
||||
Collector exporter is up (last snapshot {{ with query `time() -
|
||||
max(max_over_time(timestamp(messenger_queue_oldest_age_seconds{job="messenger-relay"})[1h:15s]))`
|
||||
}}{{ . | first | value | humanizeDuration }} ago{{ else }}more
|
||||
than an hour ago{{ end }}): the relay is stopped or cannot read
|
||||
PostgreSQL, and MessengerQueueLagHigh is blind. Runbook:
|
||||
infra/otel/runbooks/MessengerQueueMetricsMissing.md
|
||||
runbook_url: infra/otel/runbooks/MessengerQueueMetricsMissing.md
|
||||
|
||||
# оповещения о самом конвейере телеметрии
|
||||
- name: telemetry-alerts
|
||||
interval: 15s
|
||||
rules:
|
||||
- alert: TelemetryTargetDown
|
||||
expr: up{job=~"otel-collector|loki|tempo|haproxy"} == 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: 'Metrics target {{ $labels.job }} is down'
|
||||
# $value — up цели (0); рядом — сколько целей правила недоступно
|
||||
# сейчас (verify S3)
|
||||
description: >-
|
||||
Prometheus cannot scrape {{ $labels.job }} ({{ $labels.instance }})
|
||||
for a minute (up {{ $value }}; targets of the rule down now: {{
|
||||
with query `count(up{job=~"otel-collector|loki|tempo|haproxy"} ==
|
||||
0)` }}{{ . | first | value }}{{ else }}0{{ end }}); with job
|
||||
haproxy the load balancer metrics are missing and
|
||||
MessengerHighErrorRate is blind. Runbook:
|
||||
infra/otel/runbooks/TelemetryTargetDown.md
|
||||
runbook_url: infra/otel/runbooks/TelemetryTargetDown.md
|
||||
- alert: TelemetryDataLoss
|
||||
# рост суммы потерь процесса за 2 мин; новый ряд — целиком рост, сброс
|
||||
# суммы (рестарт Collector) — отрицательный, оповещения нет
|
||||
expr: telemetry:lost_items:total - (telemetry:lost_items:total offset 2m or telemetry:lost_items:total * 0) > 0
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: 'Telemetry of {{ $labels.job }} is being lost'
|
||||
description: >-
|
||||
{{ $labels.job }} ({{ $labels.instance }}) lost {{ $value }} spans,
|
||||
log records or metric points in the last 2 minutes (full queue,
|
||||
failed export or refused by the memory limiter). Runbook:
|
||||
infra/otel/runbooks/TelemetryDataLoss.md
|
||||
runbook_url: infra/otel/runbooks/TelemetryDataLoss.md
|
||||
@@ -0,0 +1,68 @@
|
||||
# MessengerHighErrorRate
|
||||
|
||||
Правило — `infra/otel/prometheus/rules.yml`, группа `messenger-alerts`; решения — design change
|
||||
`slo-alerts`, решения 1, 2, 4. `severity: critical`.
|
||||
|
||||
## Что значит и на что влияет
|
||||
|
||||
Больше 5 % ответов публичного frontend LB (`entry`) за последние 2 минуты — 5xx, при трафике больше
|
||||
0,1 запроса/с, одну минуту подряд. В счёт входят и 5xx реплик API, и ответы, которые сгенерировал
|
||||
сам LB (502, 503, 504): клиент видит отказ. Порог — 10 × допустимой доли SLO доступности (99,5 %
|
||||
за 7 суток): при такой доле бюджет 7 суток уходит за ~17 часов.
|
||||
|
||||
## Первые панели
|
||||
|
||||
Dashboard «Messenger overview»:
|
||||
|
||||
1. «SLO and alerts» → «Alert windows: 5xx share on LB and slow light requests (2 min)» — доля 5xx
|
||||
на LB, порог 5 %; «Alert states» — что ещё в pending / firing.
|
||||
2. «Load balancer» → «5xx on LB and 5xx of API per second» — кто отвечает 5xx; «Ready replicas in
|
||||
LB» — сколько реплик в балансировке.
|
||||
3. «API (messenger-api)» → «Error ratio (5xx of all requests)», «Requests per second by route and
|
||||
status class» — какие маршруты.
|
||||
|
||||
## Диагностика (только по сохранённым наблюдениям)
|
||||
|
||||
Шаг 1 — кто отвечает 5xx. Prometheus:
|
||||
|
||||
```promql
|
||||
sum(rate(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry",code="5xx"}[2m]))
|
||||
sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code=~"5.."}[2m]))
|
||||
max(haproxy_backend_active_servers{job="haproxy",proxy="api"})
|
||||
```
|
||||
|
||||
- **PostgreSQL недоступен.** 5xx на LB растут, 5xx API — около нуля (запросы до API не доходят),
|
||||
готовых реплик 0, вместе с этим в firing `MessengerNoReadyReplicas`. Метрики API почти без
|
||||
запросов — поэтому SLI доступности считается на LB. Loki:
|
||||
`{service_name="messenger-api"} |= "Database is unavailable"` — записи `warning` реплик (модуль
|
||||
`database`) в начале отказа; Tempo: `{ resource.service.name = "messenger-api" && status = error
|
||||
&& span.db.system.name = "postgresql" }` — span запроса PostgreSQL с ошибкой у 503 реплик до
|
||||
вывода их из LB.
|
||||
- **Отказ реплик API (процесс).** 5xx на LB — 502 / 503 / 504, готовых реплик меньше
|
||||
`API_REPLICAS`, 5xx API — нет. `make lb_stats` — состояние слотов; журнал LB `docker compose logs
|
||||
haproxy` — смена состояния слотов и ответы LB (успешные не пишутся).
|
||||
- **5xx самого API.** 5xx API ≈ 5xx на LB, готовые реплики на месте. По маршрутам:
|
||||
`sum by (http_route, http_response_status_code) (rate(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code=~"5.."}[2m]))`;
|
||||
503 вложений при работающем остальном API — S3 (`{service_name="messenger-api"} |= "Object storage
|
||||
is unavailable"`, span `S3.*` с ошибкой); 500 — дефект: Tempo `{ resource.service.name =
|
||||
"messenger-api" && status = error }`, `span.error.type` — класс исключения, traceback — запись
|
||||
журнала с тем же `trace_id`.
|
||||
|
||||
## Действия
|
||||
|
||||
- PostgreSQL: `docker compose ps postgres`, `docker compose start postgres` (или `make start_db`),
|
||||
затем `make lb_stats` — реплики `UP`.
|
||||
- Реплики: `make replicas` (вернуть остановленные), `docker compose logs --no-log-prefix api`.
|
||||
- S3: `docker compose ps s3`, `make start_s3`.
|
||||
|
||||
## Восстановление
|
||||
|
||||
Оповещение снимается через 2–3 минуты после конца отказа (окно 2 мин). Проверить:
|
||||
`messenger:lb_http_errors:ratio_rate2m` ниже 0,05, готовых реплик `API_REPLICAS`, `make test` —
|
||||
`PASS`. Сколько бюджета ушло — панель «SLI over the dashboard range» за интервал отказа.
|
||||
|
||||
## Связанные оповещения
|
||||
|
||||
`MessengerNoReadyReplicas` (все реплики вне LB — почти всегда PostgreSQL),
|
||||
`TelemetryTargetDown{job="haproxy"}` (LB недоступен — это оповещение слепо),
|
||||
`MessengerQueueMetricsMissing` в pending при недоступном PostgreSQL (relay не читает снимок).
|
||||
@@ -0,0 +1,52 @@
|
||||
# MessengerNoReadyReplicas
|
||||
|
||||
Правило — `infra/otel/prometheus/rules.yml`, группа `messenger-alerts`; решения — design change
|
||||
`slo-alerts`, решения 2, 4. `severity: critical`.
|
||||
|
||||
## Что значит и на что влияет
|
||||
|
||||
LB не видит ни одной реплики API, прошедшей проверку готовности (`/health/ready`), 30 секунд
|
||||
подряд. Все запросы клиентов получают 503 от самого LB (формат ошибки контракта, без
|
||||
`X-Instance-Id`). Срабатывает и без трафика. Все реплики сразу выходят из LB почти всегда из-за
|
||||
PostgreSQL: `/health/ready` проверяет только его.
|
||||
|
||||
## Первые панели
|
||||
|
||||
1. «Load balancer» → «Ready replicas in LB», «5xx on LB and 5xx of API per second».
|
||||
2. «SLO and alerts» → «Alert states» — `MessengerHighErrorRate` при трафике рядом.
|
||||
|
||||
## Диагностика (только по сохранённым наблюдениям)
|
||||
|
||||
```promql
|
||||
max(haproxy_backend_active_servers{job="haproxy",proxy="api"})
|
||||
sum by (code) (rate(haproxy_frontend_http_responses_total{job="haproxy",proxy="entry"}[2m]))
|
||||
sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[2m]))
|
||||
up{job="haproxy"}
|
||||
```
|
||||
|
||||
- **PostgreSQL недоступен.** Готовых реплик 0, ответы LB — 5xx, запросов в метриках API почти нет
|
||||
(реплики живы, но вне LB). Loki: `{service_name="messenger-api"} |= "Database is unavailable"` —
|
||||
записи реплик в начале отказа; Tempo: `{ resource.service.name = "messenger-api" && status = error
|
||||
&& span.db.system.name = "postgresql" }`. Состояние: `docker compose ps postgres`.
|
||||
- **Реплики остановлены или падают.** Метрик реплик нет (`up` есть, а рядов
|
||||
`http_server_request_duration_seconds_count` с их `instance` больше нет), `docker compose ps api`
|
||||
— `exited` или `restarting`; журнал — `docker compose logs --no-log-prefix api`.
|
||||
- **Ряд пропал совсем** — недоступен сам LB или Collector: тогда это оповещение молчит, а
|
||||
срабатывает `TelemetryTargetDown` (`job="haproxy"` или `otel-collector`).
|
||||
|
||||
## Действия
|
||||
|
||||
- PostgreSQL: `docker compose start postgres` (или `make start_db`); реплики вернутся в LB сами за
|
||||
≤ 1,5 с после готовности.
|
||||
- Реплики: `make replicas`.
|
||||
- `make lb_stats` — слоты `UP`.
|
||||
|
||||
## Восстановление
|
||||
|
||||
Оповещение снимается на первом вычислении после возврата реплики (≤ 30 с). Проверить: готовых
|
||||
реплик `API_REPLICAS`, `make test` — `PASS`.
|
||||
|
||||
## Связанные оповещения
|
||||
|
||||
`MessengerHighErrorRate` (при трафике — те же 503 LB), `MessengerQueueMetricsMissing` (relay тоже не
|
||||
читает PostgreSQL), `TelemetryTargetDown{job="haproxy"}`.
|
||||
@@ -0,0 +1,60 @@
|
||||
# MessengerQueueLagHigh
|
||||
|
||||
Правило — `infra/otel/prometheus/rules.yml`, группа `messenger-alerts`; решения — design change
|
||||
`slo-alerts`, решение 4. `severity: warning`.
|
||||
|
||||
## Что значит и на что влияет
|
||||
|
||||
Старейшее незавершённое задание обработки вложения (`queued` или `processing`) ждёт дольше 60
|
||||
секунд, одну минуту подряд (растущий queue lag). Источник — снимок очереди relay из PostgreSQL.
|
||||
Вложения остаются `queued`: загрузка отвечает 202, текст и история работают, превью и варианты не
|
||||
появляются. Такое задание уже нарушает SLO времени до `ready` (30 с).
|
||||
|
||||
## Первые панели
|
||||
|
||||
1. «Pipeline» → «Age of the oldest unfinished job» (растёт линейно, если не разбирается ничего),
|
||||
«Queue depth by stage» (какая стадия копится), «Time to ready p50, p95 and p99».
|
||||
2. «Worker» → «Jobs per second by outcome»; «Saturation» → «Worker saturation».
|
||||
|
||||
## Диагностика (только по сохранённым наблюдениям)
|
||||
|
||||
```promql
|
||||
max by (messenger_queue_stage) (messenger_queue_depth{job="messenger-relay"})
|
||||
max(messenger_queue_oldest_age_seconds{job="messenger-relay"})
|
||||
sum(rate(messenger_job_duration_seconds_count{job="messenger-worker"}[2m]))
|
||||
count(messenger_worker_capacity{job="messenger-worker"})
|
||||
```
|
||||
|
||||
- **Worker остановлен или упал.** Растут `outbox` и `published` (relay публикует, никто не берёт),
|
||||
возраст растёт линейно, заданий в секунду 0, рядов `messenger-worker` нет (`count(...)` пусто —
|
||||
экспортёр убирает ряды остановленного процесса через ≤ 75 с). Loki:
|
||||
`{service_name="messenger-worker"}` — последняя запись worker (запись «Stopped worker» пишется
|
||||
после закрытия SDK, только в stdout: `docker compose logs --no-log-prefix worker`); Tempo: `{
|
||||
resource.service.name = "messenger-worker" && kind = consumer }` — consumer span после момента
|
||||
остановки нет.
|
||||
- **Worker перегружен.** Растёт `published`, задания в секунду есть, «Worker saturation» у 1,
|
||||
«Worker deliveries waiting for a slot» > 0, время задания (`Job duration`) выросло.
|
||||
- **Задания ждут повтора.** Растёт `scheduled` (временные ошибки: S3, PostgreSQL), в журнале worker —
|
||||
`{service_name="messenger-worker"} |= "Retrying job"` с `reason`.
|
||||
- **Relay не публикует.** Растёт `outbox`, `published` нет — брокер недоступен:
|
||||
`{service_name="messenger-relay"} |= "Broker is unavailable"`.
|
||||
|
||||
## Действия
|
||||
|
||||
- Worker: `docker compose ps worker`, `docker compose start worker` (или `docker compose up -d
|
||||
--no-deps worker`).
|
||||
- Брокер: `make start_broker`.
|
||||
- Перегрузка: второй worker или конкуренция по `.claude/rules/worker.md` («Подбор конкуренции»).
|
||||
|
||||
## Восстановление
|
||||
|
||||
После запуска worker очередь разбирается за секунды, возраст падает до нуля, оповещение снимается
|
||||
на первом вычислении ниже порога (≤ 2 мин с учётом сбора). Проверить: все вложения прогона
|
||||
`ready` (`GET /api/v1/attachments/{id}`), «Queue depth by stage» — ноль, время до `ready` этих
|
||||
вложений — не меньше длительности остановки (SLI времени до `ready` за окно — «SLI over the dashboard
|
||||
range»).
|
||||
|
||||
## Связанные оповещения
|
||||
|
||||
`MessengerQueueMetricsMissing` — снимка нет, и это оповещение слепо (relay остановлен или не читает
|
||||
PostgreSQL); `TelemetryTargetDown{job="otel-collector"}` — метрик нет совсем.
|
||||
@@ -0,0 +1,50 @@
|
||||
# MessengerQueueMetricsMissing
|
||||
|
||||
Правило — `infra/otel/prometheus/rules.yml`, группа `messenger-alerts`; решения — design change
|
||||
`slo-alerts`, решения 4, 6. `severity: warning`.
|
||||
|
||||
## Что значит и на что влияет
|
||||
|
||||
Снимка очереди relay (`messenger_queue_oldest_age_seconds{job="messenger-relay"}`) нет две минуты
|
||||
подряд, хотя экспортёр Collector доступен. Значит, relay остановлен или не читает PostgreSQL дольше
|
||||
30 с (снимок старше 30 с не отдаётся, экспортёр убирает ряд через минуту). Оповещение
|
||||
`MessengerQueueLagHigh` слепо. Если relay остановлен, новые задания не публикуются: вложения
|
||||
остаются `queued`. При недоступном экспортёре Collector оповещение молчит — там срабатывает
|
||||
`TelemetryTargetDown`.
|
||||
|
||||
## Первые панели
|
||||
|
||||
1. «Pipeline» → «Queue depth by stage», «Age of the oldest unfinished job» — пустые с момента
|
||||
отказа.
|
||||
2. «Telemetry pipeline» → «Metrics targets up» — Collector доступен.
|
||||
|
||||
## Диагностика (только по сохранённым наблюдениям)
|
||||
|
||||
```promql
|
||||
absent(messenger_queue_oldest_age_seconds{job="messenger-relay"})
|
||||
up{job="otel-collector-exporter"}
|
||||
count by (job) (target_info{job="messenger-relay"})
|
||||
```
|
||||
|
||||
- **Relay остановлен.** Рядов `messenger-relay` нет совсем (`target_info` тоже пуст), `docker
|
||||
compose ps relay` — `exited`; Loki: `{service_name="messenger-relay"}` — записей после остановки
|
||||
нет (запись «Stopped relay» — только в stdout: `docker compose logs --no-log-prefix relay`).
|
||||
- **Relay жив, PostgreSQL недоступен.** `target_info{job="messenger-relay"}` есть, а снимка нет;
|
||||
Loki: `{service_name="messenger-relay"} |= "Database is unavailable"` или `|= "Relay pass was
|
||||
interrupted"`; рядом `MessengerNoReadyReplicas`.
|
||||
|
||||
## Действия
|
||||
|
||||
- Relay: `docker compose start relay` (или `docker compose up -d --no-deps relay`).
|
||||
- PostgreSQL: `docker compose start postgres`.
|
||||
|
||||
## Восстановление
|
||||
|
||||
Первый снимок приходит через ≤ 5 с после прохода relay и ≤ 15 с отправки метрик, оповещение
|
||||
снимается на следующем вычислении (≤ 2 мин). Проверить: ряды глубины и возраста снова есть, очередь
|
||||
разобрана.
|
||||
|
||||
## Связанные оповещения
|
||||
|
||||
`MessengerQueueLagHigh` (слепо, пока снимка нет), `MessengerNoReadyReplicas` (PostgreSQL),
|
||||
`TelemetryTargetDown` (экспортёр Collector недоступен — это оповещение подавлено).
|
||||
@@ -0,0 +1,75 @@
|
||||
# MessengerSlowRequests
|
||||
|
||||
Правило — `infra/otel/prometheus/rules.yml`, группа `messenger-alerts`; решения — design change
|
||||
`slo-alerts`, решения 1, 4. `severity: warning`.
|
||||
|
||||
## Что значит и на что влияет
|
||||
|
||||
Больше 10 % «лёгких» запросов API без 5xx за последние 2 минуты длились дольше 0,25 с, при трафике
|
||||
больше 0,1 запроса/с, одну минуту подряд. «Лёгкие» — все маршруты, кроме регистрации и входа (KDF
|
||||
пароля), загрузки и скачивания байтов вложения. Порог — 10 × допустимой доли SLO задержки (99 % за
|
||||
7 суток). Клиенты ждут дольше обычного; ошибок может не быть.
|
||||
|
||||
## Первые панели
|
||||
|
||||
1. «SLO and alerts» → «Alert windows: 5xx share on LB and slow light requests (2 min)» — доля
|
||||
медленных, порог 10 %; «Slow light requests (traces longer than 0.25 s)» — трассы.
|
||||
2. «API (messenger-api)» → «Request duration p95 by route» — какой маршрут медленный.
|
||||
3. «Saturation» → «PostgreSQL pool: used of max», «PostgreSQL pool: waiting», «Container CPU of
|
||||
limit».
|
||||
|
||||
## Диагностика (только по сохранённым наблюдениям)
|
||||
|
||||
Шаг 1 — какие маршруты медленные:
|
||||
|
||||
```promql
|
||||
histogram_quantile(0.95, sum by (le, http_route) (rate(http_server_request_duration_seconds_bucket{job="messenger-api"}[2m])))
|
||||
```
|
||||
|
||||
Шаг 2 — трасса медленного запроса. Tempo (TraceQL):
|
||||
|
||||
```traceql
|
||||
{ kind = server && resource.service.name = "messenger-api" && duration > 250ms && span.http.route = "/api/v1/chats/{chat_id}/messages" }
|
||||
```
|
||||
|
||||
В трассе сравнить длительность server span и сумму span PostgreSQL (`INSERT`, `SELECT`, `COMMIT`,
|
||||
атрибут `db.system.name = "postgresql"`).
|
||||
|
||||
Шаг 3 — пул и CPU:
|
||||
|
||||
```promql
|
||||
sum by (job, instance) (db_client_connection_count{db_client_connection_state="used"}) / sum by (job, instance) (db_client_connection_max)
|
||||
sum by (job, instance) (db_client_connection_pending_requests)
|
||||
sum by (job, instance) (rate(container_cpu_time_seconds_total{job="messenger-api"}[2m])) / sum by (job, instance) (messenger_container_cpu_limit{job="messenger-api"})
|
||||
```
|
||||
|
||||
- **Медленная БД (блокировка, тяжёлый запрос, нехватка CPU PostgreSQL).** Медленны маршруты,
|
||||
которые пишут или читают затронутую таблицу (например, только отправка сообщения); в медленной
|
||||
трассе span PostgreSQL занимают больше половины server span; занятость пула выше обычной, есть
|
||||
ожидающие соединения; CPU реплик ниже половины предела. Кто держит блокировку — `docker compose
|
||||
exec postgres psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -c "SELECT pid, application_name, state,
|
||||
wait_event_type, query FROM pg_stat_activity WHERE wait_event_type = 'Lock' OR state = 'idle in
|
||||
transaction'"`.
|
||||
- **Медленный handler (CPU реплики).** Длинный server span, span PostgreSQL короткие (меньше пятой
|
||||
части), пул свободен, ожидающих нет, CPU реплик у предела. Если медленны только вход и
|
||||
регистрация (KDF) — это вне SLI, и оповещение не срабатывает: длительность входа видна на панели
|
||||
квантилей по маршрутам.
|
||||
- **Перегрузка.** Растёт RPS («Requests per second by route and status class»), медленны все
|
||||
маршруты, CPU реплик или PostgreSQL у предела.
|
||||
|
||||
## Действия
|
||||
|
||||
- Блокировка: найти сессию по `pg_stat_activity` и завершить (`SELECT pg_terminate_backend(<pid>)`),
|
||||
выяснить, кто её взял (`application_name`).
|
||||
- CPU реплик: `make replicas API_REPLICAS=<N>` (больше реплик), разбор горячего маршрута по трассам.
|
||||
|
||||
## Восстановление
|
||||
|
||||
Оповещение снимается через 2–4 минуты после конца причины. Проверить:
|
||||
`messenger:http_light_slow:ratio_rate2m` ниже 0,1, p95 маршрутов вернулся, SLI задержки за
|
||||
интервал — панель «SLI over the dashboard range».
|
||||
|
||||
## Связанные оповещения
|
||||
|
||||
`MessengerHighErrorRate` (если медленная БД дошла до сроков — 503 и 504), `MessengerNoReadyReplicas`
|
||||
(проверка готовности тоже не укладывается в срок).
|
||||
@@ -0,0 +1,60 @@
|
||||
# TelemetryDataLoss
|
||||
|
||||
Правило — `infra/otel/prometheus/rules.yml`, группа `telemetry-alerts`; решения — design change
|
||||
`slo-alerts`, решения 7–9. `severity: warning`, без `for`: потеря уже случилась.
|
||||
|
||||
## Что значит и на что влияет
|
||||
|
||||
Сумма учтённых потерь телеметрии процесса (`telemetry:lost_items:total`) выросла за последние 2
|
||||
минуты. Потери считают:
|
||||
|
||||
| Где | Счётчик |
|
||||
| --- | --- |
|
||||
| очередь SDK (API, worker, relay) | `otel_sdk_processor_{span,log}_processed_total{error_type="queue_full"}` |
|
||||
| отправка SDK | `otel_sdk_exporter_{span,log}_exported_total{error_type!=""}` |
|
||||
| приём Collector (`memory_limiter`) | `otelcol_receiver_refused_{spans,log_records,metric_points}` |
|
||||
| очередь экспорта Collector полна | `otelcol_exporter_enqueue_failed_{spans,log_records}` |
|
||||
| повторы экспорта Collector истекли (30 с) | `otelcol_exporter_send_failed_{spans,log_records}` |
|
||||
|
||||
Пропали трассы или записи журнала за интервал отказа; сообщения и вложения не затронуты. Метрики
|
||||
cumulative не теряют счёт — только точки.
|
||||
|
||||
## Первые панели
|
||||
|
||||
«Telemetry pipeline» → «Telemetry lost per second by place», «Collector export queues, share of
|
||||
capacity», «SDK queues, share of capacity», «Metrics targets up», «Collector memory».
|
||||
|
||||
## Диагностика (только по сохранённым наблюдениям)
|
||||
|
||||
```promql
|
||||
telemetry:lost_items:total
|
||||
sum by (job, instance, __name__, exporter, error_type) ({__name__=~"otelcol_(receiver_refused|exporter_send_failed|exporter_enqueue_failed)_(spans|log_records|metric_points)"})
|
||||
sum by (job, instance, __name__, error_type) ({__name__=~"otel_sdk_(processor|exporter)_(span|log)_(processed|exported)_total",error_type!=""})
|
||||
```
|
||||
|
||||
- **Хранилище (Tempo / Loki) недоступно дольше 30 с.** Растут `enqueue_failed` и `send_failed`
|
||||
экспортёра этого хранилища (`exporter="otlp_http/tempo"`), очередь у ёмкости, рядом
|
||||
`TelemetryTargetDown{job="tempo"}`. SLI приложения прежние.
|
||||
- **Collector недоступен или перегружен.** После его возврата растут счётчики SDK реплик
|
||||
(`error_type="queue_full"` — очередь 2048 заполнилась; `error_type="ConnectionError"` или
|
||||
`ReadTimeout` — отправка не удалась за 2 с); записей Loki за окно отказа меньше, чем в stdout
|
||||
(`docker compose logs --no-log-prefix api`).
|
||||
- **Предел памяти Collector.** Растут `otelcol_receiver_refused_*`, «Collector memory» у мягкого
|
||||
предела `memory_limiter` (160 МиБ); журнал Collector — «Memory usage is above soft limit».
|
||||
|
||||
## Действия
|
||||
|
||||
Вернуть хранилище или Collector (`docker compose start <сервис>`, runbook `TelemetryTargetDown`).
|
||||
Предел памяти — разобрать всплеск (пик span/с на панелях), при необходимости поднять лимит
|
||||
контейнера по правилу «лимит ≥ 1,5 × пика» (`.claude/rules/telemetry.md`).
|
||||
|
||||
## Восстановление
|
||||
|
||||
Оповещение снимается через 2 минуты без нового роста. Число потерь за отказ — разность
|
||||
`telemetry:lost_items:total` до и после (рестарт Collector сбрасывает его счётчики — рост
|
||||
отрицательный, оповещения нет).
|
||||
|
||||
## Связанные оповещения
|
||||
|
||||
`TelemetryTargetDown` (причина долгого отказа), `MessengerQueueMetricsMissing` (не срабатывает при
|
||||
недоступном Collector).
|
||||
@@ -0,0 +1,59 @@
|
||||
# TelemetryTargetDown
|
||||
|
||||
Правило — `infra/otel/prometheus/rules.yml`, группа `telemetry-alerts`; решения — design change
|
||||
`slo-alerts`, решения 2, 4, 7. `severity: warning`.
|
||||
|
||||
## Что значит и на что влияет
|
||||
|
||||
Prometheus минуту не может собрать метрики цели `otel-collector` (собственные метрики Collector),
|
||||
`loki`, `tempo` или `haproxy` (метрики LB через приёмник Collector). Приложение от телеметрии не
|
||||
зависит: API и worker работают, `make test` проходит. Теряется наблюдаемость:
|
||||
|
||||
- `otel-collector` — Collector недоступен: метрик, логов и трасс приложения нет, SDK копит в своих
|
||||
очередях и теряет сверх них (учтено, `TelemetryDataLoss` после возврата);
|
||||
- `loki` / `tempo` — хранилище недоступно: Collector держит данные в очереди экспорта (16 / 8 МиБ)
|
||||
и повторяет 30 с, дальше отбрасывает (учтено);
|
||||
- `haproxy` — LB недоступен для сбора (или сам LB лежит): `MessengerHighErrorRate` и
|
||||
`MessengerNoReadyReplicas` слепы.
|
||||
|
||||
## Первые панели
|
||||
|
||||
«Telemetry pipeline» → «Metrics targets up», «Collector export queues, share of capacity»,
|
||||
«Telemetry lost per second by place», «Collector memory».
|
||||
|
||||
## Диагностика (только по сохранённым наблюдениям)
|
||||
|
||||
```promql
|
||||
up{job=~"otel-collector|otel-collector-exporter|loki|tempo|haproxy"}
|
||||
max by (exporter) (otelcol_exporter_queue_size{job="otel-collector"}) / max by (exporter) (otelcol_exporter_queue_capacity{job="otel-collector"})
|
||||
sum by (exporter) (otelcol_exporter_send_failed_spans{job="otel-collector"})
|
||||
otelcol_process_runtime_total_sys_memory_bytes{job="otel-collector"}
|
||||
```
|
||||
|
||||
- **Tempo или Loki остановлен.** `up{job="tempo"}` (или `loki`) = 0, очередь экспорта этого
|
||||
хранилища растёт к ёмкости, потом растут `otelcol_exporter_enqueue_failed_*` и
|
||||
`otelcol_exporter_send_failed_*`; память Collector ниже лимита (256 МиБ); метрики приложения и SLI
|
||||
прежние — теряется телеметрия, а не сообщения. Журнал Collector: `docker compose logs
|
||||
otel-collector` — «Exporting failed» с именем экспортёра. `docker compose ps tempo loki`.
|
||||
- **Collector остановлен.** `up{job="otel-collector"}` и `up{job="otel-collector-exporter"}` = 0,
|
||||
ряды приложения пропали, `MessengerQueueMetricsMissing` подавлено. В stdout реплик — записи SDK
|
||||
«Failed to export» не чаще раза в минуту на логгер.
|
||||
- **LB.** `up{job="haproxy"}` = 0 при работающем Collector — LB недоступен по `haproxy:8404`:
|
||||
`docker compose ps haproxy`, `make lb_stats`.
|
||||
|
||||
## Действия
|
||||
|
||||
`docker compose start <сервис>` (`otel-collector`, `loki`, `tempo`, `haproxy`); после правки
|
||||
конфигурации — `docker compose up -d --force-recreate <сервис>`.
|
||||
|
||||
## Восстановление
|
||||
|
||||
`up` = 1, оповещение снимается на следующем вычислении. Очередь экспорта разбирается до нуля,
|
||||
новые записи и трассы находятся (Loki `{service_name="messenger-api"}`, Tempo `{
|
||||
resource.service.name = "messenger-api" }`). Потери за отказ — счётчики `TelemetryDataLoss`.
|
||||
|
||||
## Связанные оповещения
|
||||
|
||||
`TelemetryDataLoss` (потери долгого отказа), `MessengerQueueMetricsMissing` (подавлено при
|
||||
недоступном экспортёре Collector), `MessengerHighErrorRate` (слепо при `job="haproxy"`).
|
||||
Отказ самого Prometheus оповещением не ловится: в Grafana — ошибка источника.
|
||||
@@ -0,0 +1,41 @@
|
||||
# Tempo 3.1.1 — хранилище трасс (design change otel-telemetry, решение 15).
|
||||
# Монолит (-target=all) с локальным хранилищем, без Kafka, metrics-generator и
|
||||
# MCP. Приём — OTLP/HTTP от Collector на :4318, запросы Grafana — :3200; оба
|
||||
# порта только в сети telemetry. Блоки и WAL — volume tempo_data
|
||||
# (/var/tempo), срок хранения блоков — 7 суток.
|
||||
stream_over_http_enabled: true
|
||||
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
log_level: info
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
|
||||
# срок хранения блоков. В Tempo 3.x задания удаления ставит backend-scheduler
|
||||
# (retention provider), выполняет backend-worker; у обоих свой ключ
|
||||
# block_retention (по умолчанию 336h), поэтому оба — 7 суток
|
||||
backend_scheduler:
|
||||
provider:
|
||||
compaction:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
backend_worker:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,6 @@
|
||||
# Предел памяти брокера задан явно: лимит контейнера он не видит (проба: 4760
|
||||
# МиБ при лимите 512 МБ, design change async-attachments, Context) и был бы
|
||||
# завершён ядром, а не сдерживал публикацию. Сработавший предел блокирует
|
||||
# публикацию: загрузки получают 503 по сроку, сообщения не теряются.
|
||||
# Новую настройку этого файла проверять запуском: неверное имя — отказ старта.
|
||||
vm_memory_high_watermark.absolute = 400MiB
|
||||
@@ -0,0 +1,14 @@
|
||||
# Откат реплик на образ до change `pipeline-reliability` (design, Migration Plan):
|
||||
# прежний код публикует задание сам, и без адреса и пароля брокера его загрузка — 503.
|
||||
#
|
||||
# make rolling_update COMMIT=7f38948 MIGRATE=0 \
|
||||
# COMPOSE_FILE=docker-compose.yml:infra/rollback/broker.compose.yml
|
||||
#
|
||||
# Только на время отката: у реплик этого кода пароля брокера быть не должно.
|
||||
services:
|
||||
api:
|
||||
environment:
|
||||
BROKER__HOST: ${RABBITMQ_HOST:-rabbitmq}
|
||||
BROKER__PORT: ${RABBITMQ_PORT:-5672}
|
||||
BROKER__USER: ${RABBITMQ_DEFAULT_USER:?RABBITMQ_DEFAULT_USER is not set, run make env_setup}
|
||||
BROKER__PASSWORD: ${RABBITMQ_DEFAULT_PASS:?RABBITMQ_DEFAULT_PASS is empty, run make env_setup}
|
||||
Executable
+600
@@ -0,0 +1,600 @@
|
||||
#!/bin/sh
|
||||
# Bootstrap S3 стенда (SeaweedFS): приватный bucket, пользователь API с
|
||||
# политикой «только объекты своего bucket», пользователь уборщика с
|
||||
# политикой «чтение и удаление объектов своего bucket и их список только по
|
||||
# префиксу вложений своей базы» (S3_CLEANER_LIST_PREFIX, <база>/attachments/:
|
||||
# для сверки bucket и БД), пользователь worker с политикой «чтение и запись
|
||||
# объектов своего bucket», проверки приватности вне API. Design change
|
||||
# s3-storage, решения 3, 4 и 8, design change upload-consistency, решение 8,
|
||||
# design change track2-reconciler, решение 2, design change
|
||||
# async-attachments, решение 12; правила — docker.md.
|
||||
#
|
||||
# Запускается сервисом compose s3-bootstrap на образе сервера в сетевом
|
||||
# пространстве сервиса s3 (network_mode: service:s3): master и filer
|
||||
# слушают 127.0.0.1 сервера, из сети стенда их нет. Административные
|
||||
# вызовы — weed shell с ключом подписи (WEED_JWT_FILER_SIGNING_KEY), а не
|
||||
# административной парой S3: её хранит только сервер.
|
||||
#
|
||||
# Режимы:
|
||||
# apply (по умолчанию) — свести состояние к окружению (.env) и проверить
|
||||
# права; каждый шаг безопасно повторять;
|
||||
# check — ничего не менять в настройке, проверить права и приватность
|
||||
# шире, чем apply: чужой bucket (временный, создаётся и удаляется
|
||||
# здесь же), административные запросы ключей API и уборщика, запись
|
||||
# ключом уборщика, его список по своему префиксу (200), без префикса и
|
||||
# с чужим (403), права ключа worker, анонимные запросы. Общий проверочный
|
||||
# объект остаётся для проверок с хоста и из сети (make s3_check) до
|
||||
# режима cleanup; объект проверок удаления ключом уборщика — свой;
|
||||
# cleanup — удалить проверочные объекты и временные bucket-ы check.
|
||||
#
|
||||
# Секреты: в weed shell — через stdin (printf — встроенная команда sh), в
|
||||
# curl — файлом -K на tmpfs; в argv процессов и в выводе их нет. Ошибка
|
||||
# шага — «FAILED: <шаг>» и код 1.
|
||||
set -eu
|
||||
|
||||
MODE=${1:-apply}
|
||||
BUCKET=${S3_BUCKET:?S3_BUCKET is not set}
|
||||
S3_PORT=${S3_PORT:?S3_PORT is not set}
|
||||
: "${S3_API_ACCESS_KEY:?S3_API_ACCESS_KEY is empty, copy S3 lines from .env.example}"
|
||||
: "${S3_API_SECRET_KEY:?S3_API_SECRET_KEY is empty, copy S3 lines from .env.example}"
|
||||
: "${S3_CLEANER_ACCESS_KEY:?S3_CLEANER_ACCESS_KEY is empty, run make env_setup}"
|
||||
: "${S3_CLEANER_SECRET_KEY:?S3_CLEANER_SECRET_KEY is empty, run make env_setup}"
|
||||
: "${S3_WORKER_ACCESS_KEY:?S3_WORKER_ACCESS_KEY is empty, run make env_setup}"
|
||||
: "${S3_WORKER_SECRET_KEY:?S3_WORKER_SECRET_KEY is empty, run make env_setup}"
|
||||
: "${WEED_JWT_FILER_SIGNING_KEY:?S3_JWT_SIGNING_KEY is empty, copy S3 lines from .env.example}"
|
||||
# префикс списка уборщика: имя базы и /attachments/; в JSON политики идёт
|
||||
# только проверенное значение
|
||||
LIST_PREFIX=${S3_CLEANER_LIST_PREFIX:-}
|
||||
|
||||
MASTER=127.0.0.1:9333
|
||||
S3=http://127.0.0.1:${S3_PORT}
|
||||
API_USER=api
|
||||
API_POLICY=api-objects
|
||||
CLEANER_USER=cleaner
|
||||
CLEANER_POLICY=cleaner-objects
|
||||
WORKER_USER=worker
|
||||
WORKER_POLICY=worker-objects
|
||||
# регион подписи; SeaweedFS берёт его из запроса
|
||||
REGION=us-east-1
|
||||
TAG="s3-bootstrap"
|
||||
# проверочный объект make s3_check: один и тот же ключ, повтор
|
||||
# перезаписывает остаток прерванного прогона
|
||||
CHECK_KEY=.s3-check/probe
|
||||
# объект проверок ключа уборщика: его он удаляет, общий нужен проверкам с
|
||||
# хоста
|
||||
CLEANER_CHECK_KEY=.s3-check/cleaner-probe
|
||||
# объект проверок ключа worker: его он пишет; удаляет ключ API
|
||||
WORKER_CHECK_KEY=.s3-check/worker-probe
|
||||
CHECK_BUCKET_PREFIX="${BUCKET}-check-"
|
||||
# сколько секунд ждать, пока изменения IAM дойдут до шлюза (подписка на
|
||||
# filer)
|
||||
IAM_WAIT_SECONDS=10
|
||||
|
||||
umask 077
|
||||
WORK=$(mktemp -d)
|
||||
API_CRED="$WORK/api.cred"
|
||||
CLEANER_CRED="$WORK/cleaner.cred"
|
||||
WORKER_CRED="$WORK/worker.cred"
|
||||
BODY="$WORK/body"
|
||||
TEMP_BUCKET=""
|
||||
|
||||
cleanup_work() {
|
||||
if [ -n "$TEMP_BUCKET" ]; then
|
||||
ws "s3.bucket.delete -name ${TEMP_BUCKET}" >/dev/null 2>&1 || true
|
||||
fi
|
||||
rm -rf "$WORK"
|
||||
}
|
||||
trap cleanup_work EXIT
|
||||
|
||||
say() {
|
||||
echo "${TAG}: $*"
|
||||
}
|
||||
|
||||
fail() {
|
||||
echo "${TAG}: FAILED: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
# одна команда weed shell; вывод — в stdout, код — код shell
|
||||
ws() {
|
||||
printf '%s\n' "$1" | weed shell -master="$MASTER" 2>&1
|
||||
}
|
||||
|
||||
# команда без секретов: при ошибке печатается вывод shell
|
||||
ws_step() {
|
||||
step=$1
|
||||
shift
|
||||
if ! out=$(ws "$*"); then
|
||||
printf '%s\n' "$out" | sed "s/^/${TAG}: /" >&2
|
||||
fail "$step"
|
||||
fi
|
||||
}
|
||||
|
||||
# команда с секретом: вывод не печатается никогда
|
||||
ws_secret_step() {
|
||||
step=$1
|
||||
shift
|
||||
ws "$*" >/dev/null || fail "$step"
|
||||
}
|
||||
|
||||
# ключи API, уборщика и worker для curl: файлы на tmpfs, в argv только путь
|
||||
printf 'user = "%s:%s"\n' "$S3_API_ACCESS_KEY" "$S3_API_SECRET_KEY" \
|
||||
>"$API_CRED"
|
||||
printf 'user = "%s:%s"\n' "$S3_CLEANER_ACCESS_KEY" "$S3_CLEANER_SECRET_KEY" \
|
||||
>"$CLEANER_CRED"
|
||||
printf 'user = "%s:%s"\n' "$S3_WORKER_ACCESS_KEY" "$S3_WORKER_SECRET_KEY" \
|
||||
>"$WORKER_CRED"
|
||||
|
||||
# подписанный ключом из файла $1 запрос: печатает код ответа, тело — в
|
||||
# $BODY
|
||||
signed_by() {
|
||||
cred=$1
|
||||
shift
|
||||
curl -s -o "$BODY" -w '%{http_code}' --max-time 5 -K "$cred" \
|
||||
--aws-sigv4 "aws:amz:${REGION}:s3" "$@" || echo 000
|
||||
}
|
||||
|
||||
# подписанный ключом API запрос
|
||||
signed() {
|
||||
signed_by "$API_CRED" "$@"
|
||||
}
|
||||
|
||||
# подписанный ключом уборщика запрос
|
||||
cleaner_signed() {
|
||||
signed_by "$CLEANER_CRED" "$@"
|
||||
}
|
||||
|
||||
# подписанный ключом worker запрос
|
||||
worker_signed() {
|
||||
signed_by "$WORKER_CRED" "$@"
|
||||
}
|
||||
|
||||
# анонимный запрос: печатает код ответа
|
||||
anon() {
|
||||
curl -s -o "$BODY" -w '%{http_code}' --max-time 5 "$@" || echo 000
|
||||
}
|
||||
|
||||
FAILED_CHECKS=0
|
||||
|
||||
# строка проверки: имя, ожидаемый и полученный код. Код выхода 1 — в
|
||||
# конце, после всех строк
|
||||
check() {
|
||||
name=$1
|
||||
expected=$2
|
||||
got=$3
|
||||
if [ "$expected" = "$got" ]; then
|
||||
verdict=ok
|
||||
else
|
||||
verdict=FAIL
|
||||
FAILED_CHECKS=$((FAILED_CHECKS + 1))
|
||||
fi
|
||||
printf '%s: check\t%s\t%s\t%s\t%s\n' "$TAG" "$name" "$expected" "$got" "$verdict"
|
||||
}
|
||||
|
||||
bucket_exists() {
|
||||
ws "s3.bucket.list" | grep -qE "^[[:space:]]*$1([[:space:]]|\$)"
|
||||
}
|
||||
|
||||
# ждать, пока ключ примет шлюз: изменения IAM доходят подпиской на filer.
|
||||
# $1 — ожидаемый код, остальное — запрос signed_by с файлом ключа.
|
||||
# SignatureDoesNotMatch — ключ есть, секрет другой: возвращается 2
|
||||
wait_key() {
|
||||
expected=$1
|
||||
shift
|
||||
i=0
|
||||
while [ "$i" -lt "$IAM_WAIT_SECONDS" ]; do
|
||||
code=$(signed_by "$@")
|
||||
if [ "$code" = "$expected" ]; then
|
||||
return 0
|
||||
fi
|
||||
if [ "$code" = 403 ] && grep -q SignatureDoesNotMatch "$BODY"; then
|
||||
return 2
|
||||
fi
|
||||
i=$((i + 1))
|
||||
sleep 1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# ключ API — записью проверочного объекта
|
||||
wait_api_key() {
|
||||
wait_key 200 "$API_CRED" -X PUT --data-binary "$TAG" "$1"
|
||||
}
|
||||
|
||||
# ключ уборщика — удалением ключа, которого нет (запись ему запрещена):
|
||||
# 204, как у удаления существующего
|
||||
wait_cleaner_key() {
|
||||
wait_key 204 "$CLEANER_CRED" -X DELETE "$1"
|
||||
}
|
||||
|
||||
# ключ worker — записью проверочного объекта, как у API
|
||||
wait_worker_key() {
|
||||
wait_key 200 "$WORKER_CRED" -X PUT --data-binary "$TAG" "$1"
|
||||
}
|
||||
|
||||
# ждать ключ пользователя $1 через функцию $2 с адресом $3; новый секрет
|
||||
# (SignatureDoesNotMatch) — пересоздать ключ и ждать снова
|
||||
wait_user_key() {
|
||||
user=$1
|
||||
waiter=$2
|
||||
url=$3
|
||||
status=0
|
||||
"$waiter" "$url" || status=$?
|
||||
if [ "$status" = 2 ]; then
|
||||
recreate_key "$user"
|
||||
status=0
|
||||
"$waiter" "$url" || status=$?
|
||||
fi
|
||||
[ "$status" = 0 ] || fail "${user} key wait (code ${code})"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- apply
|
||||
|
||||
apply_bucket() {
|
||||
if bucket_exists "$BUCKET"; then
|
||||
say "bucket ${BUCKET} exists"
|
||||
else
|
||||
ws_step "bucket create" "s3.bucket.create -name ${BUCKET}"
|
||||
say "bucket ${BUCKET} created"
|
||||
fi
|
||||
# анонимный доступ — none; меняется, только если он открыт
|
||||
if ! ws "s3.anonymous.get -bucket ${BUCKET}" | grep -q '^Access: none$'; then
|
||||
ws_step "anonymous access none" \
|
||||
"s3.anonymous.set -bucket ${BUCKET} -access none"
|
||||
say "anonymous access to ${BUCKET} closed"
|
||||
fi
|
||||
}
|
||||
|
||||
# политика $1 с действиями $2 (JSON-список) над объектами своего bucket
|
||||
put_policy() {
|
||||
cat >"$WORK/policy.json" <<EOF
|
||||
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
|
||||
"Action": $2,
|
||||
"Resource": ["arn:aws:s3:::${BUCKET}/*"]}]}
|
||||
EOF
|
||||
ws_step "policy put $1" "s3.policy -put -name=$1 -file=$WORK/policy.json"
|
||||
}
|
||||
|
||||
# префикс списка уборщика — только вида <база>/attachments/: иначе в
|
||||
# условие политики попало бы что угодно
|
||||
check_list_prefix() {
|
||||
database=${LIST_PREFIX%/attachments/}
|
||||
# ^[a-z0-9_]+/attachments/$: суффикс на месте, имя базы непустое и без
|
||||
# других символов (в том числе перевода строки и «/»)
|
||||
case "$database" in
|
||||
"$LIST_PREFIX" | "" | *[!a-z0-9_]*)
|
||||
fail "cleaner list prefix: S3_CLEANER_LIST_PREFIX must be <database>/attachments/"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# уборщику — чтение и удаление объектов своего bucket и их список только с
|
||||
# префиксом вложений своей базы (условие s3:prefix соблюдает SeaweedFS 4.48:
|
||||
# весь bucket, другой префикс и HEAD bucket — 403); без записи и прав на
|
||||
# bucket (design change track2-reconciler, решение 2). С change
|
||||
# pipeline-reliability (решение 9) — ещё префикс staging той же базы: выводится
|
||||
# из уже проверенного имени
|
||||
staging_list_prefix() {
|
||||
printf '%s/staging/' "${LIST_PREFIX%/attachments/}"
|
||||
}
|
||||
|
||||
put_cleaner_policy() {
|
||||
cat >"$WORK/policy.json" <<EOF
|
||||
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::${BUCKET}/*"]},
|
||||
{"Effect": "Allow", "Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::${BUCKET}"],
|
||||
"Condition": {"StringLike": {"s3:prefix": ["${LIST_PREFIX}*", "$(staging_list_prefix)*"]}}}]}
|
||||
EOF
|
||||
ws_step "policy put ${CLEANER_POLICY}" \
|
||||
"s3.policy -put -name=${CLEANER_POLICY} -file=$WORK/policy.json"
|
||||
}
|
||||
|
||||
apply_policies() {
|
||||
put_policy "$API_POLICY" \
|
||||
'["s3:GetObject", "s3:PutObject", "s3:DeleteObject"]'
|
||||
put_cleaner_policy
|
||||
# worker: читает staging, пишет конечный префикс; удаления и списка нет.
|
||||
# По <bucket>/*, а не по префиксу: make test_isolated работает под
|
||||
# test_<db>/ с теми же ключами (design change async-attachments, решение 12)
|
||||
put_policy "$WORKER_POLICY" '["s3:GetObject", "s3:PutObject"]'
|
||||
}
|
||||
|
||||
# ключ и секрет пользователя $1 — из окружения (.env)
|
||||
user_keys() {
|
||||
case "$1" in
|
||||
"$API_USER")
|
||||
ACCESS_KEY=$S3_API_ACCESS_KEY
|
||||
SECRET_KEY=$S3_API_SECRET_KEY
|
||||
;;
|
||||
"$CLEANER_USER")
|
||||
ACCESS_KEY=$S3_CLEANER_ACCESS_KEY
|
||||
SECRET_KEY=$S3_CLEANER_SECRET_KEY
|
||||
;;
|
||||
"$WORKER_USER")
|
||||
ACCESS_KEY=$S3_WORKER_ACCESS_KEY
|
||||
SECRET_KEY=$S3_WORKER_SECRET_KEY
|
||||
;;
|
||||
*) fail "unknown user $1" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# пользователь $1 с политикой $2 и ключом из окружения; повтор — no-op
|
||||
apply_user() {
|
||||
name=$1
|
||||
policy=$2
|
||||
user_keys "$name"
|
||||
if ws "s3.user.show -name ${name}" >/dev/null; then
|
||||
say "user ${name} exists"
|
||||
else
|
||||
ws_secret_step "user ${name} create" \
|
||||
"s3.user.create -name ${name} -access_key ${ACCESS_KEY} -secret_key ${SECRET_KEY}"
|
||||
say "user ${name} created"
|
||||
fi
|
||||
ws_step "policy attach ${name}" \
|
||||
"s3.policy.attach -policy ${policy} -user ${name}"
|
||||
# ключи пользователя: чужие удаляются, нужного нет — создаётся
|
||||
if ! keys_out=$(ws "s3.accesskey.list -user ${name}"); then
|
||||
fail "access key list ${name}"
|
||||
fi
|
||||
keys=$(printf '%s\n' "$keys_out" | awk 'NR > 1 && NF { print $1 }')
|
||||
for key in $keys; do
|
||||
if [ "$key" != "$ACCESS_KEY" ]; then
|
||||
ws_secret_step "stale key delete ${name}" \
|
||||
"s3.accesskey.delete -user ${name} -access_key ${key}"
|
||||
say "stale key of ${name} removed"
|
||||
fi
|
||||
done
|
||||
if ! printf '%s\n' "$keys" | grep -qxF "$ACCESS_KEY"; then
|
||||
ws_secret_step "key create ${name}" \
|
||||
"s3.accesskey.create -user ${name} -access_key ${ACCESS_KEY} -secret_key ${SECRET_KEY}"
|
||||
say "key of ${name} created"
|
||||
fi
|
||||
}
|
||||
|
||||
recreate_key() {
|
||||
user_keys "$1"
|
||||
ws_secret_step "key delete $1" \
|
||||
"s3.accesskey.delete -user $1 -access_key ${ACCESS_KEY}"
|
||||
ws_secret_step "key create $1" \
|
||||
"s3.accesskey.create -user $1 -access_key ${ACCESS_KEY} -secret_key ${SECRET_KEY}"
|
||||
say "key of $1 recreated (secret changed)"
|
||||
}
|
||||
|
||||
# проверки каждого запуска: ключ API пишет и читает проверочный объект,
|
||||
# список и создание bucket — 403; ключ уборщика читает его, запись и
|
||||
# список — 403, затем удаляет; после удаления ключ API получает 404; ключ
|
||||
# worker пишет и читает свой объект, читает объект API (тут же записанный),
|
||||
# удаление, список и создание bucket — 403, объект убирает ключ API;
|
||||
# аноним не читает объект и не видит список
|
||||
apply_checks() {
|
||||
probe="${S3}/${BUCKET}/.s3-bootstrap/check-$$"
|
||||
wait_user_key "$API_USER" wait_api_key "$probe"
|
||||
[ "$(signed "$probe")" = 200 ] || fail "api key get"
|
||||
[ "$(anon "$probe")" = 403 ] || fail "anonymous get is not denied"
|
||||
[ "$(anon "${S3}/${BUCKET}?list-type=2")" = 403 ] \
|
||||
|| fail "anonymous list is not denied"
|
||||
[ "$(signed "${S3}/${BUCKET}?list-type=2")" = 403 ] \
|
||||
|| fail "api key list is not denied"
|
||||
[ "$(signed -X PUT "${S3}/${CHECK_BUCKET_PREFIX}forbidden-$$")" = 403 ] \
|
||||
|| fail "api key bucket create is not denied"
|
||||
wait_user_key "$CLEANER_USER" wait_cleaner_key \
|
||||
"${S3}/${BUCKET}/.s3-bootstrap/missing-$$"
|
||||
[ "$(cleaner_signed "$probe")" = 200 ] && [ "$(cat "$BODY")" = "$TAG" ] \
|
||||
|| fail "cleaner key get"
|
||||
[ "$(cleaner_signed -X PUT --data-binary "$TAG" "$probe")" = 403 ] \
|
||||
|| fail "cleaner key put is not denied"
|
||||
[ "$(cleaner_signed "${S3}/${BUCKET}?list-type=2")" = 403 ] \
|
||||
|| fail "cleaner key list is not denied"
|
||||
# список своего префикса: политика доходит до шлюза подпиской, как ключ
|
||||
wait_key 200 "$CLEANER_CRED" "$(list_url "$LIST_PREFIX")" \
|
||||
|| fail "cleaner key list ${LIST_PREFIX} (code ${code})"
|
||||
wait_key 200 "$CLEANER_CRED" "$(list_url "$(staging_list_prefix)")" \
|
||||
|| fail "cleaner key list $(staging_list_prefix) (code ${code})"
|
||||
[ "$(cleaner_signed -X DELETE "$probe")" = 204 ] || fail "cleaner key delete"
|
||||
[ "$(signed "$probe")" = 404 ] || fail "object is still there after delete"
|
||||
worker_probe="${S3}/${BUCKET}/.s3-bootstrap/worker-check-$$"
|
||||
wait_user_key "$WORKER_USER" wait_worker_key "$worker_probe"
|
||||
[ "$(worker_signed "$worker_probe")" = 200 ] && [ "$(cat "$BODY")" = "$TAG" ] \
|
||||
|| fail "worker key get"
|
||||
[ "$(signed -X PUT --data-binary "$TAG api" "$probe")" = 200 ] \
|
||||
|| fail "api key put for worker"
|
||||
[ "$(worker_signed "$probe")" = 200 ] && [ "$(cat "$BODY")" = "$TAG api" ] \
|
||||
|| fail "worker key get object of api key"
|
||||
[ "$(worker_signed -X DELETE "$worker_probe")" = 403 ] \
|
||||
|| fail "worker key delete is not denied"
|
||||
[ "$(worker_signed "${S3}/${BUCKET}?list-type=2")" = 403 ] \
|
||||
|| fail "worker key list is not denied"
|
||||
[ "$(worker_signed "$(list_url "$LIST_PREFIX")")" = 403 ] \
|
||||
|| fail "worker key list ${LIST_PREFIX} is not denied"
|
||||
[ "$(worker_signed -X PUT "${S3}/${CHECK_BUCKET_PREFIX}forbidden-$$")" = 403 ] \
|
||||
|| fail "worker key bucket create is not denied"
|
||||
[ "$(signed -X DELETE "$probe")" = 204 ] || fail "api key delete probe"
|
||||
[ "$(signed -X DELETE "$worker_probe")" = 204 ] \
|
||||
|| fail "api key delete worker probe"
|
||||
say "checks passed (api key put/get; cleaner key get/delete and list" \
|
||||
"${LIST_PREFIX} and $(staging_list_prefix); worker key put/get; api key list and bucket create," \
|
||||
"cleaner key put and list of the bucket, worker key delete, list and" \
|
||||
"bucket create, anonymous get and list denied)"
|
||||
}
|
||||
|
||||
# адрес ListObjectsV2 своего bucket с префиксом $1 (символы [a-z0-9_.-/],
|
||||
# «/» — %2F в строке запроса подписи) и одним ключом
|
||||
list_url() {
|
||||
encoded=$(printf '%s' "$1" | sed 's#/#%2F#g')
|
||||
printf '%s' "${S3}/${BUCKET}?list-type=2&max-keys=1&prefix=${encoded}"
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- check
|
||||
|
||||
run_checks() {
|
||||
bucket_exists "$BUCKET" || fail "bucket ${BUCKET} does not exist, run make run_docker"
|
||||
access=$(ws "s3.anonymous.get -bucket ${BUCKET}" \
|
||||
| sed -n 's/^Access: //p')
|
||||
check "anonymous access setting" none "${access:-unknown}"
|
||||
|
||||
obj="${S3}/${BUCKET}/${CHECK_KEY}"
|
||||
missing="${S3}/${BUCKET}/.s3-check/missing-$$"
|
||||
# ключ API: объекты своего bucket
|
||||
check "api key put object" 200 \
|
||||
"$(signed -X PUT --data-binary "$TAG check" "$obj")"
|
||||
check "api key get object" 200 "$(signed "$obj")"
|
||||
check "api key head object" 200 "$(signed -I "$obj")"
|
||||
check "api key get missing object" 404 "$(signed "$missing")"
|
||||
# ключ API: всё остальное запрещено
|
||||
check "api key list objects" 403 "$(signed "${S3}/${BUCKET}?list-type=2")"
|
||||
check "api key create bucket" 403 \
|
||||
"$(signed -X PUT "${S3}/${CHECK_BUCKET_PREFIX}forbidden-$$")"
|
||||
check "api key delete bucket" 403 "$(signed -X DELETE "${S3}/${BUCKET}")"
|
||||
check "api key get bucket policy" 403 "$(signed "${S3}/${BUCKET}?policy")"
|
||||
check "api key put bucket policy" 403 \
|
||||
"$(signed -X PUT --data-binary '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::'"${BUCKET}"'/*"}]}' "${S3}/${BUCKET}?policy")"
|
||||
check "api key get bucket acl" 403 "$(signed "${S3}/${BUCKET}?acl")"
|
||||
check "api key put bucket acl public-read" 403 \
|
||||
"$(signed -X PUT -H 'x-amz-acl: public-read' "${S3}/${BUCKET}?acl")"
|
||||
check "api key put object acl public-read" 403 \
|
||||
"$(signed -X PUT -H 'x-amz-acl: public-read' "${obj}?acl")"
|
||||
# ключ уборщика: чтение и удаление объектов своего bucket; удаляет он
|
||||
# свой проверочный объект, общий нужен проверкам с хоста
|
||||
own="${S3}/${BUCKET}/${CLEANER_CHECK_KEY}"
|
||||
check "api key put cleaner probe object" 200 \
|
||||
"$(signed -X PUT --data-binary "$TAG cleaner" "$own")"
|
||||
check "cleaner key get object" 200 "$(cleaner_signed "$own")"
|
||||
check "cleaner key head object" 200 "$(cleaner_signed -I "$own")"
|
||||
check "cleaner key delete object" 204 "$(cleaner_signed -X DELETE "$own")"
|
||||
check "cleaner key delete object again" 204 \
|
||||
"$(cleaner_signed -X DELETE "$own")"
|
||||
check "api key get deleted object" 404 "$(signed "$own")"
|
||||
check "cleaner key delete missing object" 204 \
|
||||
"$(cleaner_signed -X DELETE "$missing")"
|
||||
# ключ уборщика: запись, список и всё, что с bucket, запрещено
|
||||
check "cleaner key put object" 403 \
|
||||
"$(cleaner_signed -X PUT --data-binary "$TAG" "$own")"
|
||||
check "cleaner key list objects" 403 \
|
||||
"$(cleaner_signed "${S3}/${BUCKET}?list-type=2")"
|
||||
check "cleaner key list attachments prefix" 200 \
|
||||
"$(cleaner_signed "$(list_url "$LIST_PREFIX")")"
|
||||
check "cleaner key list staging prefix" 200 \
|
||||
"$(cleaner_signed "$(list_url "$(staging_list_prefix)")")"
|
||||
check "cleaner key list database prefix" 403 \
|
||||
"$(cleaner_signed "$(list_url "${LIST_PREFIX%attachments/}")")"
|
||||
check "cleaner key list other prefix" 403 \
|
||||
"$(cleaner_signed "$(list_url .s3-check/)")"
|
||||
check "cleaner key create bucket" 403 \
|
||||
"$(cleaner_signed -X PUT "${S3}/${CHECK_BUCKET_PREFIX}forbidden-$$")"
|
||||
check "cleaner key delete bucket" 403 \
|
||||
"$(cleaner_signed -X DELETE "${S3}/${BUCKET}")"
|
||||
check "cleaner key get bucket policy" 403 \
|
||||
"$(cleaner_signed "${S3}/${BUCKET}?policy")"
|
||||
check "cleaner key put bucket policy" 403 \
|
||||
"$(cleaner_signed -X PUT --data-binary '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::'"${BUCKET}"'/*"}]}' "${S3}/${BUCKET}?policy")"
|
||||
check "cleaner key get bucket acl" 403 \
|
||||
"$(cleaner_signed "${S3}/${BUCKET}?acl")"
|
||||
check "cleaner key put bucket acl public-read" 403 \
|
||||
"$(cleaner_signed -X PUT -H 'x-amz-acl: public-read' "${S3}/${BUCKET}?acl")"
|
||||
check "cleaner key put object acl public-read" 403 \
|
||||
"$(cleaner_signed -X PUT -H 'x-amz-acl: public-read' "${obj}?acl")"
|
||||
# ключ worker: чтение и запись объектов своего bucket, в том числе объект,
|
||||
# записанный ключом API
|
||||
worker_own="${S3}/${BUCKET}/${WORKER_CHECK_KEY}"
|
||||
check "worker key put object" 200 \
|
||||
"$(worker_signed -X PUT --data-binary "$TAG worker" "$worker_own")"
|
||||
check "worker key get object" 200 "$(worker_signed "$worker_own")"
|
||||
check "worker key head object" 200 "$(worker_signed -I "$worker_own")"
|
||||
check "worker key get object of api key" 200 "$(worker_signed "$obj")"
|
||||
# ключ worker: удаление, список и всё, что с bucket, запрещено
|
||||
check "worker key delete object" 403 "$(worker_signed -X DELETE "$worker_own")"
|
||||
check "api key get object after worker delete" 200 "$(signed "$worker_own")"
|
||||
check "worker key list objects" 403 \
|
||||
"$(worker_signed "${S3}/${BUCKET}?list-type=2")"
|
||||
check "worker key list attachments prefix" 403 \
|
||||
"$(worker_signed "$(list_url "$LIST_PREFIX")")"
|
||||
check "worker key create bucket" 403 \
|
||||
"$(worker_signed -X PUT "${S3}/${CHECK_BUCKET_PREFIX}forbidden-$$")"
|
||||
check "worker key delete bucket" 403 \
|
||||
"$(worker_signed -X DELETE "${S3}/${BUCKET}")"
|
||||
check "worker key get bucket policy" 403 \
|
||||
"$(worker_signed "${S3}/${BUCKET}?policy")"
|
||||
check "worker key put bucket policy" 403 \
|
||||
"$(worker_signed -X PUT --data-binary '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::'"${BUCKET}"'/*"}]}' "${S3}/${BUCKET}?policy")"
|
||||
check "worker key get bucket acl" 403 \
|
||||
"$(worker_signed "${S3}/${BUCKET}?acl")"
|
||||
check "worker key put bucket acl public-read" 403 \
|
||||
"$(worker_signed -X PUT -H 'x-amz-acl: public-read' "${S3}/${BUCKET}?acl")"
|
||||
check "worker key put object acl public-read" 403 \
|
||||
"$(worker_signed -X PUT -H 'x-amz-acl: public-read' "${worker_own}?acl")"
|
||||
# чужой bucket: временный, создаёт и удаляет weed shell
|
||||
TEMP_BUCKET="${CHECK_BUCKET_PREFIX}$(od -An -N4 -tx4 /dev/urandom | tr -d ' ')"
|
||||
ws_step "temporary bucket create" "s3.bucket.create -name ${TEMP_BUCKET}"
|
||||
other="${S3}/${TEMP_BUCKET}"
|
||||
check "api key put object to other bucket" 403 \
|
||||
"$(signed -X PUT --data-binary "$TAG" "${other}/probe")"
|
||||
check "api key get object from other bucket" 403 "$(signed "${other}/probe")"
|
||||
check "api key list other bucket" 403 "$(signed "${other}?list-type=2")"
|
||||
check "api key delete other bucket" 403 "$(signed -X DELETE "$other")"
|
||||
check "cleaner key get object from other bucket" 403 \
|
||||
"$(cleaner_signed "${other}/probe")"
|
||||
check "cleaner key delete object in other bucket" 403 \
|
||||
"$(cleaner_signed -X DELETE "${other}/probe")"
|
||||
check "cleaner key list other bucket" 403 \
|
||||
"$(cleaner_signed "${other}?list-type=2")"
|
||||
check "cleaner key delete other bucket" 403 \
|
||||
"$(cleaner_signed -X DELETE "$other")"
|
||||
check "worker key put object to other bucket" 403 \
|
||||
"$(worker_signed -X PUT --data-binary "$TAG" "${other}/probe")"
|
||||
check "worker key get object from other bucket" 403 \
|
||||
"$(worker_signed "${other}/probe")"
|
||||
check "worker key list other bucket" 403 \
|
||||
"$(worker_signed "${other}?list-type=2")"
|
||||
ws_step "temporary bucket delete" "s3.bucket.delete -name ${TEMP_BUCKET}"
|
||||
TEMP_BUCKET=""
|
||||
# аноним изнутри сервера; с хоста и из сети стенда — make s3_check
|
||||
check "anonymous get object" 403 "$(anon "$obj")"
|
||||
check "anonymous head object" 403 "$(anon -I "$obj")"
|
||||
check "anonymous get missing object" 403 "$(anon "$missing")"
|
||||
check "anonymous list objects" 403 "$(anon "${S3}/${BUCKET}?list-type=2")"
|
||||
check "anonymous list buckets" 403 "$(anon "${S3}/")"
|
||||
check "anonymous put object" 403 \
|
||||
"$(anon -X PUT --data-binary "$TAG" "${S3}/${BUCKET}/.s3-check/anonymous")"
|
||||
check "anonymous create bucket" 403 \
|
||||
"$(anon -X PUT "${S3}/${CHECK_BUCKET_PREFIX}anonymous-$$")"
|
||||
if [ "$FAILED_CHECKS" -gt 0 ]; then
|
||||
fail "${FAILED_CHECKS} check(s) failed"
|
||||
fi
|
||||
say "checks passed; probe object ${BUCKET}/${CHECK_KEY} kept for host and network checks"
|
||||
}
|
||||
|
||||
run_cleanup() {
|
||||
for key in "$CHECK_KEY" "$CLEANER_CHECK_KEY" "$WORKER_CHECK_KEY"; do
|
||||
code=$(signed -X DELETE "${S3}/${BUCKET}/${key}")
|
||||
case "$code" in
|
||||
204 | 404) say "probe object ${BUCKET}/${key} removed" ;;
|
||||
*) fail "probe object delete (code ${code})" ;;
|
||||
esac
|
||||
done
|
||||
# временные bucket-ы прерванных проверок
|
||||
for name in $(ws "s3.bucket.list" | awk '{ print $1 }' \
|
||||
| grep -E "^${CHECK_BUCKET_PREFIX}[0-9a-f]+\$" || true); do
|
||||
ws_step "temporary bucket delete" "s3.bucket.delete -name ${name}"
|
||||
say "temporary bucket ${name} removed"
|
||||
done
|
||||
}
|
||||
|
||||
case "$MODE" in
|
||||
apply | check) check_list_prefix ;;
|
||||
esac
|
||||
|
||||
case "$MODE" in
|
||||
apply)
|
||||
apply_bucket
|
||||
apply_policies
|
||||
apply_user "$API_USER" "$API_POLICY"
|
||||
apply_user "$CLEANER_USER" "$CLEANER_POLICY"
|
||||
apply_user "$WORKER_USER" "$WORKER_POLICY"
|
||||
apply_checks
|
||||
;;
|
||||
check) run_checks ;;
|
||||
cleanup) run_cleanup ;;
|
||||
*) fail "unknown mode ${MODE}: apply, check or cleanup" ;;
|
||||
esac
|
||||
@@ -0,0 +1,15 @@
|
||||
# Valkey стенда — кэш карточек чатов (change membership-cache).
|
||||
# Монтируется в контейнер только на чтение. Порт и пароль задаёт command
|
||||
# в docker-compose.yml из переменных .env, здесь их нет.
|
||||
|
||||
# лимит памяти; при нехватке вытесняются давно не читанные ключи
|
||||
maxmemory 64mb
|
||||
maxmemory-policy allkeys-lru
|
||||
|
||||
# persistence выключен: источник истины — PostgreSQL, кэш после рестарта
|
||||
# пуст и заполняется заново при чтении
|
||||
save ""
|
||||
appendonly no
|
||||
|
||||
# без пароля сервер не примет соединения извне контейнера
|
||||
protected-mode yes
|
||||
Reference in New Issue
Block a user