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, 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.protocol import AsyncEngineClient
  12. APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH = (
  13. envs.APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH)
  14. async def serve_http(app: FastAPI, engine: AsyncEngineClient,
  15. **uvicorn_kwargs: Any):
  16. # Set concurrency limits in uvicorn if running in multiprocessing mode
  17. # since zmq has maximum socket limit of zmq.constants.SOCKET_LIMIT (65536).
  18. if engine.limit_concurrency is not None:
  19. logger.info(
  20. "Launching Uvicorn with --limit_concurrency "
  21. f"{engine.limit_concurrency}. "
  22. f"To avoid this limit at the expense of performance run with "
  23. f"--disable-frontend-multiprocessing")
  24. uvicorn_kwargs["limit_concurrency"] = engine.limit_concurrency
  25. config = uvicorn.Config(app, **uvicorn_kwargs)
  26. server = uvicorn.Server(config)
  27. _add_shutdown_handlers(app, server, engine)
  28. loop = asyncio.get_running_loop()
  29. server_task = loop.create_task(server.serve())
  30. def signal_handler() -> None:
  31. # prevents the uvicorn signal handler to exit early
  32. server_task.cancel()
  33. async def dummy_shutdown() -> None:
  34. pass
  35. if in_windows():
  36. # Windows - use signal.signal() directly
  37. signal.signal(signal.SIGINT, lambda signum, frame: signal_handler())
  38. signal.signal(signal.SIGTERM, lambda signum, frame: signal_handler())
  39. else:
  40. # Unix - use asyncio's add_signal_handler
  41. loop.add_signal_handler(signal.SIGINT, signal_handler)
  42. loop.add_signal_handler(signal.SIGTERM, signal_handler)
  43. try:
  44. await server_task
  45. return dummy_shutdown()
  46. except asyncio.CancelledError:
  47. port = uvicorn_kwargs["port"]
  48. process = find_process_using_port(port)
  49. if process is not None:
  50. logger.info(
  51. f"port {port} is used by process {process} launched with "
  52. f"command:\n{' '.join(process.cmdline())}")
  53. logger.info("Gracefully stopping http server")
  54. return server.shutdown()
  55. def _add_shutdown_handlers(app: FastAPI, server: uvicorn.Server,
  56. engine: AsyncEngineClient) -> None:
  57. """Adds handlers for fatal errors that should crash the server"""
  58. @app.exception_handler(RuntimeError)
  59. async def runtime_error_handler(_, __):
  60. """On generic runtime error, check to see if the engine has died.
  61. It probably has, in which case the server will no longer be able to
  62. handle requests. Trigger a graceful shutdown with a SIGTERM."""
  63. if (not APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH and engine.errored
  64. and not engine.is_running):
  65. logger.error("AsyncAphrodite has failed, terminating server "
  66. "process")
  67. # See discussions here on shutting down a uvicorn server
  68. # https://github.com/encode/uvicorn/discussions/1103
  69. # In this case we cannot await the server shutdown here because
  70. # this handler must first return to close the connection for
  71. # this request.
  72. server.should_exit = True
  73. return Response(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
  74. @app.exception_handler(AsyncEngineDeadError)
  75. async def engine_dead_handler(_, __):
  76. """Kill the server if the async engine is already dead. It will
  77. not handle any further requests."""
  78. if not APHRODITE_KEEP_ALIVE_ON_ENGINE_DEATH:
  79. logger.error("AsyncAphrodite is already dead, terminating server "
  80. "process")
  81. server.should_exit = True
  82. return Response(status_code=HTTPStatus.INTERNAL_SERVER_ERROR)