ЛР 6 — БВТ2301 — Курлова — на 5 (трек 1 «Цена наблюдаемости»)

Перенесён минимум lab5 без изменения API и добавлена наблюдаемость:
- OTel SDK в API и worker: traces, metrics, logs по OTLP; W3C trace context
  API -> outbox -> RabbitMQ -> worker (producer/consumer spans, retry в той же трассе);
- OTel Collector (memory_limiter, scrub, batch, ограниченные очереди, профиль tail sampling),
  Prometheus, Loki, Tempo, Grafana с provisioning, dashboard и 6 alert rules с runbooks;
- проверки: наблюдаемость и приватность, инциденты A/B/C, насыщение worker,
  переполнение очереди exporter, эксперимент трека 1 (4 конфигурации x 3 прогона);
- CI job со сборкой и запуском стенда; REPORT.md с доказательствами в evidence/.
This commit is contained in:
alenchha
2026-11-11 09:24:27 +03:00
parent 470d9d6f1e
commit 0638263029
86 changed files with 10512 additions and 21 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,9 @@
apiVersion: 1
providers:
- name: messenger
folder: Messenger
type: file
disableDeletion: true
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,44 @@
# Grafana 11.5.2 datasources (fixed uids are referenced by the dashboard JSON). Grafana stores no signals itself.
# "$$" escapes "$" from Grafana's env-variable interpolation in provisioning files.
apiVersion: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
jsonData:
timeInterval: 15s
prometheusType: Prometheus
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
jsonData:
maxLines: 1000
derivedFields:
# trace_id is OTLP structured metadata -> link "Open trace" to Tempo.
- name: TraceID
matcherType: label
matcherRegex: trace_id
datasourceUid: tempo
url: "$${__value.raw}"
urlDisplayLabel: Open trace
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: "-5m"
spanEndTimeShift: "5m"
filterByTraceID: true
filterBySpanID: false
customQuery: true
query: '{service_name=~"messenger-.*"} | trace_id="$${__trace.traceId}"'
nodeGraph:
enabled: true
+39
View File
@@ -0,0 +1,39 @@
# Loki 3.4.2 single binary: log store. Logs arrive by OTLP (http://loki:3100/otlp) from the Collector.
# service.name -> stream label service_name; log attributes (event, code.*) and trace_id/span_id -> structured metadata.
auth_enabled: false
server:
http_listen_port: 3100
grpc_listen_port: 9096
log_level: warn
common:
instance_addr: 127.0.0.1
path_prefix: /loki
storage:
filesystem:
chunks_directory: /loki/chunks
rules_directory: /loki/rules
replication_factor: 1
ring:
kvstore:
store: inmemory
schema_config:
configs:
- from: "2024-01-01"
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 168h
ingestion_rate_mb: 8
ingestion_burst_size_mb: 16
volume_enabled: true
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+15
View File
@@ -0,0 +1,15 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger-attachments/attachments/*", "arn:aws:s3:::messenger-attachments/staging/*"]
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::messenger-attachments"]
}
]
}
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
# Idempotent: safe to run on every `compose up`. Root credentials are used only here, never by the API.
set -eu
BUCKET="${S3_BUCKET:-messenger-attachments}"
ROOT_USER="$(cat /run/secrets/minio_root_user)"
ROOT_PASSWORD="$(cat /run/secrets/minio_root_password)"
APP_USER="$(cat /run/secrets/s3_access_key_id)"
APP_PASSWORD="$(cat /run/secrets/s3_secret_access_key)"
until mc alias set local http://minio:9000 "$ROOT_USER" "$ROOT_PASSWORD" >/dev/null 2>&1; do
echo "waiting for minio"; sleep 2
done
mc mb --ignore-existing "local/$BUCKET"
mc anonymous set none "local/$BUCKET"
mc admin policy create local app-attachments /etc/minio-policy/app-policy.json 2>/dev/null \
|| mc admin policy create local app-attachments /etc/minio-policy/app-policy.json --overwrite 2>/dev/null || true
mc admin user add local "$APP_USER" "$APP_PASSWORD" 2>/dev/null || true
mc admin policy attach local app-attachments --user "$APP_USER" 2>/dev/null || true
echo "minio bootstrap complete: bucket=$BUCKET private, app user limited to attachments/*"
+63
View File
@@ -0,0 +1,63 @@
#!/bin/sh
set -u
SERVERS="${API_UPSTREAMS:-api-1 api-2}"
INTERVAL="${HEALTH_INTERVAL:-1}"
FALL="${HEALTH_FALL:-2}"
RISE="${HEALTH_RISE:-2}"
OUT=/etc/nginx/upstream/servers.conf
mkdir -p "$(dirname "$OUT")"
var() { echo "$1" | tr -c 'a-zA-Z0-9\n' '_'; }
render() {
any_up=0
for s in $SERVERS; do
eval "[ \"\$up_$(var "$s")\" = 1 ]" && any_up=1
done
for s in $SERVERS; do
mark=""
if [ "$any_up" = 1 ] && eval "[ \"\$up_$(var "$s")\" = 0 ]"; then
mark=" down"
fi
echo "server $s:8080 resolve max_fails=1 fail_timeout=10s$mark;"
done
}
for s in $SERVERS; do
v=$(var "$s")
eval "up_$v=1 ok_$v=0 bad_$v=0"
done
render > "$OUT"
watch() {
pending=0
while sleep "$INTERVAL"; do
changed=0
for s in $SERVERS; do
v=$(var "$s")
if wget -q -T 1 -O /dev/null "http://$s:8080/health/ready" 2>/dev/null; then
eval "ok_$v=\$((ok_$v + 1)) bad_$v=0"
if eval "[ \"\$up_$v\" = 0 ] && [ \"\$ok_$v\" -ge $RISE ]"; then
eval "up_$v=1"; changed=1; echo "health: $s ready, back in upstream"
fi
else
eval "bad_$v=\$((bad_$v + 1)) ok_$v=0"
if eval "[ \"\$up_$v\" = 1 ] && [ \"\$bad_$v\" -ge $FALL ]"; then
eval "up_$v=0"; changed=1; echo "health: $s not ready, marked down"
fi
fi
done
if [ "$changed" = 1 ]; then
render > "$OUT"
pending=1
fi
if [ "$pending" = 1 ] && nginx -s reload 2>/dev/null; then
pending=0
fi
done
}
watch &
exec nginx -g 'daemon off;'
+75
View File
@@ -0,0 +1,75 @@
worker_processes 2;
events {
worker_connections 256;
}
http {
resolver 127.0.0.11 valid=5s ipv6=off;
upstream api {
zone api 64k;
include /etc/nginx/upstream/servers.conf;
keepalive 32;
keepalive_timeout 4s;
}
log_format main '$remote_addr - $upstream_addr [$time_local] '
'"$request" $status $body_bytes_sent '
'"$upstream_response_time" "$request_time"';
access_log /var/log/nginx/access.log main;
server {
listen 8080;
client_max_body_size 64k;
error_page 413 @payload_too_large;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 1s;
proxy_read_timeout 30s;
proxy_send_timeout 30s;
proxy_next_upstream_tries 2;
proxy_next_upstream_timeout 5s;
location ~ ^/api/v1/chats/[^/]+/messages$ {
proxy_pass http://api;
proxy_next_upstream error timeout http_502 http_503 non_idempotent;
}
location ~ ^/api/v1/chats/[^/]+/attachments$ {
client_max_body_size 10m;
proxy_request_buffering off;
proxy_pass http://api;
proxy_next_upstream off;
}
location @payload_too_large {
default_type application/json;
add_header X-Request-Id $request_id always;
add_header X-Instance-Id lb always;
add_header Connection close always;
return 413 '{"error":{"code":"payload_too_large","message":"Тело запроса слишком большое","request_id":"$request_id"}}';
}
location /health/ {
proxy_pass http://api;
proxy_next_upstream error timeout;
}
location ~ ^/api/v1/attachments/ {
proxy_max_temp_file_size 0;
proxy_pass http://api;
proxy_next_upstream error timeout;
}
location / {
proxy_pass http://api;
proxy_next_upstream error timeout http_502 http_503;
}
}
}
+88
View File
@@ -0,0 +1,88 @@
# OpenTelemetry Collector (contrib 0.120.0): receiver/processor/exporter only, it stores nothing long-term.
# API, worker --OTLP/HTTP:4318--> collector --> Prometheus (metrics, OTLP), Loki (logs, OTLP), Tempo (traces, OTLP/gRPC)
# Ports are reachable only inside the compose network; nothing here is published to the host.
extensions:
health_check:
endpoint: 0.0.0.0:13133
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
max_request_body_size: 4194304 # 4 MiB per OTLP request
processors:
# First in every pipeline: refuse new data (receivers answer 503 -> SDK retries/drops) before the container OOMs.
# Container limit is 256 MiB; soft limit = limit_mib - spike_limit_mib = 140 MiB.
memory_limiter:
check_interval: 1s
limit_mib: 180
spike_limit_mib: 40
batch:
send_batch_size: 1024
send_batch_max_size: 2048
timeout: 2s
# Defense in depth: even if an instrumentation adds them, these attributes never leave the collector.
# url.query would contain ?filename=...; headers could contain Authorization.
attributes/scrub:
actions:
- {key: url.query, action: delete}
- {key: url.full, action: delete}
- {key: http.target, action: delete}
- {key: http.url, action: delete}
- {key: http.request.header.authorization, action: delete}
- {key: http.request.header.cookie, action: delete}
- {key: db.query.parameters, action: delete}
exporters:
# Every exporter: bounded in-memory queue (batches) + bounded retry. Backend down => queue fills, then new
# batches are dropped and counted (otelcol_exporter_enqueue_failed_*); RAM stays bounded, apps are unaffected.
otlphttp/prometheus:
endpoint: http://prometheus:9090/api/v1/otlp
compression: gzip
timeout: 5s
sending_queue: {enabled: true, num_consumers: 2, queue_size: 100}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 120s}
otlphttp/loki:
endpoint: http://loki:3100/otlp
compression: gzip
timeout: 5s
sending_queue: {enabled: true, num_consumers: 2, queue_size: 100}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 120s}
otlp/tempo:
endpoint: tempo:4317
tls: {insecure: true}
compression: gzip
timeout: 5s
sending_queue: {enabled: true, num_consumers: 2, queue_size: 100}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 10s, max_elapsed_time: 120s}
service:
extensions: [health_check]
telemetry:
logs:
level: info
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, batch]
exporters: [otlp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, batch]
exporters: [otlphttp/loki]
+5
View File
@@ -0,0 +1,5 @@
# Default profile: no extra processing. All spans that the SDK head-sampled are exported.
# Selected with COLLECTOR_PROFILE=default (see compose.yaml); merged over collector.yaml.
processors:
batch:
timeout: 2s
+31
View File
@@ -0,0 +1,31 @@
# Track 1 "balanced" profile (COLLECTOR_PROFILE=tail): SDK keeps 100% head sampling, the collector decides per
# whole trace after decision_wait. Keeps: every trace with an error, every trace slower than 500 ms, every trace of
# the attachment pipeline (rare, async, valuable), and 10% of the remaining ordinary traffic.
# Metrics are computed in the SDK BEFORE any sampling, so RPS/error rate/percentiles are unaffected.
processors:
tail_sampling:
decision_wait: 10s
num_traces: 20000
expected_new_traces_per_sec: 200
decision_cache:
sampled_cache_size: 50000
policies:
- name: keep-errors
type: status_code
status_code: {status_codes: [ERROR]}
- name: keep-slow
type: latency
latency: {threshold_ms: 500}
- name: keep-async-pipeline
type: string_attribute
string_attribute: {key: messaging.system, values: [rabbitmq]}
- name: baseline-10pct
type: probabilistic
probabilistic: {sampling_percentage: 10}
service:
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/scrub, tail_sampling, batch]
exporters: [otlp/tempo]
+31
View File
@@ -0,0 +1,31 @@
# Prometheus v3.2.1: metrics store. Application metrics arrive by OTLP push from the Collector
# (--web.enable-otlp-receiver, /api/v1/otlp); infrastructure self-metrics are scraped.
global:
scrape_interval: 15s
evaluation_interval: 15s
otlp:
# job=service.name, instance=service.instance.id are set by Prometheus; these become extra labels.
promote_resource_attributes:
- service.name
- service.instance.id
- service.version
- deployment.environment.name
storage:
tsdb:
# OTLP pushes from several SDKs/batches may arrive slightly out of order.
out_of_order_time_window: 10m
rule_files:
- /etc/prometheus/rules/*.yml
scrape_configs:
- job_name: otel-collector
static_configs: [{targets: ["otel-collector:8888"]}]
- job_name: tempo
static_configs: [{targets: ["tempo:3200"]}]
- job_name: loki
static_configs: [{targets: ["loki:3100"]}]
- job_name: prometheus
static_configs: [{targets: ["localhost:9090"]}]
+111
View File
@@ -0,0 +1,111 @@
# Recording rules (SLI/SLO) and alert rules. Evaluated by Prometheus every 15 s; state (pending/firing/inactive)
# is visible in Prometheus /alerts, the API /api/v1/alerts and in Grafana (alert list panel). No external delivery.
# Runbooks: docs/runbooks.md (anchors in runbook_url).
#
# Label mapping (OTLP -> Prometheus 3): service.name -> service_name, service.instance.id -> instance,
# http.route -> http_route, http.response.status_code -> http_response_status_code, job.type -> job_type.
# HTTP SLI denominator: every business request of messenger-api (health probes are not instrumented).
# Numerator of errors: 5xx only. 4xx (wrong password, 404 of a foreign chat, 409) are client outcomes, not failures.
groups:
- name: messenger-sli
interval: 15s
rules:
- record: messenger:http_requests:rate2m
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api"}[2m]))
- record: messenger:http_errors_5xx:rate2m
expr: sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[2m])) or vector(0)
- record: messenger:http_error_ratio:rate2m
expr: messenger:http_errors_5xx:rate2m / messenger:http_requests:rate2m
- record: messenger:http_latency_p95:rate5m
expr: histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name="messenger-api"}[5m])))
# SLO window: rolling 30 min (lab-sized; production would use 28-30 days with the same formulas).
# Availability SLO: 99% of business requests without 5xx.
- record: messenger:slo_availability:ratio30m
expr: |
1 - (
(sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5.."}[30m])) or vector(0))
/ sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api"}[30m]))
)
# Latency SLO: 95% of business requests complete in <= 500 ms (bucket le="0.5").
- record: messenger:slo_latency:ratio30m
expr: |
sum(increase(http_server_request_duration_seconds_bucket{service_name="messenger-api",le="0.5"}[30m]))
/ sum(increase(http_server_request_duration_seconds_count{service_name="messenger-api"}[30m]))
- record: messenger:worker_saturation:ratio
# OTLP-pushed series have no staleness markers: a recreated worker would stay in the denominator for the
# 5 min lookback. Only samples fresher than 30 s (3 export intervals) are counted.
expr: |
sum(messenger_worker_busy and (time() - timestamp(messenger_worker_busy) < 30))
/ sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 30))
- name: messenger-alerts
rules:
- alert: MessengerApiHighErrorRate
expr: messenger:http_error_ratio:rate2m > 0.05 and messenger:http_requests:rate2m > 0.2
for: 1m
labels:
severity: page
annotations:
summary: "API: доля 5xx {{ $value | humanizePercentage }} за 2 мин (порог 5%)"
description: "Больше 5% бизнес-запросов messenger-api завершаются 5xx (окно 2m, держится 1m). Расходуется бюджет SLO доступности 99%."
runbook_url: "docs/runbooks.md#messengerapihigherrorrate"
- alert: MessengerQueueLagGrowing
expr: max(messenger_queue_oldest_age_seconds{queue="attachments.process"}) > 60
for: 1m
labels:
severity: page
annotations:
summary: "Очередь вложений: старейшее задание ждёт {{ $value | humanizeDuration }}"
description: "Принятое задание не завершено дольше 60 с (порог), условие держится 1m: worker остановлен, перегружен или не может писать в S3/DB."
runbook_url: "docs/runbooks.md#messengerqueuelaggrowing"
- alert: MessengerApiLatencyHigh
expr: messenger:http_latency_p95:rate5m > 1
for: 2m
labels:
severity: ticket
annotations:
summary: "API p95 = {{ $value | humanizeDuration }} (порог 1 s, окно 5m)"
description: "p95 из histogram buckets всех реплик выше 1 s."
runbook_url: "docs/runbooks.md#messengerapilatencyhigh"
- alert: MessengerDbPoolWaiting
expr: max(db_client_connection_pending_requests) > 0
for: 1m
labels:
severity: ticket
annotations:
summary: "Запросы ждут соединение из пула БД ({{ $value }} в очереди)"
description: "Пул psycopg исчерпан дольше минуты: БД медленная/блокирована или пул мал."
runbook_url: "docs/runbooks.md#messengerdbpoolwaiting"
- alert: MessengerWorkerSaturated
expr: messenger:worker_saturation:ratio > 0.9
for: 5m
labels:
severity: ticket
annotations:
summary: "Worker занят на {{ $value | humanizePercentage }} ёмкости 5 минут"
runbook_url: "docs/runbooks.md#messengerworkersaturated"
- alert: TelemetryExportFailing
# Each term has "or vector(0)": the *_failed_* series do not exist until the first failure, and a sum with an
# empty operand is empty (the alert would never fire). Early signal: exporter queue filling up (backend
# down, retries in progress); late signal: data dropped (queue full) or retries exhausted.
expr: |
(
(sum(rate(otelcol_exporter_send_failed_spans_total[2m])) or vector(0))
+ (sum(rate(otelcol_exporter_send_failed_log_records_total[2m])) or vector(0))
+ (sum(rate(otelcol_exporter_enqueue_failed_spans_total[2m])) or vector(0))
+ (sum(rate(otelcol_exporter_enqueue_failed_log_records_total[2m])) or vector(0))
) > 0
or
max(max by (exporter) (otelcol_exporter_queue_size) / max by (exporter) (otelcol_exporter_queue_capacity)) > 0.2
for: 1m
labels:
severity: ticket
annotations:
summary: "Collector не может доставить telemetry в backend"
description: "Очередь exporter заполнена >20% или данные отбрасываются: Tempo/Loki/Prometheus недоступен. Бизнес-API не затронут, RAM collector ограничена очередью и memory_limiter."
runbook_url: "docs/runbooks.md#telemetryexportfailing"
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
# Credentials come from a Docker secret; RabbitMQ's config cannot read files, so render a conf.d fragment at start.
set -eu
PASS="$(cat /run/secrets/rabbitmq_password)"
mkdir -p /etc/rabbitmq/conf.d
cat > /etc/rabbitmq/conf.d/20-credentials.conf <<CONF
default_user = messenger
default_pass = ${PASS}
default_vhost = messenger
default_permissions.configure = .*
default_permissions.read = .*
default_permissions.write = .*
CONF
exec docker-entrypoint.sh rabbitmq-server
+10
View File
@@ -0,0 +1,10 @@
# Durable broker for the attachment pipeline (see REPORT.md).
loopback_users.guest = true
listeners.tcp.default = 5672
# A delivery not acked for 10 min is returned to the queue (worker hang guard on the broker side;
# the application lease in PostgreSQL detects a hung job much earlier).
consumer_timeout = 600000
# Refuse publishes before the disk fills up (publisher sees the block and the outbox keeps the jobs).
disk_free_limit.absolute = 200MB
vm_memory_high_watermark.relative = 0.6
log.console.level = warning
+28
View File
@@ -0,0 +1,28 @@
# Tempo 2.7.1 single binary: trace store (local blocks on a volume). Receives OTLP/gRPC from the Collector.
stream_over_http_enabled: true
server:
http_listen_port: 3200
log_level: warn
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
ingester:
max_block_duration: 5m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
query_frontend:
search:
max_result_limit: 10000
usage_report:
reporting_enabled: false