Пофиксила 2 замечания: добавила one-shot миграции и лимиты ресурсов для всех сервисов
This commit is contained in:
+53
-1
@@ -4,7 +4,9 @@ x-required-roles:
|
|||||||
- postgres
|
- postgres
|
||||||
- load_balancer
|
- load_balancer
|
||||||
|
|
||||||
# Лабораторная 3. LB + 2 API-реплики + PostgreSQL + Redis.
|
# Лабораторная 3. LB + 2 API-реплики + PostgreSQL + Redis + one-shot migrate.
|
||||||
|
# Миграции вынесены в отдельный сервис migrate.
|
||||||
|
# Лимиты CPU/RAM заданы для ВСЕХ сервисов
|
||||||
services:
|
services:
|
||||||
postgres:
|
postgres:
|
||||||
image: postgres:18.6-alpine
|
image: postgres:18.6-alpine
|
||||||
@@ -22,6 +24,14 @@ services:
|
|||||||
retries: 20
|
retries: 20
|
||||||
start_period: 30s
|
start_period: 30s
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "1.0"
|
||||||
|
memory: 1G
|
||||||
|
reservations:
|
||||||
|
cpus: "0.25"
|
||||||
|
memory: 256M
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:7.4.1-alpine
|
image: redis:7.4.1-alpine
|
||||||
@@ -36,6 +46,35 @@ services:
|
|||||||
retries: 10
|
retries: 10
|
||||||
start_period: 3s
|
start_period: 3s
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 256M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 64M
|
||||||
|
|
||||||
|
migrate:
|
||||||
|
build: .
|
||||||
|
image: mtuci-messenger:lab3
|
||||||
|
# One-shot: применяет схему БД один раз и завершается с кодом 0.
|
||||||
|
# Реплики api стартуют только после успешного выхода (см. depends_on).
|
||||||
|
command: ["python", "-m", "app.storage.db"]
|
||||||
|
env_file:
|
||||||
|
- .env
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
restart: "no"
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 256M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 64M
|
||||||
|
|
||||||
api:
|
api:
|
||||||
build: .
|
build: .
|
||||||
@@ -45,6 +84,8 @@ services:
|
|||||||
env_file:
|
env_file:
|
||||||
- .env
|
- .env
|
||||||
depends_on:
|
depends_on:
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
postgres:
|
postgres:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
redis:
|
redis:
|
||||||
@@ -62,6 +103,9 @@ services:
|
|||||||
limits:
|
limits:
|
||||||
cpus: "1.0"
|
cpus: "1.0"
|
||||||
memory: 512M
|
memory: 512M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.25"
|
||||||
|
memory: 128M
|
||||||
|
|
||||||
lb:
|
lb:
|
||||||
image: nginx:1.27.3-alpine
|
image: nginx:1.27.3-alpine
|
||||||
@@ -74,6 +118,14 @@ services:
|
|||||||
api:
|
api:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
deploy:
|
||||||
|
resources:
|
||||||
|
limits:
|
||||||
|
cpus: "0.5"
|
||||||
|
memory: 128M
|
||||||
|
reservations:
|
||||||
|
cpus: "0.1"
|
||||||
|
memory: 32M
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
postgres-data:
|
postgres-data:
|
||||||
|
|||||||
+2
-2
@@ -13,7 +13,7 @@ from starlette.exceptions import HTTPException as StarletteHTTPException
|
|||||||
import psycopg
|
import psycopg
|
||||||
import uvicorn
|
import uvicorn
|
||||||
from .api import auth, chats, health, messages, users
|
from .api import auth, chats, health, messages, users
|
||||||
from .storage.db import init_schema, init_pool, close_pool
|
from .storage.db import init_pool, close_pool
|
||||||
|
|
||||||
|
|
||||||
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
# --- Логирование: структурированный stdout, без содержимого сообщений ---
|
||||||
@@ -32,7 +32,7 @@ INSTANCE_ID = os.environ.get("INSTANCE_ID") or uuid.uuid4().hex[:12]
|
|||||||
@asynccontextmanager
|
@asynccontextmanager
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
|
init_pool() # пул соединений PostgreSQL с таймаутами (уровень 4)
|
||||||
init_schema() # создать таблицы в БД если их ещё нет
|
# Схему готовит отдельный сервис migrate (service_completed_successfully)
|
||||||
logger.info(
|
logger.info(
|
||||||
"event=startup app_env=%s session_store=%s instance_id=%s",
|
"event=startup app_env=%s session_store=%s instance_id=%s",
|
||||||
os.environ.get("APP_ENV", "lab"),
|
os.environ.get("APP_ENV", "lab"),
|
||||||
|
|||||||
+35
-2
@@ -108,8 +108,41 @@ CREATE INDEX IF NOT EXISTS idx_idempotency_created
|
|||||||
|
|
||||||
|
|
||||||
def init_schema() -> None:
|
def init_schema() -> None:
|
||||||
"""Идемпотентная миграция: запускается на старте приложения."""
|
"""Идемпотентная миграция: безопасно вызывать многократно.
|
||||||
|
|
||||||
|
Вызывается ОДИН РАЗ отдельным one-shot сервисом migrate
|
||||||
|
(см. compose.yaml). Реплики API миграции больше не выполняют:
|
||||||
|
они ждут service_completed_successfully.
|
||||||
|
"""
|
||||||
with connection() as conn:
|
with connection() as conn:
|
||||||
with conn.cursor() as cur:
|
with conn.cursor() as cur:
|
||||||
cur.execute(SCHEMA_SQL)
|
cur.execute(SCHEMA_SQL)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations() -> None:
|
||||||
|
"""Точка входа для one-shot migrate-контейнера.
|
||||||
|
|
||||||
|
Поднимает пул, применяет схему, закрывает пул. Завершается с кодом 0
|
||||||
|
при успехе — этого достаточно для service_completed_successfully.
|
||||||
|
"""
|
||||||
|
init_pool()
|
||||||
|
try:
|
||||||
|
init_schema()
|
||||||
|
finally:
|
||||||
|
close_pool()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Запуск: python -m app.storage.db
|
||||||
|
# (в compose.yaml — command: ["python", "-m", "app.storage.db"])
|
||||||
|
import logging
|
||||||
|
|
||||||
|
logging.basicConfig(
|
||||||
|
level=logging.INFO,
|
||||||
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||||
|
)
|
||||||
|
log = logging.getLogger("migrate")
|
||||||
|
log.info("event=migrations_start")
|
||||||
|
run_migrations()
|
||||||
|
log.info("event=migrations_done")
|
||||||
Reference in New Issue
Block a user