lab6: добавить наблюдаемость и закрыть критерии оценки 5

This commit is contained in:
Wladislava1
2026-11-16 22:04:25 +03:00
parent 470d9d6f1e
commit 802e4b58c2
61 changed files with 7420 additions and 23 deletions
+279
View File
@@ -0,0 +1,279 @@
{
"annotations": { "list": [] },
"editable": true,
"fiscalYearStartMonth": 0,
"graphTooltip": 1,
"id": null,
"links": [],
"panels": [
{
"title": "API RPS",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 0, "y": 0 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "sum(rate(messenger_http_requests_total{http_route!~\"/health/.*\"}[1m]))",
"legendFormat": "rps",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps",
"custom": { "drawStyle": "line", "fillOpacity": 10 }
}
}
},
{
"title": "API error ratio (5xx / all business)",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 8, "y": 0 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "messenger:http_error_ratio:5m",
"legendFormat": "5m error ratio",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"custom": { "drawStyle": "line", "fillOpacity": 10 }
}
}
},
{
"title": "API latency p50/p95/p99",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 16, "y": 0 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "histogram_quantile(0.50, sum(rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[5m])) by (le))",
"legendFormat": "p50",
"refId": "A"
},
{
"expr": "histogram_quantile(0.95, sum(rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[5m])) by (le))",
"legendFormat": "p95",
"refId": "B"
},
{
"expr": "histogram_quantile(0.99, sum(rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[5m])) by (le))",
"legendFormat": "p99",
"refId": "C"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": { "drawStyle": "line", "fillOpacity": 5 }
}
}
},
{
"title": "Jobs ready / failed / retry",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 0, "y": 8 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "sum by (job_outcome) (rate(messenger_jobs_processed_total[1m]))",
"legendFormat": "{{job_outcome}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops",
"custom": { "drawStyle": "line", "fillOpacity": 10 }
}
}
},
{
"title": "Job duration p50/p95/p99",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 8, "y": 8 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "histogram_quantile(0.50, sum(rate(messenger_jobs_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p50",
"refId": "A"
},
{
"expr": "histogram_quantile(0.95, sum(rate(messenger_jobs_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p95",
"refId": "B"
},
{
"expr": "histogram_quantile(0.99, sum(rate(messenger_jobs_duration_seconds_bucket[5m])) by (le))",
"legendFormat": "p99",
"refId": "C"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": { "drawStyle": "line", "fillOpacity": 5 }
}
}
},
{
"title": "Time to ready p50/p95/p99",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 16, "y": 8 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "histogram_quantile(0.50, sum(rate(messenger_attachment_time_to_ready_seconds_bucket[5m])) by (le))",
"legendFormat": "p50",
"refId": "A"
},
{
"expr": "histogram_quantile(0.95, sum(rate(messenger_attachment_time_to_ready_seconds_bucket[5m])) by (le))",
"legendFormat": "p95",
"refId": "B"
},
{
"expr": "histogram_quantile(0.99, sum(rate(messenger_attachment_time_to_ready_seconds_bucket[5m])) by (le))",
"legendFormat": "p99",
"refId": "C"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": { "drawStyle": "line", "fillOpacity": 5 }
}
}
},
{
"title": "Queue depth",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 0, "y": 16 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "messenger_queue_depth{messaging_destination_name=~\"attachments\\\\.process|attachments\\\\.retry\"}",
"legendFormat": "{{messaging_destination_name}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": { "drawStyle": "line", "fillOpacity": 10 }
}
}
},
{
"title": "Oldest job age",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 8, "y": 16 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "max(messenger_queue_oldest_job_age_seconds{messaging_destination_name=\"attachments.process\"})",
"legendFormat": "oldest age",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s",
"custom": { "drawStyle": "line", "fillOpacity": 10 }
}
}
},
{
"title": "DB pool used / waiting",
"type": "timeseries",
"gridPos": { "h": 8, "w": 8, "x": 16, "y": 16 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "messenger_db_pool_used_ratio",
"legendFormat": "used {{service_name}}",
"refId": "A"
},
{
"expr": "messenger_db_pool_waiting_ratio",
"legendFormat": "waiting {{service_name}}",
"refId": "B"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": { "drawStyle": "line", "fillOpacity": 5 }
}
}
},
{
"title": "Worker busy / capacity",
"type": "timeseries",
"gridPos": { "h": 8, "w": 12, "x": 0, "y": 24 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "messenger_worker_busy_ratio",
"legendFormat": "busy",
"refId": "A"
},
{
"expr": "messenger_worker_capacity_ratio",
"legendFormat": "capacity",
"refId": "B"
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": { "drawStyle": "line", "fillOpacity": 5 }
}
}
},
{
"title": "Process RSS",
"type": "timeseries",
"gridPos": { "h": 8, "w": 12, "x": 12, "y": 24 },
"datasource": { "type": "prometheus", "uid": "prometheus" },
"targets": [
{
"expr": "messenger_process_rss_bytes",
"legendFormat": "{{service_name}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes",
"custom": { "drawStyle": "line", "fillOpacity": 5 }
}
}
},
{
"title": "API / worker logs",
"type": "logs",
"gridPos": { "h": 10, "w": 24, "x": 0, "y": 32 },
"datasource": { "type": "loki", "uid": "loki" },
"targets": [
{
"expr": "{service_name=~\"messenger-api|messenger-worker\"}",
"refId": "A"
}
]
}
],
"schemaVersion": 39,
"tags": ["messenger", "lab6"],
"templating": { "list": [] },
"time": { "from": "now-30m", "to": "now" },
"timezone": "browser",
"title": "Messenger observability",
"uid": "messenger-lab6",
"version": 1
}
@@ -0,0 +1,13 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
foldersFromFilesStructure: false
@@ -0,0 +1,45 @@
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
uid: prometheus
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 15s
- name: Loki
type: loki
access: proxy
uid: loki
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- datasourceUid: tempo
matcherRegex: '"trace_id":"([a-f0-9]+)"'
name: TraceID
url: "$${__value.raw}"
urlDisplayLabel: View Trace
- name: Tempo
type: tempo
access: proxy
uid: tempo
url: http://tempo:3200
editable: false
jsonData:
tracesToLogs:
datasourceUid: loki
filterByTraceID: true
filterBySpanID: false
mapTagNamesEnabled: false
serviceMap:
datasourceUid: prometheus
nodeGraph:
enabled: true
lokiSearch:
datasourceUid: loki
+47
View File
@@ -0,0 +1,47 @@
global
maxconn 256
tune.bufsize 65536
tune.maxrewrite 8192
defaults
mode http
timeout connect 500ms
timeout client 60s
timeout server 60s
timeout http-request 60s
timeout http-keep-alive 2s
timeout queue 2s
timeout check 800ms
option redispatch
option dontlognull
retries 2
retry-on conn-failure empty-response 502 503 504
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 web
bind *:8080
default_backend api
backend api
balance roundrobin
# Короткий JSON сообщения можно повторить. Загрузку файла не повторяем:
# повтор создал бы второй объект. Тело загрузки не буферизуется целиком.
acl upload method POST path_reg -i ^/api/v1/chats/[0-9a-fA-F-]+/attachments$
http-request wait-for-body time 2s if METH_POST !upload
http-request disable-l7-retry if upload
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
server-template api 8 api:8080 check inter 500ms fall 2 rise 2 resolvers docker init-addr none resolve-prefer ipv4 on-marked-down shutdown-sessions
+49
View File
@@ -0,0 +1,49 @@
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: 2020-10-24
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
storage_config:
filesystem:
directory: /loki/chunks
tsdb_shipper:
active_index_directory: /loki/tsdb-index
cache_location: /loki/tsdb-cache
limits_config:
reject_old_samples: true
reject_old_samples_max_age: 168h
ingestion_rate_mb: 16
ingestion_burst_size_mb: 32
allow_structured_metadata: true
volume_enabled: true
ruler:
alertmanager_url: http://localhost:9093
analytics:
reporting_enabled: false
+19
View File
@@ -0,0 +1,19 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": ["arn:aws:s3:::messenger-attachments/*"]
},
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::messenger-attachments"]
}
]
}
+6 -4
View File
@@ -1,7 +1,9 @@
# Конфигурация наблюдаемости — реализовать
# OpenTelemetry Collector
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
Файл `collector.yaml` принимает OTLP HTTP/gRPC от API и worker, ограничивает память (`memory_limiter`), батчит экспорт и отправляет:
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
- traces → Tempo (`otlphttp/tempo`)
- metrics → Prometheus remote write
- logs → Loki OTLP (`/otlp`)
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Очереди экспортеров ограничены (`queue_size: 256`). При недоступном backend retry ограничен `max_elapsed_time: 30s`, дальше сигнал отбрасывается. Это намеренно: приложение продолжает принимать сообщения, RAM Collector не растёт бесконечно.
+80
View File
@@ -0,0 +1,80 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
grpc:
endpoint: 0.0.0.0:4317
processors:
memory_limiter:
check_interval: 1s
limit_mib: 256
spike_limit_mib: 64
batch:
send_batch_size: 256
send_batch_max_size: 512
timeout: 2s
resource:
attributes:
- key: deployment.environment.name
value: lab
action: upsert
exporters:
otlphttp/tempo:
endpoint: http://tempo:4318
tls:
insecure: true
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
# Pull-модель: Collector держит только последние значения в памяти, без бесконечной очереди.
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
enable_open_metrics: true
otlphttp/loki:
endpoint: http://loki:3100/otlp
tls:
insecure: true
sending_queue:
enabled: true
num_consumers: 2
queue_size: 256
retry_on_failure:
enabled: true
initial_interval: 1s
max_interval: 10s
max_elapsed_time: 30s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch, resource]
exporters: [otlphttp/tempo]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch, resource]
exporters: [prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch, resource]
exporters: [otlphttp/loki]
telemetry:
metrics:
level: basic
address: 0.0.0.0:8888
+88
View File
@@ -0,0 +1,88 @@
groups:
- name: messenger-slo
rules:
- record: messenger:http_requests:rate5m
expr: sum(rate(messenger_http_requests_total{http_route!~"/health/.*"}[5m])) or vector(0)
- record: messenger:http_5xx:rate5m
expr: sum(rate(messenger_http_requests_total{http_response_status_class="5xx",http_route!~"/health/.*"}[5m])) or vector(0)
- record: messenger:http_error_ratio:5m
expr: |
(
messenger:http_5xx:rate5m
/
clamp_min(messenger:http_requests:rate5m, 0.001)
)
- record: messenger:http_requests:rate30m
expr: sum(rate(messenger_http_requests_total{http_route!~"/health/.*"}[30m])) or vector(0)
- record: messenger:http_5xx:rate30m
expr: sum(rate(messenger_http_requests_total{http_response_status_class="5xx",http_route!~"/health/.*"}[30m])) or vector(0)
- record: messenger:http_error_ratio:30m
expr: |
(
messenger:http_5xx:rate30m
/
clamp_min(messenger:http_requests:rate30m, 0.001)
)
- record: messenger:http_requests:rate1h
expr: sum(rate(messenger_http_requests_total{http_route!~"/health/.*"}[1h])) or vector(0)
- record: messenger:http_5xx:rate1h
expr: sum(rate(messenger_http_requests_total{http_response_status_class="5xx",http_route!~"/health/.*"}[1h])) or vector(0)
- record: messenger:http_error_ratio:1h
expr: |
(
messenger:http_5xx:rate1h
/
clamp_min(messenger:http_requests:rate1h, 0.001)
)
- name: messenger-alerts
rules:
- alert: HighHttpErrorRate
expr: messenger:http_error_ratio:5m > 0.05
for: 1m
labels:
severity: page
annotations:
summary: "Доля HTTP 5xx выше 5% за 5 минут"
description: "Текущая доля {{ $value | humanizePercentage }}. Runbook: evidence/runbooks/high-error-rate.md"
runbook_url: "evidence/runbooks/high-error-rate.md"
- alert: GrowingQueueLag
expr: max(messenger_queue_oldest_job_age_seconds{messaging_destination_name="attachments.process"}) > 30
for: 30s
labels:
severity: ticket
annotations:
summary: "Возраст старейшей job в attachments.process выше 30 с"
description: "Возраст {{ $value }} с. Runbook: evidence/runbooks/queue-lag.md"
runbook_url: "evidence/runbooks/queue-lag.md"
- alert: ErrorBudgetBurnFast
expr: |
(
messenger:http_error_ratio:5m > (14.4 * 0.01)
and
messenger:http_error_ratio:30m > (14.4 * 0.01)
)
for: 2m
labels:
severity: page
burn_window: fast
annotations:
summary: "Быстрый burn rate ошибки SLO (14.4x на 5м и 30м)"
description: "Кратковременный всплеск 5xx. Runbook: evidence/runbooks/burn-rate.md"
runbook_url: "evidence/runbooks/burn-rate.md"
- alert: ErrorBudgetBurnSlow
expr: |
(
messenger:http_error_ratio:30m > (6 * 0.01)
)
for: 5m
labels:
severity: ticket
burn_window: slow
annotations:
summary: "Медленный burn rate ошибки SLO (6x на 30м)"
description: "Длительная деградация. Runbook: evidence/runbooks/burn-rate.md"
runbook_url: "evidence/runbooks/burn-rate.md"
+18
View File
@@ -0,0 +1,18 @@
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
- /etc/prometheus/alerts.yml
scrape_configs:
- job_name: prometheus
static_configs:
- targets: ["localhost:9090"]
- job_name: otel-collector
static_configs:
- targets: ["otel-collector:8888"]
- job_name: messenger-otel
metrics_path: /metrics
static_configs:
- targets: ["otel-collector:8889"]
+47
View File
@@ -0,0 +1,47 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
grpc:
endpoint: 0.0.0.0:4317
ingester:
trace_idle_period: 10s
max_block_bytes: 1048576
max_block_duration: 5m
compactor:
compaction:
block_retention: 48h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
metrics_generator:
registry:
external_labels:
source: tempo
storage:
path: /var/tempo/generator/wal
overrides:
defaults:
metrics_generator:
processors: []
querier:
max_concurrent_queries: 20
query_frontend:
search:
max_duration: 1h