launch.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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.engine.async_aphrodite import AsyncEngineDeadError
  10. from aphrodite.engine.protocol import AsyncEngineClient
  11. APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH = bool(os.getenv(
  12. "APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH", 0))
  13. async def serve_http(app: FastAPI, engine: AsyncEngineClient,
  14. **uvicorn_kwargs: Any):
  15. config = uvicorn.Config(app, **uvicorn_kwargs)
  16. server = uvicorn.Server(config)
  17. _add_shutdown_handlers(app, server, engine)
  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. loop.add_signal_handler(signal.SIGINT, signal_handler)
  26. loop.add_signal_handler(signal.SIGTERM, signal_handler)
  27. try:
  28. await server_task
  29. return dummy_shutdown()
  30. except asyncio.CancelledError:
  31. logger.info("Gracefully stopping http server")
  32. return server.shutdown()
  33. def _add_shutdown_handlers(app: FastAPI, server: uvicorn.Server,
  34. engine: AsyncEngineClient) -> None:
  35. """Adds handlers for fatal errors that should crash the server"""
  36. @app.exception_handler(RuntimeError)
  37. async def runtime_error_handler(_, __):
  38. """On generic runtime error, check to see if the engine has died.
  39. It probably has, in which case the server will no longer be able to
  40. handle requests. Trigger a graceful shutdown with a SIGTERM."""
  41. if (not APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH and engine.errored
  42. and not engine.is_running):
  43. logger.error("AsyncAphrodite has failed, terminating server "
  44. "process")
  45. # See discussions here on shutting down a uvicorn server
  46. # https://github.com/encode/uvicorn/discussions/1103
  47. # In this case we cannot await the server shutdown here because
  48. # this handler must first return to close the connection for
  49. # this request.
  50. server.should_exit = True
  51. return Response(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
  52. @app.exception_handler(AsyncEngineDeadError)
  53. async def engine_dead_handler(_, __):
  54. """Kill the server if the async engine is already dead. It will
  55. not handle any further requests."""
  56. if not APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH:
  57. logger.error("AsyncAphrodite is already dead, terminating server "
  58. "process")
  59. server.should_exit = True
  60. return Response(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)