launch.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import asyncio
  2. import signal
  3. from http import HTTPStatus
  4. from typing import Any
  5. import uvicorn
  6. from fastapi import FastAPI, Request, Response
  7. from loguru import logger
  8. import aphrodite.common.envs as envs
  9. from aphrodite.common.utils import find_process_using_port, in_windows
  10. from aphrodite.engine.async_aphrodite import AsyncEngineDeadError
  11. from aphrodite.engine.multiprocessing import MQEngineDeadError
  12. APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH = (
  13. envs.APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH)
  14. async def serve_http(app: FastAPI, **uvicorn_kwargs: Any):
  15. config = uvicorn.Config(app, **uvicorn_kwargs)
  16. server = uvicorn.Server(config)
  17. _add_shutdown_handlers(app, server)
  18. loop = asyncio.get_running_loop()
  19. server_task = loop.create_task(server.serve())
  20. def signal_handler() -> None:
  21. # prevents the uvicorn signal handler to exit early
  22. server_task.cancel()
  23. async def dummy_shutdown() -> None:
  24. pass
  25. if in_windows():
  26. # Windows - use signal.signal() directly
  27. signal.signal(signal.SIGINT, lambda signum, frame: signal_handler())
  28. signal.signal(signal.SIGTERM, lambda signum, frame: signal_handler())
  29. else:
  30. # Unix - use asyncio's add_signal_handler
  31. loop.add_signal_handler(signal.SIGINT, signal_handler)
  32. loop.add_signal_handler(signal.SIGTERM, signal_handler)
  33. try:
  34. await server_task
  35. return dummy_shutdown()
  36. except asyncio.CancelledError:
  37. port = uvicorn_kwargs["port"]
  38. process = find_process_using_port(port)
  39. if process is not None:
  40. logger.info(
  41. f"port {port} is used by process {process} launched with "
  42. f"command:\n{' '.join(process.cmdline())}")
  43. logger.info("Shutting down FastAPI HTTP server.")
  44. return server.shutdown()
  45. def _add_shutdown_handlers(app: FastAPI, server: uvicorn.Server) -> None:
  46. """Adds handlers for fatal errors that should crash the server"""
  47. @app.exception_handler(RuntimeError)
  48. async def runtime_error_handler(request: Request, __):
  49. """On generic runtime error, check to see if the engine has died.
  50. It probably has, in which case the server will no longer be able to
  51. handle requests. Trigger a graceful shutdown with a SIGTERM."""
  52. engine = request.app.state.engine_client
  53. if (not APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH and engine.errored
  54. and not engine.is_running):
  55. logger.error("AsyncAphrodite has failed, terminating server "
  56. "process")
  57. # See discussions here on shutting down a uvicorn server
  58. # https://github.com/encode/uvicorn/discussions/1103
  59. # In this case we cannot await the server shutdown here because
  60. # this handler must first return to close the connection for
  61. # this request.
  62. server.should_exit = True
  63. return Response(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
  64. @app.exception_handler(AsyncEngineDeadError)
  65. async def async_engine_dead_handler(_, __):
  66. """Kill the server if the async engine is already dead. It will
  67. not handle any further requests."""
  68. if not APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH:
  69. logger.error("AsyncAphrodite is already dead, terminating server "
  70. "process")
  71. server.should_exit = True
  72. return Response(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
  73. @app.exception_handler(MQEngineDeadError)
  74. async def mq_engine_dead_handler(_, __):
  75. """Kill the server if the mq engine is already dead. It will
  76. not handle any further requests."""
  77. if not envs.APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH:
  78. logger.error("MQLLMEngine is already dead, terminating server "
  79. "process")
  80. server.should_exit = True
  81. return Response(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)