|
| 1 | +import re |
| 2 | +import logging |
| 3 | +from functools import cache |
| 4 | +from typing import Callable |
| 5 | +import requests |
| 6 | + |
| 7 | +from localstack import config |
| 8 | +from localstack.config import is_env_true |
| 9 | +from localstack_typedb.utils.h2_proxy import ( |
| 10 | + apply_http2_patches_for_grpc_support, |
| 11 | + ProxyRequestMatcher, |
| 12 | +) |
| 13 | +from localstack.utils.docker_utils import DOCKER_CLIENT |
| 14 | +from localstack.extensions.api import Extension, http |
| 15 | +from localstack.http import Request |
| 16 | +from localstack.utils.container_utils.container_client import PortMappings |
| 17 | +from localstack.utils.net import get_addressable_container_host |
| 18 | +from localstack.utils.sync import retry |
| 19 | +from rolo import route |
| 20 | +from rolo.proxy import Proxy |
| 21 | +from rolo.routing import RuleAdapter, WithHost |
| 22 | +from werkzeug.datastructures import Headers |
| 23 | + |
| 24 | +LOG = logging.getLogger(__name__) |
| 25 | +logging.getLogger("localstack_typedb").setLevel( |
| 26 | + logging.DEBUG if config.DEBUG else logging.INFO |
| 27 | +) |
| 28 | +logging.basicConfig() |
| 29 | + |
| 30 | + |
| 31 | +class ProxiedDockerContainerExtension(Extension, ProxyRequestMatcher): |
| 32 | + """ |
| 33 | + Utility class to create a LocalStack Extension backed by a Docker container that exposes a service |
| 34 | + on a network port (or several ports), with requests being proxied through the LocalStack gateway. |
| 35 | +
|
| 36 | + Requests may potentially use HTTP2 with binary content as the protocol (e.g., gRPC over HTTP2). |
| 37 | + To ensure proper routing of requests, subclasses can define the `http2_ports`. |
| 38 | + """ |
| 39 | + |
| 40 | + name: str |
| 41 | + """Name of this extension""" |
| 42 | + image_name: str |
| 43 | + """Docker image name""" |
| 44 | + container_name: str | None |
| 45 | + """Name of the Docker container spun up by the extension""" |
| 46 | + container_ports: list[int] |
| 47 | + """List of network ports of the Docker container spun up by the extension""" |
| 48 | + host: str | None |
| 49 | + """ |
| 50 | + Optional host on which to expose the container endpoints. |
| 51 | + Can be either a static hostname, or a pattern like `<regex("(.+\.)?"):subdomain>myext.<domain>` |
| 52 | + """ |
| 53 | + path: str | None |
| 54 | + """Optional path on which to expose the container endpoints.""" |
| 55 | + command: list[str] | None |
| 56 | + """Optional command (and flags) to execute in the container.""" |
| 57 | + |
| 58 | + request_to_port_router: Callable[[Request], int] | None |
| 59 | + """Callable that returns the target port for a given request, for routing purposes""" |
| 60 | + http2_ports: list[int] | None |
| 61 | + """List of ports for which HTTP2 proxy forwarding into the container should be enabled.""" |
| 62 | + |
| 63 | + def __init__( |
| 64 | + self, |
| 65 | + image_name: str, |
| 66 | + container_ports: list[int], |
| 67 | + host: str | None = None, |
| 68 | + path: str | None = None, |
| 69 | + container_name: str | None = None, |
| 70 | + command: list[str] | None = None, |
| 71 | + request_to_port_router: Callable[[Request], int] | None = None, |
| 72 | + http2_ports: list[int] | None = None, |
| 73 | + ): |
| 74 | + self.image_name = image_name |
| 75 | + self.container_ports = container_ports |
| 76 | + self.host = host |
| 77 | + self.path = path |
| 78 | + self.container_name = container_name |
| 79 | + self.command = command |
| 80 | + self.request_to_port_router = request_to_port_router |
| 81 | + self.http2_ports = http2_ports |
| 82 | + |
| 83 | + def update_gateway_routes(self, router: http.Router[http.RouteHandler]): |
| 84 | + if self.path: |
| 85 | + raise NotImplementedError( |
| 86 | + "Path-based routing not yet implemented for this extension" |
| 87 | + ) |
| 88 | + # note: for simplicity, starting the external container at startup - could be optimized over time ... |
| 89 | + self.start_container() |
| 90 | + # add resource for HTTP/1.1 requests |
| 91 | + resource = RuleAdapter(ProxyResource(self)) |
| 92 | + if self.host: |
| 93 | + resource = WithHost(self.host, [resource]) |
| 94 | + router.add(resource) |
| 95 | + |
| 96 | + # apply patches to serve HTTP/2 requests |
| 97 | + for port in self.http2_ports or []: |
| 98 | + apply_http2_patches_for_grpc_support( |
| 99 | + get_addressable_container_host(), port, self |
| 100 | + ) |
| 101 | + |
| 102 | + def on_platform_shutdown(self): |
| 103 | + self._remove_container() |
| 104 | + |
| 105 | + def _get_container_name(self) -> str: |
| 106 | + if self.container_name: |
| 107 | + return self.container_name |
| 108 | + name = f"ls-ext-{self.name}" |
| 109 | + name = re.sub(r"\W", "-", name) |
| 110 | + return name |
| 111 | + |
| 112 | + def should_proxy_request(self, headers: Headers) -> bool: |
| 113 | + # determine if this is a gRPC request targeting TypeDB |
| 114 | + content_type = headers.get("content-type") or "" |
| 115 | + req_path = headers.get(":path") or "" |
| 116 | + is_typedb_grpc_request = ( |
| 117 | + "grpc" in content_type and "/typedb.protocol.TypeDB" in req_path |
| 118 | + ) |
| 119 | + return is_typedb_grpc_request |
| 120 | + |
| 121 | + @cache |
| 122 | + def start_container(self) -> None: |
| 123 | + container_name = self._get_container_name() |
| 124 | + LOG.debug("Starting extension container %s", container_name) |
| 125 | + |
| 126 | + ports = PortMappings() |
| 127 | + for port in self.container_ports: |
| 128 | + ports.add(port) |
| 129 | + |
| 130 | + kwargs = {} |
| 131 | + if self.command: |
| 132 | + kwargs["command"] = self.command |
| 133 | + |
| 134 | + try: |
| 135 | + DOCKER_CLIENT.run_container( |
| 136 | + self.image_name, |
| 137 | + detach=True, |
| 138 | + remove=True, |
| 139 | + name=container_name, |
| 140 | + ports=ports, |
| 141 | + **kwargs, |
| 142 | + ) |
| 143 | + except Exception as e: |
| 144 | + LOG.debug("Failed to start container %s: %s", container_name, e) |
| 145 | + # allow running TypeDB in a local server in dev mode, if TYPEDB_DEV_MODE is enabled |
| 146 | + if not is_env_true("TYPEDB_DEV_MODE"): |
| 147 | + raise |
| 148 | + |
| 149 | + main_port = self.container_ports[0] |
| 150 | + container_host = get_addressable_container_host() |
| 151 | + |
| 152 | + def _ping_endpoint(): |
| 153 | + # TODO: allow defining a custom healthcheck endpoint ... |
| 154 | + response = requests.get(f"http://{container_host}:{main_port}/") |
| 155 | + assert response.ok |
| 156 | + |
| 157 | + try: |
| 158 | + retry(_ping_endpoint, retries=40, sleep=1) |
| 159 | + except Exception as e: |
| 160 | + LOG.info("Failed to connect to container %s: %s", container_name, e) |
| 161 | + self._remove_container() |
| 162 | + raise |
| 163 | + |
| 164 | + LOG.debug("Successfully started extension container %s", container_name) |
| 165 | + |
| 166 | + def _remove_container(self): |
| 167 | + container_name = self._get_container_name() |
| 168 | + LOG.debug("Stopping extension container %s", container_name) |
| 169 | + DOCKER_CLIENT.remove_container( |
| 170 | + container_name, force=True, check_existence=False |
| 171 | + ) |
| 172 | + |
| 173 | + |
| 174 | +class ProxyResource: |
| 175 | + """ |
| 176 | + Simple proxy resource that forwards incoming requests from the |
| 177 | + LocalStack Gateway to the target Docker container. |
| 178 | + """ |
| 179 | + |
| 180 | + extension: ProxiedDockerContainerExtension |
| 181 | + |
| 182 | + def __init__(self, extension: ProxiedDockerContainerExtension): |
| 183 | + self.extension = extension |
| 184 | + |
| 185 | + @route("/<path:path>") |
| 186 | + def index(self, request: Request, path: str, *args, **kwargs): |
| 187 | + return self._proxy_request(request, forward_path=f"/{path}") |
| 188 | + |
| 189 | + def _proxy_request(self, request: Request, forward_path: str, *args, **kwargs): |
| 190 | + self.extension.start_container() |
| 191 | + |
| 192 | + port = self.extension.container_ports[0] |
| 193 | + container_host = get_addressable_container_host() |
| 194 | + base_url = f"http://{container_host}:{port}" |
| 195 | + proxy = Proxy(forward_base_url=base_url) |
| 196 | + |
| 197 | + # update content length (may have changed due to content compression) |
| 198 | + if request.method not in ("GET", "OPTIONS"): |
| 199 | + request.headers["Content-Length"] = str(len(request.data)) |
| 200 | + |
| 201 | + # make sure we're forwarding the correct Host header |
| 202 | + request.headers["Host"] = f"localhost:{port}" |
| 203 | + |
| 204 | + # forward the request to the target |
| 205 | + result = proxy.forward(request, forward_path=forward_path) |
| 206 | + |
| 207 | + return result |
0 commit comments