Лабораторная 6: наблюдаемость мессенджера

This commit is contained in:
2026-11-21 11:32:12 +03:00
parent 470d9d6f1e
commit 59a3f96a82
94 changed files with 6746 additions and 35 deletions
+12
View File
@@ -0,0 +1,12 @@
FROM public.ecr.aws/docker/library/golang:1.24.2-alpine@sha256:7772cb5322baa875edd74705556d08f0eeca7b9c4b5367754ce3f2f00041ccee AS build
ENV CGO_ENABLED=0 GOPROXY="https://proxy.golang.org|https://goproxy.io|direct"
WORKDIR /src/minio
ADD https://codeload.github.com/minio/minio/tar.gz/refs/tags/RELEASE.2025-09-07T16-13-09Z /tmp/minio.tar.gz
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build tar -xzf /tmp/minio.tar.gz --strip-components=1 && go build -o /out/minio .
WORKDIR /src/mc
ADD https://codeload.github.com/minio/mc/tar.gz/refs/tags/RELEASE.2025-08-13T08-35-41Z /tmp/mc.tar.gz
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build tar -xzf /tmp/mc.tar.gz --strip-components=1 && go build -o /out/mc .
FROM python:3.12-slim-bookworm@sha256:392307d22300de8b5986851a12d9176dfc0fc073e65bf6523ebd7dcbeb23564e
COPY --from=build /out/minio /out/mc /usr/local/bin/
ENTRYPOINT ["minio"]
+19 -4
View File
@@ -1,7 +1,22 @@
# Инфраструктура студента
# Инфраструктура лабораторной 6
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Топология и ограничения ресурсов заданы в compose.yaml. Проект mtusi-lab6 использует собственные named volumes. API доступен через Nginx на localhost:18083, Grafana — localhost:13000. Секреты создаёт scripts/bootstrap.py.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
| Роль | Сервисы | Хранение / проверка |
| --- | --- | --- |
| API | api-a, api-b | PostgreSQL, readiness /health/ready |
| Балансировщик | nginx | healthwatch проверяет готовность двух реплик |
| База данных | postgres | pg_data, pg_isready |
| Кэш сессий | redis | redis_data, AOF, redis-cli ping |
| Объекты | s3, s3-bootstrap | s3_data, приватный бакет и отдельная учётная запись API |
| Очередь | rabbitmq | rabbitmq_data, durable queue, publisher confirms |
| Фоновая обработка | outbox-publisher, worker, attachment-cleaner | Job/outbox/lease в PostgreSQL |
| Сбор сигналов | otel-collector | OTLP 4317/4318, внутренний health endpoint 13133 |
| Метрики | prometheus | prometheus_data, /-/ready, локальные alert rules |
| Логи | loki | loki_data, /ready, OTLP/HTTP ingestion |
| Трассы | tempo | tempo_data, /ready, OTLP/gRPC ingestion |
| Dashboard | grafana | grafana_data, /api/health, provisioning в infra/grafana |
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
Backend и telemetry используют внутренние сети. Nginx и HTTP-интерфейсы наблюдаемости также подключены к frontend для публикации loopback-портов. OTLP на хост не опубликован. Все версии закреплены в Compose/Dockerfile. Запуск, сигналы, ограничения и результаты приведены в REPORT.md. Действия при сбое описаны в runbook.md.
scripts/restart.sh перезапускает бизнес-хранилища и приложения с существующими volumes. scripts/stop-one.sh останавливает API-реплику по TARGET_INSTANCE_ID. Историю наблюдений проверяет student-tests/telemetry_persistence.py. Сценарии student-tests/observability.py воспроизводят остановку worker, блокировку БД, retry после отказа S3 и недоступность Tempo. Каждый fault-сценарий выполняется отдельно и восстанавливает остановленные сервисы.
+446
View File
@@ -0,0 +1,446 @@
{
"uid": "messenger",
"title": "Messenger",
"schemaVersion": 40,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"tags": [
"lab6"
],
"panels": [
{
"id": 1,
"title": "API requests per second",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 0
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (method,route)(rate(messenger_http_requests_total[1m]))",
"legendFormat": "{{method}} {{route}}"
}
]
},
{
"id": 2,
"title": "API latency p50 / p95 / p99",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 0
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le)(rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p99"
}
]
},
{
"id": 3,
"title": "API 5xx ratio and 5-minute SLI",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total[1m])),0.001)",
"legendFormat": "5xx ratio"
},
{
"refId": "B",
"expr": "(1 - ((sum(increase(messenger_http_requests_total{status_class=\"5xx\"}[5m])) or vector(0)) / clamp_min(sum(increase(messenger_http_requests_total[5m])),1))) and (sum(increase(messenger_http_requests_total[5m])) > 0)",
"legendFormat": "SLI 5m"
}
]
},
{
"id": 4,
"title": "Unfinished jobs and RabbitMQ ready messages",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 8
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "max((messenger_queue_depth) and on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10))",
"legendFormat": "unfinished jobs"
},
{
"refId": "B",
"expr": "max((messenger_queue_broker_ready) and on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10))",
"legendFormat": "broker ready"
}
]
},
{
"id": 5,
"title": "PostgreSQL pool use / capacity / acquisition",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 16
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(messenger_db_pool_used) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "used {{service_name}} {{service_instance_id}}"
},
{
"refId": "B",
"expr": "(messenger_db_pool_capacity) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "capacity {{service_name}} {{service_instance_id}}"
},
{
"refId": "C",
"expr": "(messenger_db_pool_waiting) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "acquiring {{service_name}} {{service_instance_id}}"
}
]
},
{
"id": 6,
"title": "Oldest unfinished job age",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 16
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "max((messenger_queue_oldest_age_seconds) and on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10))",
"legendFormat": "age"
}
]
},
{
"id": 7,
"title": "Worker busy / capacity",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 24
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum((messenger_worker_busy{service_name=\"messenger-worker\"}) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)) or vector(0)",
"legendFormat": "busy"
},
{
"refId": "B",
"expr": "sum((messenger_worker_capacity{service_name=\"messenger-worker\"}) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)) or vector(0)",
"legendFormat": "capacity"
}
]
},
{
"id": 8,
"title": "Worker attempts by outcome",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 24
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome)(rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 9,
"title": "Worker processing p95 and accepted-to-ready p95",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 32
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "processing p95"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "time to ready p95"
}
]
},
{
"id": 10,
"title": "Process resident memory",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 32
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(messenger_process_memory_bytes) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
]
},
{
"id": 11,
"title": "Process CPU cores",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 40
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(rate(messenger_process_cpu_seconds_total[1m])) and on(service_instance_id) (time() - messenger_process_observed_at_seconds < 10)",
"legendFormat": "{{service_name}} {{service_instance_id}}"
}
]
},
{
"id": 12,
"title": "Collector exporter failures / lost records",
"type": "timeseries",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 40
},
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "{__name__=~\"otelcol_exporter_(send_failed|enqueue_failed)_(spans|log_records|metric_points).*\"}",
"legendFormat": "{{__name__}} {{exporter}}"
}
]
},
{
"id": 13,
"title": "Application logs with trace IDs",
"type": "logs",
"gridPos": {
"h": 9,
"w": 24,
"x": 0,
"y": 48
},
"datasource": {
"type": "loki",
"uid": "loki"
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-.*\"}"
}
],
"options": {
"showTime": true,
"wrapLogMessage": true
}
},
{
"id": 14,
"title": "Recent application traces",
"type": "table",
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 57
},
"datasource": {
"type": "tempo",
"uid": "tempo"
},
"targets": [
{
"refId": "A",
"queryType": "traceql",
"query": "{resource.service.name =~ \"messenger-.*\"}",
"tableType": "traces"
}
]
}
],
"annotations": {
"list": []
},
"templating": {
"list": []
}
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: true
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,33 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 3s
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
jsonData:
derivedFields:
- name: TraceID
datasourceUid: tempo
matcherRegex: '"trace_id":\s*"([0-9a-f]{32})"'
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: '-1m'
spanEndTimeShift: '1m'
tags: [{key: service.name, value: service_name}]
filterByTraceID: true
+53
View File
@@ -0,0 +1,53 @@
#!/bin/sh
# Active readiness bridge for open-source Nginx. No Docker socket or credentials.
set -eu
probe() {
if wget -T 1 -q -O /dev/null "http://$1:8080/health/ready" 2>/dev/null; then
echo up > "/tmp/$1.health"
else
echo down > "/tmp/$1.health"
fi
}
control() { cat "/tmp/control-$1" 2>/dev/null || echo serve:boot; }
echo $$ > /tmp/healthwatch.pid
while :; do
sleep 1
probe api-a &
first=$!
probe api-b &
second=$!
wait "$first"
wait "$second"
# Read desired state AFTER probes. A generation is acknowledged only after
# the matching upstream configuration has been applied, never from a stale probe.
a_control=$(control api-a)
b_control=$(control api-b)
a_state=$(cat /tmp/api-a.health)
b_state=$(cat /tmp/api-b.health)
case "$a_control" in drain:*) a_state=down;; esac
case "$b_control" in drain:*) b_state=down;; esac
: > /tmp/upstreams.next
for service in api-a api-b; do
if [ "$service" = api-a ]; then state=$a_state; else state=$b_state; fi
suffix=''
[ "$state" = up ] || suffix=' down'
printf 'server %s:8080 resolve max_fails=1 fail_timeout=2s%s;\n' "$service" "$suffix" >> /tmp/upstreams.next
done
if ! cmp -s /tmp/upstreams.next /etc/nginx/upstreams.conf; then
cp /etc/nginx/upstreams.conf /tmp/upstreams.previous
# Rename on the same filesystem: readers never see missing/partial config.
cp /tmp/upstreams.next /etc/nginx/upstreams.next
mv -f /etc/nginx/upstreams.next /etc/nginx/upstreams.conf
if nginx -t && nginx -s reload; then
echo 'readiness upstream set updated'
else
cp /tmp/upstreams.previous /etc/nginx/upstreams.next
mv -f /etc/nginx/upstreams.next /etc/nginx/upstreams.conf
exit 1
fi
fi
printf '%s %s\n' "$a_control" "$a_state" > /tmp/applied-api-a.next
mv -f /tmp/applied-api-a.next /tmp/applied-api-a
printf '%s %s\n' "$b_control" "$b_state" > /tmp/applied-api-b.next
mv -f /tmp/applied-api-b.next /tmp/applied-api-b
done
+31
View File
@@ -0,0 +1,31 @@
auth_enabled: false
server:
http_listen_port: 3100
common:
path_prefix: /loki
replication_factor: 1
ring:
kvstore:
store: inmemory
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
schema_config:
configs:
- from: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 72h
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+49
View File
@@ -0,0 +1,49 @@
worker_processes 1;
worker_shutdown_timeout 6s;
events { worker_connections 1024; }
http {
resolver 127.0.0.11 valid=1s ipv6=off;
resolver_timeout 1s;
log_format lab '$time_iso8601 $request_method $uri $status upstream=$upstream_addr '
'instance=$upstream_http_x_instance_id time=$request_time';
access_log /dev/stdout lab;
error_log /dev/stderr warn;
upstream api {
zone api 64k;
include /etc/nginx/upstreams.conf;
}
server {
listen 8080;
client_max_body_size 1m;
client_body_timeout 5s;
proxy_http_version 1.1;
proxy_set_header Connection close;
proxy_set_header Host $host;
proxy_set_header X-Request-Id $http_x_request_id;
proxy_connect_timeout 1s;
proxy_read_timeout 5s;
proxy_send_timeout 5s;
proxy_next_upstream error timeout http_502 http_504;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 6s;
location ~ ^/api/v1/chats/[^/]+/attachments$ {
# Keep a proxy ceiling above the API limit so the API can return its JSON 413.
client_max_body_size 11m;
proxy_read_timeout 45s;
proxy_send_timeout 30s;
proxy_next_upstream off;
proxy_pass http://api;
}
location ~ ^/api/v1/attachments/[^/]+/content$ {
proxy_buffering off;
proxy_read_timeout 10s;
# A shared S3 outage returns 503 without marking the API itself down.
proxy_next_upstream error timeout http_502 http_504;
proxy_pass http://api;
}
location / {
proxy_pass http://api;
}
}
}
+8 -4
View File
@@ -1,7 +1,11 @@
# Конфигурация наблюдаемости — реализовать
# OpenTelemetry
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
API, publisher и worker используют SDK 1.38.0 и OTLP/gRPC на otel-collector:4317. HTTP receiver 4318 также доступен внутри сети. Ресурсы содержат service.name, service.version, service.instance.id и deployment.environment.name=lab. Используются ручные spans и собственные имена метрик, соответствие приведено в REPORT.md.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Collector contrib 0.123.0 применяет memory_limiter и batch ко всем трём сигналам. Метрики доступны Prometheus на порту 8889, внутренние метрики Collector — на 8888. Логи отправляются OTLP/HTTP на Loki /otlp, трассы OTLP/gRPC в Tempo. Для Loki включены structured metadata и schema v13.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Очереди SDK ограничены 256 spans и logs на процесс. Collector имеет по 128 batches для Loki и Tempo, до 512 записей в batch. Retry ограничен 10 секундами. После заполнения/исчерпания retry возможны потери телеметрии, бизнес-транзакции не ждут успешного экспорта. Контейнер Collector ограничен 192 MiB, memory_limiter — 128 MiB. Критерии проверяются сценарием student-tests/observability.py backend-outage.
Grafana, Prometheus, Loki и Tempo имеют собственные volumes и retention 72 часа для сигналов. Административные HTTP-порты опубликованы только на loopback. Collector не публикует OTLP на хост.
Первичные материалы — https://opentelemetry.io/docs/collector/configuration/ и https://grafana.com/docs/loki/latest/send-data/otel/.
+73
View File
@@ -0,0 +1,73 @@
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: 128
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 512
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 128
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
timeout: 2s
sending_queue:
enabled: true
num_consumers: 2
queue_size: 128
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 3s
max_elapsed_time: 10s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
+28
View File
@@ -0,0 +1,28 @@
groups:
- name: messenger
rules:
- alert: HighApiErrorRate
expr: sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])), 0.001) > 0.01
for: 6s
labels:
severity: warning
annotations:
summary: API 5xx exceeds 1% over 1 minute
description: SLO is 99% non-5xx business requests over 5 minutes. Inspect PostgreSQL client spans and pool metrics.
runbook_url: http://localhost:13000/d/messenger/messenger?viewPanel=5
- alert: QueueLagGrowing
expr: messenger_queue_oldest_age_seconds > 15 and messenger_queue_depth > 0 and on(service_instance_id) (time() - messenger_queue_observed_at_seconds < 10)
for: 6s
labels:
severity: warning
annotations:
summary: Oldest unfinished job exceeds 15 seconds
description: Inspect worker capacity, busy gauge and consumer traces. Restore worker and verify backlog drains. See infra/runbook.md.
- alert: QueueObservationStale
expr: time() - max(messenger_queue_observed_at_seconds) > 15
for: 6s
labels:
severity: warning
annotations:
summary: Publisher backlog observations are stale
description: Check publisher and PostgreSQL availability before trusting queue gauges.
+11
View File
@@ -0,0 +1,11 @@
global:
scrape_interval: 3s
evaluation_interval: 3s
rule_files: [/etc/prometheus/alerts.yaml]
scrape_configs:
- job_name: application
static_configs:
- targets: [otel-collector:8889]
- job_name: collector
static_configs:
- targets: [otel-collector:8888]
+30
View File
@@ -0,0 +1,30 @@
# Диагностика лабораторной 6
Grafana — http://localhost:13000, dashboard Messenger. Prometheus — http://localhost:19090/alerts. Учётная запись Grafana admin, пароль в локальном secrets/grafana_password.
## Ошибки API
1. Посмотреть RPS, долю 5xx и p95/p99 за интервал алерта HighApiErrorRate.
2. В Tempo найти server span с ошибкой, раскрыть postgresql.transaction и s3 spans. HTTP server span включает шаблон маршрута и статус. SQL-параметры и содержимое объектов не экспортируются.
3. В Loki найти логи по service_name и trace_id. X-Request-Id из ответа помогает найти HTTP-событие.
4. При ошибках БД проверить здоровье postgres и число занятых соединений. getconn в psycopg2 fail-fast, waiting показывает только текущие попытки получения соединения. Exhausted и histogram acquire дополняют этот gauge.
5. Восстановить postgres. Проверить успешные запросы и исчезновение firing после выхода ошибки из минутного окна.
## Рост возраста очереди
1. Сопоставить messenger_queue_depth, messenger_queue_oldest_age_seconds, broker_ready и worker busy/capacity.
2. Backlog включает queued/processing в PostgreSQL, в том числе outbox и отложенные retry. Broker ready показывает только ожидающие доставки RabbitMQ сообщения. Processing duration измеряет одну попытку. Time to ready включает ожидание и retry.
3. Если нет свежих worker метрик, проверить worker. Gauge после остановки процесса временно сохраняется в exporter, время последнего получения данных проверять отдельно.
4. Найти trace upload по X-Trace-Id, затем producer, consumer и операции S3/DB. Попытки имеют job.attempt в traces, без job_id в metric labels.
5. Запустить worker. Убедиться, что backlog и oldest age равны нулю, алерт resolved. При QueueObservationStale проверить publisher/БД.
## Хранилище телеметрии недоступно
1. Посмотреть собственные метрики Collector, exporter send_failed и enqueue_failed, а также docker stats.
2. SDK ограничены 256 spans/logs на процесс, batch 64 и timeout 1 секунда. Collector ограничен memory_limiter 128 MiB, контейнером 192 MiB, batch максимум 512 записей и экспортными очередями по 128 batches. При заполнении/исчерпании retry телеметрия может теряться. Prometheus экспортируется pull endpoint, его остановка оставляет пробел в scrape-истории.
3. Восстановить Loki/Tempo, убедиться, что свежий trace и лог снова доступны. Подтвердить, что принятые сообщения и вложения доступны через API.
4. Разница accepted/sent и exporter failure counters помогает оценивать проблему. send_failed учитывает попытки отправки, поэтому не является точным числом уникальных потерянных spans. Без sequence IDs точные потери не заявляются.
## SLI/SLO
SLI = 1 − число 5xx / число всех бизнес-запросов за скользящие 5 минут. Health исключён при записи HTTP-метрик. SLO ≥ 99%. При отсутствии запросов окно не даёт оценки доступности. 4xx остаются в знаменателе и не считаются отказами сервера. Алерт ошибок использует более короткое окно 1 минута, порог 1%, for 6 секунд. QueueLagGrowing — возраст старейшего незавершённого задания >15 секунд, backlog >0, for 6 секунд. Это учебные пороги для воспроизводимой проверки.
+73
View File
@@ -0,0 +1,73 @@
#!/bin/sh
set -eu
umask 077
bucket=${S3_BUCKET:-messenger-attachments}
case "$bucket" in
''|*[!a-z0-9.-]*) echo 'Invalid S3 bucket name' >&2; exit 1 ;;
esac
config=$(mktemp -d)
trap 'rm -rf "$config"' EXIT
export MC_CONFIG_DIR="$config"
root_user=$(cat /run/secrets/s3_root_user)
root_password=$(cat /run/secrets/s3_root_password)
api_user=$(cat /run/secrets/s3_access_key_id)
api_password=$(cat /run/secrets/s3_secret_access_key)
endpoint=${S3_ENDPOINT:-http://s3:9000}
if [ "${1:-}" = verify ]; then
export MC_HOST_api="http://$api_user:$api_password@${endpoint#http://}"
key="attachments/probe-${config##*/}"
object="api/$bucket/$key"
trap 'mc rm "$object" >/dev/null 2>&1 || true; rm -rf "$config"' EXIT
printf '%s' 'lab6-private-bucket-probe' | mc pipe "$object" >/dev/null
test "$(mc cat "$object")" = 'lab6-private-bucket-probe'
python3 - "$endpoint/$bucket/$key" <<'PYTEST'
import sys
from urllib.error import HTTPError
from urllib.request import urlopen
try:
with urlopen(sys.argv[1], timeout=5):
raise SystemExit("FAIL: anonymous GET succeeded")
except HTTPError as exc:
if exc.code != 403:
raise
print("PASS: authenticated round trip; anonymous GET returned 403")
PYTEST
mc rm "$object" >/dev/null
exit 0
fi
attempt=0
until mc alias set storage "$endpoint" "$root_user" "$root_password" >/dev/null 2>&1 &&
mc admin info storage >/dev/null 2>&1; do
attempt=$((attempt + 1))
if [ "$attempt" -ge 30 ]; then
echo 'S3 bootstrap could not connect or authenticate' >&2
exit 1
fi
sleep 1
done
mc mb --ignore-existing "storage/$bucket"
mc anonymous set none "storage/$bucket"
cat > "$config/api-policy.json" <<POLICY
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::$bucket/attachments/*"]
}, {
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::$bucket"]
}]
}
POLICY
mc admin policy create storage lab6-attachments "$config/api-policy.json"
mc admin user add storage "$api_user" "$api_password" >/dev/null
mc admin policy attach storage lab6-attachments --user "$api_user"
echo 'PASS: private S3 bucket and scoped API policy configured'
+22
View File
@@ -0,0 +1,22 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
compactor:
compaction:
block_retention: 72h
usage_report:
reporting_enabled: false
+2
View File
@@ -0,0 +1,2 @@
server api-a:8080 resolve max_fails=1 fail_timeout=2s;
server api-b:8080 resolve max_fails=1 fail_timeout=2s;