From 03e1fa88e4506601bdf2891b46d3ff952b6af5fe Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 15 Mar 2026 18:25:49 -0500 Subject: [PATCH] refac --- README.md | 5 +- terminals/backends/base.py | 1 + terminals/backends/docker.py | 33 ++------ terminals/backends/kubernetes.py | 3 +- terminals/main.py | 2 + terminals/routers/auth.py | 7 ++ terminals/routers/policy.py | 15 +--- terminals/routers/proxy.py | 135 ++++++++++++++++++++----------- terminals/utils/parsing.py | 33 ++++++++ 9 files changed, 144 insertions(+), 90 deletions(-) create mode 100644 terminals/utils/parsing.py diff --git a/README.md b/README.md index bb251ec..a488596 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,9 @@ Per-user [Open Terminal](https://github.com/open-webui/open-terminal) orchestrat Giving terminal access to users on Open WebUI requires per-user isolation: separate containers, each with their own credentials and resource constraints. Terminals handles the full lifecycle: provisioning containers on demand, proxying traffic per user, enforcing resource and network policies, validating Open WebUI JWTs natively, and cleaning up idle instances. +> [!IMPORTANT] +> **Production use requires an [Open WebUI Enterprise License](LICENSE) that includes Terminals.** Contact the Open WebUI team to verify your plan covers it. + | Capability | | |---|---| | **Backends** | Docker, Kubernetes, K8s Operator | @@ -105,4 +108,4 @@ See [`config.py`](terminals/config.py) for the full list. ## License -[Open WebUI Enterprise License](LICENSE) +[Open WebUI Enterprise License](LICENSE) — production use requires an enterprise plan that includes Terminals. diff --git a/terminals/backends/base.py b/terminals/backends/base.py index 6d3a915..f773eb2 100644 --- a/terminals/backends/base.py +++ b/terminals/backends/base.py @@ -204,3 +204,4 @@ class Backend(ABC): self._instances.pop(key, None) self._specs.pop(key, None) self._activity.pop(key, None) + self._locks.pop(key, None) diff --git a/terminals/backends/docker.py b/terminals/backends/docker.py index d95cf98..726e150 100644 --- a/terminals/backends/docker.py +++ b/terminals/backends/docker.py @@ -3,6 +3,7 @@ import asyncio import logging import secrets +import time from pathlib import Path from typing import Optional @@ -11,6 +12,7 @@ import httpx from terminals.backends.base import Backend from terminals.config import settings +from terminals.utils.parsing import parse_cpu_nanos, parse_memory log = logging.getLogger(__name__) @@ -60,9 +62,9 @@ class DockerBackend(Backend): # Resources if s.get("memory_limit"): - host_config["Memory"] = self._parse_memory(s["memory_limit"]) + host_config["Memory"] = parse_memory(s["memory_limit"]) if s.get("cpu_limit"): - host_config["NanoCpus"] = self._parse_cpu_nanos(s["cpu_limit"]) + host_config["NanoCpus"] = parse_cpu_nanos(s["cpu_limit"]) # Egress filtering is handled inside the container (dnsmasq + ipset + # iptables + capsh) triggered by OPEN_TERMINAL_ALLOWED_DOMAINS env var. @@ -222,7 +224,7 @@ class DockerBackend(Backend): instance_info = await self._extract_instance_info(container, name, api_key) self._instances[key] = instance_info - self._activity[key] = __import__("time").monotonic() + self._activity[key] = time.monotonic() recovered += 1 log.info("Reconciled container %s → %s:%s", name, instance_info["host"], instance_info["port"]) @@ -230,32 +232,9 @@ class DockerBackend(Backend): log.info("Reconciled %d running container(s)", recovered) # ------------------------------------------------------------------ - # Resource parsing helpers + # Container lifecycle # ------------------------------------------------------------------ - @staticmethod - def _parse_memory(value: str) -> int: - """Parse K8s memory string to bytes. '512Mi' -> 536870912.""" - import re - m = re.match(r"^(\d+(?:\.\d+)?)\s*(Ki|Mi|Gi|Ti)?$", str(value).strip()) - if not m: - return int(value) - num, suffix = float(m.group(1)), m.group(2) or "" - mult = {"": 1, "Ki": 1024, "Mi": 1024**2, "Gi": 1024**3, "Ti": 1024**4} - return int(num * mult[suffix]) - - @staticmethod - def _parse_cpu_nanos(value: str) -> int: - """Parse K8s CPU string to nanocpus. '2' -> 2_000_000_000, '500m' -> 500_000_000.""" - import re - m = re.match(r"^(\d+(?:\.\d+)?)\s*(m)?$", str(value).strip()) - if not m: - return int(float(value) * 1_000_000_000) - num, suffix = float(m.group(1)), m.group(2) or "" - if suffix == "m": - return int(num * 1_000_000) - return int(num * 1_000_000_000) - async def start(self, instance_id: str) -> bool: current = await self.status(instance_id) if current == "running": diff --git a/terminals/backends/kubernetes.py b/terminals/backends/kubernetes.py index 5100bcf..26e49a6 100644 --- a/terminals/backends/kubernetes.py +++ b/terminals/backends/kubernetes.py @@ -4,6 +4,7 @@ import asyncio import logging import re import secrets +import time from typing import Optional from kubernetes_asyncio import client, config @@ -435,7 +436,7 @@ class KubernetesBackend(Backend): "host": host, "port": 8000, } - self._activity[key] = __import__("time").monotonic() + self._activity[key] = time.monotonic() recovered += 1 if recovered: diff --git a/terminals/main.py b/terminals/main.py index d666402..06f8308 100644 --- a/terminals/main.py +++ b/terminals/main.py @@ -10,6 +10,7 @@ from terminals.config import settings from terminals.db.session import close_db, init_db from terminals.logging import setup_logging from terminals.middleware import RequestIdMiddleware +from terminals.routers.auth import close_auth_client from terminals.routers.proxy import close_proxy_client, router as proxy_router @@ -33,6 +34,7 @@ async def lifespan(app: FastAPI): await app.state.backend.stop_reaper() await close_proxy_client() + await close_auth_client() await app.state.backend.close() await close_db() diff --git a/terminals/routers/auth.py b/terminals/routers/auth.py index f12e74f..c8d207b 100644 --- a/terminals/routers/auth.py +++ b/terminals/routers/auth.py @@ -17,6 +17,13 @@ async def _get_owui_client() -> httpx.AsyncClient: return _owui_client +async def close_auth_client() -> None: + global _owui_client + if _owui_client is not None: + await _owui_client.aclose() + _owui_client = None + + async def validate_token(token: str) -> Optional[str]: """Validate a bearer token against the Open WebUI instance. diff --git a/terminals/routers/policy.py b/terminals/routers/policy.py index 107c5bd..b66a129 100644 --- a/terminals/routers/policy.py +++ b/terminals/routers/policy.py @@ -9,6 +9,7 @@ from pydantic import BaseModel from terminals.config import settings from terminals.db.session import async_session from terminals.routers.auth import verify_api_key +from terminals.utils.parsing import parse_size router = APIRouter(prefix="/api/v1", tags=["policies"]) @@ -46,16 +47,6 @@ class PolicyCreate(BaseModel): # --------------------------------------------------------------------------- -def _parse_size(value: str) -> int: - """Parse K8s-style size string to bytes. '512Mi' -> 536870912.""" - import re - m = re.match(r"^(\d+(?:\.\d+)?)\s*(Ki|Mi|Gi|Ti)?$", str(value).strip()) - if not m: - return int(value) - num, suffix = float(m.group(1)), m.group(2) or "" - mult = {"": 1, "Ki": 1024, "Mi": 1024**2, "Gi": 1024**3, "Ti": 1024**4} - return int(num * mult[suffix]) - def _clamp_policy(data: dict) -> dict: """Clamp policy values against env var hard caps.""" @@ -72,7 +63,7 @@ def _clamp_policy(data: dict) -> dict: # Clamp memory if settings.max_memory and "memory_limit" in result: try: - if _parse_size(result["memory_limit"]) > _parse_size(settings.max_memory): + if parse_size(result["memory_limit"]) > parse_size(settings.max_memory): result["memory_limit"] = settings.max_memory except Exception: pass @@ -80,7 +71,7 @@ def _clamp_policy(data: dict) -> dict: # Clamp storage if settings.max_storage and "storage" in result: try: - if _parse_size(result["storage"]) > _parse_size(settings.max_storage): + if parse_size(result["storage"]) > parse_size(settings.max_storage): result["storage"] = settings.max_storage except Exception: pass diff --git a/terminals/routers/proxy.py b/terminals/routers/proxy.py index e39309b..1461ab9 100644 --- a/terminals/routers/proxy.py +++ b/terminals/routers/proxy.py @@ -18,7 +18,7 @@ from typing import Optional import httpx import websockets from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Query, Request, Response, WebSocket -from fastapi.responses import JSONResponse +from fastapi.responses import JSONResponse, StreamingResponse from loguru import logger from terminals.config import settings @@ -122,7 +122,11 @@ async def _proxy_request( policy_id: str = "default", spec: Optional[dict] = None, ) -> Response: - """Forward an HTTP request to the user's terminal instance.""" + """Forward an HTTP request to the user's terminal instance. + + Streams both the request body (upload) and response body (download) + to avoid buffering large payloads in memory. + """ instance = await _resolve_instance( request, user_id, policy_id=policy_id, spec=spec, ) @@ -138,6 +142,7 @@ async def _proxy_request( for h in ("host", "transfer-encoding", "connection", "x-user-id"): headers.pop(h, None) + # Read the request body upfront (needed for retries). body = await request.body() client = await _get_proxy_client() @@ -146,11 +151,14 @@ async def _proxy_request( max_retries = 5 for attempt in range(max_retries): try: - upstream = await client.request( - method=request.method, - url=target_url, - headers=headers, - content=body, + upstream_resp = await client.send( + client.build_request( + method=request.method, + url=target_url, + headers=headers, + content=body, + ), + stream=True, ) break except (httpx.ConnectError, httpx.ConnectTimeout) as e: @@ -160,20 +168,21 @@ async def _proxy_request( else: logger.error("Proxy request to {} failed after {} retries: {}", target_url, max_retries, e) return Response( - content=f'{{"error": "Terminal instance not reachable"}}', + content='{"error": "Terminal instance not reachable"}', status_code=502, media_type="application/json", ) - # Strip hop-by-hop from response too. - response_headers = dict(upstream.headers) - for h in ("transfer-encoding", "connection", "content-encoding", "content-length"): + # Strip hop-by-hop from response. + response_headers = dict(upstream_resp.headers) + for h in ("transfer-encoding", "connection", "content-encoding"): response_headers.pop(h, None) - return Response( - content=upstream.content, - status_code=upstream.status_code, + return StreamingResponse( + content=upstream_resp.aiter_bytes(), + status_code=upstream_resp.status_code, headers=response_headers, + background=BackgroundTasks([upstream_resp.aclose]), ) @@ -182,8 +191,7 @@ async def _proxy_request( # --------------------------------------------------------------------------- _SPEC_CACHE_TTL = 300 # seconds -_cached_spec: Optional[dict] = None -_cached_spec_ts: float = 0.0 +_spec_cache: dict[str, tuple[float, dict]] = {} # key → (timestamp, spec) _SYSTEM_USER_ID = "system" @@ -216,14 +224,49 @@ async def _fetch_spec_with_retry(instance: InstanceInfo) -> dict: raise last_err -def _strip_auth_from_spec(spec: dict) -> None: - """Remove security schemes — auth is handled transparently by the proxy.""" +def _strip_auth_from_spec(spec: dict) -> dict: + """Remove security schemes — auth is handled transparently by the proxy. + + Returns a shallow copy to avoid mutating the cached dict. + """ + spec = {**spec} spec.pop("security", None) - spec.get("components", {}).pop("securitySchemes", None) - for _path_methods in spec.get("paths", {}).values(): - for _op in _path_methods.values(): - if isinstance(_op, dict): - _op.pop("security", None) + components = spec.get("components") + if components: + spec["components"] = {**components} + spec["components"].pop("securitySchemes", None) + paths = spec.get("paths") + if paths: + new_paths = {} + for path_key, path_methods in paths.items(): + new_methods = {} + for method, op in path_methods.items(): + if isinstance(op, dict) and "security" in op: + op = {k: v for k, v in op.items() if k != "security"} + new_methods[method] = op + new_paths[path_key] = new_methods + spec["paths"] = new_paths + return spec + + +async def _get_cached_spec( + request: Request, + policy_id: str = "default", + spec: Optional[dict] = None, +) -> dict: + """Return cached OpenAPI spec, fetching from a system instance if stale.""" + now = time.monotonic() + cached = _spec_cache.get(policy_id) + if cached and (now - cached[0]) < _SPEC_CACHE_TTL: + return cached[1] + + instance = await _resolve_instance( + request, _SYSTEM_USER_ID, policy_id=policy_id, spec=spec, + ) + raw = await _fetch_spec_with_retry(instance) + stripped = _strip_auth_from_spec(raw) + _spec_cache[policy_id] = (now, stripped) + return stripped @router.get( @@ -237,29 +280,14 @@ async def get_openapi_spec(request: Request): This endpoint does **not** require ``X-User-Id`` — it is used by Open WebUI for tool discovery before any user context exists. """ - global _cached_spec, _cached_spec_ts - - now = time.monotonic() - if _cached_spec is not None and (now - _cached_spec_ts) < _SPEC_CACHE_TTL: - return JSONResponse(content=_cached_spec) - - # Provision a system instance to fetch the spec from. - instance = await _resolve_instance(request, _SYSTEM_USER_ID) - try: - spec = await _fetch_spec_with_retry(instance) + spec = await _get_cached_spec(request) except Exception as e: logger.error("Failed to fetch OpenAPI spec from instance: {}", e) return JSONResponse( content={"error": "Failed to fetch OpenAPI spec from terminal instance"}, status_code=502, ) - - _strip_auth_from_spec(spec) - - _cached_spec = spec - _cached_spec_ts = now - return JSONResponse(content=spec) @@ -267,25 +295,37 @@ async def get_openapi_spec(request: Request): # Named policy proxy — /p/{policy_id}/{path} # --------------------------------------------------------------------------- +_POLICY_CACHE_TTL = 60 # seconds +_policy_cache: dict[str, tuple[float, tuple[str, dict | None]]] = {} + async def _resolve_policy_spec(policy_id: str) -> tuple[str, dict | None]: - """Look up a policy by ID. Returns (policy_id, merged spec) or raises 404.""" + """Look up a policy by ID (cached for 60s). Returns (policy_id, merged spec).""" + now = time.monotonic() + cached = _policy_cache.get(policy_id) + if cached and (now - cached[0]) < _POLICY_CACHE_TTL: + return cached[1] + from terminals.db.session import async_session as db_session if db_session is None: - return policy_id, None + result = (policy_id, None) + _policy_cache[policy_id] = (now, result) + return result from terminals.models.policy import Policy from terminals.routers.policy import _merge_defaults async with db_session() as session: from sqlalchemy import select - result = await session.execute(select(Policy).where(Policy.id == policy_id)) - policy = result.scalar_one_or_none() + row = await session.execute(select(Policy).where(Policy.id == policy_id)) + policy = row.scalar_one_or_none() if policy is None: raise HTTPException(status_code=404, detail=f"Policy '{policy_id}' not found") - return policy_id, _merge_defaults(policy.data or {}) + result = (policy_id, _merge_defaults(policy.data or {})) + _policy_cache[policy_id] = (now, result) + return result @router.get( @@ -296,12 +336,11 @@ async def policy_openapi_spec( policy_id: str, request: Request, ): - """Serve the OpenAPI spec via a named policy container.""" + """Serve the OpenAPI spec via a named policy container (cached).""" _id, spec = await _resolve_policy_spec(policy_id) - instance = await _resolve_instance(request, _SYSTEM_USER_ID, policy_id=_id, spec=spec) try: - spec_data = await _fetch_spec_with_retry(instance) + spec_data = await _get_cached_spec(request, policy_id=_id, spec=spec) except Exception as e: logger.error("Failed to fetch OpenAPI spec from policy instance: {}", e) return JSONResponse( @@ -309,8 +348,6 @@ async def policy_openapi_spec( status_code=502, ) - _strip_auth_from_spec(spec_data) - return JSONResponse(content=spec_data) diff --git a/terminals/utils/parsing.py b/terminals/utils/parsing.py new file mode 100644 index 0000000..1c5c2b5 --- /dev/null +++ b/terminals/utils/parsing.py @@ -0,0 +1,33 @@ +"""Shared parsing utilities for K8s-style resource strings.""" + +import re + +_SIZE_RE = re.compile(r"^(\d+(?:\.\d+)?)\s*(Ki|Mi|Gi|Ti)?$") +_CPU_RE = re.compile(r"^(\d+(?:\.\d+)?)\s*(m)?$") + +_SIZE_MULT = {"": 1, "Ki": 1024, "Mi": 1024**2, "Gi": 1024**3, "Ti": 1024**4} + + +def parse_size(value: str) -> int: + """Parse K8s-style size string to bytes. '512Mi' → 536_870_912.""" + m = _SIZE_RE.match(str(value).strip()) + if not m: + return int(value) + num, suffix = float(m.group(1)), m.group(2) or "" + return int(num * _SIZE_MULT[suffix]) + + +def parse_memory(value: str) -> int: + """Alias for ``parse_size`` — parses memory values to bytes.""" + return parse_size(value) + + +def parse_cpu_nanos(value: str) -> int: + """Parse K8s CPU string to nanocpus. '2' → 2_000_000_000, '500m' → 500_000_000.""" + m = _CPU_RE.match(str(value).strip()) + if not m: + return int(float(value) * 1_000_000_000) + num, suffix = float(m.group(1)), m.group(2) or "" + if suffix == "m": + return int(num * 1_000_000) + return int(num * 1_000_000_000)