Files
leocrm/prestart.sh
T

66 lines
2.4 KiB
Bash
Executable File

#!/bin/sh
# =============================================================================
# prestart.sh — Container entrypoint for CRM API container
#
# Responsibilities:
# 1. Run Alembic DB migrations (alembic upgrade head) using the owner user.
# 2. Set the crm_runtime password (for RLS-enforced app access).
# 3. Start uvicorn as PID 1 (so signals like SIGTERM are forwarded correctly).
#
# Notes:
# - `set -e` ensures the container crashes loudly if migrations fail.
# - The ARQ worker runs in a separate container (see worker.sh / docker-compose).
# - Migrations use MIGRATION_DATABASE_URL (crm_user, owner, can bypass RLS).
# - The app uses DATABASE_URL (crm_runtime, NOSUPERUSER, NOBYPASSRLS).
# =============================================================================
set -e
# Use MIGRATION_DATABASE_URL for alembic (falls back to DATABASE_URL for backwards compat)
export ALEMBIC_DATABASE_URL="${MIGRATION_DATABASE_URL:-$DATABASE_URL}"
# Configure alembic to use the migration database URL
export ALEMBIC_DATABASE_URL
echo "[prestart] $(date -u +%Y-%m-%dT%H:%M:%SZ) - Running alembic upgrade head (owner user)..."
# Temporarily override DATABASE_URL for alembic
DATABASE_URL="$ALEMBIC_DATABASE_URL" alembic upgrade head
echo "[prestart] DB migrations completed successfully."
# Set crm_runtime password if RUNTIME_DB_PASSWORD is set
if [ -n "$RUNTIME_DB_PASSWORD" ]; then
echo "[prestart] Setting crm_runtime password..."
python3 -c "
import asyncio
import os
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
async def set_password():
db_url = os.environ.get('MIGRATION_DATABASE_URL', os.environ.get('DATABASE_URL', ''))
if not db_url:
print('[prestart] WARNING: No DB URL for password setup')
return
engine = create_async_engine(db_url)
pwd = os.environ.get('RUNTIME_DB_PASSWORD', '')
try:
async with engine.begin() as conn:
await conn.execute(text(
"ALTER ROLE crm_runtime WITH LOGIN PASSWORD :pwd NOSUPERUSER NOBYPASSRLS"
), {"pwd": pwd})
print('[prestart] crm_runtime password set.')
except Exception as e:
print(f'[prestart] WARNING: Could not set crm_runtime password: {e}')
finally:
await engine.dispose()
asyncio.run(set_password())
"
fi
echo "[prestart] Starting uvicorn on 0.0.0.0:8000 (workers=1)..."
exec uvicorn app.main:app \
--host 0.0.0.0 \
--port 8000 \
--workers 1