Lab 7
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
2026-11-27 20:47:58 +03:00
parent 20afc2c790
commit d995f98446
97 changed files with 8638 additions and 56 deletions
+106
View File
@@ -0,0 +1,106 @@
{
"annotations": {"list": []},
"editable": true,
"graphTooltip": 1,
"title": "Messenger — API, worker, queue",
"uid": "messenger-lab6",
"schemaVersion": 39,
"version": 1,
"time": {"from": "now-30m", "to": "now"},
"refresh": "10s",
"templating": {"list": []},
"panels": [
{
"id": 1, "type": "timeseries", "title": "API RPS by route",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 0},
"fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []},
"targets": [{"expr": "sum by (route) (rate(http_server_requests_total[1m]))", "legendFormat": "{{route}}"}]
},
{
"id": 2, "type": "timeseries", "title": "API 5xx error ratio (business routes)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 0},
"fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []},
"targets": [{"expr": "sum(rate(http_server_requests_total{status_class=\"5xx\",route!~\".*health.*\"}[5m])) / clamp_min(sum(rate(http_server_requests_total{route!~\".*health.*\"}[5m])), 1)", "legendFormat": "5xx ratio"}]
},
{
"id": 3, "type": "timeseries", "title": "API latency p50/p95/p99 (histogram, ms)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 8},
"fieldConfig": {"defaults": {"unit": "ms"}, "overrides": []},
"targets": [
{"expr": "histogram_quantile(0.50, sum by (le) (rate(http_server_duration_milliseconds_bucket[5m])))", "legendFormat": "p50"},
{"expr": "histogram_quantile(0.95, sum by (le) (rate(http_server_duration_milliseconds_bucket[5m])))", "legendFormat": "p95"},
{"expr": "histogram_quantile(0.99, sum by (le) (rate(http_server_duration_milliseconds_bucket[5m])))", "legendFormat": "p99"}
]
},
{
"id": 4, "type": "timeseries", "title": "Jobs processed/s by outcome",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 8},
"fieldConfig": {"defaults": {"unit": "ops"}, "overrides": []},
"targets": [{"expr": "sum by (outcome) (rate(messenger_jobs_processed_total[5m]))", "legendFormat": "{{outcome}}"}]
},
{
"id": 5, "type": "timeseries", "title": "Job duration p95 / time-to-ready p95 (histogram)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 16},
"fieldConfig": {"defaults": {"unit": "s"}, "overrides": []},
"targets": [
{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_jobs_duration_bucket[5m])))", "legendFormat": "job p95"},
{"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_bucket[5m])))", "legendFormat": "time-to-ready p95"}
]
},
{
"id": 6, "type": "timeseries", "title": "Queue depth / oldest job age",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 16},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"expr": "max(messenger_queue_depth)", "legendFormat": "depth"},
{"expr": "max(messenger_queue_oldest_job_age_seconds)", "legendFormat": "oldest age (s)"}
]
},
{
"id": 7, "type": "timeseries", "title": "DB pool used / waiting",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 24},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"expr": "max(messenger_db_pool_used)", "legendFormat": "used"},
{"expr": "max(messenger_db_pool_waiting)", "legendFormat": "waiting"}
]
},
{
"id": 8, "type": "timeseries", "title": "Worker busy / capacity",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 24},
"fieldConfig": {"defaults": {}, "overrides": []},
"targets": [
{"expr": "sum(messenger_worker_busy)", "legendFormat": "busy"},
{"expr": "sum(messenger_worker_capacity)", "legendFormat": "capacity"}
]
},
{
"id": 9, "type": "timeseries", "title": "Process memory (API + worker)",
"datasource": {"type": "prometheus", "uid": "prometheus"},
"gridPos": {"h": 8, "w": 12, "x": 0, "y": 32},
"fieldConfig": {"defaults": {"unit": "bytes"}, "overrides": []},
"targets": [{"expr": "sum by (service_name) (process_memory_usage_bytes)", "legendFormat": "{{service_name}}"}]
},
{
"id": 10, "type": "logs", "title": "API logs (Loki) — JSON with trace_id",
"datasource": {"type": "loki", "uid": "loki"},
"gridPos": {"h": 8, "w": 12, "x": 12, "y": 32},
"options": {"showTime": true, "wrapLogMessage": true},
"targets": [{"expr": "{service_name=\"messenger-api\"} | json"}]
},
{
"id": 11, "type": "traces", "title": "Traces (Tempo)",
"datasource": {"type": "tempo", "uid": "tempo"},
"gridPos": {"h": 8, "w": 24, "x": 0, "y": 40},
"targets": [{"query": "{}", "queryType": "traceql"}]
}
]
}
@@ -0,0 +1,11 @@
apiVersion: 1
providers:
- name: messenger
orgId: 1
folder: Messenger
type: file
disableDeletion: false
updateIntervalSeconds: 30
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,40 @@
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
uid: prometheus
isDefault: true
jsonData:
timeInterval: 10s
- name: Loki
type: loki
access: proxy
url: http://loki:3100
uid: loki
jsonData:
derivedFields:
- name: trace_id
matcherType: label
matcherRegex: trace_id
datasourceUid: tempo
url: "$${__value.raw}"
urlDisplayLabel: "View trace"
- name: Tempo
type: tempo
access: proxy
url: http://tempo:3200
uid: tempo
jsonData:
tracesToLogsV2:
datasourceUid: loki
spanStartTimeShift: "-1m"
spanEndTimeShift: "1m"
filterByTraceID: true
tags:
- key: service.name
value: service_name
+43
View File
@@ -0,0 +1,43 @@
# Minimal single-binary Loki for the lab. OTLP logs land at /otlp/v1/logs.
auth_enabled: false
server:
http_listen_port: 3100
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: 2024-01-01
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
allow_structured_metadata: true
retention_period: 168h
compactor:
working_directory: /loki/compactor
delete_request_store: filesystem
retention_enabled: true
ruler:
storage:
type: local
local:
directory: /loki/rules
+79
View File
@@ -0,0 +1,79 @@
# Public TLS ingress. Terminates client TLS with the project CA leaf and
# re-encrypts to every API replica over mandatory mTLS using the dedicated LB
# client identity. The API has no published port; its own nginx terminator
# verifies the client cert chain AND the CN=lb identity.
worker_processes auto;
events {
worker_connections 2048;
}
http {
sendfile on;
keepalive_timeout 30;
server_tokens off;
access_log /dev/stdout;
error_log /dev/stderr warn;
upstream api_backend {
server api:8443;
}
# Minimal loopback-only liveness listener (not published); it cannot reach
# the business API without mTLS, so it is not a bypass.
server {
listen 127.0.0.1:8080;
server_name _;
access_log off;
location = /health/live {
return 200 "ok\n";
}
location / {
return 404;
}
}
server {
listen 8443 ssl;
server_name _;
ssl_certificate /run/secrets/lb.crt;
ssl_certificate_key /run/secrets/lb.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 5m;
# One attachment (<=10 MiB) plus JSON overhead.
client_max_body_size 12m;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto https;
proxy_connect_timeout 5s;
proxy_send_timeout 30s;
proxy_read_timeout 30s;
# Mandatory mTLS to the API replicas with server verification.
proxy_ssl_verify on;
proxy_ssl_verify_depth 2;
proxy_ssl_trusted_certificate /run/secrets/ca.crt;
proxy_ssl_certificate /run/secrets/lb-client.crt;
proxy_ssl_certificate_key /run/secrets/lb-client.key;
proxy_ssl_server_name on;
proxy_ssl_name api;
proxy_ssl_protocols TLSv1.2 TLSv1.3;
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 2;
location /health/live {
access_log off;
proxy_pass https://api_backend;
}
location / {
proxy_pass https://api_backend;
}
}
}
+22
View File
@@ -0,0 +1,22 @@
# OpenBao server, NON-dev mode, persistent file storage, TLS listener.
# Root token and unseal shares are created by scripts/openbao-bootstrap.sh and
# stay with the operator (never in Git/images). Applications use AppRole.
#
# NOTE: the official image entrypoint already passes -config=/openbao/config, so
# this file must NOT be passed again with -config or the listener is parsed twice
# ("address already in use"). It is mounted INTO the config directory instead.
ui = true
api_addr = "https://openbao:8200"
cluster_addr = "https://openbao:8201"
storage "file" {
path = "/openbao/file"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_disable = 0
tls_cert_file = "/run/secrets/openbao.crt"
tls_key_file = "/run/secrets/openbao.key"
tls_min_version = "tls12"
}
+7
View File
@@ -0,0 +1,7 @@
# API service policy (attached to the AppRole messenger-api).
# Least privilege: the token can only read this service's own KV v2 secret.
# No root, no wildcard paths, no ability to write policies or read other
# services' secrets -- a stolen API token cannot escalate.
path "secret/data/messenger/api" {
capabilities = ["read"]
}
+7
View File
@@ -0,0 +1,7 @@
# Worker service policy (attached to the AppRole messenger-worker).
# The worker gets its own path only: it must NOT be able to read the API's
# database URL or any admin credential. This separation is what limits the
# blast radius of a compromised worker (grade 5, track 1).
path "secret/data/messenger/worker" {
capabilities = ["read"]
}
+90
View File
@@ -0,0 +1,90 @@
# Alternative Collector config for Track 1: tail sampling keeps all error traces
# and slow traces, and only a fraction of the rest. This is the "balanced"
# configuration: rare failures are never sampled away, while steady-state volume
# stays bounded.
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 256
spike_limit_mib: 64
resource:
attributes:
- key: deployment.environment.name
value: lab
action: upsert
tail_sampling:
decision_wait: 5s
num_traces: 50000
expected_new_traces_per_sec: 50
policies:
- name: errors
type: status_code
status_code:
status_codes: [ERROR]
- name: slow
type: latency
latency:
threshold_ms: 500
- name: baseline
type: probabilistic
probabilistic:
sampling_percentage: 10
batch:
send_batch_size: 1024
send_batch_max_size: 2048
timeout: 5s
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
sending_queue:
enabled: true
queue_size: 1000
retry_on_failure:
enabled: true
max_elapsed_time: 60s
otlphttp/loki:
endpoint: http://loki:3100/otlp
sending_queue:
enabled: true
queue_size: 1000
retry_on_failure:
enabled: true
max_elapsed_time: 60s
debug:
verbosity: basic
service:
telemetry:
logs:
level: warn
metrics:
level: basic
address: 0.0.0.0:8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, resource, tail_sampling, batch]
exporters: [otlp/tempo, debug]
metrics:
receivers: [otlp]
processors: [memory_limiter, resource, batch]
exporters: [prometheus, debug]
logs:
receivers: [otlp]
processors: [memory_limiter, resource, batch]
exporters: [otlphttp/loki, debug]
+86
View File
@@ -0,0 +1,86 @@
# OTel Collector: OTLP in, three signals out.
# - traces -> Tempo (OTLP/gRPC)
# - metrics -> Prometheus exposition on :8889 (Prometheus scrapes it)
# - logs -> Loki native OTLP endpoint
# memory_limiter + batch keep RAM bounded; exporter queues are bounded and
# retry is time-limited, so a dead backend cannot grow RAM without bound.
receivers:
otlp:
protocols:
# Internal OTLP with mandatory client certificates (mTLS): the API and the
# worker present distinct client identities. Random network clients cannot
# inject telemetry at all.
grpc:
endpoint: 0.0.0.0:4317
tls:
cert_file: /run/secrets/otel.crt
key_file: /run/secrets/otel.key
client_ca_file: /run/secrets/ca.crt
http:
endpoint: 0.0.0.0:4318
tls:
cert_file: /run/secrets/otel.crt
key_file: /run/secrets/otel.key
client_ca_file: /run/secrets/ca.crt
processors:
memory_limiter:
check_interval: 1s
limit_mib: 256
spike_limit_mib: 64
resource:
attributes:
- key: deployment.environment.name
value: lab
action: upsert
batch:
send_batch_size: 1024
send_batch_max_size: 2048
timeout: 5s
exporters:
prometheus:
endpoint: 0.0.0.0:8889
resource_to_telemetry_conversion:
enabled: true
otlp/tempo:
endpoint: tempo:4317
tls:
insecure: true
sending_queue:
enabled: true
queue_size: 1000
retry_on_failure:
enabled: true
max_elapsed_time: 60s
otlphttp/loki:
endpoint: http://loki:3100/otlp
sending_queue:
enabled: true
queue_size: 1000
retry_on_failure:
enabled: true
max_elapsed_time: 60s
debug:
verbosity: basic
service:
telemetry:
logs:
level: warn
metrics:
level: basic
address: 0.0.0.0:8888
pipelines:
traces:
receivers: [otlp]
processors: [memory_limiter, resource, batch]
exporters: [otlp/tempo, debug]
metrics:
receivers: [otlp]
processors: [memory_limiter, resource, batch]
exporters: [prometheus, debug]
logs:
receivers: [otlp]
processors: [memory_limiter, resource, batch]
exporters: [otlphttp/loki, debug]
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
# Copy the mounted TLS material into a private, postgres-owned directory with
# 0600 permissions: PostgreSQL refuses to load a key that group/other can read,
# and Docker secrets are mounted world-readable.
TLS_DIR=/var/lib/postgresql/tls
install -d -m 700 -o postgres -g postgres "$TLS_DIR"
install -m 600 -o postgres -g postgres /run/secrets/postgres.crt "$TLS_DIR/server.crt"
install -m 600 -o postgres -g postgres /run/secrets/postgres.key "$TLS_DIR/server.key"
install -m 600 -o postgres -g postgres /run/secrets/ca.crt "$TLS_DIR/ca.crt"
# Clients verify the server certificate (verify-full) against the project CA.
exec docker-entrypoint.sh postgres \
-c ssl=on \
-c ssl_cert_file="$TLS_DIR/server.crt" \
-c ssl_key_file="$TLS_DIR/server.key" \
-c ssl_ca_file="$TLS_DIR/ca.crt" \
-c ssl_min_protocol_version=TLSv1.2
+46
View File
@@ -0,0 +1,46 @@
# Alert rules (grade 4). Local firing/resolved state only; no external delivery.
# Error ratio excludes health endpoints and 4xx (client mistakes), so a wrong
# password is not confused with a real server failure.
groups:
- name: messenger-sli
rules:
- alert: HighErrorRate
expr: |
(
sum(rate(http_server_requests_total{status_class="5xx",route!~".*health.*"}[5m]))
/
clamp_min(sum(rate(http_server_requests_total{route!~".*health.*"}[5m])), 1)
) > 0.05
for: 2m
labels:
severity: warning
annotations:
summary: "API 5xx ratio above 5% of business requests"
description: "5xx / business requests > 5% for 2 minutes. Runbook: docs in REPORT.md (incident 2)."
- alert: QueueLagGrowing
expr: messenger_queue_oldest_job_age_seconds > 30
for: 2m
labels:
severity: warning
annotations:
summary: "Oldest queued attachment job is older than 30s"
description: "Backlog is not draining (worker down or overloaded). Runbook: REPORT.md incident 1."
- alert: QueueDepthHigh
expr: messenger_queue_depth > 20
for: 2m
labels:
severity: info
annotations:
summary: "Attachment queue depth above 20"
description: "Sustained backlog; check worker capacity and processing time."
- alert: WorkerInactive
expr: max(messenger_worker_capacity) == 0
for: 1m
labels:
severity: warning
annotations:
summary: "No worker reporting capacity"
description: "The worker is not exporting metrics (stopped or telemetry broken)."
+17
View File
@@ -0,0 +1,17 @@
global:
scrape_interval: 10s
evaluation_interval: 10s
rule_files:
- /etc/prometheus/alerts.yml
scrape_configs:
- job_name: otel-collector
static_configs:
- targets: ["otel-collector:8889"]
- job_name: otel-collector-internal
static_configs:
- targets: ["otel-collector:8888"]
- job_name: prometheus
static_configs:
- targets: ["localhost:9090"]
+1
View File
@@ -0,0 +1 @@
[rabbitmq_auth_mechanism_ssl,rabbitmq_management].
+16
View File
@@ -0,0 +1,16 @@
# Internal broker listener with mandatory client certificates (mTLS).
# The client identity is the certificate CN (EXTERNAL auth), so a certificate
# signed by the project CA but carrying an unknown CN cannot authenticate at
# all. Plaintext TCP is disabled; nothing is published to the host.
listeners.tcp = none
listeners.ssl.default = 5671
ssl_options.cacertfile = /run/secrets/ca.crt
ssl_options.certfile = /run/secrets/broker.crt
ssl_options.keyfile = /run/secrets/broker.key
ssl_options.verify = verify_peer
ssl_options.fail_if_no_peer_cert = true
auth_mechanisms.1 = EXTERNAL
auth_mechanisms.2 = PLAIN
ssl_cert_login_from = common_name
+29
View File
@@ -0,0 +1,29 @@
# Minimal single-binary Tempo receiving OTLP/gRPC from the Collector.
server:
http_listen_port: 3200
log_level: warn
distributor:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
storage:
trace:
backend: local
local:
path: /var/tempo/traces
wal:
path: /var/tempo/wal
compactor:
compaction:
block_retention: 24h
metrics_generator:
storage:
path: /var/tempo/generator/wal