From cd31d58fc5bd0dd445f3fe85b58f67f8a393cea0 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Mon, 20 Jul 2026 11:16:23 -0400 Subject: [PATCH] refac --- README.md | 1 + terminals/backends/base.py | 73 +++++++++++++++++++++++++++++--- terminals/backends/docker.py | 8 ++-- terminals/backends/kubernetes.py | 20 +++++++-- terminals/config.py | 1 + terminals/routers/policy.py | 6 +-- terminals/routers/proxy.py | 27 +++--------- terminals/utils/policy_specs.py | 34 +++++++++++++++ 8 files changed, 134 insertions(+), 36 deletions(-) create mode 100644 terminals/utils/policy_specs.py diff --git a/README.md b/README.md index 5c84070..b134cd7 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ All settings are configured through environment variables prefixed with `TERMINA | `TERMINALS_KUBERNETES_CONTAINER_SECURITY_CONTEXT` | | JSON container security context merged into Kubernetes terminal containers | | `TERMINALS_KUBERNETES_NODE_SELECTOR` | | Node selector for Kubernetes terminal and reset pods, as JSON or `k=v,k2=v2` | | `TERMINALS_KUBERNETES_TOLERATIONS` | | JSON array of Kubernetes tolerations for terminal and reset pods | +| `TERMINALS_IDLE_CLEANUP_TIMEOUT_SECONDS` | `120` | Timeout for each teardown/reset call during idle cleanup | | `TERMINALS_DATABASE_URL` | `sqlite+aiosqlite:///.../data/terminals.db` | SQLAlchemy database URL. SQLite is the default; PostgreSQL is optional. | | `TERMINALS_LOG_LEVEL` | `INFO` | Minimum orchestrator log level: `DEBUG`, `INFO`, `WARNING`, `ERROR`, or `CRITICAL`. On Docker, `WARNING` or higher disables child container Docker logs because Open Terminal does not expose a log-level env var. | | `TERMINALS_STATUS_CACHE_TTL` | `30` | Seconds a confirmed-running container status is trusted before re-inspecting it via the backend. `0` re-checks on every request. The cache is invalidated immediately when a proxied connection fails. | diff --git a/terminals/backends/base.py b/terminals/backends/base.py index 89c8c9c..01bc984 100644 --- a/terminals/backends/base.py +++ b/terminals/backends/base.py @@ -15,6 +15,7 @@ from terminals.utils.policy_lifecycle import ( reset_due_for, terminal_last_active_at, ) +from terminals.utils.policy_specs import PolicyNotFoundError, resolve_policy_spec log = logging.getLogger(__name__) @@ -185,6 +186,34 @@ class Backend(ABC): await mark_terminal_active(user_id, policy_id) self._activity_synced_at[key] = time.monotonic() + async def _adopted_spec(self, policy_id: str) -> dict: + """Best-effort resolved spec for instances adopted during startup.""" + try: + _, spec = await resolve_policy_spec(policy_id) + return spec or {} + except PolicyNotFoundError: + return {} + except Exception: + log.exception("Failed to resolve policy spec for %r", policy_id) + return {} + + async def _seed_adopted_activity( + self, key: str, user_id: str, policy_id: str + ) -> None: + """Preserve persisted idle time when adopting an existing instance.""" + self._record_activity(key) + try: + last_active = await terminal_last_active_at(user_id, policy_id) + except Exception: + log.exception("Failed to load persisted activity for %s", key) + return + if not last_active: + return + wall = last_active.replace(tzinfo=timezone.utc).timestamp() + if wall < self._activity_wall[key]: + self._activity_wall[key] = wall + self._activity[key] = time.monotonic() - (time.time() - wall) + async def _apply_due_reset( self, user_id: str, policy_id: str, spec: Optional[dict] ) -> bool: @@ -334,6 +363,7 @@ class Backend(ABC): spec = self._specs.get(key, {}) user_id, policy_id = key.split(":", 1) + cleanup_timeout = settings.idle_cleanup_timeout_seconds if await reset_due_for(user_id, policy_id, spec): log.info( "Refreshing terminal %s for due reset (user=%s, policy=%s)", @@ -342,14 +372,31 @@ class Backend(ABC): policy_id, ) try: - await self.teardown(info["instance_id"]) + await asyncio.wait_for( + self.teardown(info["instance_id"]), cleanup_timeout + ) + except asyncio.TimeoutError: + log.error( + "Teardown of %s timed out after %.0fs; will retry next sweep", + key, + cleanup_timeout, + ) + continue except Exception: log.exception("Failed to tear down %s for scheduled reset", key) try: - await self.reset(user_id, policy_id, spec) - await mark_reset_applied(user_id, policy_id, spec) + await asyncio.wait_for( + self.reset(user_id, policy_id, spec), cleanup_timeout + ) + await asyncio.wait_for( + mark_reset_applied(user_id, policy_id, spec), cleanup_timeout + ) except NotImplementedError: log.warning("Reset due for %s but backend does not support it", key) + except asyncio.TimeoutError: + log.error( + "Reset for %s timed out after %.0fs", key, cleanup_timeout + ) except Exception: log.exception("Failed to reset files for %s", key) self._instances.pop(key, None) @@ -387,13 +434,29 @@ class Backend(ABC): timeout_min, ) try: - await self.teardown(info["instance_id"]) + await asyncio.wait_for( + self.teardown(info["instance_id"]), cleanup_timeout + ) + except asyncio.TimeoutError: + log.error( + "Teardown of %s timed out after %.0fs; will retry next sweep", + key, + cleanup_timeout, + ) + continue except Exception: log.exception("Failed to tear down %s", key) try: - await self._apply_due_reset(user_id, policy_id, spec) + await asyncio.wait_for( + self._apply_due_reset(user_id, policy_id, spec), + cleanup_timeout, + ) except NotImplementedError: log.warning("Reset due for %s but backend does not support it", key) + except asyncio.TimeoutError: + log.error( + "Reset for %s timed out after %.0fs", key, cleanup_timeout + ) except Exception: log.exception("Failed to reset files for %s", key) self._instances.pop(key, None) diff --git a/terminals/backends/docker.py b/terminals/backends/docker.py index 371e159..ffb6e48 100644 --- a/terminals/backends/docker.py +++ b/terminals/backends/docker.py @@ -6,7 +6,6 @@ import logging import re import secrets import shutil -import time from pathlib import Path from typing import Optional @@ -248,6 +247,7 @@ class DockerBackend(Backend): ) recovered = 0 + adopted_specs: dict[str, dict] = {} for container in containers: info = await container.show() name = info.get("Name", "").lstrip("/") @@ -272,9 +272,11 @@ class DockerBackend(Backend): break instance_info = await self._extract_instance_info(container, name, api_key) + if policy_id not in adopted_specs: + adopted_specs[policy_id] = await self._adopted_spec(policy_id) self._instances[key] = instance_info - self._activity[key] = time.monotonic() - self._activity_wall[key] = time.time() + self._specs[key] = adopted_specs[policy_id] + await self._seed_adopted_activity(key, user_id, policy_id) recovered += 1 log.info("Reconciled container %s → %s:%s", name, instance_info["host"], instance_info["port"]) diff --git a/terminals/backends/kubernetes.py b/terminals/backends/kubernetes.py index 282807f..d635963 100644 --- a/terminals/backends/kubernetes.py +++ b/terminals/backends/kubernetes.py @@ -6,7 +6,6 @@ import hashlib import logging import re import secrets -import time from typing import Optional from kubernetes_asyncio import client, config @@ -29,6 +28,7 @@ log = logging.getLogger(__name__) # --------------------------------------------------------------------------- _DNS_SAFE = re.compile(r"[^a-z0-9-]") +_POLICY_ID_ANNOTATION = "openwebui.com/policy-id" def _sanitize_name(user_id: str, policy_id: str = "default") -> str: @@ -103,6 +103,7 @@ class KubernetesBackend(Backend): ns = settings.kubernetes_namespace labels = _base_labels(user_id) labels["openwebui.com/policy"] = policy_slug + annotations = {_POLICY_ID_ANNOTATION: policy_id} image = s.get("image", settings.kubernetes_image) storage_mode = s.get("storage_mode", settings.kubernetes_storage_mode) @@ -249,7 +250,12 @@ class KubernetesBackend(Backend): # ---- Pod --------------------------------------------------------- pod = client.V1Pod( - metadata=client.V1ObjectMeta(name=name, namespace=ns, labels=labels), + metadata=client.V1ObjectMeta( + name=name, + namespace=ns, + labels=labels, + annotations=annotations, + ), spec=client.V1PodSpec( containers=[ client.V1Container( @@ -530,13 +536,16 @@ class KubernetesBackend(Backend): return recovered = 0 + adopted_specs: dict[str, dict] = {} for pod in pods.items: if pod.status.phase not in ("Running", "Pending"): continue labels = pod.metadata.labels or {} + annotations = pod.metadata.annotations or {} user_id = labels.get("openwebui.com/user-id") policy_slug = labels.get("openwebui.com/policy", "default") + policy_id = annotations.get(_POLICY_ID_ANNOTATION, policy_slug) if not user_id: continue @@ -544,7 +553,7 @@ class KubernetesBackend(Backend): name = pod.metadata.name self._uid_cache[uid] = name - key = self._key(user_id, policy_slug) + key = self._key(user_id, policy_id) if key in self._instances: continue @@ -563,6 +572,8 @@ class KubernetesBackend(Backend): continue host = f"{name}.{ns}.svc.cluster.local" + if policy_id not in adopted_specs: + adopted_specs[policy_id] = await self._adopted_spec(policy_id) self._instances[key] = { "instance_id": uid, "instance_name": name, @@ -570,7 +581,8 @@ class KubernetesBackend(Backend): "host": host, "port": 8000, } - self._activity[key] = time.monotonic() + self._specs[key] = adopted_specs[policy_id] + await self._seed_adopted_activity(key, user_id, policy_id) recovered += 1 if recovered: diff --git a/terminals/config.py b/terminals/config.py index da58f11..55a1cb3 100644 --- a/terminals/config.py +++ b/terminals/config.py @@ -74,6 +74,7 @@ class Settings(BaseSettings): # Idle reaper — tear down terminals after N minutes of inactivity (0 = disabled) idle_timeout_minutes: int = 0 + idle_cleanup_timeout_seconds: float = 120 # Policy hard caps (cannot be exceeded by API) max_cpu: str = "" # TERMINALS_MAX_CPU diff --git a/terminals/routers/policy.py b/terminals/routers/policy.py index eee7076..5d6223c 100644 --- a/terminals/routers/policy.py +++ b/terminals/routers/policy.py @@ -14,6 +14,7 @@ from terminals.utils.policy_lifecycle import ( upsert_lifecycle_data, validate_lifecycle_data, ) +from terminals.utils.policy_specs import merge_policy_defaults from terminals.utils.kubernetes_security import ( restricted_enabled, restricted_env_errors, @@ -130,10 +131,7 @@ def _validate_lifecycle(data: dict) -> dict: def _merge_defaults(policy_data: dict) -> dict: """Merge env var defaults with policy overrides.""" - defaults = {} - if settings.image: - defaults["image"] = settings.image - return {**defaults, **{k: v for k, v in policy_data.items() if v is not None}} + return merge_policy_defaults(policy_data) # --------------------------------------------------------------------------- diff --git a/terminals/routers/proxy.py b/terminals/routers/proxy.py index 56c5d75..79513a6 100644 --- a/terminals/routers/proxy.py +++ b/terminals/routers/proxy.py @@ -24,6 +24,7 @@ from fastapi.responses import JSONResponse, StreamingResponse from loguru import logger from terminals.config import settings +from terminals.utils.policy_specs import PolicyNotFoundError, resolve_policy_spec from terminals.routers.auth import validate_token, verify_api_key, verify_user_id router = APIRouter() @@ -390,26 +391,12 @@ async def _resolve_policy_spec(policy_id: str) -> tuple[str, dict | None]: 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: - 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 - 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") - - result = (policy_id, _merge_defaults(policy.data or {})) - _policy_cache[policy_id] = (now, result) - return result + try: + result = await resolve_policy_spec(policy_id) + except PolicyNotFoundError: + raise HTTPException(status_code=404, detail=f"Policy '{policy_id}' not found") + _policy_cache[policy_id] = (now, result) + return result @router.get( diff --git a/terminals/utils/policy_specs.py b/terminals/utils/policy_specs.py new file mode 100644 index 0000000..6da1eb8 --- /dev/null +++ b/terminals/utils/policy_specs.py @@ -0,0 +1,34 @@ +"""Shared helpers for resolved terminal policy specs.""" + +from terminals.config import settings +from terminals.db.session import async_session + + +class PolicyNotFoundError(Exception): + """Raised when a named policy does not exist.""" + + +def merge_policy_defaults(policy_data: dict) -> dict: + """Merge env var defaults with policy overrides.""" + defaults = {} + if settings.image: + defaults["image"] = settings.image + return {**defaults, **{k: v for k, v in policy_data.items() if v is not None}} + + +async def resolve_policy_spec(policy_id: str) -> tuple[str, dict | None]: + """Look up a policy by ID. Returns (policy_id, merged spec).""" + if async_session is None: + return policy_id, None + + from sqlalchemy import select + + from terminals.models.policy import Policy + + async with async_session() as session: + row = await session.execute(select(Policy).where(Policy.id == policy_id)) + policy = row.scalar_one_or_none() + if policy is None: + raise PolicyNotFoundError(policy_id) + + return policy_id, merge_policy_defaults(policy.data or {})