"""Health check endpoints.""" import os import platform import psutil from datetime import datetime from fastapi import APIRouter, Depends from sqlalchemy.orm import Session from sqlalchemy import text from app.dependencies import get_db, get_current_user, get_current_superuser from app.config import settings from app.models.user import User router = APIRouter() # Store app start time APP_START_TIME = datetime.utcnow() def get_system_info() -> dict: """Get detailed system information.""" # Memory info memory = psutil.virtual_memory() # Disk info disk = psutil.disk_usage('/') # CPU info cpu_percent = psutil.cpu_percent(interval=0.1) return { "memory": { "total_gb": round(memory.total / (1024**3), 2), "used_gb": round(memory.used / (1024**3), 2), "available_gb": round(memory.available / (1024**3), 2), "percent": memory.percent }, "disk": { "total_gb": round(disk.total / (1024**3), 2), "used_gb": round(disk.used / (1024**3), 2), "free_gb": round(disk.free / (1024**3), 2), "percent": disk.percent }, "cpu": { "percent": cpu_percent, "cores": psutil.cpu_count() }, "platform": { "system": platform.system(), "release": platform.release(), "python": platform.python_version() } } @router.get("") def health_check(db: Session = Depends(get_db)): """ Health check endpoint that verifies database connectivity. Public endpoint for monitoring services. Returns: Dictionary with health status and database connectivity """ try: # Test database connection db.execute(text("SELECT 1")) db_status = "connected" except Exception as e: db_status = f"error: {str(e)}" # Calculate uptime uptime_seconds = (datetime.utcnow() - APP_START_TIME).total_seconds() return { "status": "healthy" if db_status == "connected" else "unhealthy", "app": settings.APP_NAME, "version": settings.APP_VERSION, "database": db_status, "uptime_seconds": int(uptime_seconds) } @router.get("/detailed") def health_check_detailed( db: Session = Depends(get_db), current_user: User = Depends(get_current_superuser) ): """ Detailed health check with system information. Requires superuser authentication. Returns: Dictionary with detailed health status and system info """ # Basic health check try: db.execute(text("SELECT 1")) db_status = "connected" except Exception as e: db_status = f"error: {str(e)}" # Calculate uptime uptime_seconds = (datetime.utcnow() - APP_START_TIME).total_seconds() days, remainder = divmod(int(uptime_seconds), 86400) hours, remainder = divmod(remainder, 3600) minutes, seconds = divmod(remainder, 60) return { "status": "healthy" if db_status == "connected" else "unhealthy", "app": settings.APP_NAME, "version": settings.APP_VERSION, "database": db_status, "uptime": { "seconds": int(uptime_seconds), "formatted": f"{days}d {hours}h {minutes}m {seconds}s" }, "started_at": APP_START_TIME.isoformat(), "system": get_system_info(), "environment": { "debug": settings.DEBUG, "log_level": settings.LOG_LEVEL } }