Один trace_id проходит от HTTP через outbox и Kafka до worker, S3 и JDBC, включая повтор. Collector держит короткую очередь и memory limiter, поэтому остановка Prometheus, Loki или Tempo не останавливает приём сообщений.

Автор / группа: ivanstorozhev, БВТ2304
Целевая оценка (3/4/5): 4
Трек 5, если заявлен: не заявлен

Что реализовано и что перенесено: из lab5 перенесены Spring Boot API, PostgreSQL, Redis-кэш сессий, Argon2id, Liquibase через одноразовый сервис migrate, HAProxy без sticky session, две реплики, X-Instance-Id, обязательный Idempotency-Key, scripts/stop-one.sh и scripts/restart.sh, приватный SeaweedFS, ответ 202, staging, transactional outbox, отдельный worker, Kafka 3.9.1 (KRaft, volume kafka-data), состояния queued/processing/ready/failed, JPEG thumbnail и crop, lossy WebP, retry с backoff и jitter, топик attachments.failed, явный replay и lease. Оригинал принимается в S3 в одной транзакции со строкой outbox. Worker коммитит смещение только после записи вариантов в фиксированные ключи. Сообщение брокера содержит идентификаторы и W3C traceparent, без тела сообщения и ключа объекта. Добавлены OTLP из API и worker в Collector 0.139.0, Prometheus v3.2.1, Loki 3.4.2, Tempo 2.7.2 и Grafana 11.6.1. Producer-спан и consumer-спан связаны через заголовок Kafka. Повторная попытка остаётся в том же trace. Дашборд messenger-lab6 считает p50/p95/p99 через histogram_quantile по сумме бакетов и делит миллисекунды на 1000. SLI доступности — доля 5xx на обычных маршрутах, SLO 99% за 5 минут. SLI очереди — возраст самого старого queued или processing, SLO меньше 30 с. Алерты messenger-error-rate и messenger-queue-lag проверяются локально, без внешней доставки. memory_limiter 192 MiB и очереди экспортёров на 256 записей сбрасывают телеметрию, если хранилище недоступно.

Команды запуска из чистого clone:
cp .env.example .env
docker compose --env-file .env config --quiet
docker compose --env-file .env up -d --build
curl -fsS http://127.0.0.1:8080/health/ready
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
docker compose --env-file .env start api
python3 scripts/grade6-evidence.py

Результаты проверок и ссылка на REPORT.md: подробности и числа в REPORT.md
make check — PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
make test — PASS: lab6 public API scenario; infrastructure and grading evidence remain separate.
python3 scripts/grade6-evidence.py — PASS. Загрузка bf19675a-7d93-4379-a708-1e5efc7366a7, trace d27d941c741436ad51a3b35c2921ca4d: HTTP-спан родитель s3.PutObject, JDBC и attachments.process publish; process — ребёнок publish; S3 и JDBC worker — дети process. Тот же trace_id в логе API attachment.accepted и в логе worker job.ready, и в Loki. Повтор ac1e1581-4d24-4789-a887-c14a1852581a в trace 5540712fa2d49096df09db864f9ad9a8: два publish и два process, S3 worker только на второй попытке, итог ready. До аварий p50 0.039 с, p95 0.132 с, p99 0.134 с по гистограмме за 5 минут. slow-db: JDBC query 3013 мс; slow-handler: сервер 3026 мс и ни одного JDBC-спана. Остановка worker: возраст очереди 75.5 с, алерт Alerting, после старта то же вложение ready и алерт Normal. 608 ответов 500: доля 1 и Alerting, после тишины доля 0 и Normal. При остановленных Prometheus, Loki и Tempo сообщение получило 201, вложение стало ready, память collector 100 → 98.87 MiB при лимите 320 MiB, 32 строки ошибки экспорта.
mvn -q test в backend/ — код выхода 0, 22 теста, 0 failures, 0 errors.

Ограничения / известные ошибки: трек 5 не делался. Один Docker-хост, единственные PostgreSQL, Redis, SeaweedFS, Kafka, Loki, Tempo и Prometheus остаются точками отказа. Replication factor топиков равен 1. Доставка at least once: повтор перезаписывает те же ключи, но это не exactly-once на стороне S3. Пока хранилище телеметрии лежит, часть спанов и строк отбрасывается; после возвращения дырка в этом интервале остаётся. Шаг метрик 10 с, поэтому короткий pg_sleep может не попасть в hikaricp_connections_pending; различие снято по спанам. Staging failed-задания хранится сутки; позже replay уже не находит байты. Пока HAProxy не снял backend, часть запросов на останавливаемую реплику завершается ошибкой соединения; повтор с тем же Idempotency-Key безопасен для отправки сообщения.

Источники и использование ИИ: контракт contracts/openapi.json, contracts/README.md, contracts/observability.md, contracts/jobs.schema.json; код lab5; Spring Boot 4.1.1, Spring Data JPA, spring-security-crypto, Spring Data Redis, Spring Kafka, Liquibase, Actuator, OpenTelemetry, opentelemetry-logback-appender 2.28.1-alpha, datasource-micrometer-spring-boot 2.3.0, MapStruct 1.6.3, OpenAPI Generator 7.17.0, AWS SDK for Java 2.31.50, Thumbnailator 0.4.20, webp-imageio 0.11.0, Bouncy Castle, PostgreSQL 16.10, Redis 7.4.6, HAProxy 3.2.6, SeaweedFS 4.52, Apache Kafka 3.9.1, Collector 0.139.0, Prometheus v3.2.1, Loki 3.4.2, Tempo 2.7.2, Grafana 11.6.1, Testcontainers. Помощь ИИ использована при переносе lab5, инструментации и отчёте.

Весь обязательный минимум текущей и предыдущих работ сохранён с объявленными переходами.
Контракт и публичные тесты не ослаблены.
make check и make test выполнены; приложен реальный вывод.
Сценарии отказов своего уровня воспроизведены.
Все секреты и приватные ключи находятся вне Git; отчёт не содержит tokens.
README задания сохранён, REPORT.md содержит инструкцию именно моего решения.
This commit is contained in:
ivanstorozhev
2026-11-19 23:31:24 +03:00
parent 470d9d6f1e
commit 33bc3616f7
142 changed files with 9145 additions and 31 deletions
+4
View File
@@ -1,3 +1,7 @@
# Инфраструктура
Стенд описан в корневом `compose.yaml`. Роли lab5 сохранены. Наблюдаемость: `otel-collector`, `prometheus`, `loki`, `tempo`, `grafana`. Конфиг Collector — `infra/otel/collector.yaml`. Provisioning Grafana — `infra/grafana`.
# Инфраструктура студента
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
+239
View File
@@ -0,0 +1,239 @@
{
"uid": "messenger-lab6",
"title": "Messenger",
"tags": ["messenger", "lab6"],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "10s",
"time": {"from": "now-30m", "to": "now"},
"panels": [
{
"id": 1,
"type": "text",
"title": "SLI / SLO",
"gridPos": {"h": 5, "w": 24, "x": 0, "y": 0},
"options": {
"mode": "markdown",
"content": "**Availability SLI:** 5xx / all business HTTP requests. Health (`/health/*`) and client 4xx are outside the numerator. **SLO:** 99% success over 5 minutes.\n\n**Latency:** Micrometer exports `http.server.requests` as a histogram in milliseconds (`http_server_requests_milliseconds_bucket`). p50/p95/p99 are `histogram_quantile` over all replicas, then divided by 1000 so the panel is in seconds. Do not average per-replica percentiles.\n\n**Queue:** `messenger_queue_oldest_age_seconds` is the age of the oldest queued or processing attachment. **SLO:** under 30s. This is backlog age, not worker duration.\n\n**Time to ready:** `messenger_job_time_to_ready` is exported in milliseconds. The panel divides the quantile by 1000 and shows seconds, from the committed upload to `ready`."
}
},
{
"id": 2,
"type": "timeseries",
"title": "Business HTTP RPS",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 5},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (method, uri) (rate(http_server_requests_milliseconds_count{uri!~\"/health.*\"}[1m]))",
"legendFormat": "{{method}} {{uri}}"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "Business HTTP error ratio (5xx)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 5},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(rate(http_server_requests_milliseconds_count{status=~\"5..\",uri!~\"/health.*\"}[5m])) / clamp_min(sum(rate(http_server_requests_milliseconds_count{uri!~\"/health.*\"}[5m])), 1e-9)",
"legendFormat": "5xx ratio"
}
]
},
{
"id": 4,
"type": "timeseries",
"title": "HTTP duration p50 / p95 / p99",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 13},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_requests_milliseconds_bucket{uri!~\"/health.*\"}[5m]))) / 1000",
"legendFormat": "p50"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_requests_milliseconds_bucket{uri!~\"/health.*\"}[5m]))) / 1000",
"legendFormat": "p95"
},
{
"refId": "C",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_requests_milliseconds_bucket{uri!~\"/health.*\"}[5m]))) / 1000",
"legendFormat": "p99"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Jobs per second",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 13},
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Job duration p95",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 21},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_duration_milliseconds_bucket[5m]))) / 1000",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Time to ready p95",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 21},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_milliseconds_bucket[5m]))) / 1000",
"legendFormat": "p95"
}
]
},
{
"id": 8,
"type": "timeseries",
"title": "Queue depth and oldest job age",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 21},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": [{"matcher": {"id": "byName", "options": "oldest age"}, "properties": [{"id": "unit", "value": "s"}]}]},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_queue_depth{queue=\"attachments.process\"})",
"legendFormat": "depth"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_queue_oldest_age_seconds{queue=\"attachments.process\"})",
"legendFormat": "oldest age"
}
]
},
{
"id": 9,
"type": "timeseries",
"title": "DB pool used and waiting",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 29},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(hikaricp_connections_active)",
"legendFormat": "active"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum(hikaricp_connections_pending)",
"legendFormat": "pending"
}
]
},
{
"id": 10,
"type": "timeseries",
"title": "Worker busy / capacity",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 29},
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_worker_busy)",
"legendFormat": "busy"
},
{
"refId": "B",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max(messenger_worker_capacity)",
"legendFormat": "capacity"
}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Process CPU",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 29},
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "max by (service_name) (process_cpu_usage)",
"legendFormat": "{{service_name}}"
}
]
},
{
"id": 12,
"type": "timeseries",
"title": "Process heap",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 37},
"fieldConfig": {"defaults": {"unit": "bytes"}, "overrides": []},
"options": {"legend": {"displayMode": "list", "placement": "bottom"}, "tooltip": {"mode": "multi"}},
"targets": [
{
"refId": "A",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"expr": "sum by (service_name) (jvm_memory_used_bytes{area=\"heap\"})",
"legendFormat": "{{service_name}}"
}
]
}
]
}
@@ -0,0 +1,8 @@
apiVersion: 1
policies:
- orgId: 1
receiver: grafana-default-email
group_by:
- grafana_folder
- alertname
@@ -0,0 +1,140 @@
apiVersion: 1
groups:
- orgId: 1
name: messenger-slo
folder: Messenger
interval: 30s
rules:
- uid: messenger-error-rate
title: High business HTTP error rate
condition: C
for: 1m
noDataState: OK
execErrState: Error
isPaused: false
labels:
severity: warning
slo: api-availability
annotations:
summary: Business HTTP 5xx ratio is above 5%.
description: "SLI = 5xx / all non-health requests. 4xx is not an error. SLO is 99% success over 5 minutes. The alert uses a 2 minute ratio and fires after 1 minute."
runbook: high-error-rate.md
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: prometheus
model:
datasource:
type: prometheus
uid: prometheus
editorMode: code
expr: sum(rate(http_server_requests_milliseconds_count{status=~"5..",uri!~"/health.*"}[2m])) / clamp_min(sum(rate(http_server_requests_milliseconds_count{uri!~"/health.*"}[2m])), 1e-9)
instant: true
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
expression: A
reducer: last
refId: B
type: reduce
intervalMs: 1000
maxDataPoints: 43200
- refId: C
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
conditions:
- evaluator:
params:
- 0.05
type: gt
expression: B
refId: C
type: threshold
intervalMs: 1000
maxDataPoints: 43200
- uid: messenger-queue-lag
title: Attachment queue lag
condition: C
for: 30s
noDataState: OK
execErrState: Error
isPaused: false
labels:
severity: warning
slo: time-to-ready
annotations:
summary: Oldest queued attachment is older than 15 seconds.
description: "Queue lag is the age of the oldest queued or processing attachment, in seconds. It is not worker duration. SLO is oldest age under 30s. The alert threshold is 15s for 30s."
runbook: queue-lag.md
data:
- refId: A
relativeTimeRange:
from: 300
to: 0
datasourceUid: prometheus
model:
datasource:
type: prometheus
uid: prometheus
editorMode: code
expr: max(messenger_queue_oldest_age_seconds{queue="attachments.process"})
instant: true
intervalMs: 1000
maxDataPoints: 43200
refId: A
- refId: B
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
expression: A
reducer: last
refId: B
type: reduce
intervalMs: 1000
maxDataPoints: 43200
- refId: C
relativeTimeRange:
from: 300
to: 0
datasourceUid: __expr__
model:
datasource:
name: Expression
type: __expr__
uid: __expr__
conditions:
- evaluator:
params:
- 15
type: gt
expression: B
refId: C
type: threshold
intervalMs: 1000
maxDataPoints: 43200
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,40 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: trace_id
matcherRegex: "trace_id=([0-9a-f]+)"
url: "$${__value.raw}"
datasourceUid: tempo
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
spanStartTimeShift: "-1m"
spanEndTimeShift: "1m"
lokiSearch:
datasourceUid: loki
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
@@ -0,0 +1,8 @@
# High business HTTP error rate
SLI: `5xx / all requests` on routes other than `/health/*`. A wrong password is 401 and is not in the numerator.
1. Open the Messenger dashboard panel "Business HTTP error ratio". Confirm the ratio, not a single replica average.
2. In Loki, filter `{service_name="messenger-api"} | event="http.completed" |= "status=5"` and read `trace_id`. `status` is part of the log line, not a label. Do not copy tokens or message text out of the log.
3. Open that trace in Tempo. A database failure has a long or error `jdbc.query` child. A slow handler has a long server span and no database child.
4. After the database is back, `/health/ready` returns 200 and the 2 minute ratio falls. The alert resolves without an external notification.
+7
View File
@@ -0,0 +1,7 @@
# Attachment queue lag
The signal is `messenger_queue_oldest_age_seconds` for queue `attachments.process`. It is the age of the oldest attachment in `queued` or `processing`, measured by the API from PostgreSQL. It is not the duration of a worker span.
1. If the age grows and `messenger_worker_busy` disappears, the worker process is down. Upload still returns 202.
2. Start the worker. The same attachment becomes `ready`. The age returns to 0 on the next sample (about 5s) and the remote-write step (10s).
3. The alert resolves on the following evaluation. No message is sent outside the stand.
+8
View File
@@ -0,0 +1,8 @@
# Slow database versus a slow HTTP handler
`POST /internal/demo/slow-db?seconds=2` runs `SELECT pg_sleep` and is a database delay. `POST /internal/demo/slow-handler?seconds=2` sleeps in the handler and does not touch PostgreSQL. Both require `X-Demo-Token`.
1. Take `trace_id` from the `http.completed` log of each call.
2. The slow-db trace contains a `jdbc.query` span of about 2 seconds inside the server span.
3. The slow-handler trace has a server span of about 2 seconds and no `jdbc.query` child.
4. Hikari `hikaricp_connections_pending` rises when the pool is waiting on PostgreSQL, and stays near zero for the handler sleep.
+39
View File
@@ -0,0 +1,39 @@
global
maxconn 200
log stdout format raw local0
defaults
mode http
log global
option httplog
timeout connect 1s
timeout client 60s
timeout server 30s
timeout http-request 60s
timeout check 1s
retries 0
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold other 1s
hold refused 1s
hold nx 1s
hold timeout 1s
hold obsolete 1s
accepted_payload_size 8192
frontend http
bind *:8080
default_backend api
backend api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr host api
http-check expect status 200
default-server inter 1s fall 2 rise 1 on-marked-down shutdown-sessions
server-template api 8 api:8080 check resolvers docker init-addr none resolve-prefer ipv4
+34
View File
@@ -0,0 +1,34 @@
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
common:
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
volume_enabled: true
compactor:
working_directory: /loki/compactor
compaction_interval: 10m
+10 -4
View File
@@ -1,7 +1,13 @@
# Конфигурация наблюдаемости — реализовать
# Collector
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
`collector.yaml` принимает OTLP/HTTP `:4318` и OTLP/gRPC `:4317` только внутри сети стенда.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
| Pipeline | Exporter | Хранилище |
| --- | --- | --- |
| traces | `otlphttp/tempo` | Tempo `2.7.2`, локальные блоки на volume `tempo-data` |
| metrics | `prometheusremotewrite` | Prometheus `v3.2.1`, remote write, volume `prometheus-data` |
| logs | `otlphttp/loki` | Loki `3.4.2`, filesystem, volume `loki-data` |
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
`memory_limiter` (192 MiB) стоит первым процессором. У Tempo и Loki очередь `queue_size: 256` с `block_on_overflow: false`. У Prometheus remote write очередь `remote_write_queue.queue_size: 256`. При недоступном backend данные отбрасываются после `max_elapsed_time: 30s`, а не копятся без предела.
Grafana `11.6.1` только читает эти хранилища. Datasource, dashboard и alert rules лежат в `infra/grafana` и подключаются provisioning-ом.
+86
View File
@@ -0,0 +1,86 @@
# OTel Collector 0.139.0. Receives OTLP from API and worker, then forwards
# metrics to Prometheus, logs to Loki and traces to Tempo.
# memory_limiter and a bounded sending queue drop data when a backend is down
# instead of growing RAM without a limit.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 48
batch:
timeout: 5s
send_batch_size: 512
send_batch_max_size: 1024
exporters:
otlphttp/tempo:
endpoint: http://tempo:4318
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
block_on_overflow: false
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 5s
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
block_on_overflow: false
prometheusremotewrite:
endpoint: http://prometheus:9090/api/v1/write
timeout: 5s
resource_to_telemetry_conversion:
enabled: true
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
remote_write_queue:
enabled: true
queue_size: 256
num_consumers: 2
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheusremotewrite]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
telemetry:
logs:
level: info
+6
View File
@@ -0,0 +1,6 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
# Series arrive by remote write from the Collector. There is no scrape of the API.
scrape_configs: []
+24
View File
@@ -0,0 +1,24 @@
{
"identities": [
{
"name": "messenger-api",
"credentials": [
{
"accessKey": "${S3_ACCESS_KEY}",
"secretKey": "${S3_SECRET_KEY}"
}
],
"actions": ["Read", "Write", "List"]
},
{
"name": "messenger-bootstrap",
"credentials": [
{
"accessKey": "${S3_BOOTSTRAP_ACCESS_KEY}",
"secretKey": "${S3_BOOTSTRAP_SECRET_KEY}"
}
],
"actions": ["Admin"]
}
]
}
+28
View File
@@ -0,0 +1,28 @@
stream_over_http_enabled: true
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks