This commit is contained in:
Timothy Jaeryang Baek committed 2026-03-13 01:50:53 -05:00
1 parent 07f9c48726
commit 8ca2313cb6
4 files changed
+75 -53

No files matched your search

+18 -19
View File
@@ -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
+3
View File
@@ -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:
+54 -33
View File
@@ -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."""
-1
View File
@@ -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: