diff --git a/secrets/pg-foriot.md b/secrets/pg-foriot.md new file mode 100644 index 0000000..46faa1e --- /dev/null +++ b/secrets/pg-foriot.md @@ -0,0 +1,11 @@ +# PostgreSQL foriot — параметры инстанса +# instanceUid: 509145c3-ba71-4687-a084-d9dcbc88d3d2 +# Кластер: iot-naeel | Версия: PostgreSQL 17 + +# --- Переменные для jsonEnv pythonk8s --- +DB_HOST=postgresqlk8s-master.509145c3-ba71-4687-a084-d9dcbc88d3d2.svc.cluster.local +DB_PORT=5432 +DB_NAME=autotest +DB_USER=superuser +DB_PASSWORD=3VPcxOiNC0HOT358LFEOpGcubnhJmp9wifwDJYD7Nl3WKu5FRPq07FUte4BazAok +DB_SSLMODE=require diff --git a/site/db/init_db.py b/site/db/init_db.py index 460edc9..3be6be8 100644 --- a/site/db/init_db.py +++ b/site/db/init_db.py @@ -49,9 +49,8 @@ CREATE INDEX IF NOT EXISTS idx_runs_created def init_db(): """Применить схему — идемпотентно, безопасно для конкурентного вызова.""" - dsn = os.getenv("DATABASE_URL", "") - if not dsn: - print("[DB] DATABASE_URL not set — skipping init", flush=True) + if not os.getenv("DB_USER"): + print("[DB] DB_USER not set — skipping init", flush=True) return conn = get_conn() diff --git a/site/db/pool.py b/site/db/pool.py index 69dc0ea..91400fc 100644 --- a/site/db/pool.py +++ b/site/db/pool.py @@ -4,8 +4,13 @@ Connection pool для PostgreSQL (psycopg2). Lazy-init: пул создаётся при первом обращении к БД в каждом gunicorn-воркере. Это безопасно для fork-модели — соединения открываются ПОСЛЕ fork. -DSN: из переменной окружения DATABASE_URL. -Формат: postgresql://user:pass@host:5432/dbname?sslmode=require +Переменные окружения (отдельно!): + DB_HOST — хост (по умолчанию localhost) + DB_PORT — порт (по умолчанию 5432) + DB_NAME — имя БД (по умолчанию autotest) + DB_USER — пользователь + DB_PASSWORD — пароль + DB_SSLMODE — sslmode (по умолчанию require) """ import os @@ -15,13 +20,25 @@ from psycopg2 import pool _pool = None +def _build_dsn(): + """Собрать DSN из отдельных переменных окружения.""" + return ( + f"host={os.getenv('DB_HOST', 'localhost')} " + f"port={os.getenv('DB_PORT', '5432')} " + f"dbname={os.getenv('DB_NAME', 'autotest')} " + f"user={os.getenv('DB_USER', '')} " + f"password={os.getenv('DB_PASSWORD', '')} " + f"sslmode={os.getenv('DB_SSLMODE', 'require')}" + ) + + def get_pool(): """Lazy-init ThreadedConnectionPool (1-5 соединений).""" global _pool if _pool is None: - dsn = os.getenv("DATABASE_URL", "") - if not dsn: - return None + dsn = _build_dsn() + if not os.getenv("DB_USER"): + return None # нет креда — нет пула _pool = pool.ThreadedConnectionPool(1, 5, dsn) return _pool