Files
leocrm/prestart.sh
T
Agent Zero 47aa42ed09 fix(prestart): dynamic owner_id fix for all plugin tables
Instead of a static list, find ALL tables with tenant_id but without
owner_id and add the column. This catches all plugin tables that were
created after core migration 0054 ran.
2026-08-07 00:29:59 +02:00

161 lines
6.3 KiB
Bash

#!/bin/sh
# =============================================================================
# prestart.sh — Container entrypoint for CRM API container
#
# Responsibilities:
# 1. Run Alembic DB migrations (alembic upgrade head) using the migration user.
# 2. Set passwords for all application DB roles (crm_api, crm_auth, crm_worker, crm_migration).
# 3. Add owner_id to plugin tables that were created after core migration 0054.
# 4. 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 for bootstrap, then crm_migration).
# - The app uses DATABASE_URL (crm_api, 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 passwords for all application DB roles (crm_api, crm_auth, crm_worker, crm_migration)
# Migration 0070 creates these roles without passwords; we set them here so the
# API/Worker/Auth connections can authenticate.
echo "[prestart] Setting DB role passwords..."
cat > /tmp/set_role_passwords.py << 'PYEOF'
import asyncio
import os
import re
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
async def set_passwords():
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
match = re.search(r'://([^:]+):([^@]+)@', db_url)
if not match:
print('[prestart] WARNING: Could not extract password from DB URL')
return
pwd = match.group(2)
engine = create_async_engine(db_url)
roles = ['crm_api', 'crm_auth', 'crm_worker', 'crm_migration']
try:
async with engine.begin() as conn:
for role in roles:
try:
await conn.execute(text(f"ALTER ROLE {role} WITH LOGIN PASSWORD '{pwd}'"))
print(f'[prestart] Password set for {role}')
except Exception as e:
print(f'[prestart] WARNING: Could not set password for {role}: {e}')
print('[prestart] DB role passwords set.')
except Exception as e:
print(f'[prestart] WARNING: Could not set DB role passwords: {e}')
finally:
await engine.dispose()
asyncio.run(set_passwords())
PYEOF
python3 /tmp/set_role_passwords.py
rm -f /tmp/set_role_passwords.py
# Set crm_runtime password if RUNTIME_DB_PASSWORD is set (legacy support)
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] Adding owner_id to plugin tables if missing..."
python3 -c "
import asyncio, os
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy import text
async def fix_owner_id():
db_url = os.environ.get('MIGRATION_DATABASE_URL', os.environ.get('DATABASE_URL', ''))
if not db_url:
print('[prestart] WARNING: No DB URL for owner_id fix')
return
engine = create_async_engine(db_url)
try:
async with engine.begin() as conn:
# Find all tables with tenant_id but without owner_id
result = await conn.execute(text(\"\"\"
SELECT t.table_name
FROM information_schema.tables t
JOIN information_schema.columns c ON t.table_name = c.table_name
WHERE t.table_schema = 'public'
AND c.column_name = 'tenant_id'
AND t.table_type = 'BASE TABLE'
AND NOT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = t.table_name AND column_name = 'owner_id'
)
ORDER BY t.table_name
\"\"\"))
tables = [row[0] for row in result.fetchall()]
for table in tables:
await conn.execute(text(
f'ALTER TABLE {table} ADD COLUMN IF NOT EXISTS owner_id UUID REFERENCES users(id) ON DELETE SET NULL'
))
await conn.execute(text(
f'CREATE INDEX IF NOT EXISTS ix_{table}_owner ON {table} (owner_id)'
))
print(f'[prestart] Added owner_id to {table}')
if not tables:
print('[prestart] All tables already have owner_id.')
else:
print(f'[prestart] Added owner_id to {len(tables)} tables.')
except Exception as e:
print(f'[prestart] WARNING: owner_id fix failed: {e}')
finally:
await engine.dispose()
asyncio.run(fix_owner_id())
"
echo "[prestart] Seeding admin user if not exists..."
python3 /app/scripts/seed_admin.py || echo "[prestart] WARNING: Admin seed failed (may already exist)"
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