This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-07 21:55:29 +09:00
1 parent e09253c73a
commit be1e682f99
9 files changed
+55 -17

No files matched your search

+3 -1
View File
@@ -140,6 +140,7 @@ curl -fsS http://localhost:3000/p/data-science/execute \
| `storage` | Storage size, such as `"5Gi"`; behavior depends on the backend below |
| `storage_mode` | Direct Kubernetes: `per-user`, `shared`, or `shared-rwo` |
| `idle_timeout_minutes` | Stop terminals after this many idle minutes; `0` disables idle cleanup |
| `max_lifetime_minutes` | Stop terminals this many minutes after they start, even while in use; `0` disables the limit |
| `restricted` | Restricted Kubernetes/OpenShift defaults |
| `pod_security_context`, `container_security_context` | Kubernetes security context overrides |
| `podTemplate` | Kubernetes pod overrides, including volumes, scheduling, and health probes |
@@ -203,7 +204,7 @@ Schedules support one-time ISO datetimes, `@weekly`, `@monthly`, and five-field
## Storage and persistence
Stopping or reaping a terminal preserves its persisted files. Idle cleanup is disabled by default; enable it with `TERMINALS_IDLE_TIMEOUT_MINUTES` or a policy. File resets and user-data deletion are separate, destructive actions.
Stopping or reaping a terminal preserves its persisted files. Idle cleanup is disabled by default; enable it with `TERMINALS_IDLE_TIMEOUT_MINUTES` or a policy. A maximum lifetime, set with `TERMINALS_MAX_LIFETIME_MINUTES` or a policy, stops terminals after a fixed time even while they are in use; the next request starts a fresh one with the same files. File resets and user-data deletion are separate, destructive actions.
| Backend | Persisted terminal files |
|---------|-------------------------|
@@ -313,6 +314,7 @@ All settings are configured through environment variables prefixed with `TERMINA
| `TERMINALS_MAX_STORAGE` | | Storage cap. Kubernetes enforces this with PVC sizes; Docker support depends on the storage driver and does not quota the bind-mounted `/home/user`. |
| `TERMINALS_ALLOWED_IMAGES` | | Comma-separated list of allowed image patterns |
| `TERMINALS_IDLE_TIMEOUT_MINUTES` | `0` | Minutes of inactivity before terminals are torn down. `0` disables idle cleanup. |
| `TERMINALS_MAX_LIFETIME_MINUTES` | `0` | Minutes after start before terminals are torn down, even while in use. `0` disables the limit. |
| `TERMINALS_IDLE_CLEANUP_TIMEOUT_SECONDS` | `120` | Timeout for each teardown/reset call during idle cleanup |
| `TERMINALS_DATABASE_URL` | `sqlite+aiosqlite:////app/data/terminals.db` in the image | SQLAlchemy database URL. Source installs use `data/terminals.db` next to the package directory. 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. |
+36 -13
View File
@@ -21,6 +21,16 @@ from terminals.utils.context import DEFAULT_CONTEXT_ID, normalize_context_id
log = logging.getLogger(__name__)
def parse_started_at(value) -> float:
"""Epoch seconds for a runtime's ISO start time, or now if unknown."""
if isinstance(value, datetime):
return value.timestamp()
try:
return datetime.fromisoformat(str(value)[:19]).replace(tzinfo=timezone.utc).timestamp()
except ValueError:
return time.time()
class ProvisioningError(RuntimeError):
"""Terminal provisioning failed with a reason suitable for the client."""
@@ -195,6 +205,7 @@ class Backend(ABC):
user_id, policy_id=policy_id, context_id=context_id, spec=spec
)
if result:
result.setdefault("started_at", time.time())
self._instances[key] = result
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
@@ -472,30 +483,42 @@ class Backend(ABC):
timeout_min = spec.get(
"idle_timeout_minutes", settings.idle_timeout_minutes
)
if not timeout_min or timeout_min <= 0:
lifetime_min = spec.get(
"max_lifetime_minutes", settings.max_lifetime_minutes
)
# Instances tracked without a start time count from first sight.
started_at = info.setdefault("started_at", time.time())
expired = bool(lifetime_min and lifetime_min > 0) and (
time.time() - started_at >= lifetime_min * 60
)
if not expired and (not timeout_min or timeout_min <= 0):
continue
shared_last_active = await terminal_last_active_at(
user_id, policy_id, context_id
)
if shared_last_active:
shared_wall = shared_last_active.replace(tzinfo=timezone.utc).timestamp()
if shared_wall > self._activity_wall.get(key, 0):
self._activity_wall[key] = shared_wall
self._activity[key] = now
idle_seconds = 0.0
if not expired:
shared_last_active = await terminal_last_active_at(
user_id, policy_id, context_id
)
if shared_last_active:
shared_wall = shared_last_active.replace(tzinfo=timezone.utc).timestamp()
if shared_wall > self._activity_wall.get(key, 0):
self._activity_wall[key] = shared_wall
self._activity[key] = now
last_active = self._activity.get(key, now)
idle_seconds = now - last_active
last_active = self._activity.get(key, now)
idle_seconds = now - last_active
if idle_seconds >= timeout_min * 60:
if expired or idle_seconds >= timeout_min * 60:
log.info(
"Reaping idle terminal %s (user=%s, policy=%s, context=%s, idle=%.0fs, timeout=%dm)",
"Reaping terminal %s (user=%s, policy=%s, context=%s, idle=%.0fs, timeout=%sm, max_lifetime=%sm, expired=%s)",
info.get("instance_name", info.get("instance_id")),
user_id,
policy_id,
context_id,
idle_seconds,
timeout_min,
lifetime_min,
expired,
)
try:
await asyncio.wait_for(
+2 -1
View File
@@ -12,7 +12,7 @@ from typing import Optional
import aiodocker
import httpx
from terminals.backends.base import Backend
from terminals.backends.base import Backend, parse_started_at
from terminals.config import settings
from terminals.utils.context import (
CONTEXT_HASH_LABEL,
@@ -279,6 +279,7 @@ class DockerBackend(Backend):
"api_key": api_key,
"host": host,
"port": port,
"started_at": parse_started_at(info.get("State", {}).get("StartedAt")),
}
# ------------------------------------------------------------------
+2 -1
View File
@@ -11,7 +11,7 @@ from typing import Optional
from kubernetes_asyncio import client, config
from kubernetes_asyncio.client import ApiClient
from terminals.backends.base import Backend
from terminals.backends.base import Backend, parse_started_at
from terminals.config import settings
from terminals.utils.network_profiles import resolve_network_profile
from terminals.utils.context import (
@@ -812,6 +812,7 @@ class KubernetesBackend(Backend):
"api_key": api_key,
"host": host,
"port": 8000,
"started_at": parse_started_at(pod.status.start_time),
}
self._specs[key] = adopted_specs[policy_id]
await self._seed_adopted_activity(key, user_id, policy_id, context_id)
+5 -1
View File
@@ -19,7 +19,7 @@ from typing import Optional
from kubernetes_asyncio import client, config
from kubernetes_asyncio.client import ApiClient
from terminals.backends.base import Backend, ProvisioningError, RefreshResult
from terminals.backends.base import Backend, ProvisioningError, RefreshResult, parse_started_at
from terminals.backends.kubernetes import _cleanup_user_pvcs, _list_user_data
from terminals.config import settings
from terminals.utils.network_profiles import resolve_network_profile
@@ -868,6 +868,7 @@ class KubernetesOperatorBackend(Backend):
info = {
"instance_id": cr["metadata"]["uid"],
"instance_name": cr["metadata"]["name"],
"started_at": parse_started_at(cr["metadata"].get("creationTimestamp")),
"api_key": api_key,
"host": host,
"port": port,
@@ -926,6 +927,7 @@ class KubernetesOperatorBackend(Backend):
info = {
"instance_id": cr["metadata"]["uid"],
"instance_name": cr["metadata"]["name"],
"started_at": parse_started_at(cr["metadata"].get("creationTimestamp")),
"api_key": api_key,
"host": host,
"port": port,
@@ -945,6 +947,7 @@ class KubernetesOperatorBackend(Backend):
info = {
"instance_id": cr["metadata"]["uid"],
"instance_name": cr["metadata"]["name"],
"started_at": parse_started_at(cr["metadata"].get("creationTimestamp")),
"api_key": ready["api_key"],
"host": host,
"port": port,
@@ -978,6 +981,7 @@ class KubernetesOperatorBackend(Backend):
return {
"instance_id": cr["metadata"]["uid"],
"instance_name": cr["metadata"]["name"],
"started_at": parse_started_at(cr["metadata"].get("creationTimestamp")),
"api_key": api_key,
"host": host,
"port": port,
+2
View File
@@ -96,6 +96,8 @@ 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
# Hard cap — tear down terminals N minutes after they start, even if active (0 = disabled)
max_lifetime_minutes: int = 0
# Policy hard caps (cannot be exceeded by API)
max_cpu: str = "" # TERMINALS_MAX_CPU
@@ -231,6 +231,8 @@
}
const idle = Number(data.get('idle_timeout_minutes'));
if (Number.isFinite(idle) && idle > 0) body.idle_timeout_minutes = idle;
const lifetime = Number(data.get('max_lifetime_minutes'));
if (Number.isFinite(lifetime) && lifetime > 0) body.max_lifetime_minutes = lifetime;
if (data.get('restricted') === 'on') body.restricted = true;
const env = String(data.get('env') || '').trim();
if (env) body.env = JSON.parse(env);
@@ -517,6 +519,7 @@
<option value="shared-rwo">shared-rwo</option>
</select></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">Idle timeout<input class="mt-1 h-7 w-full rounded-lg border border-gray-200/50 bg-gray-100 px-2 text-xs text-gray-700 outline-none focus:border-gray-400/60 dark:border-white/4 dark:bg-white/6 dark:text-gray-300 dark:focus:border-white/12" name="idle_timeout_minutes" type="number" min="0" value={editingPolicy.data.idle_timeout_minutes || ''} placeholder="30" /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">Max lifetime<input class="mt-1 h-7 w-full rounded-lg border border-gray-200/50 bg-gray-100 px-2 text-xs text-gray-700 outline-none focus:border-gray-400/60 dark:border-white/4 dark:bg-white/6 dark:text-gray-300 dark:focus:border-white/12" name="max_lifetime_minutes" type="number" min="0" value={editingPolicy.data.max_lifetime_minutes || ''} placeholder="480" /></label>
<label class="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-400"><input class="h-4 w-4 rounded border-gray-300/50" name="restricted" type="checkbox" checked={!!editingPolicy.data.restricted} />Restricted Kubernetes/OpenShift</label>
<label class="block text-xs text-gray-600 dark:text-gray-400 sm:col-span-2">Env JSON<textarea class="mt-1 min-h-24 w-full rounded-lg border border-gray-200/50 bg-gray-100 px-2 py-2 font-mono text-xs text-gray-700 outline-none focus:border-gray-400/60 dark:border-white/4 dark:bg-white/6 dark:text-gray-300 dark:focus:border-white/12" name="env" placeholder={envPlaceholder}>{editingPolicy.data.env ? JSON.stringify(editingPolicy.data.env, null, 2) : ''}</textarea></label>
<label class="block text-xs text-gray-600 dark:text-gray-400 sm:col-span-2">Pod security context JSON<textarea class="mt-1 min-h-20 w-full rounded-lg border border-gray-200/50 bg-gray-100 px-2 py-2 font-mono text-xs text-gray-700 outline-none focus:border-gray-400/60 dark:border-white/4 dark:bg-white/6 dark:text-gray-300 dark:focus:border-white/12" name="pod_security_context" placeholder={podSecurityPlaceholder}>{editingPolicy.data.pod_security_context ? JSON.stringify(editingPolicy.data.pod_security_context, null, 2) : ''}</textarea></label>
+1
View File
@@ -53,6 +53,7 @@ async def admin_status(request: Request):
"backend": settings.backend,
"image": settings.image,
"idle_timeout_minutes": settings.idle_timeout_minutes,
"max_lifetime_minutes": settings.max_lifetime_minutes,
"max_cpu": settings.max_cpu,
"max_memory": settings.max_memory,
"max_storage": settings.max_storage,
+1
View File
@@ -44,6 +44,7 @@ class PolicyData(BaseModel):
storage: Optional[str] = None
storage_mode: Optional[str] = None
idle_timeout_minutes: Optional[int] = None
max_lifetime_minutes: Optional[int] = None
restricted: Optional[bool] = None
pod_security_context: Optional[dict[str, Any]] = None
container_security_context: Optional[dict[str, Any]] = None