forked from mtusi2026/mtusi2026lab5
ЛР 5 — БВТ2301 — Курлова — на 5
RabbitMQ + transactional outbox, отдельный worker (thumbnail/crop/WebP), lease и heartbeat, retry с backoff+jitter, DLQ и replay, admission control; тесты отказов, трек 1 и отчёт.
This commit is contained in:
+7
-3
@@ -1,7 +1,11 @@
|
||||
# Инфраструктура студента
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
Основная топология — корневой [compose.yaml](../compose.yaml) (Compose v2). `compose.example.yaml` — только worksheet ролей.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
| Каталог | Что внутри |
|
||||
| --- | --- |
|
||||
| [nginx.conf](nginx.conf), [nginx-health.sh](nginx-health.sh) | LB перед двумя API-репликами, активная проверка `/health/ready` (из lab3/lab4) |
|
||||
| [minio/](minio/) | идемпотентный bootstrap приватного bucket и пользователя приложения; политика `attachments/*` + `staging/*` |
|
||||
| [rabbitmq/](rabbitmq/) | `rabbitmq.conf` (consumer_timeout, disk/memory alarms) и entrypoint, который берёт пароль из Docker secret |
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
Топология брокера (exchange, quorum-очереди, DLX/DLQ) объявляется кодом идемпотентно при каждом подключении API и worker ([app/broker.py](../app/broker.py)), отдельного bootstrap-шага нет. Повторный запуск `docker compose up` безопасен: миграции пропускают применённые версии с проверкой checksum, `minio-init` использует `--ignore-existing`, объявление очередей с теми же аргументами — no-op.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments/attachments/*", "arn:aws:s3:::messenger-attachments/staging/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket", "s3:GetBucketLocation"],
|
||||
"Resource": ["arn:aws:s3:::messenger-attachments"]
|
||||
}
|
||||
]
|
||||
}
|
||||
Executable
+19
@@ -0,0 +1,19 @@
|
||||
#!/bin/sh
|
||||
# Idempotent: safe to run on every `compose up`. Root credentials are used only here, never by the API.
|
||||
set -eu
|
||||
BUCKET="${S3_BUCKET:-messenger-attachments}"
|
||||
ROOT_USER="$(cat /run/secrets/minio_root_user)"
|
||||
ROOT_PASSWORD="$(cat /run/secrets/minio_root_password)"
|
||||
APP_USER="$(cat /run/secrets/s3_access_key_id)"
|
||||
APP_PASSWORD="$(cat /run/secrets/s3_secret_access_key)"
|
||||
|
||||
until mc alias set local http://minio:9000 "$ROOT_USER" "$ROOT_PASSWORD" >/dev/null 2>&1; do
|
||||
echo "waiting for minio"; sleep 2
|
||||
done
|
||||
mc mb --ignore-existing "local/$BUCKET"
|
||||
mc anonymous set none "local/$BUCKET"
|
||||
mc admin policy create local app-attachments /etc/minio-policy/app-policy.json 2>/dev/null \
|
||||
|| mc admin policy create local app-attachments /etc/minio-policy/app-policy.json --overwrite 2>/dev/null || true
|
||||
mc admin user add local "$APP_USER" "$APP_PASSWORD" 2>/dev/null || true
|
||||
mc admin policy attach local app-attachments --user "$APP_USER" 2>/dev/null || true
|
||||
echo "minio bootstrap complete: bucket=$BUCKET private, app user limited to attachments/*"
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/bin/sh
|
||||
set -u
|
||||
|
||||
SERVERS="${API_UPSTREAMS:-api-1 api-2}"
|
||||
INTERVAL="${HEALTH_INTERVAL:-1}"
|
||||
FALL="${HEALTH_FALL:-2}"
|
||||
RISE="${HEALTH_RISE:-2}"
|
||||
OUT=/etc/nginx/upstream/servers.conf
|
||||
|
||||
mkdir -p "$(dirname "$OUT")"
|
||||
|
||||
var() { echo "$1" | tr -c 'a-zA-Z0-9\n' '_'; }
|
||||
|
||||
render() {
|
||||
any_up=0
|
||||
for s in $SERVERS; do
|
||||
eval "[ \"\$up_$(var "$s")\" = 1 ]" && any_up=1
|
||||
done
|
||||
for s in $SERVERS; do
|
||||
mark=""
|
||||
if [ "$any_up" = 1 ] && eval "[ \"\$up_$(var "$s")\" = 0 ]"; then
|
||||
mark=" down"
|
||||
fi
|
||||
echo "server $s:8080 resolve max_fails=1 fail_timeout=10s$mark;"
|
||||
done
|
||||
}
|
||||
|
||||
for s in $SERVERS; do
|
||||
v=$(var "$s")
|
||||
eval "up_$v=1 ok_$v=0 bad_$v=0"
|
||||
done
|
||||
render > "$OUT"
|
||||
|
||||
watch() {
|
||||
pending=0
|
||||
while sleep "$INTERVAL"; do
|
||||
changed=0
|
||||
for s in $SERVERS; do
|
||||
v=$(var "$s")
|
||||
if wget -q -T 1 -O /dev/null "http://$s:8080/health/ready" 2>/dev/null; then
|
||||
eval "ok_$v=\$((ok_$v + 1)) bad_$v=0"
|
||||
if eval "[ \"\$up_$v\" = 0 ] && [ \"\$ok_$v\" -ge $RISE ]"; then
|
||||
eval "up_$v=1"; changed=1; echo "health: $s ready, back in upstream"
|
||||
fi
|
||||
else
|
||||
eval "bad_$v=\$((bad_$v + 1)) ok_$v=0"
|
||||
if eval "[ \"\$up_$v\" = 1 ] && [ \"\$bad_$v\" -ge $FALL ]"; then
|
||||
eval "up_$v=0"; changed=1; echo "health: $s not ready, marked down"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
if [ "$changed" = 1 ]; then
|
||||
render > "$OUT"
|
||||
pending=1
|
||||
fi
|
||||
if [ "$pending" = 1 ] && nginx -s reload 2>/dev/null; then
|
||||
pending=0
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
watch &
|
||||
exec nginx -g 'daemon off;'
|
||||
@@ -0,0 +1,75 @@
|
||||
worker_processes 2;
|
||||
|
||||
events {
|
||||
worker_connections 256;
|
||||
}
|
||||
|
||||
http {
|
||||
resolver 127.0.0.11 valid=5s ipv6=off;
|
||||
|
||||
upstream api {
|
||||
zone api 64k;
|
||||
include /etc/nginx/upstream/servers.conf;
|
||||
keepalive 32;
|
||||
keepalive_timeout 4s;
|
||||
}
|
||||
|
||||
log_format main '$remote_addr - $upstream_addr [$time_local] '
|
||||
'"$request" $status $body_bytes_sent '
|
||||
'"$upstream_response_time" "$request_time"';
|
||||
|
||||
access_log /var/log/nginx/access.log main;
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
client_max_body_size 64k;
|
||||
error_page 413 @payload_too_large;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
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_connect_timeout 1s;
|
||||
proxy_read_timeout 30s;
|
||||
proxy_send_timeout 30s;
|
||||
proxy_next_upstream_tries 2;
|
||||
proxy_next_upstream_timeout 5s;
|
||||
|
||||
location ~ ^/api/v1/chats/[^/]+/messages$ {
|
||||
proxy_pass http://api;
|
||||
proxy_next_upstream error timeout http_502 http_503 non_idempotent;
|
||||
}
|
||||
|
||||
location ~ ^/api/v1/chats/[^/]+/attachments$ {
|
||||
client_max_body_size 10m;
|
||||
proxy_request_buffering off;
|
||||
proxy_pass http://api;
|
||||
proxy_next_upstream off;
|
||||
}
|
||||
|
||||
location @payload_too_large {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header X-Instance-Id lb always;
|
||||
add_header Connection close always;
|
||||
return 413 '{"error":{"code":"payload_too_large","message":"Тело запроса слишком большое","request_id":"$request_id"}}';
|
||||
}
|
||||
|
||||
location /health/ {
|
||||
proxy_pass http://api;
|
||||
proxy_next_upstream error timeout;
|
||||
}
|
||||
|
||||
location ~ ^/api/v1/attachments/ {
|
||||
proxy_max_temp_file_size 0;
|
||||
proxy_pass http://api;
|
||||
proxy_next_upstream error timeout;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://api;
|
||||
proxy_next_upstream error timeout http_502 http_503;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# Credentials come from a Docker secret; RabbitMQ's config cannot read files, so render a conf.d fragment at start.
|
||||
set -eu
|
||||
PASS="$(cat /run/secrets/rabbitmq_password)"
|
||||
mkdir -p /etc/rabbitmq/conf.d
|
||||
cat > /etc/rabbitmq/conf.d/20-credentials.conf <<CONF
|
||||
default_user = messenger
|
||||
default_pass = ${PASS}
|
||||
default_vhost = messenger
|
||||
default_permissions.configure = .*
|
||||
default_permissions.read = .*
|
||||
default_permissions.write = .*
|
||||
CONF
|
||||
exec docker-entrypoint.sh rabbitmq-server
|
||||
@@ -0,0 +1,10 @@
|
||||
# Durable broker for the attachment pipeline (see REPORT.md).
|
||||
loopback_users.guest = true
|
||||
listeners.tcp.default = 5672
|
||||
# A delivery not acked for 10 min is returned to the queue (worker hang guard on the broker side;
|
||||
# the application lease in PostgreSQL detects a hung job much earlier).
|
||||
consumer_timeout = 600000
|
||||
# Refuse publishes before the disk fills up (publisher sees the block and the outbox keeps the jobs).
|
||||
disk_free_limit.absolute = 200MB
|
||||
vm_memory_high_watermark.relative = 0.6
|
||||
log.console.level = warning
|
||||
Reference in New Issue
Block a user