Реализовать защиту Lab7 и проверку отзыва worker
Skeleton contracts / contracts (pull_request) Canceled after 0s
Lab7 HTTPS integration / compose (pull_request) Canceled after 0s

This commit is contained in:
R0flyan
2026-11-27 21:53:26 +03:00
parent 20afc2c790
commit 2fa513f56c
68 changed files with 6767 additions and 64 deletions
+41
View File
@@ -0,0 +1,41 @@
global
log stdout format raw local0
maxconn 1024
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
log global
mode http
timeout connect 600ms
timeout client 40s
timeout server 40s
timeout http-request 3s
timeout http-keep-alive 5s
timeout check 700ms
retries 0
resolvers docker
nameserver dns 127.0.0.11:53
accepted_payload_size 8192
resolve_retries 2
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold obsolete 1s
hold nx 1s
frontend public
bind :8443 ssl crt /run/ingress/tls.pem
log-format "status=%ST duration_ms=%Ta method=%HM backend=%b server=%s"
http-request del-header X-User-Id
http-request del-header X-Forwarded-For
http-request set-header X-Forwarded-Proto https
http-response set-header Strict-Transport-Security max-age=86400
default_backend api
backend api
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
server-template replica 1-4 api:8080 ssl sni str(api) verify required verifyhost api ca-file /run/client/ca.crt crt /run/client/tls.pem check check-sni api inter 500ms fall 2 rise 2 resolvers docker resolve-prefer ipv4 init-addr none
+24
View File
@@ -0,0 +1,24 @@
ui = false
api_addr = "https://openbao:8200"
storage "pebbledb" {
path = "/openbao/file/store"
}
audit "file" "local" {
description = "HMAC-protected local audit log"
options = {
file_path = "/openbao/file/audit.json"
mode = "0600"
}
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/run/lab-tls/tls.crt"
tls_key_file = "/run/lab-tls/tls.key"
tls_client_ca_file = "/run/lab-tls/ca.crt"
tls_min_version = "tls12"
tls_require_and_verify_client_cert = true
max_request_size = 65536
}
+3
View File
@@ -0,0 +1,3 @@
path "lab/data/{role}" {
capabilities = ["read"]
}
+54
View File
@@ -0,0 +1,54 @@
groups:
- name: messenger
rules:
- alert: APIFastBurn
expr: |
((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[30s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[30s]))) / 0.01 > 14.4)
and ((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[10s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[10s]))) / 0.01 > 14.4)
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[30s])) >= 8)
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[10s])) >= 3)
for: 2s
labels: {severity: page, slo: api}
annotations:
summary: "Доля 5xx на маршрутах API. Burn rate выше 14.4 в окнах 30s и 10s."
runbook: "RUNBOOK.md#api"
- alert: APISlowBurn
expr: |
((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[75s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[75s]))) / 0.01 > 6)
and ((sum(rate(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[25s])) / sum(rate(messenger_http_requests_total{route!="unmatched"}[25s]))) / 0.01 > 6)
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[75s])) >= 15)
and (sum(increase(messenger_http_requests_total{route!="unmatched"}[25s])) >= 5)
for: 12s
labels: {severity: ticket, slo: api}
annotations:
summary: "Доля 5xx на маршрутах API. Burn rate выше 6 в окнах 75s и 25s."
runbook: "RUNBOOK.md#api"
- alert: ReadyFastBurn
expr: |
((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[30s])) / sum(rate(messenger_attachment_slo_jobs_total[30s]))) / 0.01 > 14.4)
and ((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[10s])) / sum(rate(messenger_attachment_slo_jobs_total[10s]))) / 0.01 > 14.4)
and (sum(increase(messenger_attachment_slo_jobs_total[30s])) >= 8)
and (sum(increase(messenger_attachment_slo_jobs_total[10s])) >= 3)
for: 2s
labels: {severity: page, slo: ready}
annotations:
summary: "Доля загрузок, не готовых за 5 секунд. Burn rate выше 14.4 в окнах 30s и 10s."
runbook: "RUNBOOK.md#ready"
- alert: ReadySlowBurn
expr: |
((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[75s])) / sum(rate(messenger_attachment_slo_jobs_total[75s]))) / 0.01 > 6)
and ((sum(rate(messenger_attachment_slo_jobs_total{outcome="missed"}[25s])) / sum(rate(messenger_attachment_slo_jobs_total[25s]))) / 0.01 > 6)
and (sum(increase(messenger_attachment_slo_jobs_total[75s])) >= 15)
and (sum(increase(messenger_attachment_slo_jobs_total[25s])) >= 5)
for: 12s
labels: {severity: ticket, slo: ready}
annotations:
summary: "Доля загрузок, не готовых за 5 секунд. Burn rate выше 6 в окнах 75s и 25s."
runbook: "RUNBOOK.md#ready"
- alert: QueueLagHigh
expr: messenger_queue_oldest_age_seconds > 5 and messenger_queue_depth > 0
for: 4s
labels: {severity: ticket}
annotations:
summary: "Старейшее ожидающее задание старше 5 секунд."
runbook: "RUNBOOK.md#ready"
+68
View File
@@ -0,0 +1,68 @@
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 125
spike_limit_mib: 25
batch:
timeout: 1s
send_batch_size: 128
send_batch_max_size: 256
exporters:
otlphttp/prometheus:
metrics_endpoint: https://prometheus:9090/api/v1/otlp/v1/metrics
tls: &backend_tls
ca_file: /run/lab-tls/ca.crt
cert_file: /run/lab-tls/tls.crt
key_file: /run/lab-tls/tls.key
timeout: 2s
sending_queue: &bounded_queue
enabled: true
num_consumers: 1
queue_size: 16
retry_on_failure: &bounded_retry
enabled: true
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 8s
otlphttp/loki:
endpoint: https://loki:3100/otlp
tls: *backend_tls
timeout: 2s
sending_queue: *bounded_queue
retry_on_failure: *bounded_retry
otlphttp/tempo:
endpoint: https://tempo:3200
tls: *backend_tls
timeout: 2s
sending_queue: *bounded_queue
retry_on_failure: *bounded_retry
service:
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 127.0.0.1
port: 8888
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/prometheus]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
@@ -0,0 +1,810 @@
{
"uid": "messenger-lab6",
"title": "Lab 6 · Messenger",
"description": "OpenTelemetry API и очереди изображений",
"tags": [
"messenger",
"opentelemetry"
],
"schemaVersion": 39,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"timezone": "browser",
"panels": [
{
"id": 1,
"title": "Запросы API",
"description": "Интенсивность по двум API-репликам. Readiness и liveness выключены на этапе инструментации.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30s]))",
"legendFormat": "известные маршруты",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30s]))",
"legendFormat": "5xx",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 2,
"title": "Ошибки API",
"description": "5xx из приложения на известных маршрутах. 4xx входят в знаменатель.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30s])))",
"legendFormat": "5xx / все",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "vector(0.01)",
"legendFormat": "допустимая доля",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 3,
"title": "Задержка API",
"description": "Перцентили из общих bucket всех реплик. Первая минута и низкий трафик дают шумную оценку.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p50",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket[1m])))",
"legendFormat": "p99",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 4,
"title": "Попытки worker",
"description": "Считаются обработанные попытки по исходу. Повторная попытка учитывается отдельно.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_job_attempts_total[30s]))",
"legendFormat": "{{outcome}}",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 5,
"title": "Задержка попытки worker",
"description": "От захвата lease до записи итога попытки или решения о повторе.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "p50",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "p99",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 6,
"title": "Время до ready",
"description": "SQL-время от принятия загрузки до записи ready. Гистограмма включает завершившиеся первые публикации.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.50, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p50",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p99",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 7,
"title": "Глубина очереди",
"description": "Строки outbox в queued, в том числе ожидающие XADD и backoff.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "messenger_queue_depth",
"legendFormat": "queued",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 8,
"title": "Возраст старейшего задания",
"description": "Возраст от создания самой старой строки outbox в queued.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "messenger_queue_oldest_age_seconds",
"legendFormat": "oldest",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "vector(5)",
"legendFormat": "порог",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 9,
"title": "Соединения PostgreSQL",
"description": "В процессе Acquire учитываются и короткие вызовы. Смотрите динамику при устойчивом ожидании.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "messenger_db_pool_used",
"legendFormat": "{{job}} {{instance}} / занято",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "messenger_db_pool_capacity",
"legendFormat": "{{job}} {{instance}} / лимит",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "C",
"expr": "messenger_db_pool_acquiring",
"legendFormat": "{{job}} {{instance}} / получение",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 10,
"title": "Получение соединения при пустом пуле",
"description": "Производная EmptyAcquireCount pgxpool. Включает ожидание создания соединения.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "rate(messenger_db_pool_waits_total[30s])",
"legendFormat": "{{job}} {{instance}}",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 11,
"title": "Занятые слоты worker",
"description": "Только свежие показания. Снимки с шагом 2 с могут пропускать очень короткие задания.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum(messenger_worker_busy and (time() - timestamp(messenger_worker_busy) < 8)) / sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 8))",
"legendFormat": "busy / capacity",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "avg_over_time((sum(messenger_worker_busy and (time() - timestamp(messenger_worker_busy) < 8)) / sum(messenger_worker_capacity and (time() - timestamp(messenger_worker_capacity) < 8)))[30s:2s])",
"legendFormat": "среднее за 30 с",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 12,
"title": "CPU контейнеров приложения",
"description": "CPU-seconds / wall-second по cgroup v2, включая дочерний Pillow в worker.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "cores"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "rate(messenger_container_cpu_seconds_total[30s])",
"legendFormat": "{{job}} {{instance}}",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 13,
"title": "RAM контейнеров приложения",
"description": "Текущий memory.current cgroup v2.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "messenger_container_memory_bytes",
"legendFormat": "{{job}} {{instance}}",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 14,
"title": "SLI за 30 минут",
"description": "Каждый upload попадает в когорту по истечении 5 с. Без трафика SLI отсутствует.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "1 - (sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30m])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30m])))",
"legendFormat": "API",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "1 - (sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[30m])) / sum(rate(messenger_attachment_slo_jobs_total[30m])))",
"legendFormat": "ready ≤ 5 с",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "C",
"expr": "vector(0.99)",
"legendFormat": "цель",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 15,
"title": "Burn rate",
"description": "Burn rate 1 соответствует расходу бюджета с нормативной скоростью.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[10s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[10s]))) / 0.01",
"legendFormat": "API 10s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[30s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[30s]))) / 0.01",
"legendFormat": "API 30s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "C",
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[25s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[25s]))) / 0.01",
"legendFormat": "API 25s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "D",
"expr": "(sum(rate(messenger_http_requests_total{route!=\"unmatched\",status_class=\"5xx\"}[75s])) / sum(rate(messenger_http_requests_total{route!=\"unmatched\"}[75s]))) / 0.01",
"legendFormat": "API 75s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "E",
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[10s])) / sum(rate(messenger_attachment_slo_jobs_total[10s]))) / 0.01",
"legendFormat": "Ready 10s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "F",
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[30s])) / sum(rate(messenger_attachment_slo_jobs_total[30s]))) / 0.01",
"legendFormat": "Ready 30s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "G",
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[25s])) / sum(rate(messenger_attachment_slo_jobs_total[25s]))) / 0.01",
"legendFormat": "Ready 25s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "H",
"expr": "(sum(rate(messenger_attachment_slo_jobs_total{outcome=\"missed\"}[75s])) / sum(rate(messenger_attachment_slo_jobs_total[75s]))) / 0.01",
"legendFormat": "Ready 75s",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 16,
"title": "Alerts в Prometheus",
"description": "Локальная история pending и firing за выбранный период.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"APIFastBurn|APISlowBurn|ReadyFastBurn|ReadySlowBurn|QueueLagHigh\"}",
"legendFormat": "{{alertname}} / {{alertstate}}",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 17,
"title": "Потери Collector",
"description": "Число элементов в терминально неотправленных или не поставленных в очередь батчах за минуту.",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
},
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (exporter) (increase({__name__=~\"otelcol_exporter_send_failed_(spans|log_records|metric_points)(_total)?\"}[1m]))",
"legendFormat": "{{exporter}} / send failed",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
},
{
"refId": "B",
"expr": "sum by (exporter) (increase({__name__=~\"otelcol_exporter_enqueue_failed_(spans|log_records|metric_points)(_total)?\"}[1m]))",
"legendFormat": "{{exporter}} / enqueue failed",
"datasource": {
"type": "prometheus",
"uid": "lab-prom"
}
}
]
},
{
"id": 18,
"title": "Логи API и worker",
"description": "В деталях записи есть trace_id и span_id. Ссылка Trace открывает Tempo.",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "lab-loki"
},
"gridPos": {
"x": 12,
"y": 64,
"w": 12,
"h": 8
},
"fieldConfig": {
"defaults": {
"unit": "none"
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-api|messenger-worker\"}",
"legendFormat": "",
"datasource": {
"type": "loki",
"uid": "lab-loki"
}
}
]
}
]
}
@@ -0,0 +1,8 @@
apiVersion: 1
providers:
- name: Lab 6
folder: Messenger
type: file
allowUiUpdates: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,50 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: lab-prom
type: prometheus
url: https://prometheus:9090
access: proxy
isDefault: true
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
timeInterval: 2s
prometheusType: Prometheus
prometheusVersion: 3.5.0
# TLS_MATERIAL
- name: Loki
uid: lab-loki
type: loki
url: https://loki:3100
access: proxy
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
derivedFields:
- name: Trace
matcherType: label
matcherRegex: trace_id
datasourceUid: lab-tempo
url: '$${__value.raw}'
# TLS_MATERIAL
- name: Tempo
uid: lab-tempo
type: tempo
url: https://tempo:3200
access: proxy
editable: false
jsonData:
tlsAuth: true
tlsAuthWithCACert: true
tracesToLogsV2:
datasourceUid: lab-loki
tags:
- {key: service.name, value: service_name}
spanStartTimeShift: "-30s"
spanEndTimeShift: "30s"
customQuery: true
query: '{service_name=~"messenger-api|messenger-dispatcher|messenger-worker"} | trace_id="$${__span.traceId}" | span_id="$${__span.spanId}"'
# TLS_MATERIAL
+40
View File
@@ -0,0 +1,40 @@
auth_enabled: false
server:
http_listen_address: 127.0.0.1
http_listen_port: 13100
grpc_listen_address: 127.0.0.1
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
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- attributes: [service.name]
action: index_label
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics:
reporting_enabled: false
+21
View File
@@ -0,0 +1,21 @@
global:
scrape_interval: 2s
evaluation_interval: 2s
storage:
tsdb:
out_of_order_time_window: 30s
otlp:
promote_resource_attributes: [service.name, service.version, deployment.environment.name]
translation_strategy: UnderscoreEscapingWithSuffixes
rule_files: [/etc/prometheus/alerts.yml]
scrape_configs:
- job_name: otel-collector
scheme: https
tls_config:
ca_file: /run/lab-tls/ca.crt
cert_file: /run/lab-tls/tls.crt
key_file: /run/lab-tls/tls.key
static_configs:
- targets: [otel-collector:4318]
+24
View File
@@ -0,0 +1,24 @@
server:
http_listen_address: 127.0.0.1
http_listen_port: 13200
grpc_listen_address: 127.0.0.1
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 127.0.0.1:14318
ingester:
max_block_duration: 1m
compactor:
compaction:
block_retention: 168h
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
DB_API="$(cat /run/db-secret/db_api)" DB_WORKER="$(cat /run/db-secret/db_worker)" \
DB_DISPATCHER="$(cat /run/db-secret/db_dispatcher)" DB_JOBS="$(cat /run/db-secret/db_jobs)" \
psql -X --quiet --set ON_ERROR_STOP=1 --username messenger --dbname messenger <<'SQL'
\getenv api DB_API
\getenv dispatcher DB_DISPATCHER
\getenv worker DB_WORKER
\getenv jobs DB_JOBS
CREATE ROLE lab_api LOGIN PASSWORD :'api';
CREATE ROLE lab_dispatcher LOGIN PASSWORD :'dispatcher';
CREATE ROLE lab_worker LOGIN PASSWORD :'worker';
CREATE ROLE lab_jobs LOGIN PASSWORD :'jobs';
SQL
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
install -o postgres -g postgres -m 0600 /run/lab-tls/tls.key /tmp/postgres.key
exec docker-entrypoint.sh "$@"
+4
View File
@@ -0,0 +1,4 @@
local all messenger trust
local all all reject
hostssl messenger all 0.0.0.0/0 scram-sha-256
hostssl messenger all ::/0 scram-sha-256
+8
View File
@@ -0,0 +1,8 @@
{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]},
{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::messenger-attachments"], "Condition": {"StringLike": {"s3:prefix": ["staging/*"]}}},
{"Effect": "Allow", "Action": ["s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}
]
}
+42
View File
@@ -0,0 +1,42 @@
#!/bin/sh
set -eu
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
cp /run/lab-ca/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
login() {
mc alias set --api S3v4 local https://s3:9000 \
"$(cat /run/secrets/s3_root_user)" "$(cat /run/secrets/s3_root_password)" >/dev/null 2>&1
}
attempt=0
until login && mc ready local >/dev/null 2>&1; do
attempt=$((attempt + 1))
if [ "$attempt" -ge 20 ]; then echo 'S3 TLS readiness failed' >&2; exit 1; fi
sleep 1
done
attach_policy() {
if ! mc admin policy attach local "$1" --user "$2" >/dev/null 2>&1; then
mc admin policy entities local "$1" --user "$2" 2>/dev/null | grep -Fq "$2"
fi
}
if [ "${1:-}" = rotate-worker ]; then
# The operator supplies the new key over stdin, never as a Compose argument.
IFS= read -r user
IFS= read -r password
mc admin user add local "$user" "$password" >/dev/null 2>&1 || { echo 'Worker S3 user update failed' >&2; exit 1; }
attach_policy messenger-worker "$user" || { echo 'Worker S3 policy verification failed' >&2; exit 1; }
echo 'Worker S3 key updated'
exit 0
fi
mc mb --ignore-existing local/messenger-attachments >/dev/null
mc anonymous set none local/messenger-attachments >/dev/null
for role in api dispatcher worker; do
case "$role" in api) policy=policy;; *) policy="$role-policy";; esac
case "$role" in api) file=s3-policy.json;; *) file="s3-$policy.json";; esac
user="$(cat "/run/s3-setup/${role}_user")"
# Existing users may have been rotated. Provisioning must not reset them.
if ! mc admin user info local "$user" >/dev/null 2>&1; then
mc admin user add local "$user" "$(cat "/run/s3-setup/${role}_key")" >/dev/null 2>&1
fi
mc admin policy create local "messenger-$role" "/bootstrap/$file" >/dev/null
attach_policy "messenger-$role" "$user"
done
echo 'Private bucket and restricted service accounts ready'
+8
View File
@@ -0,0 +1,8 @@
{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["s3:GetBucketLocation", "s3:ListBucket"], "Resource": ["arn:aws:s3:::messenger-attachments"]},
{"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]},
{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/original/*", "arn:aws:s3:::messenger-attachments/thumbnail/*", "arn:aws:s3:::messenger-attachments/crop/*", "arn:aws:s3:::messenger-attachments/optimized/*"]}
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"Version": "2012-10-17",
"Statement": [
{"Effect": "Allow", "Action": ["s3:GetBucketLocation"], "Resource": ["arn:aws:s3:::messenger-attachments"]},
{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]},
{"Effect": "Allow", "Action": ["s3:PutObject", "s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/original/*", "arn:aws:s3:::messenger-attachments/thumbnail/*", "arn:aws:s3:::messenger-attachments/crop/*", "arn:aws:s3:::messenger-attachments/optimized/*"]}
]
}
+10
View File
@@ -0,0 +1,10 @@
bind 127.0.0.1
port 16379
protected-mode yes
aclfile /run/lab-acl/broker
dir /data
appendonly yes
appendfsync always
maxmemory 128mb
maxmemory-policy noeviction
save ""
+14
View File
@@ -0,0 +1,14 @@
bind 0.0.0.0
port 0
tls-port 6379
tls-cert-file /run/lab-tls/tls.crt
tls-key-file /run/lab-tls/tls.key
tls-ca-cert-file /run/lab-tls/ca.crt
tls-auth-clients no
aclfile /run/lab-acl/sessions
dir /data
appendonly yes
appendfsync always
maxmemory 128mb
maxmemory-policy noeviction
save ""