From 5263d3ec7a6270ddc1a3045c974bc116c9d954b8 Mon Sep 17 00:00:00 2001 From: Pavel Grigorev Date: Thu, 12 Nov 2026 19:45:14 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20=D0=B1=D0=B0=D0=BB=D0=B0=D0=BD=D1=81=D0=B8=D1=80=D0=BE?= =?UTF-8?q?=D0=B2=D1=89=D0=B8=D0=BA=20HAProxy,=20=D0=B4=D0=B2=D0=B5=20?= =?UTF-8?q?=D1=80=D0=B5=D0=BF=D0=BB=D0=B8=D0=BA=D0=B8=20API=20=D0=B8=20?= =?UTF-8?q?=D1=85=D1=83=D0=BA=D0=B8=20=D0=BE=D1=82=D0=BA=D0=B0=D0=B7=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 18 +++-- .gitattributes | 2 + Makefile | 5 +- compose.yaml | 135 ++++++++++++++++++++++++++++++++++++++ infra/haproxy/haproxy.cfg | 53 +++++++++++++++ scripts/init_secrets.py | 27 ++++++++ scripts/restart.cmd | 6 ++ scripts/rolling_update.py | 76 +++++++++++++++++++++ scripts/stop-one.cmd | 11 ++++ 9 files changed, 328 insertions(+), 5 deletions(-) create mode 100644 .gitattributes create mode 100644 compose.yaml create mode 100644 infra/haproxy/haproxy.cfg create mode 100644 scripts/init_secrets.py create mode 100644 scripts/restart.cmd create mode 100644 scripts/rolling_update.py create mode 100644 scripts/stop-one.cmd diff --git a/.env.example b/.env.example index d32b9be0..9379a99d 100644 --- a/.env.example +++ b/.env.example @@ -3,11 +3,21 @@ APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab +APP_SHUTDOWN_TIMEOUT=5 +APP_DRAIN_SECONDS=3 SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. +# Credentials are generated locally by: python scripts/init_secrets.py +# File paths contain no secret values. DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url +# Sessions: PostgreSQL is the source of truth, Valkey is a read-through cache. +CACHE_URL=redis://valkey:6379/0 +SESSION_CACHE_TTL_SECONDS=60 +REVOCATION_SYNC_SECONDS=1 API_REPLICAS=2 IDEMPOTENCY_TTL_SECONDS=86400 +PASSWORD_HASH_CONCURRENCY=4 +DB_POOL_MIN=1 +DB_POOL_MAX=10 +DB_POOL_TIMEOUT_SECONDS=2 +DB_STATEMENT_TIMEOUT_MS=3000 +DB_REQUEST_TIMEOUT_SECONDS=4 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..f4609ace --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +*.sh text eol=lf +*.cmd text eol=crlf diff --git a/Makefile b/Makefile index 5d86d171..ee7fcb85 100644 --- a/Makefile +++ b/Makefile @@ -4,7 +4,7 @@ CA_FILE ?= ACTION_SCRIPT ?= TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",) -.PHONY: help check validate test load test-persistence test-failover +.PHONY: help check validate test load test-persistence test-failover student-test help: @echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes" @@ -18,6 +18,9 @@ validate: test: $(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS) +student-test: + BASE_URL="$(BASE_URL)" $(PYTHON) -m unittest discover -s student-tests -v + load: $(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS) diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..0d1380ff --- /dev/null +++ b/compose.yaml @@ -0,0 +1,135 @@ +name: grigoriev-lab3 + +x-app-env: &app-env + APP_HOST: 0.0.0.0 + APP_PORT: 8080 + APP_ENV: ${APP_ENV:-lab} + APP_SHUTDOWN_TIMEOUT: ${APP_SHUTDOWN_TIMEOUT:-5} + APP_DRAIN_SECONDS: ${APP_DRAIN_SECONDS:-3} + SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600} + SESSION_CACHE_TTL_SECONDS: ${SESSION_CACHE_TTL_SECONDS:-60} + REVOCATION_SYNC_SECONDS: ${REVOCATION_SYNC_SECONDS:-1} + IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400} + PASSWORD_HASH_CONCURRENCY: ${PASSWORD_HASH_CONCURRENCY:-4} + DB_POOL_MIN: ${DB_POOL_MIN:-1} + DB_POOL_MAX: ${DB_POOL_MAX:-10} + DB_POOL_TIMEOUT_SECONDS: ${DB_POOL_TIMEOUT_SECONDS:-2} + DB_STATEMENT_TIMEOUT_MS: ${DB_STATEMENT_TIMEOUT_MS:-3000} + DB_REQUEST_TIMEOUT_SECONDS: ${DB_REQUEST_TIMEOUT_SECONDS:-4} + MALLOC_ARENA_MAX: "2" + DATABASE_URL_FILE: /run/secrets/database_url + CACHE_URL: ${CACHE_URL:-redis://valkey:6379/0} + +x-dns-opt: &dns-opt + - timeout:1 + - attempts:1 + +services: + lb: + image: haproxy:3.0.30-alpine@sha256:d2b3567d836f3b7d174edb6d6f611ed5308e7966e53a9cd9a597e0415a298efd + volumes: + - ./infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro + ports: + - "127.0.0.1:8080:8080" + - "127.0.0.1:8404:8404" + healthcheck: + test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/lb/health"] + interval: 5s + timeout: 2s + retries: 6 + depends_on: + api: + condition: service_healthy + deploy: + resources: + limits: {cpus: "0.50", memory: 128M} + networks: [frontend, backend] + restart: unless-stopped + + api: + build: . + image: mtusi-messenger:lab3 + environment: *app-env + secrets: [database_url] + depends_on: + migrate: + condition: service_completed_successfully + postgres: + condition: service_healthy + valkey: + condition: service_started + dns_opt: *dns-opt + stop_grace_period: 15s + deploy: + replicas: ${API_REPLICAS:-2} + resources: + limits: {cpus: "0.50", memory: 320M} + networks: [backend] + restart: unless-stopped + + migrate: + build: . + image: mtusi-messenger:lab3 + command: ["python", "src/migrate.py"] + environment: *app-env + secrets: [database_url] + depends_on: + postgres: + condition: service_healthy + deploy: + resources: + limits: {cpus: "0.50", memory: 128M} + networks: [backend] + restart: "no" + + postgres: + image: postgres:17.11-alpine@sha256:266d3c257594e195b309ae9d1805e54c788f1d7b375f56bf6c367aac6c917e7b + environment: + POSTGRES_USER: messenger + POSTGRES_DB: messenger + POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password + command: ["postgres", "-c", "track_io_timing=on"] + secrets: [postgres_password] + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 3s + retries: 12 + start_period: 10s + stop_grace_period: 30s + deploy: + resources: + limits: {cpus: "1.00", memory: 384M} + networks: [backend] + restart: unless-stopped + + valkey: + image: valkey/valkey:8.1.11-alpine@sha256:2602ace2be6569bc2bbb06f873776516ab9089821525be34f4305c67eb9db02a + command: ["valkey-server", "--save", "", "--appendonly", "no", + "--maxmemory", "64mb", "--maxmemory-policy", "volatile-ttl"] + healthcheck: + test: ["CMD", "valkey-cli", "ping"] + interval: 5s + timeout: 3s + retries: 12 + deploy: + resources: + limits: {cpus: "0.25", memory: 96M} + networks: [backend] + restart: unless-stopped + +volumes: + pgdata: + +networks: + frontend: + backend: + internal: true + +secrets: + postgres_password: + file: ./secrets/postgres_password + database_url: + file: ./secrets/database_url diff --git a/infra/haproxy/haproxy.cfg b/infra/haproxy/haproxy.cfg new file mode 100644 index 00000000..5d9fac78 --- /dev/null +++ b/infra/haproxy/haproxy.cfg @@ -0,0 +1,53 @@ +global + log stdout format raw local0 info + maxconn 2000 + +defaults + mode http + log global + option httplog + option http-server-close + option forwardfor + option redispatch + retries 2 + retry-on conn-failure + timeout connect 1s + timeout client 30s + timeout server 10s + timeout check 1s + +resolvers docker + nameserver dns 127.0.0.11:53 + resolve_retries 2 + timeout resolve 1s + timeout retry 1s + hold valid 2s + hold obsolete 2s + hold nx 2s + accepted_payload_size 8192 + +frontend messenger + bind :8080 + monitor-uri /lb/health + use_backend api_live if { nbsrv(api) lt 1 } + default_backend api + +backend api + balance roundrobin + option httpchk GET /health/ready + http-check expect status 200 + default-server check inter 1s fall 2 rise 2 resolvers docker init-addr none + server-template api 1-4 api:8080 + +backend api_live + balance roundrobin + option httpchk GET /health/live + http-check expect status 200 + default-server check inter 1s fall 2 rise 2 resolvers docker init-addr none + server-template live 1-4 api:8080 + +listen stats + bind :8404 + stats enable + stats uri / + stats refresh 2s diff --git a/scripts/init_secrets.py b/scripts/init_secrets.py new file mode 100644 index 00000000..74c4503b --- /dev/null +++ b/scripts/init_secrets.py @@ -0,0 +1,27 @@ +import os +from pathlib import Path +import secrets + +ROOT = Path(__file__).resolve().parents[1] +SECRETS = ROOT / 'secrets' + + +def write(name, value): + path = SECRETS / name + if path.exists(): + print('keep existing secrets/%s' % name) + return path.read_text(encoding='utf-8').strip() + path.write_text(value + '\n', encoding='utf-8') + os.chmod(path, 0o644) + print('created secrets/%s' % name) + return value + + +def main(): + SECRETS.mkdir(exist_ok=True) + password = write('postgres_password', secrets.token_hex(24)) + write('database_url', 'postgresql://messenger:%s@postgres:5432/messenger' % password) + + +if __name__ == '__main__': + main() diff --git a/scripts/restart.cmd b/scripts/restart.cmd new file mode 100644 index 00000000..713107fb --- /dev/null +++ b/scripts/restart.cmd @@ -0,0 +1,6 @@ +@echo off +cd /d "%~dp0.." +docker compose stop api || exit /b 1 +docker compose restart postgres valkey || exit /b 1 +docker compose up -d --no-build --no-recreate --wait postgres valkey || exit /b 1 +docker compose start api || exit /b 1 diff --git a/scripts/rolling_update.py b/scripts/rolling_update.py new file mode 100644 index 00000000..dcd76906 --- /dev/null +++ b/scripts/rolling_update.py @@ -0,0 +1,76 @@ +"""Поочерёдная замена API-реплик без остановки сервиса. + + python scripts/rolling_update.py # пересобрать образ и заменить реплики по одной + python scripts/rolling_update.py --no-build # заменить на текущий образ + +1. Один раз применяет миграции (отдельный контейнер migrate; совместимые, только добавляющие изменения). +2. Для каждой старой реплики: поднимает одну новую (--scale +1, --no-recreate), ждёт, пока LB начнёт + отправлять на неё трафик, затем штатно останавливает старую (SIGTERM → вывод из ротации → завершение) + и удаляет её контейнер. Число реплик в ротации не опускается ниже исходного. +""" +import argparse +from pathlib import Path +import subprocess +import sys +import time +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] +BASE_URL = 'http://127.0.0.1:8080' + + +def compose(*args): + return subprocess.run(['docker', 'compose', *args], cwd=ROOT, check=True, capture_output=True, text=True).stdout + + +def running_api(): + return compose('ps', '-q', 'api').split() + + +def instance_of_next_response(): + try: + with urllib.request.urlopen(BASE_URL + '/health/ready', timeout=2) as response: + return response.headers.get('X-Instance-Id') + except OSError: + return None + + +def wait_in_rotation(container, seconds=90): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + if instance_of_next_response() == container[:12]: + return + time.sleep(0.1) + raise SystemExit('new replica %s did not enter LB rotation' % container[:12]) + + +def image_of(container): + return subprocess.run(['docker', 'inspect', '-f', '{{.Image}}', container], capture_output=True, text=True).stdout.strip()[7:19] + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--no-build', action='store_true') + args = parser.parse_args() + old = running_api() + print('old replicas:', ', '.join('%s(image %s)' % (c[:12], image_of(c)) for c in old)) + if not args.no_build: + compose('build', 'api') + compose('run', '--rm', '--no-deps', 'migrate') + print('migrations applied once') + for container in old: + before = set(running_api()) + compose('up', '-d', '--no-deps', '--no-recreate', '--scale', 'api=%d' % (len(before) + 1), 'api') + new = (set(running_api()) - before).pop() + started = time.monotonic() + wait_in_rotation(new) + print('+ %s (image %s) in rotation after %.1fs' % (new[:12], image_of(new), time.monotonic() - started)) + started = time.monotonic() + subprocess.run(['docker', 'stop', '-t', '15', container], check=True, capture_output=True) + subprocess.run(['docker', 'rm', container], check=True, capture_output=True) + print('- %s stopped and removed after %.1fs' % (container[:12], time.monotonic() - started)) + print('new replicas:', ', '.join('%s(image %s)' % (c[:12], image_of(c)) for c in running_api())) + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/scripts/stop-one.cmd b/scripts/stop-one.cmd new file mode 100644 index 00000000..ea9641bb --- /dev/null +++ b/scripts/stop-one.cmd @@ -0,0 +1,11 @@ +@echo off +if "%TARGET_INSTANCE_ID%"=="" exit /b 2 +cd /d "%~dp0.." +for /f %%i in ('docker compose ps -q api') do ( + echo %%i| findstr /b /i "%TARGET_INSTANCE_ID%" >nul && ( + docker stop -t 10 %%i >nul + exit /b 0 + ) +) +echo no running api replica matches TARGET_INSTANCE_ID 1>&2 +exit /b 1