forked from mtusi2026/mtusi2026lab4
Реализовать lab4 на оценку 4: SeaweedFS, вложения и согласованность БД/S3.
Перенесён стенд lab3 (API, Redis-сессии, идемпотентность, HAProxy, реплики API). Добавлены приватный bucket SeaweedFS с отдельным ключом API, загрузка PNG/JPEG с лимитами и полной проверкой, компенсация и reconciler, плавная остановка API, тесты и evidence.
This commit is contained in:
+12
-5
@@ -1,7 +1,14 @@
|
||||
# Инфраструктура студента
|
||||
# Инфраструктура lab4
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
- `haproxy.cfg` — публичный балансировщик (`127.0.0.1:8080`, `balance leastconn`).
|
||||
- Новый запрос уходит на реплику с наименьшим числом открытых соединений. Загрузка вложения держит соединение секунды, поэтому длинные upload не скапливаются на одной реплике, пока у другой свободны слоты. При равной нагрузке (короткие последовательные запросы) реплики чередуются, как при round-robin.
|
||||
- Основной backend `messenger_api` проверяет `/health/ready` (БД + Redis + S3): неготовая реплика исключается из трафика.
|
||||
- Если не готова ни одна реплика (общая зависимость недоступна), трафик идёт в `messenger_api_degraded`, который проверяет только `/health/live`. Клиент получает JSON 503 самого API на затронутых endpoint, а текстовый чат и метаданные продолжают работать.
|
||||
- Ошибки, сгенерированные самим HAProxy (502/503/504), оформлены в контрактном JSON-конверте с `X-Request-Id` и `X-Instance-Id: lb`.
|
||||
- DNS Docker `127.0.0.11` + `server-template` подхватывают `--scale api=N` и замену контейнеров.
|
||||
- `inter 1s fall 2` + `observe layer4 … on-error mark-down`: остановленная реплика исключается после первой неудачной попытки подключения или примерно через 2–3 с по health check. При `docker stop` реплика API по SIGTERM сначала отвечает 503 только на `/health/ready` и ещё 3 с (`SHUTDOWN_DRAIN_SECONDS`) обслуживает запросы, поэтому HAProxy исключает её раньше, чем она закроет listener. `timeout connect 1s` + `option redispatch 1`: запрос, не дошедший до мёртвой реплики, уходит на другую. POST повторно не отправляется: повтор возможен только на этапе connect, когда запрос ещё не передан.
|
||||
- Размер тела в HAProxy не ограничен: 10 MiB + 1 байт отклоняет API (JSON 413). `tune.*buf` фиксирует сокетные буферы, чтобы пачка загрузок не довела LB (128m) до OOM.
|
||||
- `s3-gateway.cfg` — TCP-сайдкар `s3-gw` в сетевом namespace `s3`: наружу (только в internal-сеть `storage`) отдаёт один S3 HTTP API как `s3:9000`. Master/filer/volume/gRPC SeaweedFS слушают только `127.0.0.1` внутри контейнера.
|
||||
- `s3-gw-entrypoint.sh` — entrypoint `s3-gw`: запускает HAProxy и раз в 2 с проверяет, что namespace `s3` жив. После падения или `docker restart` контейнера `s3` в старом namespace остаётся только `lo`. Тогда скрипт через 5 с завершает контейнер, и `restart: unless-stopped` запускает `s3-gw` уже в namespace нового `s3`. У `s3` и `s3-gw`, как у `api`, `lb`, `postgres` и `redis`, стоит `restart: unless-stopped`; у one-shot `migrate` и `s3-init` политики нет. Скрипт монтируется в Linux-контейнер, поэтому `.gitattributes` держит `*.sh` в LF и на Windows.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
Конфиги примонтированы как файлы, поэтому после правки `haproxy.cfg` нужен `docker compose --env-file .env restart lb`. `up -d` не пересоздаёт LB, если не изменился сам `compose.yaml`.
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# Lab4 load balancer: leastconn across Compose DNS name "api" (all replicas).
|
||||
# Uploads hold a connection for seconds, so new requests go to the replica with the
|
||||
# fewest open connections (equal load still rotates, like round-robin).
|
||||
global
|
||||
maxconn 2048
|
||||
log stdout format raw local0
|
||||
# Fixed socket buffers: a burst of 10 MiB uploads must not grow kernel buffers
|
||||
# (charged to this container's 128m cgroup) until the OOM killer stops the LB.
|
||||
tune.rcvbuf.client 262144
|
||||
tune.sndbuf.client 262144
|
||||
tune.rcvbuf.server 262144
|
||||
tune.sndbuf.server 262144
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
option httplog
|
||||
option dontlognull
|
||||
# A stopped replica's IP vanishes and connects to it hang instead of being refused;
|
||||
# on the local bridge a real connect takes milliseconds, so fail over after 1s.
|
||||
timeout connect 1s
|
||||
timeout client 30s
|
||||
# After the body is forwarded the API may still verify the image and write to S3
|
||||
# (bounded at ≈35 s in the worst case: decode 15 s + S3 ≈15 s + DB 6 s).
|
||||
timeout server 45s
|
||||
timeout check 1500ms
|
||||
timeout http-request 10s
|
||||
retries 2
|
||||
# Connect-level retries go to another replica (request not sent yet, safe for POST).
|
||||
option redispatch 1
|
||||
# LB-generated errors use the API error envelope and carry the contract headers.
|
||||
unique-id-format %[uuid()]
|
||||
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Bad gateway","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr X-Instance-Id lb
|
||||
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"No API replica available","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr X-Instance-Id lb
|
||||
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Gateway timeout","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr X-Instance-Id lb
|
||||
|
||||
resolvers docker
|
||||
nameserver dns1 127.0.0.11:53
|
||||
resolve_retries 3
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 5s
|
||||
hold obsolete 10s
|
||||
|
||||
frontend messenger_fe
|
||||
bind *:8080
|
||||
acl is_lb_live path /__lb/live
|
||||
http-request return status 200 content-type text/plain string ok if is_lb_live
|
||||
# Normal routing uses readiness. If NO replica is ready (shared dependency down:
|
||||
# PostgreSQL, Redis or S3), live replicas still answer so clients get the API's
|
||||
# own JSON 503 for affected endpoints and unaffected ones keep working.
|
||||
use_backend messenger_api_degraded if { nbsrv(messenger_api) lt 1 }
|
||||
default_backend messenger_api
|
||||
|
||||
backend messenger_api
|
||||
balance leastconn
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/ready ver HTTP/1.1 hdr Host api
|
||||
http-check expect status 200
|
||||
# server-template expands A records for Compose service DNS name "api".
|
||||
# inter=1s fall=2 → ≈2–3s to mark a backend down after failed checks; a failed
|
||||
# live connect marks it down at once (observe layer4).
|
||||
server-template api 8 api:8080 check inter 1s fall 2 rise 1 observe layer4 error-limit 1 on-error mark-down resolvers docker resolve-prefer ipv4 init-addr none
|
||||
|
||||
backend messenger_api_degraded
|
||||
balance leastconn
|
||||
option httpchk
|
||||
http-check send meth GET uri /health/live ver HTTP/1.1 hdr Host api
|
||||
http-check expect status 200
|
||||
server-template live 8 api:8080 check inter 1s fall 2 rise 1 observe layer4 error-limit 1 on-error mark-down resolvers docker resolve-prefer ipv4 init-addr none
|
||||
@@ -0,0 +1,22 @@
|
||||
# S3 gateway sidecar (lab4). Runs in the network namespace of the `s3` service:
|
||||
# SeaweedFS listens on 127.0.0.1 only, this proxy publishes just the S3 HTTP API
|
||||
# as s3:9000 on the internal `storage` network. Master/volume/filer UIs and the
|
||||
# unauthenticated gRPC ports (1xxxx) stay unreachable from other containers.
|
||||
global
|
||||
maxconn 512
|
||||
log stdout format raw local0
|
||||
|
||||
defaults
|
||||
mode tcp
|
||||
log global
|
||||
option tcplog
|
||||
timeout connect 3s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
|
||||
frontend s3_api
|
||||
bind *:9000
|
||||
default_backend seaweed_s3
|
||||
|
||||
backend seaweed_s3
|
||||
server s3 127.0.0.1:8333
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
# s3-gw shares the network namespace of the `s3` container. When s3 restarts (crash,
|
||||
# `docker restart`, Docker daemon restart) it gets a NEW namespace and this one is left
|
||||
# with only `lo`: HAProxy keeps running but nothing can reach it. Exit in that case so
|
||||
# the restart policy starts s3-gw again inside the current namespace of s3.
|
||||
haproxy -W -db -f /usr/local/etc/haproxy/haproxy.cfg &
|
||||
pid=$!
|
||||
trap 'kill -TERM "$pid" 2>/dev/null' TERM INT USR1
|
||||
|
||||
orphaned() {
|
||||
# /proc/net/dev: two header lines (with '|') and one line per interface.
|
||||
! grep -qv -e '^ *lo:' -e '|' /proc/net/dev
|
||||
}
|
||||
|
||||
while kill -0 "$pid" 2>/dev/null; do
|
||||
if orphaned; then
|
||||
echo "s3-gw: network namespace of s3 is gone; exiting so the restart policy re-joins it" >&2
|
||||
kill -TERM "$pid" 2>/dev/null
|
||||
wait "$pid"
|
||||
# Docker does not retry a start that fails because s3 is not running yet:
|
||||
# give the restart policy of s3 time to bring it back first.
|
||||
sleep 5
|
||||
exit 1
|
||||
fi
|
||||
sleep 2 &
|
||||
wait $!
|
||||
done
|
||||
wait "$pid"
|
||||
Reference in New Issue
Block a user