import subprocess import os import sys import logging import time import traceback # Configure logging logging.basicConfig( level=logging.INFO, format='[%(asctime)s] %(levelname)s: %(message)s', handlers=[logging.StreamHandler(sys.stdout)] ) logger = logging.getLogger(__name__) def run_command(command, shell=True): logger.info(f"👉 Running: {command}") try: result = subprocess.run( command, shell=shell, check=True, stdout=sys.stdout, stderr=sys.stderr ) return result except subprocess.CalledProcessError as e: logger.error(f"❌ Command failed with exit code {e.returncode}") time.sleep(1) sys.exit(e.returncode) def main(): logger.info("🚀 STARTUP SCRIPT INITIALIZED") logger.info(f"📂 CWD: {os.getcwd()}") logger.info(f"🐍 Python: {sys.version}") # 0. Debug Check: Can we trace the app? logger.info("🔍 Checking if 'app.main' is importable...") try: import app.main logger.info("✅ 'app.main' imported successfully!") except ImportError as e: logger.error(f"❌ Failed to import app.main: {e}") logger.error(traceback.format_exc()) sys.exit(1) except Exception as e: logger.error(f"❌ Unexpected error importing app.main: {e}") logger.error(traceback.format_exc()) sys.exit(1) # 1. Run Migrations logger.info("🛠️ Running Database Migrations...") run_command("python -m alembic upgrade head") logger.info("✅ Migrations done.") # 2. Start Uvicorn host = "0.0.0.0" port = os.environ.get("PORT", "8000") logger.info(f"🔌 Starting Server on {host}:{port}...") uvicorn_cmd = [ "python", "-m", "uvicorn", "app.main:app", "--host", host, "--port", port, "--log-level", "info" # Production level logging ] logger.info(f"▶️ Executing: {' '.join(uvicorn_cmd)}") sys.stdout.flush() # Use subprocess.run instead of exec to catch the exit try: proc = subprocess.run(uvicorn_cmd, check=False) logger.info(f"🛑 Uvicorn exited with code: {proc.returncode}") # If it exits cleanly (0), that's actually bad for a server (it should run forever) if proc.returncode == 0: logger.error("⚠️ Uvicorn exited with 0, but it should have kept running!") except Exception as e: logger.error(f"❌ Error running uvicorn: {e}") logger.info("👋 Startup script finishing.") if __name__ == "__main__": main()