Перенесла файлы проекта из предыдущей лабораторной работы
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
apiVersion: 1
|
||||
|
||||
contactPoints:
|
||||
- orgId: 1
|
||||
name: messenger-local
|
||||
receivers:
|
||||
- uid: messenger-local-webhook
|
||||
type: webhook
|
||||
disableResolveMessage: false
|
||||
settings:
|
||||
# Доставка наружу не требуется; локальный no-op endpoint.
|
||||
url: http://127.0.0.1:9/messenger-alerts
|
||||
httpMethod: POST
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: 1
|
||||
|
||||
policies:
|
||||
- orgId: 1
|
||||
receiver: messenger-local
|
||||
group_by: ['alertname']
|
||||
group_wait: 10s
|
||||
group_interval: 1m
|
||||
repeat_interval: 4h
|
||||
@@ -0,0 +1,109 @@
|
||||
apiVersion: 1
|
||||
|
||||
groups:
|
||||
- orgId: 1
|
||||
name: messenger-alerts
|
||||
folder: Messenger
|
||||
interval: 1m
|
||||
rules:
|
||||
- uid: messenger-high-error-rate
|
||||
title: MessengerHighErrorRate
|
||||
condition: C
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange:
|
||||
from: 60
|
||||
to: 0
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
editorMode: code
|
||||
expr: sum(rate(http_requests_total{http_status_class="5xx"}[1m])) / clamp_min(sum(rate(http_requests_total[1m])), 1e-9)
|
||||
instant: true
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
range: false
|
||||
refId: A
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model:
|
||||
conditions:
|
||||
- evaluator:
|
||||
params: [0.05]
|
||||
type: gt
|
||||
operator:
|
||||
type: and
|
||||
query:
|
||||
params: [C]
|
||||
reducer:
|
||||
params: []
|
||||
type: last
|
||||
type: query
|
||||
datasource:
|
||||
type: __expr__
|
||||
uid: __expr__
|
||||
expression: A
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: C
|
||||
type: threshold
|
||||
for: 30s
|
||||
annotations:
|
||||
summary: "API error rate > 5% over 1m"
|
||||
description: "5xx ratio exceeds SLO 5% for 30 seconds."
|
||||
runbook: "infra/runbooks/high-error-rate.md"
|
||||
labels:
|
||||
severity: warning
|
||||
noDataState: NoData
|
||||
execErrState: Error
|
||||
isPaused: false
|
||||
|
||||
- uid: messenger-jobs-backlog-growing
|
||||
title: MessengerJobsBacklogGrowing
|
||||
condition: C
|
||||
data:
|
||||
- refId: A
|
||||
relativeTimeRange:
|
||||
from: 600
|
||||
to: 0
|
||||
datasourceUid: prometheus
|
||||
model:
|
||||
editorMode: code
|
||||
expr: sum(increase(jobs_processed_total{outcome="retry"}[10m])) - sum(increase(jobs_processed_total{outcome="success"}[10m]))
|
||||
instant: true
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
range: false
|
||||
refId: A
|
||||
- refId: C
|
||||
datasourceUid: __expr__
|
||||
model:
|
||||
conditions:
|
||||
- evaluator:
|
||||
params: [5]
|
||||
type: gt
|
||||
operator:
|
||||
type: and
|
||||
query:
|
||||
params: [C]
|
||||
reducer:
|
||||
params: []
|
||||
type: last
|
||||
type: query
|
||||
datasource:
|
||||
type: __expr__
|
||||
uid: __expr__
|
||||
expression: A
|
||||
intervalMs: 1000
|
||||
maxDataPoints: 43200
|
||||
refId: C
|
||||
type: threshold
|
||||
for: 5m
|
||||
annotations:
|
||||
summary: "Retries outpace successes"
|
||||
description: "Worker retry count exceeds successes by >5 for 5m."
|
||||
runbook: "infra/runbooks/queue-lag.md"
|
||||
labels:
|
||||
severity: warning
|
||||
noDataState: NoData
|
||||
execErrState: Error
|
||||
isPaused: false
|
||||
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Messenger — lab6 observability",
|
||||
"schemaVersion": 39,
|
||||
"version": 2,
|
||||
"editable": true,
|
||||
"timezone": "browser",
|
||||
"time": {"from": "now-30m", "to": "now"},
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"name": "service",
|
||||
"type": "query",
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"query": "label_values(up, job)",
|
||||
"current": {"text": "otel-collector", "value": "otel-collector"}
|
||||
}
|
||||
]
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"type": "timeseries",
|
||||
"title": "API RPS (total)",
|
||||
"gridPos": {"x": 0, "y": 0, "w": 8, "h": 8},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"targets": [
|
||||
{"expr": "sum(rate(http_requests_total[1m]))", "legendFormat": "rps", "refId": "A"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"type": "timeseries",
|
||||
"title": "API error ratio (5xx / total)",
|
||||
"gridPos": {"x": 8, "y": 0, "w": 8, "h": 8},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"targets": [
|
||||
{"expr": "sum(rate(http_requests_total{http_status_class=\"5xx\"}[5m])) / clamp_min(sum(rate(http_requests_total[5m])), 1e-9)", "legendFormat": "ratio", "refId": "A"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"type": "timeseries",
|
||||
"title": "HTTP latency p50/p95/p99 (s)",
|
||||
"gridPos": {"x": 16, "y": 0, "w": 8, "h": 8},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"targets": [
|
||||
{"expr": "histogram_quantile(0.50, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p50", "refId": "A"},
|
||||
{"expr": "histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "B"},
|
||||
{"expr": "histogram_quantile(0.99, sum by (le) (rate(http_request_duration_seconds_bucket[5m])))", "legendFormat": "p99", "refId": "C"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"type": "timeseries",
|
||||
"title": "Jobs processed by outcome",
|
||||
"gridPos": {"x": 0, "y": 8, "w": 12, "h": 8},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"targets": [
|
||||
{"expr": "sum by (outcome) (rate(jobs_processed_total[1m]))", "legendFormat": "{{outcome}}", "refId": "A"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"type": "timeseries",
|
||||
"title": "Job duration p95 (s) by outcome",
|
||||
"gridPos": {"x": 12, "y": 8, "w": 12, "h": 8},
|
||||
"datasource": {"type": "prometheus", "uid": "prometheus"},
|
||||
"targets": [
|
||||
{"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(job_processing_duration_seconds_bucket[5m])))", "legendFormat": "{{outcome}}", "refId": "A"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"type": "logs",
|
||||
"title": "API + worker logs",
|
||||
"gridPos": {"x": 0, "y": 16, "w": 24, "h": 10},
|
||||
"datasource": {"type": "loki", "uid": "loki"},
|
||||
"targets": [
|
||||
{"expr": "{service_name=~\"messenger-api|messenger-worker|messenger-outbox\"}", "refId": "A"}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger
|
||||
folder: Messenger
|
||||
type: file
|
||||
options:
|
||||
path: /etc/grafana/provisioning/dashboards/json
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,37 @@
|
||||
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: TraceID
|
||||
matcherRegex: 'trace_id=([a-f0-9]+)'
|
||||
datasourceUid: tempo
|
||||
url: "$${__value.raw}"
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
tags:
|
||||
- key: service.name
|
||||
value: service_name
|
||||
filterByTraceID: true
|
||||
@@ -0,0 +1,42 @@
|
||||
auth_enabled: false
|
||||
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
grpc_listen_port: 9096
|
||||
log_level: warn
|
||||
|
||||
common:
|
||||
path_prefix: /loki
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
replication_factor: 1
|
||||
ring:
|
||||
instance_addr: 127.0.0.1
|
||||
kvstore:
|
||||
store: inmemory
|
||||
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
limits_config:
|
||||
retention_period: 168h
|
||||
reject_old_samples: true
|
||||
reject_old_samples_max_age: 168h
|
||||
allow_structured_metadata: true
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
delete_request_store: filesystem
|
||||
retention_enabled: true
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,48 @@
|
||||
# vhost для nginx: монтируется в /etc/nginx/conf.d/default.conf.
|
||||
# Главный nginx.conf образа сам содержит events/http/include conf.d/*.conf.
|
||||
|
||||
# DNS Docker: 127.0.0.11 — встроенный резолвер, отдаёт адреса сервисов
|
||||
# compose-сети. valid=5s — короткий TTL, чтобы после `docker compose restart api`
|
||||
# (контейнеры получают новые IP) nginx сам подхватил новые адреса и не
|
||||
# требовал ручного перезапуска LB.
|
||||
resolver 127.0.0.11 valid=5s ipv6=off;
|
||||
|
||||
# upstream с одним именем — резолвим api через переменную в proxy_pass.
|
||||
# Без `server api:8080;` в upstream, иначе nginx закэширует IP на старте.
|
||||
# Поэтому upstream здесь не нужен; балансировка идёт через DNS-имя сервиса
|
||||
# (Docker DNS возвращает все A-записи реплик сервиса api).
|
||||
# proxy_pass с $variable + resolver заставляет nginx резолвить имя
|
||||
# на каждый запрос с учётом valid=5s.
|
||||
|
||||
server {
|
||||
listen 80 default_server;
|
||||
server_name _;
|
||||
|
||||
# Не ограничивать допустимый размер вложения приложением (MAX_UPLOAD_BYTES
|
||||
# = 10 MiB); nginx по умолчанию отвечает 413 HTML. Значение "10m" не
|
||||
# меньше 10485760 байт, поэтому валидные загрузки до 10 MiB проходят.
|
||||
client_max_body_size 10m;
|
||||
|
||||
proxy_connect_timeout 1s;
|
||||
proxy_send_timeout 10s;
|
||||
proxy_read_timeout 10s;
|
||||
|
||||
location / {
|
||||
# Переменная в proxy_pass: nginx резолвит api:8080 через resolver
|
||||
# на каждый запрос, учитывая valid=5s. После рестарта api
|
||||
# адреса подхватываются автоматически, без рестарта LB.
|
||||
# Без upstream{} и без `server api:8080;` — иначе IP кэшируется.
|
||||
set $api_upstream "api:8080";
|
||||
proxy_pass http://$api_upstream;
|
||||
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_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
}
|
||||
|
||||
location = /lb/health {
|
||||
return 200 "ok\n";
|
||||
add_header Content-Type text/plain;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
|
||||
processors:
|
||||
# Level-4: ограничение RAM и batch, чтобы не расти бесконечно при
|
||||
# недоступном backend и уменьшить объём записи.
|
||||
memory_limiter:
|
||||
check_interval: 2s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 64
|
||||
batch:
|
||||
timeout: 5s
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
resource:
|
||||
attributes:
|
||||
- key: deployment.environment.name
|
||||
value: lab
|
||||
action: upsert
|
||||
|
||||
exporters:
|
||||
# Явно ограничиваем retry и время ожидания, чтобы при недоступном
|
||||
# бэкенде коллектор не накапливал данные и не падал.
|
||||
otlphttp/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
tls:
|
||||
insecure: true
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 4
|
||||
queue_size: 1000
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
tls:
|
||||
insecure: true
|
||||
retry_on_failure:
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s
|
||||
sending_queue:
|
||||
enabled: true
|
||||
num_consumers: 4
|
||||
queue_size: 1000
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
send_timestamps: true
|
||||
metric_expiration: 5m
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
logs:
|
||||
level: warn
|
||||
metrics:
|
||||
address: 0.0.0.0:8888
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, resource, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
@@ -0,0 +1,12 @@
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yaml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: otel-collector
|
||||
scrape_interval: 5s
|
||||
static_configs:
|
||||
- targets: ["otel-collector:8889"]
|
||||
@@ -0,0 +1,44 @@
|
||||
groups:
|
||||
- name: messenger-alerts
|
||||
interval: 30s
|
||||
rules:
|
||||
- alert: MessengerHighErrorRate
|
||||
expr: |
|
||||
sum(rate(http_requests_total{http_status_class="5xx"}[1m]))
|
||||
/
|
||||
sum(rate(http_requests_total[1m]))
|
||||
> 0.05
|
||||
for: 30s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "API error rate > 5% over 1m"
|
||||
description: "5xx ratio exceeds SLO 5% for 30 seconds."
|
||||
runbook: "infra/runbooks/high-error-rate.md"
|
||||
|
||||
- alert: MessengerJobsBacklogGrowing
|
||||
expr: |
|
||||
sum(increase(jobs_processed_total{outcome="retry"}[10m]))
|
||||
>
|
||||
sum(increase(jobs_processed_total{outcome="success"}[10m]))
|
||||
+ 5
|
||||
for: 5m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Retries outpace successes"
|
||||
description: "Worker retry count exceeds successes for 5m."
|
||||
runbook: "infra/runbooks/queue-lag.md"
|
||||
|
||||
- alert: MessengerUploadLatencyHigh
|
||||
expr: |
|
||||
histogram_quantile(0.95,
|
||||
sum by (le, http_route)
|
||||
(rate(http_request_duration_seconds_bucket{http_route=~"/api/v1/chats/.*/attachments"}[5m]))
|
||||
) > 2
|
||||
for: 3m
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "p95 upload latency > 2s"
|
||||
runbook: "infra/runbooks/slow-upload.md"
|
||||
@@ -0,0 +1,19 @@
|
||||
# Alert: MessengerHighErrorRate
|
||||
|
||||
## Симптомы
|
||||
- 5xx rate > 5% в течение 2 минут.
|
||||
- Панель «API error ratio» в Grafana.
|
||||
|
||||
## Диагностика (по шагам)
|
||||
1. Открыть Grafana → Dashboard «Messenger» → p95 latency.
|
||||
2. Открыть Explore → Loki: `{service_name="messenger-api"} |= "event=unhandled_exception"`.
|
||||
3. Найти в логах `request_id`, затем в Tempo trace с этим span или по
|
||||
trace_id из поля `trace_id`.
|
||||
4. Смотрим какие зависимость отвечает: postgres/redis/s3. Соответствующие
|
||||
ошибки пишутся как `event=db_unavailable`, `event=redis_unavailable`,
|
||||
`event=s3_unavailable`.
|
||||
|
||||
## Действие
|
||||
- Если виноват backend — перезапустить (`docker compose restart <service>`).
|
||||
- Если ошибка идёт от кода — rollback через `docker compose up -d --build`
|
||||
предыдущего тега.
|
||||
@@ -0,0 +1,17 @@
|
||||
# Alert: MessengerJobsBacklogGrowing
|
||||
|
||||
## Симптомы
|
||||
- `jobs_processed_total{outcome="retry"}` > `success` + 5 за 10 минут.
|
||||
|
||||
## Диагностика
|
||||
1. Проверить `docker compose ps worker` — процесс жив?
|
||||
2. `docker compose exec rabbitmq rabbitmqctl list_queues name messages consumers`
|
||||
3. Открыть Grafana → «Jobs processed by outcome» и «Job duration p95».
|
||||
4. Открыть Tempo, найти span `job.consume` с ошибкой (status=ERROR).
|
||||
|
||||
## Действие
|
||||
- Если worker упал — `docker compose restart worker`.
|
||||
- Если очередь переполнена по `retry_exhausted` — проверить S3 (`minio`
|
||||
контейнер healthy), затем `docker compose restart s3_cleanup`.
|
||||
- При долгом backlog включить alert `for: 10m` и снизить `MAX_ATTEMPTS` в `.env`
|
||||
для быстрого drain.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Alert: MessengerUploadLatencyHigh
|
||||
|
||||
## Симптомы
|
||||
- p95 длительности POST `/api/v1/chats/{id}/attachments` > 2s.
|
||||
|
||||
## Диагностика
|
||||
1. Grafana: p95 по route `/api/v1/chats/{id}/attachments`.
|
||||
2. Tempo: trace `POST /api/v1/chats/{id}/attachments` — найти самый долгий
|
||||
child span (`put_object` в S3 или `INSERT` в postgres).
|
||||
3. Loki: `{service_name="messenger-api"} |= "event=http" |~ "attachments"`.
|
||||
|
||||
## Действие
|
||||
- Если виноват S3 — проверить `docker compose ps minio`.
|
||||
- Если БД — увеличить `max_size` пула или `statement_timeout`.
|
||||
- Если телеметрия — переключить sampling (см. TRACK1).
|
||||
@@ -0,0 +1,34 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
grpc_listen_port: 9095
|
||||
log_level: warn
|
||||
|
||||
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: 24h
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
local:
|
||||
path: /var/tempo/traces
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
|
||||
metrics_generator:
|
||||
storage:
|
||||
path: /var/tempo/generator/wal
|
||||
Reference in New Issue
Block a user