Files

88 lines
5.4 KiB
INI
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# HAProxy 3.0 — единственная публичная точка входа lab3.
# Бэкенды находятся через DNS Docker (имя сервиса `api` → IP всех реплик), без sticky sessions.
#
# Обнаружение отказа реплики:
# * активная проверка GET /health/ready: inter 1s, после первой ошибки fastinter 500ms, fall 2,
# timeout check 300ms → худший случай обнаружения ≈ 1 + 0.3 + 0.5 + 0.3 ≈ 2.1 с;
# * пассивно: соединение отвергнуто → retry-on conn-failure + redispatch на другую реплику
# (только если запрос ещё не отправлен — безопасно и для неидемпотентных POST).
# * graceful shutdown реплики: SIGTERM → /health/ready = 503 на SHUTDOWN_DRAIN_SECONDS=3 с
# (> fall × fastinter) → LB выводит реплику до того, как она закроет listener.
global
log stdout format raw local0 info
maxconn 4096
defaults
mode http
log global
option httplog
option dontlognull
timeout connect 300ms # сеть Docker: connect < 1 мс; к «мёртвому» IP (kill) нет RST — ждём не дольше 300 мс
timeout check 300ms # проверка не висит 1 с на убитой реплике → быстрее fall
timeout client 30s
timeout server 15s # > REQUEST_TIMEOUT_SECONDS (10 с) приложения
timeout http-request 10s
timeout http-keep-alive 10s
timeout queue "${LB_QUEUE_TIMEOUT}" # сколько запрос может ждать свободный слот maxconn в очереди LB
retries 2
option redispatch 1
retry-on conn-failure # НЕ empty-response/response-timeout: иначе возможен повтор выполненного POST
unique-id-format %[uuid()] # request_id ответов самого LB: случайный, без IP/портов
default-server inter 1s fastinter 500ms downinter 2s fall 2 rise 2 init-addr none resolvers docker
# Ответы, созданные самим LB, — в формате ошибок API (X-Instance-Id у них нет, это допустимо).
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Нет доступных реплик API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr Retry-After 1
http-error status 502 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Реплика API недоступна","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
http-error status 504 content-type application/json lf-string '{"error":{"code":"unavailable","message":"Таймаут реплики API","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id]
resolvers docker
nameserver dns 127.0.0.11:53
resolve_retries 3
timeout resolve 1s
timeout retry 1s
hold valid 2s
hold obsolete 5s # исчезнувший из DNS контейнер убирается из слота через 5 с
accepted_payload_size 8192
frontend api
bind :8080
# Внутренняя диагностика реплик снаружи недоступна.
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
default_backend api
frontend api_ttl
bind :8081
http-request return status 404 content-type application/json lf-string '{"error":{"code":"not_found","message":"Объект не найден","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] if { path_beg /internal }
default_backend api_ttl
frontend stats
bind :8404
stats enable
stats uri /stats
stats refresh 2s
stats show-legends
backend api
balance roundrobin # без stickiness: состояние не хранится в реплике
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
http-reuse safe
# maxconn: не больше LB_SERVER_MAXCONN одновременных запросов на реплику, излишек ждёт в очереди LB
# (0 = без ограничения). Обоснование значения — трек 5.1 в REPORT.md.
server-template api 8 api:8080 check maxconn "${LB_SERVER_MAXCONN}"
# «Panic mode»: если readiness не проходит НИ У ОДНОЙ реплики (например, упала БД), запросы всё
# равно идут в живые процессы, и клиент получает ответ приложения (401 анониму, 503 unavailable
# в формате API, /health/live = 200), а не безликий 503 LB. Мёртвый процесс → conn-failure → 503 LB.
option allbackups
server-template apibk 8 api:8080 backup resolve-opts allow-dup-ip
backend api_ttl
balance roundrobin
option httpchk
http-check send meth GET uri /health/ready
http-check expect status 200
server-template ttl 2 api-ttl:8080 check
option allbackups
server-template ttlbk 2 api-ttl:8080 backup resolve-opts allow-dup-ip