Spaces:
Running
Running
| #!/usr/bin/env python3 | |
| """ | |
| Production startup script for CVE Fact Checker. | |
| This script handles environment setup and graceful startup. | |
| """ | |
| import os | |
| import sys | |
| import time | |
| import signal | |
| import subprocess | |
| from pathlib import Path | |
| def setup_signal_handlers(): | |
| """Setup graceful shutdown handlers.""" | |
| def signal_handler(signum, frame): | |
| print(f"\nπ Received signal {signum}, shutting down gracefully...") | |
| sys.exit(0) | |
| signal.signal(signal.SIGTERM, signal_handler) | |
| signal.signal(signal.SIGINT, signal_handler) | |
| def run_health_check(): | |
| """Run basic health check before starting.""" | |
| print("π₯ Running pre-startup health check...") | |
| try: | |
| result = subprocess.run([ | |
| sys.executable, "health_check.py" | |
| ], capture_output=True, text=True, timeout=30) | |
| if result.returncode == 0: | |
| print("β Health check passed") | |
| return True | |
| else: | |
| print("β οΈ Health check warnings:") | |
| print(result.stdout) | |
| print(result.stderr) | |
| return True # Continue anyway | |
| except Exception as e: | |
| print(f"β οΈ Health check failed: {e}") | |
| return True # Continue anyway | |
| def start_application(): | |
| """Start the application with gunicorn.""" | |
| print("π Starting CVE Fact Checker...") | |
| # Environment setup | |
| env = os.environ.copy() | |
| env.update({ | |
| 'PYTHONUNBUFFERED': '1', | |
| 'PYTHONDONTWRITEBYTECODE': '1', | |
| }) | |
| # Gunicorn command | |
| cmd = [ | |
| "gunicorn", | |
| "-w", "1", # Single worker to avoid race conditions | |
| "-k", "gthread", | |
| "--threads", "4", | |
| "-b", f"0.0.0.0:{env.get('PORT', '7860')}", | |
| "--timeout", "180", | |
| "--access-logfile", "-", # Log to stdout | |
| "--error-logfile", "-", # Log to stderr | |
| "cve_factchecker.wsgi:application" | |
| ] | |
| print(f"π Command: {' '.join(cmd)}") | |
| print(f"π Will bind to port {env.get('PORT', '7860')}") | |
| try: | |
| # Run gunicorn | |
| subprocess.run(cmd, env=env, check=True) | |
| except KeyboardInterrupt: | |
| print("\nπ Interrupted by user") | |
| except subprocess.CalledProcessError as e: | |
| print(f"β Application failed with exit code {e.returncode}") | |
| sys.exit(e.returncode) | |
| except Exception as e: | |
| print(f"β Unexpected error: {e}") | |
| sys.exit(1) | |
| def main(): | |
| """Main startup routine.""" | |
| print("=" * 60) | |
| print("π€ CVE Fact Checker - Production Startup") | |
| print("=" * 60) | |
| print(f"β° Starting at: {time.strftime('%Y-%m-%d %H:%M:%S')}") | |
| print(f"π Python: {sys.version}") | |
| print(f"π Working directory: {os.getcwd()}") | |
| print() | |
| setup_signal_handlers() | |
| # Optional health check | |
| if os.path.exists("health_check.py"): | |
| run_health_check() | |
| print() | |
| start_application() | |
| if __name__ == "__main__": | |
| main() | |