Реализовать наблюдаемость мессенджера для ЛР 6 на четыре

This commit is contained in:
2026-11-18 13:24:20 +03:00
parent 470d9d6f1e
commit c236059a83
184 changed files with 20450 additions and 54 deletions
+28
View File
@@ -0,0 +1,28 @@
global
log stdout format raw local0
stats socket ipv4@127.0.0.1:9999 level admin
defaults
mode http
log global
option httplog
timeout connect 2s
timeout client 30s
timeout server 30s
timeout http-request 10s
resolvers docker
nameserver docker 127.0.0.11:53
accepted_payload_size 8192
hold valid 1s
frontend api
bind *:8080
default_backend api_replicas
backend api_replicas
balance roundrobin
timeout check 3s
option httpchk GET /health/ready
http-check expect status 200
server-template api 4 api:8080 check inter 1s fall 2 rise 2 resolvers docker init-addr none
+16
View File
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<policymap>
<policy domain="resource" name="thread" value="1"/>
<policy domain="resource" name="memory" value="256MiB"/>
<policy domain="resource" name="map" value="256MiB"/>
<policy domain="resource" name="disk" value="512MiB"/>
<policy domain="resource" name="time" value="45"/>
<policy domain="resource" name="list-length" value="2"/>
<policy domain="delegate" rights="none" pattern="*"/>
<policy domain="filter" rights="none" pattern="*"/>
<policy domain="path" rights="none" pattern="@*"/>
<policy domain="module" rights="none" pattern="*"/>
<policy domain="module" rights="read | write" pattern="{JPEG,PNG,WEBP}"/>
<policy domain="coder" rights="none" pattern="*"/>
<policy domain="coder" rights="read | write" pattern="{JPEG,JPG,PNG,WEBP}"/>
</policymap>
+11 -4
View File
@@ -1,7 +1,14 @@
# Конфигурация наблюдаемости — реализовать
# Конфигурация наблюдаемости
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
`collector.yaml` принимает OTLP/HTTP от API, relay и worker и отправляет
сигналы в Prometheus, Loki и Tempo. `prometheus.yaml` настраивает сбор
метрик приложения и самого Collector. `alerts.yaml` содержит два правила
с последовательностью диагностики в [runbook](runbook.md).
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
`grafana/provisioning` подключает три источника и регистрирует dashboard
[Messenger observability](grafana/dashboards/messenger.json). JSON можно
импортировать в Grafana, где доступны те же UID источников. Compose
публикует интерфейсы чтения только на loopback. Приёмник OTLP и scrape
endpoints находятся во внутренней сети.
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
Команды запуска и описание метрик приведены в [отчёте](../../REPORT.md).
+27
View File
@@ -0,0 +1,27 @@
groups:
- name: messenger
rules:
- alert: HighAPIErrorRate
expr: |
(
sum(rate(messenger_http_requests_total{route!~"/health/(live|ready)",status_class="5xx"}[30s]))
/ clamp_min(sum(rate(messenger_http_requests_total{route!~"/health/(live|ready)"}[30s])), 0.001)
) > 0.10
and sum(increase(messenger_http_requests_total{route!~"/health/(live|ready)"}[30s])) >= 5
for: 15s
labels:
severity: warning
annotations:
summary: Business API 5xx ratio above 10 percent
runbook: See infra/otel/runbook.md, PostgreSQL degradation.
- alert: GrowingQueueLag
expr: |
max by (queue) (messenger_queue_oldest_age_seconds) > 15
and on (queue) max by (queue) (messenger_queue_depth) >= 1
and on (queue) min by (queue) (messenger_queue_sample_age_seconds) < 8
for: 15s
labels:
severity: warning
annotations:
summary: A durable queued job has waited longer than 15 seconds
runbook: See infra/otel/runbook.md, stopped worker.
+68
View File
@@ -0,0 +1,68 @@
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
processors:
memory_limiter:
check_interval: 1s
limit_mib: 96
spike_limit_mib: 24
batch:
timeout: 1s
send_batch_size: 64
send_batch_max_size: 128
exporters:
prometheus:
endpoint: 0.0.0.0:9464
metric_expiration: 1m
resource_to_telemetry_conversion:
enabled: true
otlphttp/loki:
endpoint: http://loki:3100/otlp
timeout: 2s
sending_queue:
enabled: true
num_consumers: 1
queue_size: 16
retry_on_failure:
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 5s
otlphttp/tempo:
endpoint: http://tempo:4318
timeout: 2s
sending_queue:
enabled: true
num_consumers: 1
queue_size: 16
retry_on_failure:
initial_interval: 1s
max_interval: 2s
max_elapsed_time: 5s
service:
telemetry:
metrics:
readers:
- pull:
exporter:
prometheus:
host: 0.0.0.0
port: 8888
without_units: true
pipelines:
metrics:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [prometheus]
traces:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/tempo]
logs:
receivers: [otlp]
processors: [memory_limiter, batch]
exporters: [otlphttp/loki]
@@ -0,0 +1,572 @@
{
"id": null,
"uid": "lab6-messenger",
"title": "Messenger observability",
"tags": [
"lab6"
],
"timezone": "browser",
"schemaVersion": 39,
"version": 1,
"refresh": "5s",
"time": {
"from": "now-15m",
"to": "now"
},
"panels": [
{
"id": 1,
"type": "timeseries",
"title": "API requests per second",
"description": "Per-second rate across both API replicas, excluding health checks. Window 1 minute.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "reqps",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum(rate(messenger_http_requests_total{route!~\"/health/(live|ready)\"}[1m]))",
"legendFormat": "All business requests"
},
{
"refId": "B",
"expr": "sum(rate(messenger_http_requests_total{route!~\"/health/(live|ready)\",status_class=\"5xx\"}[1m]))",
"legendFormat": "5xx"
}
]
},
{
"id": 2,
"type": "timeseries",
"title": "API error ratio",
"description": "Server errors divided by all business responses. An empty window has no ratio.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 0
},
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0,
"max": 1
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "(sum(rate(messenger_http_requests_total{route!~\"/health/(live|ready)\",status_class=\"5xx\"}[1m])) or 0 * sum(rate(messenger_http_requests_total{route!~\"/health/(live|ready)\"}[1m]))) / (sum(rate(messenger_http_requests_total{route!~\"/health/(live|ready)\"}[1m])) > 0)",
"legendFormat": "5xx / requests"
}
]
},
{
"id": 3,
"type": "timeseries",
"title": "API response duration",
"description": "p50, p95 and p99 from cumulative histogram buckets, aggregated across replicas.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route!~\"/health/(live|ready)\"}[1m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route!~\"/health/(live|ready)\"}[1m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_request_duration_seconds_bucket{route!~\"/health/(live|ready)\"}[1m])))",
"legendFormat": "p99"
}
]
},
{
"id": 4,
"type": "timeseries",
"title": "Worker job outcomes per second",
"description": "Rate of actual attempts, grouped by outcome. Duplicate deliveries without a claim are not attempts.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 7
},
"fieldConfig": {
"defaults": {
"unit": "ops",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (outcome) (rate(messenger_jobs_total[1m]))",
"legendFormat": "{{outcome}}"
}
]
},
{
"id": 5,
"type": "timeseries",
"title": "Worker processing duration",
"description": "p50, p95 and p99 from the duration histogram for claimed attempts.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_job_duration_seconds_bucket[1m])))",
"legendFormat": "p99"
}
]
},
{
"id": 6,
"type": "timeseries",
"title": "Attachment time to ready",
"description": "From durable job creation to the commit that exposes ready. Includes time queued and any retries.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 14
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p50"
},
{
"refId": "B",
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p95"
},
{
"refId": "C",
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_attachment_time_to_ready_seconds_bucket[1m])))",
"legendFormat": "p99"
}
]
},
{
"id": 7,
"type": "timeseries",
"title": "Queue depth",
"description": "Durable queued jobs on the current pipeline version, including pending outbox and delayed retries.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "max by (queue) (messenger_queue_depth)",
"legendFormat": "{{queue}}"
}
]
},
{
"id": 8,
"type": "timeseries",
"title": "Oldest queued job age",
"description": "Elapsed time since the oldest job still in the durable queue was accepted.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 21
},
"fieldConfig": {
"defaults": {
"unit": "s",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "max by (queue) (messenger_queue_oldest_age_seconds)",
"legendFormat": "{{queue}}"
}
]
},
{
"id": 9,
"type": "timeseries",
"title": "PostgreSQL pool used and capacity",
"description": "Checked-out connections and configured pool capacity, summed per service.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 28
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name,state) (messenger_db_pool_connections)",
"legendFormat": "{{service_name}} / {{state}}"
}
]
},
{
"id": 10,
"type": "timeseries",
"title": "PostgreSQL pool waiting",
"description": "Acquisition calls in progress. Instantaneous gauge, so very short waits can fall between scrapes.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 28
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum by (service_name) (messenger_db_pool_waiting)",
"legendFormat": "{{service_name}}"
}
]
},
{
"id": 11,
"type": "timeseries",
"title": "Worker busy and capacity",
"description": "Active claimed jobs and total processing lanes.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 35
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum(messenger_worker_busy)",
"legendFormat": "Busy"
},
{
"refId": "B",
"expr": "sum(messenger_worker_capacity)",
"legendFormat": "Capacity"
}
]
},
{
"id": 12,
"type": "timeseries",
"title": "Worker saturation",
"description": "Fraction of processing lanes occupied by claimed attempts.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 35
},
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"min": 0,
"max": 1
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "sum(messenger_worker_busy) / (sum(messenger_worker_capacity) > 0)",
"legendFormat": "Busy / capacity"
}
]
},
{
"id": 13,
"type": "timeseries",
"title": "Process CPU",
"description": "CPU seconds per wall second. 1.0 is one full CPU core.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 42
},
"fieldConfig": {
"defaults": {
"unit": "none",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "rate(messenger_process_cpu_time_seconds_total[1m])",
"legendFormat": "{{service_name}} / {{service_instance_id}}"
}
]
},
{
"id": 14,
"type": "timeseries",
"title": "Process resident memory",
"description": "RSS per application process, read from Linux statm.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 42
},
"fieldConfig": {
"defaults": {
"unit": "bytes",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "messenger_process_memory_bytes",
"legendFormat": "{{service_name}} / {{service_instance_id}}"
}
]
},
{
"id": 15,
"type": "timeseries",
"title": "Firing alerts",
"description": "Firing state reported by Prometheus. Inactive rules disappear from this series.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 0,
"y": 49
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "ALERTS{alertname=~\"HighAPIErrorRate|GrowingQueueLag\",alertstate=\"firing\"}",
"legendFormat": "{{alertname}} {{queue}}"
}
]
},
{
"id": 16,
"type": "timeseries",
"title": "Collector exporter queue",
"description": "Batches pending delivery to telemetry storage and the configured queue limit.",
"datasource": {
"type": "prometheus",
"uid": "lab-prometheus"
},
"gridPos": {
"h": 7,
"w": 12,
"x": 12,
"y": 49
},
"fieldConfig": {
"defaults": {
"unit": "short",
"min": 0
},
"overrides": []
},
"targets": [
{
"refId": "A",
"expr": "otelcol_exporter_queue_size",
"legendFormat": "{{exporter}} queued"
},
{
"refId": "B",
"expr": "otelcol_exporter_queue_capacity",
"legendFormat": "{{exporter}} capacity"
}
]
},
{
"id": 17,
"type": "logs",
"title": "Correlated API and worker logs",
"description": "Expand a log line and follow its TraceID to Tempo.",
"datasource": {
"type": "loki",
"uid": "lab-loki"
},
"gridPos": {
"h": 9,
"w": 24,
"x": 0,
"y": 56
},
"targets": [
{
"refId": "A",
"expr": "{service_name=~\"messenger-api|messenger-worker\"}"
}
],
"options": {
"showTime": true,
"sortOrder": "Descending",
"wrapLogMessage": false
}
}
]
}
@@ -0,0 +1,9 @@
apiVersion: 1
providers:
- name: Messenger
orgId: 1
folder: Lab 6
type: file
updateIntervalSeconds: 10
options:
path: /var/lib/grafana/dashboards
@@ -0,0 +1,38 @@
apiVersion: 1
datasources:
- name: Prometheus
uid: lab-prometheus
type: prometheus
access: proxy
url: http://prometheus:9090
isDefault: true
editable: false
jsonData:
timeInterval: 5s
- name: Loki
uid: lab-loki
type: loki
access: proxy
url: http://loki:3100
editable: false
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"trace_id":"([0-9a-f]{32})"'
datasourceUid: lab-tempo
url: '$${__value.raw}'
- name: Tempo
uid: lab-tempo
type: tempo
access: proxy
url: http://tempo:3200
editable: false
jsonData:
tracesToLogsV2:
datasourceUid: lab-loki
spanStartTimeShift: -30s
spanEndTimeShift: 30s
tags:
- key: service.name
value: service_name
filterByTraceID: true
+30
View File
@@ -0,0 +1,30 @@
auth_enabled: false
server:
http_listen_port: 3100
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
compactor:
working_directory: /loki/compactor
retention_enabled: true
delete_request_store: filesystem
limits_config:
allow_structured_metadata: true
retention_period: 24h
+13
View File
@@ -0,0 +1,13 @@
global:
scrape_interval: 5s
evaluation_interval: 5s
rule_files: [/etc/prometheus/alerts.yaml]
scrape_configs:
- job_name: messenger-otlp
static_configs:
- targets: [otel-collector:9464]
- job_name: otel-collector
static_configs:
- targets: [otel-collector:8888]
+69
View File
@@ -0,0 +1,69 @@
# Диагностика ЛР 6
Команды рассчитаны на локальный стенд с синтетическими данными. Выполняйте
сценарии по одному. После остальных проверок запустите автоматическую приёмку
с тестовым Compose override по [инструкции](../../student-tests/lab6/README.md).
## Где смотреть
- [Dashboard Messenger](http://127.0.0.1:3006/d/lab6-messenger) показывает историю
HTTP, worker, очереди, пула, CPU/RAM и доступные логи.
- [Правила Prometheus](http://127.0.0.1:9096/alerts) показывают состояние каждого
алерта. Переход `firing → inactive` означает, что условие сбросилось.
- В Grafana Explore выберите Loki. По ответу API и его `X-Request-Id` найдите
запись `{service_name="messenger-api"} | json | request_id="<id>"`.
В записи откройте поле `TraceID` или вставьте значение `trace_id` в поиск Tempo.
- В Tempo проверьте дочерние операции `postgres.query`, `postgres.acquire`
и `s3.get`/`s3.put`. Для worker используйте
`{service_name="messenger-worker"} | json | trace_id="<id>"` в Loki.
## PostgreSQL degradation
1. Создайте синтетического пользователя и получите сессию, пока БД отвечает.
2. В отдельном терминале откройте сессию
`docker compose exec -it postgres psql -U messenger -d messenger`. Выполните:
```sql
BEGIN;
LOCK TABLE public.users IN ACCESS EXCLUSIVE MODE;
```
3. Не закрывая транзакцию, 45 секунд посылайте небольшим постоянным потоком
авторизованные `GET /api/v1/users/me`. Проверьте `/health/ready` параллельно.
Если LB доступен, запросы с ошибкой и здоровая readiness указывают на
проблему внутри рабочего пути. `HighAPIErrorRate` должен стать `firing`.
4. Найдите по `X-Request-Id` структурный лог ответа и откройте трассу. Проверьте
длительность и ошибку дочернего чтения `postgres.query` с операцией
`GetUserByID`. CPU и pool gauges помогают отличить блокировку от насыщения.
5. В том же терминале PostgreSQL выполните `ROLLBACK;`. Продолжайте делать
успешные запросы до опустошения 30-секундного окна и сброса алерта.
## Stopped worker
1. Выполните `docker compose stop worker`. Оставьте RabbitMQ, relay, DB и API
включёнными.
2. Через публичный API загрузите три исправных небольших PNG в свой чат.
Ожидайте `202 Accepted`, рост `messenger_queue_depth` и возраста самой
старой задачи. Подождите, пока `GrowingQueueLag` станет `firing`.
3. В Tempo найдите producer. Пока worker остановлен, за producer для этих
задач ещё нет consumer spans. Проверьте также состояние worker в Compose.
4. Выполните `docker compose start worker`. Убедитесь, что все три вложения
стали `ready`, глубина и возраст вернулись к нулю, а алерт стал `inactive`.
## Остановка Loki
1. Запишите текущее значение `otelcol_exporter_send_failed_log_records_total`
и `otelcol_exporter_enqueue_failed_log_records_total` для
`exporter="otlphttp/loki"` в Prometheus. Отсутствующий счётчик до первой
ошибки считайте нулём.
2. Выполните `docker compose stop loki`. Проверьте readiness, проведите серию
синтетических записей и прочитайте их через API. Сохраните максимум
`otelcol_exporter_queue_size`, вместимость
`otelcol_exporter_queue_capacity` для Loki и
`otelcol_process_memory_rss` за время опыта.
3. Выполните `docker compose start loki`. Дождитесь `/ready` на порту 3106.
Отправьте новый рабочий запрос, найдите его в Loki по `X-Request-Id`.
Сравните счётчики после обработки очереди и проверьте, что Collector
сохранил тот же контейнер без рестарта. `send_failed` и `enqueue_failed`
считают записи в разных точках, первая величина относится к уже принятым
экспортёром пачкам, вторая к записям, которые экспортёр не принял.
+18
View File
@@ -0,0 +1,18 @@
server:
http_listen_port: 3200
distributor:
receivers:
otlp:
protocols:
http:
endpoint: 0.0.0.0:4318
compactor:
compaction:
block_retention: 24h
storage:
trace:
backend: local
local:
path: /var/tempo/blocks
wal:
path: /var/tempo/wal
+65
View File
@@ -0,0 +1,65 @@
#!/bin/sh
set -eu
for name in rustfs_root_access_key rustfs_root_secret_key s3_access_key_id s3_secret_access_key; do
if [ ! -s "/run/secrets/$name" ]; then
echo "missing S3 secret: $name" >&2
exit 1
fi
done
root_key=$(cat /run/secrets/rustfs_root_access_key)
root_secret=$(cat /run/secrets/rustfs_root_secret_key)
app_key=$(cat /run/secrets/s3_access_key_id)
app_secret=$(cat /run/secrets/s3_secret_access_key)
if [ "$root_key" = "$app_key" ]; then
echo 'API and RustFS root access keys must differ' >&2
exit 1
fi
# These values become path and JSON fragments below.
case "$S3_BUCKET" in
messenger-attachments) ;;
*) echo 'unsupported S3_BUCKET in bootstrap' >&2; exit 1 ;;
esac
rc=/usr/bin/rc
policy=messenger-attachments-api-v1
"$rc" alias set root http://s3:9000 "$root_key" "$root_secret" \
--region "$S3_REGION" --bucket-lookup path >/dev/null
"$rc" bucket create "root/$S3_BUCKET" --ignore-existing
# A new bucket is private by default; this also removes a stale public policy.
"$rc" bucket anonymous set private "root/$S3_BUCKET"
cat > /tmp/api-policy.json <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
"Resource": "arn:aws:s3:::$S3_BUCKET"
},
{
"Effect": "Allow",
"Action": ["s3:PutObject", "s3:GetObject", "s3:DeleteObject"],
"Resource": "arn:aws:s3:::$S3_BUCKET/*"
}
]
}
EOF
if ! "$rc" admin policy info root/ "$policy" >/dev/null 2>&1; then
"$rc" admin policy create root/ "$policy" /tmp/api-policy.json
fi
if ! "$rc" admin user info root/ "$app_key" >/dev/null 2>&1; then
"$rc" admin user add root/ "$app_key" "$app_secret" >/dev/null
fi
"$rc" admin policy attach root/ "$policy" --user "$app_key" >/dev/null
"$rc" alias set app http://s3:9000 "$app_key" "$app_secret" \
--region "$S3_REGION" --bucket-lookup path >/dev/null
"$rc" bucket list "app/$S3_BUCKET" >/dev/null
echo "S3 bucket and API identity ready: $S3_BUCKET"