lab 7 done

This commit is contained in:
Khakimov Dmitrij
2026-11-29 21:59:16 +03:00
parent 20afc2c790
commit 2a7418fc45
170 changed files with 10332 additions and 96 deletions
+3 -5
View File
@@ -1,7 +1,5 @@
# Инфраструктура студента
# Настройки стенда
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
Compose запускает две реплики API, HAProxy, worker, PostgreSQL, Redis, MinIO, OpenBao и подсистему телеметрии. Goose применяет миграции из lab6. Операторские контейнеры выдают рабочие права и проверяют сервисы.
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
Операторские команды создают сертификаты и секреты перед запуском. CA и ключи остаются на хосте. Опубликованные порты относятся к входному HTTPS, Grafana и OpenBao. [Запуск](../REPORT.md) · [Матрица доверия](../contracts/trust-matrix.md)
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
export PGPASSWORD="$(cat /bootstrap/admin/POSTGRES_PASSWORD)"
if [ "${1:-}" = worker ]; then
exec psql -X -q -h postgres -U messenger -d messenger -f /rotate-worker.sql
fi
exec psql -X -q -h postgres -U messenger -d messenger -f /grants.sql
+32
View File
@@ -0,0 +1,32 @@
\set ON_ERROR_STOP on
SELECT 'CREATE ROLE messenger_api LOGIN' WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger_api') \gexec
SELECT 'CREATE ROLE messenger_worker LOGIN' WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger_worker') \gexec
SELECT 'CREATE ROLE messenger_operator LOGIN' WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='messenger_operator') \gexec
\set api_password `cat /bootstrap/api/POSTGRES_PASSWORD`
\set worker_password `cat /bootstrap/worker/POSTGRES_PASSWORD`
\set operator_password `cat /bootstrap/operator/POSTGRES_PASSWORD`
ALTER ROLE messenger_api PASSWORD :'api_password';
ALTER ROLE messenger_worker PASSWORD :'worker_password';
ALTER ROLE messenger_operator PASSWORD :'operator_password';
REVOKE ALL ON DATABASE messenger FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker, messenger_operator;
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker, messenger_operator;
GRANT SELECT, INSERT ON users, chats, chat_members, messages TO messenger_api;
GRANT UPDATE (password_hash) ON users TO messenger_api;
GRANT SELECT, INSERT, UPDATE ON attachments, attachment_jobs, attachment_outbox TO messenger_api;
REVOKE ALL ON attachments, attachment_jobs, attachment_outbox FROM messenger_worker;
GRANT SELECT (id, status, object_key, content_type, size_bytes, variants, pipeline_version,
staging_key, sha256, width, height, updated_at, storage_cleaned_at)
ON attachments TO messenger_worker;
GRANT SELECT (id, attachment_id, state, attempts, max_attempts, available_at, pipeline_version,
fence, lease_until, last_error, updated_at)
ON attachment_jobs TO messenger_worker;
GRANT SELECT (job_id) ON attachment_outbox TO messenger_worker;
GRANT SELECT ON attachments, attachment_jobs, attachment_outbox TO messenger_operator;
GRANT SELECT (attachment_ids) ON messages TO messenger_operator;
GRANT UPDATE (status, updated_at, error_code, variants, staging_key, storage_cleaned_at) ON attachments TO messenger_worker;
GRANT UPDATE (state, attempts, fence, lease_until, available_at, last_error, updated_at) ON attachment_jobs TO messenger_worker;
GRANT UPDATE (published_at, available_at) ON attachment_outbox TO messenger_worker;
GRANT UPDATE ON attachments, attachment_jobs, attachment_outbox TO messenger_operator;
GRANT INSERT ON attachment_replays TO messenger_operator;
+519
View File
@@ -0,0 +1,519 @@
{
"uid": "messenger",
"title": "Messenger observability",
"schemaVersion": 41,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"title": "API RPS (business routes)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(messenger_http_requests_total[$__rate_interval])) by (route)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "reqps"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 2,
"title": "API 5xx / all business requests",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 0,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\"}[$__rate_interval])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total[$__rate_interval])),0.001)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 3,
"title": "API p50 / p95 / p99 (all replicas, histogram)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.5,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "p50",
"refId": "A"
},
{
"expr": "histogram_quantile(0.95,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "p95",
"refId": "B"
},
{
"expr": "histogram_quantile(0.99,sum(rate(messenger_http_duration_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "p99",
"refId": "C"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 4,
"title": "Worker job outcomes per second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 8,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(rate(messenger_jobs_total[$__rate_interval])) by(outcome)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "ops"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 5,
"title": "Worker job p95 duration",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum(rate(messenger_job_duration_seconds_bucket[$__rate_interval])) by(le,outcome))",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 6,
"title": "Time from durable acceptance to ready p95",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 16,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "histogram_quantile(0.95,sum(rate(messenger_attachment_ready_seconds_bucket[$__rate_interval])) by(le))",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 7,
"title": "Authoritative queue depth (max across observers)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_queue_depth)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 8,
"title": "Oldest unfinished job age",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 24,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "max(messenger_queue_oldest_age_seconds)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "s"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 9,
"title": "DB pool acquired / acquiring / max",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "messenger_db_pool_used",
"legendFormat": "used {{service_name}} {{service_instance_id}}",
"refId": "A"
},
{
"expr": "messenger_db_pool_waiting",
"legendFormat": "waiting {{service_name}} {{service_instance_id}}",
"refId": "B"
},
{
"expr": "messenger_db_pool_max",
"legendFormat": "max {{service_name}} {{service_instance_id}}",
"refId": "C"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 10,
"title": "Worker saturation busy / capacity",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 32,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(messenger_worker_busy{service_name=\"messenger-worker\"}) / clamp_min(sum(messenger_worker_capacity{service_name=\"messenger-worker\"}),1)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 11,
"title": "Go runtime reserved memory (MemStats.Sys)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "messenger_process_memory_bytes",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "bytes"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 12,
"title": "Process CPU seconds / second",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 40,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "rate(messenger_process_cpu_seconds_total[$__rate_interval])",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 13,
"title": "SDK failed telemetry export operations",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 0,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "messenger_telemetry_export_errors",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 14,
"title": "Exporter failed spans (attempts, not unique loss)",
"type": "timeseries",
"datasource": {
"type": "prometheus",
"uid": "prometheus"
},
"gridPos": {
"x": 12,
"y": 48,
"w": 12,
"h": 8
},
"targets": [
{
"expr": "sum(otelcol_exporter_send_failed_spans_total) by (exporter)",
"legendFormat": "{{service_name}} {{outcome}} {{route}}",
"refId": "A"
}
],
"fieldConfig": {
"defaults": {
"unit": "short"
}
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom"
}
}
},
{
"id": 99,
"title": "API and worker structured logs; trace ID opens Tempo",
"type": "logs",
"datasource": {
"type": "loki",
"uid": "loki"
},
"gridPos": {
"x": 0,
"y": 56,
"w": 24,
"h": 10
},
"targets": [
{
"expr": "{service_name=~\"messenger-api|messenger-worker\"} | json",
"refId": "A"
}
]
}
],
"annotations": {
"list": []
}
}
@@ -0,0 +1,6 @@
apiVersion: 1
providers:
- name: Messenger
type: file
options: {path: /var/lib/grafana/dashboards}
updateIntervalSeconds: 10
@@ -0,0 +1,40 @@
{
"apiVersion": 1,
"datasources": [
{
"name": "Prometheus",
"uid": "prometheus",
"type": "prometheus",
"access": "proxy",
"url": "https://prometheus:49090",
"isDefault": true,
"jsonData": {}
},
{
"name": "Loki",
"uid": "loki",
"type": "loki",
"access": "proxy",
"url": "https://loki:43101",
"jsonData": {
"derivedFields": [{
"name": "TraceID",
"matcherRegex": "\"trace_id\":\"([a-f0-9]{32})\"",
"datasourceUid": "tempo",
"url": "$${__value.raw}"
}]
}
},
{
"name": "Tempo",
"uid": "tempo",
"type": "tempo",
"access": "proxy",
"url": "https://tempo:43200",
"jsonData": {
"tracesToLogsV2": {"datasourceUid": "loki", "filterByTraceID": true},
"serviceMap": {"datasourceUid": "prometheus"}
}
}
]
}
+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
ssl-default-server-options ssl-min-ver TLSv1.2 no-tls-tickets
defaults
log global
mode http
timeout connect 1s
timeout client 55s
timeout server 55s
timeout check 1s
retries 0
option http-server-close
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
hold refused 1s
hold timeout 1s
frontend public
bind :8443 ssl crt /identity/server.pem
unique-id-format %[uuid()]
acl oversized req.hdr_val(content-length) gt 10485760
http-request return status 413 content-type application/json lf-string '{"error":{"code":"payload_too_large","message":"Payload exceeds 10 MiB","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr X-Instance-Id gateway if oversized
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
default-server inter 1s fastinter 500ms downinter 1s fall 2 rise 1
server-template replica 1-8 api:8080 ssl verify required ca-file /trust/ca.crt verifyhost api sni str(api) crt /identity/client.pem check check-sni api resolvers docker init-addr none
+27
View File
@@ -0,0 +1,27 @@
auth_enabled: false
server: {http_listen_address: 127.0.0.1, http_listen_port: 3100, grpc_listen_address: 127.0.0.1, grpc_listen_port: 9096}
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-04-01'
store: tsdb
object_store: filesystem
schema: v13
index: {prefix: index_, period: 24h}
limits_config:
allow_structured_metadata: true
retention_period: 168h
ingestion_rate_mb: 4
ingestion_burst_size_mb: 8
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
analytics: {reporting_enabled: false}
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
# Keep the password out of argv and disable automatic dotenv loading.
if [ -n "${POSTGRES_PASSWORD_FILE:-}" ]; then
PGPASSWORD=$(cat "$POSTGRES_PASSWORD_FILE")
export PGPASSWORD
fi
exec goose -env /dev/null -dir /migrations -timeout 30s "$@"
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
export MINIO_ROOT_USER="$(cat /bootstrap/S3_ACCESS_KEY)"
export MINIO_ROOT_PASSWORD="$(cat /bootstrap/S3_SECRET_KEY)"
exec minio server /data --certs-dir /identity --address :9000 --console-address 127.0.0.1:9001
+6 -4
View File
@@ -1,7 +1,9 @@
# OpenBao — реализовать конфигурацию и политики
# OpenBao
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
Контейнер запускает `bao server -config=/etc/bao.hcl` и использует том `openbao_data`. Декларативный аудит пишет JSONL в том. OpenBao хэширует чувствительные поля журнала. Приложения используют TLS, проверяют имя `openbao` и входят по сертификату.
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
`scripts/stand.py bootstrap` создаёт схему Shamir 2 из 3 и сохраняет ответ в каталоге оператора. Каталог оператора доступен с хоста и отсутствует в mount контейнеров. В учебном стенде один оператор хранит все доли. Для своего окружения разнесите доли между операторами и сохраните резервную копию отдельно.
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
После перезапуска выполните `python3 scripts/stand.py unseal`. Пароли сервисов остаются в KV v2. OpenBao проверяет конкретный сертификат, привязанный к роли. Для продления доступа сервис входит повторно через 10 секунд. Если смените сертификат, обновите привязку и перезапустите сервис. Для worker эту процедуру выполняет `rotate-worker`. [Операторские команды](../../REPORT.md)
`disable_mlock` позволяет контейнеру работать без `IPC_LOCK`. Это учебное ограничение. OpenBao использует один том и один локальный журнал. [Официальная документация по аудиту](https://openbao.org/docs/audit/)
+6
View File
@@ -0,0 +1,6 @@
path "lab/data/api" {
capabilities = ["read"]
}
path "auth/token/revoke-self" {
capabilities = ["update"]
}
+19
View File
@@ -0,0 +1,19 @@
ui = false
disable_mlock = true
api_addr = "https://openbao:8200"
storage "file" {
path = "/openbao/file"
}
listener "tcp" {
address = "0.0.0.0:8200"
tls_cert_file = "/identity/tls.crt"
tls_key_file = "/identity/tls.key"
tls_client_ca_file = "/trust/ca.crt"
tls_min_version = "tls12"
}
audit "file" "operator-audit" {
options {
file_path = "/openbao/file/audit.jsonl"
log_raw = "false"
}
}
+6
View File
@@ -0,0 +1,6 @@
path "lab/data/operator" {
capabilities = ["read"]
}
path "auth/token/revoke-self" {
capabilities = ["update"]
}
+6
View File
@@ -0,0 +1,6 @@
path "lab/data/worker" {
capabilities = ["read"]
}
path "auth/token/revoke-self" {
capabilities = ["update"]
}
+4 -4
View File
@@ -1,7 +1,7 @@
# Конфигурация наблюдаемости — реализовать
# Сбор телеметрии
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
API и worker передают OTLP/HTTP через mTLS на Collector. Collector отправляет логи в Loki и трассы в Tempo. Prometheus собирает метрики раз в 5 секунд. Grafana получает данные через HTTPS с сертификатом роли `grafana`.
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
Настройки прокси задают разрешённые URI SAN и операции HTTP. Collector, Loki, Tempo и Prometheus слушают открытый протокол только внутри своих сетевых пространств имён. [Матрица доверия](../../contracts/trust-matrix.md)
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
В момент запуска оператор создаёт локальные настройки источников Grafana из шаблонов. Настройки содержат приватный ключ Grafana. Панели и настройки сбора входят в репозиторий. Grafana доступна по HTTPS на порту 13000. [Запуск и проверка](../../REPORT.md)
+42
View File
@@ -0,0 +1,42 @@
receivers:
otlp:
protocols:
http: {endpoint: '127.0.0.1:4318'}
processors:
memory_limiter:
check_interval: 1s
limit_mib: 128
spike_limit_mib: 32
batch:
timeout: 1s
send_batch_size: 256
send_batch_max_size: 512
exporters:
prometheus:
endpoint: 127.0.0.1:8889
metric_expiration: 15s
resource_to_telemetry_conversion: {enabled: true}
otlphttp/tempo:
endpoint: https://tempo:44318
tls: {ca_file: /trust/ca.crt, cert_file: /identity/tls.crt, key_file: /identity/tls.key}
timeout: 2s
sending_queue: {enabled: true, queue_size: 256, num_consumers: 2}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 20s}
otlphttp/loki:
endpoint: https://loki:43100/otlp
tls: {ca_file: /trust/ca.crt, cert_file: /identity/tls.crt, key_file: /identity/tls.key}
timeout: 2s
sending_queue: {enabled: true, queue_size: 256, num_consumers: 2}
retry_on_failure: {enabled: true, initial_interval: 1s, max_interval: 5s, max_elapsed_time: 20s}
service:
telemetry:
metrics:
level: detailed
readers:
- pull:
exporter:
prometheus: {host: 127.0.0.1, port: 8888}
pipelines:
traces: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/tempo]}
metrics: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [prometheus]}
logs: {receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/loki]}
+2
View File
@@ -0,0 +1,2 @@
local all all peer map=bootstrap
hostssl all all all scram-sha-256
+1
View File
@@ -0,0 +1 @@
bootstrap postgres messenger
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
install -m 600 /identity/tls.key /tmp/postgres.key
exec docker-entrypoint.sh postgres -c ssl=on \
-c ssl_cert_file=/identity/tls.crt -c ssl_key_file=/tmp/postgres.key \
-c ident_file=/etc/pg_ident.conf -c hba_file=/etc/pg_hba.conf -c shared_buffers=32MB -c max_connections=48
+19
View File
@@ -0,0 +1,19 @@
groups:
- name: messenger-slo
rules:
- alert: APIHighErrorRate
expr: sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])), 0.01) > 0.05
for: 5s
labels: {severity: warning}
annotations:
summary: More than 5 percent API server failures over 1 minute
runbook_url: http://localhost:13000/d/messenger/messenger-observability
description: Excludes health and client 4xx. Inspect PostgreSQL spans and pool; see RUNBOOK.md.
- alert: QueueLagGrowing
expr: max(messenger_queue_oldest_age_seconds) > 10 and max(messenger_queue_depth) > 0
for: 5s
labels: {severity: warning}
annotations:
summary: Oldest unfinished attachment exceeds 10 seconds
runbook_url: http://localhost:13000/d/messenger/messenger-observability
description: Inspect worker capacity, busy, outcomes and dependency spans; see RUNBOOK.md.
+26
View File
@@ -0,0 +1,26 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files: [/etc/prometheus/alerts.yaml]
scrape_configs:
- job_name: messenger
scheme: https
tls_config: &client
ca_file: /trust/ca.crt
cert_file: /identity/tls.crt
key_file: /identity/tls.key
static_configs: [{targets: ['collector:48889']}]
- job_name: collector
scheme: https
tls_config: *client
static_configs: [{targets: ['collector:48888']}]
- job_name: tempo
scheme: https
tls_config: *client
static_configs: [{targets: ['tempo:43201']}]
- job_name: loki
scheme: https
tls_config: *client
static_configs: [{targets: ['loki:43102']}]
- job_name: prometheus
static_configs: [{targets: ['localhost:9090']}]
+10
View File
@@ -0,0 +1,10 @@
bind 127.0.0.1
protected-mode yes
port 6379
dir /data
aclfile /acl/users.acl
appendonly yes
appendfsync always
save ""
maxmemory 96mb
maxmemory-policy noeviction
+6
View File
@@ -0,0 +1,6 @@
\set ON_ERROR_STOP on
\set worker_password `cat /bootstrap/worker/POSTGRES_PASSWORD`
ALTER ROLE messenger_worker PASSWORD :'worker_password';
SELECT count(*) FROM (
SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='messenger_worker'
) AS terminated;
+9
View File
@@ -0,0 +1,9 @@
{
"Version": "2012-10-17",
"Statement": [
{"Effect":"Allow","Action":["s3:GetBucketLocation"],"Resource":["arn:aws:s3:::attachments"]},
{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::attachments"],"Condition":{"StringLike":{"s3:prefix":["original/*"]}}},
{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::attachments/original/*"]},
{"Effect":"Allow","Action":["s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/staging/*"]}
]
}
+23
View File
@@ -0,0 +1,23 @@
#!/bin/sh
set -eu
export MC_CONFIG_DIR=/tmp/mc
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
cp /trust/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
mc alias set admin https://minio:9000 "$(cat /bootstrap/admin/S3_ACCESS_KEY)" "$(cat /bootstrap/admin/S3_SECRET_KEY)" >/dev/null
mc ready admin >/dev/null
mc mb --ignore-existing admin/attachments >/dev/null
mc anonymous set none admin/attachments >/dev/null
if [ "${1:-}" = worker ]; then
old=$(cat /retired/S3_ACCESS_KEY)
mc admin user rm admin "$old" >/dev/null
set -- worker
else
set -- api worker operator
fi
for role do
mc admin policy create admin "attachments-$role" "/policies/s3-$role.json" >/dev/null
key=$(cat "/bootstrap/$role/S3_ACCESS_KEY")
mc admin user add admin "$key" "$(cat "/bootstrap/$role/S3_SECRET_KEY")" >/dev/null
mc admin policy attach admin "attachments-$role" --user "$key" >/dev/null
done
printf '%s\n' 'Private bucket and scoped S3 accounts configured.'
+21
View File
@@ -0,0 +1,21 @@
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:GetBucketLocation"],
"Resource": ["arn:aws:s3:::attachments"]
},
{
"Effect": "Allow",
"Action": ["s3:ListBucket"],
"Resource": ["arn:aws:s3:::attachments"],
"Condition": {"StringLike": {"s3:prefix": ["original/*", "staging/*"]}}
},
{
"Effect": "Allow",
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
"Resource": ["arn:aws:s3:::attachments/original/*", "arn:aws:s3:::attachments/staging/*"]
}
]
}
+9
View File
@@ -0,0 +1,9 @@
{
"Version": "2012-10-17",
"Statement": [
{"Effect":"Allow","Action":["s3:GetBucketLocation"],"Resource":["arn:aws:s3:::attachments"]},
{"Effect":"Allow","Action":["s3:ListBucket"],"Resource":["arn:aws:s3:::attachments"],"Condition":{"StringLike":{"s3:prefix":["staging/*"]}}},
{"Effect":"Allow","Action":["s3:GetObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/staging/*"]},
{"Effect":"Allow","Action":["s3:GetObject","s3:PutObject","s3:DeleteObject"],"Resource":["arn:aws:s3:::attachments/original/*"]}
]
}
+18
View File
@@ -0,0 +1,18 @@
server: {http_listen_address: 127.0.0.1, http_listen_port: 3200, grpc_listen_address: 127.0.0.1}
distributor:
receivers:
otlp:
protocols:
http: {endpoint: '127.0.0.1:4318'}
ingester:
max_block_duration: 1m
compactor:
compaction:
block_retention: 168h
max_compaction_objects: 20000
storage:
trace:
backend: local
wal: {path: /var/tempo/wal}
local: {path: /var/tempo/blocks}
usage_report: {reporting_enabled: false}