health.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. """
  2. Health Check Router
  3. """
  4. from fastapi import APIRouter, Depends
  5. from fastapi.responses import JSONResponse
  6. from sqlalchemy.orm import Session
  7. from shared.database import get_db
  8. from shared.models.health import HealthStatus
  9. import asyncio
  10. import time
  11. router = APIRouter()
  12. @router.get("/health", response_model=HealthStatus)
  13. async def health_check(db: Session = Depends(get_db)):
  14. """Health check endpoint"""
  15. start_time = time.time()
  16. # Check database connection
  17. try:
  18. db.execute("SELECT 1")
  19. db_status = "healthy"
  20. except Exception as e:
  21. db_status = f"unhealthy: {str(e)}"
  22. # Check external services
  23. services_status = await check_external_services()
  24. response_time = time.time() - start_time
  25. return HealthStatus(
  26. status="healthy" if db_status == "healthy" else "unhealthy",
  27. timestamp=time.time(),
  28. response_time=response_time,
  29. database=db_status,
  30. services=services_status
  31. )
  32. @router.get("/health/ready")
  33. async def readiness_check():
  34. """Readiness check for Kubernetes"""
  35. return {"status": "ready"}
  36. @router.get("/health/live")
  37. async def liveness_check():
  38. """Liveness check for Kubernetes"""
  39. return {"status": "alive"}
  40. async def check_external_services():
  41. """Check external services status"""
  42. services = {
  43. "redis": await check_redis(),
  44. "rabbitmq": await check_rabbitmq(),
  45. "model_service": await check_model_service(),
  46. "user_service": await check_user_service(),
  47. "task_service": await check_task_service()
  48. }
  49. return services
  50. async def check_redis():
  51. """Check Redis connection"""
  52. try:
  53. # Implementation would check Redis connection
  54. return "healthy"
  55. except Exception:
  56. return "unhealthy"
  57. async def check_rabbitmq():
  58. """Check RabbitMQ connection"""
  59. try:
  60. # Implementation would check RabbitMQ connection
  61. return "healthy"
  62. except Exception:
  63. return "unhealthy"
  64. async def check_model_service():
  65. """Check model service"""
  66. try:
  67. # Implementation would check model service
  68. return "healthy"
  69. except Exception:
  70. return "unhealthy"
  71. async def check_user_service():
  72. """Check user service"""
  73. try:
  74. # Implementation would check user service
  75. return "healthy"
  76. except Exception:
  77. return "unhealthy"
  78. async def check_task_service():
  79. """Check task service"""
  80. try:
  81. # Implementation would check task service
  82. return "healthy"
  83. except Exception:
  84. return "unhealthy"