launch.py 3.4 KB

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