From 25bd3594de1c0af6365966491b7960e9478c8905 Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Tue, 10 Nov 2026 23:09:00 +0900 Subject: [PATCH] refac --- .github/workflows/docker-build.yml | 4 +- README.md | 146 +++-- docs/openshift.md | 34 +- manifests/terminal-crd.yaml | 19 +- operator/Dockerfile | 5 +- operator/handler.py | 39 +- pyproject.toml | 2 +- terminals/backends/base.py | 610 ++++-------------- terminals/backends/docker.py | 178 ++--- terminals/backends/kubernetes.py | 255 ++------ terminals/backends/kubernetes_operator.py | 473 ++++---------- terminals/cli.py | 5 +- terminals/config.py | 16 +- terminals/db/session.py | 14 + terminals/db/urls.py | 2 + terminals/frontend/src/routes/+page.svelte | 587 ++--------------- terminals/main.py | 12 +- terminals/migrations/env.py | 13 +- .../migrations/versions/004_templates.py | 53 ++ terminals/models/{policy.py => template.py} | 36 +- terminals/routers/auth.py | 154 +---- terminals/routers/lifecycle.py | 137 ---- terminals/routers/policy.py | 315 --------- terminals/routers/proxy.py | 428 +++--------- terminals/routers/templates.py | 310 +++++++++ terminals/routers/terminals.py | 27 + terminals/utils/context.py | 60 +- terminals/utils/env.py | 6 +- terminals/utils/image_pull.py | 102 +++ terminals/utils/instances.py | 211 ++++++ terminals/utils/kubernetes_labels.py | 7 + terminals/utils/network_profiles.py | 2 +- terminals/utils/policy_specs.py | 37 -- ...icy_lifecycle.py => template_lifecycle.py} | 129 ++-- terminals/utils/template_specs.py | 39 ++ uv.lock | 2 +- 36 files changed, 1591 insertions(+), 2878 deletions(-) create mode 100644 terminals/migrations/versions/004_templates.py rename terminals/models/{policy.py => template.py} (55%) delete mode 100644 terminals/routers/lifecycle.py delete mode 100644 terminals/routers/policy.py create mode 100644 terminals/routers/templates.py create mode 100644 terminals/routers/terminals.py create mode 100644 terminals/utils/image_pull.py create mode 100644 terminals/utils/instances.py create mode 100644 terminals/utils/kubernetes_labels.py delete mode 100644 terminals/utils/policy_specs.py rename terminals/utils/{policy_lifecycle.py => template_lifecycle.py} (71%) create mode 100644 terminals/utils/template_specs.py diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index 7d2059e..016775a 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -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 \ No newline at end of file + make_latest: true diff --git a/README.md b/README.md index 5601b5b..f42f3bf 100644 --- a/README.md +++ b/README.md @@ -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.
Try a terminal directly with curl -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/` 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/` | `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 diff --git a/docs/openshift.md b/docs/openshift.md index 312db59..d576cdb 100644 --- a/docs/openshift.md +++ b/docs/openshift.md @@ -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. diff --git a/manifests/terminal-crd.yaml b/manifests/terminal-crd.yaml index 540357d..ee05b54 100644 --- a/manifests/terminal-crd.yaml +++ b/manifests/terminal-crd.yaml @@ -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:", and "automation:". 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 diff --git a/operator/Dockerfile b/operator/Dockerfile index cb8e74a..f62dca8 100644 --- a/operator/Dockerfile +++ b/operator/Dockerfile @@ -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 diff --git a/operator/handler.py b/operator/handler.py index 894153f..bc124ae 100644 --- a/operator/handler.py +++ b/operator/handler.py @@ -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) diff --git a/pyproject.toml b/pyproject.toml index 02cbb5e..e7dd612 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 = [ diff --git a/terminals/backends/base.py b/terminals/backends/base.py index 56001aa..40bfd4d 100644 --- a/terminals/backends/base.py +++ b/terminals/backends/base.py @@ -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) diff --git a/terminals/backends/docker.py b/terminals/backends/docker.py index 9d82f0a..08e85d9 100644 --- a/terminals/backends/docker.py +++ b/terminals/backends/docker.py @@ -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: diff --git a/terminals/backends/kubernetes.py b/terminals/backends/kubernetes.py index f1de446..b9e938c 100644 --- a/terminals/backends/kubernetes.py +++ b/terminals/backends/kubernetes.py @@ -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: diff --git a/terminals/backends/kubernetes_operator.py b/terminals/backends/kubernetes_operator.py index def3828..a7359e6 100644 --- a/terminals/backends/kubernetes_operator.py +++ b/terminals/backends/kubernetes_operator.py @@ -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) diff --git a/terminals/cli.py b/terminals/cli.py index a79f27d..4d8e545 100644 --- a/terminals/cli.py +++ b/terminals/cli.py @@ -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.") diff --git a/terminals/config.py b/terminals/config.py index 9be2fb3..5e16198 100644 --- a/terminals/config.py +++ b/terminals/config.py @@ -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 diff --git a/terminals/db/session.py b/terminals/db/session.py index 4b55aca..0beebe4 100644 --- a/terminals/db/session.py +++ b/terminals/db/session.py @@ -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") diff --git a/terminals/db/urls.py b/terminals/db/urls.py index 1a37ca9..4307df7 100644 --- a/terminals/db/urls.py +++ b/terminals/db/urls.py @@ -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://"): diff --git a/terminals/frontend/src/routes/+page.svelte b/terminals/frontend/src/routes/+page.svelte index 67ce745..9d560ab 100644 --- a/terminals/frontend/src/routes/+page.svelte +++ b/terminals/frontend/src/routes/+page.svelte @@ -1,540 +1,67 @@ - - - Terminals - - - - - -
-
- - -
-
-

Terminals

-
- {status?.backend ?? '-'} - {status?.active_terminals ?? terminals.length} active - {status?.policy_count ?? policies.length} policies -
-
- saveToken(event.currentTarget.value)} - /> - -
-
- -
-
-

Active terminals

-
- {#if terminals.length === 0} -
No active terminals.
- {:else} -
- - - - - - - - - - - - - {#each terminals as terminal} - - - - - - - - - {/each} - -
UserPolicyStatus
{terminal.user_id} - {policies.some((policy) => policy.id === terminal.policy_id) - ? terminal.policy_id - : 'Service defaults'} - - - - {terminal.status} - - - -
-
- {/if} -
- -
-

User data

-

Persisted terminal files, including users with no active terminals.

- {#if status && status.backend !== 'docker'} -

Shared storage requires separate cleanup and is not listed here.

- {/if} - {#if usersWithData.length === 0} -
No user data found.
- {:else} - - - - - - {#each usersWithData as userId} - - - - - {/each} - -
UserAction
{userId} - -
- {/if} -
- -
-
-

Policies

- -
- {#if policies.length === 0} -
No policies configured.
- {:else} -
- - - - - - - - - - - - - - - {#each policies as policy} - - - - - - - - - - - {/each} - -
IDCPUMemoryMode
{policy.id}{policyValue(policy, 'cpu_limit')}{policyValue(policy, 'memory_limit')}{restrictedLabel(policy)} -
- - - -
-
-
- {/if} -
- - {#if notice} -
{notice}
- {/if} - {#if error} -
{error}
- {/if} -
-
-
- -{#if editingPolicy} -
-
-
-

{editingPolicy.existing ? 'Edit policy' : 'Add policy'}

- -
- -
-
Policy
-
- - - - - - - - - - - - - -
-
Lifecycle
-
- - -
-
- - -
-
-
-
-{/if} +Terminals +
+

Terminals 0.4.0

+
{event.preventDefault(); sessionStorage.setItem('terminals-key', token); void run(load);}}>
+ {#if error}{/if} + {#if editing}
+

{editing.fresh ? 'New terminal' : 'Configure terminal'}

+ + +