Реализовать наблюдаемость и доказательства уровня 4

This commit is contained in:
EgorAnti
2026-11-19 20:08:50 +03:00
parent 470d9d6f1e
commit 935de06050
195 changed files with 19333 additions and 53 deletions
+27
View File
@@ -0,0 +1,27 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetBucketLocation",
"s3:ListBucket"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::__S3_BUCKET__/attachments/*",
"arn:aws:s3:::__S3_BUCKET__/staging/*"
]
}
]
}
+103
View File
@@ -0,0 +1,103 @@
worker_processes auto;
worker_shutdown_timeout 10s;
events {
worker_connections 1024;
}
http {
# Let the application enforce the exact 10 MiB contract and return JSON.
client_max_body_size 11m;
client_body_timeout 10s;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;
# Docker embedded DNS returns current Compose replicas. Nginx OSS 1.27.3+
# refreshes these addresses without a configuration reload.
resolver 127.0.0.11 valid=2s ipv6=off;
resolver_timeout 1s;
upstream api_backend {
zone api_backend 64k;
least_conn;
server api:8080 resolve max_fails=1 fail_timeout=2s;
keepalive 32;
}
server {
listen 80;
server_name _;
proxy_intercept_errors on;
error_page 502 503 504 = @no_ready_api;
location = /nginx-health {
access_log off;
default_type application/json;
return 200 '{"status":"ok"}';
}
# After both peers have refused traffic or become unreachable, Nginx
# would normally emit its own HTML 502. Keep the public API contract:
# no ready backend is a JSON 503 with the required tracing headers.
location @no_ready_api {
internal;
default_type application/json;
add_header X-Request-Id $request_id always;
add_header X-Instance-Id nginx always;
add_header Cache-Control "no-store" always;
return 503 '{"error":{"code":"unavailable","message":"No ready API backend","request_id":"$request_id"}}';
}
# Message POST is the only non-idempotent HTTP method that is safe to
# replay here: the API requires Idempotency-Key and commits the message
# together with its shared PostgreSQL idempotency record.
location ~ ^/api/v1/chats/[0-9a-fA-F-]+/messages$ {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_request_buffering on;
proxy_connect_timeout 500ms;
proxy_send_timeout 4s;
proxy_read_timeout 4s;
proxy_next_upstream error timeout http_502 http_503 http_504 non_idempotent;
proxy_next_upstream_tries 2;
}
location ~ ^/api/v1/chats/[0-9a-fA-F-]+/attachments$ {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_request_buffering on;
proxy_connect_timeout 500ms;
proxy_send_timeout 20s;
proxy_read_timeout 20s;
# Upload is not replayed: it has no idempotency key. The client may retry explicitly.
proxy_next_upstream off;
}
location / {
proxy_pass http://api_backend;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 500ms;
proxy_send_timeout 4s;
proxy_read_timeout 4s;
# No sticky sessions. Failed/unready peers are retried elsewhere.
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
}
}
}
+27 -4
View File
@@ -1,7 +1,30 @@
# Конфигурация наблюдаемости — реализовать
# Стек наблюдаемости
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Поток данных:
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
`messenger-api / messenger-worker -> OTLP/HTTP -> otel-collector -> Prometheus / Loki / Tempo -> Grafana`.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Версии закреплены в `compose.yaml`: Java agent 2.33.1 (SDK 1.67.0), Collector Contrib 0.165.0, Prometheus 3.14.0, Loki 3.7.8, Tempo 3.1.1 и Grafana 13.3.0.
## Файлы
- `collector.yaml` — OTLP receivers, memory limiter, redaction, batch и bounded retry queues;
- `prometheus.yaml` и `prometheus-alerts.yaml` — scrape, SLO/queue/worker/export alerts;
- `loki.yaml` — локальное хранилище структурных OTLP logs;
- `tempo.yaml` — локальное хранилище traces;
- `grafana/provisioning` — три datasources и dashboard provisioning;
- `grafana/dashboards/messenger-overview.json` — импортируемый dashboard;
- `runbooks.md` — локальные действия для каждого alert.
Grafana доступна только на `127.0.0.1:3000`, Prometheus — на `127.0.0.1:9090`. Для автоматизированных incident snapshots Loki и Tempo доступны только на loopback-портах 3100 и 3200. OTLP Collector не публикуется на интерфейсы хоста.
## Проверка корреляции
1. Выполнить `python tests/smoke.py --base-url http://localhost:8080`.
2. В Tempo найти server span upload и перейти к RabbitMQ producer/consumer span.
3. Скопировать `trace_id` и выполнить в Loki `{service_name=~"messenger-(api|worker)"} | json | trace_id="..."`.
4. Убедиться, что у API и worker разные `service.name`, но общий trace context.
Для durable retry `traceparent/tracestate` сохраняются рядом с job в PostgreSQL и восстанавливаются перед outbox republish. Проверяемый сценарий: `scripts/incident-retry-trace.ps1`; он требует минимум два producer/consumer span в одной trace и сохраняет их parent IDs.
Collector удаляет потенциально чувствительные HTTP/message/body/DB parameter attributes. Java agent не настроен на захват request/response headers или bodies. Метрики используют только route template, status/method, job type/outcome и queue name.
+87
View File
@@ -0,0 +1,87 @@
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
processors:
memory_limiter:
check_interval: 1s
limit_mib: 384
spike_limit_mib: 96
attributes/redact:
actions:
- key: http.request.header.authorization
action: delete
- key: http.request.body
action: delete
- key: http.response.body
action: delete
- key: messaging.message.body
action: delete
- key: db.statement.parameters
action: delete
- key: url.query
action: delete
batch:
send_batch_size: 512
timeout: 5s
exporters:
prometheus:
endpoint: 0.0.0.0:8889
send_timestamps: true
resource_constant_labels:
included: ["service.*", "deployment.environment.name"]
otlp_http/tempo:
endpoint: http://tempo:4318
sending_queue:
enabled: true
queue_size: 2048
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
otlp_http/loki:
endpoint: http://loki:3100/otlp
sending_queue:
enabled: true
queue_size: 2048
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 60s
service:
extensions: [health_check]
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
without_type_suffix: false
without_units: false
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlp_http/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, attributes/redact, batch]
exporters: [otlp_http/loki]
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
if [ "${OTEL_SDK_DISABLED:-false}" = "true" ]; then
exec java -jar /app/app.jar "$@"
fi
exec java -javaagent:/opt/opentelemetry-javaagent.jar -jar /app/app.jar "$@"
@@ -0,0 +1,141 @@
{
"annotations": {"list": []},
"editable": false,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"liveNow": false,
"panels": [
{
"id": 1,
"title": "API requests / second",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "sum by (http_request_method) (rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m]))", "legendFormat": "{{http_request_method}}"}],
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 0}
},
{
"id": 2,
"title": "API 5xx ratio",
"description": "5xx business responses divided by all business responses over 5 minutes; health routes are excluded. Displayed as percent (0..100%).",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_response_status_code=~\"5..\",http_route!~\"/health/.*\"}[5m])) or vector(0)) / clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])), 0.001)", "legendFormat": "5xx / all"}],
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 0}
},
{
"id": 3,
"title": "API duration p50 / p95 / p99",
"description": "Seconds. histogram_quantile is calculated from the summed Prometheus histogram buckets of all API replicas; replica percentiles are never averaged.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p50"},
{"refId": "B", "expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p95"},
{"refId": "C", "expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{service_name=\"messenger-api\",http_route!~\"/health/.*\"}[5m])))", "legendFormat": "p99"}
],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 0}
},
{
"id": 4,
"title": "Job outcomes / second",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "sum by (outcome) (rate(messenger_jobs_processed_total{service_name=\"messenger-worker\"}[5m]))", "legendFormat": "{{outcome}}"}],
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 8}
},
{
"id": 5,
"title": "Job duration p95",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_processing_duration_seconds_bucket{service_name=\"messenger-worker\"}[5m])))", "legendFormat": "{{outcome}}"}],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 8}
},
{
"id": 6,
"title": "Time to ready p95",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket{service_name=\"messenger-worker\"}[10m])))", "legendFormat": "p95"}],
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 8}
},
{
"id": 7,
"title": "Queue depth and oldest age",
"description": "Left axis: durable queued jobs (count). Right axis: age of the oldest unfinished job (seconds). Backlog age is not processing latency.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "max(messenger_queue_depth{service_name=\"messenger-api\"})", "legendFormat": "depth"},
{"refId": "B", "expr": "max(messenger_queue_oldest_job_age_seconds{service_name=\"messenger-api\"})", "legendFormat": "oldest age (s)"}
],
"fieldConfig": {
"defaults": {},
"overrides": [
{"matcher": {"id": "byName", "options": "depth"}, "properties": [{"id": "unit", "value": "short"}, {"id": "custom.axisPlacement", "value": "left"}]},
{"matcher": {"id": "byName", "options": "oldest age (s)"}, "properties": [{"id": "unit", "value": "s"}, {"id": "custom.axisPlacement", "value": "right"}]}
]
},
"gridPos": {"h": 8, "w": 8, "x": 0, "y": 16}
},
{
"id": 8,
"title": "Worker saturation",
"description": "busy workers / configured worker capacity. Dimensionless ratio displayed as percent.",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [{"refId": "A", "expr": "messenger_worker_busy{service_name=\"messenger-worker\"} / clamp_min(messenger_worker_capacity{service_name=\"messenger-worker\"}, 1)", "legendFormat": "{{service_instance_id}}"}],
"fieldConfig": {"defaults": {"unit": "percentunit", "min": 0, "max": 1}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 8, "y": 16}
},
{
"id": 9,
"title": "DB pool used / waiting",
"description": "Number of HikariCP connections by state plus pending acquisition requests. Unit: connections/requests (count).",
"type": "timeseries",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"targets": [
{"refId": "A", "expr": "sum by (service_name, state) (db_client_connections_usage{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} {{state}}"},
{"refId": "B", "expr": "sum by (service_name) (db_client_connections_pending_requests{service_name=~\"messenger-(api|worker)\"})", "legendFormat": "{{service_name}} waiting"}
],
"fieldConfig": {"defaults": {"unit": "short"}, "overrides": []},
"gridPos": {"h": 8, "w": 8, "x": 16, "y": 16}
},
{
"id": 10,
"title": "Correlated application logs",
"type": "logs",
"datasource": {"type": "loki", "uid": "loki"},
"targets": [{"refId": "A", "expr": "{service_name=~\"messenger-(api|worker)\"} | json", "queryType": "range"}],
"options": {"showTime": true, "showLabels": false, "wrapLogMessage": true, "prettifyLogMessage": true, "enableLogDetails": true, "sortOrder": "Descending", "dedupStrategy": "none"},
"gridPos": {"h": 10, "w": 16, "x": 0, "y": 24}
},
{
"id": 11,
"title": "Recent traces",
"type": "traces",
"datasource": {"type": "tempo", "uid": "tempo"},
"targets": [{"refId": "A", "queryType": "search", "serviceName": "messenger-api", "limit": 20}],
"gridPos": {"h": 10, "w": 8, "x": 16, "y": 24}
}
],
"refresh": "10s",
"schemaVersion": 41,
"tags": ["hla", "lab6", "opentelemetry"],
"templating": {"list": []},
"time": {"from": "now-30m", "to": "now"},
"timepicker": {},
"timezone": "browser",
"title": "Messenger observability",
"uid": "messenger-observability",
"version": 3,
"weekStart": ""
}
@@ -0,0 +1,13 @@
apiVersion: 1
providers:
- name: Messenger Lab 6
orgId: 1
folder: HLA Lab 6
type: file
disableDeletion: true
updateIntervalSeconds: 30
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,59 @@
apiVersion: 1
deleteDatasources:
- name: Prometheus
orgId: 1
- name: Loki
orgId: 1
- name: Tempo
orgId: 1
datasources:
- name: Prometheus
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 10s
exemplarTraceIdDestinations:
- name: trace_id
datasourceUid: tempo
- name: Loki
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":"([a-f0-9]{32})"'
datasourceUid: tempo
url: '$${__value.raw}'
- name: Tempo
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
httpMethod: GET
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: -1m
spanEndTimeShift: 1m
filterByTraceID: true
filterBySpanID: false
customQuery: true
query: '{$${__tags}} | json | trace_id="$${__trace.traceId}"'
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
search:
hide: false
+37
View File
@@ -0,0 +1,37 @@
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
+51
View File
@@ -0,0 +1,51 @@
groups:
- name: messenger-slo
rules:
- alert: MessengerApiHighErrorRate
expr: |
(
(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code=~"5..",http_route!~"/health/.*"}[5m])) or vector(0))
/
clamp_min(sum(rate(http_server_request_duration_seconds_count{service_name="messenger-api",http_route!~"/health/.*"}[5m])), 0.001)
) > 0.05
for: 2m
labels:
severity: warning
slo: api-availability
annotations:
summary: Messenger API 5xx ratio exceeds 5%
description: Five-minute 5xx ratio is above 5% for two minutes.
runbook: infra/otel/runbooks.md#api-high-error-rate
- alert: AttachmentQueueLagHigh
expr: messenger_queue_oldest_job_age_seconds{service_name="messenger-api"} > 60
for: 1m
labels:
severity: warning
slo: attachment-time-to-ready
annotations:
summary: Oldest attachment job is over 60 seconds old
description: The durable worker queue has not drained within the SLO threshold.
runbook: infra/otel/runbooks.md#queue-lag
- alert: AttachmentWorkerSaturated
expr: |
messenger_worker_busy{service_name="messenger-worker"}
/ clamp_min(messenger_worker_capacity{service_name="messenger-worker"}, 1) >= 1
for: 2m
labels:
severity: warning
annotations:
summary: All attachment workers are busy
description: Worker busy/capacity has remained at 100% for two minutes.
runbook: infra/otel/runbooks.md#worker-saturation
- alert: TelemetryExportFailures
expr: sum(rate(otelcol_exporter_send_failed_spans_total[5m])) + sum(rate(otelcol_exporter_send_failed_log_records_total[5m])) > 0
for: 1m
labels:
severity: info
annotations:
summary: Collector is dropping traces or logs
description: A telemetry backend is unavailable or rejecting data.
runbook: infra/otel/runbooks.md#telemetry-backend
+19
View File
@@ -0,0 +1,19 @@
global:
scrape_interval: 10s
evaluation_interval: 10s
rule_files:
- /etc/prometheus/prometheus-alerts.yaml
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ["prometheus:9090"]
- job_name: otel-collector-exported-metrics
static_configs:
- targets: ["otel-collector:8889"]
- job_name: otel-collector-internal
static_configs:
- targets: ["otel-collector:8888"]
+27
View File
@@ -0,0 +1,27 @@
# Runbooks
## API high error rate
1. In Grafana, compare the 5xx ratio with `db_client_*` pool metrics.
2. Open a failed server span in Tempo and inspect child JDBC/Redis/S3 spans.
3. Search Loki by the trace ID. Do not search by a user, chat or message ID.
4. Restore the failing dependency and confirm the alert resolves after the five-minute window.
## Queue lag
1. Check `messenger_queue_depth` and `messenger_queue_oldest_job_age_seconds`.
2. Check worker busy/capacity and the rate of `messenger_jobs_processed_total` by outcome.
3. Search worker errors in Loki, then open the linked consumer trace in Tempo.
4. Restore or scale the worker and confirm depth and age return to zero.
## Worker saturation
1. Compare busy/capacity with job duration p95 and container CPU/RAM.
2. Inspect slow consumer spans and their S3/JDBC children.
3. Remove the bottleneck before increasing concurrency; memory is explicitly bounded.
## Telemetry backend
1. Inspect Collector exporter failure and queue metrics on port 8888 through Prometheus.
2. Restore Loki or Tempo. Collector retries for at most 60 seconds with a 2048-item queue.
3. Confirm the application remained available; telemetry loss is allowed and bounded.
+31
View File
@@ -0,0 +1,31 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
live_store:
max_trace_idle: 10s
max_block_duration: 5m
wal:
path: /var/tempo/live-store/traces
storage:
trace:
backend: local
local:
path: /var/tempo/blocks
overrides:
defaults:
compaction:
block_retention: 72h
usage_report:
reporting_enabled: false