forked from mtusi2026/mtusi2026lab7
Выполнить лабораторную 7 по безопасности мессенджера
This commit is contained in:
+9
-5
@@ -1,7 +1,11 @@
|
||||
# Инфраструктура студента
|
||||
# Инфраструктура ЛР7
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
`compose.yaml` задаёт закреплённые версии образов, сети, volumes и роли.
|
||||
`haproxy.cfg` обслуживает публичный TLS и mTLS до всех API. Отдельные TLS-прокси
|
||||
защищают RustFS и сигналы наблюдаемости. PostgreSQL, OpenBao и RabbitMQ завершают
|
||||
TLS сами. Контейнерные plaintext listeners сторонних хранилищ доступны через
|
||||
loopback соответствующего network namespace.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
В [матрице доверия](../contracts/trust-matrix.md) перечислены порты, identities,
|
||||
права и команды проб. Порядок запуска и сценарии эксплуатации находятся в
|
||||
[отчёте](../REPORT.md).
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 512
|
||||
hard-stop-after 5s
|
||||
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
|
||||
log-format "%HM %ST %Ta %tsc"
|
||||
timeout connect 2s
|
||||
timeout check 3s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
timeout http-request 4s
|
||||
retries 1
|
||||
option redispatch
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
|
||||
resolvers docker
|
||||
nameserver embedded 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 2s
|
||||
hold obsolete 2s
|
||||
|
||||
frontend public_api
|
||||
bind :8443 ssl crt /run/edge/service.pem
|
||||
http-request del-header X-User-Id
|
||||
default_backend messenger_api
|
||||
|
||||
backend messenger_api
|
||||
balance roundrobin
|
||||
server-template api 1-8 api:8080 ssl verify required ca-file /run/identity/ca.crt crt /run/identity/service.pem sni str(api) check-sni api verifyhost api check inter 1s fastinter 500ms fall 2 rise 1 resolvers docker init-addr libc,none
|
||||
@@ -0,0 +1,16 @@
|
||||
global
|
||||
maxconn 128
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
listen loki
|
||||
bind :3100 ssl ssl-min-ver TLSv1.2 no-tls-tickets crt /run/identity/service.pem ca-file /run/identity/ca.crt verify required
|
||||
acl collector ssl_c_s_dn(cn) -m str collector
|
||||
acl reader ssl_c_s_dn(cn) -m str grafana
|
||||
acl ingest path -m str /otlp/v1/logs
|
||||
acl query path_beg /loki/api/v1/query /loki/api/v1/labels /loki/api/v1/label/ /loki/api/v1/series /loki/api/v1/index/
|
||||
http-request allow if collector ingest METH_POST
|
||||
http-request deny unless reader query METH_GET
|
||||
server local 127.0.0.1:13100
|
||||
+13
-4
@@ -1,7 +1,16 @@
|
||||
# OpenBao — реализовать конфигурацию и политики
|
||||
# OpenBao
|
||||
|
||||
Добавьте non-dev конфигурацию listener/storage/TLS, API/worker policies, bootstrap и rotation scripts. Credentials и unseal material создаются локально; здесь нет готового root token или private key.
|
||||
OpenBao работает в режиме server с TLS и постоянным Raft volume. Прикладная политика
|
||||
ограничена собственными KV path и ролью динамической БД. Настройки порта и TLS
|
||||
находятся в `bao.hcl`, шаблон каждой политики в `service-policy.hcl`.
|
||||
|
||||
Решение должно показать реальную сервисную аутентификацию и получение нужного secret по ограниченной policy; просто работающий контейнер OpenBao не засчитывается. На 3 статический KV secret допустим. На 4 покажите expiry/renewal/rotation и allow/deny. Путь KV v2 data/metadata и ACL должен соответствовать фактическому mount; не копируйте широкое `path "*"` для приложения.
|
||||
Первый запуск выполняет `scripts/start.sh`. Действия оператора можно выполнять
|
||||
по отдельности через `python3 scripts/operator.py`: `prepare`, `init`, `unseal`,
|
||||
`database`, `configure`. После перезапуска потребуется `unseal`. Материалы init и CA
|
||||
хранятся в `secrets/operator`; файлы доступны только на локальном хосте в каталоге
|
||||
с режимом 0700. Аудит записывает JSON с HMAC внутри Raft volume; содержимое аудита
|
||||
не копируется в публичные доказательства.
|
||||
|
||||
Документируйте шаги оператора init/unseal и восстановление после restart. Скрипт не должен печатать tokens/shares или хранить их в Git. См. contracts/trust-matrix.md и REPORT.md.
|
||||
При ротации S3 применяются команды `rotate-s3-add` и `rotate-s3-remove OLD_USER`.
|
||||
Выполняйте отзыв после проверки текущего ключа и завершения обработки, см.
|
||||
`make test-s3-rotation` и [отчёт](../../REPORT.md).
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
ui = false
|
||||
disable_mlock = true
|
||||
api_addr = "https://openbao:8200"
|
||||
cluster_addr = "https://openbao:8201"
|
||||
|
||||
storage "raft" {
|
||||
path = "/openbao/file"
|
||||
node_id = "lab7"
|
||||
}
|
||||
|
||||
listener "tcp" {
|
||||
address = "0.0.0.0:8200"
|
||||
tls_cert_file = "/run/identity/service.crt"
|
||||
tls_key_file = "/run/identity/service.key"
|
||||
tls_client_ca_file = "/run/identity/ca.crt"
|
||||
tls_min_version = "tls12"
|
||||
}
|
||||
|
||||
audit "file" "operator" {
|
||||
description = "HMAC-protected requests and responses"
|
||||
options {
|
||||
file_path = "/openbao/file/audit.jsonl"
|
||||
log_raw = "false"
|
||||
mode = "0600"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
path "runtime/data/ROLE" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "database/creds/ROLE" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
path "sys/leases/renew/database/creds/ROLE/*" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
path "auth/token/renew-self" {
|
||||
capabilities = ["update"]
|
||||
}
|
||||
path "auth/token/lookup-self" {
|
||||
capabilities = ["read"]
|
||||
}
|
||||
+10
-4
@@ -1,7 +1,13 @@
|
||||
# Конфигурация наблюдаемости — реализовать
|
||||
# Наблюдаемость ЛР7
|
||||
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
API и worker отправляют OTLP/HTTP с отдельными клиентскими сертификатами.
|
||||
Collector экспортирует логи в Loki, трассы в Tempo, метрики забирает
|
||||
Prometheus. Все три маршрута проверяют CA, имя сервера и роль клиента.
|
||||
Grafana выполняет запросы к этим источникам по mTLS с правами чтения.
|
||||
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
Административный интерфейс доступен по `https://localhost:3007/d/messenger-lab7`.
|
||||
Для доверия к HTTPS используется `secrets/trust/grafana.crt`. Логин `admin`,
|
||||
пароль находится в локальном файле `secrets/runtime/grafana/grafana_password`.
|
||||
UI и API остальных хранилищ доступны через datasource proxy Grafana.
|
||||
|
||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
||||
В качестве сквозной проверки запустите `make test-telemetry`.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
# Диагностика API и обработки вложений
|
||||
|
||||
Откройте Grafana → ЛР7 → [Наблюдаемость мессенджера](https://localhost:3007/d/messenger-lab7). Выставьте окно, включающее инцидент. В [Prometheus → Alerts](http://127.0.0.1:9096/alerts) проверьте состояние сработавших правил. В Grafana сплошная линия в панели срабатываний означает `firing`; после восстановления серия исчезает. Короткая пауза `pending` нужна, чтобы отфильтровать колебания около порога.
|
||||
|
||||
## API возвращает 503
|
||||
|
||||
1. Сверьте **Ошибки API** и **Задержка API**. В Prometheus посмотрите `messenger:api:burn20s`, `messenger:api:burn1m` и `messenger:api:count20s`. Если запросов мало, сравните с графиком RPS.
|
||||
2. В панели зависимостей сравните p95 `postgresql / api transaction / error` и `postgresql / acquire`. Если долгий именно `api transaction`, а `acquire` остаётся коротким, SQL ждёт внутри уже полученного соединения. Рост обоих сигналов означает, что клиенты начали ждать и свободное соединение.
|
||||
3. В Loki найдите событие `{service_name="messenger-api"} | event = "dependency_error"`. Если есть ответ клиента, добавьте `| request_id = "ЗНАЧЕНИЕ_X_REQUEST_ID"`. В деталях строки откройте Trace. В сохранённом сценарии SQL-спан длился около 1,5 с и имел статус ERROR, а лог содержал `error_type=QueryCanceled`. Проверки S3 и очередь оставались работоспособны.
|
||||
4. Для подтверждения блокировки на локальном PostgreSQL проверьте wait event и наличие блокирующего PID. Запрос не выводит текст SQL или параметры сессии.
|
||||
|
||||
```sql
|
||||
SELECT pid, wait_event_type, wait_event, pg_blocking_pids(pid) AS blockers
|
||||
FROM pg_stat_activity
|
||||
WHERE datname=current_database() AND cardinality(pg_blocking_pids(pid))>0;
|
||||
```
|
||||
|
||||
5. Для воспроизведения блокировка снимается автоматически после `pg_sleep` и `ROLLBACK`. Проверьте появление 200, падение p95 и переход правил API в состояние inactive. Отметьте отдельно время возврата HTTP и время выхода из окна алерта.
|
||||
|
||||
## Backlog растёт, API принимает файлы
|
||||
|
||||
1. Проверьте **Глубину очереди**, **Возраст старейшей задачи**, **Занятые слоты worker** и **Время до ready**. Рост возраста при сохранённых 202 и исчезновении серии capacity указывает на недоступный worker. Если capacity есть и busy близко к capacity, сравните длительность попытки и спаны S3/PostgreSQL.
|
||||
2. В Loki найдите `{service_name="messenger-api"} | event = "job_published"` и откройте Trace. Для остановленного worker producer есть, а consumer появится после восстановления. Если upload найден, а publish отсутствует, проверьте relay, RabbitMQ и непубликованный outbox.
|
||||
3. Проверьте `docker compose ps -a worker`; для учебной остановки выполните `docker compose start worker`. Дождитесь обработки накопившихся сообщений, depth=0 или обычного небольшого фона и выхода `QueueLagHigh` из firing. Ready burn-rate ещё некоторое время учитывает просроченную когорту в своих окнах. Повторно померьте долю good в `messenger:ready_slo:cohort`.
|
||||
|
||||
## Исчезли трассы, HTTP и очередь работают
|
||||
|
||||
Сверьте `up{job="collector"}`, `otelcol_exporter_queue_size{exporter="otlphttp/tempo"}` и `increase(otelcol_exporter_send_failed_spans_total{exporter="otlphttp/tempo"}[1m])`. В Loki может сохраниться `trace_id`, даже если Tempo не получил трассу. Проверьте готовность Tempo и появление новой трассы после восстановления. Retry Collector ограничен временем, поэтому старые утраченные спаны могут не вернуться.
|
||||
|
||||
## Быстрый разбор логов и связей
|
||||
|
||||
- По одному HTTP-запросу ищите `{service_name="messenger-api"} | request_id = "…"`. Сравните идентификатор span у события `http_request` с HTTP server span.
|
||||
- Для всех процессов в одной трассе используйте `{service_name=~"messenger-api|messenger-worker"} | trace_id = "…"`.
|
||||
- При retry цепочка выглядит так: server → publish #1 → consumer #1 → publish #2 → consumer #2. Внутри consumer #2 видны чтение staging, запись оригинала и вариантов, затем `postgresql commit ready`.
|
||||
@@ -0,0 +1,65 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 127.0.0.1:14318
|
||||
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 48
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 256
|
||||
send_batch_max_size: 256
|
||||
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 127.0.0.1:18889
|
||||
metric_expiration: 15s
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
otlphttp/loki:
|
||||
endpoint: https://loki:3100/otlp
|
||||
tls: &mtls
|
||||
ca_file: /run/identity/ca.crt
|
||||
cert_file: /run/identity/service.crt
|
||||
key_file: /run/identity/service.key
|
||||
timeout: 2s
|
||||
sending_queue: &bounded_queue
|
||||
queue_size: 32
|
||||
num_consumers: 2
|
||||
retry_on_failure: &bounded_retry
|
||||
initial_interval: 1s
|
||||
max_interval: 3s
|
||||
max_elapsed_time: 8s
|
||||
otlphttp/tempo:
|
||||
endpoint: https://tempo:4318
|
||||
tls: *mtls
|
||||
timeout: 2s
|
||||
sending_queue: *bounded_queue
|
||||
retry_on_failure: *bounded_retry
|
||||
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 127.0.0.1
|
||||
port: 18888
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,7 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: lab
|
||||
type: file
|
||||
folder: ЛР7
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,54 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
url: https://prometheus:9090
|
||||
isDefault: true
|
||||
secureJsonData:
|
||||
tlsCACert: $LAB_TLS_CA
|
||||
tlsClientCert: $LAB_TLS_CERT
|
||||
tlsClientKey: $LAB_TLS_KEY
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
httpMethod: GET
|
||||
timeInterval: 3s
|
||||
manageAlerts: false
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
url: https://loki:3100
|
||||
secureJsonData:
|
||||
tlsCACert: $LAB_TLS_CA
|
||||
tlsClientCert: $LAB_TLS_CERT
|
||||
tlsClientKey: $LAB_TLS_KEY
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
derivedFields:
|
||||
- name: Trace
|
||||
matcherType: label
|
||||
matcherRegex: trace_id
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
urlDisplayLabel: View trace
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
url: https://tempo:3200
|
||||
secureJsonData:
|
||||
tlsCACert: $LAB_TLS_CA
|
||||
tlsClientCert: $LAB_TLS_CERT
|
||||
tlsClientKey: $LAB_TLS_KEY
|
||||
jsonData:
|
||||
tlsAuth: true
|
||||
tlsAuthWithCACert: true
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-5s'
|
||||
spanEndTimeShift: '5s'
|
||||
customQuery: true
|
||||
query: '{service_name=~"messenger-api|messenger-worker"} | trace_id = "$${__span.traceId}"'
|
||||
nodeGraph:
|
||||
enabled: true
|
||||
@@ -0,0 +1,42 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_address: 127.0.0.1
|
||||
http_listen_port: 13100
|
||||
grpc_listen_address: 127.0.0.1
|
||||
common:
|
||||
path_prefix: /loki
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
replication_factor: 1
|
||||
ring:
|
||||
instance_addr: 127.0.0.1
|
||||
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: 336h
|
||||
otlp_config:
|
||||
resource_attributes:
|
||||
ignore_defaults: true
|
||||
attributes_config:
|
||||
- action: index_label
|
||||
attributes: [service.name]
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
frontend:
|
||||
instance_interface_names: [lo]
|
||||
@@ -0,0 +1,19 @@
|
||||
global:
|
||||
scrape_interval: 3s
|
||||
evaluation_interval: 3s
|
||||
rule_files:
|
||||
- /etc/prometheus/rules.yaml
|
||||
scrape_configs:
|
||||
- job_name: messenger
|
||||
scheme: https
|
||||
tls_config: &mtls
|
||||
ca_file: /run/identity/ca.crt
|
||||
cert_file: /run/identity/service.crt
|
||||
key_file: /run/identity/service.key
|
||||
static_configs:
|
||||
- targets: [collector:8889]
|
||||
- job_name: collector
|
||||
scheme: https
|
||||
tls_config: *mtls
|
||||
static_configs:
|
||||
- targets: [collector:8888]
|
||||
@@ -0,0 +1,101 @@
|
||||
groups:
|
||||
- name: messenger-slo
|
||||
rules:
|
||||
- record: messenger:ready_slo:cohort
|
||||
expr: max by (queue, result) (messenger_ready_slo_total)
|
||||
- record: messenger:api:count20s
|
||||
expr: sum(increase(messenger_http_requests_total{route!="unmatched",status_class!="aborted"}[20s]))
|
||||
- record: messenger:api:burn20s
|
||||
expr: (sum(increase(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[20s])) / (messenger:api:count20s > 0)) / 0.01
|
||||
- record: messenger:ready:count20s
|
||||
expr: sum(increase(messenger:ready_slo:cohort[20s]))
|
||||
- record: messenger:ready:burn20s
|
||||
expr: (sum(increase(messenger:ready_slo:cohort{result="bad"}[20s])) / (messenger:ready:count20s > 0)) / 0.01
|
||||
- record: messenger:api:count30s
|
||||
expr: sum(increase(messenger_http_requests_total{route!="unmatched",status_class!="aborted"}[30s]))
|
||||
- record: messenger:api:burn30s
|
||||
expr: (sum(increase(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[30s])) / (messenger:api:count30s > 0)) / 0.01
|
||||
- record: messenger:ready:count30s
|
||||
expr: sum(increase(messenger:ready_slo:cohort[30s]))
|
||||
- record: messenger:ready:burn30s
|
||||
expr: (sum(increase(messenger:ready_slo:cohort{result="bad"}[30s])) / (messenger:ready:count30s > 0)) / 0.01
|
||||
- record: messenger:api:count45s
|
||||
expr: sum(increase(messenger_http_requests_total{route!="unmatched",status_class!="aborted"}[45s]))
|
||||
- record: messenger:api:burn45s
|
||||
expr: (sum(increase(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[45s])) / (messenger:api:count45s > 0)) / 0.01
|
||||
- record: messenger:ready:count45s
|
||||
expr: sum(increase(messenger:ready_slo:cohort[45s]))
|
||||
- record: messenger:ready:burn45s
|
||||
expr: (sum(increase(messenger:ready_slo:cohort{result="bad"}[45s])) / (messenger:ready:count45s > 0)) / 0.01
|
||||
- record: messenger:api:count1m
|
||||
expr: sum(increase(messenger_http_requests_total{route!="unmatched",status_class!="aborted"}[1m]))
|
||||
- record: messenger:api:burn1m
|
||||
expr: (sum(increase(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[1m])) / (messenger:api:count1m > 0)) / 0.01
|
||||
- record: messenger:ready:count1m
|
||||
expr: sum(increase(messenger:ready_slo:cohort[1m]))
|
||||
- record: messenger:ready:burn1m
|
||||
expr: (sum(increase(messenger:ready_slo:cohort{result="bad"}[1m])) / (messenger:ready:count1m > 0)) / 0.01
|
||||
- record: messenger:api:count3m
|
||||
expr: sum(increase(messenger_http_requests_total{route!="unmatched",status_class!="aborted"}[3m]))
|
||||
- record: messenger:api:burn3m
|
||||
expr: (sum(increase(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[3m])) / (messenger:api:count3m > 0)) / 0.01
|
||||
- record: messenger:ready:count3m
|
||||
expr: sum(increase(messenger:ready_slo:cohort[3m]))
|
||||
- record: messenger:ready:burn3m
|
||||
expr: (sum(increase(messenger:ready_slo:cohort{result="bad"}[3m])) / (messenger:ready:count3m > 0)) / 0.01
|
||||
- record: messenger:api:count14d
|
||||
expr: sum(increase(messenger_http_requests_total{route!="unmatched",status_class!="aborted"}[14d]))
|
||||
- record: messenger:api:burn14d
|
||||
expr: (sum(increase(messenger_http_requests_total{route!="unmatched",status_class="5xx"}[14d])) / (messenger:api:count14d > 0)) / 0.01
|
||||
- record: messenger:ready:count14d
|
||||
expr: sum(increase(messenger:ready_slo:cohort[14d]))
|
||||
- record: messenger:ready:burn14d
|
||||
expr: (sum(increase(messenger:ready_slo:cohort{result="bad"}[14d])) / (messenger:ready:count14d > 0)) / 0.01
|
||||
- alert: ApiSLOBurnFast
|
||||
expr: messenger:api:burn20s > 15 and messenger:api:burn1m > 15 and messenger:api:count20s >= 5
|
||||
for: 6s
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Api SLO error budget burn above 15x for both windows"
|
||||
runbook: "infra/otel/RUNBOOK.md"
|
||||
- alert: ApiSLOBurnSlow
|
||||
expr: messenger:api:burn45s > 6 and messenger:api:burn3m > 6 and messenger:api:count45s >= 12
|
||||
for: 6s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Api SLO error budget burn above 6x for both windows"
|
||||
runbook: "infra/otel/RUNBOOK.md"
|
||||
- alert: ReadySLOBurnFast
|
||||
expr: messenger:ready:burn20s > 15 and messenger:ready:burn1m > 15 and messenger:ready:count20s >= 5
|
||||
for: 6s
|
||||
labels:
|
||||
severity: critical
|
||||
annotations:
|
||||
summary: "Ready SLO error budget burn above 15x for both windows"
|
||||
runbook: "infra/otel/RUNBOOK.md"
|
||||
- alert: ReadySLOBurnSlow
|
||||
expr: messenger:ready:burn45s > 6 and messenger:ready:burn3m > 6 and messenger:ready:count45s >= 12
|
||||
for: 6s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Ready SLO error budget burn above 6x for both windows"
|
||||
runbook: "infra/otel/RUNBOOK.md"
|
||||
- alert: ApiHighErrorRate
|
||||
expr: messenger:api:burn30s > 20 and messenger:api:count30s >= 15
|
||||
for: 6s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "More than 20 percent of API requests return 5xx"
|
||||
runbook: "infra/otel/RUNBOOK.md"
|
||||
- alert: QueueLagHigh
|
||||
expr: max by (queue) (messenger_queue_oldest_seconds) > 10
|
||||
for: 6s
|
||||
labels:
|
||||
severity: warning
|
||||
annotations:
|
||||
summary: "Oldest outstanding attachment has waited over 10 seconds"
|
||||
runbook: "infra/otel/RUNBOOK.md"
|
||||
@@ -0,0 +1,27 @@
|
||||
server:
|
||||
http_listen_address: 127.0.0.1
|
||||
http_listen_port: 13200
|
||||
grpc_listen_address: 127.0.0.1
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 127.0.0.1:14318
|
||||
ingester:
|
||||
lifecycler:
|
||||
address: 127.0.0.1
|
||||
trace_idle_period: 5s
|
||||
max_block_duration: 5m
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 336h
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,3 @@
|
||||
local all all trust
|
||||
hostssl all all 0.0.0.0/0 scram-sha-256
|
||||
hostssl all all ::/0 scram-sha-256
|
||||
@@ -0,0 +1,12 @@
|
||||
global
|
||||
maxconn 128
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
listen prometheus
|
||||
bind :9090 ssl ssl-min-ver TLSv1.2 no-tls-tickets crt /run/identity/service.pem ca-file /run/identity/ca.crt verify required
|
||||
acl query_path path_beg /api/v1/query /api/v1/label /api/v1/series /api/v1/metadata /api/v1/status/
|
||||
http-request deny unless { ssl_c_s_dn(cn) -m str grafana } query_path METH_GET
|
||||
server local 127.0.0.1:19090
|
||||
@@ -0,0 +1,2 @@
|
||||
{host, {127,0,0,1}, ["rabbitmq", "localhost"]}.
|
||||
{lookup, [file, native]}.
|
||||
@@ -0,0 +1 @@
|
||||
[rabbitmq_auth_mechanism_ssl].
|
||||
@@ -0,0 +1,13 @@
|
||||
listeners.tcp = none
|
||||
listeners.ssl.default = 5671
|
||||
ssl_options.cacertfile = /run/identity/ca.crt
|
||||
ssl_options.certfile = /run/identity/service.crt
|
||||
ssl_options.keyfile = /run/identity/service.key
|
||||
ssl_options.verify = verify_peer
|
||||
ssl_options.fail_if_no_peer_cert = true
|
||||
ssl_options.versions.1 = tlsv1.3
|
||||
ssl_options.versions.2 = tlsv1.2
|
||||
auth_mechanisms.1 = EXTERNAL
|
||||
ssl_cert_login_from = common_name
|
||||
definitions.import_backend = local_filesystem
|
||||
definitions.local.path = /etc/rabbitmq/definitions.json
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"users": [{"name": "api", "password_hash": "", "tags": []}, {"name": "worker", "password_hash": "", "tags": []}],
|
||||
"vhosts": [{"name": "/messenger"}],
|
||||
"permissions": [
|
||||
{"user": "api", "vhost": "/messenger", "configure": "^$", "write": "^amq\\.default$", "read": "^$"},
|
||||
{"user": "worker", "vhost": "/messenger", "configure": "^$", "write": "^$", "read": "^attachment-processing-v1$"}
|
||||
],
|
||||
"queues": [
|
||||
{"name": "attachment-processing-v1", "vhost": "/messenger", "durable": true, "auto_delete": false, "arguments": {}}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:ListBucket"], "Resource": ["arn:aws:s3:::messenger-attachments"], "Condition": {"StringLike": {"s3:prefix": ["attachments/*"]}}},
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject"], "Resource": ["arn:aws:s3:::messenger-attachments/attachments/*"]},
|
||||
{"Effect": "Allow", "Action": ["s3:PutObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
. /run/local-config/env
|
||||
export SSL_CERT_FILE=/run/local-config/ca.crt
|
||||
rc alias set local https://rustfs:9000 "$RUSTFS_ACCESS_KEY" "$RUSTFS_SECRET_KEY" >/dev/null
|
||||
attempt=0
|
||||
until rc ls local/ >/dev/null 2>&1; do
|
||||
attempt=$((attempt + 1))
|
||||
if [ "$attempt" -ge 20 ]; then echo 'S3 TLS endpoint did not become ready' >&2; exit 1; fi
|
||||
sleep 2
|
||||
done
|
||||
if [ "$#" -gt 0 ]; then
|
||||
case "$1" in
|
||||
add)
|
||||
read -r user
|
||||
read -r password
|
||||
rc admin user add local/ "$user" "$password" >/dev/null
|
||||
rc admin policy attach local/ messenger-worker --user "$user" >/dev/null
|
||||
;;
|
||||
remove)
|
||||
read -r user
|
||||
rc admin user remove local/ "$user" >/dev/null
|
||||
;;
|
||||
*) exit 2 ;;
|
||||
esac
|
||||
exit
|
||||
fi
|
||||
rc bucket create --ignore-existing local/messenger-attachments >/dev/null
|
||||
for role in api worker; do
|
||||
case "$role" in
|
||||
api) user="$API_S3_USER"; password="$API_S3_PASSWORD";;
|
||||
worker) user="$WORKER_S3_USER"; password="$WORKER_S3_PASSWORD";;
|
||||
esac
|
||||
rc admin policy create local/ "messenger-$role" "/bootstrap/$role.json" >/dev/null
|
||||
if ! rc admin user list local/ | awk '{print $1}' | grep -Fxq "$user"; then
|
||||
rc admin user add local/ "$user" "$password" >/dev/null
|
||||
fi
|
||||
rc admin policy attach local/ "messenger-$role" --user "$user" >/dev/null
|
||||
done
|
||||
printf '%s\n' 'Private bucket and both scoped S3 users are ready.'
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{"Effect": "Allow", "Action": ["s3:GetObject", "s3:DeleteObject"], "Resource": ["arn:aws:s3:::messenger-attachments/staging/*"]},
|
||||
{"Effect": "Allow", "Action": ["s3:PutObject"], "Resource": ["arn:aws:s3:::messenger-attachments/attachments/*"]}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
global
|
||||
maxconn 128
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 3s
|
||||
timeout client 20s
|
||||
timeout server 20s
|
||||
listen s3
|
||||
bind :9000 ssl ssl-min-ver TLSv1.2 no-tls-tickets crt /run/identity/service.pem
|
||||
server local 127.0.0.1:19000
|
||||
@@ -0,0 +1,28 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 128
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets
|
||||
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
timeout http-request 4s
|
||||
|
||||
listen collector_ingest
|
||||
bind :4318 ssl crt /run/identity/service.pem ca-file /run/identity/ca.crt verify required
|
||||
acl accepted_role ssl_c_s_dn(cn) -m str api worker
|
||||
acl signal_path path -m str /v1/metrics /v1/traces /v1/logs
|
||||
http-request deny unless accepted_role signal_path METH_POST
|
||||
server local 127.0.0.1:14318
|
||||
|
||||
listen collector_metrics
|
||||
bind :8889 ssl crt /run/identity/service.pem ca-file /run/identity/ca.crt verify required
|
||||
http-request deny unless { ssl_c_s_dn(cn) -m str prometheus } { path /metrics } METH_GET
|
||||
server local 127.0.0.1:18889
|
||||
|
||||
listen collector_self_metrics
|
||||
bind :8888 ssl crt /run/identity/service.pem ca-file /run/identity/ca.crt verify required
|
||||
http-request deny unless { ssl_c_s_dn(cn) -m str prometheus } { path /metrics } METH_GET
|
||||
server local 127.0.0.1:18888
|
||||
@@ -0,0 +1,17 @@
|
||||
global
|
||||
maxconn 128
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 15s
|
||||
timeout server 15s
|
||||
listen query
|
||||
bind :3200 ssl ssl-min-ver TLSv1.2 no-tls-tickets crt /run/identity/service.pem ca-file /run/identity/ca.crt verify required
|
||||
acl query_path path_beg /api/traces/ /api/search /api/echo /api/v2/
|
||||
http-request deny unless { ssl_c_s_dn(cn) -m str grafana } query_path METH_GET
|
||||
server local 127.0.0.1:13200
|
||||
|
||||
listen ingest
|
||||
bind :4318 ssl ssl-min-ver TLSv1.2 no-tls-tickets crt /run/identity/service.pem ca-file /run/identity/ca.crt verify required
|
||||
http-request deny unless { ssl_c_s_dn(cn) -m str collector } { path /v1/traces } METH_POST
|
||||
server local 127.0.0.1:14318
|
||||
Reference in New Issue
Block a user