This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-10 23:09:00 +09:00
1 parent 12437231eb
commit 25bd3594de
36 files changed
+1591 -2878

No files matched your search

+2 -2
View File
@@ -196,7 +196,7 @@ jobs:
uses: docker/build-push-action@v5
id: build
with:
context: ./operator
context: .
file: ./operator/Dockerfile
push: true
platforms: ${{ matrix.platform }}
@@ -354,4 +354,4 @@ jobs:
tag_name: v${{ needs.get-version.outputs.version }}
name: v${{ needs.get-version.outputs.version }}
body_path: /tmp/release-notes.md
make_latest: true
make_latest: true
+90 -56
View File
@@ -1,6 +1,6 @@
# Terminals
Give each Open WebUI user their own [Open Terminal](https://github.com/open-webui/open-terminal) container. Terminals starts containers on demand, routes requests to the right user, and manages policies, persistent files, and idle cleanup on Docker or Kubernetes.
Run [Open Terminal](https://github.com/open-webui/open-terminal) environments from shared templates. Terminals starts containers on demand, routes requests by template and scope, and manages persistent files and idle cleanup on Docker or Kubernetes.
```text
Open WebUI → Terminals → Open Terminal containers
@@ -9,11 +9,11 @@ Open WebUI → Terminals → Open Terminal containers
> [!IMPORTANT]
> Commercial or organizational production use requires an [Open WebUI Enterprise License](LICENSE) with Terminals access.
[Quick start](#quick-start) · [Admin UI](#admin-ui) · [Policies](#policies) · [Storage](#storage-and-persistence) · [Kubernetes](#kubernetes-deployment) · [Configuration](#configuration) · [Troubleshooting](#troubleshooting)
[Quick start](#quick-start) · [Admin UI](#admin-ui) · [Templates](#templates) · [Storage](#storage-and-persistence) · [Kubernetes](#kubernetes-deployment) · [Configuration](#configuration) · [Troubleshooting](#troubleshooting)
## Quick start
You need Docker running and an existing Open WebUI instance. These commands use a macOS/Linux shell or WSL, with `openssl` available to generate a key. No repository clone or separate database is needed.
You need Docker running and an existing Open WebUI deployment. These commands use a macOS/Linux shell or WSL, with `openssl` available to generate a key. No repository clone or separate database is needed.
### 1. Start Terminals
@@ -46,7 +46,7 @@ The service and the terminal containers use the same Docker network, so no host
### 2. Open the admin UI
Open **[http://localhost:3000](http://localhost:3000)**, paste the key into **Admin key**, and click **Refresh**. An empty Active terminals list is expected until someone uses a terminal.
Open **[http://localhost:3000](http://localhost:3000)**, paste the key into **Admin key**, and click **Refresh**. An empty Environments list is expected until someone uses a template.
Check that the service is running:
@@ -74,19 +74,27 @@ In Open WebUI, open **Settings → Admin → Integrations → Open Terminal** an
If Open WebUI runs directly on the same host, use `http://localhost:3000` instead. The URL must be reachable from the Open WebUI server. The quick start binds the admin port to localhost; for remote access, expose it through your usual authenticated HTTPS deployment.
Verify the connection and save it. In a chat, select it from the terminal menu. Terminals creates the user's container on first use; the first request can take longer while its image is downloaded.
Verify the connection and save it. In the terminal menu, choose **New terminal**, enter a name, choose a scope, and save. Select that template to use it. Terminals creates its environment on first use; the first request can take longer while its image is downloaded.
See the [Open WebUI connection guide](https://docs.openwebui.com/features/open-terminal/setup/connecting/) for the full UI walkthrough.
<details>
<summary>Try a terminal directly with curl</summary>
This creates a terminal for the example user `demo-user`:
Create a user-scoped template, then execute as the example user `demo-user`:
```bash
curl -fsS -X POST http://localhost:3000/api/v1/terminals/templates \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"id":"demo","data":{"name":"My workspace","scope":"user"}}'
```
```bash
curl -fsS http://localhost:3000/execute \
-H "Authorization: Bearer $API_KEY" \
-H "X-User-Id: demo-user" \
-H "X-Terminal-Template-Id: demo" \
-H "Content-Type: application/json" \
-d '{"command":"echo hello"}'
```
@@ -97,42 +105,70 @@ The examples below use the same `$API_KEY` shell variable. In a new shell, set i
## Admin UI
The built-in UI at `/` has three sections:
The built-in UI at `/` has two sections:
- **Active terminals:** inspect user terminals and stop individual instances. Stopping a terminal keeps its persisted files; the next access starts it again.
- **User data:** discover persisted files, including users with no active terminals. **Delete user data** confirms, stops the user's tracked terminals, then deletes their files across policies and contexts. If terminals remain, files are preserved.
- **Policies:** create or edit terminal settings, configure scheduled resets, and roll out changes to idle terminals.
- **Templates:** create or edit instance configuration and scheduled resets, or delete a template and its environments.
- **Environments:** inspect tracked environments, including stopped ones; restart, reset, or delete the selected environment.
Use the Terminals admin API key. Set `TERMINALS_ENABLE_UI=false` for an API-only deployment.
## Policies
## Templates in Open WebUI
A policy defines a terminal's image, environment variables, and resource limits. The default proxy routes work without creating a policy. Add policies in the admin UI or through the API when you need different environments:
Connect a Terminals server using its server key. In the terminal picker, choose **New terminal**, enter a name and instance configuration, and choose one scope:
| Scope | Environment |
|-------|-------------|
| None (`null`) | One environment for everyone authorized to use the template |
| User (`"user"`) | One environment per user |
| Chat (`"chat"`) | One environment per saved chat, shared by its authorized collaborators |
| Model (`"model"`) | One environment per selected WebUI model or preset |
Missing required context is an error. Creating two independent terminals creates two templates. Renaming a template does not change its environment identity or files.
Open WebUI stores access grants per template. **Use** permits commands and file changes; **Manage** also permits configuration, sharing, and environment management. New templates are private to their creator. Parent connection access remains required. Snapshot-only chat sharing grants no execution access.
Templates are managed at `/api/v1/terminals/templates`. Execution uses the existing proxy with `X-Terminal-Template-Id` and verified user, chat, or model headers from WebUI. Managed requests require `TERMINALS_API_KEY`; Terminals does not call WebUI to authorize them.
Persistent homes live under `.terminals/<terminal-id>` on Docker and shared Kubernetes storage; dedicated Kubernetes storage uses a separate PVC. The terminal ID is derived from the template and scope context. Restart preserves files. Reset clears only the selected environment's files. Deleting a template removes its environments and files.
For existing deployments, see the [0.4.0 upgrade requirements](CHANGELOG.md#moving-to-040-manually). Existing populated deployments use the documented manual migration to a new database and separate storage; `terminals db upgrade` does not convert them.
## Templates
A template defines the terminal's scope, image, environment variables, and resource limits. Create one in the admin UI or through the API; fresh installations do not create a default template automatically.
```bash
curl -fsS -X PUT http://localhost:3000/api/v1/policies/data-science \
curl -fsS -X POST http://localhost:3000/api/v1/terminals/templates \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"image": "ghcr.io/open-webui/open-terminal:latest",
"cpu_limit": "2",
"memory_limit": "4Gi",
"idle_timeout_minutes": 30
"id": "data-science",
"data": {
"name": "Data science",
"scope": "user",
"image": "ghcr.io/open-webui/open-terminal:latest",
"cpu_limit": "2",
"memory_limit": "4Gi",
"idle_timeout_minutes": 30
}
}'
```
Use `/p/{policy_id}/` to route a request through that policy:
Select the template in the execution headers:
```bash
curl -fsS http://localhost:3000/p/data-science/execute \
curl -fsS http://localhost:3000/execute \
-H "Authorization: Bearer $API_KEY" \
-H "X-User-Id: demo-user" \
-H "X-Terminal-Template-Id: data-science" \
-H "Content-Type: application/json" \
-d '{"command":"echo hello"}'
```
| Field | Purpose |
|-------|---------|
| `name` | Display name; changing it preserves instance identity |
| `scope` | `null`, `"user"`, `"chat"`, or `"model"` |
| `image` | Open Terminal image to run |
| `env` | Environment variables passed to the terminal |
| `network_profile` | Optional name from `TERMINALS_NETWORK_PROFILES`; omitted uses existing networking defaults |
@@ -145,12 +181,12 @@ curl -fsS http://localhost:3000/p/data-science/execute \
| `pod_security_context`, `container_security_context` | Kubernetes security context overrides |
| `podTemplate` | Kubernetes pod overrides, including volumes, scheduling, and health probes |
Service limits such as `TERMINALS_MAX_CPU`, `TERMINALS_MAX_MEMORY`, and `TERMINALS_ALLOWED_IMAGES` constrain policy settings.
Service limits such as `TERMINALS_MAX_CPU`, `TERMINALS_MAX_MEMORY`, and `TERMINALS_ALLOWED_IMAGES` constrain template settings.
### Network profiles
Define named profiles in the orchestrator's environment, then select one with
`"network_profile": "restricted"` in a policy or the admin policy editor:
`"network_profile": "restricted"` in a template or the admin template editor:
```bash
TERMINALS_NETWORK_PROFILES='{"restricted":{"docker_network":"terminals-restricted","kubernetes_labels":{"network-tier":"restricted"}}}'
@@ -173,44 +209,44 @@ Profiles select configuration; they do not create networks, firewall rules, or
NetworkPolicies. Configure Docker firewall rules or Kubernetes NetworkPolicies
and a CNI that enforces them to provide the intended access restrictions. A name
such as `restricted` alone does not enforce isolation. Allow the orchestrator to
reach terminal port 8000 and permit DNS if needed. Use the rollout below to apply
reach terminal port 8000 and permit DNS if needed. Use the restart operation below to apply
profile changes to existing terminals.
### Apply changes to existing terminals
Changes take effect when a terminal is next provisioned. Use the policy's rollout action in the UI, or:
Edit configuration with `PATCH /api/v1/terminals/templates/{id}`. Changes take effect when an environment is next created. Restart stops the selected environment and preserves its files; its next use loads the current template configuration:
```bash
curl -fsS -X POST http://localhost:3000/api/v1/terminals/refresh \
curl -fsS -X POST http://localhost:3000/api/v1/terminals/templates/data-science/restart \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"policy_id":"data-science","only_idle":true}'
-d '{"user_id":"demo-user"}'
```
`only_idle` defaults to `true`. Set it to `false` to stop active terminals too. Add `user_id` or `context_id` to narrow the selection. Files are preserved unless you explicitly set `reset:true`.
For chat or model scope, also supply `chat_id` or `model_id`. Restart does not create an unused environment. Scope and storage-mode changes are rejected while affected environments exist.
### Schedule file resets
Scheduled resets delete persisted terminal files and refresh matching terminals, including active ones. Configure them in the policy editor or with:
Scheduled resets delete persisted terminal files and refresh matching terminals, including active ones. Configure them in the template editor or with:
```bash
curl -fsS -X PUT http://localhost:3000/api/v1/policies/data-science/lifecycle \
curl -fsS -X PUT http://localhost:3000/api/v1/terminals/templates/data-science/lifecycle \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"reset":{"schedule":"@weekly","timezone":"UTC"}}'
```
Schedules support one-time ISO datetimes, `@weekly`, `@monthly`, and five-field cron expressions. Docker clears the matching home directory. Kubernetes uses a reset pod to clear the matching PVC or user subdirectory.
Schedules support one-time ISO datetimes, `@weekly`, `@monthly`, and five-field cron expressions. Docker clears the matching home directory. Kubernetes uses a reset pod to clear the matching PVC or environment subdirectory.
## 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. 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.
Stopping or reaping a terminal preserves its persisted files. Idle cleanup is disabled by default; enable it with `TERMINALS_IDLE_TIMEOUT_MINUTES` or a template. A maximum lifetime, set with `TERMINALS_MAX_LIFETIME_MINUTES` or a template, 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 environment deletion are separate, destructive actions.
| Backend | Persisted terminal files |
|---------|-------------------------|
| Docker | Bind-mounted under `TERMINALS_DOCKER_DATA_DIR`, regardless of the policy's `storage` field |
| Docker | Bind-mounted under `TERMINALS_DOCKER_DATA_DIR`, regardless of the template's `storage` field |
| Kubernetes | PVCs; defaults to `1Gi` per terminal, with optional shared storage modes |
| Kubernetes operator | Set `storage` in the policy to create a dedicated PVC; omitting it uses ephemeral storage |
| Kubernetes operator | Dedicated PVCs; `storage` overrides the server default size |
### Docker paths
@@ -218,8 +254,8 @@ The quick start mounts the host's `./data` directory at `/app/data`:
| Host path | Container path | Contents |
|-----------|----------------|----------|
| `./data/terminals.db` | `/app/data/terminals.db` | SQLite database: policies and lifecycle state |
| `./data/terminals/` | `/app/data/terminals/` | Users' terminal files, including chat and automation contexts |
| `./data/terminals.db` | `/app/data/terminals.db` | SQLite database: templates and lifecycle state |
| `./data/terminals/` | `/app/data/terminals/` | Terminal homes under `.terminals/<terminal-id>` |
`TERMINALS_DOCKER_HOST_DATA_DIR` tells the Docker daemon where those same terminal files live on its host. It is optional when the orchestrator and daemon use the same path. Both paths must refer to the same storage so provisioning, resets, and deletion operate on the same files. The quick start assumes a local Docker daemon.
@@ -231,22 +267,20 @@ On Kubernetes, `storage` sets the requested PVC size. On Docker it caps only the
Terminal files need a filesystem. Open WebUI's uploaded-file storage and Azure Blob cleanup do not manage them. For Azure, use Azure Files, managed disks, or Kubernetes PVCs for terminal homes.
### Delete a user's files
### Delete an environment's files
Deleting an account in Open WebUI does not notify Terminals. After revoking that user's access, use **User data → Delete user data** in the admin UI.
For API-based cleanup, list users with `GET /api/v1/terminals/data`, stop their terminals through `/api/v1/terminals/refresh` with `user_id` and `only_idle:false`, then call:
Deleting an Open WebUI account does not automatically delete terminal storage. Inspect a template's tracked instances with `GET /api/v1/terminals/templates/{id}/instances` (or all instances with `GET /api/v1/terminals`), then delete the specific template/context:
```bash
curl -fsS -X POST http://localhost:3000/api/v1/terminals/cleanup \
curl -fsS -X DELETE http://localhost:3000/api/v1/terminals/templates/data-science/instance \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"user_id":"deleted-user-id"}'
```
Cleanup removes the user's Docker directory or requests deletion of their labeled per-user PVCs, clears lifecycle records, and logs each storage deletion. It works after idle terminals have been reaped. Repeating the call is safe. It waits for terminating Kubernetes resources and returns `409` if terminal resources remain; remove them before retrying.
Use the context required by the template's scope. Chat- and model-scoped environments are shared; they do not belong to the first user who opened them. Deletion stops the workload before removing its storage and lifecycle record. Failed cleanup retains records so it can be retried. Selecting the same template/context later creates an empty environment.
Shared PVCs need separate cleanup of the user's subdirectory and are not listed in the UI. The cleanup endpoint refuses deletion when shared storage exists. PVC removal follows the storage class's reclaim policy; retained volumes and backups need separate removal.
Shared PVC deletion clears only the selected environment's subdirectory. Dedicated PVC deletion follows the storage class's reclaim policy; retained volumes and backups need separate removal.
## Kubernetes deployment
@@ -278,7 +312,7 @@ env:
key: api-key
```
Create the referenced Secret, mount persistent storage at `/app/data` for SQLite, and give the service account the backend's required Kubernetes permissions. The operator RBAC is in [operator-deployment.yaml](manifests/operator-deployment.yaml). Expose the Terminals service on port `3000` to Open WebUI. Add `"storage":"5Gi"` to operator policies that need persistent files.
Create the referenced Secret, mount persistent storage at `/app/data` for SQLite, and give the service account the backend's required Kubernetes permissions. The operator RBAC is in [operator-deployment.yaml](manifests/operator-deployment.yaml). Expose the Terminals service on port `3000` to Open WebUI. Add `"storage":"5Gi"` to operator templates to request that PVC size.
For direct Kubernetes provisioning, use `TERMINALS_BACKEND=kubernetes`; no operator or CRD is required. For restricted OpenShift clusters, follow [OpenShift deployment](docs/openshift.md).
@@ -286,11 +320,11 @@ For direct Kubernetes provisioning, use `TERMINALS_BACKEND=kubernetes`; no opera
The quick start uses a static `TERMINALS_API_KEY` for both the admin UI and Open WebUI's Bearer connection. Keep it on trusted servers: API-key requests trust the supplied `X-User-Id` to select the user.
For Open WebUI session authentication, set `TERMINALS_OPEN_WEBUI_URL` and use **Session** auth on the Open WebUI terminal connection. Terminals validates user tokens against that instance. Admin policy and lifecycle APIs still require a separate Terminals admin API key; user JWTs are not enough.
Managed execution uses the server key. WebUI checks access and forwards verified context; user JWTs do not authorize managed template requests.
Tool discovery at `/openapi.json` and `/p/{policy_id}/openapi.json` also accepts the Terminals admin API key in Session mode. Terminal operations still require a valid user token.
Tool discovery at `/openapi.json` uses the server API key and the same verified template, user, and scope context as execution. It uses that instance; there is no separate discovery instance.
`terminals serve` generates and prints a key if none is configured. That generated key changes when the service process restarts. Running the ASGI app directly without either authentication setting allows unauthenticated access and is intended only for local development.
`terminals serve` generates and prints a key if none is configured. That generated key changes when the service process restarts. Configure a persistent API key for deployments; managed execution requires it even when running the ASGI app directly.
## Configuration
@@ -302,12 +336,13 @@ All settings are configured through environment variables prefixed with `TERMINA
|----------|---------|-------------|
| `TERMINALS_BACKEND` | `docker` | `docker`, `kubernetes`, or `kubernetes-operator` |
| `TERMINALS_API_KEY` | *(auto-generated)* | Bearer token for API auth |
| `TERMINALS_OPEN_WEBUI_URL` | | Advanced Open WebUI integration mode. If set, Terminals validates Open WebUI JWTs against that instance. Requires an Open WebUI terminal connection using session auth. |
| `TERMINALS_HOST` | `0.0.0.0` | Orchestrator API bind host |
| `TERMINALS_PORT` | `3000` | Orchestrator API bind port |
| `TERMINALS_WORKERS` | `1` | Uvicorn worker process count. Docker workers adopt existing per-user containers by deterministic name instead of replacing them. |
| `TERMINALS_WORKERS` | `1` | Uvicorn worker process count. Docker workers adopt existing containers by deterministic name instead of replacing them. |
| `TERMINALS_ENABLE_UI` | `true` | Serve the built-in minimal admin UI at `/`. Set to `false` for API-only deployments. |
| `TERMINALS_IMAGE` | `ghcr.io/open-webui/open-terminal:latest` | Default Open Terminal container image |
| `TERMINALS_IMAGE_PULL_POLICY` | | `Always`, `IfNotPresent`, or `Never`, for every backend. Unset pulls images tagged `:latest` or untagged on every start and other tags only when missing, matching Kubernetes. |
| `TERMINALS_IMAGE_PULL_INTERVAL_SECONDS` | `3600` | Docker only: how long a pulled image is used before `Always` checks the registry again. If the registry can't be reached, the local copy is used. |
| `TERMINALS_NETWORK_PROFILES` | `{}` | JSON object mapping profile names to `docker_network` and/or `kubernetes_labels` configuration |
| `TERMINALS_MAX_CPU` | | Hard cap on CPU per terminal container/pod |
| `TERMINALS_MAX_MEMORY` | | Hard cap on memory per terminal container/pod |
@@ -319,7 +354,6 @@ All settings are configured through environment variables prefixed with `TERMINA
| `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. |
| `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. |
| `TERMINALS_TOKEN_CACHE_TTL` | `60` | Seconds a successfully validated Open WebUI token is cached (JWT mode only). A revoked token stays usable for up to the TTL; `0` validates every request. |
| `TERMINALS_WS_COMPRESSION` | `false` | Enable permessage-deflate on proxied WebSocket terminal traffic. Leave off unless clients connect over slow links. |
| `TERMINALS_ACCESS_LOG` | `false` | Log every HTTP request. Off by default because per-request logging is expensive at high request rates. |
| `TERMINALS_REPLAY_BODY_LIMIT` | | Maximum proxied request body bytes buffered for retry. Unset, `none`, `null`, or `unlimited` means no size cap. |
@@ -345,7 +379,7 @@ All settings are configured through environment variables prefixed with `TERMINA
|----------|---------|-------------|
| `TERMINALS_KUBERNETES_NAMESPACE` | `terminals` | Namespace for terminal pods, services, PVCs, and CRDs |
| `TERMINALS_KUBERNETES_STORAGE_CLASS` | | Storage class for terminal PVCs. Empty uses the cluster default. |
| `TERMINALS_KUBERNETES_STORAGE_SIZE` | `1Gi` | Default PVC size for the direct `kubernetes` backend; operator policies must set `storage` for persistence |
| `TERMINALS_KUBERNETES_STORAGE_SIZE` | `1Gi` | Default PVC size for the direct `kubernetes` backend; both Kubernetes backends use this default when template `storage` is omitted |
| `TERMINALS_KUBERNETES_STORAGE_MODE` | `per-user` | Direct Kubernetes storage mode: `per-user`, `shared`, or `shared-rwo`; the operator creates dedicated PVCs |
| `TERMINALS_KUBERNETES_SERVICE_TYPE` | `ClusterIP` | Service type for terminal services |
| `TERMINALS_KUBERNETES_KUBECONFIG` | | Kubeconfig path. Empty uses in-cluster config. |
@@ -388,7 +422,7 @@ container path. `readOnly` defaults to `true`. Do not mount over `/home/user`;
Open Terminal expects that directory to stay writable.
Kubernetes deployments do not use `TERMINALS_DOCKER_MOUNTS`. Use the existing
policy `podTemplate` field and native Kubernetes volumes instead:
template `podTemplate` field and native Kubernetes volumes instead:
```json
{
@@ -416,7 +450,7 @@ boundary if terminal containers are privileged or can access the Docker socket.
### Kubernetes health probes
Both Kubernetes backends accept probe overrides in the policy's `podTemplate`.
Both Kubernetes backends accept probe overrides in the template's `podTemplate`.
Each supplied probe replaces the default, so include its check (such as
`httpGet`) as well as timing settings. For slower hardware:
@@ -445,12 +479,12 @@ Each supplied probe replaces the default, so include its check (such as
}
```
Omitted probes keep their existing defaults. Refresh existing terminals to apply
the updated policy on their next access.
Omitted probes keep their existing defaults. Restart existing terminals to apply
the updated template on their next access.
### Docker network scaling
For larger Docker deployments, create multiple bridge networks and set `TERMINALS_DOCKER_NETWORK` to a comma-separated list. Terminals assigns each user/policy/context to a stable network. Attach the orchestrator container to every listed network so it can reach terminals by name.
For larger Docker deployments, create multiple bridge networks and set `TERMINALS_DOCKER_NETWORK` to a comma-separated list. Terminals assigns each template/context to a stable network. Attach the orchestrator container to every listed network so it can reach terminals by name.
## Troubleshooting
@@ -460,8 +494,8 @@ For larger Docker deployments, create multiple bridge networks and set `TERMINAL
| Open WebUI cannot connect | Use `http://terminals:3000` on the shared Docker network. Inside a container, `localhost` refers to that container. |
| First terminal is slow or fails | Check `docker logs terminals`; the configured terminal image must be available or pullable. |
| Files disappear after recreating the service | Check the `/app/data` bind mount and both Docker data paths. Keep the same host directory across recreations. |
| Kubernetes terminal files disappear after idle cleanup | For the operator backend, set `storage` in the policy so files live on a PVC. |
| User-data deletion returns `409` | Terminal resources still exist or shared storage needs separate handling. Check the returned error; files are not deleted while terminals remain. |
| Kubernetes terminal files disappear after idle cleanup | Check that the environment PVC still exists and `/home/user` is mounted from it. |
| Environment deletion returns `409` | The workload may still be stopping. Check the returned error and retry; files are not deleted while the workload remains. |
| UI is unavailable in a source install | Build the frontend and ensure `TERMINALS_ENABLE_UI` is not `false`. |
## Development
+19 -15
View File
@@ -6,10 +6,10 @@ OpenShift restricted SCC does not support the full rootful agent devbox model. U
## What Works
- One Open Terminal pod per user and policy.
- One Open Terminal pod per template and user when `scope: "user"`.
- Persistent user files through PVCs.
- Policy-selected images, env vars, CPU, memory, storage, and idle timeout.
- Refresh and scheduled reset of persisted terminal files.
- Template-selected images, env vars, CPU, memory, storage, and idle timeout.
- Restart and scheduled reset of persisted terminal files.
- File browser, command execution, notebooks, and tools that are already in the image.
## What Does Not Work Under Restricted SCC
@@ -61,23 +61,27 @@ env:
If you use the default SQLite database, mount a PVC at `/app/data`.
## Example Policy
## Example Template
Use the OpenShift-compatible Open Terminal image:
```bash
curl -X PUT https://terminals.example.com/api/v1/policies/openshift \
curl -X POST https://terminals.example.com/api/v1/terminals/templates \
-H "Authorization: Bearer $TERMINALS_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"image": "ghcr.io/open-webui/open-terminal:openshift",
"restricted": true,
"storage": "5Gi",
"storage_mode": "per-user",
"cpu_limit": "1",
"memory_limit": "1Gi",
"env": {
"OPEN_TERMINAL_FILE_BROWSER_ROOT": "home"
"id": "openshift",
"data": {
"name": "OpenShift",
"scope": "user",
"image": "ghcr.io/open-webui/open-terminal:openshift",
"restricted": true,
"storage": "5Gi",
"cpu_limit": "1",
"memory_limit": "1Gi",
"env": {
"OPEN_TERMINAL_FILE_BROWSER_ROOT": "home"
}
}
}'
```
@@ -102,7 +106,7 @@ Restricted mode applies these defaults unless you override them:
}
```
Do not set `OPEN_TERMINAL_ALLOWED_DOMAINS` in restricted policies. Use cluster network policy for egress control on OpenShift.
Do not set `OPEN_TERMINAL_ALLOWED_DOMAINS` in restricted templates. Use cluster network policy for egress control on OpenShift.
## Custom Images
@@ -119,4 +123,4 @@ RUN apt-get update && apt-get install -y --no-install-recommends ripgrep \
USER 1001
```
Then point the policy `image` field at your built image and refresh affected terminals.
Then point the template `image` field at your built image and restart affected environments.
+13 -6
View File
@@ -27,22 +27,29 @@ spec:
spec:
type: object
required:
- userId
- templateId
properties:
userId:
templateId:
type: string
description: Open WebUI user ID that owns this terminal.
contextId:
type: string
default: "default"
description: >-
Optional runtime context for separate terminal instances.
Optional runtime context for separate terminal environments.
v1 supports "default", "chat:<chat_id>", and
"automation:<automation_id>".
image:
type: string
default: "ghcr.io/open-webui/open-terminal:latest"
description: Container image for the Open Terminal instance.
description: Container image for the Open Terminal environment.
imagePullPolicy:
type: string
enum: ["Always", "IfNotPresent", "Never"]
description: >-
Pull policy for the image. When omitted, Kubernetes pulls
:latest and untagged images on every start and other tags
only when missing.
podTemplate:
type: object
x-kubernetes-preserve-unknown-fields: true
@@ -169,9 +176,9 @@ spec:
subresources:
status: {}
additionalPrinterColumns:
- name: User
- name: Template
type: string
jsonPath: .spec.userId
jsonPath: .spec.templateId
- name: Phase
type: string
jsonPath: .status.phase
+4 -1
View File
@@ -6,7 +6,10 @@ RUN pip install --no-cache-dir \
kopf>=1.37.0 \
kubernetes>=31.0.0
COPY handler.py /app/handler.py
COPY operator/handler.py /app/handler.py
COPY terminals/utils/kubernetes_labels.py /app/terminals/utils/kubernetes_labels.py
ENV PYTHONPATH=/app
USER 65534:65534
+21 -18
View File
@@ -26,6 +26,7 @@ from datetime import datetime, timezone
import kopf
import kubernetes
from kubernetes import client as k8s
from terminals.utils.kubernetes_labels import template_label
log = logging.getLogger(__name__)
@@ -272,7 +273,7 @@ def _owner_ref(body: dict) -> dict:
}
def _labels(name: str, user_id: str = "") -> dict[str, str]:
def _labels(name: str, template_id: str = "") -> dict[str, str]:
labels = {
"app.kubernetes.io/name": "open-terminal",
"app.kubernetes.io/instance": name,
@@ -280,8 +281,8 @@ def _labels(name: str, user_id: str = "") -> dict[str, str]:
"app.kubernetes.io/part-of": "open-terminal",
"openwebui.com/terminal": name,
}
if user_id:
labels["openwebui.com/user-id"] = user_id
if template_id:
labels["openwebui.com/template"] = template_label(template_id)
return labels
@@ -356,9 +357,9 @@ def _build_pod_manifest(
api_key: str,
owner_ref: dict,
pvc_name: str | None,
user_id: str = "",
template_id: str = "",
) -> dict:
"""Build the Pod manifest for an Open Terminal instance."""
"""Build the Pod manifest for an Open Terminal environment."""
image = spec.get("image", "ghcr.io/open-webui/open-terminal:latest")
resources_spec = spec.get("resources", {})
packages = spec.get("packages", [])
@@ -407,6 +408,8 @@ def _build_pod_manifest(
"periodSeconds": 15,
},
}
if spec.get("imagePullPolicy"):
container["imagePullPolicy"] = spec["imagePullPolicy"]
requests = resources_spec.get("requests", {})
limits = resources_spec.get("limits", {})
@@ -425,7 +428,7 @@ def _build_pod_manifest(
if container_security_context:
container["securityContext"] = container_security_context
pod_labels = _labels(name, user_id)
pod_labels = _labels(name, template_id)
pod_spec = {
"containers": [container],
"volumes": volumes,
@@ -461,7 +464,7 @@ def _build_pod_manifest(
def _build_service_manifest(
name: str, namespace: str, owner_ref: dict, user_id: str = ""
name: str, namespace: str, owner_ref: dict, template_id: str = ""
) -> dict:
return {
"apiVersion": "v1",
@@ -469,7 +472,7 @@ def _build_service_manifest(
"metadata": {
"name": _resource_name(name, "svc"),
"namespace": namespace,
"labels": _labels(name, user_id),
"labels": _labels(name, template_id),
"ownerReferences": [owner_ref],
},
"spec": {
@@ -484,7 +487,7 @@ def _build_service_manifest(
def _build_secret_manifest(
name: str, namespace: str, api_key: str, owner_ref: dict,
user_id: str = "",
template_id: str = "",
) -> dict:
return {
"apiVersion": "v1",
@@ -492,7 +495,7 @@ def _build_secret_manifest(
"metadata": {
"name": _resource_name(name, "apikey"),
"namespace": namespace,
"labels": _labels(name, user_id),
"labels": _labels(name, template_id),
"ownerReferences": [owner_ref],
},
"type": "Opaque",
@@ -504,7 +507,7 @@ def _build_secret_manifest(
def _build_pvc_manifest(
name: str, namespace: str, spec: dict, owner_ref: dict,
user_id: str = "",
template_id: str = "",
) -> dict:
persistence = spec.get("persistence", {})
size = persistence.get("size", "1Gi")
@@ -519,7 +522,7 @@ def _build_pvc_manifest(
"metadata": {
"name": _resource_name(name, "pvc"),
"namespace": namespace,
"labels": _labels(name, user_id),
"labels": _labels(name, template_id),
},
"spec": {
"accessModes": ["ReadWriteOnce"],
@@ -556,9 +559,9 @@ def _raise_provisioning_error(error, patch):
@kopf.on.create(GROUP, VERSION, PLURAL)
async def on_create(body, spec, name, namespace, patch, **_):
"""Create all child resources for a new Terminal CR."""
log.info("Creating terminal %s/%s for user %s", namespace, name, spec.get("userId"))
log.info("Creating terminal %s/%s for user %s", namespace, name, spec.get("templateId"))
user_id = spec.get("userId", "")
template_id = spec.get("templateId", "")
owner_ref = _owner_ref(body)
api_key = _generate_api_key()
core_v1 = k8s.CoreV1Api()
@@ -575,7 +578,7 @@ async def on_create(body, spec, name, namespace, patch, **_):
pvc_name = None
if persistence.get("enabled", True):
pvc_name = _resource_name(name, "pvc")
pvc_manifest = _build_pvc_manifest(name, namespace, spec, owner_ref, user_id=user_id)
pvc_manifest = _build_pvc_manifest(name, namespace, spec, owner_ref, template_id=template_id)
try:
core_v1.create_namespaced_persistent_volume_claim(
namespace=namespace, body=pvc_manifest
@@ -589,7 +592,7 @@ async def on_create(body, spec, name, namespace, patch, **_):
# -- Secret (API key)
secret_name = _resource_name(name, "apikey")
secret_manifest = _build_secret_manifest(name, namespace, api_key, owner_ref, user_id=user_id)
secret_manifest = _build_secret_manifest(name, namespace, api_key, owner_ref, template_id=template_id)
try:
core_v1.create_namespaced_secret(namespace=namespace, body=secret_manifest)
log.info("Created Secret %s/%s", namespace, secret_name)
@@ -603,7 +606,7 @@ async def on_create(body, spec, name, namespace, patch, **_):
# -- Service
svc_name = _resource_name(name, "svc")
svc_manifest = _build_service_manifest(name, namespace, owner_ref, user_id=user_id)
svc_manifest = _build_service_manifest(name, namespace, owner_ref, template_id=template_id)
try:
core_v1.create_namespaced_service(namespace=namespace, body=svc_manifest)
log.info("Created Service %s/%s", namespace, svc_name)
@@ -616,7 +619,7 @@ async def on_create(body, spec, name, namespace, patch, **_):
# -- Pod
pod_name = _resource_name(name, "pod")
pod_manifest = _build_pod_manifest(
name, namespace, spec, api_key, owner_ref, pvc_name, user_id=user_id
name, namespace, spec, api_key, owner_ref, pvc_name, template_id=template_id
)
try:
core_v1.create_namespaced_pod(namespace=namespace, body=pod_manifest)
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "terminals"
version = "0.3.3"
version = "0.4.0"
description = "Multi-tenant terminal orchestrator for Open Terminal."
readme = "README.md"
authors = [
+117 -493
View File
@@ -3,26 +3,25 @@
import asyncio
import logging
import time
from abc import ABC, abstractmethod
from dataclasses import dataclass
from abc import ABC
from datetime import datetime, timezone
from typing import Optional
from terminals.config import settings
from terminals.utils.policy_lifecycle import (
from terminals.utils.template_lifecycle import (
ensure_terminal_state,
mark_reset_applied,
mark_terminal_active,
reset_due_for,
terminal_last_active_at,
)
from terminals.utils.policy_specs import PolicyNotFoundError, resolve_policy_spec
from terminals.utils.context import DEFAULT_CONTEXT_ID, normalize_context_id
from terminals.utils.template_specs import resolve_template_spec
from terminals.utils.context import DEFAULT_CONTEXT_ID, normalize_context_id, get_terminal_id
log = logging.getLogger(__name__)
def parse_started_at(value) -> float:
"""Epoch seconds for a runtime's ISO start time, or now if unknown."""
"""Epoch seconds for a instance's ISO start time, or now if unknown."""
if isinstance(value, datetime):
return value.timestamp()
try:
@@ -35,386 +34,110 @@ class ProvisioningError(RuntimeError):
"""Terminal provisioning failed with a reason suitable for the client."""
@dataclass
class RefreshResult:
matched: int = 0
refreshed: int = 0
reset: int = 0
skipped_active: int = 0
class Backend(ABC):
"""Lifecycle interface for provisioning and managing terminal instances.
"""Backend caches use the same deterministic key as persistent lifecycle state."""
Includes an in-memory activity tracker and idle reaper that automatically
tears down terminals that haven't been accessed within the configured
timeout (``settings.idle_timeout_minutes`` or per-policy
``idle_timeout_minutes``).
"""
def __init__(self) -> None:
# key = (user_id, policy_id, context_id)
self._activity: dict[tuple[str, str, str], float] = {}
self._activity_wall: dict[tuple[str, str, str], float] = {}
self._instances: dict[tuple[str, str, str], dict] = {}
self._specs: dict[tuple[str, str, str], dict] = {}
self._locks: dict[tuple[str, str, str], asyncio.Lock] = {}
self._running_checked_at: dict[tuple[str, str, str], float] = {}
self._activity_synced_at: dict[tuple[str, str, str], float] = {}
self._reaper_task: Optional[asyncio.Task] = None
# ------------------------------------------------------------------
# Abstract interface
# ------------------------------------------------------------------
@abstractmethod
async def provision(
self,
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
) -> dict:
"""Create a new terminal instance for *user_id*.
*policy_id* scopes the environment shape. *context_id* optionally
scopes separate runtime copies of that policy.
*spec* is the resolved policy spec dict; if ``None``, the backend
uses ``settings.*`` defaults.
Returns a dict with at least:
``instance_id``, ``instance_name``, ``api_key``, ``host``, ``port``.
"""
@abstractmethod
async def start(self, instance_id: str) -> bool:
"""Idempotent start — no-op if already running."""
@abstractmethod
async def teardown(self, instance_id: str) -> None:
"""Stop and remove the instance."""
@abstractmethod
async def status(self, instance_id: str) -> str:
"""Return ``'running'``, ``'stopped'``, or ``'missing'``."""
@abstractmethod
async def close(self) -> None:
"""Release resources on shutdown."""
async def reset(
self,
user_id: str,
policy_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
) -> None:
"""Delete persisted files for a user terminal."""
raise NotImplementedError("Reset is not supported by this backend")
async def list_user_data(self) -> list[str]:
"""List users with persisted terminal files, including inactive users."""
raise NotImplementedError("Listing user data is not supported by this backend")
async def cleanup_user(self, user_id: str) -> int:
"""Remove an inactive user's persisted workspace storage."""
raise NotImplementedError("User cleanup is not supported by this backend")
# ------------------------------------------------------------------
# Instance tracking
# ------------------------------------------------------------------
def __init__(self):
self._instances = {}
self._specs = {}
self._activity_synced_at = {}
self._running_checked_at = {}
self._reaper_task = None
@staticmethod
def _key(
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
) -> tuple[str, str, str]:
return (user_id, policy_id, normalize_context_id(context_id))
def _key(template_id, context_id=DEFAULT_CONTEXT_ID):
return get_terminal_id(template_id, context_id)
def _record_activity(self, key: tuple[str, str, str]) -> None:
self._activity[key] = time.monotonic()
self._activity_wall[key] = time.time()
def invalidate_status(
self,
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
) -> None:
self._running_checked_at.pop(self._key(user_id, policy_id, context_id), None)
def invalidate_status(self, template_id, context_id=DEFAULT_CONTEXT_ID):
self._running_checked_at.pop(self._key(template_id, context_id), None)
async def ensure_terminal(
self,
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
) -> Optional[dict]:
"""Get-or-create a terminal for *user_id*.
def forget(self, key):
for cache in (self._instances, self._specs,
self._activity_synced_at, self._running_checked_at):
cache.pop(key, None)
Returns a dict with ``api_key``, ``host``, ``port``, or ``None``.
Tracks the instance for idle reaping.
Uses a per-key lock so concurrent requests for the same user+policy
don't race to provision the same container.
"""
async def ensure_terminal(self, template_id, context_id=DEFAULT_CONTEXT_ID):
from terminals.utils.instances import instance_lock
context_id = normalize_context_id(context_id)
key = self._key(user_id, policy_id, context_id)
key = self._key(template_id, context_id)
async with instance_lock("template:" + template_id, shared=True), instance_lock(key):
# Read under the template lock: edits/deletion cannot race allocation.
spec = await resolve_template_spec(template_id)
scope = (spec or {}).get("scope")
valid = context_id == "default" if scope is None else context_id.startswith(scope + ":")
if not valid:
from fastapi import HTTPException
raise HTTPException(409, "Template scope changed; reopen the terminal")
await ensure_terminal_state(template_id, context_id)
info = await self._ensure_terminal(template_id, context_id, spec)
if info:
info.update(template_id=template_id, context_id=context_id)
return info
# Fast path — already tracked and running.
if key in self._instances:
info = self._instances[key]
checked = self._running_checked_at.get(key)
if (
settings.status_cache_ttl > 0
and checked is not None
and time.monotonic() - checked < settings.status_cache_ttl
):
self._record_activity(key)
return info
st = await self.status(info["instance_id"])
if st == "running":
self._running_checked_at[key] = time.monotonic()
self._record_activity(key)
return info
async def _ensure_terminal(self, template_id, context_id=DEFAULT_CONTEXT_ID, spec=None):
key = self._key(template_id, context_id)
info = self._instances.get(key)
if info and await self.status(info["workload_name"]) == "running":
return info
self.forget(key)
await self._apply_due_reset(template_id, context_id, spec)
info = await self.provision(template_id=template_id, context_id=context_id, spec=spec)
if info:
info.setdefault("started_at", time.time())
self._instances[key] = info
self._specs[key] = spec or {}
return info
# Serialise provisioning per key.
if key not in self._locks:
self._locks[key] = asyncio.Lock()
async with self._locks[key]:
# Re-check after acquiring lock — another request may have
# already provisioned while we were waiting.
if key in self._instances:
info = self._instances[key]
st = await self.status(info["instance_id"])
if st == "running":
self._running_checked_at[key] = time.monotonic()
self._record_activity(key)
return info
self._instances.pop(key, None)
self._specs.pop(key, None)
self._activity.pop(key, None)
self._activity_wall.pop(key, None)
self._running_checked_at.pop(key, None)
self._activity_synced_at.pop(key, None)
await self._apply_due_reset(user_id, policy_id, context_id, spec)
result = await self.provision(
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()
self._record_activity(key)
return result
async def get_terminal_info(
self,
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
) -> Optional[dict]:
"""Look up a running terminal without starting it or recording activity."""
info = self._instances.get(self._key(user_id, policy_id, context_id))
if info and await self.status(info["instance_id"]) == "running":
async def get_terminal_info(self, template_id, context_id=DEFAULT_CONTEXT_ID):
info = self._instances.get(self._key(template_id, context_id))
if info and await self.status(info["workload_name"]) == "running":
return info
return None
async def touch_activity(
self,
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
) -> None:
"""Record that *user_id*'s terminal is actively being used."""
context_id = normalize_context_id(context_id)
key = self._key(user_id, policy_id, context_id)
self._record_activity(key)
async def touch_activity(self, template_id, context_id=DEFAULT_CONTEXT_ID):
key = self._key(template_id, context_id)
checked = self._activity_synced_at.get(key)
interval = max(1, min(settings.status_cache_ttl or 30, 60))
if checked is not None and time.monotonic() - checked < interval:
return
await mark_terminal_active(user_id, policy_id, context_id)
self._activity_synced_at[key] = time.monotonic()
if checked is None or time.monotonic() - checked >= interval:
await mark_terminal_active(template_id, context_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: tuple[str, str, str],
user_id: str,
policy_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
) -> 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, context_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,
context_id: str,
spec: Optional[dict],
) -> bool:
if not await reset_due_for(user_id, policy_id, context_id, spec):
async def _apply_due_reset(self, template_id, context_id, spec):
if not await reset_due_for(template_id, context_id):
return False
await self.reset(user_id, policy_id, context_id, spec)
await mark_reset_applied(user_id, policy_id, context_id, spec)
log.info("Reset files for user=%s policy=%s", user_id, policy_id)
from terminals.utils.instances import stop_instance
await stop_instance(self, template_id, context_id)
await self.reset(template_id, context_id, spec)
await mark_reset_applied(template_id, context_id)
return True
def _tracked_items(
self,
*,
user_id: str | None = None,
policy_id: str | None = None,
context_id: str | None = None,
) -> list[tuple[tuple[str, str, str], str, str, str, dict, dict]]:
matches = []
for key, info in list(self._instances.items()):
item_user, item_policy, item_context = key
if user_id and item_user != user_id:
continue
if policy_id and item_policy != policy_id:
continue
if context_id is not None and item_context != normalize_context_id(context_id):
continue
matches.append(
(key, item_user, item_policy, item_context, info, self._specs.get(key, {}))
)
return matches
async def list_terminals(self, template_id=None):
from sqlalchemy import select
from terminals.db.session import async_session
from terminals.models.template import TemplateLifecycleState
from terminals.utils.instances import describe_instance
async with async_session() as session:
query = select(TemplateLifecycleState)
if template_id is not None:
query = query.where(TemplateLifecycleState.template_id == template_id)
rows = list(await session.scalars(query.order_by(TemplateLifecycleState.created_at)))
return [await describe_instance(self, row) for row in rows]
def _is_idle_by_activity(
self, key: tuple[str, str, str], spec: Optional[dict], now: float
) -> bool:
timeout_min = (spec or {}).get(
"idle_timeout_minutes", settings.idle_timeout_minutes
)
if not timeout_min or timeout_min <= 0:
return False
last_active = self._activity.get(key, now)
return now - last_active >= timeout_min * 60
async def refresh(
self,
*,
user_id: str | None = None,
policy_id: str | None = None,
context_id: str | None = None,
only_idle: bool = True,
reset: bool = False,
) -> RefreshResult:
"""Tear down matching terminals so the next access provisions fresh."""
result = RefreshResult()
now = time.monotonic()
for key, item_user, item_policy, item_context, info, spec in self._tracked_items(
user_id=user_id, policy_id=policy_id, context_id=context_id
):
result.matched += 1
st = await self.status(info["instance_id"])
idle = st != "running" or self._is_idle_by_activity(key, spec, now)
if only_idle and not idle:
result.skipped_active += 1
continue
await self.teardown(info["instance_id"])
self._instances.pop(key, None)
self._specs.pop(key, None)
self._activity.pop(key, None)
self._activity_wall.pop(key, None)
self._running_checked_at.pop(key, None)
self._activity_synced_at.pop(key, None)
self._locks.pop(key, None)
result.refreshed += 1
if reset:
await self.reset(item_user, item_policy, item_context, spec)
result.reset += 1
return result
async def list_terminals(self) -> list[dict]:
"""Return sanitized tracked terminal instances for the admin UI."""
rows = []
now = time.monotonic()
for key, user_id, policy_id, context_id, info, spec in self._tracked_items():
status = await self.status(info["instance_id"])
last_active = self._activity.get(key)
last_active_wall = self._activity_wall.get(key)
timeout_min = (spec or {}).get(
"idle_timeout_minutes", settings.idle_timeout_minutes
)
rows.append(
{
"user_id": user_id,
"policy_id": policy_id,
"context_id": context_id,
"status": status,
"instance_id": info.get("instance_id", ""),
"instance_name": info.get("instance_name", info.get("instance_id", "")),
"host": info.get("host", ""),
"port": info.get("port"),
"last_active_at": (
datetime.fromtimestamp(last_active_wall, timezone.utc).isoformat()
if last_active_wall
else None
),
"idle_seconds": int(now - last_active) if last_active else None,
"idle_timeout_minutes": timeout_min or 0,
}
)
return rows
# ------------------------------------------------------------------
# Idle reaper
# ------------------------------------------------------------------
def start_reaper(self) -> None:
"""Start the background idle-reaper task."""
if self._reaper_task is not None:
return
self._reaper_task = asyncio.create_task(self._reaper_loop())
log.info("Idle reaper started")
async def stop_reaper(self) -> None:
"""Cancel the reaper and wait for it to finish."""
def start_reaper(self):
if self._reaper_task is None:
return
self._reaper_task.cancel()
try:
await self._reaper_task
except asyncio.CancelledError:
pass
self._reaper_task = None
log.info("Idle reaper stopped")
self._reaper_task = asyncio.create_task(self._reaper_loop())
async def _reaper_loop(self) -> None:
"""Periodically check for idle terminals and tear them down."""
async def stop_reaper(self):
if self._reaper_task is not None:
self._reaper_task.cancel()
try:
await self._reaper_task
except asyncio.CancelledError:
pass
self._reaper_task = None
async def _reaper_loop(self):
while True:
try:
await asyncio.sleep(60)
@@ -424,132 +147,33 @@ class Backend(ABC):
except Exception:
log.exception("Idle reaper error")
async def _reap_idle(self) -> None:
"""Scan tracked instances and tear down any that exceeded their timeout."""
now = time.monotonic()
for key in list(self._instances):
info = self._instances.get(key)
if info is None:
continue
spec = self._specs.get(key, {})
user_id, policy_id, context_id = key
cleanup_timeout = settings.idle_cleanup_timeout_seconds
if await reset_due_for(user_id, policy_id, context_id, spec):
log.info(
"Refreshing terminal %s for due reset (user=%s, policy=%s)",
info.get("instance_name", info.get("instance_id")),
user_id,
policy_id,
)
try:
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 asyncio.wait_for(
self.reset(user_id, policy_id, context_id, spec), cleanup_timeout
)
await asyncio.wait_for(
mark_reset_applied(user_id, policy_id, context_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)
self._specs.pop(key, None)
self._activity.pop(key, None)
self._activity_wall.pop(key, None)
self._running_checked_at.pop(key, None)
self._activity_synced_at.pop(key, None)
self._locks.pop(key, None)
continue
timeout_min = spec.get(
"idle_timeout_minutes", settings.idle_timeout_minutes
)
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
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
if expired or idle_seconds >= timeout_min * 60:
log.info(
"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(
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 asyncio.wait_for(
self._apply_due_reset(user_id, policy_id, context_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)
self._specs.pop(key, None)
self._activity.pop(key, None)
self._activity_wall.pop(key, None)
self._running_checked_at.pop(key, None)
self._activity_synced_at.pop(key, None)
self._locks.pop(key, None)
async def _reap_idle(self):
from sqlalchemy import select
from terminals.db.session import async_session
from terminals.models.template import TemplateLifecycleState
from terminals.utils.instances import instance_lock, stop_instance
async with async_session() as session:
rows = list(await session.scalars(select(TemplateLifecycleState)))
for row in rows:
try:
async with instance_lock("template:" + row.template_id, shared=True), instance_lock(row.id):
async with async_session() as session:
if await session.get(TemplateLifecycleState, row.id) is None:
continue
current_spec = await resolve_template_spec(row.template_id)
spec = self._specs.get(row.id, current_spec) or {}
async with asyncio.timeout(settings.idle_cleanup_timeout_seconds):
if await self._apply_due_reset(row.template_id, row.context_id, spec):
continue
info = self._instances.get(row.id)
if not info:
continue
last_active = await terminal_last_active_at(row.template_id, row.context_id)
active_at = last_active.replace(tzinfo=timezone.utc).timestamp() if last_active else time.time()
idle = spec.get("idle_timeout_minutes", settings.idle_timeout_minutes)
lifetime = spec.get("max_lifetime_minutes", settings.max_lifetime_minutes)
expired = lifetime and lifetime > 0 and time.time() - info.get("started_at", time.time()) >= lifetime * 60
if expired or (idle and idle > 0 and time.time() - active_at >= idle * 60):
await stop_instance(self, row.template_id, row.context_id)
except Exception:
log.exception("Failed lifecycle sweep for %s", row.id)
+58 -120
View File
@@ -14,6 +14,7 @@ import httpx
from terminals.backends.base import Backend, parse_started_at
from terminals.config import settings
from terminals.utils.template_specs import resolve_template_spec
from terminals.utils.context import (
CONTEXT_HASH_LABEL,
CONTEXT_ID_ANNOTATION,
@@ -21,11 +22,13 @@ from terminals.utils.context import (
DEFAULT_CONTEXT_ID,
context_hash,
normalize_context_id,
get_terminal_id,
)
from terminals.utils.env import build_terminal_env
from terminals.utils.docker_mounts import parse_docker_mounts
from terminals.utils.parsing import parse_cpu_nanos, parse_memory, parse_size
from terminals.utils.network_profiles import resolve_network_profile
from terminals.utils.image_pull import ensure_docker_image
log = logging.getLogger(__name__)
@@ -36,7 +39,7 @@ _QUIET_LOG_LEVELS = {"WARNING", "ERROR", "CRITICAL"}
class DockerBackend(Backend):
"""Manage terminal instances as Docker containers."""
"""Manage terminal environments as Docker containers."""
def __init__(self) -> None:
super().__init__()
@@ -49,27 +52,16 @@ class DockerBackend(Backend):
return self._docker
@staticmethod
def _container_name(
policy_id: str, user_id: str, context_id: str = DEFAULT_CONTEXT_ID
) -> str:
"""Build a deterministic, DNS-safe container name (≤63 chars)."""
short = hashlib.sha256(user_id.encode()).hexdigest()[:12]
context_id = normalize_context_id(context_id)
if policy_id == "default":
name = f"{_CONTAINER_PREFIX}{short}"
else:
policy_slug = _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20]
name = f"{_CONTAINER_PREFIX}{short}-{policy_slug}"
if context_id != DEFAULT_CONTEXT_ID:
name = f"{name}-{context_hash(context_id)}"
return name
def _container_name(template_id: str, context_id: str = DEFAULT_CONTEXT_ID) -> str:
return f"terminal-{get_terminal_id(template_id, context_id)}"
@staticmethod
def _home_dir(user_id: str, context_id: str = DEFAULT_CONTEXT_ID) -> Path:
context_id = normalize_context_id(context_id)
if context_id == DEFAULT_CONTEXT_ID:
return Path(settings.docker_data_dir) / user_id
return Path(settings.docker_data_dir) / user_id / "contexts" / context_hash(context_id)
def _home_dir(template_id: str, context_id: str = DEFAULT_CONTEXT_ID) -> Path:
root = Path(settings.docker_data_dir) / ".terminals"
home = root / get_terminal_id(template_id, context_id)
if root.is_symlink() or home.is_symlink():
raise ValueError("Terminal directories must not be symlinks")
return home
# ------------------------------------------------------------------
# Backend interface
@@ -77,8 +69,7 @@ class DockerBackend(Backend):
async def provision(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> dict:
@@ -86,10 +77,10 @@ class DockerBackend(Backend):
docker = await self._get_docker()
api_key = secrets.token_urlsafe(24)
context_id = normalize_context_id(context_id)
instance_name = self._container_name(policy_id, user_id, context_id)
host_data_dir = str(self._home_dir(user_id, context_id).resolve())
workload_name = self._container_name(template_id, context_id)
host_data_dir = str(self._home_dir(template_id, context_id).resolve())
if settings.docker_host_data_dir:
relative_home = self._home_dir(user_id, context_id).relative_to(settings.docker_data_dir)
relative_home = self._home_dir(template_id, context_id).relative_to(settings.docker_data_dir)
host_data_dir = str(Path(settings.docker_host_data_dir) / relative_home)
s = spec or {}
@@ -100,7 +91,7 @@ class DockerBackend(Backend):
if len(networks) == 1:
network_name = networks[0]
elif networks:
key = f"{policy_id}:{user_id}:{context_id}".encode()
key = get_terminal_id(template_id, context_id).encode()
network_name = networks[int(hashlib.sha256(key).hexdigest(), 16) % len(networks)]
host_config: dict = {
@@ -127,7 +118,7 @@ class DockerBackend(Backend):
host_config["StorageOpt"] = {"size": str(parse_size(s["storage"]))}
log.info(
"Applying storage quota %s to writable layer of %s (/home/user not limited)",
s["storage"], instance_name,
s["storage"], workload_name,
)
# Egress filtering is handled inside the container (dnsmasq + ipset +
@@ -156,8 +147,8 @@ class DockerBackend(Backend):
"ExposedPorts": {"8000/tcp": {}},
"Labels": {
"app.kubernetes.io/managed-by": "terminals",
"openwebui.com/user-id": user_id,
"openwebui.com/policy": policy_id,
"openwebui.com/instance": get_terminal_id(template_id, context_id),
"openwebui.com/template": template_id,
CONTEXT_ID_ANNOTATION: context_id,
CONTEXT_TYPE_LABEL: (
DEFAULT_CONTEXT_ID
@@ -169,24 +160,25 @@ class DockerBackend(Backend):
}
log.info(
"Provisioning container %s for user %s (policy=%s, context=%s, network=%s)",
instance_name,
user_id,
policy_id,
"Provisioning container %s (template=%s, context=%s, network=%s)",
workload_name,
template_id,
context_id,
network_name or "default",
)
await ensure_docker_image(docker, image)
max_conflict_retries = 3
container = None
for attempt in range(max_conflict_retries + 1):
try:
container = await docker.containers.run(config, name=instance_name)
container = await docker.containers.run(config, name=workload_name)
break
except aiodocker.exceptions.DockerError as exc:
if exc.status == 409 and attempt < max_conflict_retries:
try:
old = await docker.containers.get(instance_name)
old = await docker.containers.get(workload_name)
old_info = await old.show()
if old_info.get("State", {}).get("Running"):
for entry in old_info.get("Config", {}).get("Env", []):
@@ -194,15 +186,15 @@ class DockerBackend(Backend):
api_key = entry.split("=", 1)[1]
break
container = old
log.info("Adopted running container %s", instance_name)
log.info("Adopted running container %s", workload_name)
break
log.warning(
"Container %s conflict (attempt %d/%d), removing stopped container",
instance_name, attempt + 1, max_conflict_retries,
workload_name, attempt + 1, max_conflict_retries,
)
await old.delete(force=True)
except aiodocker.exceptions.DockerError as adopt_exc:
log.warning("Could not adopt/remove %s: %s", instance_name, adopt_exc)
log.warning("Could not adopt/remove %s: %s", workload_name, adopt_exc)
await asyncio.sleep(1)
continue
# The storage driver may not support StorageOpt size quotas
@@ -214,17 +206,17 @@ class DockerBackend(Backend):
log.warning(
"Storage quota not supported by the Docker storage driver "
"for %s (%s), provisioning without a storage limit",
instance_name, exc,
workload_name, exc,
)
host_config.pop("StorageOpt", None)
continue
log.error("Failed to provision container for %s: %s", user_id, exc)
log.error("Failed to provision container for %s: %s", template_id, exc)
raise
if container is None:
raise RuntimeError(f"Failed to provision or adopt container {instance_name}")
raise RuntimeError(f"Failed to provision or adopt container {workload_name}")
result = await self._extract_instance_info(container, instance_name, api_key)
result = await self._extract_instance_info(container, workload_name, api_key)
await self._wait_until_ready(result, timeout=15)
return result
@@ -238,28 +230,27 @@ class DockerBackend(Backend):
async with httpx.AsyncClient(timeout=3) as client:
resp = await client.get(url)
if resp.status_code == 200:
log.info("Container %s is ready", instance["instance_name"])
log.info("Container %s is ready", instance["workload_name"])
return
except Exception:
pass
await asyncio.sleep(0.5)
log.warning("Container %s did not become ready within %ds", instance["instance_name"], timeout)
log.warning("Container %s did not become ready within %ds", instance["workload_name"], timeout)
async def _extract_instance_info(
self,
container,
instance_name: str,
workload_name: str,
api_key: str,
) -> dict:
"""Read container metadata and return the instance info dict."""
info = await container.show()
instance_id = info["Id"]
# When using a custom Docker network, containers can reach each other
# by name. Otherwise, use the published port on the Docker host.
network_mode = info.get("HostConfig", {}).get("NetworkMode", "default")
if network_mode not in ("default", "bridge", "host", "none", ""):
host = instance_name
host = workload_name
port = 8000
else:
port_bindings = (
@@ -274,8 +265,7 @@ class DockerBackend(Backend):
host = settings.docker_host
return {
"instance_id": instance_id,
"instance_name": instance_name,
"workload_name": workload_name,
"api_key": api_key,
"host": host,
"port": port,
@@ -291,7 +281,7 @@ class DockerBackend(Backend):
Called during startup to recover state after a restart without
tearing down existing containers. Uses Docker labels to identify
user_id and policy_id. The API key is read from the container's
the template and context. The API key is read from the container's
``OPEN_TERMINAL_API_KEY`` env var.
"""
docker = await self._get_docker()
@@ -309,14 +299,15 @@ class DockerBackend(Backend):
name = info.get("Name", "").lstrip("/")
labels = info.get("Config", {}).get("Labels", {})
user_id = labels.get("openwebui.com/user-id")
policy_id = labels.get("openwebui.com/policy", "default")
context_id = normalize_context_id(labels.get(CONTEXT_ID_ANNOTATION))
if not user_id:
log.debug("Skipping container %s: no user-id label", name)
template_id = labels.get("openwebui.com/template")
context_id = labels.get(CONTEXT_ID_ANNOTATION)
if not template_id or not context_id:
log.warning("Skipping container %s without template/context metadata", name)
continue
if name != self._container_name(template_id, context_id):
continue
key = self._key(user_id, policy_id, context_id)
key = self._key(template_id, context_id)
# Already tracked
if key in self._instances:
@@ -329,11 +320,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)
if template_id not in adopted_specs:
adopted_specs[template_id] = await resolve_template_spec(template_id)
self._instances[key] = instance_info
self._specs[key] = adopted_specs[policy_id]
await self._seed_adopted_activity(key, user_id, policy_id, context_id)
self._specs[key] = adopted_specs[template_id]
self._instances[key].update(template_id=template_id, context_id=context_id)
recovered += 1
log.info("Reconciled container %s → %s:%s", name, instance_info["host"], instance_info["port"])
@@ -344,42 +335,15 @@ class DockerBackend(Backend):
# Container lifecycle
# ------------------------------------------------------------------
async def start(self, instance_id: str) -> bool:
current = await self.status(instance_id)
if current == "running":
return True
if current == "stopped":
docker = await self._get_docker()
try:
container = await docker.containers.get(instance_id)
await container.start()
return True
except aiodocker.exceptions.DockerError as exc:
log.error("Failed to restart container %s: %s", instance_id, exc)
return False
return False # missing
async def teardown(self, instance_id: str) -> None:
docker = await self._get_docker()
try:
container = await docker.containers.get(instance_id)
await container.stop(t=10)
except aiodocker.exceptions.DockerError:
pass
try:
container = await docker.containers.get(instance_id)
await container.delete(force=True)
except aiodocker.exceptions.DockerError:
log.warning("Could not remove container %s (may already be gone)", instance_id)
async def reset(
self,
user_id: str,
policy_id: str,
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> None:
home_dir = self._home_dir(user_id, context_id).resolve()
home_dir = self._home_dir(template_id, context_id).resolve()
home_dir.mkdir(parents=True, exist_ok=True)
for child in home_dir.iterdir():
if child.is_dir() and not child.is_symlink():
@@ -387,44 +351,18 @@ class DockerBackend(Backend):
else:
child.unlink(missing_ok=True)
async def list_user_data(self) -> list[str]:
root = Path(settings.docker_data_dir)
if not root.exists():
return []
return sorted(path.name for path in root.iterdir() if not path.is_symlink() and path.is_dir())
async def cleanup_user(self, user_id: str) -> int:
home_dir = self._home_dir(user_id)
root = Path(settings.docker_data_dir).resolve()
if Path(user_id).name != user_id or home_dir.is_symlink() or home_dir.resolve().parent != root:
raise ValueError("User workspace must be a direct directory under the data directory")
docker = await self._get_docker()
containers = await docker.containers.list(
all=True,
filters={"label": ["app.kubernetes.io/managed-by=terminals"]},
)
for container in containers:
info = await container.show()
if (info.get("Config", {}).get("Labels") or {}).get("openwebui.com/user-id") == user_id:
raise RuntimeError("Remove the user's terminal containers before cleanup")
if not home_dir.exists():
return 0
await asyncio.to_thread(shutil.rmtree, home_dir)
log.info("Deleted workspace for user=%s path=%s", user_id, home_dir)
return 1
async def status(self, instance_id: str) -> str:
async def status(self, name: str) -> str:
docker = await self._get_docker()
try:
container = await docker.containers.get(instance_id)
container = await docker.containers.get(name)
info = await container.show()
state = info.get("State", {})
if state.get("Running"):
return "running"
return "stopped"
except aiodocker.exceptions.DockerError:
except aiodocker.exceptions.DockerError as exc:
if exc.status != 404:
raise
return "missing"
async def close(self) -> None:
+53 -202
View File
@@ -2,9 +2,7 @@
import asyncio
import base64
import hashlib
import logging
import re
import secrets
from typing import Optional
@@ -13,6 +11,8 @@ from kubernetes_asyncio.client import ApiClient
from terminals.backends.base import Backend, parse_started_at
from terminals.config import settings
from terminals.utils.kubernetes_labels import template_label
from terminals.utils.template_specs import resolve_template_spec
from terminals.utils.network_profiles import resolve_network_profile
from terminals.utils.context import (
CONTEXT_HASH_LABEL,
@@ -21,6 +21,7 @@ from terminals.utils.context import (
DEFAULT_CONTEXT_ID,
context_hash,
normalize_context_id,
get_terminal_id,
)
from terminals.utils.env import build_terminal_env
from terminals.utils.kubernetes_security import (
@@ -30,6 +31,7 @@ from terminals.utils.kubernetes_security import (
restricted_enabled,
)
from terminals.utils.kubernetes_scheduling import node_selector, tolerations
from terminals.utils.image_pull import pull_policy
log = logging.getLogger(__name__)
@@ -37,26 +39,11 @@ log = logging.getLogger(__name__)
# Helpers
# ---------------------------------------------------------------------------
_DNS_SAFE = re.compile(r"[^a-z0-9-]")
_POLICY_ID_ANNOTATION = "openwebui.com/policy-id"
_TEMPLATE_ID_ANNOTATION = "openwebui.com/template-id"
def _sanitize_name(
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
) -> str:
"""Deterministic, DNS-safe K8s resource name (≤63 chars)."""
short = hashlib.sha256(user_id.encode()).hexdigest()[:12]
context_id = normalize_context_id(context_id)
if policy_id == "default":
name = f"terminal-{short}"
else:
policy_slug = _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20]
name = f"terminal-{short}-{policy_slug}"
if context_id != DEFAULT_CONTEXT_ID:
name = f"{name}-{context_hash(context_id)}"
return name
def _sanitize_name(template_id: str, context_id: str = DEFAULT_CONTEXT_ID) -> str:
return f"terminal-{get_terminal_id(template_id, context_id)}"
def _parse_labels() -> dict[str, str]:
@@ -72,69 +59,17 @@ def _parse_labels() -> dict[str, str]:
return labels
def _base_labels(user_id: str) -> dict[str, str]:
def _base_labels(template_id: str, context_id: str) -> dict[str, str]:
"""Standard labels applied to every resource we create."""
labels = {
"app.kubernetes.io/managed-by": "terminals",
"app.kubernetes.io/part-of": "open-terminal",
"openwebui.com/user-id": user_id,
"openwebui.com/instance": get_terminal_id(template_id, context_id),
}
labels.update(_parse_labels())
return labels
async def _list_user_data(core) -> list[str]:
pvcs = await core.list_namespaced_persistent_volume_claim(
settings.kubernetes_namespace, label_selector="app.kubernetes.io/managed-by=terminals"
)
return sorted({
pvc.metadata.labels["openwebui.com/user-id"] for pvc in pvcs.items
if (pvc.metadata.labels or {}).get("openwebui.com/user-id")
})
async def _cleanup_user_pvcs(core, user_id: str) -> int:
ns = settings.kubernetes_namespace
pvcs = await core.list_namespaced_persistent_volume_claim(
ns, label_selector="app.kubernetes.io/managed-by=terminals"
)
if any(pvc.metadata.name == f"terminals-shared-{ns}" for pvc in pvcs.items):
raise RuntimeError("Shared PVC storage requires clearing the user's subdirectory separately")
claims = {
pvc.metadata.name: pvc for pvc in pvcs.items
if (pvc.metadata.labels or {}).get("openwebui.com/user-id") == user_id
}
for attempt in range(61):
pods = await core.list_namespaced_pod(ns)
matching = [
pod for pod in pods.items
if (pod.metadata.labels or {}).get("openwebui.com/user-id") == user_id or any(
volume.persistent_volume_claim
and volume.persistent_volume_claim.claim_name in claims
for volume in pod.spec.volumes or []
)
]
if not matching:
break
if attempt == 60 or any(not pod.metadata.deletion_timestamp for pod in matching):
raise RuntimeError("Terminal pods still exist; user data has not been deleted. Remove them and retry.")
await asyncio.sleep(0.5)
deleted = 0
for name, pvc in claims.items():
try:
await core.delete_namespaced_persistent_volume_claim(
name, ns,
body=client.V1DeleteOptions(preconditions=client.V1Preconditions(uid=pvc.metadata.uid)),
)
except client.exceptions.ApiException as exc:
if exc.status != 404:
raise
continue
deleted += 1
log.info("Requested workspace PVC deletion for user=%s namespace=%s name=%s", user_id, ns, name)
return deleted
def _deep_merge(*items: dict | None) -> dict:
result = {}
for item in items:
@@ -225,12 +160,11 @@ def _apply_pod_template(pod_manifest: dict, pod_template: dict | None) -> dict:
class KubernetesBackend(Backend):
"""Manage terminal instances as Kubernetes Pods + Services."""
"""Manage terminal environments as Kubernetes Pods + Services."""
def __init__(self) -> None:
super().__init__()
self._api_client: Optional[ApiClient] = None
self._uid_cache: dict[str, str] = {} # uid → pod name
async def _ensure_client(self) -> ApiClient:
if self._api_client is None:
@@ -249,8 +183,7 @@ class KubernetesBackend(Backend):
async def provision(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> dict:
@@ -261,12 +194,12 @@ class KubernetesBackend(Backend):
api_key = secrets.token_urlsafe(24)
context_id = normalize_context_id(context_id)
name = _sanitize_name(user_id, policy_id, context_id)
policy_slug = _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20]
name = _sanitize_name(template_id, context_id)
template_slug = template_label(template_id)
ns = settings.kubernetes_namespace
labels = _base_labels(user_id)
labels = _base_labels(template_id, context_id)
labels.update(profile.get("kubernetes_labels", {}))
labels["openwebui.com/policy"] = policy_slug
labels["openwebui.com/template"] = template_slug
labels[CONTEXT_TYPE_LABEL] = (
DEFAULT_CONTEXT_ID
if context_id == DEFAULT_CONTEXT_ID
@@ -274,7 +207,7 @@ class KubernetesBackend(Backend):
)
labels[CONTEXT_HASH_LABEL] = context_hash(context_id)
annotations = {
_POLICY_ID_ANNOTATION: policy_id,
_TEMPLATE_ID_ANNOTATION: template_id,
CONTEXT_ID_ANNOTATION: context_id,
}
@@ -321,11 +254,11 @@ class KubernetesBackend(Backend):
# Egress filtering is handled inside the container (dnsmasq + ipset +
# iptables + capsh) triggered by OPEN_TERMINAL_ALLOWED_DOMAINS env var.
has_egress_policy = "OPEN_TERMINAL_ALLOWED_DOMAINS" in terminal_env
has_egress_template = "OPEN_TERMINAL_ALLOWED_DOMAINS" in terminal_env
restricted = restricted_enabled(s)
pod_security = pod_security_context(s)
container_security = container_security_context(s)
if not container_security and has_egress_policy and not restricted:
if not container_security and has_egress_template and not restricted:
container_security = {
"capabilities": {
"add": ["NET_ADMIN"],
@@ -347,15 +280,11 @@ class KubernetesBackend(Backend):
volume_mounts = []
affinity = None
shared_pvc_name = f"terminals-shared-{ns}"
shared_sub_path = (
user_id
if context_id == DEFAULT_CONTEXT_ID
else f"{user_id}/contexts/{context_hash(context_id)}"
)
shared_sub_path = f".terminals/{get_terminal_id(template_id, context_id)}"
if storage_size:
if storage_mode == "per-user":
# Each user gets their own PVC
# Legacy storage-mode spelling; each environment gets its own PVC.
pvc = client.V1PersistentVolumeClaim(
metadata=client.V1ObjectMeta(name=name, namespace=ns, labels=labels),
spec=client.V1PersistentVolumeClaimSpec(
@@ -439,6 +368,7 @@ class KubernetesBackend(Backend):
client.V1Container(
name="open-terminal",
image=image,
image_pull_policy=pull_policy(image),
ports=[client.V1ContainerPort(container_port=8000)],
env=env_vars,
volume_mounts=volume_mounts or None,
@@ -467,19 +397,17 @@ class KubernetesBackend(Backend):
)
try:
created = await core.create_namespaced_pod(ns, pod)
log.info("Created Pod %s in %s (policy=%s, storage=%s)", name, ns, policy_id, storage_mode)
await core.create_namespaced_pod(ns, pod)
log.info("Created Pod %s in %s (template=%s, storage=%s)", name, ns, template_id, storage_mode)
except client.exceptions.ApiException as exc:
if exc.status == 409:
log.info("Pod %s already exists, replacing", name)
await core.delete_namespaced_pod(name, ns)
await self._wait_for_pod_deletion(core, name, ns)
created = await core.create_namespaced_pod(ns, pod)
await core.create_namespaced_pod(ns, pod)
else:
raise
instance_id = created.metadata.uid
self._uid_cache[instance_id] = name
# ---- Service -----------------------------------------------------
svc = client.V1Service(
@@ -487,8 +415,8 @@ class KubernetesBackend(Backend):
spec=client.V1ServiceSpec(
type=settings.kubernetes_service_type,
selector={
"openwebui.com/user-id": user_id,
"openwebui.com/policy": policy_slug,
"openwebui.com/instance": get_terminal_id(template_id, context_id),
"openwebui.com/template": template_slug,
CONTEXT_HASH_LABEL: context_hash(context_id),
},
ports=[
@@ -509,8 +437,7 @@ class KubernetesBackend(Backend):
await self._wait_until_pod_ready(core, name, ns, timeout=60)
return {
"instance_id": instance_id,
"instance_name": name,
"workload_name": name,
"api_key": api_key,
"host": host,
"port": 8000,
@@ -539,61 +466,13 @@ class KubernetesBackend(Backend):
await asyncio.sleep(1)
log.warning("Pod %s did not become ready within %ds", name, timeout)
async def start(self, instance_id: str) -> bool:
current = await self.status(instance_id)
if current == "running":
return True
# Pods cannot be restarted. The caller should refresh the terminal.
return False
async def teardown(self, instance_id: str) -> None:
api_client = await self._ensure_client()
core = client.CoreV1Api(api_client)
ns = settings.kubernetes_namespace
# Find the pod by UID to get the name.
name = await self._name_from_uid(instance_id)
if name is None:
log.warning("No pod found for UID %s", instance_id)
return
# Delete Pod.
try:
await core.delete_namespaced_pod(name, ns)
log.info("Deleted Pod %s", name)
except client.exceptions.ApiException:
log.warning("Could not delete Pod %s (may already be gone)", name)
# Delete Service.
try:
await core.delete_namespaced_service(name, ns)
log.info("Deleted Service %s", name)
except client.exceptions.ApiException:
log.warning("Could not delete Service %s", name)
# Delete Secret.
secret_name = f"{name}-apikey"
try:
await core.delete_namespaced_secret(secret_name, ns)
log.info("Deleted Secret %s", secret_name)
except client.exceptions.ApiException:
log.warning("Could not delete Secret %s (may already be gone)", secret_name)
# Clean up UID cache.
self._uid_cache.pop(instance_id, None)
# Note: PVC is intentionally kept for data persistence.
async def list_user_data(self) -> list[str]:
api_client = await self._ensure_client()
return await _list_user_data(client.CoreV1Api(api_client))
async def cleanup_user(self, user_id: str) -> int:
api_client = await self._ensure_client()
return await _cleanup_user_pvcs(client.CoreV1Api(api_client), user_id)
async def reset(
self,
user_id: str,
policy_id: str,
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> None:
@@ -607,18 +486,14 @@ class KubernetesBackend(Backend):
storage_mode = s.get("storage_mode", settings.kubernetes_storage_mode)
context_id = normalize_context_id(context_id)
terminal_name = _sanitize_name(user_id, policy_id, context_id)
terminal_name = _sanitize_name(template_id, context_id)
reset_name = f"{terminal_name[:57]}-reset"
shared_pvc_name = f"terminals-shared-{ns}"
claim_name = terminal_name
sub_path = None
if storage_mode in ("shared", "shared-rwo"):
claim_name = shared_pvc_name
sub_path = (
user_id
if context_id == DEFAULT_CONTEXT_ID
else f"{user_id}/contexts/{context_hash(context_id)}"
)
sub_path = f".terminals/{get_terminal_id(template_id, context_id)}"
try:
await core.read_namespaced_persistent_volume_claim(claim_name, ns)
@@ -627,8 +502,8 @@ class KubernetesBackend(Backend):
return
raise
labels = _base_labels(user_id)
labels["openwebui.com/policy"] = _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20]
labels = _base_labels(template_id, context_id)
labels["openwebui.com/template"] = template_label(template_id)
labels[CONTEXT_TYPE_LABEL] = (
DEFAULT_CONTEXT_ID
if context_id == DEFAULT_CONTEXT_ID
@@ -648,6 +523,7 @@ class KubernetesBackend(Backend):
(item for item in template.get("containers", []) if item.get("name") == "open-terminal"),
{},
)
reset_image = s.get("image", settings.effective_kubernetes_image)
pod = client.V1Pod(
metadata=client.V1ObjectMeta(name=reset_name, namespace=ns, labels=labels),
spec=client.V1PodSpec(
@@ -659,7 +535,8 @@ class KubernetesBackend(Backend):
containers=[
client.V1Container(
name="reset",
image=s.get("image", settings.effective_kubernetes_image),
image=reset_image,
image_pull_policy=pull_policy(reset_image),
security_context=deep_merge(
terminal_container.get("securityContext"), container_security_context(s)
) or None,
@@ -710,15 +587,11 @@ class KubernetesBackend(Backend):
except client.exceptions.ApiException:
pass
async def status(self, instance_id: str) -> str:
async def status(self, name: str) -> str:
api_client = await self._ensure_client()
core = client.CoreV1Api(api_client)
ns = settings.kubernetes_namespace
name = await self._name_from_uid(instance_id)
if name is None:
return "missing"
try:
pod = await core.read_namespaced_pod(name, ns)
phase = pod.status.phase # Pending, Running, Succeeded, Failed, Unknown
@@ -735,7 +608,9 @@ class KubernetesBackend(Backend):
# Still pulling or initializing — treat as starting.
return "running"
return "stopped"
except client.exceptions.ApiException:
except client.exceptions.ApiException as exc:
if exc.status != 404:
raise
return "missing"
async def close(self) -> None:
@@ -751,8 +626,8 @@ class KubernetesBackend(Backend):
"""Scan running K8s pods and repopulate ``_instances``.
Called during startup to recover state after a restart.
Reads user_id and policy from pod labels, and the API key
from the pod's env vars.
Reads full template/context identifiers from annotations and the API key
from the companion Secret.
"""
api_client = await self._ensure_client()
core = client.CoreV1Api(api_client)
@@ -772,20 +647,18 @@ class KubernetesBackend(Backend):
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)
context_id = normalize_context_id(annotations.get(CONTEXT_ID_ANNOTATION))
if not user_id:
template_id = annotations.get(_TEMPLATE_ID_ANNOTATION)
context_id = annotations.get(CONTEXT_ID_ANNOTATION)
if not template_id or not context_id:
log.warning("Skipping pod %s without template/context metadata", pod.metadata.name)
continue
if pod.metadata.name != _sanitize_name(template_id, context_id):
continue
uid = pod.metadata.uid
name = pod.metadata.name
self._uid_cache[uid] = name
key = self._key(user_id, policy_id, context_id)
key = self._key(template_id, context_id)
if key in self._instances:
continue
@@ -804,18 +677,17 @@ 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)
if template_id not in adopted_specs:
adopted_specs[template_id] = await resolve_template_spec(template_id)
self._instances[key] = {
"instance_id": uid,
"instance_name": name,
"workload_name": name,
"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)
self._specs[key] = adopted_specs[template_id]
self._instances[key].update(template_id=template_id, context_id=context_id)
recovered += 1
if recovered:
@@ -825,27 +697,6 @@ class KubernetesBackend(Backend):
# Internal helpers
# ------------------------------------------------------------------
async def _name_from_uid(self, uid: str) -> Optional[str]:
"""Look up a Pod name by its UID (cached)."""
if uid in self._uid_cache:
return self._uid_cache[uid]
api_client = await self._ensure_client()
core = client.CoreV1Api(api_client)
ns = settings.kubernetes_namespace
try:
pods = await core.list_namespaced_pod(
ns, label_selector="app.kubernetes.io/managed-by=terminals"
)
for pod in pods.items:
self._uid_cache[pod.metadata.uid] = pod.metadata.name
if pod.metadata.uid == uid:
return pod.metadata.name
except client.exceptions.ApiException:
pass
return None
async def _wait_for_pod_deletion(
self, core: client.CoreV1Api, name: str, ns: str, timeout: int = 30,
) -> None:
+116 -357
View File
@@ -10,18 +10,16 @@ This backend reads the key from the Secret referenced in ``status.apiKeySecret``
import asyncio
import base64
import hashlib
import logging
import re
import time
from typing import Optional
from kubernetes_asyncio import client, config
from kubernetes_asyncio.client import ApiClient
from terminals.backends.base import Backend, ProvisioningError, RefreshResult, parse_started_at
from terminals.backends.kubernetes import _cleanup_user_pvcs, _list_user_data
from terminals.backends.base import Backend, ProvisioningError, parse_started_at
from terminals.config import settings
from terminals.utils.kubernetes_labels import template_label
from terminals.utils.network_profiles import resolve_network_profile
from terminals.utils.context import (
CONTEXT_HASH_LABEL,
@@ -30,6 +28,7 @@ from terminals.utils.context import (
DEFAULT_CONTEXT_ID,
context_hash,
normalize_context_id,
get_terminal_id,
)
from terminals.utils.env import build_terminal_env
from terminals.utils.kubernetes_security import (
@@ -39,7 +38,8 @@ from terminals.utils.kubernetes_security import (
restricted_enabled,
)
from terminals.utils.kubernetes_scheduling import node_selector, tolerations
from terminals.utils.policy_lifecycle import mark_terminal_active
from terminals.utils.template_lifecycle import mark_terminal_active
from terminals.utils.image_pull import pull_policy
log = logging.getLogger(__name__)
@@ -47,30 +47,15 @@ log = logging.getLogger(__name__)
# Helpers
# ---------------------------------------------------------------------------
_DNS_SAFE = re.compile(r"[^a-z0-9-]")
_POLICY_ID_ANNOTATION = "openwebui.com/policy-id"
_TEMPLATE_ID_ANNOTATION = "openwebui.com/template-id"
def _sanitize_name(
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
) -> str:
"""Deterministic, DNS-safe Terminal CR name from a user ID + policy."""
short = hashlib.sha256(user_id.encode()).hexdigest()[:12]
context_id = normalize_context_id(context_id)
if policy_id == "default":
name = f"terminal-{short}"
else:
policy_slug = _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20]
name = f"terminal-{short}-{policy_slug}"
if context_id != DEFAULT_CONTEXT_ID:
name = f"{name}-{context_hash(context_id)}"
return name
def _sanitize_name(template_id: str, context_id: str = DEFAULT_CONTEXT_ID) -> str:
return f"terminal-{get_terminal_id(template_id, context_id)}"
class KubernetesOperatorBackend(Backend):
"""Manage terminal instances via Terminal CRDs.
"""Manage terminal environments via Terminal CRDs.
The backend creates/deletes ``Terminal`` custom resources in the
configured namespace. A Kopf operator running in the cluster watches
@@ -80,7 +65,7 @@ class KubernetesOperatorBackend(Backend):
def __init__(self) -> None:
super().__init__()
self._api_client: Optional[ApiClient] = None
self._last_activity_status_updated_at: dict[tuple[str, str, str], float] = {}
self._last_activity_status_updated_at: dict[str, float] = {}
async def _ensure_client(self) -> ApiClient:
if self._api_client is None:
@@ -125,14 +110,13 @@ class KubernetesOperatorBackend(Backend):
async def _get_terminal_cr(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
) -> Optional[dict]:
"""Get the Terminal CR for a user+policy, or None if it doesn't exist."""
"""Get the Terminal CR for a template/context, or None if it doesn't exist."""
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
name = _sanitize_name(user_id, policy_id, context_id)
name = _sanitize_name(template_id, context_id)
ns = settings.kubernetes_namespace
try:
cr = await custom.get_namespaced_custom_object(
@@ -160,27 +144,28 @@ class KubernetesOperatorBackend(Backend):
async def _create_terminal_cr(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> dict:
"""Create a Terminal CR for a user+policy and return it."""
"""Create a Terminal CR for a template/context and return it."""
profile = resolve_network_profile(spec, "kubernetes-operator")
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
context_id = normalize_context_id(context_id)
name = _sanitize_name(user_id, policy_id, context_id)
name = _sanitize_name(template_id, context_id)
ns = settings.kubernetes_namespace
s = spec or {}
s = dict(spec or {})
s.setdefault("storage", settings.kubernetes_storage_size)
image = s.get("image", settings.effective_kubernetes_image)
storage_size = s.get("storage") # absent = ephemeral
# Build CRD spec aligned with manifests/terminal-crd.yaml.
cr_spec: dict = {
"userId": user_id,
"templateId": template_id,
"image": image,
"imagePullPolicy": pull_policy(image),
"contextId": context_id,
}
restricted = restricted_enabled(s)
@@ -207,9 +192,6 @@ class KubernetesOperatorBackend(Backend):
cr_spec["storage"] = storage_size
if settings.kubernetes_storage_class:
cr_spec["storageClass"] = settings.kubernetes_storage_class
# Storage mode (per-user, shared, shared-rwo)
storage_mode = s.get("storage_mode", settings.kubernetes_storage_mode)
cr_spec["storageMode"] = storage_mode
cr_spec["persistence"] = {
"enabled": True,
"size": storage_size,
@@ -239,7 +221,7 @@ class KubernetesOperatorBackend(Backend):
if idle_timeout is not None and idle_timeout >= 0:
cr_spec["idleTimeoutMinutes"] = idle_timeout
policy_slug = _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20]
template_slug = template_label(template_id)
cr = {
"apiVersion": f"{self._group}/{self._version}",
@@ -250,8 +232,8 @@ class KubernetesOperatorBackend(Backend):
"labels": {
"app.kubernetes.io/managed-by": "terminals",
"app.kubernetes.io/part-of": "open-terminal",
"openwebui.com/user-id": user_id,
"openwebui.com/policy": policy_slug,
"openwebui.com/instance": get_terminal_id(template_id, context_id),
"openwebui.com/template": template_slug,
CONTEXT_TYPE_LABEL: (
DEFAULT_CONTEXT_ID
if context_id == DEFAULT_CONTEXT_ID
@@ -260,7 +242,7 @@ class KubernetesOperatorBackend(Backend):
CONTEXT_HASH_LABEL: context_hash(context_id),
},
"annotations": {
_POLICY_ID_ANNOTATION: policy_id,
_TEMPLATE_ID_ANNOTATION: template_id,
CONTEXT_ID_ANNOTATION: context_id,
},
},
@@ -278,11 +260,11 @@ class KubernetesOperatorBackend(Backend):
except client.exceptions.ApiException as exc:
if exc.status == 409:
# Already exists — but may be mid-deletion (finalizer pending).
existing = await self._get_terminal_cr(user_id, policy_id, context_id)
existing = await self._get_terminal_cr(template_id, context_id)
if existing and existing.get("metadata", {}).get("deletionTimestamp"):
# CR is being deleted; wait for it to vanish, then retry create
await self._wait_for_deletion(
user_id, policy_id, context_id=context_id, timeout=60
template_id, context_id=context_id, timeout=60
)
return await custom.create_namespaced_custom_object(
group=self._group,
@@ -305,30 +287,27 @@ class KubernetesOperatorBackend(Backend):
async def _delete_terminal_cr(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
wait: bool = True,
timeout: int = 60,
) -> bool:
"""Delete the Terminal CR for a user+policy and optionally wait for it to be gone.
"""Delete the Terminal CR for a template/context and optionally wait for it to be gone.
When *wait* is True (default), polls until the CR returns 404 so that
a subsequent create won't collide with the kopf finalizer.
"""
context_id = normalize_context_id(context_id)
key = self._key(user_id, policy_id, context_id)
key = self._key(template_id, context_id)
self._instances.pop(key, None)
self._specs.pop(key, None)
self._activity.pop(key, None)
self._activity_wall.pop(key, None)
self._running_checked_at.pop(key, None)
self._activity_synced_at.pop(key, None)
self._last_activity_status_updated_at.pop(key, None)
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
name = _sanitize_name(user_id, policy_id, context_id)
name = _sanitize_name(template_id, context_id)
ns = settings.kubernetes_namespace
try:
await custom.delete_namespaced_custom_object(
@@ -363,20 +342,18 @@ class KubernetesOperatorBackend(Backend):
raise
await asyncio.sleep(1)
log.warning("Terminal CR %s not fully deleted after %ds", name, timeout)
return True
raise RuntimeError(f"Terminal CR {name} is still terminating after {timeout}s")
async def _wait_for_deletion(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
timeout: int = 60,
) -> None:
"""Poll until a Terminal CR no longer exists (404)."""
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
name = _sanitize_name(user_id, policy_id, context_id)
name = _sanitize_name(template_id, context_id)
ns = settings.kubernetes_namespace
deadline = asyncio.get_event_loop().time() + timeout
@@ -441,27 +418,6 @@ class KubernetesOperatorBackend(Backend):
)
return None
async def _name_from_uid(self, uid: str) -> Optional[str]:
"""Look up a Terminal CR name by its UID."""
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
ns = settings.kubernetes_namespace
try:
result = await custom.list_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=ns,
plural=self._plural,
label_selector="app.kubernetes.io/managed-by=terminals",
)
for item in result.get("items", []):
if item["metadata"]["uid"] == uid:
return item["metadata"]["name"]
except client.exceptions.ApiException:
pass
return None
def _parse_service_url(self, service_url: str) -> tuple[str, int]:
"""Extract host and port from a service URL like http://svc:8000."""
url = service_url.rstrip("/")
@@ -499,46 +455,19 @@ class KubernetesOperatorBackend(Backend):
raise
await asyncio.sleep(0.5)
async def list_user_data(self) -> list[str]:
api_client = await self._ensure_client()
return await _list_user_data(client.CoreV1Api(api_client))
async def cleanup_user(self, user_id: str) -> int:
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
for attempt in range(61):
crs = await custom.list_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=settings.kubernetes_namespace,
plural=self._plural,
label_selector="app.kubernetes.io/managed-by=terminals",
)
matching = [
item for item in crs.get("items", [])
if item.get("metadata", {}).get("labels", {}).get("openwebui.com/user-id") == user_id
or item.get("spec", {}).get("userId") == user_id
]
if not matching:
break
if attempt == 60 or any(not item.get("metadata", {}).get("deletionTimestamp") for item in matching):
raise RuntimeError("Terminal resources still exist; user data has not been deleted. Remove them and retry.")
await asyncio.sleep(0.5)
return await _cleanup_user_pvcs(client.CoreV1Api(api_client), user_id)
async def reset(
self,
user_id: str,
policy_id: str,
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> None:
api_client = await self._ensure_client()
core = client.CoreV1Api(api_client)
ns = settings.kubernetes_namespace
s = spec or {}
s = dict(spec or {})
s.setdefault("storage", settings.kubernetes_storage_size)
context_id = normalize_context_id(context_id)
terminal_name = _sanitize_name(user_id, policy_id, context_id)
terminal_name = _sanitize_name(template_id, context_id)
reset_name = f"{terminal_name[:57]}-reset"
claim_name = f"{terminal_name}-pvc"
@@ -552,8 +481,8 @@ class KubernetesOperatorBackend(Backend):
labels = {
"app.kubernetes.io/managed-by": "terminals",
"app.kubernetes.io/part-of": "open-terminal",
"openwebui.com/user-id": user_id,
"openwebui.com/policy": _DNS_SAFE.sub("-", policy_id.lower()).strip("-")[:20],
"openwebui.com/instance": get_terminal_id(template_id, context_id),
"openwebui.com/template": template_label(template_id),
CONTEXT_TYPE_LABEL: (
DEFAULT_CONTEXT_ID
if context_id == DEFAULT_CONTEXT_ID
@@ -570,6 +499,7 @@ class KubernetesOperatorBackend(Backend):
(item for item in template.get("containers", []) if item.get("name") == "open-terminal"),
{},
)
reset_image = s.get("image", settings.effective_kubernetes_image)
pod = client.V1Pod(
metadata=client.V1ObjectMeta(name=reset_name, namespace=ns, labels=labels),
spec=client.V1PodSpec(
@@ -581,7 +511,8 @@ class KubernetesOperatorBackend(Backend):
containers=[
client.V1Container(
name="reset",
image=s.get("image", settings.effective_kubernetes_image),
image=reset_image,
image_pull_policy=pull_policy(reset_image),
security_context=deep_merge(
terminal_container.get("securityContext"), container_security_context(s)
) or None,
@@ -634,84 +565,9 @@ class KubernetesOperatorBackend(Backend):
except client.exceptions.ApiException:
pass
async def refresh(
self,
*,
user_id: str | None = None,
policy_id: str | None = None,
context_id: str | None = None,
only_idle: bool = True,
reset: bool = False,
) -> RefreshResult:
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
ns = settings.kubernetes_namespace
result = RefreshResult()
selector = "app.kubernetes.io/managed-by=terminals"
crs = await custom.list_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=ns,
plural=self._plural,
label_selector=selector,
)
for item in crs.get("items", []):
labels = item.get("metadata", {}).get("labels", {})
annotations = item.get("metadata", {}).get("annotations", {})
item_user = labels.get("openwebui.com/user-id") or item.get("spec", {}).get("userId")
item_policy = annotations.get(_POLICY_ID_ANNOTATION) or labels.get(
"openwebui.com/policy", "default"
)
item_context = normalize_context_id(
item.get("spec", {}).get("contextId")
or annotations.get(CONTEXT_ID_ANNOTATION)
)
if user_id and item_user != user_id:
continue
if policy_id and item_policy != policy_id:
continue
if context_id is not None and item_context != normalize_context_id(context_id):
continue
result.matched += 1
phase = (item.get("status") or {}).get("phase")
if only_idle and phase == "Running":
result.skipped_active += 1
continue
name = item["metadata"]["name"]
await custom.delete_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=ns,
plural=self._plural,
name=name,
)
key = self._key(item_user or "", item_policy, item_context)
self._instances.pop(key, None)
self._specs.pop(key, None)
self._activity.pop(key, None)
self._activity_wall.pop(key, None)
self._running_checked_at.pop(key, None)
self._activity_synced_at.pop(key, None)
self._last_activity_status_updated_at.pop(key, None)
result.refreshed += 1
if reset and item_user:
await self.reset(item_user, item_policy, item_context, item.get("spec") or {})
result.reset += 1
return result
# ------------------------------------------------------------------
# Backend interface
# ------------------------------------------------------------------
async def provision(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> Optional[dict]:
@@ -721,7 +577,7 @@ class KubernetesOperatorBackend(Backend):
"""
context_id = normalize_context_id(context_id)
cr = await self._create_terminal_cr(
user_id, policy_id=policy_id, context_id=context_id, spec=spec
template_id=template_id, context_id=context_id, spec=spec
)
name = cr["metadata"]["name"]
ns = settings.kubernetes_namespace
@@ -730,8 +586,7 @@ class KubernetesOperatorBackend(Backend):
if ready:
host, port = self._parse_service_url(ready["service_url"])
return {
"instance_id": cr["metadata"]["uid"],
"instance_name": name,
"workload_name": name,
"api_key": ready["api_key"],
"host": host,
"port": port,
@@ -739,69 +594,13 @@ class KubernetesOperatorBackend(Backend):
return None
async def start(self, instance_id: str) -> bool:
"""For idle terminals, delete and re-create the CR."""
name = await self._name_from_uid(instance_id)
if name is None:
return False
async def status(self, name: str) -> str:
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
ns = settings.kubernetes_namespace
try:
cr = await custom.get_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=ns,
plural=self._plural,
name=name,
)
except client.exceptions.ApiException:
return False
phase = cr.get("status", {}).get("phase")
if phase == "Running":
return True
if phase in ("Pending", "Provisioning"):
return True # still coming up
# Idle or Error means the caller should refresh this CR.
return False
async def teardown(self, instance_id: str) -> None:
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
ns = settings.kubernetes_namespace
name = await self._name_from_uid(instance_id)
if name is None:
log.warning("No Terminal CR found for UID %s", instance_id)
return
try:
await custom.delete_namespaced_custom_object(
group=self._group,
version=self._version,
namespace=ns,
plural=self._plural,
name=name,
)
log.info("Deleted Terminal CR %s", name)
except client.exceptions.ApiException:
log.warning(
"Could not delete Terminal CR %s (may already be gone)", name
)
async def status(self, instance_id: str) -> str:
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
ns = settings.kubernetes_namespace
name = await self._name_from_uid(instance_id)
if name is None:
return "missing"
try:
cr = await custom.get_namespaced_custom_object(
group=self._group,
@@ -818,7 +617,9 @@ class KubernetesOperatorBackend(Backend):
if phase == "Idle":
return "stopped"
return "stopped"
except client.exceptions.ApiException:
except client.exceptions.ApiException as exc:
if exc.status != 404:
raise
return "missing"
async def close(self) -> None:
@@ -830,22 +631,20 @@ class KubernetesOperatorBackend(Backend):
# Operator-aware ensure_terminal
# ------------------------------------------------------------------
async def ensure_terminal(
async def _ensure_terminal(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
) -> Optional[dict]:
"""Get or create a terminal, resolving from K8s CRDs.
Uses a per-key lock so concurrent requests for the same user+policy
don't race to create the same CR.
Called under the instance lock by ensure_terminal.
Returns a dict with ``api_key``, ``host``, ``port`` or ``None``.
"""
context_id = normalize_context_id(context_id)
key = self._key(user_id, policy_id, context_id)
key = self._key(template_id, context_id)
checked = self._running_checked_at.get(key)
if (
key in self._instances
@@ -853,121 +652,84 @@ class KubernetesOperatorBackend(Backend):
and checked is not None
and time.monotonic() - checked < settings.status_cache_ttl
):
self._record_activity(key)
return self._instances[key]
# Fast path: check if CR is already Running without taking the lock.
cr = await self._get_terminal_cr(user_id, policy_id, context_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"])
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,
}
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
self._record_activity(key)
return info
cr = await self._get_terminal_cr(template_id, context_id)
# Serialise provisioning per key.
if key not in self._locks:
self._locks[key] = asyncio.Lock()
if cr is None:
await self._apply_due_reset(template_id, context_id, spec)
info = await self.provision(
template_id=template_id, context_id=context_id, spec=spec
)
if info:
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
return info
async with self._locks[key]:
# Re-check after acquiring lock.
cr = await self._get_terminal_cr(user_id, policy_id, context_id)
status = cr.get("status") or {}
phase = status.get("phase")
if cr is None:
await self._apply_due_reset(user_id, policy_id, context_id, spec)
info = await self.provision(
user_id, policy_id=policy_id, context_id=context_id, spec=spec
)
if info:
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
self._record_activity(key)
return info
if phase in ("Idle", "Error"):
log.info(
"Terminal CR %s in phase %s, deleting before refresh",
cr["metadata"]["name"],
phase,
)
await self._delete_terminal_cr(template_id, context_id=context_id)
await self._apply_due_reset(template_id, context_id, spec)
info = await self.provision(
template_id=template_id, context_id=context_id, spec=spec
)
if info:
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
return info
status = cr.get("status") or {}
phase = status.get("phase")
if phase in ("Idle", "Error"):
log.info(
"Terminal CR %s in phase %s, deleting before refresh",
cr["metadata"]["name"],
phase,
)
await self._delete_terminal_cr(user_id, policy_id, context_id=context_id)
await self._apply_due_reset(user_id, policy_id, context_id, spec)
info = await self.provision(
user_id, policy_id=policy_id, context_id=context_id, spec=spec
)
if info:
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
self._record_activity(key)
return info
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"])
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,
}
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
self._record_activity(key)
return info
# 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)
if ready:
host, port = self._parse_service_url(ready["service_url"])
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"])
info = {
"instance_id": cr["metadata"]["uid"],
"instance_name": cr["metadata"]["name"],
"workload_name": cr["metadata"]["name"],
"started_at": parse_started_at(cr["metadata"].get("creationTimestamp")),
"api_key": ready["api_key"],
"api_key": api_key,
"host": host,
"port": port,
}
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
self._record_activity(key)
return info
return None
# 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)
if ready:
host, port = self._parse_service_url(ready["service_url"])
info = {
"workload_name": cr["metadata"]["name"],
"started_at": parse_started_at(cr["metadata"].get("creationTimestamp")),
"api_key": ready["api_key"],
"host": host,
"port": port,
}
self._instances[key] = info
self._specs[key] = spec or {}
self._running_checked_at[key] = time.monotonic()
return info
return None
async def get_terminal_info(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
) -> Optional[dict]:
"""Look up an existing terminal from the K8s CRD without creating one."""
cr = await self._get_terminal_cr(user_id, policy_id, context_id)
cr = await self._get_terminal_cr(template_id, context_id)
if cr is None:
return None
@@ -979,8 +741,7 @@ class KubernetesOperatorBackend(Backend):
if api_key:
host, port = self._parse_service_url(status["serviceUrl"])
return {
"instance_id": cr["metadata"]["uid"],
"instance_name": cr["metadata"]["name"],
"workload_name": cr["metadata"]["name"],
"started_at": parse_started_at(cr["metadata"].get("creationTimestamp")),
"api_key": api_key,
"host": host,
@@ -991,26 +752,24 @@ class KubernetesOperatorBackend(Backend):
async def touch_activity(
self,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
) -> None:
"""Update lastActivityAt on the Terminal CR to prevent idle culling."""
context_id = normalize_context_id(context_id)
key = self._key(user_id, policy_id, context_id)
key = self._key(template_id, context_id)
checked = self._last_activity_status_updated_at.get(key)
self._record_activity(key)
synced = self._activity_synced_at.get(key)
interval = max(1, min(settings.status_cache_ttl or 30, 60))
if synced is None or time.monotonic() - synced >= interval:
await mark_terminal_active(user_id, policy_id, context_id)
await mark_terminal_active(template_id, context_id)
self._activity_synced_at[key] = time.monotonic()
if checked is not None and time.monotonic() - checked < interval:
return
api_client = await self._ensure_client()
custom = client.CustomObjectsApi(api_client)
name = _sanitize_name(user_id, policy_id, context_id)
name = _sanitize_name(template_id, context_id)
ns = settings.kubernetes_namespace
from datetime import datetime, timezone
now = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -1029,5 +788,5 @@ class KubernetesOperatorBackend(Backend):
if e.status != 404:
log.warning("Failed to touch activity for %s: %s", name, e)
else:
self.invalidate_status(user_id, policy_id, context_id)
self.invalidate_status(template_id, context_id)
self._last_activity_status_updated_at.pop(key, None)
+4 -1
View File
@@ -110,7 +110,10 @@ def upgrade(revision: str):
from alembic import command
click.echo(f"Upgrading database to {revision}…")
command.upgrade(_alembic_cfg(), revision)
try:
command.upgrade(_alembic_cfg(), revision)
except RuntimeError as exc:
raise click.ClickException(str(exc)) from exc
click.echo("Done.")
+13 -3
View File
@@ -16,7 +16,6 @@ class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="TERMINALS_", env_file=".env")
api_key: str = ""
open_webui_url: str = "" # if set, validate JWTs against this Open WebUI instance
# Database
database_url: str = f"sqlite+aiosqlite:///{_DEFAULT_DATA_DIR}/terminals.db"
@@ -27,6 +26,18 @@ class Settings(BaseSettings):
# Docker settings
image: str = "ghcr.io/open-webui/open-terminal:latest"
# Always, IfNotPresent, or Never; empty pulls :latest (or untagged) images on every
# start and other tags only when missing. Applies to every backend.
image_pull_policy: str = ""
# Docker only: how long a pulled image is trusted before Always checks the registry again.
image_pull_interval_seconds: int = 3600
@field_validator("image_pull_policy")
@classmethod
def _validate_image_pull_policy(cls, value: str) -> str:
from terminals.utils.image_pull import normalize_policy
return normalize_policy(value)
docker_network: str = Field(
default="",
validation_alias=AliasChoices("TERMINALS_DOCKER_NETWORK", "TERMINALS_NETWORK"),
@@ -52,7 +63,6 @@ class Settings(BaseSettings):
log_level: str = "INFO" # DEBUG, INFO, WARNING, ERROR, CRITICAL
enable_ui: bool = True
status_cache_ttl: int = 30
token_cache_ttl: int = 60
ws_compression: bool = False
access_log: bool = False
replay_body_limit: int | None = None
@@ -99,7 +109,7 @@ class Settings(BaseSettings):
# 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)
# Template hard caps (cannot be exceeded by API)
max_cpu: str = "" # TERMINALS_MAX_CPU
max_memory: str = "" # TERMINALS_MAX_MEMORY
max_storage: str = "" # TERMINALS_MAX_STORAGE
+14
View File
@@ -36,6 +36,20 @@ def init_db():
migrations_dir = Path(__file__).resolve().parent.parent / "migrations"
alembic_cfg.set_main_option("script_location", str(migrations_dir))
from sqlalchemy import create_engine, inspect, text
from terminals.db.urls import sync_database_url
check_engine = create_engine(sync_database_url(settings.database_url))
try:
with check_engine.connect() as connection:
tables = inspect(connection).get_table_names()
if "alembic_version" in tables:
revision = connection.scalar(text("SELECT version_num FROM alembic_version"))
if revision != "004_templates":
raise RuntimeError("Pre-0.4 database detected. Follow the manual 0.4 migration in CHANGELOG.md using a new database and separate storage; keep this database unchanged.")
elif tables:
raise RuntimeError("Existing unversioned database requires explicit migration")
finally:
check_engine.dispose()
command.upgrade(alembic_cfg, "head")
+2
View File
@@ -3,6 +3,8 @@
def async_database_url(url: str) -> str:
"""Return a URL suitable for SQLAlchemy's async engine."""
if url.startswith("sqlite://"):
return "sqlite+aiosqlite://" + url.removeprefix("sqlite://")
if url.startswith("postgres://"):
return "postgresql+asyncpg://" + url.removeprefix("postgres://")
if url.startswith("postgresql://"):
+57 -530
View File
@@ -1,540 +1,67 @@
<script lang="ts">
import { onMount } from 'svelte';
type AdminStatus = {
status: boolean;
backend: string;
active_terminals: number;
policy_count: number;
};
type TerminalRow = {
user_id: string;
policy_id: string;
status: string;
instance_id: string;
instance_name: string;
last_active_at: string | null;
idle_timeout_minutes: number;
};
type PolicyRow = {
id: string;
data: Record<string, any>;
lifecycle?: Record<string, any>;
created_at?: string | null;
updated_at?: string | null;
};
type EditingPolicy = {
id: string;
existing: boolean;
data: Record<string, any>;
lifecycle: Record<string, any>;
};
let token = $state('');
let status = $state<AdminStatus | null>(null);
let terminals = $state<TerminalRow[]>([]);
let usersWithData = $state<string[]>([]);
let policies = $state<PolicyRow[]>([]);
let templates = $state<any[]>([]);
let environments = $state<any[]>([]);
let error = $state('');
let notice = $state('');
let loading = $state(false);
let cleaningUser = $state<string | null>(null);
let editingPolicy = $state<EditingPolicy | null>(null);
const envPlaceholder = '{"OPEN_TERMINAL_ALLOWED_DOMAINS":"github.com"}';
const podSecurityPlaceholder = '{"runAsNonRoot":true,"seccompProfile":{"type":"RuntimeDefault"}}';
const containerSecurityPlaceholder =
'{"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]},"runAsNonRoot":true}';
onMount(() => {
token = localStorage.getItem('terminals.adminToken') || '';
void loadAll();
});
function headers(json = false): HeadersInit {
return {
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(json ? { 'Content-Type': 'application/json' } : {})
};
let busy = $state(false);
let editing = $state<any>(null);
let configuration = $state('{}');
let lifecycle = $state('{}');
const input = 'w-full rounded-lg border border-gray-200 bg-transparent px-3 py-2 text-sm dark:border-gray-700';
const button = 'rounded-lg px-3 py-2 text-sm hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-50';
async function api(path: string, method = 'GET', body?: unknown) {
const response = await fetch(`/api/v1/terminals${path}`, {method, headers: {Authorization: `Bearer ${token}`, ...(body !== undefined ? {'Content-Type': 'application/json'} : {})}, ...(body !== undefined ? {body: JSON.stringify(body)} : {})});
const data = await response.json();
if (!response.ok) throw new Error(typeof data.detail === 'string' ? data.detail : 'Request failed');
return data;
}
async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
const res = await fetch(path, {
...init,
headers: {
...headers(Boolean(init.body)),
...(init.headers || {})
}
async function run(work: () => Promise<void>) {busy = true; error = ''; try {await work();} catch(e) {error = String(e);} finally {busy = false;}}
async function load() { [templates, environments] = await Promise.all([api('/templates'), api('')]); }
async function edit(template: any = null) {
await run(async () => {
editing = template ?? {id: crypto.randomUUID(), fresh: true, data: {name: '', scope: null}};
configuration = JSON.stringify(editing.data, null, 2);
lifecycle = JSON.stringify(template ? (await api(`/templates/${encodeURIComponent(template.id)}/lifecycle`)).data : {}, null, 2);
});
if (!res.ok) {
let message = `${res.status} ${res.statusText}`;
try {
const body = await res.json();
message = body.detail || body.error || message;
} catch {}
throw new Error(message);
}
return (await res.json()) as T;
}
async function loadAll() {
loading = true;
error = '';
try {
const [nextStatus, nextTerminals, nextPolicies, nextUsersWithData] = await Promise.all([
api<AdminStatus>('/api/v1/status'),
api<TerminalRow[]>('/api/v1/terminals'),
api<PolicyRow[]>('/api/v1/policies'),
api<string[]>('/api/v1/terminals/data')
]);
const policiesWithLifecycle = await Promise.all(
nextPolicies.map(async (policy) => {
const lifecycle = await api<{ data?: Record<string, any> }>(
`/api/v1/policies/${encodeURIComponent(policy.id)}/lifecycle`
);
return { ...policy, lifecycle: lifecycle.data || {} };
})
);
status = nextStatus;
terminals = nextTerminals;
usersWithData = nextUsersWithData;
policies = policiesWithLifecycle;
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to load';
} finally {
loading = false;
}
}
function saveToken(value: string) {
token = value;
localStorage.setItem('terminals.adminToken', value);
}
function lastActive(value: string | null) {
if (!value) return 'never';
const seconds = Math.max(0, Math.floor((Date.now() - new Date(value).getTime()) / 1000));
if (seconds < 60) return `${seconds}s ago`;
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return new Date(value).toLocaleDateString();
}
function policyValue(policy: PolicyRow, key: string, fallback = '-') {
return policy.data?.[key] ?? fallback;
}
function resetSchedule(policy: PolicyRow) {
return policy.lifecycle?.reset?.schedule ?? '-';
}
function restrictedLabel(policy: PolicyRow) {
return policy.data?.restricted ? 'restricted' : 'standard';
}
function statusClass(value: string) {
if (value === 'running') return 'bg-emerald-600';
if (value === 'stopped' || value === 'missing') return 'bg-gray-400';
return 'bg-amber-500';
}
async function stopTerminal(row: TerminalRow) {
error = '';
notice = '';
try {
await api('/api/v1/terminals/stop', {
method: 'POST',
body: JSON.stringify({ user_id: row.user_id, policy_id: row.policy_id })
});
await loadAll();
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to stop terminal';
}
}
async function cleanupUser(userId: string) {
if (cleaningUser !== null) return;
if (!confirm(`Stop all terminals and permanently delete all terminal files for user "${userId}", across all policies and contexts? This cannot be undone.`)) return;
error = '';
notice = '';
cleaningUser = userId;
try {
await api('/api/v1/terminals/refresh', {
method: 'POST',
body: JSON.stringify({ user_id: userId, only_idle: false })
});
const result = await api<{ deleted: number }>('/api/v1/terminals/cleanup', {
method: 'POST',
body: JSON.stringify({ user_id: userId })
});
notice = result.deleted
? (status?.backend === 'docker'
? `Terminal files deleted for user "${userId}".`
: `Terminal file deletion requested for user "${userId}". Storage removal may still be pending.`)
: `No terminal files found for user "${userId}". Lifecycle records cleared.`;
await loadAll();
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to delete user data';
} finally {
cleaningUser = null;
}
}
async function rolloutPolicy(policy: PolicyRow) {
error = '';
notice = '';
try {
const result = await api<{ refreshed: number; skipped_active: number }>('/api/v1/terminals/refresh', {
method: 'POST',
body: JSON.stringify({ policy_id: policy.id, only_idle: true })
});
notice = `Rolled out to ${result.refreshed} idle terminal${result.refreshed === 1 ? '' : 's'}${result.skipped_active ? `; ${result.skipped_active} active skipped` : ''}.`;
await loadAll();
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to roll out policy';
}
}
function openPolicy(policy: PolicyRow | null = null) {
notice = '';
editingPolicy = policy
? {
id: policy.id,
existing: true,
data: { ...(policy.data || {}) },
lifecycle: { ...(policy.lifecycle || {}) }
}
: { id: '', existing: false, data: {}, lifecycle: {} };
}
async function deletePolicy(policy: PolicyRow) {
if (!confirm(`Delete policy "${policy.id}"?`)) return;
error = '';
notice = '';
try {
await api(`/api/v1/policies/${encodeURIComponent(policy.id)}`, { method: 'DELETE' });
await loadAll();
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to delete policy';
}
}
function readPolicyForm(form: HTMLFormElement) {
const data = new FormData(form);
const id = String(data.get('id') || '').trim();
const body: Record<string, any> = {};
for (const key of ['image', 'cpu_limit', 'memory_limit', 'storage', 'storage_mode', 'network_profile']) {
const value = String(data.get(key) || '').trim();
if (value) body[key] = value;
}
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);
const podSecurityContext = String(data.get('pod_security_context') || '').trim();
if (podSecurityContext) body.pod_security_context = JSON.parse(podSecurityContext);
const containerSecurityContext = String(data.get('container_security_context') || '').trim();
if (containerSecurityContext) {
body.container_security_context = JSON.parse(containerSecurityContext);
}
return { id, body };
}
function readLifecycleForm(form: HTMLFormElement) {
const data = new FormData(form);
const schedule = String(data.get('reset_schedule') || '').trim();
const timezone = String(data.get('reset_timezone') || '').trim();
if (!schedule) return {};
return {
reset: {
schedule,
...(timezone ? { timezone } : {})
}
};
}
async function savePolicy(event: SubmitEvent) {
async function save(event: SubmitEvent) {
event.preventDefault();
error = '';
notice = '';
try {
const { id, body } = readPolicyForm(event.currentTarget as HTMLFormElement);
const lifecycle = readLifecycleForm(event.currentTarget as HTMLFormElement);
if (!id) throw new Error('Policy ID is required');
await api(`/api/v1/policies/${encodeURIComponent(id)}`, {
method: 'PUT',
body: JSON.stringify(body)
});
await api(`/api/v1/policies/${encodeURIComponent(id)}/lifecycle`, {
method: 'PUT',
body: JSON.stringify(lifecycle)
});
editingPolicy = null;
await loadAll();
} catch (err) {
error = err instanceof Error ? err.message : 'Failed to save policy';
}
await run(async () => {
const form = new FormData(event.currentTarget as HTMLFormElement);
const data = {...JSON.parse(configuration), name: form.get('name'), scope: form.get('scope') || null};
const schedule = JSON.parse(lifecycle);
if (editing.fresh) {await api('/templates', 'POST', {id: editing.id, data}); editing.fresh = false;}
else await api(`/templates/${encodeURIComponent(editing.id)}`, 'PATCH', data);
await api(`/templates/${encodeURIComponent(editing.id)}/lifecycle`, 'PUT', schedule);
editing = null; await load();
});
}
function context(row: any) {const [scope, ...parts] = row.context_id.split(':'); return {user_id: 'admin', ...(scope === 'user' ? {user_id: parts.join(':')} : scope === 'chat' ? {chat_id: parts.join(':')} : scope === 'model' ? {model_id: parts.join(':')} : {})};}
async function action(row: any, action: string) {
if (!confirm(action === 'restart' ? 'Stop running work and retain files?' : 'Remove files and running work for everyone using this environment?')) return;
await run(async () => {await api(`/templates/${encodeURIComponent(row.template_id)}/${action === 'delete' ? 'instance' : action}`, action === 'delete' ? 'DELETE' : 'POST', context(row)); await load();});
}
async function remove(template: any) {
const count = environments.filter(row => row.template_id === template.id).length;
if (!confirm(`Delete ${template.data.name ?? template.id} and ${count} environments, including their files?`)) return;
await run(async () => {await api(`/templates/${encodeURIComponent(template.id)}`, 'DELETE'); await load();});
}
onMount(() => {token = sessionStorage.getItem('terminals-key') ?? ''; if (token) void run(load);});
</script>
<svelte:head>
<title>Terminals</title>
</svelte:head>
<div class="app-theme min-h-dvh bg-white font-sans antialiased text-gray-700">
<div class="grid min-h-dvh grid-cols-1 md:grid-cols-[16.5rem_minmax(0,1fr)]">
<aside class="hidden border-r border-gray-200/50 bg-gray-50/50 px-1.5 py-1.5 md:block">
<div class="mb-1 flex h-7 items-center gap-1.5 px-2 text-xs font-medium text-gray-900">
<span class="flex h-3.5 w-3.5 items-center justify-center rounded-[3px] bg-gray-900 text-[8px] text-white">▣</span>
<span>Terminals</span>
</div>
<nav class="space-y-px text-xs">
<a class="block h-7 rounded-md bg-gray-200/70 px-2 leading-7 font-medium text-gray-900" href="#terminals">Terminals</a>
<a class="block h-7 rounded-md px-2 leading-7 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700" href="#user-data">User data</a>
<a class="block h-7 rounded-md px-2 leading-7 text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700" href="#policies">Policies</a>
</nav>
</aside>
<main class="min-w-0">
<div class="flex h-8 items-center px-3">
<h1 class="px-0.5 text-xs font-medium text-gray-700">Terminals</h1>
<div class="ml-4 flex items-center gap-3 text-[11px] text-gray-500">
<span>{status?.backend ?? '-'}</span>
<span>{status?.active_terminals ?? terminals.length} active</span>
<span>{status?.policy_count ?? policies.length} policies</span>
</div>
<div class="ml-auto flex min-w-0 items-center gap-1.5">
<input
class="h-6 w-40 min-w-0 border-0 bg-transparent px-1.5 text-xs text-gray-700 outline-none placeholder:text-gray-400 focus:bg-gray-100 sm:w-52"
type="password"
placeholder="Admin key"
value={token}
oninput={(event) => saveToken(event.currentTarget.value)}
/>
<button
class="flex h-6 w-6 shrink-0 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700"
type="button"
aria-label="Refresh"
title="Refresh"
onclick={() => loadAll()}
disabled={loading}
>
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M21 12a9 9 0 0 1-15 6.7" />
<path d="M3 12a9 9 0 0 1 15-6.7" />
<path d="M3 19v-5h5" />
<path d="M21 5v5h-5" />
</svg>
</button>
</div>
</div>
<section id="terminals" class="pt-1">
<div class="flex h-6 items-center justify-between px-3">
<h2 class="text-xs text-gray-500">Active terminals</h2>
</div>
{#if terminals.length === 0}
<div class="px-3 py-2 text-xs text-gray-400">No active terminals.</div>
{:else}
<div class="overflow-x-auto">
<table class="w-full table-fixed border-collapse text-xs">
<thead class="text-left text-[11px] font-normal text-gray-500">
<tr>
<th class="h-6 w-[30%] px-3 font-normal">User</th>
<th class="h-6 w-[30%] px-3 font-normal">Policy</th>
<th class="h-6 px-2 font-normal">Status</th>
<th class="hidden h-6 px-2 font-normal sm:table-cell">Last active</th>
<th class="hidden h-6 px-2 font-normal lg:table-cell">Instance</th>
<th class="h-6 w-8 px-1"></th>
</tr>
</thead>
<tbody>
{#each terminals as terminal}
<tr class="text-gray-700 hover:bg-gray-50">
<td class="h-6 truncate px-3">{terminal.user_id}</td>
<td class="h-6 truncate px-2">
{policies.some((policy) => policy.id === terminal.policy_id)
? terminal.policy_id
: 'Service defaults'}
</td>
<td class="h-6 truncate px-2">
<span class="inline-flex items-center gap-2">
<span class={`h-1.5 w-1.5 rounded-full ${statusClass(terminal.status)}`}></span>
{terminal.status}
</span>
</td>
<td class="hidden h-6 truncate px-2 sm:table-cell">{lastActive(terminal.last_active_at)}</td>
<td class="hidden h-6 truncate px-2 lg:table-cell">{terminal.instance_name || terminal.instance_id}</td>
<td class="h-6 px-1 text-right">
<button
class="inline-flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700"
type="button"
aria-label="Stop"
title="Stop"
onclick={() => stopTerminal(terminal)}
>
<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor" aria-hidden="true"><rect x="7" y="7" width="10" height="10" rx="1.5" /></svg>
</button>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
</section>
<section id="user-data" class="mt-3">
<h2 class="flex h-6 items-center px-3 text-xs text-gray-500">User data</h2>
<p class="px-3 pb-1 text-[11px] text-gray-500">Persisted terminal files, including users with no active terminals.</p>
{#if status && status.backend !== 'docker'}
<p class="px-3 pb-1 text-[11px] text-gray-500">Shared storage requires separate cleanup and is not listed here.</p>
{/if}
{#if usersWithData.length === 0}
<div class="px-3 py-2 text-xs text-gray-400">No user data found.</div>
{:else}
<table class="w-full table-fixed border-collapse text-xs">
<thead class="text-left text-[11px] font-normal text-gray-500">
<tr><th class="h-6 px-3 font-normal">User</th><th class="h-6 w-36 px-3 font-normal text-right">Action</th></tr>
</thead>
<tbody>
{#each usersWithData as userId}
<tr class="text-gray-700 hover:bg-gray-50">
<td class="h-6 truncate px-3" title={userId}>{userId}</td>
<td class="h-6 px-3 text-right">
<button class="rounded-md px-2 py-1 text-[11px] text-gray-500 hover:bg-gray-100 hover:text-gray-700 disabled:opacity-50" type="button" disabled={cleaningUser !== null} onclick={() => cleanupUser(userId)}>
{cleaningUser === userId ? 'Deleting…' : 'Delete user data'}
</button>
</td>
</tr>
{/each}
</tbody>
</table>
{/if}
</section>
<section id="policies" class="mt-3">
<div class="flex h-6 items-center justify-between px-3">
<h2 class="text-xs text-gray-500">Policies</h2>
<button
class="flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700"
type="button"
aria-label="Add policy"
title="Add policy"
onclick={() => openPolicy()}
>
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 5v14M5 12h14" /></svg>
</button>
</div>
{#if policies.length === 0}
<div class="px-3 py-2 text-xs text-gray-400">No policies configured.</div>
{:else}
<div class="overflow-x-auto">
<table class="w-full table-fixed border-collapse text-xs">
<thead class="text-left text-[11px] font-normal text-gray-500">
<tr>
<th class="h-6 w-[30%] px-3 font-normal md:w-[20%]">ID</th>
<th class="hidden h-6 px-2 font-normal md:table-cell md:w-[35%]">Image</th>
<th class="h-6 px-2 font-normal">CPU</th>
<th class="h-6 px-2 font-normal">Memory</th>
<th class="hidden h-6 px-2 font-normal sm:table-cell">Idle</th>
<th class="h-6 px-2 font-normal">Mode</th>
<th class="hidden h-6 px-2 font-normal lg:table-cell">Reset</th>
<th class="h-6 w-24 px-2"></th>
</tr>
</thead>
<tbody>
{#each policies as policy}
<tr class="text-gray-700 hover:bg-gray-50">
<td class="h-6 truncate px-3">{policy.id}</td>
<td class="hidden h-6 truncate px-2 md:table-cell">{policyValue(policy, 'image', 'default')}</td>
<td class="h-6 truncate px-2">{policyValue(policy, 'cpu_limit')}</td>
<td class="h-6 truncate px-2">{policyValue(policy, 'memory_limit')}</td>
<td class="hidden h-6 truncate px-2 sm:table-cell">{policyValue(policy, 'idle_timeout_minutes')}</td>
<td class="h-6 truncate px-2">{restrictedLabel(policy)}</td>
<td class="hidden h-6 truncate px-2 lg:table-cell">{resetSchedule(policy)}</td>
<td class="h-6 px-2 text-right">
<div class="inline-flex items-center gap-0.5 whitespace-nowrap">
<button class="inline-flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700" type="button" aria-label="Roll out to idle terminals" title="Roll out to idle terminals" onclick={() => rolloutPolicy(policy)}>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12a8 8 0 1 0 2.34-5.66L4 8.67" /><path d="M4 4v4.67h4.67" /></svg>
</button>
<button class="inline-flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700" type="button" aria-label="Edit" title="Edit" onclick={() => openPolicy(policy)}>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 20h9" /><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4Z" /></svg>
</button>
<button class="inline-flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700" type="button" aria-label="Delete" title="Delete" onclick={() => deletePolicy(policy)}>
<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 6h18" /><path d="M8 6V4h8v2" /><path d="M19 6l-1 14H6L5 6" /></svg>
</button>
</div>
</td>
</tr>
{/each}
</tbody>
</table>
</div>
{/if}
</section>
{#if notice}
<div class="px-3 py-2 text-[11px] text-emerald-700">{notice}</div>
{/if}
{#if error}
<div class="px-3 py-2 text-[11px] text-red-700">{error}</div>
{/if}
</main>
</div>
</div>
{#if editingPolicy}
<div class="fixed inset-0 z-20 flex items-center justify-center bg-black/50 p-4">
<div class="app-theme max-h-[calc(100vh-2rem)] w-full max-w-xl overflow-auto rounded-3xl border border-gray-200/50 bg-white px-5 py-4 shadow-2xl dark:border-white/4 dark:bg-gray-950">
<div class="mb-3 flex items-center justify-between">
<h2 class="text-sm font-medium text-gray-900 dark:text-white">{editingPolicy.existing ? 'Edit policy' : 'Add policy'}</h2>
<button class="flex h-6 w-6 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-600 dark:hover:bg-white/6 dark:hover:text-gray-300" type="button" aria-label="Close" onclick={() => (editingPolicy = null)}>
<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M18 6 6 18M6 6l12 12" /></svg>
</button>
</div>
<form onsubmit={savePolicy}>
<div class="mb-2 border-b border-gray-200/50 pb-1 text-xs text-gray-400 dark:border-white/4 dark:text-gray-600">Policy</div>
<div class="grid grid-cols-1 gap-x-3 gap-y-2 sm:grid-cols-2">
<label class="block text-xs text-gray-600 dark:text-gray-400">ID<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="id" value={editingPolicy.id} readonly={editingPolicy.existing} /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">Image<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="image" value={editingPolicy.data.image || ''} placeholder="ghcr.io/open-webui/open-terminal:latest" /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">CPU<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="cpu_limit" value={editingPolicy.data.cpu_limit || ''} placeholder="1" /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">Network profile<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="network_profile" value={editingPolicy.data.network_profile || ''} placeholder="Deployment default" /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">Memory<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="memory_limit" value={editingPolicy.data.memory_limit || ''} placeholder="1Gi" /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">Storage<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="storage" value={editingPolicy.data.storage || ''} placeholder="5Gi" /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400">Storage mode<select 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="storage_mode" value={editingPolicy.data.storage_mode || ''}>
<option value="">default</option>
<option value="per-user">per-user</option>
<option value="shared">shared</option>
<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>
<label class="block text-xs text-gray-600 dark:text-gray-400 sm:col-span-2">Container 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="container_security_context" placeholder={containerSecurityPlaceholder}>{editingPolicy.data.container_security_context ? JSON.stringify(editingPolicy.data.container_security_context, null, 2) : ''}</textarea></label>
</div>
<div class="mb-2 mt-3 border-b border-gray-200/50 pb-1 text-xs text-gray-400 dark:border-white/4 dark:text-gray-600">Lifecycle</div>
<div class="grid grid-cols-1 gap-x-3 gap-y-2 sm:grid-cols-2">
<label class="block text-xs text-gray-600 dark:text-gray-400">Reset timezone<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="reset_timezone" value={editingPolicy.lifecycle.reset?.timezone || ''} placeholder="UTC" /></label>
<label class="block text-xs text-gray-600 dark:text-gray-400 sm:col-span-2">Scheduled reset<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="reset_schedule" value={editingPolicy.lifecycle.reset?.schedule || ''} placeholder="@weekly, @monthly, cron, or ISO date" /></label>
</div>
<div class="sticky bottom-0 -mx-5 mt-3 flex justify-end gap-2 border-t border-gray-200/50 bg-white px-5 py-2 dark:border-white/4 dark:bg-gray-950">
<button class="text-xs text-gray-400 transition-colors hover:text-gray-700 dark:hover:text-gray-300" type="button" onclick={() => (editingPolicy = null)}>Cancel</button>
<button class="text-xs text-gray-600 transition-colors hover:text-gray-900 dark:text-gray-400 dark:hover:text-white" type="submit">Save</button>
</div>
</form>
</div>
</div>
{/if}
<svelte:head><title>Terminals</title></svelte:head>
<main class="mx-auto max-w-5xl space-y-6 p-6 text-gray-900 dark:text-gray-100">
<header class="flex items-center justify-between"><h1 class="text-xl font-semibold">Terminals <span class="text-sm font-normal text-gray-500">0.4.0</span></h1><button class={button} disabled={busy} onclick={() => edit()}>New terminal</button></header>
<form class="flex gap-2" onsubmit={(event) => {event.preventDefault(); sessionStorage.setItem('terminals-key', token); void run(load);}}><input class={input} type="password" bind:value={token} placeholder="Server key" aria-label="Server key" /><button class={button} disabled={busy}>Connect</button></form>
{#if error}<p role="alert" class="text-sm text-red-500">{error}</p>{/if}
{#if editing}<form class="space-y-3 rounded-xl border border-gray-200 p-4 dark:border-gray-800" onsubmit={save}>
<h2 class="font-medium">{editing.fresh ? 'New terminal' : 'Configure terminal'}</h2>
<label class="block text-sm">Name<input class={input} name="name" value={editing.data.name ?? editing.id} required /></label>
<label class="block text-sm">Scope<select class={input} name="scope" value={editing.data.scope ?? ''}><option value="">None</option><option value="user">User</option><option value="chat">Chat</option><option value="model">Model</option></select></label>
<label class="block text-sm">Instance configuration<textarea class={`${input} font-mono`} rows="8" bind:value={configuration} /></label>
<label class="block text-sm">Lifecycle schedule<textarea class={`${input} font-mono`} rows="4" bind:value={lifecycle} /></label>
<div class="flex justify-end"><button type="button" class={button} onclick={() => editing = null}>Cancel</button><button class={button} disabled={busy}>Save</button></div>
</form>{/if}
<section><h2 class="mb-3 font-medium">Templates</h2><div class="space-y-2">{#each templates as template (template.id)}<div class="flex items-center justify-between rounded-xl border border-gray-200 p-3 dark:border-gray-800"><div><p class="text-sm">{template.data.name ?? template.id}</p><p class="text-xs text-gray-500">{template.data.scope ?? 'None'} · {template.data.image ?? 'Server default'}</p></div><div><button class={button} disabled={busy} onclick={() => edit(template)}>Configure</button><button class={button} disabled={busy} onclick={() => remove(template)}>Delete terminal</button></div></div>{:else}<p class="text-sm text-gray-500">No templates yet.</p>{/each}</div></section>
<section><h2 class="mb-3 font-medium">Environments</h2><div class="space-y-2">{#each environments as row (row.id)}<div class="flex flex-wrap items-center justify-between gap-2 rounded-xl border border-gray-200 p-3 dark:border-gray-800"><div><p class="text-sm">{templates.find(t => t.id === row.template_id)?.data.name ?? row.template_id}</p><p class="text-xs text-gray-500">{row.context_id} · {row.status}</p></div><div><button class={button} disabled={busy} onclick={() => action(row, 'restart')}>Restart</button><button class={button} disabled={busy} onclick={() => action(row, 'reset')}>Reset</button><button class={button} disabled={busy} onclick={() => action(row, 'delete')}>Delete environment</button></div></div>{:else}<p class="text-sm text-gray-500">No environments created.</p>{/each}</div></section>
</main>
+4 -8
View File
@@ -13,9 +13,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.lifecycle import router as lifecycle_router
from terminals.routers.policy import router as policy_router
from terminals.routers.terminals import router as terminals_router
from terminals.routers.proxy import close_proxy_client, router as proxy_router
@@ -40,7 +38,6 @@ 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()
@@ -48,7 +45,7 @@ async def lifespan(app: FastAPI):
app = FastAPI(
title="Terminals",
description="Multi-tenant terminal orchestrator for Open Terminal.",
version="0.3.3",
version="0.4.0",
lifespan=lifespan,
openapi_url=None, # Disable built-in OpenAPI; proxy router serves the terminal spec
)
@@ -67,9 +64,8 @@ async def health():
return {"status": True}
# Policy CRUD must be before the catch-all proxy.
app.include_router(policy_router)
app.include_router(lifecycle_router)
# Template CRUD must be before the catch-all proxy.
app.include_router(terminals_router)
FRONTEND_BUILD_DIR = Path(__file__).parent / "frontend" / "build"
if FRONTEND_BUILD_DIR.exists():
+11 -2
View File
@@ -15,7 +15,7 @@ from terminals.db.urls import sync_database_url
# Import *all* models so Base.metadata is fully populated.
from terminals.models.base import Base # noqa: F401
from terminals.models.policy import Policy, PolicyLifecycle, PolicyLifecycleState # noqa: F401
from terminals.models.template import Template, TemplateLifecycle, TemplateLifecycleState # noqa: F401
# Alembic Config object — gives access to alembic.ini values.
config = context.config
@@ -73,13 +73,22 @@ def run_migrations_online() -> None:
(via ``asyncio.to_thread``), so we use a plain sync engine here to
avoid nested-event-loop issues with aiosqlite/asyncpg.
"""
from sqlalchemy import create_engine
from sqlalchemy import create_engine, event
url = _sync_url(_get_url())
_ensure_sqlite_dir(url)
connectable = create_engine(url, poolclass=pool.NullPool)
if connectable.dialect.name == "sqlite":
@event.listens_for(connectable, "connect")
def explicit_transactions(dbapi_connection, _):
dbapi_connection.isolation_level = None
@event.listens_for(connectable, "begin")
def begin(connection):
connection.exec_driver_sql("BEGIN IMMEDIATE")
with connectable.connect() as connection:
do_run_migrations(connection)
@@ -0,0 +1,53 @@
"""Templates and deterministic lifecycle identities."""
from alembic import op
import sqlalchemy as sa
revision = "004_templates"
down_revision = "003_lifecycle_context"
branch_labels = None
depends_on = None
def upgrade():
connection = op.get_bind()
metadata = sa.MetaData()
policies = sa.Table("policies", metadata, autoload_with=connection)
old_states = sa.Table("policy_lifecycle_states", metadata, autoload_with=connection)
lifecycle = sa.Table("policy_lifecycles", metadata, autoload_with=connection)
populated = any(connection.execute(sa.select(table.c.id).limit(1)).first()
for table in (policies, old_states, lifecycle))
if populated:
raise RuntimeError(
"Populated pre-0.4 databases cannot be upgraded in place. "
"Keep this database and follow the manual 0.4 migration in CHANGELOG.md "
"using a new database and separate storage."
)
op.rename_table("policies", "templates")
op.rename_table("policy_lifecycles", "template_lifecycles")
with op.batch_alter_table("template_lifecycles") as batch:
batch.alter_column("policy_id", new_column_name="template_id", existing_type=sa.String())
batch.drop_constraint("uq_policy_lifecycles_policy", type_="unique")
batch.drop_index("ix_policy_lifecycles_policy_id")
with op.batch_alter_table("template_lifecycles") as batch:
batch.create_unique_constraint("uq_template_lifecycles_template", ["template_id"])
op.create_index("ix_template_lifecycles_template_id", "template_lifecycles", ["template_id"])
op.rename_table("policy_lifecycle_states", "legacy_lifecycle_states")
op.create_table(
"template_lifecycle_states",
sa.Column("id", sa.String(), primary_key=True),
sa.Column("template_id", sa.String(), sa.ForeignKey("templates.id"), nullable=False),
sa.Column("context_id", sa.String(), nullable=False),
sa.Column("data", sa.JSON(), nullable=False),
sa.Column("created_at", sa.DateTime(), server_default=sa.func.now()),
sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now()),
sa.UniqueConstraint("template_id", "context_id", name="uq_template_lifecycle_context"),
)
op.create_index("ix_template_lifecycle_states_template_id", "template_lifecycle_states", ["template_id"])
op.create_index("ix_template_lifecycle_states_context_id", "template_lifecycle_states", ["context_id"])
op.drop_table("legacy_lifecycle_states")
def downgrade():
raise RuntimeError("Restore the pre-0.4 database and storage backups to roll back this data migration")
@@ -1,13 +1,13 @@
"""Policy database model."""
"""Template database model."""
from sqlalchemy import Column, DateTime, String, UniqueConstraint, func
from sqlalchemy import Column, DateTime, String, ForeignKey, UniqueConstraint, func
from sqlalchemy.types import JSON
from terminals.models.base import Base
class Policy(Base):
__tablename__ = "policies"
class Template(Base):
__tablename__ = "templates"
id = Column(String, primary_key=True)
data = Column(JSON, nullable=False, default=dict)
@@ -15,39 +15,37 @@ class Policy(Base):
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
def __repr__(self) -> str:
return f"<Policy id={self.id!r}>"
return f"<Template id={self.id!r}>"
class PolicyLifecycle(Base):
__tablename__ = "policy_lifecycles"
class TemplateLifecycle(Base):
__tablename__ = "template_lifecycles"
__table_args__ = (
UniqueConstraint("policy_id", name="uq_policy_lifecycles_policy"),
UniqueConstraint("template_id", name="uq_template_lifecycles_template"),
)
id = Column(String, primary_key=True)
policy_id = Column(String, nullable=False, index=True)
template_id = Column(String, ForeignKey("templates.id"), nullable=False, index=True)
data = Column(JSON, nullable=False, default=dict)
created_at = Column(DateTime, server_default=func.now())
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
def __repr__(self) -> str:
return f"<PolicyLifecycle policy_id={self.policy_id!r}>"
return f"<TemplateLifecycle template_id={self.template_id!r}>"
class PolicyLifecycleState(Base):
__tablename__ = "policy_lifecycle_states"
class TemplateLifecycleState(Base):
__tablename__ = "template_lifecycle_states"
__table_args__ = (
UniqueConstraint(
"user_id",
"policy_id",
"template_id",
"context_id",
name="uq_policy_lifecycle_states_user_policy_context",
name="uq_template_lifecycle_context",
),
)
id = Column(String, primary_key=True)
user_id = Column(String, nullable=False, index=True)
policy_id = Column(String, nullable=False, index=True)
template_id = Column(String, ForeignKey("templates.id"), nullable=False, index=True)
context_id = Column(String, nullable=False, default="default", index=True)
data = Column(JSON, nullable=False, default=dict)
created_at = Column(DateTime, server_default=func.now())
@@ -55,6 +53,6 @@ class PolicyLifecycleState(Base):
def __repr__(self) -> str:
return (
f"<PolicyLifecycleState user_id={self.user_id!r} "
f"policy_id={self.policy_id!r} context_id={self.context_id!r}>"
f"<TemplateLifecycleState "
f"template_id={self.template_id!r} context_id={self.context_id!r}>"
)
+22 -132
View File
@@ -1,116 +1,18 @@
"""Authentication dependencies for the proxy and API routes."""
import hashlib
import time
import hmac
from typing import Optional
import httpx
from fastapi import Depends, Header, HTTPException
from fastapi import Header, HTTPException, Request
from terminals.config import settings
_owui_client: Optional[httpx.AsyncClient] = None
_token_cache: dict[str, tuple[float, str]] = {}
async def _get_owui_client() -> httpx.AsyncClient:
global _owui_client
if _owui_client is None:
_owui_client = httpx.AsyncClient(timeout=10.0)
return _owui_client
async def close_auth_client() -> None:
global _owui_client
_token_cache.clear()
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.
Returns the verified user ID on success.
Raises ``HTTPException`` on failure.
Only call when ``settings.open_webui_url`` is set.
"""
ttl = settings.token_cache_ttl
key = hashlib.sha256(token.encode()).hexdigest() if ttl > 0 else ""
if key:
cached = _token_cache.get(key)
if cached and cached[0] > time.monotonic():
return cached[1]
client = await _get_owui_client()
url = settings.open_webui_url.rstrip("/")
try:
resp = await client.get(
f"{url}/api/v1/auths/",
headers={"Authorization": f"Bearer {token}"},
)
if resp.status_code != 200:
raise HTTPException(status_code=401, detail="Invalid token")
except httpx.HTTPError:
raise HTTPException(status_code=502, detail="Failed to reach Open WebUI")
data = resp.json()
verified_user_id = data.get("id")
if not verified_user_id:
raise HTTPException(status_code=401, detail="Token response missing user ID")
if key:
if len(_token_cache) >= 10000:
_token_cache.clear()
_token_cache[key] = (time.monotonic() + ttl, verified_user_id)
return verified_user_id
async def verify_api_key(
authorization: Optional[str] = Header(None),
) -> Optional[str]:
"""Validate the caller's token.
Supports three modes:
1. Open WebUI - validates the JWT against the configured Open WebUI instance
2. API Key - checks against TERMINALS_API_KEY
3. Open - no auth when neither is configured
Returns the verified user ID when using Open WebUI JWT validation,
or ``None`` for API-key / open modes (where ``X-User-Id`` is trusted).
"""
# Mode 1: Open WebUI JWT validation
if settings.open_webui_url:
if not authorization:
raise HTTPException(status_code=401, detail="Missing Authorization header")
scheme, _, token = authorization.partition(" ")
if scheme.lower() != "bearer" or not token:
raise HTTPException(status_code=401, detail="Invalid Authorization header")
return await validate_token(token)
# Mode 2: Static API key
if settings.api_key:
if not authorization:
raise HTTPException(status_code=401, detail="Missing Authorization header")
scheme, _, token = authorization.partition(" ")
if scheme.lower() != "bearer" or token != settings.api_key:
raise HTTPException(status_code=401, detail="Invalid API key")
return None
# Mode 3: Open access (no key configured)
return None
async def verify_admin_api_key(
authorization: Optional[str] = Header(None),
x_user_id: Optional[str] = Header(None, alias="X-User-Id"),
) -> None:
"""Validate admin control-plane access.
User JWTs are intentionally not sufficient for policy or lifecycle
administration. When Open WebUI auth is enabled, callers must still use
the Terminals admin API key.
"""
"""Validate server-key access to template and lifecycle administration."""
# Trusted proxies set X-User-Id themselves when delegating user requests
# with the shared key. Those requests must not inherit admin privileges.
if x_user_id is not None:
@@ -124,40 +26,28 @@ async def verify_admin_api_key(
raise HTTPException(status_code=401, detail="Invalid admin API key")
return None
if settings.open_webui_url:
raise HTTPException(
status_code=401,
detail="TERMINALS_API_KEY is required for admin APIs",
)
# Open access remains available for local development when no auth mode is
# configured, matching the existing API-key behavior.
# Open access remains available for local administration without a key.
return None
async def verify_spec_access(
authorization: Optional[str] = Header(None),
) -> Optional[str]:
"""Allow the admin API key for tool discovery before a user is involved."""
def require_server_key(token: str) -> None:
if not settings.api_key:
raise HTTPException(503, "TERMINALS_API_KEY is required for managed terminals")
if not isinstance(token, str) or not hmac.compare_digest(token, settings.api_key):
raise HTTPException(401, "Invalid server key")
async def verify_proxy_credentials(authorization, user_id):
scheme, _, token = (authorization or "").partition(" ")
if settings.api_key and scheme.lower() == "bearer" and token == settings.api_key:
return None
return await verify_api_key(authorization)
require_server_key(token if scheme.lower() == "bearer" else "")
if not user_id:
raise HTTPException(400, "Missing X-User-Id")
from terminals.utils.context import validate_identifier
try:
return validate_identifier(user_id)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
async def verify_user_id(
verified_id: Optional[str] = Depends(verify_api_key),
x_user_id: str = Header(..., alias="X-User-Id"),
) -> str:
"""Return the effective user ID after verifying against JWT identity.
In JWT mode (``open_webui_url`` configured), the user ID extracted from
the validated token **must** match ``X-User-Id``. In API-key or open
modes the header is trusted as-is.
"""
if verified_id is not None and verified_id != x_user_id:
raise HTTPException(
status_code=403,
detail="X-User-Id does not match authenticated identity",
)
return x_user_id
async def verify_proxy_user(request: Request, authorization: Optional[str] = Header(None), x_user_id: str = Header(..., alias="X-User-Id")):
return await verify_proxy_credentials(authorization, x_user_id)
-137
View File
@@ -1,137 +0,0 @@
"""Administrative terminal lifecycle endpoints."""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field
from terminals.config import settings
from terminals.db.session import async_session
from terminals.routers.auth import verify_admin_api_key
from terminals.routers.proxy import active_ws_connections
from terminals.utils.context import DEFAULT_CONTEXT_ID
router = APIRouter(prefix="/api/v1", tags=["terminals"])
class RefreshRequest(BaseModel):
user_id: Optional[str] = None
policy_id: Optional[str] = None
context_id: Optional[str] = None
only_idle: bool = True
reset: bool = False
class StopRequest(BaseModel):
user_id: str
policy_id: str = "default"
context_id: str = DEFAULT_CONTEXT_ID
class CleanupRequest(BaseModel):
user_id: str = Field(min_length=1, pattern=r"^[A-Za-z0-9][A-Za-z0-9_.@-]*$")
async def _policy_count() -> int:
if async_session is None:
return 0
from sqlalchemy import func, select
from terminals.models.policy import Policy
async with async_session() as session:
result = await session.execute(select(func.count()).select_from(Policy))
return int(result.scalar_one() or 0)
@router.get("/status", dependencies=[Depends(verify_admin_api_key)])
async def admin_status(request: Request):
"""Return control-plane status for the built-in admin UI."""
terminals = await request.app.state.backend.list_terminals()
return {
"status": True,
"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,
"allowed_images": settings.allowed_images,
"active_terminals": len(terminals),
"policy_count": await _policy_count(),
"active_websocket_connections": active_ws_connections,
}
@router.get("/terminals", dependencies=[Depends(verify_admin_api_key)])
async def list_terminals(request: Request):
"""List sanitized active terminal instances."""
return await request.app.state.backend.list_terminals()
@router.post("/terminals/stop", dependencies=[Depends(verify_admin_api_key)])
async def stop_terminal(request: Request, body: StopRequest):
"""Stop one terminal so the next access starts a fresh instance."""
result = await request.app.state.backend.refresh(
user_id=body.user_id,
policy_id=body.policy_id,
context_id=body.context_id,
only_idle=False,
reset=False,
)
if result.matched == 0:
raise HTTPException(status_code=404, detail="Terminal not found")
return {
"matched": result.matched,
"stopped": result.refreshed,
"skipped_active": result.skipped_active,
}
@router.post("/terminals/refresh", dependencies=[Depends(verify_admin_api_key)])
async def refresh_terminals(request: Request, body: RefreshRequest):
"""Tear down matching terminals so their next access provisions fresh."""
result = await request.app.state.backend.refresh(
user_id=body.user_id,
policy_id=body.policy_id,
context_id=body.context_id,
only_idle=body.only_idle,
reset=body.reset,
)
return {
"matched": result.matched,
"refreshed": result.refreshed,
"reset": result.reset,
"skipped_active": result.skipped_active,
}
@router.get("/terminals/data", dependencies=[Depends(verify_admin_api_key)])
async def list_user_data(request: Request):
"""List users with persisted terminal files."""
return await request.app.state.backend.list_user_data()
@router.post("/terminals/cleanup", dependencies=[Depends(verify_admin_api_key)])
async def cleanup_user(request: Request, body: CleanupRequest):
"""Permanently remove one deleted user's inactive workspace storage."""
try:
deleted = await request.app.state.backend.cleanup_user(body.user_id)
except NotImplementedError as exc:
raise HTTPException(status_code=501, detail=str(exc)) from exc
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
if async_session is not None:
from sqlalchemy import delete
from terminals.models.policy import PolicyLifecycleState
async with async_session() as session:
await session.execute(
delete(PolicyLifecycleState).where(PolicyLifecycleState.user_id == body.user_id)
)
await session.commit()
return {"deleted": deleted}
-315
View File
@@ -1,315 +0,0 @@
"""Policy CRUD API."""
from datetime import datetime, timezone
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel, ConfigDict
from terminals.config import settings
from terminals.backends.base import ProvisioningError
from terminals.db.session import async_session
from terminals.routers.auth import verify_admin_api_key
from terminals.utils.policy_lifecycle import (
get_lifecycle_data,
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,
)
from terminals.utils.parsing import parse_size
from terminals.utils.network_profiles import resolve_network_profile
router = APIRouter(prefix="/api/v1", tags=["policies"])
# ---------------------------------------------------------------------------
# Pydantic schemas
# ---------------------------------------------------------------------------
class PolicyData(BaseModel):
"""Policy data. All fields are optional and merged with defaults."""
model_config = ConfigDict(extra="allow")
image: Optional[str] = None
network_profile: Optional[str] = None
env: Optional[dict] = None
cpu_limit: Optional[str] = None
memory_limit: Optional[str] = None
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
class PolicyResponse(BaseModel):
id: str
data: dict
created_at: Optional[str] = None
updated_at: Optional[str] = None
class PolicyCreate(BaseModel):
id: str
data: PolicyData = PolicyData()
class PolicyLifecycleData(BaseModel):
"""Policy lifecycle config, stored separately from provisioning policy."""
model_config = ConfigDict(extra="allow")
reset: Optional[dict[str, Any]] = None
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _clamp_policy(data: dict) -> dict:
"""Clamp policy values against env var hard caps."""
result = {k: v for k, v in data.items() if v is not None}
try:
resolve_network_profile(result, settings.backend)
except ProvisioningError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
lifecycle_keys = {"reset", "reset_schedule", "reset_timezone", "lifecycle"}
unexpected = sorted(lifecycle_keys.intersection(result))
if unexpected:
raise HTTPException(
status_code=400,
detail=f"Lifecycle keys are not valid policy fields: {', '.join(unexpected)}",
)
if restricted_enabled(result):
errors = restricted_env_errors(result.get("env") or {})
if errors:
raise HTTPException(status_code=400, detail="; ".join(errors))
# Clamp CPU
if settings.max_cpu and "cpu_limit" in result:
try:
if float(result["cpu_limit"]) > float(settings.max_cpu):
result["cpu_limit"] = settings.max_cpu
except (ValueError, TypeError):
pass
# Clamp memory
if settings.max_memory and "memory_limit" in result:
try:
if parse_size(result["memory_limit"]) > parse_size(settings.max_memory):
result["memory_limit"] = settings.max_memory
except Exception:
pass
# Clamp storage
if settings.max_storage and "storage" in result:
try:
if parse_size(result["storage"]) > parse_size(settings.max_storage):
result["storage"] = settings.max_storage
except Exception:
pass
# Validate image against allowlist
if settings.allowed_images and "image" in result:
import fnmatch
patterns = [p.strip() for p in settings.allowed_images.split(",")]
if not any(fnmatch.fnmatch(result["image"], p) for p in patterns):
raise HTTPException(
status_code=400,
detail=f"Image '{result['image']}' not in allowed list",
)
return result
def _validate_lifecycle(data: dict) -> dict:
result = {k: v for k, v in data.items() if v is not None}
if not validate_lifecycle_data(result):
raise HTTPException(status_code=400, detail="Invalid lifecycle configuration")
return result
def _merge_defaults(policy_data: dict) -> dict:
"""Merge env var defaults with policy overrides."""
return merge_policy_defaults(policy_data)
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@router.get("/policies", dependencies=[Depends(verify_admin_api_key)])
async def list_policies():
"""List all policies."""
if async_session is None:
raise HTTPException(status_code=503, detail="Database not configured")
from terminals.models.policy import Policy
async with async_session() as session:
from sqlalchemy import select
result = await session.execute(select(Policy).order_by(Policy.created_at))
policies = result.scalars().all()
return [
PolicyResponse(
id=p.id,
data=p.data or {},
created_at=str(p.created_at) if p.created_at else None,
updated_at=str(p.updated_at) if p.updated_at else None,
)
for p in policies
]
@router.post("/policies", dependencies=[Depends(verify_admin_api_key)], status_code=201)
async def create_policy(body: PolicyCreate):
"""Create a new policy."""
if async_session is None:
raise HTTPException(status_code=503, detail="Database not configured")
from terminals.models.policy import Policy
clamped = _clamp_policy(body.data.model_dump(exclude_none=True))
async with async_session() as session:
from sqlalchemy import select
existing = await session.execute(select(Policy).where(Policy.id == body.id))
if existing.scalar_one_or_none():
raise HTTPException(status_code=409, detail=f"Policy '{body.id}' already exists")
now = datetime.now(timezone.utc).replace(tzinfo=None)
policy = Policy(
id=body.id,
data=clamped,
created_at=now,
updated_at=now,
)
session.add(policy)
await session.commit()
return PolicyResponse(
id=policy.id,
data=policy.data or {},
created_at=str(policy.created_at),
updated_at=str(policy.updated_at),
)
@router.get("/policies/{policy_id}", dependencies=[Depends(verify_admin_api_key)])
async def get_policy(policy_id: str):
"""Get a single policy."""
if async_session is None:
raise HTTPException(status_code=503, detail="Database not configured")
from terminals.models.policy import Policy
async with async_session() as session:
from sqlalchemy import select
result = await session.execute(select(Policy).where(Policy.id == policy_id))
policy = result.scalar_one_or_none()
if not policy:
raise HTTPException(status_code=404, detail=f"Policy '{policy_id}' not found")
return PolicyResponse(
id=policy.id,
data=policy.data or {},
created_at=str(policy.created_at) if policy.created_at else None,
updated_at=str(policy.updated_at) if policy.updated_at else None,
)
@router.get("/policies/{policy_id}/lifecycle", dependencies=[Depends(verify_admin_api_key)])
async def get_policy_lifecycle(policy_id: str):
"""Get policy lifecycle configuration."""
if async_session is None:
raise HTTPException(status_code=503, detail="Database not configured")
return {
"policy_id": policy_id,
"data": await get_lifecycle_data(policy_id),
}
@router.put("/policies/{policy_id}/lifecycle", dependencies=[Depends(verify_admin_api_key)])
async def put_policy_lifecycle(policy_id: str, body: PolicyLifecycleData):
"""Create or update policy lifecycle configuration."""
if async_session is None:
raise HTTPException(status_code=503, detail="Database not configured")
data = _validate_lifecycle(body.model_dump(exclude_none=True))
return {
"policy_id": policy_id,
"data": await upsert_lifecycle_data(policy_id, data),
}
@router.put("/policies/{policy_id}", dependencies=[Depends(verify_admin_api_key)])
async def upsert_policy(policy_id: str, body: PolicyData):
"""Create or update a policy."""
if async_session is None:
raise HTTPException(status_code=503, detail="Database not configured")
from terminals.models.policy import Policy
clamped = _clamp_policy(body.model_dump(exclude_none=True))
async with async_session() as session:
from sqlalchemy import select
result = await session.execute(select(Policy).where(Policy.id == policy_id))
policy = result.scalar_one_or_none()
if policy:
policy.data = clamped
policy.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
else:
now = datetime.now(timezone.utc).replace(tzinfo=None)
policy = Policy(
id=policy_id,
data=clamped,
created_at=now,
updated_at=now,
)
session.add(policy)
await session.commit()
from terminals.routers.proxy import invalidate_policy_caches
invalidate_policy_caches(policy_id)
return PolicyResponse(
id=policy.id,
data=policy.data or {},
created_at=str(policy.created_at),
updated_at=str(policy.updated_at),
)
@router.delete("/policies/{policy_id}", dependencies=[Depends(verify_admin_api_key)])
async def delete_policy(policy_id: str):
"""Delete a policy."""
if async_session is None:
raise HTTPException(status_code=503, detail="Database not configured")
from terminals.models.policy import Policy
async with async_session() as session:
from sqlalchemy import select
result = await session.execute(select(Policy).where(Policy.id == policy_id))
policy = result.scalar_one_or_none()
if not policy:
raise HTTPException(status_code=404, detail=f"Policy '{policy_id}' not found")
await session.delete(policy)
await session.commit()
from terminals.routers.proxy import invalidate_policy_caches
invalidate_policy_caches(policy_id)
return {"ok": True}
+94 -334
View File
@@ -1,18 +1,11 @@
"""Catch-all reverse proxy into terminal instances.
"""Reverse proxy to the selected template's environment.
Routing is based on the ``X-User-Id`` header — the caller (e.g. Open WebUI
backend) sets this header and the proxy resolves / provisions the correct
instance automatically. The path structure mirrors open-terminal exactly
(``/execute``, ``/files/list``, …) so the two are interchangeable.
Named policy endpoints:
/p/{policy_id}/* — provisions using the named policy config
The trusted caller supplies the template and verified user/chat/model context.
The template's stored scope determines the instance; paths mirror Open Terminal.
"""
import asyncio
import hmac
import json
import time
from dataclasses import dataclass
from typing import Optional
from urllib.parse import quote
@@ -20,7 +13,7 @@ from urllib.parse import quote
import httpx
import websockets
from websockets.exceptions import InvalidHandshake
from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Query, Request, Response, WebSocket
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Query, Request, Response, WebSocket
from fastapi.responses import JSONResponse, StreamingResponse
from loguru import logger
from starlette.background import BackgroundTask
@@ -28,12 +21,11 @@ from starlette.background import BackgroundTask
from terminals.backends.base import ProvisioningError
from terminals.config import settings
from terminals.utils.context import (
CONTEXT_HEADER,
CONTEXT_HEADER, TEMPLATE_HEADER, CHAT_HEADER, MODEL_HEADER, terminal_identity, get_terminal_id,
DEFAULT_CONTEXT_ID,
normalize_context_id,
)
from terminals.utils.policy_specs import PolicyNotFoundError, resolve_policy_spec
from terminals.routers.auth import validate_token, verify_api_key, verify_spec_access, verify_user_id
from terminals.utils.template_specs import TemplateNotFoundError, resolve_template_spec
from terminals.routers.auth import verify_proxy_user, verify_proxy_credentials, require_server_key
router = APIRouter()
@@ -43,8 +35,6 @@ router = APIRouter()
_proxy_clients: dict[tuple[str, int], httpx.AsyncClient] = {}
# Active WebSocket connection counter (for stats endpoint)
active_ws_connections: int = 0
async def _get_proxy_client(host: str, port: int) -> httpx.AsyncClient:
@@ -81,34 +71,24 @@ async def close_proxy_client() -> None:
# ---------------------------------------------------------------------------
def _client_ip(request) -> str:
"""Extract client IP, respecting X-Forwarded-For."""
headers = getattr(request, "headers", {})
forwarded = headers.get("x-forwarded-for") if hasattr(headers, "get") else None
if forwarded:
return forwarded.split(",")[0].strip()
client = getattr(request, "client", None)
return client.host if client else ""
def _user_agent(request) -> str:
headers = getattr(request, "headers", {})
return headers.get("user-agent", "") if hasattr(headers, "get") else ""
def _request_id(request) -> Optional[str]:
return getattr(getattr(request, "state", None), "request_id", None)
def _context_from_request(request: Request) -> str:
try:
return normalize_context_id(request.headers.get(CONTEXT_HEADER))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
def _context_from_websocket(ws: WebSocket, query_context_id: str) -> str:
return normalize_context_id(ws.headers.get(CONTEXT_HEADER) or query_context_id)
async def _request_target(request, user_id):
template_id = request.headers.get(TEMPLATE_HEADER)
if not template_id:
raise HTTPException(400, "Missing X-Terminal-Template-Id")
if request.headers.get(CONTEXT_HEADER):
raise HTTPException(400, "Client-selected instance contexts are no longer supported")
spec = await _resolve_template_spec(template_id)
scope = (spec or {}).get("scope")
context, _ = terminal_identity(template_id, scope, user_id=user_id,
chat_id=request.headers.get(CHAT_HEADER),
model_id=request.headers.get(MODEL_HEADER))
return template_id, context
# ---------------------------------------------------------------------------
@@ -119,49 +99,47 @@ def _context_from_websocket(ws: WebSocket, query_context_id: str) -> str:
@dataclass
class InstanceInfo:
"""Resolved terminal instance."""
instance_id: str
host: str
port: int
api_key: str
async def _touch_activity(backend, user_id: str, policy_id: str, context_id: str) -> None:
"""Record terminal use; backends throttle the persisted write."""
async def _touch_activity(backend, template_id, context_id):
try:
await backend.touch_activity(user_id, policy_id=policy_id, context_id=context_id)
await backend.touch_activity(template_id, context_id=context_id)
except Exception:
logger.debug("touch_activity failed for user {}", user_id)
logger.debug("Failed to persist activity for {}", template_id)
async def _resolve_instance(
request,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
existing_only: bool = False,
) -> InstanceInfo:
"""Return a running instance, auto-provisioning if needed."""
backend = request.app.state.backend
try:
if existing_only:
info = await backend.get_terminal_info(user_id, policy_id=policy_id, context_id=context_id)
info = await backend.get_terminal_info(template_id=template_id, context_id=context_id)
if info is None:
raise HTTPException(status_code=409, detail="Terminal instance is not running")
return InstanceInfo(
instance_id=info["instance_id"], host=info["host"],
host=info["host"],
port=info["port"], api_key=info["api_key"],
)
info = await backend.ensure_terminal(
user_id, policy_id=policy_id, context_id=context_id, spec=spec
template_id=template_id, context_id=context_id
)
except TemplateNotFoundError as exc:
raise HTTPException(404, "Template not found") from exc
except ProvisioningError as exc:
raise HTTPException(status_code=503, detail=str(exc)) from exc
if info is None:
raise RuntimeError(f"Failed to provision terminal for user {user_id}")
await _touch_activity(backend, user_id, policy_id, context_id)
await _touch_activity(backend, template_id, context_id)
return InstanceInfo(
instance_id=info["instance_id"],
host=info["host"],
port=info["port"],
api_key=info["api_key"],
@@ -176,9 +154,9 @@ async def _resolve_instance(
async def _proxy_request(
request: Request, user_id: str, path: str,
background_tasks: Optional[BackgroundTasks] = None,
policy_id: str = "default",
*,
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
) -> Response:
"""Forward an HTTP request to the user's terminal instance.
@@ -188,7 +166,7 @@ async def _proxy_request(
# Inspecting machine health must never provision, wake, or keep an instance alive.
existing_only = path.rstrip("/") == "system/info"
instance = await _resolve_instance(
request, user_id, policy_id=policy_id, context_id=context_id, spec=spec,
request, user_id, template_id=template_id, context_id=context_id,
existing_only=existing_only,
)
@@ -200,7 +178,7 @@ async def _proxy_request(
# Replace auth with the instance's own API key.
headers["authorization"] = f"Bearer {instance.api_key}"
# Remove hop-by-hop / routing headers.
for h in ("host", "transfer-encoding", "connection", "x-user-id", CONTEXT_HEADER.lower()):
for h in ("host", "transfer-encoding", "connection", "x-user-id", CONTEXT_HEADER.lower(), TEMPLATE_HEADER.lower(), CHAT_HEADER.lower(), MODEL_HEADER.lower()):
headers.pop(h, None)
raw_content_length = request.headers.get("content-length")
@@ -236,7 +214,7 @@ async def _proxy_request(
)
break
except (httpx.ConnectError, httpx.ConnectTimeout) as e:
request.app.state.backend.invalidate_status(user_id, policy_id, context_id)
request.app.state.backend.invalidate_status(template_id, context_id)
if attempt < max_retries - 1:
logger.debug("Proxy attempt {} to {} failed ({}), retrying...", attempt + 1, target_url, e)
await asyncio.sleep(1)
@@ -244,9 +222,8 @@ async def _proxy_request(
instance = await _resolve_instance(
request,
user_id,
policy_id=policy_id,
template_id=template_id,
context_id=context_id,
spec=spec,
)
except HTTPException:
raise
@@ -282,7 +259,7 @@ async def _proxy_request(
)
except (httpx.RemoteProtocolError, httpx.ReadError) as e:
request.app.state.backend.invalidate_status(
user_id, policy_id, context_id
template_id, context_id
)
if attempt < max_retries - 1:
logger.debug(
@@ -295,9 +272,8 @@ async def _proxy_request(
instance = await _resolve_instance(
request,
user_id,
policy_id=policy_id,
template_id=template_id,
context_id=context_id,
spec=spec,
)
except HTTPException:
raise
@@ -335,14 +311,9 @@ async def _proxy_request(
# ---------------------------------------------------------------------------
# OpenAPI spec passthrough (tool discovery — no X-User-Id required)
# OpenAPI spec passthrough (tool discovery uses the same verified context as execution)
# ---------------------------------------------------------------------------
_SPEC_CACHE_TTL = 300 # seconds
_spec_cache: dict[str, tuple[float, dict]] = {} # key → (timestamp, spec)
_SYSTEM_USER_ID = "system"
# Max retries when waiting for a freshly provisioned container to become ready.
_SPEC_FETCH_RETRIES = 10
_SPEC_FETCH_DELAY = 1 # seconds between retries
@@ -397,147 +368,28 @@ def _strip_auth_from_spec(spec: dict) -> dict:
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,
)
async def _resolve_template_spec(template_id):
try:
raw = await _fetch_spec_with_retry(instance)
except Exception:
request.app.state.backend.invalidate_status(_SYSTEM_USER_ID, policy_id)
raise
stripped = _strip_auth_from_spec(raw)
_spec_cache[policy_id] = (now, stripped)
return stripped
return await resolve_template_spec(template_id)
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
except TemplateNotFoundError as exc:
raise HTTPException(404, "Template not found") from exc
@router.get(
"/openapi.json",
dependencies=[Depends(verify_spec_access)],
)
async def get_openapi_spec(request: Request):
"""Return the open-terminal OpenAPI spec.
The spec is fetched from a running instance and cached for 5 minutes.
This endpoint does **not** require ``X-User-Id`` — it is used by
Open WebUI for tool discovery before any user context exists.
"""
try:
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,
)
return JSONResponse(content=spec)
@router.get("/openapi.json")
async def get_openapi_spec(request: Request, user_id: str = Depends(verify_proxy_user)):
template_id, context_id = await _request_target(request, user_id)
instance = await _resolve_instance(request, user_id, template_id, context_id)
return JSONResponse(content=_strip_auth_from_spec(await _fetch_spec_with_retry(instance)))
# ---------------------------------------------------------------------------
# Named policy proxy — /p/{policy_id}/{path}
# ---------------------------------------------------------------------------
_POLICY_CACHE_TTL = 60 # seconds
_policy_cache: dict[str, tuple[float, tuple[str, dict | None]]] = {}
def invalidate_policy_caches(policy_id: str) -> None:
"""Discard cached policy data and tool specs after a policy change."""
_policy_cache.pop(policy_id, None)
_spec_cache.pop(policy_id, None)
async def _resolve_policy_spec(policy_id: str) -> tuple[str, dict | None]:
"""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]
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(
"/p/{policy_id}/openapi.json",
dependencies=[Depends(verify_spec_access)],
)
async def policy_openapi_spec(
policy_id: str,
request: Request,
):
"""Serve the OpenAPI spec via a named policy container (cached)."""
_id, spec = await _resolve_policy_spec(policy_id)
try:
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(
content={"error": "Failed to fetch OpenAPI spec"},
status_code=502,
)
return JSONResponse(content=spec_data)
@router.api_route(
"/p/{policy_id}/{path:path}",
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
)
async def policy_proxy(
policy_id: str,
path: str,
request: Request,
background_tasks: BackgroundTasks,
x_user_id: str = Depends(verify_user_id),
):
"""Proxy a request through a named policy endpoint."""
_id, spec = await _resolve_policy_spec(policy_id)
context_id = _context_from_request(request)
return await _proxy_request(
request, x_user_id, path, background_tasks,
policy_id=_id, context_id=context_id, spec=spec,
)
# ---------------------------------------------------------------------------
# Header-based catch-all proxy — default endpoint (backward compat)
# ---------------------------------------------------------------------------
@router.api_route(
"/{path:path}",
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"],
)
async def proxy(
path: str,
request: Request,
background_tasks: BackgroundTasks,
x_user_id: str = Depends(verify_user_id),
):
"""Reverse-proxy any request into the user's Open Terminal instance.
Uses settings.* defaults — no policy lookup.
"""
context_id = _context_from_request(request)
return await _proxy_request(
request, x_user_id, path, background_tasks, context_id=context_id
)
@router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"])
async def proxy(path: str, request: Request, background_tasks: BackgroundTasks,
x_user_id: str = Depends(verify_proxy_user)):
template_id, context_id = await _request_target(request, x_user_id)
return await _proxy_request(request, x_user_id, path, background_tasks,
template_id=template_id, context_id=context_id)
# ---------------------------------------------------------------------------
@@ -575,15 +427,10 @@ async def _validate_ws_auth(
await ws.close(code=4001, reason="Auth failed")
return None
verified_user_id = None
if settings.open_webui_url:
try:
verified_user_id = await validate_token(token)
except Exception:
await ws.close(code=4001, reason="Invalid token")
return None
elif settings.api_key and not hmac.compare_digest(token, settings.api_key):
await ws.close(code=4001, reason="Invalid API key")
try:
require_server_key(token)
except HTTPException:
await ws.close(code=4001, reason="Invalid server key")
return None
user_id = ws.headers.get("x-user-id") or user_id
@@ -591,57 +438,21 @@ async def _validate_ws_auth(
await ws.close(code=4002, reason="Missing user_id")
return None
if verified_user_id is not None and verified_user_id != user_id:
await ws.close(code=4003, reason="user_id does not match authenticated identity")
return None
return user_id
async def _ws_proxy_handler(
ws: WebSocket,
path: str,
user_id: str,
policy_id: str = "default",
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
):
"""Core WebSocket proxy logic, shared by default and policy routes.
The connection counter is maintained here with a try/finally around the
whole proxy body — early returns on resolve/connect failures previously
skipped the decrement, inflating the counter permanently.
"""
global active_ws_connections
active_ws_connections += 1
try:
await _ws_proxy(
ws,
path,
user_id,
policy_id=policy_id,
context_id=context_id,
spec=spec,
)
finally:
active_ws_connections -= 1
try:
await ws.close()
except Exception:
pass
async def _ws_proxy(
ws: WebSocket,
path: str,
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: Optional[dict] = None,
):
try:
instance = await _resolve_instance(
ws, user_id, policy_id=policy_id, context_id=context_id, spec=spec
ws, user_id, template_id=template_id, context_id=context_id
)
except Exception as e:
logger.error("Failed to resolve instance for WS: {}", e)
@@ -668,7 +479,7 @@ async def _ws_proxy(
OSError,
InvalidHandshake,
) as e:
ws.app.state.backend.invalidate_status(user_id, policy_id, context_id)
ws.app.state.backend.invalidate_status(template_id, context_id)
if attempt < max_retries - 1:
logger.debug("WS connect attempt {} to {} failed ({}), retrying...", attempt + 1, upstream_url, e)
await asyncio.sleep(1)
@@ -676,9 +487,8 @@ async def _ws_proxy(
instance = await _resolve_instance(
ws,
user_id,
policy_id=policy_id,
template_id=template_id,
context_id=context_id,
spec=spec,
)
except Exception as resolve_err:
logger.error("WS re-resolve for user {} failed: {}", user_id, resolve_err)
@@ -711,7 +521,7 @@ async def _ws_proxy(
if msg["type"] == "websocket.disconnect":
break
if msg.get("text") != '{"type":"ping"}':
await _touch_activity(backend, user_id, policy_id, context_id)
await _touch_activity(backend, template_id, context_id)
if "bytes" in msg and msg["bytes"]:
await upstream.send(msg["bytes"])
elif "text" in msg and msg["text"]:
@@ -722,7 +532,7 @@ async def _ws_proxy(
async def _upstream_to_client():
try:
async for message in upstream:
await _touch_activity(backend, user_id, policy_id, context_id)
await _touch_activity(backend, template_id, context_id)
if isinstance(message, bytes):
await ws.send_bytes(message)
else:
@@ -744,74 +554,11 @@ async def _ws_proxy(
logger.error("WebSocket terminal proxy error: {}", e)
@router.websocket("/api/terminals/{session_id}")
async def ws_terminal_proxy(
ws: WebSocket,
session_id: str,
user_id: str = Query(""),
context_id: str = Query(DEFAULT_CONTEXT_ID),
):
"""Default WebSocket terminal proxy (no policy)."""
effective_user = await _validate_ws_auth(ws, user_id)
if effective_user is None:
return
try:
context_id = _context_from_websocket(ws, context_id)
except ValueError as exc:
await ws.close(code=4004, reason=str(exc))
return
await _ws_proxy_handler(ws, f"api/terminals/{session_id}", effective_user, context_id=context_id)
@router.websocket("/p/{policy_id}/api/terminals/{session_id}")
async def ws_policy_terminal_proxy(
ws: WebSocket,
policy_id: str,
session_id: str,
user_id: str = Query(""),
context_id: str = Query(DEFAULT_CONTEXT_ID),
):
"""Policy-scoped WebSocket terminal proxy."""
effective_user = await _validate_ws_auth(ws, user_id)
if effective_user is None:
return
try:
_id, spec = await _resolve_policy_spec(policy_id)
context_id = _context_from_websocket(ws, context_id)
except HTTPException:
await ws.close(code=4004, reason=f"Policy '{policy_id}' not found")
return
except ValueError as exc:
await ws.close(code=4004, reason=str(exc))
return
await _ws_proxy_handler(
ws,
f"api/terminals/{session_id}",
effective_user,
policy_id=_id,
context_id=context_id,
spec=spec,
)
@router.websocket("/{path:path}")
@router.websocket("/p/{policy_id}/{path:path}")
async def ws_proxy(
ws: WebSocket,
path: str,
policy_id: Optional[str] = None,
user_id: str = Query(""),
context_id: str = Query(DEFAULT_CONTEXT_ID),
):
async def ws_proxy(ws: WebSocket, path: str, user_id: str = Query("")):
if path.startswith("browser/view/"):
try:
verified_id = await verify_api_key(ws.headers.get("authorization"))
user_id = ws.headers.get("x-user-id", "")
if not user_id:
raise HTTPException(status_code=400, detail="Missing X-User-Id")
effective_user = await verify_user_id(verified_id, user_id)
effective_user = await verify_proxy_credentials(ws.headers.get("authorization"), ws.headers.get("x-user-id"))
except HTTPException as exc:
await ws.close(code=4001, reason=str(exc.detail))
return
@@ -820,20 +567,33 @@ async def ws_proxy(
effective_user = await _validate_ws_auth(ws, user_id)
if effective_user is None:
return
try:
spec = None
if policy_id is not None:
policy_id, spec = await _resolve_policy_spec(policy_id)
context_id = _context_from_websocket(ws, context_id)
except HTTPException:
await ws.close(code=4004, reason=f"Policy '{policy_id}' not found")
return
except ValueError as exc:
await ws.close(code=4004, reason=str(exc))
template_id, context_id = await _request_target(ws, effective_user)
except HTTPException as exc:
await ws.close(code=4004, reason=str(exc.detail))
return
key = get_terminal_id(template_id, context_id)
_instance_sockets.setdefault(key, set()).add(ws)
try:
await _ws_proxy(ws, path, effective_user, template_id=template_id, context_id=context_id)
finally:
try:
await ws.close()
except Exception:
pass
sockets = _instance_sockets.get(key)
if sockets is not None:
sockets.discard(ws)
if not sockets:
_instance_sockets.pop(key, None)
await _ws_proxy_handler(
ws, path, effective_user, policy_id=policy_id or "default",
context_id=context_id, spec=spec,
)
_instance_sockets = {}
async def close_instance_sessions(key):
for socket in list(_instance_sockets.pop(key, ())):
try:
await socket.close(code=1012, reason="Terminal restarted")
except Exception:
pass
+310
View File
@@ -0,0 +1,310 @@
"""Template CRUD API."""
from datetime import datetime, timezone
from typing import Any, Optional, Literal
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, ConfigDict, field_validator
from terminals.config import settings
from terminals.backends.base import ProvisioningError
from terminals.db.session import async_session
from terminals.routers.auth import verify_admin_api_key
from terminals.utils.template_lifecycle import (
get_lifecycle_data,
upsert_lifecycle_data,
validate_lifecycle_data,
)
from terminals.utils.kubernetes_security import (
restricted_enabled,
restricted_env_errors,
)
from terminals.utils.parsing import parse_size
from terminals.utils.network_profiles import resolve_network_profile
router = APIRouter(tags=["templates"], dependencies=[Depends(verify_admin_api_key)])
# ---------------------------------------------------------------------------
# Pydantic schemas
# ---------------------------------------------------------------------------
class TemplateData(BaseModel):
"""Template data. All fields are optional and merged with defaults."""
model_config = ConfigDict(extra="allow")
name: str | None = None
scope: Literal["user", "chat", "model"] | None = None
image: Optional[str] = None
network_profile: Optional[str] = None
env: Optional[dict] = None
cpu_limit: Optional[str] = None
memory_limit: Optional[str] = None
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
class TemplateResponse(BaseModel):
id: str
data: dict
created_at: Optional[str] = None
updated_at: Optional[str] = None
class TemplateCreate(BaseModel):
id: str
data: TemplateData = TemplateData()
@field_validator("id")
@classmethod
def valid_id(cls, value):
from terminals.utils.context import validate_identifier
validate_identifier(value)
if "/" in value:
raise ValueError("Template IDs cannot contain slashes")
return value
class TemplateLifecycleData(BaseModel):
"""Template lifecycle config, stored separately from instance configuration."""
model_config = ConfigDict(extra="allow")
reset: Optional[dict[str, Any]] = None
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _clamp_template(data: dict) -> dict:
"""Clamp template values against env var hard caps."""
removed = {"per_chat", "per_automation", "max_instances"}.intersection(data)
if removed:
raise HTTPException(422, "Use scope instead of legacy allocation fields")
result = {k: v for k, v in data.items() if v is not None}
try:
resolve_network_profile(result, settings.backend)
except ProvisioningError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
lifecycle_keys = {"reset", "reset_schedule", "reset_timezone", "lifecycle"}
unexpected = sorted(lifecycle_keys.intersection(result))
if unexpected:
raise HTTPException(
status_code=400,
detail=f"Lifecycle keys are not valid template fields: {', '.join(unexpected)}",
)
if restricted_enabled(result):
errors = restricted_env_errors(result.get("env") or {})
if errors:
raise HTTPException(status_code=400, detail="; ".join(errors))
# Clamp CPU
if settings.max_cpu and "cpu_limit" in result:
try:
if float(result["cpu_limit"]) > float(settings.max_cpu):
result["cpu_limit"] = settings.max_cpu
except (ValueError, TypeError):
pass
# Clamp memory
if settings.max_memory and "memory_limit" in result:
try:
if parse_size(result["memory_limit"]) > parse_size(settings.max_memory):
result["memory_limit"] = settings.max_memory
except Exception:
pass
# Clamp storage
if settings.max_storage and "storage" in result:
try:
if parse_size(result["storage"]) > parse_size(settings.max_storage):
result["storage"] = settings.max_storage
except Exception:
pass
# Validate image against allowlist
if settings.allowed_images and "image" in result:
import fnmatch
patterns = [p.strip() for p in settings.allowed_images.split(",")]
if not any(fnmatch.fnmatch(result["image"], p) for p in patterns):
raise HTTPException(
status_code=400,
detail=f"Image '{result['image']}' not in allowed list",
)
return result
def _validate_lifecycle(data: dict) -> dict:
result = {k: v for k, v in data.items() if v is not None}
if not validate_lifecycle_data(result):
raise HTTPException(status_code=400, detail="Invalid lifecycle configuration")
return result
# ---------------------------------------------------------------------------
# Endpoints
from sqlalchemy import select, delete
from sqlalchemy.exc import IntegrityError
from terminals.models.template import Template, TemplateLifecycle, TemplateLifecycleState
from terminals.utils.instances import instance_lock, change_instance, stop_instance, remove_home, describe_instance
from terminals.utils.context import terminal_identity
from terminals.utils.template_specs import resolve_template_spec
def response(row):
return TemplateResponse(id=row.id, data=row.data or {},
created_at=str(row.created_at), updated_at=str(row.updated_at))
async def require_template(template_id):
async with async_session() as session:
row = await session.get(Template, template_id)
if row is None:
raise HTTPException(404, "Template not found")
return row
@router.get("")
async def list_templates():
async with async_session() as session:
rows = await session.scalars(select(Template).order_by(Template.created_at))
return [response(row) for row in rows]
@router.post("", status_code=201)
async def create_template(body: TemplateCreate):
data = _clamp_template(body.data.model_dump(exclude_none=True))
async with instance_lock("template:" + body.id), async_session() as session:
row = Template(id=body.id, data=data)
session.add(row)
try:
await session.commit()
except IntegrityError as exc:
await session.rollback()
raise HTTPException(409, "Template already exists") from exc
await session.refresh(row)
return response(row)
@router.get("/{template_id}")
async def get_template(template_id: str):
return response(await require_template(template_id))
@router.get("/{template_id}/instances")
async def list_instances(template_id: str, request: Request):
await require_template(template_id)
return await request.app.state.backend.list_terminals(template_id)
@router.patch("/{template_id}")
async def update_template(template_id: str, body: TemplateData):
async with instance_lock("template:" + template_id), async_session() as session:
row = await session.get(Template, template_id)
if row is None:
raise HTTPException(404, "Template not found")
old = row.data or {}
data = _clamp_template({**old, **body.model_dump(exclude_unset=True)})
protected = ("scope", "storage_mode")
if any(old.get(k) != data.get(k) for k in protected):
exists = await session.scalar(select(TemplateLifecycleState.id).where(
TemplateLifecycleState.template_id == template_id,
).limit(1))
if exists:
raise HTTPException(409, "Delete existing environments before changing scope or storage mode")
row.data = data
row.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
await session.commit()
return response(row)
@router.delete("/{template_id}")
async def delete_template(template_id: str, request: Request):
async with instance_lock("template:" + template_id):
await require_template(template_id)
spec = await resolve_template_spec(template_id)
async with async_session() as session:
rows = list(await session.scalars(select(TemplateLifecycleState).where(
TemplateLifecycleState.template_id == template_id).order_by(TemplateLifecycleState.id)))
for row in rows:
async with instance_lock(row.id):
await stop_instance(request.app.state.backend, row.template_id, row.context_id)
await remove_home(request.app.state.backend, row, spec)
async with async_session() as session:
await session.execute(delete(TemplateLifecycleState).where(TemplateLifecycleState.id == row.id))
await session.commit()
async with async_session() as session:
await session.execute(delete(TemplateLifecycle).where(TemplateLifecycle.template_id == template_id))
await session.execute(delete(Template).where(Template.id == template_id))
await session.commit()
return {"ok": True}
class InstanceContext(BaseModel):
user_id: str
chat_id: str | None = None
model_id: str | None = None
async def context_for(template_id, form):
template = await require_template(template_id)
scope = (template.data or {}).get("scope")
context, key = terminal_identity(template_id, scope, user_id=form.user_id,
chat_id=form.chat_id, model_id=form.model_id)
return context, key
@router.get("/{template_id}/instance")
async def get_instance(template_id: str, user_id: str, request: Request,
chat_id: str | None = None, model_id: str | None = None):
context, key = await context_for(template_id, InstanceContext(user_id=user_id, chat_id=chat_id, model_id=model_id))
async with async_session() as session:
row = await session.get(TemplateLifecycleState, key)
if row is None:
return {"id": key, "template_id": template_id, "context_id": context, "status": "not_created"}
return await describe_instance(request.app.state.backend, row)
@router.post("/{template_id}/restart")
async def restart_instance(template_id: str, body: InstanceContext, request: Request):
context, _ = await context_for(template_id, body)
await change_instance(request.app.state.backend, template_id, context, "restart")
return {"ok": True}
@router.post("/{template_id}/reset")
async def reset_instance(template_id: str, body: InstanceContext, request: Request):
context, _ = await context_for(template_id, body)
await change_instance(request.app.state.backend, template_id, context, "reset")
return {"ok": True}
@router.delete("/{template_id}/instance")
async def delete_instance(template_id: str, body: InstanceContext, request: Request):
context, _ = await context_for(template_id, body)
await change_instance(request.app.state.backend, template_id, context, "delete")
return {"ok": True}
@router.get("/{template_id}/lifecycle")
async def get_template_lifecycle(template_id: str):
await require_template(template_id)
return {"template_id": template_id, "data": await get_lifecycle_data(template_id)}
@router.put("/{template_id}/lifecycle")
async def put_template_lifecycle(template_id: str, body: TemplateLifecycleData):
async with instance_lock("template:" + template_id):
await require_template(template_id)
data = _validate_lifecycle(body.model_dump(exclude_none=True))
return {"template_id": template_id, "data": await upsert_lifecycle_data(template_id, data)}
+27
View File
@@ -0,0 +1,27 @@
"""Terminal administration; all template routes are mounted here."""
from fastapi import APIRouter, Depends, Request
from sqlalchemy import func, select
from terminals.config import settings
from terminals.db.session import async_session
from terminals.models.template import Template
from terminals.routers.auth import verify_admin_api_key
from terminals.routers.templates import router as templates_router
router = APIRouter(prefix="/api/v1/terminals", tags=["terminals"], dependencies=[Depends(verify_admin_api_key)])
router.include_router(templates_router, prefix="/templates")
@router.get("")
async def list_terminals(request: Request, template_id: str | None = None):
return await request.app.state.backend.list_terminals(template_id)
@router.get("/status")
async def status(request: Request):
async with async_session() as session:
count = await session.scalar(select(func.count()).select_from(Template))
return {"status": True, "version": "0.4.0", "backend": settings.backend,
"template_count": count, "image": settings.image,
"max_cpu": settings.max_cpu, "max_memory": settings.max_memory,
"max_storage": settings.max_storage, "allowed_images": settings.allowed_images,
"network_profiles": sorted(settings.network_profiles)}
+46 -14
View File
@@ -1,28 +1,60 @@
"""Terminal context helpers."""
"""Stable identities for template environments. This encoding is a storage contract."""
import hashlib
import json
from fastapi import HTTPException
DEFAULT_CONTEXT_ID = "default"
TEMPLATE_HEADER = "X-Terminal-Template-Id"
CHAT_HEADER = "X-Terminal-Chat-Id"
MODEL_HEADER = "X-Terminal-Model-Id"
CONTEXT_HEADER = "X-Terminal-Context-Id"
CONTEXT_ID_ANNOTATION = "openwebui.com/context-id"
CONTEXT_TYPE_LABEL = "openwebui.com/context-type"
CONTEXT_HASH_LABEL = "openwebui.com/context-hash"
def validate_identifier(value: str) -> str:
if not isinstance(value, str) or not value or len(value) > 2048:
raise ValueError("Identifier must contain 1–2048 characters")
if value != value.strip() or any(ord(c) < 32 or ord(c) == 127 for c in value):
raise ValueError("Invalid identifier")
return value
def normalize_context_id(value: str | None) -> str:
context_id = (value or "").strip()
if not context_id:
return DEFAULT_CONTEXT_ID
if len(context_id) > 256:
raise ValueError("context_id is too long")
if any(ord(char) < 32 for char in context_id):
raise ValueError("context_id contains control characters")
if context_id != DEFAULT_CONTEXT_ID and not context_id.startswith(
("chat:", "automation:")
):
raise ValueError("only chat and automation contexts are supported")
return context_id
value = value or DEFAULT_CONTEXT_ID
if value == DEFAULT_CONTEXT_ID:
return value
prefix, separator, identifier = value.partition(":")
if not separator or prefix not in {"user", "chat", "model"}:
raise ValueError("Invalid terminal context")
validate_identifier(identifier)
return value
def context_hash(context_id: str) -> str:
return hashlib.sha256(context_id.encode()).hexdigest()[:12]
def get_terminal_id(template_id: str, context_id: str = DEFAULT_CONTEXT_ID) -> str:
"""Return the stable instance/storage ID for an already resolved template context."""
validate_identifier(template_id)
normalize_context_id(context_id)
encoded = json.dumps([template_id, context_id], separators=(",", ":"), ensure_ascii=True)
return hashlib.sha256(encoded.encode()).hexdigest()[:32]
def terminal_identity(template_id, scope, *, user_id, chat_id=None, model_id=None):
if scope is None:
context_id = DEFAULT_CONTEXT_ID
else:
if scope not in {"user", "chat", "model"}:
raise HTTPException(422, "Invalid template scope")
value = {"user": user_id, "chat": chat_id, "model": model_id}[scope]
if not value:
raise HTTPException(409, f"This terminal requires a {scope}")
try:
context_id = f"{scope}:{validate_identifier(value)}"
except ValueError as exc:
raise HTTPException(422, str(exc)) from exc
return context_id, get_terminal_id(template_id, context_id)
+3 -3
View File
@@ -1,4 +1,4 @@
"""Environment helpers for Open Terminal instances."""
"""Environment helpers for Open Terminal environments."""
import os
from collections.abc import Mapping
@@ -18,7 +18,7 @@ def _format_cpu_count(value: str) -> str:
def build_terminal_env(
policy_env: Mapping[str, Any] | None = None,
template_env: Mapping[str, Any] | None = None,
*,
cpu_limit: str | None = None,
memory_limit: str | None = None,
@@ -31,7 +31,7 @@ def build_terminal_env(
if value:
env[key] = value
for key, value in (policy_env or {}).items():
for key, value in (template_env or {}).items():
key = str(key)
if key in _RESERVED_CONTAINER_ENV or value is None:
continue
+102
View File
@@ -0,0 +1,102 @@
"""Image pull policy shared by every backend.
Values follow Kubernetes: ``Always``, ``IfNotPresent``, and ``Never``. When
``TERMINALS_IMAGE_PULL_POLICY`` is unset, a moving tag (``:latest`` or no tag)
is pulled on every start and anything else is pulled only when missing, so a
host never stays on a stale ``latest`` image.
"""
import asyncio
import logging
import time
# Settings are imported inside functions: config.py validates with normalize_policy at import time.
log = logging.getLogger(__name__)
POLICIES = ("Always", "IfNotPresent", "Never")
_last_pulled: dict[str, float] = {}
_locks: dict[str, asyncio.Lock] = {}
def normalize_policy(value: str) -> str:
"""Return the canonical policy name, or '' for unset. Raises on unknown values."""
value = (value or "").strip()
if not value:
return ""
for policy in POLICIES:
if value.lower() == policy.lower():
return policy
raise ValueError(f"Image pull policy must be one of {', '.join(POLICIES)}")
def split_image(image: str) -> tuple[str, str]:
"""Split an image reference into repository and tag or digest ('' when absent)."""
if "@" in image:
repository, _, digest = image.partition("@")
return repository, digest
name = image.rsplit("/", 1)[-1]
if ":" in name:
repository, _, tag = image.rpartition(":")
return repository, tag
return image, ""
def pull_policy(image: str) -> str:
"""Pull policy for an image: the configured one, else the Kubernetes default."""
from terminals.config import settings
configured = normalize_policy(settings.image_pull_policy)
if configured:
return configured
if "@" in image:
return "IfNotPresent"
_, tag = split_image(image)
return "Always" if tag in ("", "latest") else "IfNotPresent"
async def ensure_docker_image(docker, image: str) -> None:
"""Apply the pull policy before a Docker container is created from ``image``.
``Always`` re-pulls at most once per ``TERMINALS_IMAGE_PULL_INTERVAL_SECONDS``
per image, and falls back to the local copy when the registry is unreachable.
``IfNotPresent`` leaves pulling to container creation, which fetches missing
images. ``Never`` requires the image to exist locally.
"""
from aiodocker.exceptions import DockerError
from terminals.backends.base import ProvisioningError
from terminals.config import settings
policy = pull_policy(image)
if policy == "IfNotPresent":
return
if policy == "Never":
try:
await docker.images.inspect(image)
except DockerError as exc:
if exc.status == 404:
raise ProvisioningError(
f"Image {image!r} is not present and the pull policy is Never"
) from exc
raise
return
lock = _locks.setdefault(image, asyncio.Lock())
async with lock:
last = _last_pulled.get(image)
if last is not None and time.monotonic() - last < settings.image_pull_interval_seconds:
return
repository, tag = split_image(image)
try:
# Without a tag Docker would pull every tag of the repository.
await docker.images.pull(repository, tag=tag or "latest")
log.info("Pulled image %s", image)
except DockerError as exc:
try:
await docker.images.inspect(image)
except DockerError:
raise ProvisioningError(f"Could not pull image {image!r}: {exc.message}") from exc
log.warning("Could not pull image %s, using the local copy: %s", image, exc.message)
_last_pulled[image] = time.monotonic()
+211
View File
@@ -0,0 +1,211 @@
"""Cross-worker locks and cleanup for deterministic terminal environments."""
import asyncio
import hashlib
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import HTTPException
from sqlalchemy import text
from sqlalchemy.exc import DBAPIError
from terminals.db.session import engine
@asynccontextmanager
async def instance_lock(key_name, *, shared=False):
# Do not hold a SQLite write transaction while the backend persists activity.
# The lock file is shared by all workers using this database and is never unlinked.
if engine.dialect.name == "sqlite":
import os
directory = Path(engine.url.database).resolve().parent / ".terminal-locks"
directory.mkdir(parents=True, exist_ok=True)
lock = open(directory / hashlib.sha256(key_name.encode()).hexdigest(), "a+b")
if os.name == "nt":
import msvcrt
if lock.tell() == 0:
lock.write(b"\0")
lock.flush()
lock.seek(0)
acquire = lambda: msvcrt.locking(lock.fileno(), (msvcrt.LK_NBRLCK if shared else msvcrt.LK_NBLCK), 1)
else:
import fcntl
acquire = lambda: fcntl.flock(lock, (fcntl.LOCK_SH if shared else fcntl.LOCK_EX) | fcntl.LOCK_NB)
try:
deadline = asyncio.get_running_loop().time() + 5
while True:
try:
acquire()
break
except (BlockingIOError, OSError):
if asyncio.get_running_loop().time() >= deadline:
raise HTTPException(409, "Environment is busy; retry shortly")
await asyncio.sleep(0.05)
yield
finally:
lock.close()
else:
key = int.from_bytes(
hashlib.sha256(key_name.encode()).digest()[:8], "big", signed=True
)
async with engine.connect() as connection:
async with connection.begin():
await connection.execute(text("SET LOCAL lock_timeout = '5s'"))
try:
await connection.execute(
text("SELECT pg_advisory_xact_lock_shared(:key)" if shared else "SELECT pg_advisory_xact_lock(:key)"), {"key": key}
)
except DBAPIError as exc:
if getattr(exc.orig, "sqlstate", None) == "55P03":
raise HTTPException(
409, "Environment is busy; retry shortly"
) from exc
raise
yield
async def stop_instance(backend, template_id, context_id):
"""Stop by deterministic identity, including resources unknown to this worker."""
from terminals.routers.proxy import close_instance_sessions
from terminals.utils.context import get_terminal_id
await close_instance_sessions(get_terminal_id(template_id, context_id))
from terminals.config import settings
if settings.backend == "docker":
from aiodocker.exceptions import DockerError
docker = await backend._get_docker()
name = backend._container_name(template_id, context_id)
try:
container = await docker.containers.get(name)
await container.delete(force=True)
except DockerError as exc:
if exc.status != 404:
raise
try:
await docker.containers.get(name)
except DockerError as exc:
if exc.status != 404:
raise
else:
raise HTTPException(409, "Environment is still stopping")
else:
from kubernetes_asyncio import client
from terminals.backends.kubernetes import _sanitize_name
api = await backend._ensure_client()
core = client.CoreV1Api(api)
name = _sanitize_name(template_id, context_id)
ns = settings.kubernetes_namespace
if settings.backend == "kubernetes-operator":
await backend._delete_terminal_cr(
template_id, context_id
)
# A deleted CR can still have live dependent pods during garbage collection.
selector = f"openwebui.com/terminal={name}"
else:
selector = None
for method, resource in (
(core.delete_namespaced_pod, name),
(core.delete_namespaced_service, name),
(core.delete_namespaced_secret, name + "-apikey"),
):
try:
await method(resource, ns)
except client.exceptions.ApiException as exc:
if exc.status != 404:
raise
async with asyncio.timeout(120):
while True:
if selector:
pods = (
await core.list_namespaced_pod(ns, label_selector=selector)
).items
else:
try:
pods = [await core.read_namespaced_pod(name, ns)]
except client.exceptions.ApiException as exc:
if exc.status != 404:
raise
pods = []
if not pods:
break
await asyncio.sleep(0.2)
backend.forget(backend._key(template_id, context_id))
async def remove_home(backend, row, spec):
from terminals.config import settings
if settings.backend == "docker":
import shutil
home = backend._home_dir(row.template_id, row.context_id)
if home.exists():
await asyncio.to_thread(shutil.rmtree, home)
elif settings.backend == "kubernetes" and spec.get(
"storage_mode", settings.kubernetes_storage_mode
) in ("shared", "shared-rwo"):
await backend.reset(row.template_id, row.context_id, spec)
else:
from kubernetes_asyncio import client
from terminals.backends.kubernetes import _sanitize_name
core = client.CoreV1Api(await backend._ensure_client())
name = _sanitize_name(row.template_id, row.context_id)
if settings.backend == "kubernetes-operator":
name += "-pvc"
try:
await core.delete_namespaced_persistent_volume_claim(
name, settings.kubernetes_namespace
)
except client.exceptions.ApiException as exc:
if exc.status != 404:
raise
async with asyncio.timeout(120):
while True:
try:
await core.read_namespaced_persistent_volume_claim(
name, settings.kubernetes_namespace
)
except client.exceptions.ApiException as exc:
if exc.status == 404:
break
raise
await asyncio.sleep(0.2)
async def describe_instance(backend, row):
status = await backend.status(f"terminal-{row.id}")
return {
"id": row.id,
"template_id": row.template_id,
"context_id": row.context_id,
"status": "stopped" if status == "missing" else status,
"created_at": row.created_at,
"updated_at": row.updated_at,
"last_active_at": (row.data or {}).get("activity", {}).get("last_seen_at"),
}
async def change_instance(backend, template_id, context_id, action):
from terminals.db.session import async_session
from terminals.models.template import TemplateLifecycleState
from terminals.utils.context import get_terminal_id
from terminals.utils.template_specs import resolve_template_spec
key = get_terminal_id(template_id, context_id)
async with instance_lock("template:" + template_id, shared=True), instance_lock(key):
spec = await resolve_template_spec(template_id)
async with async_session() as session:
row = await session.get(TemplateLifecycleState, key)
if row is None:
if action == "delete":
return
raise HTTPException(404, "Environment has not been created")
await stop_instance(backend, row.template_id, row.context_id)
if action == "reset":
await backend.reset(template_id, context_id, spec)
elif action == "delete":
await remove_home(backend, row, spec)
await session.delete(row)
await session.commit()
+7
View File
@@ -0,0 +1,7 @@
"""Kubernetes label formatting shared by the backends and operator."""
import re
def template_label(template_id: str) -> str:
return re.sub(r"[^a-z0-9-]", "-", template_id.lower()).strip("-")[:20]
+1 -1
View File
@@ -1,4 +1,4 @@
"""Resolve administrator-defined networking configuration for a policy."""
"""Resolve administrator-defined networking configuration for a template."""
from terminals.backends.base import ProvisioningError
from terminals.config import settings
-37
View File
@@ -1,37 +0,0 @@
"""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 = {}
image = settings.image
if settings.backend in ("kubernetes", "kubernetes-operator"):
image = settings.effective_kubernetes_image
if image:
defaults["image"] = 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 {})
@@ -1,4 +1,4 @@
"""Helpers for recurring policy lifecycle work."""
"""Helpers for recurring template lifecycle work."""
from __future__ import annotations
@@ -10,7 +10,7 @@ from croniter import croniter
from sqlalchemy import select
from terminals.db.session import async_session
from terminals.utils.context import DEFAULT_CONTEXT_ID, normalize_context_id
from terminals.utils.context import DEFAULT_CONTEXT_ID, normalize_context_id, get_terminal_id
RESET_KEY = "reset"
ACTIVITY_KEY = "activity"
@@ -118,23 +118,21 @@ def next_reset_after(
async def reset_due_for(
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> bool:
"""Return True if this user/policy/context has a reset due."""
"""Return True if this template/context has a reset due."""
if async_session is None:
return False
now = _utc_now()
context_id = normalize_context_id(context_id)
from terminals.models.policy import PolicyLifecycle, PolicyLifecycleState
from terminals.models.template import TemplateLifecycle, TemplateLifecycleState
async with async_session() as session:
lifecycle_row = await session.execute(
select(PolicyLifecycle).where(PolicyLifecycle.policy_id == policy_id)
select(TemplateLifecycle).where(TemplateLifecycle.template_id == template_id)
)
lifecycle = lifecycle_row.scalar_one_or_none()
lifecycle_data = dict(lifecycle.data or {}) if lifecycle else {}
@@ -146,22 +144,14 @@ async def reset_due_for(
timezone_name = reset_config.get("timezone") or "UTC"
state_row = await session.execute(
select(PolicyLifecycleState).where(
PolicyLifecycleState.user_id == user_id,
PolicyLifecycleState.policy_id == policy_id,
PolicyLifecycleState.context_id == context_id,
select(TemplateLifecycleState).where(
TemplateLifecycleState.template_id == template_id,
TemplateLifecycleState.context_id == context_id,
)
)
state = state_row.scalar_one_or_none()
if state is None:
state = PolicyLifecycleState(
id=f"{user_id}:{policy_id}:{context_id}",
user_id=user_id,
policy_id=policy_id,
context_id=context_id,
data={},
)
session.add(state)
return False
data = dict(state.data or {})
reset = dict(data.get(RESET_KEY) or {})
@@ -183,10 +173,8 @@ async def reset_due_for(
async def mark_reset_applied(
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
spec: dict | None = None,
) -> None:
if async_session is None:
return
@@ -194,11 +182,11 @@ async def mark_reset_applied(
now = _utc_now()
context_id = normalize_context_id(context_id)
from terminals.models.policy import PolicyLifecycle, PolicyLifecycleState
from terminals.models.template import TemplateLifecycle, TemplateLifecycleState
async with async_session() as session:
lifecycle_row = await session.execute(
select(PolicyLifecycle).where(PolicyLifecycle.policy_id == policy_id)
select(TemplateLifecycle).where(TemplateLifecycle.template_id == template_id)
)
lifecycle = lifecycle_row.scalar_one_or_none()
lifecycle_data = dict(lifecycle.data or {}) if lifecycle else {}
@@ -210,22 +198,14 @@ async def mark_reset_applied(
timezone_name = reset_config.get("timezone") or "UTC"
state_row = await session.execute(
select(PolicyLifecycleState).where(
PolicyLifecycleState.user_id == user_id,
PolicyLifecycleState.policy_id == policy_id,
PolicyLifecycleState.context_id == context_id,
select(TemplateLifecycleState).where(
TemplateLifecycleState.template_id == template_id,
TemplateLifecycleState.context_id == context_id,
)
)
state = state_row.scalar_one_or_none()
if state is None:
state = PolicyLifecycleState(
id=f"{user_id}:{policy_id}:{context_id}",
user_id=user_id,
policy_id=policy_id,
context_id=context_id,
data={},
)
session.add(state)
return False
data = dict(state.data or {})
reset = dict(data.get(RESET_KEY) or {})
@@ -247,8 +227,7 @@ async def mark_reset_applied(
async def mark_terminal_active(
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
) -> None:
"""Persist a cross-worker activity heartbeat for a terminal."""
@@ -258,26 +237,18 @@ async def mark_terminal_active(
now = _utc_now()
context_id = normalize_context_id(context_id)
from terminals.models.policy import PolicyLifecycleState
from terminals.models.template import TemplateLifecycleState
async with async_session() as session:
state_row = await session.execute(
select(PolicyLifecycleState).where(
PolicyLifecycleState.user_id == user_id,
PolicyLifecycleState.policy_id == policy_id,
PolicyLifecycleState.context_id == context_id,
select(TemplateLifecycleState).where(
TemplateLifecycleState.template_id == template_id,
TemplateLifecycleState.context_id == context_id,
)
)
state = state_row.scalar_one_or_none()
if state is None:
state = PolicyLifecycleState(
id=f"{user_id}:{policy_id}:{context_id}",
user_id=user_id,
policy_id=policy_id,
context_id=context_id,
data={},
)
session.add(state)
return False
data = dict(state.data or {})
data[ACTIVITY_KEY] = {"last_seen_at": _iso(now)}
@@ -286,8 +257,7 @@ async def mark_terminal_active(
async def terminal_last_active_at(
user_id: str,
policy_id: str = "default",
template_id: str,
context_id: str = DEFAULT_CONTEXT_ID,
) -> datetime | None:
"""Return the latest persisted activity heartbeat for a terminal."""
@@ -296,14 +266,13 @@ async def terminal_last_active_at(
context_id = normalize_context_id(context_id)
from terminals.models.policy import PolicyLifecycleState
from terminals.models.template import TemplateLifecycleState
async with async_session() as session:
state_row = await session.execute(
select(PolicyLifecycleState).where(
PolicyLifecycleState.user_id == user_id,
PolicyLifecycleState.policy_id == policy_id,
PolicyLifecycleState.context_id == context_id,
select(TemplateLifecycleState).where(
TemplateLifecycleState.template_id == template_id,
TemplateLifecycleState.context_id == context_id,
)
)
state = state_row.scalar_one_or_none()
@@ -312,31 +281,31 @@ async def terminal_last_active_at(
return _parse_iso(activity.get("last_seen_at"))
async def get_lifecycle_data(policy_id: str) -> dict:
"""Return policy-level lifecycle configuration."""
async def get_lifecycle_data(template_id: str) -> dict:
"""Return template-level lifecycle configuration."""
if async_session is None:
return {}
from terminals.models.policy import PolicyLifecycle
from terminals.models.template import TemplateLifecycle
async with async_session() as session:
row = await session.execute(
select(PolicyLifecycle).where(PolicyLifecycle.policy_id == policy_id)
select(TemplateLifecycle).where(TemplateLifecycle.template_id == template_id)
)
lifecycle = row.scalar_one_or_none()
return deepcopy(lifecycle.data or {}) if lifecycle else {}
async def upsert_lifecycle_data(policy_id: str, data: dict) -> dict:
"""Create or update policy-level lifecycle configuration."""
async def upsert_lifecycle_data(template_id: str, data: dict) -> dict:
"""Create or update template-level lifecycle configuration."""
if async_session is None:
return {}
from terminals.models.policy import PolicyLifecycle
from terminals.models.template import TemplateLifecycle
async with async_session() as session:
row = await session.execute(
select(PolicyLifecycle).where(PolicyLifecycle.policy_id == policy_id)
select(TemplateLifecycle).where(TemplateLifecycle.template_id == template_id)
)
lifecycle = row.scalar_one_or_none()
now = _utc_now()
@@ -345,9 +314,9 @@ async def upsert_lifecycle_data(policy_id: str, data: dict) -> dict:
lifecycle.data = data
lifecycle.updated_at = now
else:
lifecycle = PolicyLifecycle(
id=policy_id,
policy_id=policy_id,
lifecycle = TemplateLifecycle(
id=template_id,
template_id=template_id,
data=data,
created_at=now,
updated_at=now,
@@ -356,3 +325,23 @@ async def upsert_lifecycle_data(policy_id: str, data: dict) -> dict:
await session.commit()
return deepcopy(lifecycle.data or {})
async def ensure_terminal_state(template_id: str, context_id: str):
"""Called under the instance lock before any persistent resources are created."""
from sqlalchemy.exc import IntegrityError
from terminals.models.template import TemplateLifecycleState
key = get_terminal_id(template_id, context_id)
async with async_session() as session:
row = await session.get(TemplateLifecycleState, key)
if row is None:
row = TemplateLifecycleState(id=key, template_id=template_id, context_id=context_id, data={})
session.add(row)
try:
await session.commit()
except IntegrityError:
await session.rollback()
row = await session.get(TemplateLifecycleState, key)
if row is None:
raise
return row
+39
View File
@@ -0,0 +1,39 @@
"""Shared helpers for resolved terminal template specs."""
from terminals.config import settings
from terminals.db.session import async_session
from terminals.utils.context import validate_identifier
class TemplateNotFoundError(Exception):
"""Raised when a template does not exist."""
def merge_template_defaults(template_data: dict) -> dict:
"""Merge env var defaults with template overrides."""
defaults = {}
image = settings.image
if settings.backend in ("kubernetes", "kubernetes-operator"):
image = settings.effective_kubernetes_image
if image:
defaults["image"] = image
return {**defaults, **{k: v for k, v in template_data.items() if v is not None}}
async def resolve_template_spec(template_id: str) -> dict:
"""Look up a template by ID and merge its configuration with server defaults."""
validate_identifier(template_id)
if async_session is None:
raise RuntimeError("A database is required to resolve templates")
from sqlalchemy import select
from terminals.models.template import Template
async with async_session() as session:
row = await session.execute(select(Template).where(Template.id == template_id))
template = row.scalar_one_or_none()
if template is None:
raise TemplateNotFoundError(template_id)
return merge_template_defaults(template.data or {})
Generated
+1 -1
View File
@@ -1222,7 +1222,7 @@ wheels = [
[[package]]
name = "terminals"
version = "0.3.3"
version = "0.4.0"
source = { editable = "." }
dependencies = [
{ name = "aiodocker" },