|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import contextlib |
| 4 | +import logging |
| 5 | +import typing as t |
| 6 | + |
| 7 | +import anyio |
| 8 | +import httpx |
| 9 | +from pyparsing import cast |
| 10 | +from starlette.requests import Request |
| 11 | + |
| 12 | +from _bentoml_sdk import Service |
| 13 | +from bentoml import get_current_service |
| 14 | +from bentoml._internal.utils import expand_envs |
| 15 | +from bentoml.exceptions import BentoMLConfigException |
| 16 | + |
| 17 | +if t.TYPE_CHECKING: |
| 18 | + from starlette.applications import Starlette |
| 19 | + |
| 20 | +logger = logging.getLogger("bentoml.server") |
| 21 | + |
| 22 | + |
| 23 | +async def _check_health(client: httpx.AsyncClient, health_endpoint: str) -> bool: |
| 24 | + try: |
| 25 | + response = await client.get(health_endpoint, timeout=5.0) |
| 26 | + if response.status_code == 404: |
| 27 | + raise BentoMLConfigException( |
| 28 | + f"Health endpoint {health_endpoint} not found (404). Please make sure the health " |
| 29 | + "endpoint is correctly configured in the service config." |
| 30 | + ) |
| 31 | + return response.is_success |
| 32 | + except (httpx.HTTPError, httpx.RequestError): |
| 33 | + return False |
| 34 | + |
| 35 | + |
| 36 | +def create_proxy_app(service: Service[t.Any]) -> Starlette: |
| 37 | + """A reverse-proxy that forwards all requests to the HTTP server started |
| 38 | + by the custom command. |
| 39 | + """ |
| 40 | + import fastapi |
| 41 | + from fastapi.responses import StreamingResponse |
| 42 | + |
| 43 | + health_endpoint = service.config.get("endpoints", {}).get("livez", "/health") |
| 44 | + |
| 45 | + @contextlib.asynccontextmanager |
| 46 | + async def lifespan( |
| 47 | + app: fastapi.FastAPI, |
| 48 | + ) -> t.AsyncGenerator[dict[str, t.Any], None]: |
| 49 | + server_instance = get_current_service() |
| 50 | + assert server_instance is not None, "Current service is not initialized" |
| 51 | + async with contextlib.AsyncExitStack() as stack: |
| 52 | + if cmd_getter := getattr(server_instance, "__command__", None): |
| 53 | + if not callable(cmd_getter): |
| 54 | + raise TypeError( |
| 55 | + f"__command__ must be a callable that returns a list of strings, got {type(cmd_getter)}" |
| 56 | + ) |
| 57 | + cmd = cast("list[str]", cmd_getter()) |
| 58 | + else: |
| 59 | + cmd = service.cmd |
| 60 | + assert cmd is not None, "must have a command" |
| 61 | + cmd = [expand_envs(c) for c in cmd] |
| 62 | + logger.info("Running service with command: %s", " ".join(cmd)) |
| 63 | + if ( |
| 64 | + instance_client := getattr(server_instance, "client", None) |
| 65 | + ) is not None and isinstance(instance_client, httpx.AsyncClient): |
| 66 | + # TODO: support aiohttp client |
| 67 | + client = instance_client |
| 68 | + else: |
| 69 | + proxy_port = service.config.get("http", {}).get("proxy_port") |
| 70 | + if proxy_port is None: |
| 71 | + raise BentoMLConfigException( |
| 72 | + "proxy_port must be set in service config to use custom command" |
| 73 | + ) |
| 74 | + proxy_url = f"http://localhost:{proxy_port}" |
| 75 | + client = await stack.enter_async_context( |
| 76 | + httpx.AsyncClient(base_url=proxy_url, timeout=None) |
| 77 | + ) |
| 78 | + proc = await anyio.open_process(cmd, stdout=None, stderr=None) |
| 79 | + while proc.returncode is None: |
| 80 | + if await _check_health(client, health_endpoint): |
| 81 | + break |
| 82 | + await anyio.sleep(0.5) |
| 83 | + else: |
| 84 | + raise RuntimeError( |
| 85 | + "Service process exited before becoming healthy, see the error above" |
| 86 | + ) |
| 87 | + |
| 88 | + app.state.client = client |
| 89 | + try: |
| 90 | + state = {"proc": proc, "client": client} |
| 91 | + service.context.state.update(state) |
| 92 | + yield state |
| 93 | + finally: |
| 94 | + proc.terminate() |
| 95 | + await proc.wait() |
| 96 | + |
| 97 | + assert service.has_custom_command(), "Service does not have custom command" |
| 98 | + app = fastapi.FastAPI(lifespan=lifespan) |
| 99 | + |
| 100 | + # TODO: support websocket endpoints |
| 101 | + @app.api_route( |
| 102 | + "/{path:path}", |
| 103 | + methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"], |
| 104 | + ) |
| 105 | + async def reverse_proxy(request: Request, path: str): |
| 106 | + url = httpx.URL( |
| 107 | + path=f"/{path}", query=request.url.query.encode("utf-8") or None |
| 108 | + ) |
| 109 | + client = t.cast(httpx.AsyncClient, app.state.client) |
| 110 | + headers = dict(request.headers) |
| 111 | + headers.pop("host", None) |
| 112 | + req = client.build_request( |
| 113 | + method=request.method, url=url, headers=headers, content=request.stream() |
| 114 | + ) |
| 115 | + try: |
| 116 | + resp = await client.send(req, stream=True) |
| 117 | + except httpx.ConnectError: |
| 118 | + return fastapi.Response(503) |
| 119 | + except httpx.RequestError: |
| 120 | + return fastapi.Response(500) |
| 121 | + |
| 122 | + return StreamingResponse( |
| 123 | + resp.aiter_raw(), |
| 124 | + status_code=resp.status_code, |
| 125 | + headers=resp.headers, |
| 126 | + background=resp.aclose, |
| 127 | + ) |
| 128 | + |
| 129 | + return app |
0 commit comments