Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
# Dashboards from JSON files in Git (infra/grafana/dashboards, mounted read-only). Editing in the
|
||||
# UI is possible but not saved: the files are the source of truth (scripts/build_dashboard.py
|
||||
# generates messenger.json).
|
||||
apiVersion: 1
|
||||
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: Messenger
|
||||
type: file
|
||||
disableDeletion: true
|
||||
allowUiUpdates: false
|
||||
updateIntervalSeconds: 30
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
foldersFromFilesStructure: false
|
||||
@@ -0,0 +1,73 @@
|
||||
# Grafana datasources, provisioned at start (nothing is clicked by hand). The UIDs are FIXED:
|
||||
# the dashboard JSON, the trace->logs and logs->trace links refer to exactly these UIDs
|
||||
# (prometheus / loki / tempo). A datasource without a fixed uid gets a random one and every
|
||||
# reference to it breaks ("data source not found").
|
||||
apiVersion: 1
|
||||
|
||||
deleteDatasources:
|
||||
- {name: Prometheus, orgId: 1}
|
||||
- {name: Loki, orgId: 1}
|
||||
- {name: Tempo, orgId: 1}
|
||||
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
httpMethod: POST
|
||||
timeInterval: 15s # = scrape/evaluation interval: $__rate_interval >= 4 x 15 s
|
||||
prometheusType: Prometheus
|
||||
prometheusVersion: 3.16.0
|
||||
manageAlerts: true # show the Prometheus alert rules in Grafana's alert list
|
||||
exemplarTraceIdDestinations: []
|
||||
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
maxLines: 1000
|
||||
# log line -> its trace in Tempo (trace_id is structured metadata of the OTLP record)
|
||||
derivedFields:
|
||||
- name: trace_id
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: "$${__value.raw}"
|
||||
urlDisplayLabel: "Trace in Tempo"
|
||||
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
# span -> the log records of the same trace (and service) in Loki
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: "-5m"
|
||||
spanEndTimeShift: "5m"
|
||||
customQuery: true
|
||||
query: '{service_name="$${__span.tags["service.name"]}"} | trace_id="$${__trace.traceId}"'
|
||||
tracesToMetrics:
|
||||
datasourceUid: prometheus
|
||||
spanStartTimeShift: "-5m"
|
||||
spanEndTimeShift: "5m"
|
||||
tags:
|
||||
- {key: service.name, value: job}
|
||||
queries:
|
||||
- name: HTTP p95 of this service
|
||||
query: 'histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{$$__tags}[1m])))'
|
||||
search:
|
||||
hide: false
|
||||
nodeGraph:
|
||||
enabled: false
|
||||
lokiSearch:
|
||||
datasourceUid: loki
|
||||
@@ -0,0 +1,116 @@
|
||||
# HAProxy 3.2 LTS — the single public entry point of the lab 4 stand (compose service `lb`).
|
||||
#
|
||||
# Backend discovery: Docker DNS name `api` returns one A record per RUNNING replica of the
|
||||
# compose service `api` (deploy.replicas / --scale). server-template keeps 8 slots and
|
||||
# re-resolves every second, so scale up/down, a restarted container with a new IP and a
|
||||
# full stack restart are picked up without restarting the LB. A stopped container drops
|
||||
# out of DNS and its slot goes to MAINT.
|
||||
#
|
||||
# Readiness: an ACTIVE check `GET /health/ready` (PostgreSQL + Valkey + S3 reachable, not
|
||||
# draining) every 1 s; 2 failures -> DOWN, 2 successes -> UP. Passive errors do not decide
|
||||
# anything on their own, and there are NO fallback servers without checks: a replica that
|
||||
# answers /health/live but not /health/ready never gets traffic while a fully ready one exists.
|
||||
#
|
||||
# Degraded mode (lab 4): S3 is a SHARED dependency. If it is down, /health/ready is 503 on
|
||||
# every replica and backend `api` has no server. Instead of answering 503 to everything, the
|
||||
# frontend then switches to backend `api_core`: the same replicas, checked by
|
||||
# /health/ready/core (PostgreSQL + Valkey, not draining). Chats and text messages keep working,
|
||||
# every attachment request is answered 503 by the API itself (fast, S3_TIMEOUT_SECONDS).
|
||||
# A replica that alone lost S3 (e.g. its storage network) is DOWN in `api` while the others are
|
||||
# UP, so it gets no traffic at all.
|
||||
# Worst case detection of a failed replica (a check answered at once counts at once, a check
|
||||
# that hangs counts only after `timeout check`):
|
||||
# fast explicit 503 (drain after SIGTERM): inter 1 s + fastinter 0.5 s ~= 1.5 s;
|
||||
# slow ready (PostgreSQL/Valkey unreachable: the answer takes ~1 s = timeout check)
|
||||
# or frozen process: inter 1 s + 1 s + fastinter 0.5 s + 1 s ~= 3.5 s.
|
||||
# Requests that could not even be SENT (connection refused/reset before the request)
|
||||
# are retried on another replica (retry-on conn-failure + redispatch) - safe for POST,
|
||||
# because the API has not seen them. Nothing that may have reached the API is retried by
|
||||
# the LB: an uncertain POST is retried by the CLIENT with the same Idempotency-Key.
|
||||
# No sticky sessions: sessions live in Valkey, every replica serves every user.
|
||||
|
||||
global
|
||||
log stdout format raw local0 info
|
||||
maxconn 4096
|
||||
# Runtime API for `show servers state` / `show stat` (scripts and tests, no network port).
|
||||
stats socket /var/lib/haproxy/admin.sock mode 600 level admin
|
||||
hard-stop-after 15s
|
||||
|
||||
resolvers docker
|
||||
nameserver dns1 127.0.0.11:53
|
||||
accepted_payload_size 8192
|
||||
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
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
option http-keep-alive
|
||||
timeout connect 1s
|
||||
timeout client 30s
|
||||
timeout server 10s # > DB_TIMEOUT_SECONDS (3 s): the API answers 503 itself first
|
||||
timeout http-request 10s
|
||||
timeout http-keep-alive 10s
|
||||
timeout queue 3s
|
||||
timeout check 1s
|
||||
retries 2
|
||||
retry-on conn-failure
|
||||
option redispatch 1
|
||||
# Errors generated by the LB itself, in the contract error format with the same request id.
|
||||
# They carry no X-Instance-Id: no API replica produced them. 502/504 = the outcome of the
|
||||
# request is unknown (a replica died mid-request / did not answer in time): retry with the
|
||||
# same Idempotency-Key. 503 = no ready replica at all.
|
||||
http-error status 502 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика оборвала ответ; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]"
|
||||
http-error status 503 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"Нет готовых API-реплик\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]"
|
||||
http-error status 504 content-type application/json lf-string "{\"error\":{\"code\":\"unavailable\",\"message\":\"API-реплика не ответила вовремя; повторите с тем же Idempotency-Key\",\"request_id\":\"%[var(txn.request_id)]\"}}" hdr X-Request-Id "%[var(txn.request_id)]"
|
||||
|
||||
frontend public
|
||||
bind :8080
|
||||
# One request id end to end: keep a valid client X-Request-Id, otherwise create one; the
|
||||
# API echoes it, and errors generated by the LB itself carry the same value.
|
||||
http-request set-header X-Request-Id %[uuid()] unless { req.hdr(x-request-id) -m reg ^[A-Za-z0-9._:-]{1,128}$ }
|
||||
http-request set-var(txn.request_id) req.hdr(x-request-id)
|
||||
log-format "%ci:%cp [%tr] %ft %b/%s %TR/%Tw/%Tc/%Tr/%Ta %ST %B %tsc %ac/%fc/%bc/%sc/%rc %sq/%bq rid=%[var(txn.request_id)] \"%HM %HPO\""
|
||||
use_backend api if { nbsrv(api) gt 0 }
|
||||
default_backend api_core
|
||||
|
||||
backend api
|
||||
balance roundrobin
|
||||
# Uploads (<= 10 MiB body + verification + S3 PUT): the API's own budget is
|
||||
# UPLOAD_READ_TIMEOUT 30 s + IMAGE_VERIFY 10 s + S3; the LB must not cut it at 10 s (a 504
|
||||
# after a successful upload would make the client upload a duplicate).
|
||||
acl is_upload path_reg ^/api/v1/chats/[^/]+/attachments$
|
||||
http-request set-timeout server 60s if is_upload METH_POST
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
|
||||
http-check expect status 200
|
||||
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200
|
||||
server-template api 8 api:8080
|
||||
|
||||
# Degraded mode only (see the header): used when NO replica is fully ready.
|
||||
backend api_core
|
||||
balance roundrobin
|
||||
acl is_upload path_reg ^/api/v1/chats/[^/]+/attachments$
|
||||
http-request set-timeout server 60s if is_upload METH_POST
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready/core ver HTTP/1.1 hdr Host api
|
||||
http-check expect status 200
|
||||
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 2 check resolvers docker init-addr none resolve-prefer ipv4 maxconn 200
|
||||
server-template core 8 api:8080
|
||||
|
||||
# Local-only status page (127.0.0.1:8404 on the host): which replica is UP/DOWN right now.
|
||||
frontend stats
|
||||
bind :8404
|
||||
stats enable
|
||||
stats uri /
|
||||
stats refresh 2s
|
||||
stats show-legends
|
||||
@@ -0,0 +1,60 @@
|
||||
# Loki 3.7 (grafana/loki:3.7.10), single binary, lab 6: the LOGS store.
|
||||
#
|
||||
# Logs arrive from the Collector over OTLP (POST /otlp/v1/logs). Loki turns a few RESOURCE
|
||||
# attributes into index labels (service_name, service_instance_id, deployment_environment_name):
|
||||
# few values, small index. Log-record attributes (event, request_id, job_id, trace_id, span_id,
|
||||
# route, status...) are stored as STRUCTURED METADATA next to the line - searchable
|
||||
# (`{service_name="messenger-api"} | trace_id="..."`) without creating a stream per value.
|
||||
# That is why an id such as request_id/attachment_id never becomes a label (it would create a
|
||||
# new stream - and index entries - per request, see docs/DEFENSE.md).
|
||||
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: 2026-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 168h # 7 days of logs, deleted by the compactor
|
||||
ingestion_rate_mb: 8
|
||||
ingestion_burst_size_mb: 16
|
||||
max_query_lookback: 168h
|
||||
volume_enabled: true
|
||||
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
|
||||
ingester:
|
||||
wal:
|
||||
dir: /loki/wal # on the named volume: a restart does not lose buffered logs
|
||||
|
||||
pattern_ingester:
|
||||
enabled: false
|
||||
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,93 @@
|
||||
# OpenTelemetry Collector (otel/opentelemetry-collector-contrib 0.165.0), lab 6.
|
||||
#
|
||||
# API x2 / relay / worker --OTLP/HTTP protobuf :4318--> [receiver otlp]
|
||||
# -> memory_limiter -> batch -> exporters:
|
||||
# traces -> Tempo (otlp_http/tempo, http://tempo:4318/v1/traces)
|
||||
# metrics -> Prometheus (otlp_http/prometheus, http://prometheus:9090/api/v1/otlp/v1/metrics)
|
||||
# logs -> Loki (otlp_http/loki, http://loki:3100/otlp/v1/logs)
|
||||
#
|
||||
# The Collector stores nothing for long: it receives, limits, batches and forwards. When a backend
|
||||
# is down, each exporter keeps a BOUNDED queue (sending_queue) and retries for at most
|
||||
# max_elapsed_time; then the data is dropped and counted (otelcol_exporter_send_failed_*,
|
||||
# otelcol_exporter_enqueue_failed_*). memory_limiter refuses new data above its limit (the SDKs
|
||||
# get a retryable error and drop after their own bounded queue) instead of growing until OOM.
|
||||
# Its own metrics: Prometheus scrapes :8888 (otelcol_*). Only on the internal `telemetry` network.
|
||||
#
|
||||
# Traces pipeline variants (track 1, docs/TRACK1.md): this file keeps EVERY span; the overlay
|
||||
# traces-tail.yaml (passed as a second --config, compose OTEL_COLLECTOR_TRACES) adds tail sampling.
|
||||
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
max_request_body_size: 8388608 # 8 MiB per export request
|
||||
|
||||
processors:
|
||||
# First in every pipeline. Container limit 512 MiB: soft limit = 400 - 80 = 320 MiB (start
|
||||
# refusing + GC), hard limit 400 MiB (forced GC). The contrib binary alone is ~150 MiB RSS;
|
||||
# 256 MiB of container memory left the limiter refusing data at idle. GOMEMLIMIT = 360 MiB.
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 400
|
||||
spike_limit_mib: 80
|
||||
# Fewer, larger requests to the backends; at most 2 s of delay.
|
||||
batch:
|
||||
send_batch_size: 1024
|
||||
send_batch_max_size: 2048
|
||||
timeout: 2s
|
||||
|
||||
exporters:
|
||||
otlp_http/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
timeout: 5s
|
||||
sending_queue: &queue
|
||||
enabled: true
|
||||
num_consumers: 2
|
||||
queue_size: 100 # batches (<= 2048 items each): bounded, in memory only
|
||||
retry_on_failure: &retry
|
||||
enabled: true
|
||||
initial_interval: 1s
|
||||
max_interval: 10s
|
||||
max_elapsed_time: 60s # then the batch is dropped (counted), never retried forever
|
||||
otlp_http/prometheus:
|
||||
endpoint: http://prometheus:9090/api/v1/otlp
|
||||
timeout: 5s
|
||||
sending_queue: *queue
|
||||
retry_on_failure: *retry
|
||||
otlp_http/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 5s
|
||||
sending_queue: *queue
|
||||
retry_on_failure: *retry
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
telemetry:
|
||||
logs:
|
||||
level: warn
|
||||
metrics:
|
||||
level: normal
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
pipelines:
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_http/tempo]
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_http/prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_http/loki]
|
||||
@@ -0,0 +1,6 @@
|
||||
# Overlay for collector.yaml: keep every received span (no tail sampling). Selected by
|
||||
# OTEL_COLLECTOR_TRACES=traces-all (compose). Lists are replaced, maps are merged by the Collector.
|
||||
service:
|
||||
pipelines:
|
||||
traces:
|
||||
processors: [memory_limiter, batch]
|
||||
@@ -0,0 +1,39 @@
|
||||
# Overlay for collector.yaml: TAIL sampling of traces (track 1 "balanced" configuration,
|
||||
# docs/TRACK1.md). The decision is taken per trace after decision_wait, when its spans are in:
|
||||
# keep ALL traces with an error span (status ERROR: HTTP 5xx, failed/retried job, S3/DB error),
|
||||
# keep ALL slow traces (root to last span >= 250 ms),
|
||||
# keep 10 % of the rest (probabilistic, by trace id: the same trace -> the same decision).
|
||||
# Head sampling in the SDK (OTEL_TRACES_SAMPLER_ARG) decides at the first span and cannot know
|
||||
# whether the request will fail or be slow; tail sampling can, at the price of buffering spans
|
||||
# in the Collector (num_traces x spans) for decision_wait.
|
||||
#
|
||||
# A job is processed seconds after its upload: those spans may arrive after the upload trace was
|
||||
# decided. decision_cache remembers the decision per trace id, so late spans of a kept trace are
|
||||
# kept, and late spans of a dropped one are dropped (unless they are errors/slow by themselves:
|
||||
# then they form a partial trace - a documented limit of the approach).
|
||||
processors:
|
||||
tail_sampling:
|
||||
decision_wait: 5s
|
||||
num_traces: 20000
|
||||
expected_new_traces_per_sec: 200
|
||||
decision_cache:
|
||||
sampled_cache_size: 100000
|
||||
non_sampled_cache_size: 100000
|
||||
policies:
|
||||
- name: errors
|
||||
type: status_code
|
||||
status_code:
|
||||
status_codes: [ERROR]
|
||||
- name: slow
|
||||
type: latency
|
||||
latency:
|
||||
threshold_ms: 250
|
||||
- name: baseline
|
||||
type: probabilistic
|
||||
probabilistic:
|
||||
sampling_percentage: 10
|
||||
|
||||
service:
|
||||
pipelines:
|
||||
traces:
|
||||
processors: [memory_limiter, tail_sampling, batch]
|
||||
@@ -0,0 +1,36 @@
|
||||
# Prometheus 3.16 (prom/prometheus:v3.16.0), lab 6: the METRICS store.
|
||||
#
|
||||
# Application metrics are PUSHED by the Collector over OTLP (flag --web.enable-otlp-receiver,
|
||||
# endpoint /api/v1/otlp/v1/metrics). Prometheus derives `job` = service.name and
|
||||
# `instance` = service.instance.id from the OTLP resource, and translates the OTel names with
|
||||
# suffixes: http.server.request.duration (unit s) -> http_server_request_duration_seconds_bucket,
|
||||
# messenger.jobs.processed -> messenger_jobs_processed_total (mapping: docs/OBSERVABILITY.md).
|
||||
# The telemetry components themselves are SCRAPED (pull) below.
|
||||
global:
|
||||
scrape_interval: 15s
|
||||
evaluation_interval: 15s # alert rules: detection delay = condition + `for` + <= 15 s
|
||||
|
||||
otlp:
|
||||
# deployment.environment.name=lab as a label on every series (low cardinality, one value).
|
||||
promote_resource_attributes: [deployment.environment.name, service.version]
|
||||
keep_identifying_resource_attributes: true
|
||||
|
||||
storage:
|
||||
tsdb:
|
||||
# OTLP pushes from several processes arrive slightly out of order; accept 10 min of it.
|
||||
out_of_order_time_window: 10m
|
||||
|
||||
rule_files:
|
||||
- /etc/prometheus/rules/*.yml
|
||||
|
||||
scrape_configs:
|
||||
- job_name: otel-collector # otelcol_* : accepted/refused/sent/failed, queue size, RSS
|
||||
static_configs: [{targets: ["otel-collector:8888"]}]
|
||||
- job_name: prometheus
|
||||
static_configs: [{targets: ["localhost:9090"]}]
|
||||
- job_name: loki
|
||||
static_configs: [{targets: ["loki:3100"]}]
|
||||
- job_name: tempo
|
||||
static_configs: [{targets: ["tempo:3200"]}]
|
||||
- job_name: grafana
|
||||
static_configs: [{targets: ["grafana:3000"]}]
|
||||
@@ -0,0 +1,90 @@
|
||||
# Alert rules (evaluated by Prometheus every 15 s; state pending -> firing -> resolved is visible
|
||||
# in Prometheus /api/v1/alerts, the ALERTS series and the Grafana dashboard "Alerts" panel).
|
||||
# No delivery outside (no Alertmanager): the task asks for the local firing/resolved state only.
|
||||
# Runbook of every alert: docs/RUNBOOK.md#<alert name>.
|
||||
groups:
|
||||
- name: messenger-alerts
|
||||
rules:
|
||||
- alert: MessengerApiHighErrorRate
|
||||
# 5xx share of business requests over 1 min, summed over all API replicas. The traffic
|
||||
# guard (> 0.2 req/s) keeps a single failed request on an idle stand from paging.
|
||||
expr: messenger:http_error_ratio:rate1m > 0.05 and messenger:http_requests:rate1m > 0.2
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
slo: api-availability
|
||||
annotations:
|
||||
summary: "API: {{ $value | humanizePercentage }} of business requests answer 5xx"
|
||||
description: >-
|
||||
More than 5 % of non-health API requests failed with 5xx for over a minute (SLO: 99 %
|
||||
non-5xx over 1 h). Typical causes: PostgreSQL/Valkey/S3 unavailable or too slow (503),
|
||||
pool exhausted, crash (500).
|
||||
runbook: docs/RUNBOOK.md#messengerapihigherrorrate
|
||||
|
||||
- alert: MessengerQueueLagGrowing
|
||||
# Oldest unfinished job older than 60 s while jobs are waiting: nobody processes the queue
|
||||
# (worker stopped/stuck, broker unreachable) or processing is far slower than arrivals.
|
||||
# Measured in PostgreSQL by the relay: retries and unpublished jobs count too.
|
||||
expr: max(messenger_queue_oldest_age_seconds) > 60 and max(messenger_queue_depth{state="queued"}) > 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: page
|
||||
slo: time-to-ready
|
||||
annotations:
|
||||
summary: "Queue: the oldest job waits {{ $value | humanizeDuration }}"
|
||||
description: >-
|
||||
Accepted uploads are not becoming ready. Check messenger_worker_busy / capacity, the
|
||||
worker container, messenger_outbox_oldest_age_seconds (broker) and job outcomes.
|
||||
runbook: docs/RUNBOOK.md#messengerqueuelaggrowing
|
||||
|
||||
- alert: MessengerApiLatencyHigh
|
||||
# p99 of business requests over 2 min, from the buckets of all replicas.
|
||||
expr: messenger:http_latency:p99_2m > 1
|
||||
for: 2m
|
||||
labels:
|
||||
severity: ticket
|
||||
slo: api-latency
|
||||
annotations:
|
||||
summary: "API p99 = {{ $value | humanizeDuration }} (> 1 s)"
|
||||
description: >-
|
||||
Slow API. Compare db.client.operation.duration and the DB pool (pending requests) with
|
||||
the HTTP duration: slow database vs slow handler code (docs/RUNBOOK.md).
|
||||
runbook: docs/RUNBOOK.md#messengerapilatencyhigh
|
||||
|
||||
- alert: MessengerDbPoolSaturated
|
||||
# Requests waiting for a database connection in any process, for 1 min.
|
||||
expr: max by (job) (db_client_connection_pending_requests) > 0
|
||||
for: 1m
|
||||
labels:
|
||||
severity: ticket
|
||||
annotations:
|
||||
summary: "{{ $labels.job }}: requests wait for a PostgreSQL connection"
|
||||
description: The pool is exhausted - queries hold connections too long (slow DB, locks) or the pool is too small.
|
||||
runbook: docs/RUNBOOK.md#messengerdbpoolsaturated
|
||||
|
||||
- alert: MessengerQueueMetricsAbsent
|
||||
# The relay reports the backlog from PostgreSQL every 5 s; no value for 2 min means the
|
||||
# relay is down or cannot read the database - the queue is then NOT observed at all.
|
||||
expr: absent(messenger_queue_oldest_age_seconds)
|
||||
for: 2m
|
||||
labels:
|
||||
severity: ticket
|
||||
annotations:
|
||||
summary: "No queue metrics (relay down or database unreachable)"
|
||||
runbook: docs/RUNBOOK.md#messengerqueuemetricsabsent
|
||||
|
||||
- alert: TelemetryExportFailing
|
||||
# The Collector cannot deliver to a backend (Tempo/Loki/Prometheus down): data is buffered
|
||||
# in its bounded queue and then dropped. The application itself is not affected.
|
||||
expr: |
|
||||
sum by (exporter) (
|
||||
rate(otelcol_exporter_send_failed_spans[2m])
|
||||
or rate(otelcol_exporter_send_failed_log_records[2m])
|
||||
or rate(otelcol_exporter_send_failed_metric_points[2m])
|
||||
) > 0
|
||||
for: 30s
|
||||
labels:
|
||||
severity: ticket
|
||||
annotations:
|
||||
summary: "Collector exporter {{ $labels.exporter }} fails to send"
|
||||
runbook: docs/RUNBOOK.md#telemetryexportfailing
|
||||
@@ -0,0 +1,38 @@
|
||||
# Recording rules: SLIs of docs/SLO.md (lab windows). All ratios are computed from COUNTERS and
|
||||
# histogram BUCKETS summed over every replica first, then divided - never an average of
|
||||
# per-replica ratios or percentiles.
|
||||
#
|
||||
# Business requests = every API request except /health/* (load-balancer/Docker probes).
|
||||
# "Bad" for availability = HTTP 5xx only: 4xx (wrong password, 404 of an outsider, 409) is a
|
||||
# correct answer to a wrong request, not a failure of the service.
|
||||
groups:
|
||||
- name: messenger-sli
|
||||
interval: 15s
|
||||
rules:
|
||||
- record: messenger:http_requests:rate1m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[1m]))
|
||||
- record: messenger:http_errors5xx:rate1m
|
||||
expr: sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[1m])) or vector(0)
|
||||
- record: messenger:http_error_ratio:rate1m
|
||||
expr: messenger:http_errors5xx:rate1m / messenger:http_requests:rate1m
|
||||
- record: messenger:http_error_ratio:rate5m
|
||||
expr: |
|
||||
(sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[5m])) or vector(0))
|
||||
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[5m]))
|
||||
- record: messenger:http_error_ratio:rate1h
|
||||
expr: |
|
||||
(sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*", http_response_status_class="5xx"}[1h])) or vector(0))
|
||||
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[1h]))
|
||||
# Latency SLI: share of business requests answered within 250 ms (bucket le="0.25").
|
||||
- record: messenger:http_fast_ratio:rate5m
|
||||
expr: |
|
||||
sum(rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*", le="0.25"}[5m]))
|
||||
/ sum(rate(http_server_request_duration_seconds_count{job="messenger-api", http_route!~"/health/.*"}[5m]))
|
||||
# p50/p95/p99 over ALL replicas: buckets summed by le, then histogram_quantile.
|
||||
- record: messenger:http_latency:p99_2m
|
||||
expr: histogram_quantile(0.99, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="messenger-api", http_route!~"/health/.*"}[2m])))
|
||||
# Time-to-ready SLI: share of uploads ready within 30 s (bucket le="30").
|
||||
- record: messenger:ready_within_30s_ratio:rate1h
|
||||
expr: |
|
||||
sum(rate(messenger_attachment_time_to_ready_seconds_bucket{le="30"}[1h]))
|
||||
/ sum(rate(messenger_attachment_time_to_ready_seconds_count[1h]))
|
||||
@@ -0,0 +1 @@
|
||||
[].
|
||||
@@ -0,0 +1,24 @@
|
||||
# RabbitMQ 4.3 of the lab 5 stand (compose service `broker`), mounted as conf.d/20-lab5.conf.
|
||||
# Only AMQP 0-9-1 on 5672 inside the internal network `queue`: no management UI, no Prometheus
|
||||
# listener (enabled_plugins is empty), nothing published on the host.
|
||||
listeners.tcp.default = 5672
|
||||
|
||||
# Users, permissions and topology are imported from files at every boot (idempotent):
|
||||
# /etc/rabbitmq/definitions.d/topology.json exchanges, quorum queues, bindings (this repo)
|
||||
# /etc/rabbitmq/definitions.d/users.json users relay/worker + permissions (Docker secret,
|
||||
# generated by scripts/init_secrets.py)
|
||||
# With imported definitions no default `guest` user is created.
|
||||
definitions.import_backend = local_filesystem
|
||||
definitions.local.path = /etc/rabbitmq/definitions.d
|
||||
definitions.skip_if_unchanged = false
|
||||
|
||||
# A delivery that stays unacked longer than this closes the consumer's channel and the message
|
||||
# is returned to the queue (a worker that hangs while connected). Far above JOB_TIMEOUT_SECONDS.
|
||||
consumer_timeout = 300000
|
||||
|
||||
# The container has a 512 MiB limit; flow control starts well before the cgroup OOM.
|
||||
vm_memory_high_watermark.relative = 0.5
|
||||
disk_free_limit.absolute = 200MB
|
||||
|
||||
log.console = true
|
||||
log.console.level = info
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"vhosts": [{"name": "/"}],
|
||||
"exchanges": [
|
||||
{"name": "messenger.jobs", "vhost": "/", "type": "direct", "durable": true, "auto_delete": false,
|
||||
"internal": false, "arguments": {}},
|
||||
{"name": "messenger.jobs.dlx", "vhost": "/", "type": "fanout", "durable": true, "auto_delete": false,
|
||||
"internal": false, "arguments": {}}
|
||||
],
|
||||
"queues": [
|
||||
{"name": "messenger.attachment-jobs", "vhost": "/", "durable": true, "auto_delete": false,
|
||||
"arguments": {"x-queue-type": "quorum", "x-delivery-limit": 20, "x-dead-letter-exchange": "messenger.jobs.dlx"}},
|
||||
{"name": "messenger.attachment-jobs.dlq", "vhost": "/", "durable": true, "auto_delete": false,
|
||||
"arguments": {"x-queue-type": "quorum"}}
|
||||
],
|
||||
"bindings": [
|
||||
{"source": "messenger.jobs", "vhost": "/", "destination": "messenger.attachment-jobs", "destination_type": "queue",
|
||||
"routing_key": "attachment.process.v1", "arguments": {}},
|
||||
{"source": "messenger.jobs.dlx", "vhost": "/", "destination": "messenger.attachment-jobs.dlq",
|
||||
"destination_type": "queue", "routing_key": "", "arguments": {}}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
#!/bin/sh
|
||||
# Entry point of the compose service `s3` (SeaweedFS 4.46, one container: master + volume +
|
||||
# filer + S3 gateway). Renders the S3 identities from Docker secrets, then execs `weed`.
|
||||
#
|
||||
# Two private buckets (lab 5): S3_STAGING_BUCKET holds originals accepted by the API before 202,
|
||||
# S3_BUCKET holds the published originals and variants written by the worker.
|
||||
# Identities (SeaweedFS s3.json, actions scoped to a bucket):
|
||||
# bootstrap-admin Admin (create buckets) -> only s3-init has these keys
|
||||
# messenger-api Write staging, Read final -> API replicas (no List, no Admin)
|
||||
# messenger-worker Read + Write staging, Read + Write final -> worker (no List, no Admin)
|
||||
# messenger-auditor Read + List both buckets (no Write) -> invariant checker (tools profile)
|
||||
# There is NO anonymous identity, so every unsigned request is refused: the buckets are private.
|
||||
#
|
||||
# Exposure: master (9333), volume (8080), filer (8888) with their web UIs and gRPC listen on
|
||||
# 127.0.0.1 INSIDE the container only (-ip.bind); only the S3 API port 8333 listens on the
|
||||
# container network `storage` (internal, not published on the host). Telemetry is off.
|
||||
set -eu
|
||||
umask 077
|
||||
secret() { tr -d '\r\n' < "/run/secrets/$1"; }
|
||||
bucket="${S3_BUCKET:?S3_BUCKET is required}"
|
||||
staging="${S3_STAGING_BUCKET:?S3_STAGING_BUCKET is required}"
|
||||
cat > /tmp/s3.json <<EOF
|
||||
{
|
||||
"identities": [
|
||||
{"name": "bootstrap-admin",
|
||||
"credentials": [{"accessKey": "$(secret s3_admin_access_key_id)", "secretKey": "$(secret s3_admin_secret_access_key)"}],
|
||||
"actions": ["Admin", "Read", "Write", "List", "Tagging"]},
|
||||
{"name": "messenger-api",
|
||||
"credentials": [{"accessKey": "$(secret s3_api_access_key_id)", "secretKey": "$(secret s3_api_secret_access_key)"}],
|
||||
"actions": ["Write:${staging}", "Read:${bucket}"]},
|
||||
{"name": "messenger-worker",
|
||||
"credentials": [{"accessKey": "$(secret s3_worker_access_key_id)", "secretKey": "$(secret s3_worker_secret_access_key)"}],
|
||||
"actions": ["Read:${staging}", "Write:${staging}", "Read:${bucket}", "Write:${bucket}"]},
|
||||
{"name": "messenger-auditor",
|
||||
"credentials": [{"accessKey": "$(secret s3_auditor_access_key_id)", "secretKey": "$(secret s3_auditor_secret_access_key)"}],
|
||||
"actions": ["Read:${staging}", "List:${staging}", "Read:${bucket}", "List:${bucket}"]}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
# Memory: by default SeaweedFS buffers every in-flight upload without a limit and the Go runtime
|
||||
# keeps freed heap; measured ~1 GB under 16 parallel 9.4 MiB PUTs (lab 4). The upload limits make
|
||||
# excess PUTs wait inside SeaweedFS instead of growing the heap, and GOMEMLIMIT (set in
|
||||
# compose.yaml below the container limit) makes the Go GC return memory before the cgroup OOM.
|
||||
exec weed server \
|
||||
-dir=/data \
|
||||
-ip=127.0.0.1 -ip.bind=127.0.0.1 \
|
||||
-master.telemetry=false \
|
||||
-master.volumeSizeLimitMB=1024 -volume.max=0 \
|
||||
-filer -filer.disableDirListing -filer.concurrentUploadLimitMB=128 \
|
||||
-volume.concurrentUploadLimitMB=128 \
|
||||
-s3 -s3.ip.bind=0.0.0.0 -s3.port=8333 -s3.config=/tmp/s3.json -s3.concurrentUploadLimitMB=128 \
|
||||
-s3.iam=false -s3.autoCreateBucket=false -s3.port.iceberg=0 -s3.port.lance=0
|
||||
@@ -0,0 +1,34 @@
|
||||
# Tempo 2.10 (grafana/tempo:2.10.10), single binary, lab 6: the TRACES store.
|
||||
# Spans arrive from the Collector over OTLP/HTTP (:4318). Blocks + WAL on the named volume
|
||||
# tempodata; traces are kept 72 h. Search by attributes (TraceQL), e.g.
|
||||
# { resource.service.name = "messenger-worker" && span.messenger.job.outcome = "retry" }
|
||||
stream_over_http_enabled: true
|
||||
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
log_level: warn
|
||||
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
ingester:
|
||||
max_block_duration: 5m # small blocks: a restart loses at most the WAL replay time
|
||||
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 72h
|
||||
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,17 @@
|
||||
# Valkey is the single store of sessions (SESSION_STORE=valkey), so it must be durable.
|
||||
# AOF with fsync on every write: a confirmed login or logout survives a crash/restart,
|
||||
# a logout can never be lost and "resurrect" a token. Sessions are small and rare
|
||||
# writes, so the fsync cost is acceptable here (see REPORT.md).
|
||||
appendonly yes
|
||||
appendfsync always
|
||||
appenddirname "appendonlydir"
|
||||
# RDB snapshots are not needed on top of AOF.
|
||||
save ""
|
||||
dir /data
|
||||
port 6379
|
||||
protected-mode yes
|
||||
# Sessions are never evicted silently: if memory is full, writes fail and login returns 503.
|
||||
maxmemory 128mb
|
||||
maxmemory-policy noeviction
|
||||
# Password, generated by scripts/init_secrets.py and written here at container start.
|
||||
include /tmp/requirepass.conf
|
||||
Reference in New Issue
Block a user