From 8ca2313cb6e2b09f64e381f222dce91849efce85 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Fri, 13 Mar 2026 01:50:53 -0500 Subject: [PATCH] refac --- terminals/backends/docker.py | 37 +++++----- terminals/backends/kubernetes.py | 3 + terminals/backends/kubernetes_operator.py | 87 ++++++++++++++--------- terminals/routers/proxy.py | 1 - 4 files changed, 75 insertions(+), 53 deletions(-) diff --git a/terminals/backends/docker.py b/terminals/backends/docker.py index 1a886f0..d95cf98 100644 --- a/terminals/backends/docker.py +++ b/terminals/backends/docker.py @@ -7,6 +7,7 @@ from pathlib import Path from typing import Optional import aiodocker +import httpx from terminals.backends.base import Backend from terminals.config import settings @@ -92,29 +93,28 @@ class DockerBackend(Backend): log.info("Provisioning container %s for user %s (policy=%s)", instance_name, user_id, policy_id) - try: - container = await docker.containers.create_or_replace( - name=instance_name, - config=config, - ) - await container.start() - except aiodocker.exceptions.DockerError as exc: - if exc.status == 409: - # Container name conflict (e.g. stale container being removed). - # Force-remove and retry. - log.warning("Container %s conflict, force-removing and retrying", instance_name) - try: - old = await docker.containers.get(instance_name) - await old.delete(force=True) - except aiodocker.exceptions.DockerError: - pass - await asyncio.sleep(1) + max_conflict_retries = 3 + for attempt in range(max_conflict_retries + 1): + try: container = await docker.containers.create_or_replace( name=instance_name, config=config, ) await container.start() - else: + break + except aiodocker.exceptions.DockerError as exc: + if exc.status == 409 and attempt < max_conflict_retries: + log.warning( + "Container %s conflict (attempt %d/%d), force-removing and retrying", + instance_name, attempt + 1, max_conflict_retries, + ) + try: + old = await docker.containers.get(instance_name) + await old.delete(force=True) + except aiodocker.exceptions.DockerError: + pass + await asyncio.sleep(1) + continue log.error("Failed to provision container for %s: %s", user_id, exc) raise @@ -124,7 +124,6 @@ class DockerBackend(Backend): async def _wait_until_ready(self, instance: dict, timeout: int = 15) -> None: """Poll the container's /health endpoint until it responds.""" - import httpx url = f"http://{instance['host']}:{instance['port']}/health" deadline = asyncio.get_event_loop().time() + timeout diff --git a/terminals/backends/kubernetes.py b/terminals/backends/kubernetes.py index 4fafca3..5100bcf 100644 --- a/terminals/backends/kubernetes.py +++ b/terminals/backends/kubernetes.py @@ -333,6 +333,9 @@ class KubernetesBackend(Backend): except client.exceptions.ApiException: log.warning("Could not delete Service %s", name) + # Clean up UID cache. + self._uid_cache.pop(instance_id, None) + # Note: PVC is intentionally kept for data persistence. async def status(self, instance_id: str) -> str: diff --git a/terminals/backends/kubernetes_operator.py b/terminals/backends/kubernetes_operator.py index d9689ec..e490a35 100644 --- a/terminals/backends/kubernetes_operator.py +++ b/terminals/backends/kubernetes_operator.py @@ -495,54 +495,75 @@ class KubernetesOperatorBackend(Backend): ) -> Optional[dict]: """Get or create a terminal, resolving from K8s CRDs. - Mirrors the reference ``ensure_terminal`` pattern: - - If no CR exists → create and wait for ready. - - If Idle → delete CR and re-create (operator spawns fresh pod). - - If Running → return connection info immediately. - - If Pending/Provisioning → wait for ready. + Uses a per-key lock so concurrent requests for the same user+policy + don't race to create the same CR. Returns a dict with ``api_key``, ``host``, ``port`` or ``None``. """ + key = self._key(user_id, policy_id) + + # Fast path — check if CR is already Running (no lock needed). cr = await self._get_terminal_cr(user_id, policy_id) + if cr: + status = cr.get("status") or {} + phase = status.get("phase") + if phase == "Running" and status.get("serviceUrl") and status.get("apiKeySecret"): + api_key = await self._read_api_key_from_secret(status["apiKeySecret"]) + if api_key: + host, port = self._parse_service_url(status["serviceUrl"]) + return { + "instance_id": cr["metadata"]["uid"], + "instance_name": cr["metadata"]["name"], + "api_key": api_key, + "host": host, + "port": port, + } - if cr is None: - return await self.provision(user_id, policy_id=policy_id, spec=spec) + # Serialise provisioning per key. + if key not in self._locks: + self._locks[key] = asyncio.Lock() - status = cr.get("status") or {} - phase = status.get("phase") + async with self._locks[key]: + # Re-check after acquiring lock. + cr = await self._get_terminal_cr(user_id, policy_id) - if phase == "Idle": - # Terminal was idled — delete and re-create to spawn a fresh pod - await self._delete_terminal_cr(user_id, policy_id) - return await self.provision(user_id, policy_id=policy_id, spec=spec) + if cr is None: + return await self.provision(user_id, policy_id=policy_id, spec=spec) - if phase == "Running" and status.get("serviceUrl") and status.get("apiKeySecret"): - api_key = await self._read_api_key_from_secret(status["apiKeySecret"]) - if api_key: - host, port = self._parse_service_url(status["serviceUrl"]) + status = cr.get("status") or {} + phase = status.get("phase") + + if phase == "Idle": + await self._delete_terminal_cr(user_id, policy_id) + return await self.provision(user_id, policy_id=policy_id, spec=spec) + + if phase == "Running" and status.get("serviceUrl") and status.get("apiKeySecret"): + api_key = await self._read_api_key_from_secret(status["apiKeySecret"]) + if api_key: + host, port = self._parse_service_url(status["serviceUrl"]) + return { + "instance_id": cr["metadata"]["uid"], + "instance_name": cr["metadata"]["name"], + "api_key": api_key, + "host": host, + "port": port, + } + + # Still provisioning — wait for the operator to bring it up + name = cr["metadata"]["name"] + ns = settings.kubernetes_namespace + ready = await self._wait_for_ready(name, ns, timeout=120) + if ready: + host, port = self._parse_service_url(ready["service_url"]) return { "instance_id": cr["metadata"]["uid"], "instance_name": cr["metadata"]["name"], - "api_key": api_key, + "api_key": ready["api_key"], "host": host, "port": port, } - # Still provisioning — wait for the operator to bring it up - name = cr["metadata"]["name"] - ns = settings.kubernetes_namespace - ready = await self._wait_for_ready(name, ns, timeout=120) - if ready: - host, port = self._parse_service_url(ready["service_url"]) - return { - "instance_id": cr["metadata"]["uid"], - "instance_name": cr["metadata"]["name"], - "api_key": ready["api_key"], - "host": host, - "port": port, - } - - return None + return None async def get_terminal_info(self, user_id: str) -> Optional[dict]: """Look up an existing terminal from the K8s CRD without creating one.""" diff --git a/terminals/routers/proxy.py b/terminals/routers/proxy.py index d72e2e9..e39309b 100644 --- a/terminals/routers/proxy.py +++ b/terminals/routers/proxy.py @@ -143,7 +143,6 @@ async def _proxy_request( client = await _get_proxy_client() # Retry on connection errors — the container may still be starting. - import httpx max_retries = 5 for attempt in range(max_retries): try: