feat: import lab 7 security implementation
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
# Телеметрия стенда (`infra/otel/`)
|
||||
|
||||
Collector, Prometheus, Loki, Tempo, Grafana, их TLS-шлюзы, правила, runbooks.
|
||||
`README.md` — skeleton. Сначала прочитай `infra/AGENTS.md` (compose, HAProxy, PKI).
|
||||
Имена метрик и меток — контракт `contracts/observability.md`.
|
||||
|
||||
```
|
||||
api, relay, worker ─mTLS→ otel-gateway :4318 ─loopback→ Collector 127.0.0.1:14318
|
||||
Collector (otel-collector-client) ─mTLS→ loki-gateway :3100 ─loopback→ Loki 127.0.0.1:13100
|
||||
─mTLS→ tempo-gateway :4318 ─loopback→ Tempo 127.0.0.1:14318
|
||||
─mTLS, имя ingress→ haproxy :8404 (только GET /metrics)
|
||||
Prometheus (prometheus-client) ─mTLS→ loki :3100, tempo :3200, otel-gateway :8888 / :8889 (→ 18888 / 18889)
|
||||
Grafana (grafana-client) ─mTLS→ loki :3100, tempo :3200 (→ 13200), prometheus-gateway :9090 (→ 19090)
|
||||
оператор ─HTTPS (leaf grafana, SAN localhost)→ 127.0.0.1:GRAFANA_HOST_PORT
|
||||
healthcheck каждого шлюза → 127.0.0.1:8405 /ready (сервис за шлюзом не проверяется)
|
||||
```
|
||||
|
||||
## Сервисы (лаба 6)
|
||||
|
||||
- Наружу (127.0.0.1) — только Grafana (`GRAFANA_HOST_PORT`, с лабы 7 HTTPS). Порты
|
||||
Collector, Prometheus, Loki, Tempo не публиковать: для проверок их читают через
|
||||
прокси источников Grafana.
|
||||
- Collector `0.164.0` (`collector.yaml`): приём OTLP/HTTP — `127.0.0.1:14318`
|
||||
пространства шлюза, конвейер `memory_limiter` (180/36 МиБ при лимите контейнера
|
||||
256) → `batch`; метрики отдаёт экспортёром для Prometheus (`metric_expiration` 3
|
||||
мин), логи и трассы — OTLP/HTTP в Loki и Tempo с очередью 20 000 элементов без
|
||||
блокировки и повтором до 60 с; забирает метрики LB (`prometheus/haproxy`, ряды
|
||||
`job="haproxy"`, с лабы 7). Образы без оболочки: healthcheck нет.
|
||||
- Prometheus: `prometheus.yml` (задания `messenger` — Collector 8889,
|
||||
`otel-collector` 8888, `loki`, `tempo`, `prometheus`), `rules.yml` (SLO и три
|
||||
alert), `rules.test.yml` (promtool); хранение 7 сут или 1 ГБ. Loki и Tempo — по 168
|
||||
ч. Grafana: provisioning источников (`datasources.yaml`) и dashboard
|
||||
`messenger-lab6.json` из файлов; ручных правок в UI нет. uid `messenger-lab6`
|
||||
сохранён: на него ссылаются `scripts/lab7.py`, runbooks и `make grafana`.
|
||||
- Правка `prometheus.yml` — та же правка копии `bench/otel/prometheus-lean.yml` (вне
|
||||
блоков `>>> lean` файлы совпадают построчно, `bench/telemetry.py --selftest`).
|
||||
- Лимиты: Collector 0,5 CPU / 256 МиБ; Prometheus, Loki, Tempo, Grafana — по 0,25 CPU,
|
||||
320 / 384 / 512 / 448 МиБ; шлюзы — `otel-gateway` 0,25 / 56 МиБ, трёх хранилищ по
|
||||
0,1 / 56 МиБ (по замеру: 0,003 CPU, пик 34–35 МиБ; правило «лимит ≥ 1,5 × пика»:
|
||||
`docker compose exec loki-gateway cat /sys/fs/cgroup/memory.peak`). Суммы —
|
||||
`infra/AGENTS.md`, «`compose.yaml`».
|
||||
- Ограничения (перенос `container-hardening`, `infra/AGENTS.md`, «Ограничения
|
||||
контейнеров»): у всех сервисов телеметрии `x-hardened` (корень только на чтение, без
|
||||
capabilities, `no-new-privileges`) и `pids` — Collector, Prometheus, Loki, Tempo 128
|
||||
(рантайм Go), шлюзы 64, Grafana 256. Запись — только в volumes и tmpfs: Loki — `/tmp`
|
||||
32m (метки retention compactor через ~10 мин после старта: без него «failed to
|
||||
process marks / create marker writer … read-only file system» и чанки старше срока не
|
||||
удаляются); Grafana — `/var/lib/grafana` 128m (472:0, 0770) и `/tmp` 16m (без него
|
||||
backend источников не стартуют, а `/api/health` отвечает), `GF_LOG_MODE=console`
|
||||
(иначе ошибка файлового журнала). Новый путь записи — tmpfs с пределом.
|
||||
- Runbooks `runbooks/*.md` — по одному на alert; имя файла указано в `runbook_url`
|
||||
правила.
|
||||
|
||||
## mTLS к Collector (лаба 7, перенос `telemetry-mtls`)
|
||||
|
||||
- **Identity**: `otel-collector` (server, SAN — имя, по которому подключается и
|
||||
которое проверяет SDK; `.pem` шлюзу), `api-client` (client, SAN `api`): у leaf `api`
|
||||
только `serverAuth`, назначения не смешиваются — LB проверяет у реплики `sslserver`,
|
||||
allowlist реплики `api` не пускает, пользователя `api` у брокера нет; отзыв — по
|
||||
имени строки (`make pki-revoke IDENTITY=api-client`). Worker и relay предъявляют те
|
||||
же leaf, что брокеру.
|
||||
- **Шлюз** — `gateway.cfg`, образ и digest LB, `OPENSSL_CONF` —
|
||||
`infra/haproxy/openssl.cnf` (билетов нет — нет возобновления в обход CRL): `verify
|
||||
required`, CA, CRL, `ssl-min-ver TLSv1.3`; allowlist — `tcp-request session reject`
|
||||
вне `ssl_c_san -m str DNS:api DNS:worker DNS:relay` (вся строка SAN, ровно одно
|
||||
имя), закрытие до чтения запроса; дальше — только `POST /v1/traces|metrics|logs`,
|
||||
остальное 404. Журнал — только отказы и недоступность Collector: `otlp-refused
|
||||
<адрес> san=… reason=… cert_err=…`, `otlp … status=503`. **Новый отправитель —
|
||||
строка `identities.conf` и имя в allowlist вместе**
|
||||
(`test_gateway_allowlist_matches_identities`).
|
||||
- **Остановленный Collector** — закрытие соединения без ответа (`errorfile 503
|
||||
/dev/null` в `backend collector`): ответ 503 SDK не считает исключением экспорта, а
|
||||
ошибку соединения повторяет и считает потерей. В журнале шлюза остаётся `status=503
|
||||
bytes=0`. Бэкенды метрик отвечают 503 (Prometheus считает отказ scrape сам).
|
||||
- **Топология**: шлюз владеет сетевым пространством (сети `default` и `telemetry`,
|
||||
алиас `otel-collector` в обеих), Collector — `network_mode: service:otel-gateway`,
|
||||
свои `networks` и алиасы ему не давать. Health шлюза Collector не проверяет: тот
|
||||
ждёт `service_healthy` шлюза. Рестарты — раздел «Шлюз владеет пространством» ниже.
|
||||
- **Файлы** шлюз и SDK читают при старте. CRL и пары SDK — пересоздание api, worker,
|
||||
relay.
|
||||
- **SDK** — `src/AGENTS.md`, «mTLS к Collector»: только `https`, контекст один раз,
|
||||
без файлов код 2. Отказ шлюза — недоступность Collector: SDK теряет сигналы,
|
||||
приложение работает. Консоль (`make run*`) и временные стенды телеметрию выключают
|
||||
— файлов не нужно.
|
||||
- **Остаточное**: identity не связана с содержимым — разрешённый процесс может
|
||||
прислать сигналы с чужим `service.name`.
|
||||
|
||||
## TLS хранилищ телеметрии, метрик и Grafana (лаба 7, перенос `telemetry-backends-tls`)
|
||||
|
||||
- **Identity** (`infra/pki/identities.conf`): серверные `loki`, `tempo`, `prometheus`
|
||||
(SAN = имя, bundle — шлюзам) и `grafana` (SAN `grafana,localhost`, split — интерфейс);
|
||||
клиентские `otel-collector-client` (SAN `otel-collector`), `prometheus-client`
|
||||
(`prometheus`), `grafana-client` (`grafana`). Назначения не смешиваются, отзыв — по
|
||||
имени строки. Порт метрик LB берёт серверный leaf `ingress`, порты метрик Collector —
|
||||
`otel-collector`.
|
||||
- **Шлюз на хранилище** — `loki-gateway.cfg`, `tempo-gateway.cfg`,
|
||||
`prometheus-gateway.cfg` (якорь `x-storage-gateway` compose: образ LB, `OPENSSL_CONF`,
|
||||
healthcheck, лимиты; плюс `x-hardened`). Родной TLS Loki и Tempo проверяет у клиента
|
||||
только цепочку — ни allowlist, ни прав по пути, ни CRL. Каждый `bind … ssl` —
|
||||
`verify required`, CA и CRL стенда, `ssl-min-ver TLSv1.3`; allowlist порта — вся
|
||||
строка SAN равна одному имени, чужая identity закрывается до чтения запроса.
|
||||
- **Права** — по методу и точному списку путей, в конце `deny 403` с заголовком
|
||||
`X-Gateway-Refused: <шлюз>` (по нему проверка отличает отказ шлюза от ответа
|
||||
хранилища):
|
||||
|
||||
| Порт | Identity | Разрешено |
|
||||
|---|---|---|
|
||||
| `loki:3100` | `otel-collector` | `POST /otlp/v1/logs` |
|
||||
| | `grafana` | `GET /loki/api/v1/…` — запросы, метки, серии, `index/…`, `detected_…`, `patterns`, `status/buildinfo` |
|
||||
| | `prometheus` | `GET /metrics` |
|
||||
| `tempo:4318` | `otel-collector` | `POST /v1/traces` |
|
||||
| `tempo:3200` | `grafana` | `GET /api/echo`, `search…`, `v2/search/…`, `traces/…`, `v2/traces/…`, `status/buildinfo`, `metrics/…` |
|
||||
| | `prometheus` | `GET /metrics` |
|
||||
| `prometheus:9090` | `grafana` | `GET`, `POST` `/api/v1/…` — запросы, метки, серии, метаданные, цели, правила, оповещения, `status/…` |
|
||||
| `otel-collector:8888`, `:8889` | `prometheus` | `GET /metrics` (иначе 404) |
|
||||
| `haproxy:8404` | `otel-collector` | `GET /metrics` (иначе 404) |
|
||||
|
||||
Нет ни у кого: push и удаление Loki, `/config`, `/flush`, `/ring`, `/status/config`
|
||||
Tempo, `/federate`, `/-/*`, административный API, remote write и приём OTLP
|
||||
Prometheus, `/metrics` Prometheus, статистика LB с сети. **Новый путь Grafana или
|
||||
`scripts/lab7.py` — строка списка шлюза** (признак — 403 с `X-Gateway-Refused` в
|
||||
журнале), а не `path_beg`; новая identity — строка `identities.conf`, allowlist и
|
||||
права вместе. Сверяет `student-tests/unit/test_telemetry_backends_tls.py`.
|
||||
- **Путь, который хранилище прочло бы иначе, чем шлюз** (`%XX`, `//`, сегменты `.` и
|
||||
`..`), отвергает первое правило каждого frontend хранилища (`unsafe_path`). У порта
|
||||
запросов Tempo разрешён `%3A`: Grafana кодирует им двоеточие встроенных тегов
|
||||
(`span:name`). Регулярные выражения HAProxy — без обратной косой (`[.]`).
|
||||
- **Хранилища** слушают только `127.0.0.1` пространства шлюза: Loki 13100 / 9095, Tempo
|
||||
13200 / 14318 / 9095, Prometheus 19090 (номера портов шлюза в том же пространстве
|
||||
заняты). Себя Prometheus забирает и проверяется healthcheck по этому loopback.
|
||||
Потоковые запросы Tempo выключены (`stream_over_http_enabled: false`,
|
||||
`streamingEnabled` источника): gRPC через шлюз не идёт.
|
||||
- **LB**: `frontend monitor` `:8404` — mTLS, только `GET /metrics` для Collector
|
||||
(встроенный экспортёр, ряды frontend и backend); статистика и `/lb/ready` —
|
||||
`frontend health` на `127.0.0.1:8405` контейнера LB (healthcheck, `make lb-stats`,
|
||||
`bench/`).
|
||||
- **Клиенты** (Collector `tls` / `tls_config`, Prometheus `tls_config`, Grafana
|
||||
`tlsAuthWithCACert`) проверяют сервер по CA стенда и имени, **CRL не читают** — не
|
||||
умеют (как клиенты PostgreSQL, Valkey, S3): отозванный серверный leaf они примут до
|
||||
перевыпуска; `insecure_skip_verify`, `tlsSkipVerify` и системные корни не добавлять.
|
||||
CRL читают шлюзы и LB.
|
||||
- **Grafana** — `GF_SERVER_PROTOCOL=https`, TLS ≥ 1.2 (браузер и скрипты на хосте),
|
||||
healthcheck — `curl --cacert … --resolve localhost:3000:127.0.0.1`. Источники — пара
|
||||
`grafana-client`, пути `$__file{/run/secrets/…}` в `datasources.yaml` (PEM в git нет).
|
||||
`scripts/lab7.py` — `https://localhost:<порт>` с `--ca-file`; браузеру — импорт
|
||||
`.pki/stand/ca.crt`. Неверный пароль подряд не пробовать: защита Grafana от перебора
|
||||
заблокирует `admin` на 5 мин.
|
||||
- **Файлы PKI** (`secrets`): шлюзам — `ca.crt`, `crl.pem`, свой `.pem`; Collector,
|
||||
Prometheus — `ca.crt` и клиентская пара; Grafana — `ca.crt`, `grafana.*`,
|
||||
`grafana-client.*`; у Loki и Tempo файлов нет.
|
||||
- **Журналы шлюзов** — `dontlog-normal` и `http-ignore-probes` (соединения без запроса,
|
||||
закрытые клиентом, строк не дают; `dontlognull` не ставить — убрал бы отказы
|
||||
identity): `<шлюз>-refused … san=… reason=… cert_err=…` (рукопожатие и identity),
|
||||
`<шлюз> … <метод> <путь> status=403|503|504` (путь без query, без тел).
|
||||
- `make alerts-test` — `promtool check config` с пустыми заглушками файлов
|
||||
`/run/secrets/…` (существование), затем check и test правил.
|
||||
|
||||
## Шлюз владеет пространством: рестарты (все четыре шлюза)
|
||||
|
||||
Collector, Loki, Tempo и Prometheus живут в сетевом пространстве своего шлюза
|
||||
(`<шлюз>` → `<сервис>`):
|
||||
|
||||
- правка `*gateway.cfg` (редактор пишет новый файл, bind mount показывает прежний
|
||||
inode) и новый CRL — `docker compose restart <шлюз>`: сервис перезапустится с ним
|
||||
(`depends_on … restart: true`);
|
||||
- рестарт шлюза политикой Docker, `stop` + `start` (или `up -d`, в том числе `make
|
||||
up`) одного шлюза сервис не трогают — он без сети: `docker compose restart <шлюз>`
|
||||
(или `restart <сервис>`); `make stop` + `make up` всего стенда безопасны;
|
||||
- пересоздание одного шлюза (`up -d --force-recreate <шлюз>`, правка его сервиса)
|
||||
оставляет сервис в пространстве удалённого контейнера: `docker compose up -d
|
||||
<сервис>` (`restart` — «No such container»); `make up` пересоздаёт оба;
|
||||
- у Prometheus такой отказ **немой**: оповещения считает он сам. Признаки — ошибка
|
||||
источника Prometheus в Grafana, `docker compose ps`, `NetworkMode` контейнера не
|
||||
`container:<id шлюза>`; всё это называет `make telemetry-tls-check`.
|
||||
|
||||
Признаки и действия — `runbooks/telemetry-down.md`.
|
||||
|
||||
## Стенды, переход, проверка
|
||||
|
||||
- `stand.py` телеметрию не запускает (новые `secrets` берутся из PKI прогона);
|
||||
`bench/` — шлюзы `vlad-bench-*-gw` у профиля `telemetry` (с лабы 7 не
|
||||
поддерживается), паспорт `stand.telemetry_tls`, `bench/lookup.py` ходит парами
|
||||
`grafana-client` и `prometheus-client` PKI прогона.
|
||||
- **Переход рабочего стенда**: `make up` — `pki-stand` выпускает семь leaf, создаются
|
||||
три шлюза, пересоздаются LB, `otel-gateway`, Collector, хранилища и Grafana; `.env` и
|
||||
volume не меняются. Grafana — `https://localhost:<порт>`. Откат: `docker compose rm
|
||||
-sf loki-gateway tempo-gateway prometheus-gateway otel-gateway loki tempo prometheus
|
||||
otel-collector`, прежний commit, `make up` (иначе оставшиеся шлюзы делили бы алиасы с
|
||||
прежними хранилищами).
|
||||
- **Проверка**: `make telemetry-tls-check [REPORT=1]` (`scripts/lab7.py
|
||||
telemetry-tls-check`, докстринг) — приём OTLP из сетей `default` и `telemetry`, семь
|
||||
каналов хранилищ и метрик (`TB_CHANNELS`: отказы TLS и identity, разрешённое и
|
||||
запрещённое каждой identity, обходные пути), отзыв на разовых шлюзах тех же
|
||||
конфигураций со своей временной PKI (CRL стенда не трогается), порты, источники и
|
||||
HTTPS Grafana, журналы шлюзов, рост метрик трёх сервисов, цели `up`. `REPORT=1` — без
|
||||
вердикта, годится и для стенда «до» (`5ae607b`; там проверка красная). Метка
|
||||
`vladimirceva.telemetry-tls-check`, уборка контейнеров и каталогов ключей — при
|
||||
любом исходе. Evidence — `evidence/security/telemetry-mtls.txt`,
|
||||
`telemetry-backends-tls.txt`.
|
||||
- Правка чего угодно здесь — ещё `make telemetry-check`, `make alerts-test`; учения —
|
||||
`make telemetry-outage`, `make alerts-check`.
|
||||
@@ -0,0 +1,154 @@
|
||||
# OpenTelemetry Collector contrib 0.164.0 стенда vladimirceva-lab7.
|
||||
#
|
||||
# Collector — не хранилище: принимает OTLP от api, worker и relay, держит
|
||||
# ограниченный буфер и раскладывает сигналы по трём backend:
|
||||
# метрики → экспортёр prometheus :8889 → его забирает Prometheus;
|
||||
# логи → OTLP/HTTP в Loki (родной приёмник /otlp);
|
||||
# трассы → OTLP/HTTP в Tempo.
|
||||
# Лаба 7, перенос telemetry-mtls: Collector работает в сетевом пространстве
|
||||
# TLS-шлюза otel-gateway (infra/otel/gateway.cfg) и слушает только его loopback;
|
||||
# :4318, :8888 и :8889 с mTLS и allowlist identity — порты шлюза. Перенос
|
||||
# telemetry-backends-tls: экспорт в Loki и Tempo и scrape LB — https через их
|
||||
# TLS-порты с leaf otel-collector-client (файлы — secrets Collector). Наружу ничего
|
||||
# не опубликовано (compose.yaml).
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
# SDK приложения шлёт только OTLP/HTTP protobuf; gRPC не включён. Только
|
||||
# loopback: аутентификация — у шлюза, из сетей стенда приёмника нет
|
||||
http:
|
||||
endpoint: 127.0.0.1:14318
|
||||
|
||||
# метрики LB: встроенный экспортёр HAProxy на его TLS-порту (frontend monitor).
|
||||
# Забирает Collector, а не Prometheus: у LB нет сети telemetry, у Prometheus —
|
||||
# default. Только frontend и backend (без слотов и адресов реплик) и отобранные
|
||||
# имена; job = haproxy. Сервер — по CA стенда и имени ingress (leaf LB), клиент —
|
||||
# otel-collector-client; CRL клиент не умеет (матрица доверия)
|
||||
prometheus/haproxy:
|
||||
config:
|
||||
scrape_configs:
|
||||
- job_name: haproxy
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
metrics_path: /metrics
|
||||
params:
|
||||
scope: [frontend, backend]
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/ca.crt
|
||||
cert_file: /run/secrets/otel-collector-client.crt
|
||||
key_file: /run/secrets/otel-collector-client.key
|
||||
server_name: ingress
|
||||
min_version: TLS13
|
||||
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 отказывает приёмнику (SDK
|
||||
# получит ошибку и отбросит пакет), а не растёт до OOM. Мягкий предел —
|
||||
# 180 − 36 МиБ, жёсткий — 180 МиБ при лимите контейнера 256 МиБ
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 180
|
||||
spike_limit_mib: 36
|
||||
# пакеты к backend: по 512 элементов или раз в 2 с
|
||||
batch:
|
||||
send_batch_size: 512
|
||||
send_batch_max_size: 1024
|
||||
timeout: 2s
|
||||
|
||||
exporters:
|
||||
# только loopback пространства шлюза: в сеть :8889 выводит otel-gateway
|
||||
prometheus:
|
||||
endpoint: 127.0.0.1:18889
|
||||
# классические имена Prometheus: единица и _total суффиксами
|
||||
# (http_server_request_duration_seconds_bucket, messenger_relay_jobs_total)
|
||||
translation_strategy: UnderscoreEscapingWithSuffixes
|
||||
# ряды остановленной реплики уходят из экспортёра через 3 мин
|
||||
metric_expiration: 3m
|
||||
# ресурс не размножает метки: service.name → job,
|
||||
# service.instance.id → instance, остальное — в target_info
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: false
|
||||
|
||||
# Очередь экспорта ограничена числом элементов и не блокирует приём:
|
||||
# пока backend недоступен, Collector повторяет отправку до минуты, затем
|
||||
# отбрасывает пакет; переполненная очередь отбрасывает новое. Потери видны
|
||||
# в собственных метриках Collector (otelcol_exporter_send_failed_*,
|
||||
# otelcol_exporter_enqueue_failed_*)
|
||||
#
|
||||
# Лаба 7: https через TLS-шлюзы хранилищ — leaf otel-collector-client, сервер по CA
|
||||
# стенда и имени (системные корни не участвуют), TLS 1.3; CRL клиент не умеет
|
||||
# (матрица доверия). Отказ TLS — недоступность backend: очередь и потери прежние
|
||||
otlp_http/loki:
|
||||
endpoint: https://loki:3100/otlp
|
||||
timeout: 5s
|
||||
tls:
|
||||
ca_file: /run/secrets/ca.crt
|
||||
cert_file: /run/secrets/otel-collector-client.crt
|
||||
key_file: /run/secrets/otel-collector-client.key
|
||||
min_version: "1.3"
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
sizer: items
|
||||
queue_size: 20000
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 2s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
|
||||
otlp_http/tempo:
|
||||
endpoint: https://tempo:4318
|
||||
timeout: 5s
|
||||
tls:
|
||||
ca_file: /run/secrets/ca.crt
|
||||
cert_file: /run/secrets/otel-collector-client.crt
|
||||
key_file: /run/secrets/otel-collector-client.key
|
||||
min_version: "1.3"
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
sizer: items
|
||||
queue_size: 20000
|
||||
block_on_overflow: false
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 2s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
logs:
|
||||
level: info
|
||||
# собственные метрики Collector (очереди, отказы, отброшенное) для
|
||||
# Prometheus. Только loopback: в сеть :8888 выводит otel-gateway
|
||||
metrics:
|
||||
level: normal
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 127.0.0.1
|
||||
port: 18888
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp, prometheus/haproxy]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_http/loki]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_http/tempo]
|
||||
@@ -0,0 +1,110 @@
|
||||
# TLS-шлюз Collector (сервис otel-gateway, лаба 7, перенос telemetry-mtls;
|
||||
# правила — infra/otel/AGENTS.md, «mTLS к Collector»). Образ — тот же HAProxy, что
|
||||
# у LB (тег и digest). TLS-сервер самого Collector проверяет у клиента только
|
||||
# цепочку по CA, allowlist по SAN у него нет — поэтому перед ним шлюз:
|
||||
# SDK api / worker / relay ──mTLS (TLS 1.3, CA и CRL стенда, SAN из allowlist)
|
||||
# ──→ otel-gateway :4318 ──loopback──→ Collector 127.0.0.1:14318
|
||||
# Prometheus (prometheus-client) ──mTLS──→ :8888, :8889 ──→ 127.0.0.1:18888, 18889
|
||||
# Шлюз владеет сетевым пространством, Collector работает в нём (network_mode:
|
||||
# service:otel-gateway): порты Collector из сетей стенда недоступны, а его экспорт
|
||||
# в Loki и Tempo и scrape LB идут из этого пространства по mTLS (leaf
|
||||
# otel-collector-client, перенос telemetry-backends-tls). Файлы — secrets compose
|
||||
# (/run/secrets/: CA, CRL, otel-collector.pem), читаются при старте. Новый CRL и
|
||||
# правка этого файла — `docker compose restart otel-gateway` (Collector
|
||||
# перезапускается с ним); пересоздание одного шлюза (--force-recreate) оставило
|
||||
# бы Collector без сети.
|
||||
|
||||
global
|
||||
# журнал — stdout контейнера (make logs-telemetry)
|
||||
log stdout format raw local0 info
|
||||
# один поток на лимит 0,25 CPU; соединений SDK — по нескольку на процесс
|
||||
nbthread 1
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
# успешный экспорт строк не даёт; отказы рукопожатия и identity, 404 шлюза,
|
||||
# 503 и 504 недоступного Collector — пишутся
|
||||
option dontlog-normal
|
||||
# соединение без запроса, закрытое клиентом (Prometheus держит такие про
|
||||
# запас), строк не даёт; отказы рукопожатия и identity остаются
|
||||
option http-ignore-probes
|
||||
# Collector — на loopback: остановлен — отказ сразу, без повторов. У приёма OTLP
|
||||
# это закрытие без ответа (backend collector), у метрик — 503
|
||||
timeout connect 250ms
|
||||
retries 0
|
||||
# заморожен — SDK бросает запрос через 2 с, шлюз — через 10 с
|
||||
timeout server 10s
|
||||
# в несколько раз больше периода отправки метрик (15 с, в замерах 30 с):
|
||||
# соединения SDK в штатной работе не рвутся
|
||||
timeout client 60s
|
||||
timeout http-keep-alive 60s
|
||||
timeout http-request 10s
|
||||
|
||||
# health шлюза — только loopback его пространства и без обращения к Collector:
|
||||
# иначе Collector ждал бы healthy шлюза, а шлюз — Collector
|
||||
frontend health
|
||||
bind 127.0.0.1:8405
|
||||
# проверка раз в 5 с журнал не засоряет
|
||||
no log
|
||||
monitor-uri /ready
|
||||
http-request deny deny_status 404
|
||||
|
||||
# приём OTLP: только TLS 1.3 с сертификатом клиента CA стенда и проверкой по
|
||||
# CRL (OPENSSL_CONF — infra/haproxy/openssl.cnf: билетов сессии нет, значит нет
|
||||
# и возобновления в обход CRL)
|
||||
frontend otlp
|
||||
bind :4318 ssl crt /run/secrets/otel-collector.pem ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required ssl-min-ver TLSv1.3 alpn http/1.1
|
||||
# allowlist — DNS SAN клиента: вся строка SAN равна одному разрешённому
|
||||
# имени, то есть имя у сертификата ровно одно. Чужая identity того же CA
|
||||
# (haproxy, разовая, несколько имён) — закрытие после рукопожатия, запрос не
|
||||
# читается. Список = DNS SAN строк api-client, worker, relay
|
||||
# infra/pki/identities.conf (student-tests/unit/test_telemetry_tls.py)
|
||||
tcp-request session set-var(sess.refusal) str(identity_not_allowed) unless { ssl_c_san -m str DNS:api DNS:worker DNS:relay }
|
||||
tcp-request session reject if { var(sess.refusal) -m found }
|
||||
# дальше Collector — только экспорт OTLP, остальное отвергает сам шлюз
|
||||
http-request deny deny_status 404 unless METH_POST { path /v1/traces /v1/metrics /v1/logs }
|
||||
# журнал без тел, query и содержимого сертификатов: адрес, SAN, версия TLS
|
||||
# и причина
|
||||
log-format "otlp %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] %HM %HPO status=%ST bytes=%B term=%tsc backend=%b/%s time=%Ta"
|
||||
error-log-format "otlp-refused %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] reason=%[var(sess.refusal)] conn_err=%[fc_err_str] ssl_err=%[ssl_fc_err_str] cert_err=%[ssl_c_err,x509_v_err_str] ca_err=%[ssl_c_ca_err,x509_v_err_str] term=%tsc"
|
||||
default_backend collector
|
||||
|
||||
# метрики Collector для scrape (перенос telemetry-backends-tls): собственные (:8888)
|
||||
# и экспортёра prometheus (:8889) — тот же mTLS, только identity prometheus (DNS SAN
|
||||
# строки prometheus-client), только GET /metrics
|
||||
frontend metrics_own
|
||||
bind :8888 ssl crt /run/secrets/otel-collector.pem ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required ssl-min-ver TLSv1.3 alpn http/1.1
|
||||
tcp-request session set-var(sess.refusal) str(identity_not_allowed) unless { ssl_c_san -m str DNS:prometheus }
|
||||
tcp-request session reject if { var(sess.refusal) -m found }
|
||||
http-request deny deny_status 404 unless METH_GET { path /metrics }
|
||||
log-format "metrics_own %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] %HM %HPO status=%ST bytes=%B term=%tsc backend=%b/%s time=%Ta"
|
||||
error-log-format "otlp-refused metrics_own %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] reason=%[var(sess.refusal)] conn_err=%[fc_err_str] ssl_err=%[ssl_fc_err_str] cert_err=%[ssl_c_err,x509_v_err_str] ca_err=%[ssl_c_ca_err,x509_v_err_str] term=%tsc"
|
||||
default_backend collector_own
|
||||
|
||||
frontend metrics_app
|
||||
bind :8889 ssl crt /run/secrets/otel-collector.pem ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required ssl-min-ver TLSv1.3 alpn http/1.1
|
||||
tcp-request session set-var(sess.refusal) str(identity_not_allowed) unless { ssl_c_san -m str DNS:prometheus }
|
||||
tcp-request session reject if { var(sess.refusal) -m found }
|
||||
http-request deny deny_status 404 unless METH_GET { path /metrics }
|
||||
log-format "metrics_app %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] %HM %HPO status=%ST bytes=%B term=%tsc backend=%b/%s time=%Ta"
|
||||
error-log-format "otlp-refused metrics_app %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] reason=%[var(sess.refusal)] conn_err=%[fc_err_str] ssl_err=%[ssl_fc_err_str] cert_err=%[ssl_c_err,x509_v_err_str] ca_err=%[ssl_c_ca_err,x509_v_err_str] term=%tsc"
|
||||
default_backend collector_app
|
||||
|
||||
# Collector в том же сетевом пространстве: открытый текст только на loopback
|
||||
backend collector
|
||||
option abortonclose
|
||||
# остановленный Collector — закрытие соединения без ответа HTTP, а не 503: ответ
|
||||
# 503 SDK 1.45 не считает исключением экспорта, а ошибку соединения повторяет и
|
||||
# считает потерей. Строка журнала остаётся (status=503 bytes=0)
|
||||
errorfile 503 /dev/null
|
||||
server collector 127.0.0.1:14318
|
||||
|
||||
backend collector_own
|
||||
option abortonclose
|
||||
server collector 127.0.0.1:18888
|
||||
|
||||
backend collector_app
|
||||
option abortonclose
|
||||
server collector 127.0.0.1:18889
|
||||
@@ -0,0 +1,17 @@
|
||||
# Dashboard стенда грузится из файлов infra/otel/grafana/dashboards/
|
||||
# (в контейнере — /var/lib/grafana-dashboards). Правки через UI не
|
||||
# сохраняются: источник правды — JSON в git, его же можно импортировать в
|
||||
# другую Grafana руками (Dashboards → New → Import).
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: vladimirceva-messenger
|
||||
orgId: 1
|
||||
folder: Messenger lab 6
|
||||
folderUid: messenger-lab6
|
||||
type: file
|
||||
disableDeletion: true
|
||||
allowUiUpdates: false
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /var/lib/grafana-dashboards
|
||||
@@ -0,0 +1,414 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Messenger — API, worker, relay (lab 6)",
|
||||
"description": "Signals of contracts/observability.md, levels 3 and 4 (backlog, saturation, time to ready, SLO and alerts — the last row). Metric names are Prometheus forms of OTel instruments: http.server.request.duration -> http_server_request_duration_seconds_*, messenger.job.duration -> messenger_job_duration_seconds_*, messenger.relay.jobs -> messenger_relay_jobs_total. Request counts are _count of the duration histogram; health is not recorded.",
|
||||
"tags": ["messenger", "lab6", "opentelemetry"],
|
||||
"editable": false,
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"time": {"from": "now-30m", "to": "now"},
|
||||
"refresh": "30s",
|
||||
"timezone": "utc",
|
||||
"graphTooltip": 1,
|
||||
"templating": {"list": []},
|
||||
"annotations": {"list": []},
|
||||
"links": [],
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "row",
|
||||
"title": "Messenger API replicas",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 0},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "timeseries",
|
||||
"title": "Request rate: route x status class",
|
||||
"description": "rate of http_server_request_duration_seconds_count over all replicas; label http_route is the route template.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 1},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (http_request_method, http_route, http_response_status_class) (rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{http_request_method}} {{http_route}} {{http_response_status_class}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "timeseries",
|
||||
"title": "Server error ratio (5xx / all business requests)",
|
||||
"description": "Numerator: responses 5xx of the API replicas. Denominator: all API responses except health (health is not recorded). 4xx — client errors, shown separately.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 12, "y": 1},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "(sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_response_status_class=\"5xx\"}[5m])) or vector(0)) / sum(rate(http_server_request_duration_seconds_count{job=\"messenger-api\"}[5m]))",
|
||||
"legendFormat": "5xx ratio"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "timeseries",
|
||||
"title": "Client errors (4xx) per second by route",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 6, "x": 18, "y": 1},
|
||||
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (http_route, http_response_status_code) (rate(http_server_request_duration_seconds_count{job=\"messenger-api\", http_response_status_class=\"4xx\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{http_response_status_code}} {{http_route}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "timeseries",
|
||||
"title": "Request duration p50 / p95 / p99 (from histogram buckets of all replicas)",
|
||||
"description": "Unit: seconds. histogram_quantile(q, sum by (le) (rate(http_server_request_duration_seconds_bucket{job=\"messenger-api\"}[5m]))) for q = 0.5, 0.95, 0.99 — buckets of every replica are summed first, not an average of per-replica percentiles. Accuracy is bounded by bucket edges (TELEMETRY_HISTOGRAM_BUCKETS).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 9},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"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": "metrics"},
|
||||
"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": "metrics"},
|
||||
"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": "p95 latency per route",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 9},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"options": {"legend": {"displayMode": "table", "placement": "right", "calcs": ["lastNotNull"]}},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"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": "Background processing (messenger-worker, messenger-relay)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 17},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"type": "timeseries",
|
||||
"title": "Job deliveries per second by outcome",
|
||||
"description": "ready — variants committed; failed — permanent error; retry — scheduled again with backoff; finished/leased/stale/fenced — no-op duplicates; unavailable/error/rejected/cancelled — delivery not completed.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 18},
|
||||
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_job_type, messenger_job_outcome) (rate(messenger_job_duration_seconds_count{job=\"messenger-worker\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{messenger_job_outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"type": "stat",
|
||||
"title": "Unsuccessful job deliveries, last 1h",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 4, "x": 8, "y": 18},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0}, "overrides": []},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"]}, "colorMode": "value", "textMode": "value_and_name"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_job_outcome) (increase(messenger_job_duration_seconds_count{job=\"messenger-worker\", messenger_job_outcome=~\"failed|retry|error|unavailable|rejected|cancelled\"}[1h]))",
|
||||
"legendFormat": "{{messenger_job_outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"type": "timeseries",
|
||||
"title": "Job delivery duration p50 / p95 by outcome",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 18},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "histogram_quantile(0.5, sum by (le, messenger_job_outcome) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "p50 {{messenger_job_outcome}}"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "histogram_quantile(0.95, sum by (le, messenger_job_outcome) (rate(messenger_job_duration_seconds_bucket{job=\"messenger-worker\"}[5m])))",
|
||||
"legendFormat": "p95 {{messenger_job_outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"type": "timeseries",
|
||||
"title": "Relay: jobs per second by action",
|
||||
"description": "published — confirmed by the broker; requeued/exhausted — expired leases; republished — lost messages; failed_* — passes interrupted by the broker or PostgreSQL.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 7, "w": 12, "x": 0, "y": 26},
|
||||
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_relay_action) (rate(messenger_relay_jobs_total{job=\"messenger-relay\"}[$__rate_interval]))",
|
||||
"legendFormat": "{{messenger_relay_action}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"type": "stat",
|
||||
"title": "Scrape targets up",
|
||||
"description": "messenger — exporter of the Collector with application metrics; the rest — the telemetry pipeline itself.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 7, "w": 12, "x": 12, "y": 26},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 1}]}}, "overrides": []},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"]}, "colorMode": "background", "textMode": "value_and_name"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "up",
|
||||
"legendFormat": "{{job}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"type": "row",
|
||||
"title": "Loki logs and Tempo traces",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 33},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"type": "logs",
|
||||
"title": "Application logs (Loki): messenger-api, messenger-worker, messenger-relay",
|
||||
"description": "Each record carries event, logger, request_id (inside a request) and trace_id/span_id (inside a sampled span); the TraceID link opens the trace in Tempo.",
|
||||
"datasource": {"type": "loki", "uid": "logs"},
|
||||
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 34},
|
||||
"options": {"showTime": true, "wrapLogMessage": true, "sortOrder": "Descending", "enableLogDetails": true, "dedupStrategy": "none"},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "loki", "uid": "logs"},
|
||||
"expr": "{service_name=~\"messenger-.+\"}",
|
||||
"queryType": "range"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"type": "table",
|
||||
"title": "Recent traces (Tempo): API requests and worker jobs",
|
||||
"description": "TraceQL search; open a trace ID to see server/consumer spans with PostgreSQL, S3 and render children.",
|
||||
"datasource": {"type": "tempo", "uid": "traces"},
|
||||
"gridPos": {"h": 10, "w": 24, "x": 0, "y": 44},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "tempo", "uid": "traces"},
|
||||
"queryType": "traceql",
|
||||
"query": "{resource.service.name=~\"messenger-.+\" && (kind=server || kind=consumer)}",
|
||||
"limit": 20,
|
||||
"tableType": "traces"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"type": "row",
|
||||
"title": "Backlog, saturation and SLO (level 4)",
|
||||
"collapsed": false,
|
||||
"gridPos": {"h": 1, "w": 24, "x": 0, "y": 54},
|
||||
"panels": []
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"type": "timeseries",
|
||||
"title": "Job queue depth by state",
|
||||
"description": "Unit: jobs. sum by (messenger_job_state) (messenger_job_queue_depth). Source: PostgreSQL attachment_jobs counted over partial indexes by relay every 5 s (not the broker queue): outbox — accepted, not yet published; published — in the broker or waiting for retry backoff; processing — leased by worker. Backlog, not processing latency.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 55},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "custom": {"stacking": {"mode": "normal"}, "fillOpacity": 30}}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "sum by (messenger_job_state) (messenger_job_queue_depth)",
|
||||
"legendFormat": "{{messenger_job_state}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"type": "timeseries",
|
||||
"title": "Oldest unfinished job age",
|
||||
"description": "Unit: seconds. max by (messaging_destination_name) (messenger_job_queue_oldest_age_seconds): age of the oldest queued or processing job (from its durable acceptance). Red line — threshold of MessengerQueueLagGrowing (60 s for 1 m).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 55},
|
||||
"fieldConfig": {"defaults": {"unit": "s", "min": 0, "custom": {"thresholdsStyle": {"mode": "line"}}, "thresholds": {"mode": "absolute", "steps": [{"color": "green", "value": null}, {"color": "red", "value": 60}]}}, "overrides": []},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"expr": "max by (messaging_destination_name) (messenger_job_queue_oldest_age_seconds)",
|
||||
"legendFormat": "{{messaging_destination_name}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 19,
|
||||
"type": "timeseries",
|
||||
"title": "Time to ready p50 / p95 / p99 (upload accepted → ready)",
|
||||
"description": "Unit: seconds. histogram_quantile(q, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m]))). Recorded by worker when ready is committed; start — created_at of the job row written before 202. Includes broker wait, retries and backoff. Latency SLO: 95% of successful ready transitions within 30 s over 7 days; failed and unfinished jobs are excluded from this histogram.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 55},
|
||||
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p50"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p95"},
|
||||
{"refId": "C", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[5m])))", "legendFormat": "p99"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 20,
|
||||
"type": "timeseries",
|
||||
"title": "DB pool: used / waiting / max by process",
|
||||
"description": "Unit: connections and operations. db_client_connection_count{db_client_connection_state=\"used\"} — checked out of the SQLAlchemy pool; db_client_connection_pending_requests — operations waiting for a connection (counted in src/db.py); db_client_connection_max — DB_POOL_SIZE + DB_POOL_OVERFLOW. Summed per job (messenger-api replicas together).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 63},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job) (db_client_connection_count{db_client_connection_state=\"used\"})", "legendFormat": "used {{job}}"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job) (db_client_connection_pending_requests)", "legendFormat": "waiting {{job}}"},
|
||||
{"refId": "C", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job) (db_client_connection_max)", "legendFormat": "max {{job}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 21,
|
||||
"type": "timeseries",
|
||||
"title": "Worker saturation: busy / capacity",
|
||||
"description": "Unit: tasks. messenger_worker_busy — tasks processing a delivery now; messenger_worker_capacity — WORKER_CONCURRENCY. busy = capacity for long with a growing queue — the worker is the bottleneck. Sampled at metric export (15 s), short bursts are not visible.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 63},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum(messenger_worker_busy)", "legendFormat": "busy"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum(messenger_worker_capacity)", "legendFormat": "capacity"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 22,
|
||||
"type": "timeseries",
|
||||
"title": "Process CPU (cores) by service and instance",
|
||||
"description": "Unit: CPU cores. sum by (job, instance) (rate(process_cpu_time_seconds_total[$__rate_interval])): user + system time of each process; worker includes its finished render subprocesses (os.times children).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 63},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (job, instance) (rate(process_cpu_time_seconds_total[$__rate_interval]))", "legendFormat": "{{job}} {{instance}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 23,
|
||||
"type": "timeseries",
|
||||
"title": "Process RSS by service and instance",
|
||||
"description": "Unit: bytes. process_memory_usage_bytes: resident set of each application process (/proc/self/statm). Collector: otelcol_process_memory_rss (bytes, no unit suffix in 0.164).",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 71},
|
||||
"fieldConfig": {"defaults": {"unit": "bytes", "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "process_memory_usage_bytes", "legendFormat": "{{job}} {{instance}}"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "otelcol_process_memory_rss", "legendFormat": "otel-collector"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 24,
|
||||
"type": "stat",
|
||||
"title": "7-day SLO: API ≥ 99.5%, 95% of successful jobs ready within 30 s",
|
||||
"description": "Unit: ratio. messenger:http_availability:ratio_7d = 1 − 5xx / all recorded API responses (health excluded; failures before API entry are not measured). messenger:attachment_ready_30s:ratio_7d = successful ready transitions within 30 s / all observed successful ready transitions; failed and unfinished jobs are excluded. This is a conditional latency SLI, not the success ratio of all accepted uploads. Recording rules: infra/otel/prometheus/rules.yml.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 71},
|
||||
"fieldConfig": {"defaults": {"unit": "percentunit", "decimals": 2, "thresholds": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.995}]}}, "overrides": [{"matcher": {"id": "byName", "options": "ready ≤ 30 s"}, "properties": [{"id": "thresholds", "value": {"mode": "absolute", "steps": [{"color": "red", "value": null}, {"color": "green", "value": 0.95}]}}]}]},
|
||||
"options": {"reduceOptions": {"calcs": ["lastNotNull"]}, "colorMode": "background", "textMode": "value_and_name"},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "messenger:http_availability:ratio_7d", "legendFormat": "API availability"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "messenger:attachment_ready_30s:ratio_7d", "legendFormat": "ready ≤ 30 s"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 25,
|
||||
"type": "timeseries",
|
||||
"title": "Alerts: pending / firing",
|
||||
"description": "Unit: alerts. sum by (alertname, alertstate) (ALERTS) — built-in series of Prometheus rule evaluation; absence means resolved. Runbooks: infra/otel/runbooks/.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 71},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "decimals": 0, "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (alertname, alertstate) (ALERTS)", "legendFormat": "{{alertname}} {{alertstate}}"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 26,
|
||||
"type": "timeseries",
|
||||
"title": "Telemetry losses and export queue (Collector)",
|
||||
"description": "Unit: items per second and items. Collector 0.164 exposes its counters without the _total suffix. rate of otelcol_exporter_send_failed_{spans,log_records} — dropped after retries (backend down), otelcol_exporter_enqueue_failed_* — dropped because the export queue (20000 items) is full (appears after the first such drop), otelcol_receiver_refused_* — refused by memory_limiter; otelcol_exporter_queue_size — items buffered now.",
|
||||
"datasource": {"type": "prometheus", "uid": "metrics"},
|
||||
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 79},
|
||||
"fieldConfig": {"defaults": {"unit": "short", "min": 0}, "overrides": []},
|
||||
"targets": [
|
||||
{"refId": "A", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (exporter) (rate(otelcol_exporter_send_failed_spans[5m]) or rate(otelcol_exporter_send_failed_log_records[5m]))", "legendFormat": "send failed {{exporter}}"},
|
||||
{"refId": "B", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (exporter) (rate(otelcol_exporter_enqueue_failed_spans[5m]) or rate(otelcol_exporter_enqueue_failed_log_records[5m]))", "legendFormat": "queue full {{exporter}}"},
|
||||
{"refId": "C", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum(rate(otelcol_receiver_refused_spans[5m]) or rate(otelcol_receiver_refused_log_records[5m]) or rate(otelcol_receiver_refused_metric_points[5m]))", "legendFormat": "refused by receiver"},
|
||||
{"refId": "D", "datasource": {"type": "prometheus", "uid": "metrics"}, "expr": "sum by (exporter) (otelcol_exporter_queue_size)", "legendFormat": "queue size {{exporter}}"}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
# Источники Grafana стенда: три хранилища, по одному на сигнал. uid
|
||||
# постоянные — на них ссылаются dashboard и scripts/lab7.py
|
||||
# (telemetry-check ходит в хранилища через прокси источников Grafana).
|
||||
# Из UI не меняются; удалённый из файла источник удаляется (prune).
|
||||
#
|
||||
# Лаба 7, перенос telemetry-backends-tls: адреса — TLS-шлюзы хранилищ, Grafana
|
||||
# предъявляет leaf grafana-client (права шлюзов — только чтение) и проверяет
|
||||
# сервер по CA стенда и имени (tlsAuthWithCACert: системные корни не участвуют;
|
||||
# tlsSkipVerify не добавлять). Содержимого PEM здесь нет: $__file{} — пути к
|
||||
# secrets Grafana, файлы она читает при provisioning.
|
||||
apiVersion: 1
|
||||
prune: true
|
||||
|
||||
datasources:
|
||||
- name: Metrics (Prometheus)
|
||||
uid: metrics
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
secureJsonData:
|
||||
tlsCACert: $__file{/run/secrets/ca.crt}
|
||||
tlsClientCert: $__file{/run/secrets/grafana-client.crt}
|
||||
tlsClientKey: $__file{/run/secrets/grafana-client.key}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
httpMethod: POST
|
||||
# равно scrape_interval: rate() по окну меньше двух точек пуст
|
||||
timeInterval: 15s
|
||||
|
||||
- name: Logs (Loki)
|
||||
uid: logs
|
||||
type: loki
|
||||
access: proxy
|
||||
url: https://loki:3100
|
||||
editable: false
|
||||
secureJsonData:
|
||||
tlsCACert: $__file{/run/secrets/ca.crt}
|
||||
tlsClientCert: $__file{/run/secrets/grafana-client.crt}
|
||||
tlsClientKey: $__file{/run/secrets/grafana-client.key}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
maxLines: 500
|
||||
# из записи журнала — переход в её трассу по trace_id (structured
|
||||
# metadata записи OTLP)
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: traces
|
||||
url: "$${__value.raw}"
|
||||
urlDisplayLabel: Open trace
|
||||
|
||||
- name: Traces (Tempo)
|
||||
uid: traces
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: https://tempo:3200
|
||||
editable: false
|
||||
secureJsonData:
|
||||
tlsCACert: $__file{/run/secrets/ca.crt}
|
||||
tlsClientCert: $__file{/run/secrets/grafana-client.crt}
|
||||
tlsClientKey: $__file{/run/secrets/grafana-client.key}
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
# потоковые запросы (gRPC поверх HTTP/2) выключены: через шлюз — только REST
|
||||
# (у Tempo stream_over_http_enabled: false)
|
||||
streamingEnabled:
|
||||
search: false
|
||||
metrics: false
|
||||
# из span — записи журнала того же сервиса с этим trace_id
|
||||
tracesToLogsV2:
|
||||
datasourceUid: logs
|
||||
spanStartTimeShift: "-2m"
|
||||
spanEndTimeShift: "2m"
|
||||
customQuery: true
|
||||
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"'
|
||||
search:
|
||||
hide: false
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
@@ -0,0 +1,91 @@
|
||||
# TLS-шлюз Loki (сервис loki-gateway, лаба 7, перенос telemetry-backends-tls;
|
||||
# правила — infra/otel/AGENTS.md, «TLS хранилищ телеметрии»). Образ — HAProxy
|
||||
# балансировщика (тег и digest). Родной TLS Loki проверяет у клиента только
|
||||
# цепочку по CA — ни allowlist по SAN, ни прав по пути, ни CRL, поэтому перед ним
|
||||
# шлюз:
|
||||
# Collector (otel-collector-client) ──mTLS──→ loki-gateway :3100
|
||||
# Grafana (grafana-client) ──mTLS──→ └─loopback─→ Loki 127.0.0.1:13100
|
||||
# Prometheus (prometheus-client) ──mTLS──→
|
||||
# Шлюз владеет сетевым пространством Loki (network_mode: service:loki-gateway):
|
||||
# порты Loki (HTTP 13100, gRPC 9095) из сетей стенда недоступны. Файлы — secrets
|
||||
# compose (/run/secrets/: CA, CRL, loki.pem), читаются при старте: новый CRL и
|
||||
# правка этого файла — `docker compose restart loki-gateway` (Loki
|
||||
# перезапускается с ним), а не --force-recreate (Loki остался бы без сети).
|
||||
|
||||
global
|
||||
# журнал — stdout контейнера (make logs-telemetry)
|
||||
log stdout format raw local0 info
|
||||
# один поток: клиентов — три сервиса телеметрии
|
||||
nbthread 1
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
# успешный запрос строк не даёт; отказы рукопожатия и identity, 403 прав,
|
||||
# 503 и 504 недоступного Loki — пишутся
|
||||
option dontlog-normal
|
||||
# соединение без запроса, закрытое клиентом (Go-клиенты держат такие про
|
||||
# запас), строк не даёт; отказы рукопожатия и identity остаются (dontlognull
|
||||
# убрал бы и их)
|
||||
option http-ignore-probes
|
||||
# Loki — на loopback: остановлен — 503 сразу, без повторов (Collector повторяет
|
||||
# сам, scrape — up = 0, Grafana — ошибка источника)
|
||||
timeout connect 250ms
|
||||
retries 0
|
||||
# больше срока запроса прокси Grafana (30 с); экспорту Collector — 10 с ниже
|
||||
timeout server 60s
|
||||
# scrape раз в 15 с и экспорт держат keep-alive
|
||||
timeout client 60s
|
||||
timeout http-keep-alive 60s
|
||||
timeout http-request 10s
|
||||
|
||||
# health шлюза — только loopback и без обращения к Loki: иначе Loki ждал бы healthy
|
||||
# шлюза, а шлюз — Loki
|
||||
frontend health
|
||||
bind 127.0.0.1:8405
|
||||
no log
|
||||
monitor-uri /ready
|
||||
http-request deny deny_status 404
|
||||
|
||||
# приём записей и запросы: только TLS 1.3 с сертификатом клиента CA стенда и CRL
|
||||
# (OPENSSL_CONF — infra/haproxy/openssl.cnf: билетов нет — нет возобновления в
|
||||
# обход CRL)
|
||||
frontend loki_in
|
||||
bind :3100 ssl crt /run/secrets/loki.pem ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required ssl-min-ver TLSv1.3 alpn http/1.1
|
||||
# allowlist порта — DNS SAN клиента: вся строка SAN равна одному имени. Чужая
|
||||
# identity того же CA (haproxy, разовая, несколько имён) — закрытие до чтения
|
||||
# запроса. Имена = DNS SAN строк otel-collector-client, grafana-client,
|
||||
# prometheus-client (student-tests/unit/test_telemetry_backends_tls.py)
|
||||
tcp-request session set-var(sess.refusal) str(identity_not_allowed) unless { ssl_c_san -m str DNS:otel-collector DNS:grafana DNS:prometheus }
|
||||
tcp-request session reject if { var(sess.refusal) -m found }
|
||||
# первым: шлюз сравнивает сырой путь, а Loki раскодирует %XX и исправляет //,
|
||||
# сегменты . и .. — такой путь отвергается до прав; клиенты стенда его не шлют
|
||||
acl unsafe_path path_sub % //
|
||||
acl unsafe_path path_reg /[.][.]?(/|$)
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused loki-gateway if unsafe_path
|
||||
# права по методу и пути: Collector — только приём OTLP, Grafana — только
|
||||
# запросы чтения, Prometheus — только метрики. Нет ни у кого: push мимо OTLP,
|
||||
# удаление (/loki/api/v1/delete, /compactor/…), /config, /flush, /ring, правила.
|
||||
# Новый путь Grafana — строка этого списка, а не префикс
|
||||
acl id_collector ssl_c_san -m str DNS:otel-collector
|
||||
acl id_grafana ssl_c_san -m str DNS:grafana
|
||||
acl id_prometheus ssl_c_san -m str DNS:prometheus
|
||||
acl read_path path_reg ^/loki/api/v1/(query|query_range|labels|label/[^/]+/values|series|index/(stats|volume|volume_range)|detected_fields|detected_field/[^/]+/values|detected_labels|patterns|status/buildinfo)$
|
||||
http-request allow if id_collector METH_POST { path /otlp/v1/logs }
|
||||
http-request allow if id_grafana METH_GET read_path
|
||||
http-request allow if id_prometheus METH_GET { path /metrics }
|
||||
# отказ прав — 403 самого шлюза с заголовком: по нему проверка отличает его от
|
||||
# ответа Loki, Loki запроса не видит
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused loki-gateway
|
||||
# журнал без тел, query и содержимого сертификатов
|
||||
log-format "loki-gateway %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] %HM %HPO status=%ST bytes=%B term=%tsc backend=%b/%s time=%Ta"
|
||||
error-log-format "loki-gateway-refused %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] reason=%[var(sess.refusal)] conn_err=%[fc_err_str] ssl_err=%[ssl_fc_err_str] cert_err=%[ssl_c_err,x509_v_err_str] ca_err=%[ssl_c_ca_err,x509_v_err_str] term=%tsc"
|
||||
default_backend loki
|
||||
|
||||
# Loki в том же сетевом пространстве: открытый текст только на loopback
|
||||
backend loki
|
||||
option abortonclose
|
||||
# экспорт Collector (срок 5 с) — 10 с; в frontend set-timeout невозможен
|
||||
http-request set-timeout server 10s if { ssl_c_san -m str DNS:otel-collector }
|
||||
server loki 127.0.0.1:13100
|
||||
@@ -0,0 +1,53 @@
|
||||
# Loki 3.7.10: хранилище логов стенда, один процесс, данные — файлы в
|
||||
# volume lokidata (/loki). Записи приходят от Collector по OTLP:
|
||||
# service.name, service.instance.id и deployment.environment.name
|
||||
# становятся метками потока (service_name, ...), атрибуты записи (event,
|
||||
# request_id, logger) и trace_id/span_id — structured metadata, тело —
|
||||
# сообщение. Срок хранения — 7 суток (compactor). Лаба 7, перенос
|
||||
# telemetry-backends-tls: Loki живёт в сетевом пространстве шлюза loki-gateway и
|
||||
# слушает только его loopback; :3100 с mTLS, allowlist и правами по пути — порт
|
||||
# шлюза, поэтому номер порта Loki другой.
|
||||
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_address: 127.0.0.1
|
||||
http_listen_port: 13100
|
||||
grpc_listen_address: 127.0.0.1
|
||||
log_level: warn
|
||||
|
||||
common:
|
||||
instance_addr: 127.0.0.1
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2026-11-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
limits_config:
|
||||
retention_period: 168h
|
||||
# structured metadata нужна для trace_id и атрибутов записи
|
||||
allow_structured_metadata: true
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
|
||||
# без отправки статистики разработчикам Loki
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,66 @@
|
||||
# TLS-шлюз Prometheus (сервис prometheus-gateway, лаба 7, перенос
|
||||
# telemetry-backends-tls; правила — infra/otel/AGENTS.md, «TLS хранилищ
|
||||
# телеметрии»). Родной TLS Prometheus (--web.config.file) CRL не знает, пускает
|
||||
# сертификат с несколькими именами, а busybox wget его healthcheck сертификата не
|
||||
# предъявит — поэтому шлюз, как у Loki и Tempo:
|
||||
# Grafana (grafana-client) ──mTLS──→ prometheus-gateway :9090
|
||||
# ──loopback──→ Prometheus 127.0.0.1:19090
|
||||
# Шлюз владеет сетевым пространством Prometheus (network_mode:
|
||||
# service:prometheus-gateway): его порт из сетей стенда недоступен; себя Prometheus
|
||||
# забирает и проверяется healthcheck по этому loopback, scrape Collector, Loki и
|
||||
# Tempo — исходящие mTLS из пространства. Файлы — secrets compose, читаются при
|
||||
# старте: новый CRL и правка этого файла — `docker compose restart
|
||||
# prometheus-gateway` (Prometheus перезапускается с ним).
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
nbthread 1
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option dontlog-normal
|
||||
option http-ignore-probes
|
||||
# Prometheus — на loopback: остановлен — 503 сразу, без повторов
|
||||
timeout connect 250ms
|
||||
retries 0
|
||||
# больше срока запроса прокси Grafana (30 с)
|
||||
timeout server 60s
|
||||
timeout client 60s
|
||||
timeout http-keep-alive 60s
|
||||
timeout http-request 10s
|
||||
|
||||
# health шлюза — только loopback и без обращения к Prometheus
|
||||
frontend health
|
||||
bind 127.0.0.1:8405
|
||||
no log
|
||||
monitor-uri /ready
|
||||
http-request deny deny_status 404
|
||||
|
||||
frontend prometheus_in
|
||||
bind :9090 ssl crt /run/secrets/prometheus.pem ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required ssl-min-ver TLSv1.3 alpn http/1.1
|
||||
# allowlist — DNS SAN строки grafana-client (вся строка SAN — одно имя)
|
||||
tcp-request session set-var(sess.refusal) str(identity_not_allowed) unless { ssl_c_san -m str DNS:grafana }
|
||||
tcp-request session reject if { var(sess.refusal) -m found }
|
||||
# первым: роутер Prometheus сравнивает раскодированный и исправленный путь (%XX,
|
||||
# //, сегменты . и .., регистр — 307) — такой путь отвергается до прав
|
||||
acl unsafe_path path_sub % //
|
||||
acl unsafe_path path_reg /[.][.]?(/|$)
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused prometheus-gateway if unsafe_path
|
||||
# права: Grafana — GET и POST чтения, явный список. Административного API, remote
|
||||
# write и приёма OTLP (флаги их и так выключают — шлюз страхует от смены флагов),
|
||||
# /federate, /-/reload, /-/quit, /metrics — ни у кого
|
||||
acl id_grafana ssl_c_san -m str DNS:grafana
|
||||
acl read_path path_reg ^/api/v1/(query|query_range|query_exemplars|format_query|parse_query|series|labels|label/[^/]+/values|metadata|targets|targets/metadata|scrape_pools|rules|alerts|alertmanagers|status/(buildinfo|config|flags|runtimeinfo|tsdb|walreplay))$
|
||||
http-request allow if id_grafana METH_GET read_path
|
||||
http-request allow if id_grafana METH_POST read_path
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused prometheus-gateway
|
||||
log-format "prometheus-gateway %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] %HM %HPO status=%ST bytes=%B term=%tsc backend=%b/%s time=%Ta"
|
||||
error-log-format "prometheus-gateway-refused %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] reason=%[var(sess.refusal)] conn_err=%[fc_err_str] ssl_err=%[ssl_fc_err_str] cert_err=%[ssl_c_err,x509_v_err_str] ca_err=%[ssl_c_ca_err,x509_v_err_str] term=%tsc"
|
||||
default_backend prometheus
|
||||
|
||||
# Prometheus в том же сетевом пространстве: открытый текст только на loopback
|
||||
backend prometheus
|
||||
option abortonclose
|
||||
server prometheus 127.0.0.1:19090
|
||||
@@ -0,0 +1,66 @@
|
||||
# Prometheus v3.15.1: хранилище метрик стенда. Метрики приложения сюда
|
||||
# не пушатся — Prometheus сам забирает экспортёр Collector (:8889), куда
|
||||
# SDK api, worker и relay отправляют OTLP. Срок (7d) и объём (1GB) хранения
|
||||
# — флаги в compose.yaml; volume promdata. Лаба 7, перенос
|
||||
# telemetry-backends-tls: Prometheus живёт в сетевом пространстве шлюза
|
||||
# prometheus-gateway и слушает только 127.0.0.1:19090; цели в сети — https с
|
||||
# leaf prometheus-client, сервер — по CA стенда и имени цели (SAN шлюза), TLS
|
||||
# 1.3 (CRL scrape-клиент не умеет — матрица доверия). Файлы tls_config: стенд
|
||||
# — secrets, make alerts-test — пустые заглушки.
|
||||
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
scrape_timeout: 10s
|
||||
evaluation_interval: 15s
|
||||
|
||||
# SLI и alert rules (уровень 4). Оповещения наружу не уходят: Alertmanager
|
||||
# не подключён, состояние pending/firing видно в /api/v1/alerts и в Grafana
|
||||
rule_files:
|
||||
- /etc/prometheus/rules.yml
|
||||
|
||||
scrape_configs:
|
||||
# метрики приложения: job и instance уже проставил Collector из ресурса
|
||||
# (service.name, service.instance.id) — honor_labels их сохраняет
|
||||
- job_name: messenger
|
||||
honor_labels: true
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/ca.crt
|
||||
cert_file: /run/secrets/prometheus-client.crt
|
||||
key_file: /run/secrets/prometheus-client.key
|
||||
min_version: TLS13
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8889"]
|
||||
|
||||
# здоровье самого конвейера телеметрии: очередь экспорта, отказы, память
|
||||
- job_name: otel-collector
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/ca.crt
|
||||
cert_file: /run/secrets/prometheus-client.crt
|
||||
key_file: /run/secrets/prometheus-client.key
|
||||
min_version: TLS13
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8888"]
|
||||
- job_name: loki
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/ca.crt
|
||||
cert_file: /run/secrets/prometheus-client.crt
|
||||
key_file: /run/secrets/prometheus-client.key
|
||||
min_version: TLS13
|
||||
static_configs:
|
||||
- targets: ["loki:3100"]
|
||||
- job_name: tempo
|
||||
scheme: https
|
||||
tls_config:
|
||||
ca_file: /run/secrets/ca.crt
|
||||
cert_file: /run/secrets/prometheus-client.crt
|
||||
key_file: /run/secrets/prometheus-client.key
|
||||
min_version: TLS13
|
||||
static_configs:
|
||||
- targets: ["tempo:3200"]
|
||||
# себя — по loopback пространства шлюза (закрытый hop), без TLS
|
||||
- job_name: prometheus
|
||||
static_configs:
|
||||
- targets: ["127.0.0.1:19090"]
|
||||
@@ -0,0 +1,104 @@
|
||||
# promtool test rules (make alerts-test): каждое правило — сработало при
|
||||
# поломке, не сработало до неё и ушло после восстановления.
|
||||
|
||||
rule_files:
|
||||
- rules.yml
|
||||
|
||||
evaluation_interval: 15s
|
||||
|
||||
tests:
|
||||
# 5xx начинаются на 150-й секунде: треть ответов
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/users/me", http_response_status_class="2xx"}'
|
||||
values: '0+10x60'
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/users/me", http_response_status_class="5xx"}'
|
||||
values: '0+0x10 5+5x20 105+0x29'
|
||||
alert_rule_test:
|
||||
- eval_time: 2m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
- eval_time: 6m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: page
|
||||
exp_annotations:
|
||||
summary: API answers 5xx to more than 5% of business requests
|
||||
description: >-
|
||||
Ratio of 5xx to all API responses (health excluded) over 2m stayed
|
||||
above 0.05 for 1m. Check PostgreSQL first: database unavailable
|
||||
lines and the postgresql spans of failing requests.
|
||||
runbook_url: infra/otel/runbooks/high-error-rate.md
|
||||
# ошибки кончились на 450-й секунде, окно 2 мин прошло
|
||||
- eval_time: 10m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
promql_expr_test:
|
||||
- expr: messenger:http_errors:ratio_rate2m
|
||||
eval_time: 6m
|
||||
exp_samples:
|
||||
- labels: 'messenger:http_errors:ratio_rate2m'
|
||||
value: 0.3333333333333333
|
||||
|
||||
# одиночная ошибка при почти нулевом трафике не будит
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/users/me", http_response_status_class="5xx"}'
|
||||
values: '0+0x10 1+0x30'
|
||||
alert_rule_test:
|
||||
- eval_time: 5m
|
||||
alertname: MessengerHighErrorRate
|
||||
exp_alerts: []
|
||||
|
||||
# worker остановлен на 5 мин: возраст растёт, затем backlog разобран
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'messenger_job_queue_oldest_age_seconds{job="messenger-relay", instance="relay-1", messaging_destination_name="messenger.attachment-jobs"}'
|
||||
values: '0+15x20 0x20'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts: []
|
||||
- eval_time: 4m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: page
|
||||
messaging_destination_name: messenger.attachment-jobs
|
||||
exp_annotations:
|
||||
summary: Oldest unfinished attachment job is older than 60s
|
||||
description: >-
|
||||
Oldest queued or processing job has waited more than 60s for 1m:
|
||||
jobs are accepted (202) but not finished. Usual causes: worker
|
||||
stopped, broker unavailable, relay stuck, retries with backoff.
|
||||
runbook_url: infra/otel/runbooks/queue-lag.md
|
||||
- eval_time: 7m
|
||||
alertname: MessengerQueueLagGrowing
|
||||
exp_alerts: []
|
||||
|
||||
# Collector не отвечает на scrape
|
||||
- interval: 15s
|
||||
input_series:
|
||||
- series: 'up{job="otel-collector", instance="otel-collector:8888"}'
|
||||
values: '1x5 0x10 1x10'
|
||||
alert_rule_test:
|
||||
- eval_time: 1m
|
||||
alertname: MessengerTelemetryTargetDown
|
||||
exp_alerts: []
|
||||
- eval_time: 3m
|
||||
alertname: MessengerTelemetryTargetDown
|
||||
exp_alerts:
|
||||
- exp_labels:
|
||||
severity: ticket
|
||||
job: otel-collector
|
||||
instance: otel-collector:8888
|
||||
exp_annotations:
|
||||
summary: Prometheus cannot scrape the telemetry Collector
|
||||
description: >-
|
||||
Scrape target of the Collector (application metrics or its own
|
||||
metrics) is down for 1m; application alerts are blind meanwhile.
|
||||
runbook_url: infra/otel/runbooks/telemetry-down.md
|
||||
- eval_time: 6m
|
||||
alertname: MessengerTelemetryTargetDown
|
||||
exp_alerts: []
|
||||
@@ -0,0 +1,86 @@
|
||||
# SLI, SLO и alert rules стенда vladimirceva-lab7 (уровень 4 лабы 6).
|
||||
#
|
||||
# Цели SLO считаются за 7 суток; ровно столько Prometheus держит данные.
|
||||
# API: ≥ 99,5 % бизнес-запросов без 5xx. Числитель — ответы 5xx
|
||||
# реплик API, знаменатель — все их ответы; health в метрику не
|
||||
# попадает вовсе, 4xx (неверный пароль, 404) — не отказ сервиса.
|
||||
# загрузка: ≥ 95 % вложений становятся ready не позже 30 с после 202
|
||||
# (histogram messenger_attachment_time_to_ready_seconds,
|
||||
# корзина le="30.0").
|
||||
# Оповещения быстрые, на явную поломку, а не burn rate: окно 2–5 мин и
|
||||
# `for` 1 мин. Alertmanager не подключён: состояние pending → firing →
|
||||
# (нет в списке) resolved видно в Prometheus /api/v1/alerts и в Grafana.
|
||||
# Тесты правил: make alerts-test (promtool, infra/otel/prometheus/rules.test.yml).
|
||||
|
||||
groups:
|
||||
- name: messenger-sli
|
||||
interval: 15s
|
||||
rules:
|
||||
- record: messenger:http_requests:rate2m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[2m]))
|
||||
- record: messenger:http_errors:ratio_rate2m
|
||||
expr: |
|
||||
(sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_response_status_class="5xx"}[2m])) or vector(0))
|
||||
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[2m]))
|
||||
# SLI доступности за окно SLO; 1 − значение = израсходованная доля
|
||||
- record: messenger:http_availability:ratio_7d
|
||||
expr: |
|
||||
1 - (
|
||||
(sum(increase(http_server_request_duration_seconds_count{job="messenger-api", http_response_status_class="5xx"}[7d])) or vector(0))
|
||||
/ sum(increase(http_server_request_duration_seconds_count{job="messenger-api"}[7d]))
|
||||
)
|
||||
# SLI времени до ready: доля готовых за 30 с (экспортёр Collector пишет
|
||||
# границы с дробной частью: le="30.0")
|
||||
- record: messenger:attachment_ready_30s:ratio_7d
|
||||
expr: |
|
||||
sum(increase(messenger_attachment_time_to_ready_seconds_bucket{le="30.0"}[7d]))
|
||||
/ sum(increase(messenger_attachment_time_to_ready_seconds_count[7d]))
|
||||
|
||||
- name: messenger-alerts
|
||||
interval: 15s
|
||||
rules:
|
||||
- alert: MessengerHighErrorRate
|
||||
# 5 % = 10 × бюджет SLO; нижний порог трафика (≈ 6 запросов за 2 мин),
|
||||
# чтобы одиночный 503 в тишине не будил
|
||||
expr: |
|
||||
messenger:http_errors:ratio_rate2m > 0.05
|
||||
and messenger:http_requests:rate2m > 0.05
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
annotations:
|
||||
summary: API answers 5xx to more than 5% of business requests
|
||||
description: >-
|
||||
Ratio of 5xx to all API responses (health excluded) over 2m stayed
|
||||
above 0.05 for 1m. Check PostgreSQL first: database unavailable
|
||||
lines and the postgresql spans of failing requests.
|
||||
runbook_url: infra/otel/runbooks/high-error-rate.md
|
||||
|
||||
- alert: MessengerQueueLagGrowing
|
||||
# возраст старейшего незавершённого задания (outbox, брокер, аренда)
|
||||
# из PostgreSQL; без worker растёт на 1 с в секунду
|
||||
expr: max by (messaging_destination_name) (messenger_job_queue_oldest_age_seconds) > 60
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
annotations:
|
||||
summary: Oldest unfinished attachment job is older than 60s
|
||||
description: >-
|
||||
Oldest queued or processing job has waited more than 60s for 1m:
|
||||
jobs are accepted (202) but not finished. Usual causes: worker
|
||||
stopped, broker unavailable, relay stuck, retries with backoff.
|
||||
runbook_url: infra/otel/runbooks/queue-lag.md
|
||||
|
||||
- alert: MessengerTelemetryTargetDown
|
||||
# без Collector пропадают метрики приложения, и два правила выше
|
||||
# молча перестают срабатывать
|
||||
expr: up{job=~"messenger|otel-collector"} == 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: ticket
|
||||
annotations:
|
||||
summary: Prometheus cannot scrape the telemetry Collector
|
||||
description: >-
|
||||
Scrape target of the Collector (application metrics or its own
|
||||
metrics) is down for 1m; application alerts are blind meanwhile.
|
||||
runbook_url: infra/otel/runbooks/telemetry-down.md
|
||||
@@ -0,0 +1,38 @@
|
||||
# MessengerHighErrorRate — API отвечает 5xx
|
||||
|
||||
**Условие.** `messenger:http_errors:ratio_rate2m > 0.05` при трафике больше
|
||||
0,05 запроса/с, держится 1 мин (`infra/otel/prometheus/rules.yml`). 5 % —
|
||||
в 10 раз выше бюджета SLO 99,5 % за 7 суток.
|
||||
|
||||
**Что это значит для пользователя.** Часть запросов получает 503 (чаще
|
||||
всего) или 500. Health в метрике нет, 4xx не считаются.
|
||||
|
||||
## Шаги
|
||||
|
||||
1. Grafana → dashboard `messenger-lab6`, панель «Server error ratio» и
|
||||
«Request rate: route x status class»: все маршруты или
|
||||
один? Все — общий ресурс (PostgreSQL, пул); только загрузки и
|
||||
скачивание — S3.
|
||||
2. Панель «DB pool: used / waiting». `waiting > 0` и `used` у предела —
|
||||
база медленная или зависла: запросы стоят в очереди за соединением.
|
||||
3. Tempo: `{resource.service.name="messenger-api" && status=error}`.
|
||||
Открыть трассу:
|
||||
- длинный span `postgresql read|transaction` (≈ 5–6 с, `error.type`
|
||||
`Unavailable`/`TimeoutError`) почти на всю длину server span —
|
||||
виновата база, а не код ручки;
|
||||
- span базы короткий, а server span длинный — медленный handler
|
||||
(CPU, Argon2, S3): смотреть детей span'а и CPU процесса.
|
||||
4. Loki: `{service_name="messenger-api"} |= "database unavailable"` —
|
||||
класс ошибки драйвера (`error_type=`): `ConnectionRefusedError` —
|
||||
база остановлена, `TimeoutError`/`QueryCanceledError` — зависла или
|
||||
держит блокировку.
|
||||
5. В PostgreSQL (`docker compose exec postgres psql -U messenger messenger`):
|
||||
`SELECT pid, state, wait_event_type, now() - xact_start AS age, left(query, 60)
|
||||
FROM pg_stat_activity WHERE datname = current_database() ORDER BY age DESC NULLS LAST;`
|
||||
долгая транзакция с `Lock` у остальных — её завершить
|
||||
`pg_terminate_backend(pid)`.
|
||||
|
||||
## Восстановление и проверка
|
||||
|
||||
После устранения причины доля 5xx падает за окно 2 мин, alert уходит из
|
||||
`/api/v1/alerts` (resolved). Повтор проверки — `make alerts-check`.
|
||||
@@ -0,0 +1,36 @@
|
||||
# MessengerQueueLagGrowing — задания не доходят до ready
|
||||
|
||||
**Условие.** `max by (messaging_destination_name)
|
||||
(messenger_job_queue_oldest_age_seconds) > 60` в течение 1 мин. Метрику
|
||||
снимает relay раз в 5 с из PostgreSQL (частичный индекс незавершённых
|
||||
заданий): это возраст старейшего задания в состоянии `queued` или
|
||||
`processing`, где бы оно ни ждало — в outbox, в брокере или у worker.
|
||||
|
||||
**Что это значит для пользователя.** Загрузки отвечают 202, но вложения
|
||||
долго остаются `queued`/`processing`; ссылки на них в сообщениях есть, а
|
||||
байтов (`/content`) нет — 409.
|
||||
|
||||
## Шаги
|
||||
|
||||
1. Dashboard, панель «Job queue depth by state»:
|
||||
- растёт `outbox` — relay не публикует: брокер недоступен или relay
|
||||
остановлен (`docker compose ps relay rabbitmq`, журнал relay:
|
||||
`broker publish failed`, `relay pass failed`);
|
||||
- растёт `published`, `processing` ≈ 0 — worker не берёт:
|
||||
«Worker busy / capacity» пусто или 0 → worker остановлен
|
||||
(`make pipeline-state`, `docker compose ps worker`);
|
||||
- `processing` = capacity долго — worker занят до предела: смотреть
|
||||
«Job delivery duration» и CPU worker.
|
||||
2. Loki: `{service_name="messenger-worker"} |= "attachment processed"` —
|
||||
последние исходы; `retry` с растущими задержками — временный отказ
|
||||
S3, задания ждут backoff (до `JOB_RETRY_MAX_SECONDS`).
|
||||
3. Трасса одной зависшей загрузки: `make trace-chain` показывает, как
|
||||
найти её по id вложения (`messenger.attachment.id`) и где цепочка
|
||||
оборвалась (нет producer — relay; нет consumer — брокер или worker).
|
||||
|
||||
## Восстановление и проверка
|
||||
|
||||
Запустить остановленное (`make start-worker`, `docker compose start relay`).
|
||||
Backlog разбирается со скоростью панели «Job deliveries per second»;
|
||||
когда старейшее задание завершено, возраст падает, alert resolved.
|
||||
Повтор проверки — `make alerts-check`.
|
||||
@@ -0,0 +1,55 @@
|
||||
# MessengerTelemetryTargetDown — Prometheus не видит Collector
|
||||
|
||||
**Условие.** `up{job=~"messenger|otel-collector"} == 0` 1 мин. Метрики
|
||||
приложения приходят в Prometheus только через экспортёр Collector, поэтому
|
||||
без него alerts по ошибкам и очереди молчат, хотя сервис может работать.
|
||||
|
||||
**Что это значит для пользователя.** Ничего: сообщения и загрузки от
|
||||
телеметрии не зависят (SDK держит ограниченную очередь и отбрасывает
|
||||
лишнее). Теряются сигналы.
|
||||
|
||||
## Шаги
|
||||
|
||||
1. `docker compose ps` — сервисы телеметрии и их шлюзы (лаба 7: `otel-gateway` →
|
||||
`otel-collector`, `loki-gateway` → `loki`, `tempo-gateway` → `tempo`,
|
||||
`prometheus-gateway` → `prometheus`). Остановлен или перезапускается: OOM
|
||||
Collector (лимит контейнера 256 МиБ, `memory_limiter` 180 МиБ); шлюз не healthy —
|
||||
нет файлов PKI или ошибка в `infra/otel/*gateway.cfg` (`docker compose logs
|
||||
<шлюз>`). Каналы целиком проверяет `make telemetry-tls-check`.
|
||||
2. Сервис и шлюз работают, а цель `up` = 0 (или экспорт Collector получает от шлюза
|
||||
503, SDK — закрытие соединения) — **сервис остался без сети**, он живёт в
|
||||
пространстве шлюза:
|
||||
- шлюз перезапустила политика Docker (`RestartCount` шлюза вырос) или его одного
|
||||
остановили и запустили (`stop` и `start` / `up -d`) — `docker compose restart
|
||||
<шлюз>` (сервис перезапустится с ним) или `restart <сервис>`;
|
||||
- шлюз пересоздан один (`up -d --force-recreate <шлюз>`): `docker inspect -f
|
||||
'{{.HostConfig.NetworkMode}}'` контейнера сервиса не равно `container:<id
|
||||
шлюза>`, `restart` падает с «No such container» — `docker compose up -d
|
||||
<сервис>` (пересоздаст его).
|
||||
3. **Отказ TLS или прав**: отказы рукопожатия и identity — строки `otlp-refused`,
|
||||
`<шлюз>-refused` журнала шлюза (SAN, причина; `cert_err=X509_V_ERR_CERT_REVOKED` —
|
||||
отозван, шлюз со старым CRL или клиент со старым leaf), 403 прав — `<шлюз> …
|
||||
<метод> <путь> status=403` (новый путь Grafana — строка списка `read_path` в
|
||||
`*gateway.cfg`). Метрики LB (`up{job="haproxy"}`) — `docker compose logs haproxy`,
|
||||
строки `monitor-refused`; у Collector — «Failed to scrape Prometheus endpoint». Клиент
|
||||
не доверяет серверу — ошибка сертификата в журнале Collector, Prometheus или
|
||||
Grafana: `make pki-status`, после `make pki-stand` — рестарт шлюза и клиента.
|
||||
4. **Prometheus без сети — немой отказ**: оповещения считает он сам. Признаки — ошибка
|
||||
источника Prometheus в Grafana, `docker compose ps prometheus-gateway prometheus`,
|
||||
`NetworkMode` Prometheus.
|
||||
5. `make logs-telemetry`: `memory limiter` — отказ приёма по памяти,
|
||||
`Exporting failed` — backend (Tempo/Loki) или его шлюз недоступен.
|
||||
6. Потери (у Collector 0.164 счётчики без суффикса `_total`):
|
||||
`otelcol_receiver_refused_*` (отказано SDK),
|
||||
`otelcol_exporter_send_failed_*` и `otelcol_exporter_enqueue_failed_*`
|
||||
(не доставлено в backend), `otelcol_exporter_queue_size` против
|
||||
`otelcol_exporter_queue_capacity`. В stdout процессов приложения —
|
||||
не чаще раза в минуту `Failed to export …` со счётчиком пропущенных.
|
||||
|
||||
## Восстановление и проверка
|
||||
|
||||
`docker compose up -d otel-collector` (или нужное хранилище), затем, если
|
||||
останавливался шлюз, — `docker compose restart <шлюз>`; `up` снова 1, alert resolved.
|
||||
После правки `*gateway.cfg` или нового CRL — `docker compose restart <шлюз>` (сервис
|
||||
перезапускается с ним), а не `--force-recreate`. Отказ хранилища телеметрии под
|
||||
нагрузкой — `make telemetry-outage`.
|
||||
@@ -0,0 +1,91 @@
|
||||
# TLS-шлюз Tempo (сервис tempo-gateway, лаба 7, перенос telemetry-backends-tls;
|
||||
# правила — infra/otel/AGENTS.md, «TLS хранилищ телеметрии»; устройство и причины
|
||||
# — как у loki-gateway.cfg):
|
||||
# Collector (otel-collector-client) ──mTLS──→ :4318 ──→ OTLP 127.0.0.1:14318
|
||||
# Grafana, Prometheus (*-client) ──mTLS──→ :3200 ──→ HTTP 127.0.0.1:13200
|
||||
# Шлюз владеет сетевым пространством Tempo (network_mode: service:tempo-gateway):
|
||||
# порты Tempo (HTTP 13200, gRPC 9095, OTLP 14318) из сетей стенда недоступны.
|
||||
# Файлы — secrets compose, читаются при старте: новый CRL и правка этого файла —
|
||||
# `docker compose restart tempo-gateway` (Tempo перезапускается с ним).
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
nbthread 1
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option dontlog-normal
|
||||
option http-ignore-probes
|
||||
# Tempo — на loopback: остановлен — 503 сразу, без повторов
|
||||
timeout connect 250ms
|
||||
retries 0
|
||||
# больше срока запроса прокси Grafana (30 с); приёму OTLP — 10 с (backend)
|
||||
timeout server 60s
|
||||
timeout client 60s
|
||||
timeout http-keep-alive 60s
|
||||
timeout http-request 10s
|
||||
|
||||
# health шлюза — только loopback и без обращения к Tempo
|
||||
frontend health
|
||||
bind 127.0.0.1:8405
|
||||
no log
|
||||
monitor-uri /ready
|
||||
http-request deny deny_status 404
|
||||
|
||||
# приём span: только Collector, только экспорт трасс
|
||||
frontend otlp_in
|
||||
bind :4318 ssl crt /run/secrets/tempo.pem ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required ssl-min-ver TLSv1.3 alpn http/1.1
|
||||
# allowlist — DNS SAN строки otel-collector-client (вся строка SAN — одно имя)
|
||||
tcp-request session set-var(sess.refusal) str(identity_not_allowed) unless { ssl_c_san -m str DNS:otel-collector }
|
||||
tcp-request session reject if { var(sess.refusal) -m found }
|
||||
# первым: путь, который Tempo прочёл бы иначе, чем шлюз
|
||||
acl unsafe_path path_sub % //
|
||||
acl unsafe_path path_reg /[.][.]?(/|$)
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused tempo-gateway if unsafe_path
|
||||
acl id_collector ssl_c_san -m str DNS:otel-collector
|
||||
http-request allow if id_collector METH_POST { path /v1/traces }
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused tempo-gateway
|
||||
log-format "tempo-gateway %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] %HM %HPO status=%ST bytes=%B term=%tsc backend=%b/%s time=%Ta"
|
||||
error-log-format "tempo-gateway-refused %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] reason=%[var(sess.refusal)] conn_err=%[fc_err_str] ssl_err=%[ssl_fc_err_str] cert_err=%[ssl_c_err,x509_v_err_str] ca_err=%[ssl_c_ca_err,x509_v_err_str] term=%tsc"
|
||||
default_backend tempo_otlp
|
||||
|
||||
# запросы: Grafana — чтение трасс и поиск, Prometheus — метрики
|
||||
frontend query_in
|
||||
bind :3200 ssl crt /run/secrets/tempo.pem ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required ssl-min-ver TLSv1.3 alpn http/1.1
|
||||
# allowlist — DNS SAN строк grafana-client, prometheus-client
|
||||
tcp-request session set-var(sess.refusal) str(identity_not_allowed) unless { ssl_c_san -m str DNS:grafana DNS:prometheus }
|
||||
tcp-request session reject if { var(sess.refusal) -m found }
|
||||
# первым: Tempo раскодирует %XX и исправляет //, сегменты . и .. (301:
|
||||
# /api/search/../../status/config → /status/config). Точка в начале имени тега
|
||||
# (/api/v2/search/tag/.service.name/values) — не сегмент. Исключение из «%» —
|
||||
# %3A: им Grafana кодирует двоеточие встроенных тегов (span:name) в подсказках
|
||||
# TraceQL, маршрут оно не меняет
|
||||
acl unsafe_path path_sub //
|
||||
acl unsafe_path path_reg %(?!3[Aa])
|
||||
acl unsafe_path path_reg /[.][.]?(/|$)
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused tempo-gateway if unsafe_path
|
||||
# права: Grafana — проверка источника (/api/echo), поиск, теги и значения,
|
||||
# трассы, buildinfo, TraceQL metrics; Prometheus — /metrics. /status/config,
|
||||
# /flush, /shutdown — ни у кого
|
||||
acl id_grafana ssl_c_san -m str DNS:grafana
|
||||
acl id_prometheus ssl_c_san -m str DNS:prometheus
|
||||
acl read_path path_reg ^/api/(echo|search(/.*)?|v2/search/.+|traces/[^/]+|v2/traces/[^/]+|status/buildinfo|metrics/.+)$
|
||||
http-request allow if id_grafana METH_GET read_path
|
||||
http-request allow if id_prometheus METH_GET { path /metrics }
|
||||
http-request deny deny_status 403 hdr X-Gateway-Refused tempo-gateway
|
||||
log-format "tempo-gateway %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] %HM %HPO status=%ST bytes=%B term=%tsc backend=%b/%s time=%Ta"
|
||||
error-log-format "tempo-gateway-refused %ci:%cp san=%[ssl_c_san] tls=%[ssl_fc_protocol] reason=%[var(sess.refusal)] conn_err=%[fc_err_str] ssl_err=%[ssl_fc_err_str] cert_err=%[ssl_c_err,x509_v_err_str] ca_err=%[ssl_c_ca_err,x509_v_err_str] term=%tsc"
|
||||
default_backend tempo_query
|
||||
|
||||
# Tempo в том же сетевом пространстве: открытый текст только на loopback
|
||||
backend tempo_otlp
|
||||
option abortonclose
|
||||
# срок экспорта Collector 5 с: зависший приём не держит соединение дольше
|
||||
timeout server 10s
|
||||
server tempo 127.0.0.1:14318
|
||||
|
||||
backend tempo_query
|
||||
option abortonclose
|
||||
server tempo 127.0.0.1:13200
|
||||
@@ -0,0 +1,45 @@
|
||||
# Tempo 3.1.1: хранилище трасс стенда, монолит (-target=all в compose.yaml)
|
||||
# без Kafka. Принимает OTLP/HTTP от Collector, API запросов — поиск TraceQL,
|
||||
# /api/v2/traces/<id>. Блоки и WAL — в volume tempodata, срок хранения блоков —
|
||||
# 7 суток. Лаба 7, перенос telemetry-backends-tls: Tempo живёт в сетевом
|
||||
# пространстве шлюза tempo-gateway и слушает только его loopback; :4318 (OTLP) и
|
||||
# :3200 (запросы) с mTLS, allowlist и правами — порты шлюза, поэтому номера
|
||||
# портов Tempo другие.
|
||||
|
||||
# потоковые запросы (gRPC поверх HTTP/2) выключены: через шлюз — только REST
|
||||
stream_over_http_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_address: 127.0.0.1
|
||||
http_listen_port: 13200
|
||||
grpc_listen_address: 127.0.0.1
|
||||
log_level: warn
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 127.0.0.1:14318
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
|
||||
# в 3.x срок блоков задают планировщик и исполнитель уплотнения
|
||||
backend_scheduler:
|
||||
provider:
|
||||
compaction:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
backend_worker:
|
||||
compaction:
|
||||
block_retention: 168h
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
Reference in New Issue
Block a user