feat(observability): add bounded OTLP signals, causal jobs and SLO rules

This commit is contained in:
2026-11-20 15:41:53 +03:00
parent 470d9d6f1e
commit 8f3ff33b2d
76 changed files with 9995 additions and 33 deletions
+107
View File
@@ -0,0 +1,107 @@
// Fetch the immutable module ZIP in bounded HTTP ranges. The subsequent
// go mod download validates its h1 checksum through the Go checksum database.
package main
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sync"
"time"
)
func main() {
const version = "v0.0.0-20251015172955-9e49d5e7a648"
const total int64 = 25342606
const chunk int64 = 512 * 1024
const source = "https://proxy.golang.org/github.com/minio/minio/@v/" + version + ".zip"
directory := "/go/pkg/mod/cache/download/github.com/minio/minio/@v"
if err := os.MkdirAll(directory, 0755); err != nil {
panic(err)
}
target := filepath.Join(directory, version+".zip")
if info, err := os.Stat(target); err == nil && info.Size() == total {
fmt.Println("Source ZIP cached; Go will validate checksum")
return
}
client := &http.Client{Timeout: 90 * time.Second}
jobs := make(chan int64)
errors := make(chan error, 64)
var group sync.WaitGroup
for worker := 0; worker < 8; worker++ {
group.Add(1)
go func() {
defer group.Done()
for start := range jobs {
end := min(start+chunk, total) - 1
part := fmt.Sprintf("%s.part-%d", target, start)
if info, err := os.Stat(part); err == nil && info.Size() == end-start+1 {
continue
}
var last error
for attempt := 0; attempt < 4; attempt++ {
req, _ := http.NewRequest("GET", source, nil)
req.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", start, end))
response, err := client.Do(req)
if err != nil {
last = fmt.Errorf("source range request failed")
continue
}
expected := fmt.Sprintf("bytes %d-%d/%d", start, end, total)
if response.StatusCode != 206 || response.Header.Get("Content-Range") != expected {
response.Body.Close()
last = fmt.Errorf("unexpected source range response: HTTP %d", response.StatusCode)
continue
}
data, err := io.ReadAll(io.LimitReader(response.Body, end-start+2))
response.Body.Close()
if err != nil || int64(len(data)) != end-start+1 {
last = fmt.Errorf("incomplete source range")
continue
}
if err := os.WriteFile(part, data, 0644); err != nil {
last = err
continue
}
last = nil
fmt.Printf("Source part %d verified\n", start/chunk+1)
break
}
if last != nil {
errors <- last
}
}
}()
}
for start := int64(0); start < total; start += chunk {
jobs <- start
}
close(jobs)
group.Wait()
close(errors)
for err := range errors {
panic(err)
}
out, err := os.Create(target + ".partial")
if err != nil {
panic(err)
}
for start := int64(0); start < total; start += chunk {
part, err := os.Open(fmt.Sprintf("%s.part-%d", target, start))
if err != nil {
panic(err)
}
if _, err := io.Copy(out, part); err != nil {
panic(err)
}
part.Close()
}
if err := out.Close(); err != nil {
panic(err)
}
if err := os.Rename(target+".partial", target); err != nil {
panic(err)
}
}
+789
View File
@@ -0,0 +1,789 @@
{
"uid": "messenger-lab6",
"title": "Мессенджер: диагностика и SLO",
"schemaVersion": 41,
"version": 1,
"editable": false,
"timezone": "utc",
"refresh": "5s",
"time": {
"from": "now-30m",
"to": "now"
},
"tags": [
"lab6",
"slo"
],
"panels": [
{
"id": 1,
"title": "Запросы через балансировщик, в секунду",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(haproxy_backend_http_responses_total{proxy=\"messenger\"}[1m]))",
"refId": "A",
"legendFormat": "все бизнес-запросы",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Health requests use a separate backend and are excluded. Includes ingress 503 with no API available.",
"fieldConfig": {
"defaults": {
"unit": "reqps"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 2,
"title": "Доля ответов 5xx",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(haproxy_backend_http_responses_total{proxy=\"messenger\",code=\"5xx\"}[1m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy=\"messenger\"}[1m])),0.001)",
"refId": "A",
"legendFormat": "ошибки 5xx",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 3,
"title": "API: p50 / p95 / p99, секунды",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.5, sum by(le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"refId": "A",
"legendFormat": "p50",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.95, sum by(le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"refId": "B",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.99, sum by(le) (rate(messenger_http_duration_seconds_bucket[2m])))",
"refId": "C",
"legendFormat": "p99",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Quantiles from combined histogram buckets; complete ASGI response, no average of replica quantiles.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 4,
"title": "Очередь: ожидающие задания",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_queue_depth)",
"refId": "A",
"legendFormat": "ожидают",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Logical PostgreSQL jobs in queued state, not count of duplicate stream notifications.",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 5,
"title": "Возраст старейшего незавершённого задания",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_oldest_job_age_seconds)",
"refId": "A",
"legendFormat": "возраст",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 6,
"title": "Обработчик: занято / доступно",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(messenger_worker_busy)",
"refId": "A",
"legendFormat": "занято",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum(messenger_worker_capacity)",
"refId": "B",
"legendFormat": "всего мест",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 7,
"title": "Соединения PostgreSQL",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(service_name) (messenger_db_pool_used)",
"refId": "A",
"legendFormat": "{{service_name}} занято",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum by(service_name) (messenger_db_pool_waiting)",
"refId": "B",
"legendFormat": "{{service_name}} ожидают",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 8,
"title": "Попытки обработки по результату",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(outcome) (rate(messenger_job_attempts_total[2m]))",
"refId": "A",
"legendFormat": "{{outcome}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "ops"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 9,
"title": "Длительность попытки обработки: p95",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_job_duration_seconds_bucket[2m])))",
"refId": "A",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 10,
"title": "От приёма до ready: p50 / p95 / p99",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.5,sum by(le)(rate(messenger_time_to_ready_seconds_bucket[2m])))",
"refId": "A",
"legendFormat": "p50",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.95,sum by(le)(rate(messenger_time_to_ready_seconds_bucket[2m])))",
"refId": "B",
"legendFormat": "p95",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "histogram_quantile(0.99,sum by(le)(rate(messenger_time_to_ready_seconds_bucket[2m])))",
"refId": "C",
"legendFormat": "p99",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Only completed publications have a duration. Deadline SLI below also counts unfinished tasks.",
"fieldConfig": {
"defaults": {
"unit": "s"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 11,
"title": "SLO API за 30 минут: цель 99%",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "1 - sum(increase(haproxy_backend_http_responses_total{proxy=\"messenger\",code=\"5xx\"}[30m])) / clamp_min(sum(increase(haproxy_backend_http_responses_total{proxy=\"messenger\"}[30m])),1)",
"refId": "A",
"legendFormat": "доступность",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 12,
"title": "SLO ready за 30 минут: 99% не позже 10 секунд",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(increase(messenger_slo_decisions_total{outcome=\"good\"}[30m])) / clamp_min(sum(increase(messenger_slo_decisions_total[30m])),1)",
"refId": "A",
"legendFormat": "доля вовремя",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "Durable one-time decisions per non-obsolete logical job; unfinished jobs become bad at ten seconds. Synthetic 320x200 profile.",
"fieldConfig": {
"defaults": {
"unit": "percentunit"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 13,
"title": "CPU процессов, ядра",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum by(service_name)(rate(messenger_process_cpu_seconds_total[1m]))",
"refId": "A",
"legendFormat": "{{service_name}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 14,
"title": "Память процессов",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max by(service_name)(messenger_process_memory_bytes)",
"refId": "A",
"legendFormat": "{{service_name}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "bytes"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 15,
"title": "Буфер экспорта Collector",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "otelcol_exporter_queue_size",
"refId": "A",
"legendFormat": "{{exporter}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "otelcol_exporter_queue_capacity",
"refId": "B",
"legendFormat": "{{exporter}} capacity",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 16,
"title": "Ошибки отправки трасс и логов",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 56,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(otelcol_exporter_send_failed_spans_total[1m]))",
"refId": "A",
"legendFormat": "spans/s",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
},
{
"expr": "sum(rate(otelcol_exporter_send_failed_log_records_total[1m]))",
"refId": "B",
"legendFormat": "logs/s",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 17,
"title": "Состояния локальных alerts",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 64,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "ALERTS{alertstate=\"firing\"}",
"refId": "A",
"legendFormat": "{{alertname}}",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
}
}
],
"description": "",
"fieldConfig": {
"defaults": {
"unit": "short"
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 18,
"title": "Связанные логи API и обработчика",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 12,
"y": 64,
"w": 12,
"h": 8
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-api|messenger-worker\"}",
"queryType": "range",
"datasource": {
"type": "loki",
"uid": "loki"
}
}
],
"options": {
"showTime": true,
"wrapLogMessage": true,
"sortOrder": "Descending"
},
"description": "Filter structured metadata trace_id in Explore; open the same ID in the Traces datasource."
}
],
"annotations": {
"list": []
}
}
@@ -0,0 +1,10 @@
apiVersion: 1
providers:
- name: Messenger
orgId: 1
folder: Laboratory 6
type: file
disableDeletion: true
editable: false
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,37 @@
apiVersion: 1
datasources:
- name: Metrics
uid: prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
httpMethod: POST
timeInterval: 5s
- name: Logs
uid: loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherType: label
matcherRegex: trace_id
url: $${__value.raw}
datasourceUid: tempo
- name: Traces
uid: tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: loki
filterByTraceID: true
spanStartTimeShift: -1m
spanEndTimeShift: 1m
+50
View File
@@ -0,0 +1,50 @@
global
log stdout format raw local0
maxconn 512
stats socket /tmp/admin.sock mode 600 level admin
defaults
mode http
log global
log-format "http status=%ST duration_ms=%Ta"
timeout connect 1s
timeout client 15s
timeout server 8s
timeout http-request 10s
timeout http-keep-alive 5s
retries 0
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 1s
hold obsolete 1s
hold nx 1s
frontend public
bind :8080
use_backend health if { path_beg /health/ }
default_backend messenger
backend messenger
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fastinter 250ms fall 2 rise 1 resolvers docker init-addr libc,none resolve-prefer ipv4
server-template api 1-8 api:8080
backend health
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
http-check expect status 200
default-server check inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
server-template api 1-8 api:8080
frontend internal_metrics
bind :8404
http-request use-service prometheus-exporter if { path /metrics }
http-request deny
+50
View File
@@ -0,0 +1,50 @@
# Диагностика по сохранённой телеметрии
Открой dashboard «Мессенджер: диагностика и SLO», временная зона UTC.
Сопоставляй время оповещения с метриками, трассами и связанными логами.
## API errors
Признак: ApiHighErrorRate, ApiFastBurn или ApiSlowBurn. Числитель доступности:
`sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m]))`.
Знаменатель — тот же backend со всеми code. Health использует другой backend.
Сравни API histogram, DB pool used/waiting и worker busy. В Traces найди
ошибочный server span и вложенный db.postgresql или s3.*. Длинная DB-операция
с ошибкой и занятым пулом при нормальной очереди указывает на БД. Отсутствие
API span при ingress503 может означать отсутствие готовых API. Один5xx не
доказывает причину. Через trace_id найди соответствующий Logs record.
После исправления проверь новые сообщения, спад5xx, resolved и прежние данные.
## Queue age
Признак: QueueLagGrowing, ReadyFastBurn или ReadySlowBurn. Сравни логические
queued jobs PG, oldest job age и worker busy/capacity. Upload202 при росте
ожидающей очереди и отсутствии новых worker spans указывает на обработчик.
Если попытки идут и содержат DB/S3 ошибки, причина может быть в зависимости.
Найди путь upload→producer→consumer→S3/DB. Histogram ready содержит только
завершения, поэтому отдельно проверь deadline SLI для незавершённых jobs.
После восстановления проверь тот же attachment_id, original, спад и resolved.
## Telemetry backend
Проверь backend health, Collector queue и accepted/sent/failed счётчики.
Failed attempts не равны числу уникально потерянных spans: пакет повторяется.
После слива очередей сравни изменение accepted-minus-sent и исходное состояние.
SDK queues traces/logs512records, timeout0.75s; Collector memory limiter192MiB,
batch≤256, очереди logs/traces по32пакета, один sender и finite retry≤10s.
При отказе telemetry может теряться; измеряй память и настоящие бизнес-запросы.
После восстановления найди новую трассу и лог, а не только старый screenshot.
## SLO и окна
Учебный профиль: синтетические PNG320×200, upload не чаще одного каждые3s,
закреплённые CPU/RAM. API цель99%ответов без5xx за30m на ingress. Jobs цель99%
ready≤10s от PG created_at принимающей транзакции до committed_at публикации.
Начальная граница консервативно включает завершение принимающей транзакции.
Однократные durable good/bad решения учитывают failed и незавершённые после10s.
Ручной replay не стирает прежний bad; устаревшие до решения jobs исключены.
Burn rate = доля плохих событий/0.01. Быстрое правило: burn>14.4 в30s и2m,
непрерывно45s. Длительное: burn>6 в2m и5m, непрерывно60s. Короткие окна выбраны
для воспроизводимого стенда, а не универсальной production paging policy.
Измеряются краткий всплеск/длительная деградация/firing/resolved/ложные события.
Точность времени ограничена polling2s, scrape/evaluation5s и экспортом.
+53
View File
@@ -0,0 +1,53 @@
groups:
- name: messenger-slo
interval: 5s
rules:
- alert: ApiHighErrorRate
expr: sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[2m])),0.001) > 0.05
for: 20s
labels: {severity: warning, signal: api}
annotations:
summary: More than 5 percent business responses are 5xx
runbook: infra/otel/RUNBOOK.md#api-errors
- alert: QueueLagGrowing
expr: max(messenger_oldest_job_age_seconds) > 20 and max(messenger_queue_depth) > 0
for: 10s
labels: {severity: warning, signal: ready}
annotations:
summary: Oldest unfinished attachment exceeds 20 seconds
runbook: infra/otel/RUNBOOK.md#queue-age
- alert: ApiFastBurn
expr: (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[30s])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[30s])),0.001) / 0.01 > 14.4) and (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[2m])),0.001) / 0.01 > 14.4)
for: 45s
labels: {severity: critical, signal: api, burn: fast}
annotations:
summary: API burns the one-percent error budget in both fast windows
runbook: infra/otel/RUNBOOK.md#api-errors
- alert: ApiSlowBurn
expr: (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[2m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[2m])),0.001) / 0.01 > 6) and (sum(rate(haproxy_backend_http_responses_total{proxy="messenger",code="5xx"}[5m])) / clamp_min(sum(rate(haproxy_backend_http_responses_total{proxy="messenger"}[5m])),0.001) / 0.01 > 6)
for: 60s
labels: {severity: critical, signal: api, burn: slow}
annotations:
summary: API burns the error budget across two longer windows
runbook: infra/otel/RUNBOOK.md#api-errors
- alert: ReadyFastBurn
expr: (sum(rate(messenger_slo_decisions_total{outcome="bad"}[30s])) / clamp_min(sum(rate(messenger_slo_decisions_total[30s])),0.001) / 0.01 > 14.4) and (sum(rate(messenger_slo_decisions_total{outcome="bad"}[2m])) / clamp_min(sum(rate(messenger_slo_decisions_total[2m])),0.001) / 0.01 > 14.4)
for: 45s
labels: {severity: critical, signal: ready, burn: fast}
annotations:
summary: Attachment deadline SLO burns the error budget
runbook: infra/otel/RUNBOOK.md#queue-age
- alert: ReadySlowBurn
expr: (sum(rate(messenger_slo_decisions_total{outcome="bad"}[2m])) / clamp_min(sum(rate(messenger_slo_decisions_total[2m])),0.001) / 0.01 > 6) and (sum(rate(messenger_slo_decisions_total{outcome="bad"}[5m])) / clamp_min(sum(rate(messenger_slo_decisions_total[5m])),0.001) / 0.01 > 6)
for: 60s
labels: {severity: critical, signal: ready, burn: slow}
annotations:
summary: Sustained misses of the attachment ten-second deadline
runbook: infra/otel/RUNBOOK.md#queue-age
- alert: CollectorUnavailable
expr: up{job="collector"} == 0
for: 15s
labels: {severity: warning, signal: telemetry}
annotations:
summary: Collector self metrics are unavailable
runbook: infra/otel/RUNBOOK.md#telemetry-backend
+71
View File
@@ -0,0 +1,71 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 192
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 128
send_batch_max_size: 256
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
metric_expiration: 5m
otlp_http/tempo:
endpoint: http://tempo:4318
timeout: 2s
sending_queue:
queue_size: 32
num_consumers: 1
block_on_overflow: false
retry_on_failure:
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 10s
otlp_http/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue:
queue_size: 32
num_consumers: 1
block_on_overflow: false
retry_on_failure:
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 10s
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
telemetry:
logs:
level: warn
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/tempo]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlp_http/loki]
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
+38
View File
@@ -0,0 +1,38 @@
auth_enabled: false
server:
http_listen_port: 3100
log_level: warn
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: 2026-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
ingestion_rate_mb: 4
ingestion_burst_size_mb: 8
volume_enabled: true
otlp_config:
resource_attributes:
ignore_defaults: true
attributes_config:
- action: index_label
attributes: [service.name]
- action: structured_metadata
attributes: [service.instance.id, service.version, deployment.environment.name]
analytics:
reporting_enabled: false
+23
View File
@@ -0,0 +1,23 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files: [/etc/prometheus/alerts.yaml]
scrape_configs:
- job_name: application_otlp
static_configs:
- targets: [otel:8889]
- job_name: collector
static_configs:
- targets: [otel:8888]
- job_name: ingress
static_configs:
- targets: [lb:8404]
- job_name: prometheus
static_configs:
- targets: [localhost:9090]
- job_name: tempo
static_configs:
- targets: [tempo:3200]
- job_name: loki
static_configs:
- targets: [loki:3100]
+20
View File
@@ -0,0 +1,20 @@
target: all
stream_over_http_enabled: true
server:
http_listen_port: 3200
log_level: warn
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
storage:
trace:
backend: local
wal:
path: /var/tempo/wal
local:
path: /var/tempo/blocks
usage_report:
reporting_enabled: false
+7
View File
@@ -0,0 +1,7 @@
{
"otel": "otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
"prometheus": "prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
"loki": "grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
"tempo": "grafana/tempo:3.1.1@sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
"grafana": "grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf"
}
+14
View File
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
root_user=$(cat /run/secrets/s3_root_user)
root_password=$(cat /run/secrets/s3_root_password)
api_key=$(cat /run/secrets/s3_access_key)
api_secret=$(cat /run/secrets/s3_secret_key)
# Credentials are passed only inside this isolated bootstrap container.
mc alias set local http://s3:9000 "$root_user" "$root_password" >/dev/null 2>&1
mc mb --ignore-existing local/messenger >/dev/null 2>&1
mc anonymous set none local/messenger >/dev/null 2>&1
mc admin user add local "$api_key" "$api_secret" >/dev/null 2>&1
mc admin policy create local messenger-api /policy.json >/dev/null 2>&1
mc admin policy attach local messenger-api --user "$api_key" >/dev/null 2>&1
printf '%s\n' 'Private bucket and scoped application policy ready'
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat /run/secrets/s3_root_user)"
export MINIO_ROOT_PASSWORD="$(cat /run/secrets/s3_root_password)"
export MINIO_BROWSER_REDIRECT_URL=http://127.0.0.1:9001
exec minio server /data --address :9000 --console-address 127.0.0.1:9001
+15
View File
@@ -0,0 +1,15 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
"Resource": ["arn:aws:s3:::messenger"]
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::messenger/objects/*"]
}
]
}
+49
View File
@@ -0,0 +1,49 @@
FROM golang:1.24.8-bookworm@sha256:4ed690d6649d63c312b99a6120025ec79ce3b542968a37da53d6236c7c61a848 AS toolchain
ENV CGO_ENABLED=0 GOMAXPROCS=2 GOFLAGS=-p=2 GOTOOLCHAIN=local
FROM toolchain AS minio-build
WORKDIR /source
COPY infra/fetch-source.go /tmp/fetch-source.go
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
go run /tmp/fetch-source.go && \
for attempt in 1 2 3 4; do \
go mod download -json github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648 && break; \
test "$attempt" -lt 4 || exit 1; sleep 1; \
done && \
cp -a /go/pkg/mod/github.com/minio/minio@v0.0.0-20251015172955-9e49d5e7a648/. /source/
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
for attempt in 1 2 3; do \
timeout 900s go build -trimpath -ldflags='-s -w -X github.com/minio/minio/cmd.Version=2025-10-15T17:29:55Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-10-15T17-29-55Z -X github.com/minio/minio/cmd.CommitID=9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a' -o /out/minio . && break; \
test "$attempt" -lt 3 || exit 1; sleep 1; \
done
FROM toolchain AS mc-build
WORKDIR /source
RUN git init . && git remote add origin https://github.com/minio/mc.git && \
git fetch --depth 1 origin 7394ce0dd2a80935aded936b09fa12cbb3cb8096 && git checkout --detach FETCH_HEAD
RUN --mount=type=cache,target=/go/pkg/mod,sharing=locked \
--mount=type=cache,target=/root/.cache/go-build,sharing=locked \
go build -trimpath -ldflags='-s -w' -o /out/mc .
FROM python:3.14.7-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS server
LABEL org.opencontainers.image.revision=9e49d5e7a648f00e26f2246f4dc28e6b07f8c84a org.opencontainers.image.version=RELEASE.2025-10-15T17-29-55Z
COPY --from=minio-build /out/minio /usr/local/bin/minio
COPY --from=minio-build /source/LICENSE /licenses/minio.LICENSE
COPY --chmod=755 infra/s3-entrypoint.sh /usr/local/bin/s3-entrypoint
RUN mkdir /data && chown 10001:10001 /data
USER 10001:10001
ENTRYPOINT ["/usr/local/bin/s3-entrypoint"]
EXPOSE 9000
HEALTHCHECK --interval=2s --timeout=2s --start-period=10s --retries=30 CMD ["python","-c","import urllib.request; urllib.request.urlopen('http://127.0.0.1:9000/minio/health/ready',timeout=1).read()"]
FROM python:3.14.7-slim-trixie@sha256:51dafde81dbdb6ebde285137a295cf18a47ca95234fe388a343719cb97305b3d AS bootstrap
LABEL org.opencontainers.image.revision=7394ce0dd2a80935aded936b09fa12cbb3cb8096 org.opencontainers.image.version=RELEASE.2025-08-13T08-35-41Z
COPY --from=mc-build /out/mc /usr/local/bin/mc
COPY --from=mc-build /source/LICENSE /licenses/mc.LICENSE
COPY --chmod=755 infra/s3-bootstrap.sh /usr/local/bin/s3-bootstrap
COPY infra/s3-policy.json /policy.json
USER 10001:10001
ENV MC_CONFIG_DIR=/tmp/mc
ENTRYPOINT ["/usr/local/bin/s3-bootstrap"]