diff --git a/.agents/skills/build-openshell-mxc-windows/SKILL.md b/.agents/skills/build-openshell-mxc-windows/SKILL.md index d61fc555e9..954fcedf2f 100644 --- a/.agents/skills/build-openshell-mxc-windows/SKILL.md +++ b/.agents/skills/build-openshell-mxc-windows/SKILL.md @@ -231,7 +231,7 @@ crypto dependency builds. | `windows:build:arm64` | Release-builds `openshell-gateway.exe` and `openshell.exe` for ARM64. | | `windows:test:x64` | Runs native x64 workspace tests with `--no-fail-fast`, excluding unsupported Windows packages as top-level workspace targets. | | `windows:test:arm64` | Runs native ARM64 workspace tests with `--no-fail-fast` and the same package exclusions. Rejects non-ARM64 hosts. | -| `windows:test:unsupported:x64` | Re-runs focused `openshell-server` tests for unsupported Windows driver behavior. | +| `windows:test:unsupported:x64` | Re-runs focused `openshell-gateway` tests for unsupported Windows driver behavior. | | `windows:test:unsupported:arm64` | Re-runs the same focused contracts natively on ARM64. Rejects non-ARM64 hosts. | | `windows:artifacts` | Reports size and SHA256 for release artifacts that exist. | | `windows:ci` | Runs the full ordered x64-host Windows CI lane, plus ARM64 check/build when not skipped. | @@ -248,10 +248,10 @@ Windows must continue to reject unsupported compute drivers clearly. | Driver | Windows build behavior | Runtime behavior | |---|---|---| -| Docker | Driver crate excluded; server config contract retained. | Gateway construction returns unsupported. | -| Kubernetes | Driver crate excluded; server config contract retained. | Gateway construction returns unsupported. | -| Podman | Driver crate excluded; server config contract retained. | Gateway construction returns unsupported. | -| VM | Driver crate excluded from workspace validation. | Gateway construction returns unsupported. | +| Docker | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | +| Kubernetes | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | +| Podman | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | +| VM | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | The focused contract tasks for either native architecture run: diff --git a/.agents/skills/build-openshell-mxc-windows/reference.md b/.agents/skills/build-openshell-mxc-windows/reference.md index 4a5f2668a1..16b9a48586 100644 --- a/.agents/skills/build-openshell-mxc-windows/reference.md +++ b/.agents/skills/build-openshell-mxc-windows/reference.md @@ -85,7 +85,7 @@ Windows is a build target only. These runtimes remain unsupported: Rules: -- Keep config/library stubs where the gateway needs them. +- Keep registration stubs in the gateway composition crate where the gateway needs them. - Return clear unsupported errors at runtime. - Do not build standalone Windows driver binaries. - Do not add Docker Desktop, WSL, Hyper-V, Podman machine, Podman Desktop, or @@ -180,7 +180,7 @@ blocked dependency. ### Focused tests report many filtered-out tests This is expected for `windows:test:unsupported:x64`. Cargo runs one named test -and filters the other `openshell-server` tests. Report these as filtered, not +and filters the other `openshell-gateway` tests. Report these as filtered, not ignored. ## Reporting Counts diff --git a/.agents/skills/debug-openshell-cluster/SKILL.md b/.agents/skills/debug-openshell-cluster/SKILL.md index 86395af148..47588b1aeb 100644 --- a/.agents/skills/debug-openshell-cluster/SKILL.md +++ b/.agents/skills/debug-openshell-cluster/SKILL.md @@ -19,8 +19,9 @@ The target deployment flow is: 4. The CLI registers a reachable gateway endpoint with `openshell gateway add`. 5. The gateway creates sandboxes through the selected compute driver. -The standard gateway binary explicitly installs its compiled Docker, Podman, -Kubernetes, and VM registrations at startup. With no configured driver, the +The `openshell-gateway` composition crate explicitly installs its compiled +Docker, Podman, Kubernetes, and VM registrations at startup; `openshell-server` +does not link compute-driver crates. With no configured driver, the gateway probes only installed registrations in priority order (Kubernetes, Podman, then Docker); VM has no probe and remains opt-in. A custom gateway binary may install a different set, so confirm the binary's registered drivers @@ -475,6 +476,26 @@ helm -n openshell get values openshell | grep sandboxNamespace Then inspect sandbox resources in that namespace. +For a split release, the gateway values should have +`workspaceResources.enabled=false`, and the target namespace should contain a +separate `openshell-workspace` release: + +```bash +helm -n openshell get values openshell | grep -A2 workspaceResources +helm -n status openshell-workspace +kubectl -n get serviceaccount,role,rolebinding,networkpolicy \ + -l app.kubernetes.io/instance=openshell-workspace +kubectl auth can-i create sandboxes.agents.x-k8s.io \ + --namespace \ + --as system:serviceaccount:openshell:openshell +``` + +If the gateway cannot create or watch sandboxes, verify the workspace +RoleBinding subject matches the gateway ServiceAccount name and namespace. +If SSH relay connections fail, verify the workspace NetworkPolicy selects the +gateway's actual `app.kubernetes.io/name` and +`app.kubernetes.io/instance` labels. + Check the configured sandbox service account when TokenReview bootstrap or sandbox registration fails. Helm creates a dedicated sandbox service account by default and writes it to `[openshell.drivers.kubernetes].service_account_name`; diff --git a/.agents/skills/openshell-cli/SKILL.md b/.agents/skills/openshell-cli/SKILL.md index a1ed3bef9b..f268527956 100644 --- a/.agents/skills/openshell-cli/SKILL.md +++ b/.agents/skills/openshell-cli/SKILL.md @@ -242,6 +242,7 @@ Key flags: - `--gpu [COUNT]`: Request the driver's default GPU selection or a specific GPU count - `--cpu`, `--memory`: Set per-sandbox compute sizing. Docker/Podman apply limits; Kubernetes applies matching requests and limits. - `--driver-config-json`: Pass experimental driver-specific sandbox configuration +- `--template NAME`: Create from a named sandbox workload template. Conflicts with inline workload flags such as `--from`, `--gpu`, `--cpu`, `--memory`, `--env`, and `--driver-config-json`. - `--label KEY=VALUE`: Add labels for later selection (repeatable) - `--env KEY=VALUE`: Set non-secret sandbox environment variables (repeatable); use `--provider` for credentials - `--tty`: Allocate a retained PTY for the canonical main process @@ -262,6 +263,45 @@ Do not combine `--upload` with a trailing main command. Uploads currently finish after the canonical process starts; create a scratch sandbox and use `sandbox exec`, or build the files into the image. +Create from a reusable workload template when several sandboxes should share +image, environment, sizing, or driver-specific configuration: + +```bash +openshell sandbox template create gpu-kata \ + --image ghcr.io/nvidia/openshell-community/sandboxes/python:latest \ + --cpu 2 \ + --memory 4Gi \ + --gpu 1 \ + --driver-config-json '{"kubernetes":{"pod":{"node_selector":{"pool":"gpu"}}}}' + +openshell sandbox create --name my-sandbox --template gpu-kata --provider my-github -- claude +``` + +Direct `sandbox create --driver-config-json` remains valid for one-off +creates. Put driver config on a template only when it should be reused. + +### Manage sandbox workload templates + +```bash +openshell sandbox template create gpu-kata \ + --image ghcr.io/nvidia/openshell-community/sandboxes/python:latest \ + --cpu 2 \ + --memory 4Gi \ + --gpu 1 \ + --label team=runtime \ + --env FEATURE_FLAG=on +openshell sandbox template list +openshell sandbox template list --label-selector team=runtime +openshell sandbox template list --all-workspaces --output json +openshell sandbox template get gpu-kata +openshell sandbox template delete gpu-kata +``` + +Template `--image` accepts an OCI image reference. If omitted, the gateway +applies its default sandbox image when creating a sandbox from the template. +Create-time policy, providers, labels, uploads, forwarding, editor launch, and +the initial command stay on `sandbox create`. + ### List and inspect sandboxes ```bash @@ -384,7 +424,7 @@ the operation that removes retained state. This is the most important multi-step workflow. It enables a tight feedback cycle where sandbox policy is refined based on observed activity. -**Key concept**: Policies have static fields (immutable after creation: `filesystem_policy`, `landlock`, `process`) and two dynamic fields: `network_policies` and `network_middlewares`. Both dynamic fields can be updated without recreating the sandbox when the selected compute driver supports live policy updates. MXC rejects live policy replacement and merge updates; delete and recreate an MXC sandbox instead. +**Key concept**: Policies have static fields (immutable after creation: `filesystem_policy`, `landlock`, `process`) and two dynamic fields: `network_policies` and `network_middlewares`. Both dynamic fields can be updated without recreating the sandbox when the selected compute driver supports live policy updates. Drivers without the standard supervisor fetch revisions through the sandbox configuration API and report whether they loaded them. An endpoint with omitted `protocol` retains explicit-proxy behavior. Explicit `protocol: tcp` requests policy DNS and transparent TCP and currently requires @@ -454,7 +494,7 @@ Edit `current-policy.yaml` to allow the blocked actions. **For policy content au - Binary matching patterns - Ordered `network_middlewares`, host selection, HTTP and WebSocket bindings, and `fail_open` or `fail_closed` behavior -`network_policies` and `network_middlewares` can be modified at runtime when the selected compute driver supports live policy updates. MXC rejects live policy replacement and merge updates; delete and recreate an MXC sandbox instead. If `filesystem_policy`, `landlock`, or `process` need changes, the sandbox must be recreated. Built-in middleware such as `openshell/regex` needs no gateway registration. An operator-run middleware must already be registered under `[[openshell.supervisor.middleware]]`; changing that static registration requires a gateway restart. +`network_policies` and `network_middlewares` can be modified at runtime when the selected compute driver supports live policy updates. Use `--wait` to verify that the active runtime loaded the revision; do not infer enforcement from the gateway accepting the update. If `filesystem_policy`, `landlock`, or `process` need changes, the sandbox must be recreated. Built-in middleware such as `openshell/regex` needs no gateway registration. An operator-run middleware must already be registered under `[[openshell.supervisor.middleware]]`; changing that static registration requires a gateway restart. Middleware can inspect parsed HTTP request bodies and complete client-to-upstream WebSocket text messages over both `ws://` and `wss://` when the implementation advertises the matching binding. The built-in `openshell/regex` advertises both bindings and applies its fixed patterns to UTF-8 text. A host-matched HTTP-only attachment can inspect the upgrade GET but does not join the WebSocket chain; look for `binding_not_selected` coverage. Binary messages pass under both `on_error` modes and active stages emit `unsupported_message_type` coverage; upstream-to-client messages remain uninspected. A broken fail-open WebSocket stage is disabled for the rest of that connection; inspect sandbox OCSF logs for `openshell.middleware.websocket_stage_disabled`. @@ -772,7 +812,7 @@ The CLI help is always authoritative. If the help output contradicts this skill, ```bash $ openshell sandbox --help -# Shows: create, get, list, stop, start, delete, exec, connect, upload, download, ssh-config, provider +# Shows: create, get, list, stop, start, delete, exec, connect, upload, download, ssh-config, provider, template $ openshell sandbox upload --help # Shows: positional arguments (name, path, dest), usage examples @@ -793,6 +833,8 @@ $ openshell sandbox upload --help | Create sandbox with tool | `openshell sandbox create -- claude` | | Create sandbox with GPUs | `openshell sandbox create --gpu 1` | | Create with custom policy | `openshell sandbox create --policy ./p.yaml` | +| Create from template | `openshell sandbox create --template gpu-kata` | +| Create workload template | `openshell sandbox template create gpu-kata --image python:3.12` | | Connect to sandbox | `openshell sandbox connect ` | | Stop sandbox compute | `openshell sandbox stop [name]` | | Start sandbox compute | `openshell sandbox start [name]` | diff --git a/.agents/skills/openshell-cli/cli-reference.md b/.agents/skills/openshell-cli/cli-reference.md index f53289b89f..2f1065c234 100644 --- a/.agents/skills/openshell-cli/cli-reference.md +++ b/.agents/skills/openshell-cli/cli-reference.md @@ -12,6 +12,7 @@ Quick-reference for the `openshell` command-line interface. For workflow guidanc | `-g`, `--gateway ` | Gateway to operate on. Also settable via `OPENSHELL_GATEWAY` env var. Falls back to active gateway in `~/.config/openshell/active_gateway`. | | `--gateway-endpoint ` | Connect directly to a gateway endpoint without looking up stored metadata. Also settable via `OPENSHELL_GATEWAY_ENDPOINT`. | | `--gateway-insecure` | Skip TLS certificate verification. Also settable via `OPENSHELL_GATEWAY_INSECURE`; use only for trusted development endpoints. | +| `--color ` | `auto` (default), `always`, or `never`. `auto` decides per stream, so a redirected stream is plain text while a stream still on the terminal stays styled. Covers tables, `-v` log lines, progress spinners, prompts, and error messages. Also settable via `OPENSHELL_COLOR`. | ## Environment Variables @@ -20,6 +21,9 @@ Quick-reference for the `openshell` command-line interface. For workflow guidanc | `OPENSHELL_GATEWAY` | Override active gateway name (same as `--gateway`) | | `OPENSHELL_GATEWAY_ENDPOINT` | Connect directly to a gateway endpoint (same as `--gateway-endpoint`) | | `OPENSHELL_GATEWAY_INSECURE` | Skip TLS verification when set (same as `--gateway-insecure`) | +| `OPENSHELL_COLOR` | When to colorize output: `auto`, `always`, `never` (same as `--color`) | +| `NO_COLOR` | Disable colorized output when set to any non-empty value ([no-color.org](https://no-color.org)) | +| `FORCE_COLOR` | Force colorized output when set to any non-empty value ([force-color.org](https://force-color.org)) | | `OPENSHELL_SANDBOX_POLICY` | Path to default sandbox policy YAML (fallback when `--policy` is not provided) | | `OPENSHELL_COMMUNITY_REGISTRY` | Override the community sandbox image registry prefix used by `sandbox create --from ` | | `OPENSHELL_THEME` | TUI theme: `auto`, `dark`, or `light` | @@ -56,10 +60,15 @@ openshell │ ├── upload [dest] │ ├── download [dest] │ ├── ssh-config [name] -│ └── provider -│ ├── list [name] [-o table|yaml|json] -│ ├── attach -│ └── detach +│ ├── provider +│ │ ├── list [name] [-o table|yaml|json] +│ │ ├── attach +│ │ └── detach +│ └── template +│ ├── create [opts] +│ ├── get +│ ├── list [opts] +│ └── delete ... ├── forward │ ├── start [name] [-d] │ ├── stop [name] @@ -239,6 +248,7 @@ process result immediately when it exits. Foreground creation declares one expected main-process SSH attachment; cleanup finalizes after that connection drains and closes naturally. | `--driver-config-json ` | Experimental driver-keyed configuration object | +| `--template ` | Create from a named sandbox workload template | | `--provider ` | Provider to attach (repeatable) | | `--policy ` | Custom policy YAML; overrides the built-in default and `OPENSHELL_SANDBOX_POLICY` | | `--forward <[BIND:]PORT>` | Start a local port forward and keep the sandbox alive | @@ -257,6 +267,57 @@ currently complete after the canonical process starts. Create the default scratch sandbox, upload files, then use `sandbox exec`, or build the files into the image. +`--template` uses the named template workload, so it conflicts with inline +workload flags: `--from`, `--gpu`, `--cpu`, `--memory`, `--env`, and +`--driver-config-json`. Direct `sandbox create --driver-config-json` remains +valid when `--template` is not set. + +### `openshell sandbox template create NAME [OPTIONS]` + +Create a reusable sandbox workload template. Templates hold image, +environment, resource, startup, and driver-specific configuration for later +`sandbox create --template NAME` calls. + +| Flag | Description | +|------|-------------| +| `--image ` | OCI image reference; when omitted, the gateway default image is applied at sandbox create time | +| `--env ` | Set a non-secret template workload environment variable (repeatable) | +| `--cpu ` | CPU limit for sandboxes created from the template | +| `--memory ` | Memory limit for sandboxes created from the template | +| `--gpu [COUNT]` | Request the driver's default GPU selection or a specific GPU count for sandboxes created from the template | +| `--driver-config-json ` | Experimental driver-keyed configuration object owned by the template | +| `--ready-within ` | Target startup readiness duration, for example `30s`, `5m`, or `1h` | +| `--max-burst ` | Maximum startup burst associated with this template | +| `--label ` | Attach a template label (repeatable) | +| `--annotation ` | Attach a template annotation (repeatable) | +| `--output table|yaml|json` | Output format | + +### `openshell sandbox template get NAME` + +Show a sandbox workload template. + +| Flag | Description | +|------|-------------| +| `--output table|yaml|json` | Output format | + +### `openshell sandbox template list` + +List sandbox workload templates. + +| Flag | Default | Description | +|------|---------|-------------| +| `--limit ` | 100 | Maximum templates | +| `--offset ` | 0 | Pagination offset | +| `--label-selector ` | empty | Filter templates by labels | +| `--names` | false | Print only template names | +| `--all-workspaces` | false | List templates across all workspaces; requires platform-admin permissions | +| `--output table|yaml|json` | `table` | Output format | + +### `openshell sandbox template delete NAME...` + +Delete one or more sandbox workload templates by name. Existing sandboxes +created from a template are not deleted. + ### `openshell sandbox get [name]` Show sandbox details and the active policy. Metadata identifies sandbox or global policy source and the corresponding revision. The name defaults to the last-used sandbox. @@ -413,7 +474,7 @@ The sandbox name defaults to the last-used sandbox. ### `openshell policy update [name]` -Incrementally merge live network policy changes into the current sandbox policy when the selected compute driver supports live updates. Multiple flags in one invocation are applied as one atomic batch and create at most one new revision. MXC rejects live policy merges; delete and recreate an MXC sandbox instead. +Incrementally merge live network policy changes into the current sandbox policy when the selected compute driver supports live updates. Multiple flags in one invocation are applied as one atomic batch and create at most one new revision. Use `--wait` to verify that the active runtime loaded the new revision. | Flag | Default | Description | |------|---------|-------------| @@ -443,7 +504,7 @@ Notes: ### `openshell policy set [name] --policy ` -Replace the full policy on a live sandbox when the selected compute driver supports live updates. Only the dynamic `network_policies` field can be changed at runtime. MXC rejects live policy replacement; delete and recreate an MXC sandbox instead. +Replace the full policy on a live sandbox when the selected compute driver supports live updates. Only dynamic policy fields can be changed at runtime. Use `--wait` to verify that the active runtime loaded the new revision. | Flag | Default | Description | |------|---------|-------------| diff --git a/.agents/skills/tui-development/SKILL.md b/.agents/skills/tui-development/SKILL.md index 5d61af6ecd..f570f283f0 100644 --- a/.agents/skills/tui-development/SKILL.md +++ b/.agents/skills/tui-development/SKILL.md @@ -384,7 +384,7 @@ All actions are accessible via keyboard shortcuts displayed in the nav bar. The `[Tab] Switch Panel [Enter] Select [j/k] Navigate │ [:] Command [q] Quit` **Dashboard (Providers focus):** -`[Tab] Switch Panel [h/l] Switch Tab [j/k] Navigate [Enter] Detail [c] Create [u] Update [d] Delete │ [:] Command [q] Quit` +`[Tab] Switch Panel [h/l] Switch Tab [j/k] Navigate [Enter] Detail [c] Create [u] Update [d] Delete [w] Workspace │ [:] Command [q] Quit` **Dashboard (Global Settings focus):** `[Tab] Switch Panel [h/l] Switch Tab [j/k] Navigate [Enter] Edit [d] Delete │ [:] Command [q] Quit` @@ -535,7 +535,7 @@ On launch, before the event loop starts: ### Workspace switching lifecycle -1. User presses `[w]` on the sandboxes panel → `cycle_workspace()` advances through discovered workspace names, then "all" +1. User presses `[w]` on the providers or sandboxes panel → `cycle_workspace()` advances through discovered workspace names, then "all" 2. `pending_workspace_refresh = true` is set, cursor indices are reset 3. Event loop calls `refresh_providers()` and `refresh_sandboxes()` with the new workspace scope diff --git a/.github/actions/release-helm-oci/action.yml b/.github/actions/release-helm-oci/action.yml index d20691ad0f..46649e0cb0 100644 --- a/.github/actions/release-helm-oci/action.yml +++ b/.github/actions/release-helm-oci/action.yml @@ -4,7 +4,7 @@ name: Release Helm OCI description: > Patch chart version/appVersion, refuse duplicate OCI versions on public - releases, package the chart, and push to GHCR OCI. + releases, package the gateway and workspace charts, and push them to GHCR OCI. inputs: chart-version: @@ -51,11 +51,16 @@ runs: shell: bash run: | set -euo pipefail - CHART_DIR="${RUNNER_TEMP}/chart-build" - cp -a deploy/helm/openshell/. "${CHART_DIR}" - sed -i "s/^version:.*/version: ${CHART_VERSION}/" "${CHART_DIR}/Chart.yaml" - sed -i "s/^appVersion:.*/appVersion: \"${APP_VERSION}\"/" "${CHART_DIR}/Chart.yaml" - echo "chart_dir=${CHART_DIR}" >> "$GITHUB_OUTPUT" + GATEWAY_CHART_DIR="${RUNNER_TEMP}/gateway-chart-build" + WORKSPACE_CHART_DIR="${RUNNER_TEMP}/workspace-chart-build" + cp -a deploy/helm/openshell/. "${GATEWAY_CHART_DIR}" + cp -a deploy/helm/openshell-workspace/. "${WORKSPACE_CHART_DIR}" + for chart_dir in "${GATEWAY_CHART_DIR}" "${WORKSPACE_CHART_DIR}"; do + sed -i "s/^version:.*/version: ${CHART_VERSION}/" "${chart_dir}/Chart.yaml" + sed -i "s/^appVersion:.*/appVersion: \"${APP_VERSION}\"/" "${chart_dir}/Chart.yaml" + done + echo "gateway_chart_dir=${GATEWAY_CHART_DIR}" >> "$GITHUB_OUTPUT" + echo "workspace_chart_dir=${WORKSPACE_CHART_DIR}" >> "$GITHUB_OUTPUT" echo "chart_version=${CHART_VERSION}" >> "$GITHUB_OUTPUT" - name: Refuse duplicate chart version @@ -65,38 +70,52 @@ runs: shell: bash run: | set -euo pipefail - OCI_CHART="oci://ghcr.io/nvidia/openshell/helm-chart" - if helm show chart "${OCI_CHART}" --version "${CHART_VERSION}" >/dev/null 2>&1; then - echo "::error::Chart ${CHART_VERSION} is already published. Use a new tag or delete the existing package first." - exit 1 - fi + for chart in helm-chart openshell-workspace; do + OCI_CHART="oci://ghcr.io/nvidia/openshell/${chart}" + if helm show chart "${OCI_CHART}" --version "${CHART_VERSION}" >/dev/null 2>&1; then + echo "::error::Chart ${chart}:${CHART_VERSION} is already published. Use a new tag or delete the existing package first." + exit 1 + fi + done - name: Package Helm chart env: - CHART_DIR: ${{ steps.prep.outputs.chart_dir }} + GATEWAY_CHART_DIR: ${{ steps.prep.outputs.gateway_chart_dir }} + WORKSPACE_CHART_DIR: ${{ steps.prep.outputs.workspace_chart_dir }} shell: bash run: | set -euo pipefail - helm package "${CHART_DIR}" --destination /tmp - ls /tmp/helm-chart-*.tgz + mkdir -p /tmp/helm-charts + helm package "${GATEWAY_CHART_DIR}" --destination /tmp/helm-charts + helm package "${WORKSPACE_CHART_DIR}" --destination /tmp/helm-charts + ls /tmp/helm-charts/*.tgz - name: Push Helm chart to GHCR OCI shell: bash run: | set -euo pipefail - helm push /tmp/helm-chart-*.tgz oci://ghcr.io/nvidia/openshell + for archive in /tmp/helm-charts/*.tgz; do + helm push "${archive}" oci://ghcr.io/nvidia/openshell + done - name: Push SHA-pinned chart if: inputs.pin-sha != '' env: PIN_SHA: ${{ inputs.pin-sha }} - CHART_DIR: ${{ steps.prep.outputs.chart_dir }} + GATEWAY_CHART_DIR: ${{ steps.prep.outputs.gateway_chart_dir }} + WORKSPACE_CHART_DIR: ${{ steps.prep.outputs.workspace_chart_dir }} shell: bash run: | set -euo pipefail - SHA_CHART_DIR="${RUNNER_TEMP}/chart-build-sha" - cp -a "${CHART_DIR}/." "${SHA_CHART_DIR}" - sed -i "s/^version:.*/version: 0.0.0-dev.${PIN_SHA}/" "${SHA_CHART_DIR}/Chart.yaml" - sed -i "s/^appVersion:.*/appVersion: \"${PIN_SHA}\"/" "${SHA_CHART_DIR}/Chart.yaml" - helm package "${SHA_CHART_DIR}" --destination /tmp/sha-pin - helm push /tmp/sha-pin/helm-chart-*.tgz oci://ghcr.io/nvidia/openshell + mkdir -p /tmp/sha-pin + for source_dir in "${GATEWAY_CHART_DIR}" "${WORKSPACE_CHART_DIR}"; do + chart_name="$(basename "${source_dir}")" + sha_chart_dir="${RUNNER_TEMP}/${chart_name}-sha" + cp -a "${source_dir}/." "${sha_chart_dir}" + sed -i "s/^version:.*/version: 0.0.0-dev.${PIN_SHA}/" "${sha_chart_dir}/Chart.yaml" + sed -i "s/^appVersion:.*/appVersion: \"${PIN_SHA}\"/" "${sha_chart_dir}/Chart.yaml" + helm package "${sha_chart_dir}" --destination /tmp/sha-pin + done + for archive in /tmp/sha-pin/*.tgz; do + helm push "${archive}" oci://ghcr.io/nvidia/openshell + done diff --git a/.github/workflows/branch-checks.yml b/.github/workflows/branch-checks.yml index 2d9dc9914f..2d22b4eafc 100644 --- a/.github/workflows/branch-checks.yml +++ b/.github/workflows/branch-checks.yml @@ -167,6 +167,30 @@ jobs: run: | cargo nextest run --profile ci --workspace --features openshell-server/test-support + - name: Verify telemetry can be compiled out + run: | + cargo build -p openshell-gateway --bin openshell-gateway + tasks/scripts/verify-telemetry-compiled-out.sh present target/debug/openshell-gateway + cargo build -p openshell-gateway --bin openshell-gateway --no-default-features --features defaults-without-telemetry + tasks/scripts/verify-telemetry-compiled-out.sh absent target/debug/openshell-gateway + cargo build -p openshell-sandbox --bin openshell-sandbox --no-default-features --features defaults-without-telemetry + tasks/scripts/verify-telemetry-compiled-out.sh absent target/debug/openshell-sandbox + + - name: Verify the defaults-without-telemetry feature alias tracks the default feature set + run: tasks/scripts/verify-defaults-without-telemetry.sh + + - name: Verify system CA roots build mode compiles and excludes bundled Mozilla roots + run: | + cargo check -p openshell-sandbox --all-targets --no-default-features --features system-ca-roots + if cargo tree -p openshell-sandbox -i webpki-roots --no-default-features --features system-ca-roots 2>/dev/null | grep -q webpki-roots; then + echo "ERROR: webpki-roots found in system CA roots build" >&2 + exit 1 + fi + if cargo tree -p openshell-sandbox -i webpki-root-certs --no-default-features --features system-ca-roots 2>/dev/null | grep -q webpki-root-certs; then + echo "ERROR: webpki-root-certs found in system CA roots build" >&2 + exit 1 + fi + python: name: Python (${{ matrix.runner }}) needs: pr_metadata diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 580a05c1f9..2e316f88bd 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -166,7 +166,7 @@ jobs: interpreter: /lib/ld-linux-aarch64.so.1 uses: ./.github/workflows/build-binaries.yml with: - package: openshell-server + package: openshell-gateway binary: openshell-gateway artifact-name: openshell-gateway-plain-${{ matrix.triple }} triple: ${{ matrix.triple }} diff --git a/.github/workflows/build-gateway-binaries.yml b/.github/workflows/build-gateway-binaries.yml index ed5219e7c6..391e421080 100644 --- a/.github/workflows/build-gateway-binaries.yml +++ b/.github/workflows/build-gateway-binaries.yml @@ -43,7 +43,7 @@ jobs: interpreter: "" uses: ./.github/workflows/build-binaries.yml with: - package: openshell-server + package: openshell-gateway binary: openshell-gateway triple: ${{ matrix.triple }} runner: ${{ matrix.runner }} diff --git a/AGENTS.md b/AGENTS.md index 2c11b4c4ce..33dad248d7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,6 +43,7 @@ These pipelines connect skills into end-to-end workflows. Individual skill files | `crates/openshell-otel-test-support/` | OpenTelemetry test support | Shared loopback OTLP collector fixture for tracing tests | | `crates/openshell-core/` | Shared core | Common types, configuration, error handling | | `crates/openshell-extension-core/` | Extension core | Shared extension identity, JWT claims, bearer-token rotation, and TLS transport primitives | +| `crates/openshell-gateway/` | Gateway binary composition | Links selected first-party compute drivers into the backend-agnostic server registry | | `crates/openshell-sdk/` | Shared client SDK | Async Rust gateway client (gRPC transport, TLS, OIDC refresh, edge tunnel); consumed by CLI, TUI, and `@openshell/sdk` | | `crates/openshell-providers/` | Provider management | Credential provider backends | | `crates/openshell-tui/` | Terminal UI | Ratatui-based dashboard for monitoring | @@ -51,6 +52,7 @@ These pipelines connect skills into end-to-end workflows. Individual skill files | `crates/openshell-driver-db-credstore/` | Database credential driver | In-process `CredentialDriver` backend for gateway database credential storage | | `crates/openshell-driver-kubernetes/` | Kubernetes compute driver | In-process `ComputeDriver` backend for K8s sandbox pods | | `crates/openshell-driver-docker/` | Docker compute driver | In-process `ComputeDriver` backend for local Docker sandbox containers | +| `crates/openshell-driver-mxc/` | MXC compute driver | Windows in-process `ComputeDriver` backend for MXC sandbox execution | | `crates/openshell-driver-podman/` | Podman compute driver | In-process `ComputeDriver` backend for local Podman sandbox containers | | `crates/openshell-driver-vm/` | VM compute driver | Standalone libkrun-backed `ComputeDriver` subprocess (embeds its own rootfs + runtime) | | `crates/openshell-prover/` | Policy prover | Policy verification and proof generation | diff --git a/Cargo.lock b/Cargo.lock index 9188a93d0c..90240d6b3a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3782,6 +3782,7 @@ dependencies = [ "chrono", "clap", "clap_complete", + "console", "crossterm 0.28.1", "dialoguer", "futures", @@ -4069,6 +4070,7 @@ dependencies = [ "nix 0.29.0", "oci-client", "openshell-core", + "openshell-driver-podman", "openshell-otel", "openshell-otel-test-support", "openshell-policy", @@ -4113,6 +4115,30 @@ dependencies = [ "tower 0.5.3", ] +[[package]] +name = "openshell-gateway" +version = "0.0.0" +dependencies = [ + "async-trait", + "hyper-util", + "miette", + "nix 0.29.0", + "openshell-core", + "openshell-driver-docker", + "openshell-driver-kubernetes", + "openshell-driver-mxc", + "openshell-driver-podman", + "openshell-otel", + "openshell-server", + "rustix 1.1.4", + "serde", + "tempfile", + "tokio", + "tonic", + "tower 0.5.3", + "tracing", +] + [[package]] name = "openshell-gateway-interceptors" version = "0.0.0" @@ -4324,11 +4350,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-driver-db-credstore", - "openshell-driver-docker", - "openshell-driver-kubernetes", "openshell-driver-kubernetes-secrets", - "openshell-driver-mxc", - "openshell-driver-podman", "openshell-driver-vault", "openshell-extension-core", "openshell-gateway-interceptors", diff --git a/README.md b/README.md index ba1ccf9859..751eba780d 100644 --- a/README.md +++ b/README.md @@ -258,7 +258,15 @@ OpenShell collects anonymous telemetry to help improve the project for developer Disable telemetry at runtime by setting `OPENSHELL_TELEMETRY_ENABLED=false` on the gateway deployment. For Helm installs, set `server.telemetryEnabled=false`. OpenShell propagates this deployment setting into sandbox supervisor environments so sandbox-side telemetry collection is disabled as well. -You can also compile telemetry out entirely. Telemetry support is a default-on `telemetry` Cargo feature; building with `--no-default-features` produces binaries that contain no telemetry endpoint, no telemetry HTTP client, and no emission code. Build telemetry-free artifacts with, for example, `cargo build --release -p openshell-server --no-default-features` (gateway) and the equivalent for `openshell-sandbox` and `openshell-driver-vm`. With telemetry compiled out, the gateway emits nothing and reports telemetry disabled to the sandboxes it launches. +You can also compile telemetry out entirely. Telemetry support is a default-on `telemetry` Cargo feature, and each crate that carries it also defines a `defaults-without-telemetry` alias covering every other default feature. Build telemetry-free artifacts with `--no-default-features --features defaults-without-telemetry`: + +```shell +cargo build --release -p openshell-gateway --no-default-features --features defaults-without-telemetry +cargo build --release -p openshell-sandbox --no-default-features --features defaults-without-telemetry +cargo build --release -p openshell-driver-vm --no-default-features --features defaults-without-telemetry +``` + +The resulting binaries contain no telemetry endpoint, no telemetry HTTP client, and no emission code. With telemetry compiled out, the gateway emits nothing and reports telemetry disabled to the sandboxes it launches. Cargo has no way to subtract a single default feature, so `defaults-without-telemetry` must be paired with `--no-default-features`; passing it on its own leaves the defaults in place and fails the build rather than producing a binary that still emits. Telemetry events are limited to anonymous operational categories and counts, such as sandbox lifecycle outcomes, provider profile buckets, policy decision counts, and aggregate network activity denial categories. OpenShell telemetry does not collect sandbox names or IDs, hostnames, file paths, binary paths, prompts, credentials, provider names, model names, or user content. diff --git a/architecture/README.md b/architecture/README.md index 0d814a7a22..d48a0d53f9 100644 --- a/architecture/README.md +++ b/architecture/README.md @@ -141,9 +141,13 @@ bridge networks, port mappings, NAT traversal, or bespoke tunnels. The common runtime requirement is narrower: the supervisor must be able to reach the gateway. -The Windows MXC driver is an explicit exception. It launches and monitors a -one-shot workload in the driver, self-reports readiness, and does not expose a -supervisor session, interactive connect, live policy delivery, or governed egress. +The compute-driver capability contract identifies whether a driver reports +runtime readiness. Most drivers use the supervisor session model above. A +driver that sets `driver_reports_runtime_readiness` may self-report readiness +without a supervisor session. Every driver receives the canonical create-time +policy in `DriverSandboxSpec`; drivers without a supervisor use the existing +sandbox configuration API for later revisions. The Windows MXC driver reports +its own readiness and does not expose interactive connect or governed egress. The gateway delivers desired state; the sandbox applies it locally. Policy, settings, credentials, and inference routes flow from the gateway to the diff --git a/architecture/build.md b/architecture/build.md index 32c50aa397..393eb9e468 100644 --- a/architecture/build.md +++ b/architecture/build.md @@ -10,7 +10,7 @@ OpenShell builds these main artifacts: | Artifact | Source | |---|---| -| Gateway binary | `crates/openshell-server` | +| Gateway binary | `crates/openshell-gateway` | | CLI binaries and system packages | `crates/openshell-cli` plus release packaging | | E2E conformance CLI | `crates/openshell-conformance-cli` | | Python SDK wheel | `python/openshell` | @@ -28,19 +28,34 @@ Sandbox community images are built outside this repository. Anonymous telemetry emission is gated behind a default-on `telemetry` Cargo feature. It is defined in `openshell-core` (where the emission code, HTTP client, and endpoint live) and forwarded by the binary crates that emit or -collect telemetry: `openshell-server` (gateway), `openshell-sandbox` +collect telemetry: `openshell-gateway`, `openshell-sandbox` (supervisor), and `openshell-driver-vm`. Every crate depends on `openshell-core` with `default-features = false`, so the binary crate's feature is the single switch that enables `openshell-core/telemetry` for its build graph. In-process drivers (`docker`, `kubernetes`, `podman`) inherit the gateway's setting through feature unification and carry no passthrough. -Building a binary with `--no-default-features` compiles out telemetry entirely: -no endpoint, no telemetry HTTP client, and no emission code. With telemetry -compiled out, `telemetry::enabled()` is always `false` and the `emit_*` helpers -are no-ops, so the data-model types stay available and dependent crates compile -unchanged. The runtime `OPENSHELL_TELEMETRY_ENABLED` switch remains the way to -disable telemetry in a default (telemetry-enabled) build. +Building a binary without the `telemetry` feature compiles out telemetry +entirely: no endpoint, no telemetry HTTP client, and no emission code. With +telemetry compiled out, `telemetry::enabled()` is always `false` and the +`emit_*` helpers are no-ops, so the data-model types stay available and +dependent crates compile unchanged. The runtime `OPENSHELL_TELEMETRY_ENABLED` +switch remains the way to disable telemetry in a default (telemetry-enabled) +build. + +Cargo cannot subtract a single default feature, so each of the three binary +crates also defines a `defaults-without-telemetry` alias listing every default +except `telemetry`. Telemetry-free builds use +`--no-default-features --features defaults-without-telemetry` and stay correct +as the default set grows, instead of dropping unrelated defaults the way a bare +`--no-default-features` does on `openshell-sandbox`. The alias is a keep-list, +not a switch: enabling it on top of the defaults would otherwise yield a +telemetry-on binary that reads as telemetry-free, so each crate root carries a +`compile_error!` for the `telemetry` + `defaults-without-telemetry` combination. +`rust:verify:defaults-without-telemetry` guards both properties — that each +alias still equals its crate's defaults minus `telemetry`, and that the +mutual-exclusion error is wired up — and `rust:verify:telemetry-off` builds +through the alias and inspects the resulting binaries for telemetry markers. Supervisor upstream TLS root-store selection is controlled by the `bundled-ca-roots` Cargo feature (on by default). Default builds use Mozilla diff --git a/architecture/compute-runtimes.md b/architecture/compute-runtimes.md index 200e15fe72..e1e731a0ce 100644 --- a/architecture/compute-runtimes.md +++ b/architecture/compute-runtimes.md @@ -1,34 +1,43 @@ # Compute Runtimes Compute runtimes create, stop, start, delete, and watch sandbox workloads for the -gateway. They do not replace sandbox policy enforcement. Every runtime starts a -workload that runs the `openshell-sandbox` supervisor, and the supervisor -enforces the sandbox contract locally. +gateway. Supervisor-controlled runtimes start a workload that runs the +`openshell-sandbox` supervisor, which enforces the sandbox contract locally. +Driver-controlled runtimes apply the canonical sandbox policy while +provisioning and report workload readiness directly. ## Driver Contract -Each runtime receives a sandbox spec from the gateway and is responsible for: +Each runtime receives a sandbox spec and canonical policy from the gateway and +is responsible for: - Selecting the sandbox image. -- Injecting sandbox identity and gateway callback configuration. -- Supplying TLS or secret material for supervisor callbacks. -- Providing the supervisor binary or image in the workload. +- For supervisor-controlled runtimes, injecting sandbox identity and gateway + callback configuration, supplying callback credentials, and providing the + supervisor binary or image. +- For runtimes without the standard supervisor, validating and applying the + canonical policy before launching the workload. - Forwarding the exact canonical main-process argv and TTY mode without shell reconstruction. The sandbox-level environment and policy workspace apply to the main process. - Reporting lifecycle and platform events back to the gateway. - Cleaning up runtime-owned resources. -Drivers report **backend state only**. A driver snapshot with `Ready=True` means -the underlying compute resource (container, pod, VM) is healthy and running — -nothing more. Drivers must not gate on supervisor session state or hold -references to gateway-internal types. The gateway owns the public -`SandboxPhase::Ready` decision. This applies equally to extension drivers -implementing `ComputeDriver` out of tree. +Drivers report **runtime-observed state only** and must not hold references to +gateway-internal types. For supervisor-controlled runtimes, `Ready=True` means +only that the compute resource is healthy; the gateway also requires a +supervisor session before publishing `SandboxPhase::Ready`. For +drivers that report runtime readiness, `Ready=True` is authoritative because the driver +launches and monitors the policy-constrained workload itself. `compute_driver.proto` is the supported gateway/driver extension boundary. At initialization the gateway snapshots the driver's identity, version, -default image, and gateway-lifecycle preference from `GetCapabilities`. +default image, gateway-lifecycle preference, and +`driver_reports_runtime_readiness` from `GetCapabilities`. The gateway includes +the canonical `SandboxPolicy` in `DriverSandboxSpec.policy` for validation and +creation. Drivers that enforce policy outside the standard supervisor fetch +later revisions through `GetSandboxConfig` and acknowledge them through +`ReportPolicyStatus`. Process-identity omissions are preserved across this boundary so every driver can apply its native image or runtime defaults. Driver-requested listeners are structurally validated and remain restricted to sandbox callback RPCs. @@ -45,28 +54,29 @@ reason strings. ## Sandbox Readiness Composition -The gateway composes driver backend state with supervisor session presence to -produce the public `SandboxPhase`. This composition is gateway-owned and applied -uniformly across all drivers: +The gateway composes driver state with the advertised readiness behavior to +produce the public `SandboxPhase`: ``` backend_phase = derive_phase(driver_status) public_phase = if backend_phase in {Error, Deleting}: → pass through (terminal precedence) + if driver_reports_runtime_readiness && backend_phase == Ready: → Ready if backend_phase == Ready && session connected: → Ready if backend_phase == Ready && no session: → Provisioning if backend_phase in {Provisioning, Unknown} && session: → Ready if backend_phase in {Provisioning, Unknown} && no session: → Provisioning ``` -When `public_phase == Ready` the sandbox is usable through the gateway — both the +For a supervisor-controlled runtime, `public_phase == Ready` means both the backend resource is healthy and a supervisor session is registered. A sandbox whose backend reports ready but has no supervisor session yet holds `Provisioning` with a `Ready=False`, `SupervisorNotConnected` condition and the message `Backend ready; waiting for supervisor session`. This distinguishes it from a sandbox whose compute resource is still provisioning without exposing contradictory public -readiness signals. +readiness signals. When the driver reports runtime readiness, its ready condition +is published without waiting for a supervisor session. **Session precedence over lagging driver snapshots:** A supervisor session can only be established by a running workload. When `set_supervisor_session_state` promotes the @@ -85,10 +95,12 @@ session-owning replica. That work is deferred to GitHub issue #1868. Until then, deployments that require reliable readiness composition must run a single gateway replica. -**Extension point:** The readiness decision is a safety invariant, not an -operator-configurable hook. The driver contract is the correct extension point for -custom backend readiness semantics. RFC-0010 lifecycle hooks may observe readiness -transitions via `post_commit`; they do not override the composition rule. +**Extension point:** Driver-reported readiness is a capability, not an +operator-configurable hook. A driver may enable it only when it owns workload +readiness. Policy delivery remains independent: create-time policy is embedded +in the sandbox specification, and later revisions use the existing sandbox +configuration API. RFC-0010 lifecycle hooks may observe readiness transitions via +`post_commit`; they do not override the composition rule. The capability RPC reports driver identity, version, and the default sandbox image used by the gateway. GPU availability stays driver-local and is validated @@ -103,9 +115,8 @@ of re-querying drivers on each request. The gateway binary explicitly installs the compute drivers compiled into that binary before entering server startup. The server selects a configured driver by normalized registry name. When no driver is configured, it evaluates only -the installed drivers' probes in registered priority order, records every -available registration, and selects the first. Drivers without a probe, -including VM, remain opt-in. +the installed drivers' probes and chooses the lowest registered priority. +Drivers without a probe, including VM, remain opt-in. Startup computes this selection once after merging configuration. The same selection drives authentication defaults and runtime construction, so a probe @@ -117,17 +128,18 @@ registry. Adding or removing a compiled driver therefore changes registration rather than the server's selection flow. Alternate gateway binaries can install their own `ComputeDriverFactory` registrations and hand the completed registry to `run_cli_with_compute_drivers`; factories receive merged driver config and -finish through the same in-process runtime adapter. A configured UDS endpoint -still takes precedence over a compiled registration with the same name. - -The standard server crate groups first-party registrations behind the -`in-tree-compute-drivers` feature. Protocol-only gateway builds disable that -feature and link no compute-driver crates. E2E lanes compose that gateway with -Docker, Podman, Kubernetes, and VM driver executables over the public UDS gRPC -contract so an in-tree driver cannot silently depend on a server-only API. -External Kubernetes drivers support shared and managed workspace modes. -Operator mode requires an in-process dynamic namespace allowlist and is -rejected when Kubernetes is configured through an external endpoint. +return either an in-process driver or a gateway-managed remote endpoint. The +server constructs the common runtime adapter and snapshots `GetCapabilities` +for either result. A configured UDS endpoint still takes precedence over a +compiled registration with the same name. + +The `openshell-gateway` composition crate groups first-party registrations +behind the `in-tree-compute-drivers` feature. `openshell-server` has no compute +driver dependencies or backend-name dispatch. Protocol-only gateway builds +disable the composition feature and link no compute-driver crates. E2E lanes +compose that gateway with Docker, Podman, Kubernetes, and VM driver executables +over the public UDS gRPC contract so an in-tree driver cannot silently depend +on a server-only API. ## Stop and Start Lifecycle @@ -246,6 +258,16 @@ template resource limits. Docker and Podman apply them as runtime limits. Kubernetes mirrors each limit into the matching request. VM accepts the fields but currently ignores them. +Reusable sandbox workload templates are resolved before the compute-driver +boundary. Drivers do not receive a separate template resource; the gateway +lowers the selected `SandboxWorkloadTemplate` into the existing sandbox spec +and validates that spec before calling `ValidateSandboxCreate` or +`CreateSandbox`. Template CPU and memory become the same typed resource limits +described above. Template GPU settings become `ResourceRequirements`, preserving +the driver's default GPU assignment when the count is omitted. Template +`driver_config` remains a driver-keyed envelope until the compute layer selects +the active driver block and forwards only that block to the driver. + Docker and Podman also accept per-sandbox driver-config mounts for existing runtime-managed named volumes and tmpfs mounts. Podman additionally accepts image mounts through its image-volume API. User-supplied bind and volume mounts @@ -271,6 +293,17 @@ through the driver configuration. The Helm chart defaults sandbox agents to `Unconfined` so runtime/default AppArmor profiles do not block supervisor network namespace setup on AppArmor-enabled nodes. +The Kubernetes deployment packaging has two ownership boundaries. The gateway +chart owns the gateway workload, configuration, Services, PKI, and +cluster-scoped gateway resources. It can retain the legacy combined behavior, +or omit workspace resources. The workspace chart is installed into a +pre-provisioned sandbox namespace and owns only the sandbox ServiceAccount, +namespaced RBAC, and sandbox ingress NetworkPolicy. Its RoleBinding names the +gateway ServiceAccount and namespace explicitly, so the two releases have +disjoint lifecycle ownership. A shared-mode gateway can target one external +namespace, while operator mode maps workspace names to multiple +platform-provisioned namespaces. + Resource requirements enter the driver layer through `SandboxSpec.resource_requirements`. This includes a set of GPU requirements, where a user can request a specific number of GPUs or the driver-specific default behaviour. For all in-tree drivers, this is equivalent to selecting a single GPU. @@ -471,13 +504,13 @@ image-pull Secrets in every operator-managed namespace. **Operator** uses pre-provisioned namespaces discovered through two optional sources: a K8s label selector (`operator_namespace_label`) and a drop-in -allowlist file (`operator_namespace_file`). At least one must be configured. -The `OperatorNamespaceAllowlist` (`Arc>>`) is populated -at runtime by background watchers and read by the namespace resolver. Sandbox -creation fails closed if the workspace is not in the current allowlist. Platform -teams manage namespace lifecycle externally. RBAC uses the same ClusterRole as -managed mode but without namespace `create`/`delete` or ServiceAccount -permissions. +allowlist file (`operator_namespace_file`). Exactly one must be configured. +The compute driver and the gateway's ServiceAccount authenticator independently +watch that public config source; no in-process driver state crosses into the +server. Sandbox creation and token bootstrap fail closed if the workspace is +not in the current allowlist. Platform teams manage namespace lifecycle +externally. RBAC uses the same ClusterRole as managed mode but without namespace +`create`/`delete` or ServiceAccount permissions. ### Watching and Querying diff --git a/architecture/gateway.md b/architecture/gateway.md index 0430d95159..f86411511b 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -344,23 +344,33 @@ default WAL journal mode), which mirror the same sensitive contents. Persisted state includes sandboxes, providers, provider credential refresh state, SSH sessions, policy revisions, settings, inference configuration, and -deployment records. Provider refresh state is stored as a separate object -scoped to the provider instance through `objects.scope`. Its non-secret -configuration remains inline, while refresh tokens, client secrets, private -keys, and other secret source material are stored through the active credential -driver and represented by opaque handles. The provider record keeps only the -current injectable credential handles and optional per-credential expiry -timestamps. A refresh normally mints one credential, but a strategy may -co-mint several (AWS STS mints the access key, secret key, and session token in -one call); the refresh state pins the resolved set of env keys it owns so -collision checks reserve all of them before the first mint. Provider records -keep inline credential values only for legacy records created before credential -driver storage. New provider and refresh-material writes keep driver-owned -credential handles. When no external credential driver is configured, gateways -use server-owned encrypted database credential storage for defense in depth. -Multi-replica deployments can use that default with a shared database and -shared key-encryption key, or opt into an external backend such as Vault or -Kubernetes Secrets. +deployment records, and reusable sandbox workload templates. Provider refresh +state is stored as a separate object scoped to the provider instance through +`objects.scope`. Its non-secret configuration remains inline, while refresh +tokens, client secrets, private keys, and other secret source material are +stored through the active credential driver and represented by opaque handles. +The provider record keeps only the current injectable credential handles and +optional per-credential expiry timestamps. A refresh normally mints one +credential, but a strategy may co-mint several (AWS STS mints the access key, +secret key, and session token in one call); the refresh state pins the resolved +set of env keys it owns so collision checks reserve all of them before the +first mint. Provider records keep inline credential values only for legacy +records created before credential driver storage. New provider and +refresh-material writes keep driver-owned credential handles. When no external +credential driver is configured, gateways use server-owned encrypted database +credential storage for defense in depth. Multi-replica deployments can use that +default with a shared database and shared key-encryption key, or opt into an +external backend such as Vault or Kubernetes Secrets. + +Sandbox workload templates are workspace-scoped gateway resources. Workspace +admins create and delete them; workspace users can read and list them. A +template owns reusable workload intent: image, environment, CPU and memory +limits, GPU request, driver-specific config, and service-level hints. A sandbox +created from a template resolves that resource once and persists an ordinary +`SandboxSpec` snapshot. The create request still owns per-sandbox governance: +name, labels, annotations, provider attachments, and policy. The sandbox stores +template provenance as the template name and resource version used for the +snapshot, so later template edits or deletes do not mutate existing sandboxes. OAuth refresh failures retain a gateway-owned recovery classification alongside the refresh state. The gateway reads only a bounded error response and maps diff --git a/architecture/sandbox-limits.md b/architecture/sandbox-limits.md index 49f1ab7ce9..9635bc1c30 100644 --- a/architecture/sandbox-limits.md +++ b/architecture/sandbox-limits.md @@ -40,6 +40,15 @@ New limits should follow these rules: query parameters, or external free-form diagnostics. - Test time bounds with simulated time and test shared budgets under saturation. +## Gateway Sandbox Resources + +Gateway-owned sandbox resources also carry admission limits before they can +produce supervisor work. Reusable workload templates are capped at 1000 per +workspace. Template payloads reuse sandbox spec validation for environment +entry count and size, image and resource field sizes, driver-config serialized +size, and GPU count. Template names use the same DNS-style resource-name rules +as other named gateway resources. + ## Middleware Middleware limits are process-wide per sandbox. Registry replacement preserves diff --git a/architecture/sandbox.md b/architecture/sandbox.md index 6365ed0631..6e4e020536 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -259,6 +259,12 @@ own DNS view, e.g. DoH tunneled via CONNECT, is a possible future enhancement and out of scope.) The workload child's proxy variables are unaffected — they are always rewritten to point at the local policy proxy. +Template environment is treated like user-provided sandbox environment. It can +shape the workload child, but it cannot override driver-controlled identity, +gateway callback, TLS, relay socket, proxy, provider, or supervisor coordination +variables. Drivers and the supervisor rewrite those reserved values after image +and template environment are considered. + The configuration is fail-closed: a setting that is present but invalid — an empty value, an unsupported or malformed proxy URL, an unreadable auth file or CA bundle, a malformed credential, or an auth file, `NO_PROXY` list, or CA diff --git a/architecture/windows-msvc-build.md b/architecture/windows-msvc-build.md index e940b83273..6b0d675a9c 100644 --- a/architecture/windows-msvc-build.md +++ b/architecture/windows-msvc-build.md @@ -10,6 +10,9 @@ driver. It does not make Windows a Docker, Kubernetes, Podman, or VM runtime hos - Keep the Linux and macOS build paths unchanged. - Preserve gateway configuration parsing for all existing compute driver names. - Build and test the in-process MXC driver on supported Windows hosts. +- Use the ordinary in-process compute-driver composition path; MXC receives the + canonical sandbox policy through `DriverSandboxSpec` and advertises that it + reports runtime readiness. - Return clear unsupported errors when a Windows gateway is configured to use Docker, Kubernetes, Podman, or VM. - Keep dedicated `windows:*` validation tasks while allowing the repository-wide `pre-commit` task to delegate compiler-bearing Rust checks to the native @@ -23,9 +26,10 @@ driver. It does not make Windows a Docker, Kubernetes, Podman, or VM runtime hos ## Unsupported Driver Strategy -The gateway uses platform-specific configuration contracts on Windows. These -contracts preserve config-file parsing and reject unsupported driver selection -with a clear error without depending on the runtime driver crates. +The gateway composition crate installs platform-specific registration stubs on +Windows. These registrations preserve config-file selection and reject +unsupported drivers with a clear error without depending on their runtime +crates. The Windows lane does not build, release, package, or smoke-test standalone driver binaries for Docker, Kubernetes, Podman, or VM. Those binaries are Linux @@ -39,10 +43,10 @@ on Windows. | Driver | Windows build behavior | Runtime behavior | |---|---|---| -| Docker | Driver crate excluded; server config contract retained. | Gateway construction returns unsupported. | -| Kubernetes | Driver crate excluded; server config contract retained. | Gateway construction returns unsupported. | -| Podman | Driver crate excluded; server config contract retained. | Gateway construction returns unsupported. | -| VM | Driver crate excluded from workspace validation. | Gateway construction returns unsupported. | +| Docker | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | +| Kubernetes | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | +| Podman | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | +| VM | Driver crate excluded; gateway registration stub retained. | Gateway construction returns unsupported. | | MXC | Driver links into the native gateway and runs in Windows validation. | `process_container` is default-deny; grant-only `isolation_session` requires explicit configuration. | This keeps Windows behavior explicit without carrying runtime dependencies or @@ -66,7 +70,7 @@ Windows validation is exposed through `tasks/windows.toml`: | `windows:build:arm64` | Build release ARM64 `openshell-gateway.exe` and `openshell.exe`. | | `windows:test:x64` | Run native x64 workspace tests, including MXC mapper and lifecycle tests, while excluding unsupported Windows packages as top-level test targets. | | `windows:test:arm64` | Run native ARM64 workspace tests with the same package exclusions. | -| `windows:test:unsupported:x64` | Run focused server/runtime tests for unsupported driver contracts. | +| `windows:test:unsupported:x64` | Run focused gateway-composition tests for unsupported driver contracts. | | `windows:test:unsupported:arm64` | Run the same focused contracts natively on ARM64. | | `windows:ci` | Run check, build, test, unsupported-contract tests, and artifact reporting. | diff --git a/crates/openshell-cli/Cargo.toml b/crates/openshell-cli/Cargo.toml index 4b96253310..ddaf09f889 100644 --- a/crates/openshell-cli/Cargo.toml +++ b/crates/openshell-cli/Cargo.toml @@ -37,6 +37,9 @@ chrono = "0.4" clap = { workspace = true } clap_complete = { workspace = true } crossterm = { workspace = true } +# Styling backend shared by dialoguer and indicatif; `color` overrides its +# global switch so both follow the CLI's --color setting. +console = "0.15" dialoguer = "0.11" indicatif = { workspace = true } owo-colors = { workspace = true } diff --git a/crates/openshell-cli/src/color.rs b/crates/openshell-cli/src/color.rs new file mode 100644 index 0000000000..e6a185bdad --- /dev/null +++ b/crates/openshell-cli/src/color.rs @@ -0,0 +1,534 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Runtime color control for CLI output. +//! +//! The CLI styles its human-readable tables and status lines with ANSI escape +//! sequences. Those sequences must not appear when the output is being consumed +//! by another program, or callers end up writing brittle patterns against bytes +//! they cannot see. +//! +//! `owo_colors::OwoColorize` emits escapes unconditionally, so this module wraps +//! it with a process-wide switch resolved once at startup by [`init`]. Command +//! modules import [`Colorize`] instead of `OwoColorize`; the method names match, +//! so call sites are unchanged, but each one now checks the switch when it +//! renders. +//! +//! Styling is not confined to `owo-colors`, and the other paths each carry +//! their own default, so [`init`] brings them under the same setting: +//! +//! - `tracing_subscriber` formats with ANSI on, does no terminal detection, and +//! writes to stdout. Left alone, `openshell -v ... | ...` leaks escapes into a +//! pipe exactly like the styled tables did. `main` passes [`stdout_enabled`] +//! to `with_ansi`. +//! - `indicatif` and `dialoguer` both style through `console`, which has its own +//! detection and honors `NO_COLOR` but cannot know about `--color`. [`init`] +//! overrides it globally, which covers every progress bar and prompt rather +//! than the specific ones the CLI happens to construct today. +//! - `miette` renders errors to stderr with its own detection, likewise unaware +//! of `--color`. [`init`] installs a report handler built from +//! [`stderr_enabled`]. +//! +//! Resolution order, highest precedence first: +//! +//! 1. `--color always|never` on the command line. +//! 2. `NO_COLOR`, set and non-empty, disables color (). +//! 3. `FORCE_COLOR`, set and non-empty, forces color on (). +//! 4. Otherwise the stream is styled only when that stream is a terminal. +//! +//! Step 4 is resolved per stream. Redirecting one must not decide for the other: +//! `openshell ... 2> build.log` from a terminal should keep a styled stdout and +//! write a plain-text log, and `openshell ... | grep` should keep styled +//! diagnostics on the terminal while feeding the pipe clean bytes. [`init`] +//! therefore stores one answer per stream and hands each library the one for the +//! stream it writes to. +//! +//! The `owo-colors` wrapper is the exception, because its call sites are split +//! across `println!` and `eprintln!` and a [`Painted`] value cannot tell which +//! macro will consume it. It styles only when both streams accept escapes, which +//! errs toward plain text rather than risk writing escapes to a redirected +//! stream. + +use std::ffi::OsStr; +use std::fmt::{self, Display}; +use std::io::IsTerminal; +use std::sync::atomic::{AtomicBool, Ordering}; + +use owo_colors::{OwoColorize, Style}; + +/// Whether stdout may carry escapes. Consulted for `tracing` and console's +/// stdout switch. +/// +/// Defaults to disabled so that any output produced before [`init`] runs — and +/// output from unit tests, which never call `init` — stays free of escapes. +static STDOUT_ENABLED: AtomicBool = AtomicBool::new(false); + +/// Whether stderr may carry escapes. Consulted for `miette` and console's stderr +/// switch. +static STDERR_ENABLED: AtomicBool = AtomicBool::new(false); + +/// When to colorize CLI output. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)] +pub enum ColorChoice { + /// Colorize a stream only when that stream is a terminal and no environment + /// override applies. + #[default] + Auto, + /// Always colorize, even when output is redirected. + Always, + /// Never colorize. + Never, +} + +/// Resolve the color setting and store it for the rest of the process. +/// +/// Call once, as early as possible after argument parsing and before any output +/// is written. +pub fn init(choice: ColorChoice) { + let no_color = std::env::var_os("NO_COLOR"); + let force_color = std::env::var_os("FORCE_COLOR"); + + // Under `auto` each stream answers for itself. Redirecting one must not + // decide for the other: `openshell ... 2> build.log` from a terminal has a + // styled stdout and a plain-text stderr, and vice versa for `| grep`. + let stdout_enabled = resolve( + choice, + no_color.as_deref(), + force_color.as_deref(), + std::io::stdout().is_terminal(), + ); + let stderr_enabled = resolve( + choice, + no_color.as_deref(), + force_color.as_deref(), + std::io::stderr().is_terminal(), + ); + STDOUT_ENABLED.store(stdout_enabled, Ordering::Relaxed); + STDERR_ENABLED.store(stderr_enabled, Ordering::Relaxed); + + // `indicatif` and `dialoguer` both style through `console`, which keeps its + // own detection. Override it so progress bars and prompts follow the same + // setting as everything else — including `--color`, which console has no way + // to learn about on its own. + console::set_colors_enabled(stdout_enabled); + console::set_colors_enabled_stderr(stderr_enabled); + + // miette renders errors to stderr. The hook can only be installed once per + // process; a failure means something already installed one, and error + // rendering is not worth aborting the command over. + let _ = miette::set_hook(Box::new(move |_| { + Box::new( + miette::MietteHandlerOpts::new() + .color(stderr_enabled) + .build(), + ) + })); +} + +/// Whether stdout may carry ANSI escapes. +/// +/// [`init`] configures `console` and `miette` directly; `tracing` is wired up by +/// the caller, which writes to stdout and passes this to `with_ansi`. +#[must_use] +pub fn stdout_enabled() -> bool { + STDOUT_ENABLED.load(Ordering::Relaxed) +} + +/// Whether stderr may carry ANSI escapes. +#[must_use] +pub fn stderr_enabled() -> bool { + STDERR_ENABLED.load(Ordering::Relaxed) +} + +/// Whether a [`Painted`] value should render styled. +/// +/// The `owo-colors` call sites are split across `println!` and `eprintln!` and +/// the wrapper cannot tell which one will consume it, so it styles only when +/// *both* streams accept escapes. Erring toward plain text keeps a redirected +/// stream clean, which is the whole point of the switch; the cost is that +/// `openshell ... 2>/dev/null` from a terminal prints an uncolored table. +/// `--color always` overrides it. +#[must_use] +fn painted_enabled() -> bool { + stdout_enabled() && stderr_enabled() +} + +/// Decide whether one stream may carry escapes. Split out from [`init`] so the +/// precedence rules are testable without mutating process state. +fn resolve( + choice: ColorChoice, + no_color: Option<&OsStr>, + force_color: Option<&OsStr>, + stream_is_terminal: bool, +) -> bool { + match choice { + ColorChoice::Always => return true, + ColorChoice::Never => return false, + ColorChoice::Auto => {} + } + + // Both conventions key on presence rather than value: set and non-empty + // means yes, regardless of what the value is. and + // . + if is_set(no_color) { + return false; + } + if is_set(force_color) { + return true; + } + + stream_is_terminal +} + +/// Whether an environment variable counts as set: present and not empty. +fn is_set(value: Option<&OsStr>) -> bool { + value.is_some_and(|value| !value.is_empty()) +} + +/// A value tagged with a style, rendered only when color is enabled. +/// +/// Borrows its value and forwards the caller's format specification to the +/// inner `Display`, so width and alignment apply to the text rather than to the +/// text plus escapes. +pub struct Painted<'a, T: ?Sized> { + value: &'a T, + style: Style, +} + +impl Display for Painted<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if !painted_enabled() { + return Display::fmt(&self.value, f); + } + // Hand the whole style to owo-colors in one go. `Styled` writes the + // prefix, forwards `f` to the inner `Display` so padding still measures + // the text, then writes the reset. + Display::fmt(&OwoColorize::style(&self.value, self.style), f) + } +} + +/// Style-combining methods, so `x.green().bold()` renders as one escape +/// sequence rather than nesting two. +/// +/// These are inherent so they take precedence over the [`Colorize`] blanket +/// impl, which would otherwise wrap a `Painted` in another `Painted`. +impl Painted<'_, T> { + /// Add bold to the current style. + #[must_use] + pub fn bold(self) -> Self { + Self { + style: self.style.bold(), + ..self + } + } + /// Add cyan to the current style. + #[must_use] + pub fn cyan(self) -> Self { + Self { + style: self.style.cyan(), + ..self + } + } + /// Add dimmed to the current style. + #[must_use] + pub fn dimmed(self) -> Self { + Self { + style: self.style.dimmed(), + ..self + } + } + /// Add green to the current style. + #[must_use] + pub fn green(self) -> Self { + Self { + style: self.style.green(), + ..self + } + } + /// Add red to the current style. + #[must_use] + pub fn red(self) -> Self { + Self { + style: self.style.red(), + ..self + } + } + /// Add yellow to the current style. + #[must_use] + pub fn yellow(self) -> Self { + Self { + style: self.style.yellow(), + ..self + } + } +} + +/// Styling methods mirroring the `owo_colors::OwoColorize` surface the CLI uses. +/// +/// Import this instead of `OwoColorize` so styled output honors [`init`]. The +/// two traits have colliding method names on purpose: importing both in one +/// module is an ambiguity error, which keeps unconditional coloring from +/// creeping back in. +pub trait Colorize { + /// Render in bold. + fn bold(&self) -> Painted<'_, Self>; + /// Render in cyan. + fn cyan(&self) -> Painted<'_, Self>; + /// Render dimmed. + fn dimmed(&self) -> Painted<'_, Self>; + /// Render in green. + fn green(&self) -> Painted<'_, Self>; + /// Render in red. + fn red(&self) -> Painted<'_, Self>; + /// Render in yellow. + fn yellow(&self) -> Painted<'_, Self>; +} + +impl Colorize for T { + fn bold(&self) -> Painted<'_, Self> { + Painted { + value: self, + style: Style::new().bold(), + } + } + fn cyan(&self) -> Painted<'_, Self> { + Painted { + value: self, + style: Style::new().cyan(), + } + } + fn dimmed(&self) -> Painted<'_, Self> { + Painted { + value: self, + style: Style::new().dimmed(), + } + } + fn green(&self) -> Painted<'_, Self> { + Painted { + value: self, + style: Style::new().green(), + } + } + fn red(&self) -> Painted<'_, Self> { + Painted { + value: self, + style: Style::new().red(), + } + } + fn yellow(&self) -> Painted<'_, Self> { + Painted { + value: self, + style: Style::new().yellow(), + } + } +} + +#[cfg(test)] +mod tests { + // Deliberately not `use super::*`: that would also pull in `OwoColorize` + // and make every `.green()` below ambiguous. + use super::{ + ColorChoice, Colorize, Ordering, STDERR_ENABLED, STDOUT_ENABLED, Style, painted_enabled, + resolve, + }; + use std::ffi::OsStr; + + /// Serializes tests that flip the process-wide switches. + static SWITCH_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + + /// Set both stream switches, since [`Painted`] requires both. + fn with_color(on: bool, body: impl FnOnce() -> R) -> R { + with_streams(on, on, body) + } + + fn with_streams(stdout: bool, stderr: bool, body: impl FnOnce() -> R) -> R { + let _guard = SWITCH_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let prev_out = STDOUT_ENABLED.swap(stdout, Ordering::Relaxed); + let prev_err = STDERR_ENABLED.swap(stderr, Ordering::Relaxed); + let result = body(); + STDOUT_ENABLED.store(prev_out, Ordering::Relaxed); + STDERR_ENABLED.store(prev_err, Ordering::Relaxed); + result + } + + /// Helper so the `resolve` cases read as plain strings. + fn env(value: &str) -> &OsStr { + OsStr::new(value) + } + + #[test] + fn disabled_output_has_no_escapes() { + with_color(false, || { + assert_eq!("running".green().to_string(), "running"); + assert_eq!("dead".red().to_string(), "dead"); + assert_eq!("STATUS".bold().to_string(), "STATUS"); + }); + } + + #[test] + fn enabled_output_is_wrapped_in_the_expected_escapes() { + with_color(true, || { + // The styling the bug report observed from `forward list`. + assert_eq!("running".green().to_string(), "\u{1b}[32mrunning\u{1b}[0m"); + // Delegation is to owo-colors, so the bytes match what it would + // produce for the same style. + assert_eq!( + "running".green().to_string(), + owo_colors::OwoColorize::style(&"running", Style::new().green()).to_string() + ); + assert_eq!( + "x".dimmed().to_string(), + owo_colors::OwoColorize::style(&"x", Style::new().dimmed()).to_string() + ); + }); + } + + #[test] + fn format_width_applies_to_text_not_escapes() { + // Padding must measure the value, so columns line up identically whether + // or not color is on. + let plain = with_color(false, || format!("[{:<10}]", "running".green())); + let colored = with_color(true, || format!("[{:<10}]", "running".green())); + + assert_eq!(plain, "[running ]"); + assert_eq!(colored, "[\u{1b}[32mrunning \u{1b}[0m]"); + } + + #[test] + fn styles_merge_into_one_escape_sequence() { + with_color(true, || { + // Chaining combines into a single style rather than nesting two + // wrappers, so there is one prefix and one reset. + assert_eq!("hi".green().bold().to_string(), "\u{1b}[32;1mhi\u{1b}[0m"); + assert_eq!( + "hi".green().bold().to_string(), + owo_colors::OwoColorize::style(&"hi", Style::new().green().bold()).to_string() + ); + // Order of the calls does not change the resulting style. + assert_eq!( + "hi".green().bold().to_string(), + "hi".bold().green().to_string() + ); + }); + with_color(false, || { + assert_eq!("hi".green().bold().to_string(), "hi"); + }); + } + + #[test] + fn non_string_values_render() { + with_color(false, || { + assert_eq!(8443.green().to_string(), "8443"); + assert_eq!(true.yellow().to_string(), "true"); + }); + } + + /// Render a `dialoguer` confirm prompt, which styles through `console`. + /// + /// Asserting on emitted bytes rather than on `console::colors_enabled()` + /// keeps this honest about what a user would actually see. + fn rendered_prompt() -> String { + use dialoguer::theme::Theme as _; + + let mut out = String::new(); + dialoguer::theme::ColorfulTheme::default() + .format_confirm_prompt(&mut out, "Continue?", Some(false)) + .expect("format confirm prompt"); + out + } + + #[test] + fn console_override_governs_indicatif_and_dialoguer_styling() { + let _guard = SWITCH_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + // Prompts and progress bars draw to stderr, so their styles consult + // console's stderr switch. `init` sets both; so does this test. + let previous = console::colors_enabled_stderr(); + + console::set_colors_enabled_stderr(true); + let styled = rendered_prompt(); + console::set_colors_enabled_stderr(false); + let plain = rendered_prompt(); + + console::set_colors_enabled_stderr(previous); + + // Positive control first: without it, the plain assertion could pass + // simply because dialoguer stopped emitting anything at all. + assert!( + styled.contains('\u{1b}'), + "console override should permit styling, got: {styled:?}" + ); + assert!( + !plain.contains('\u{1b}'), + "console override should suppress styling, got: {plain:?}" + ); + assert!(plain.contains("Continue?"), "got: {plain:?}"); + } + + #[test] + fn explicit_choice_overrides_environment_and_terminal() { + assert!(resolve(ColorChoice::Always, Some(env("1")), None, false)); + assert!(!resolve(ColorChoice::Never, None, Some(env("1")), true)); + } + + #[test] + fn no_color_disables_when_set_and_non_empty() { + assert!(!resolve(ColorChoice::Auto, Some(env("1")), None, true)); + // Presence is what counts; the value is not interpreted, so a value that + // reads as falsy still disables color. + assert!(!resolve(ColorChoice::Auto, Some(env("0")), None, true)); + // NO_COLOR outranks FORCE_COLOR. + assert!(!resolve( + ColorChoice::Auto, + Some(env("1")), + Some(env("1")), + true + )); + // An empty value is not "set" for the purposes of the convention. + assert!(resolve(ColorChoice::Auto, Some(env("")), None, true)); + } + + #[test] + fn force_color_enables_when_set_and_non_empty() { + assert!(resolve(ColorChoice::Auto, None, Some(env("1")), false)); + // Same presence rule as NO_COLOR: `0` is a value, not an opt-out. + // keys on presence and non-emptiness only. + assert!(resolve(ColorChoice::Auto, None, Some(env("0")), false)); + assert!(!resolve(ColorChoice::Auto, None, Some(env("")), false)); + } + + #[test] + fn auto_resolves_each_stream_independently() { + // `openshell ... 2> build.log` from a terminal: stdout is styled, the + // log file is not. Resolving both from stdout's answer would put escapes + // in the log. + assert!(resolve(ColorChoice::Auto, None, None, true)); + assert!(!resolve(ColorChoice::Auto, None, None, false)); + } + + #[test] + fn painted_requires_both_streams() { + // A `Painted` value cannot tell whether it is bound for stdout or + // stderr, so it stays plain unless both streams accept escapes. + assert!(with_streams(true, true, painted_enabled)); + assert!(!with_streams(true, false, painted_enabled)); + assert!(!with_streams(false, true, painted_enabled)); + assert!(!with_streams(false, false, painted_enabled)); + + // The rendered consequence: stderr redirected to a file leaves the + // styled text plain rather than writing escapes into it. + assert_eq!( + with_streams(true, false, || "running".green().to_string()), + "running" + ); + } + + #[test] + fn auto_follows_the_terminal() { + assert!(resolve(ColorChoice::Auto, None, None, true)); + assert!(!resolve(ColorChoice::Auto, None, None, false)); + } +} diff --git a/crates/openshell-cli/src/commands/common.rs b/crates/openshell-cli/src/commands/common.rs index 03cb3260cf..0f12c3df4e 100644 --- a/crates/openshell-cli/src/commands/common.rs +++ b/crates/openshell-cli/src/commands/common.rs @@ -3,6 +3,7 @@ //! Shared helpers, types, and parsing utilities used across CLI command groups. +use crate::color::Colorize; use chrono::DateTime; use dialoguer::{Confirm, theme::ColorfulTheme}; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; @@ -17,7 +18,6 @@ use openshell_core::proto::{ }; use openshell_core::settings::{self, SettingValueKind}; use openshell_providers::builtin_profiles; -use owo_colors::OwoColorize; use std::collections::HashMap; use std::io::IsTerminal; use std::process::Command; diff --git a/crates/openshell-cli/src/commands/gateway.rs b/crates/openshell-cli/src/commands/gateway.rs index 7a3ebf01f0..0a7950050d 100644 --- a/crates/openshell-cli/src/commands/gateway.rs +++ b/crates/openshell-cli/src/commands/gateway.rs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +use crate::color::Colorize; use crate::tls::{ TlsOptions, build_insecure_rustls_config, build_rustls_config, grpc_client, require_tls_materials, @@ -20,7 +21,6 @@ use openshell_bootstrap::{ }; use openshell_bootstrap::{GatewayMetadataSource, ListedGateway}; use openshell_core::proto::{GetGatewayInfoRequest, HealthRequest, ServiceStatus}; -use owo_colors::OwoColorize; use std::io::IsTerminal; use std::path::PathBuf; use tonic::{Code, Status}; diff --git a/crates/openshell-cli/src/lib.rs b/crates/openshell-cli/src/lib.rs index e28b84b05d..910920f42a 100644 --- a/crates/openshell-cli/src/lib.rs +++ b/crates/openshell-cli/src/lib.rs @@ -11,6 +11,7 @@ pub(crate) static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(() pub(crate) mod test_utils; pub mod auth; +pub mod color; pub(crate) mod commands; pub mod completers; pub mod edge_tunnel; diff --git a/crates/openshell-cli/src/main.rs b/crates/openshell-cli/src/main.rs index 80668272db..befac54759 100644 --- a/crates/openshell-cli/src/main.rs +++ b/crates/openshell-cli/src/main.rs @@ -7,7 +7,7 @@ use clap::{CommandFactory, Parser, Subcommand, ValueEnum, ValueHint}; use clap_complete::engine::ArgValueCompleter; use clap_complete::env::CompleteEnv; use miette::Result; -use owo_colors::OwoColorize; +use openshell_cli::color::{self, ColorChoice, Colorize}; use std::collections::HashMap; use std::io::Write; use std::path::PathBuf; @@ -468,6 +468,18 @@ struct Cli { #[arg(short, long, action = clap::ArgAction::Count, global = true, help_heading = "GLOBAL FLAGS")] verbose: u8, + /// When to colorize output. `auto` colorizes only when stdout is a terminal. + #[arg( + long, + global = true, + value_enum, + default_value_t = ColorChoice::Auto, + value_name = "WHEN", + env = "OPENSHELL_COLOR", + help_heading = "GLOBAL FLAGS" + )] + color: ColorChoice, + /// Print help. #[arg(short = 'h', long, action = clap::ArgAction::Help, global = true, help_heading = "GLOBAL FLAGS")] help: (), @@ -1339,6 +1351,10 @@ enum SandboxCommands { #[arg(long, add = ArgValueCompleter::new(completers::complete_sandbox_names))] name: Option, + /// Create the sandbox from a named sandbox template. + #[arg(long, conflicts_with_all = ["from", "gpu", "cpu", "memory", "driver_config_json", "envs"])] + template: Option, + /// Sandbox source: a community sandbox name (e.g., `ollama`), a path /// to a Dockerfile or directory containing one, or a full container /// image reference (e.g., `myregistry.com/img:tag`). @@ -1681,6 +1697,10 @@ enum SandboxCommands { /// Manage providers attached to a sandbox. #[command(subcommand)] Provider(SandboxProviderCommands), + + /// Manage reusable sandbox workload templates. + #[command(subcommand)] + Template(SandboxTemplateCommands), } #[derive(Subcommand, Debug)] @@ -1722,6 +1742,121 @@ enum SandboxProviderCommands { }, } +#[derive(Subcommand, Debug)] +// `Create` carries several optional strings and repeated key-value flags. This +// enum is only used for clap parsing, so boxing fields would add friction +// without a meaningful runtime win. +#[allow(clippy::large_enum_variant)] +enum SandboxTemplateCommands { + /// Create a reusable sandbox workload template. + #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] + Create { + /// Template name. + name: String, + + /// Container image for sandboxes created from this template. + /// When omitted, the gateway's default sandbox image is used at create time. + #[arg(long)] + image: Option, + + /// CPU limit for sandboxes created from this template (for example: 500m, 1, 2.5). + #[arg(long)] + cpu: Option, + + /// Memory limit for sandboxes created from this template (for example: 512Mi, 4Gi, 8G). + #[arg(long)] + memory: Option, + + /// Request GPU resources for sandboxes created from this template. + /// + /// Omit COUNT for the driver's default GPU selection, or pass COUNT + /// to request a specific number of GPUs. + #[arg(long, num_args = 0..=1, value_name = "COUNT", default_missing_value = "", value_parser = parse_gpu_request)] + gpu: Option, + + /// Experimental driver-keyed JSON object for driver-specific sandbox settings. + #[arg(long, value_name = "JSON")] + driver_config_json: Option, + + /// Target startup readiness duration for this template (for example: 30s, 5m, 1h). + #[arg(long, value_name = "DURATION")] + ready_within: Option, + + /// Maximum startup burst associated with this template. + #[arg(long, value_name = "COUNT", value_parser = clap::value_parser!(u32).range(1..))] + max_burst: Option, + + /// Attach labels to the template (key=value format, repeatable). + #[arg(long = "label", value_name = "KEY=VALUE")] + labels: Vec, + + /// Attach annotations to the template (key=value format, repeatable). + #[arg(long = "annotation", value_name = "KEY=VALUE")] + annotations: Vec, + + /// Set a non-secret environment variable in sandboxes created from this template. + /// Do not use this option for API keys, tokens, or other secrets; create + /// a provider and attach it when creating sandboxes instead. Repeatable. + #[arg(long = "env", value_name = "KEY=VALUE")] + envs: Vec, + + /// Suppress warnings when --env values look like credentials. + #[arg(long = "no-credential-warnings")] + no_credential_warnings: bool, + + /// Output format. + #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)] + output: OutputFormat, + }, + + /// Fetch a sandbox workload template by name. + #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] + Get { + /// Template name. + name: String, + + /// Output format. + #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table)] + output: OutputFormat, + }, + + /// List sandbox workload templates. + #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] + List { + /// Maximum number of templates to return. + #[arg(long, default_value_t = 100)] + limit: u32, + + /// Offset into the template list. + #[arg(long, default_value_t = 0)] + offset: u32, + + /// Filter templates by labels, e.g. env=prod,team=runtime. + #[arg(long)] + label_selector: Option, + + /// Print only template names (one per line). + #[arg(long, conflicts_with = "output")] + names: bool, + + /// Output format. + #[arg(short = 'o', long = "output", value_enum, default_value_t = OutputFormat::Table, conflicts_with = "names")] + output: OutputFormat, + + /// List templates across all workspaces (overrides --workspace). + #[arg(long)] + all_workspaces: bool, + }, + + /// Delete sandbox workload templates. + #[command(help_template = LEAF_HELP_TEMPLATE, next_help_heading = "FLAGS")] + Delete { + /// Template names. + #[arg(required = true, num_args = 1.., value_name = "NAME")] + names: Vec, + }, +} + #[derive(Subcommand, Debug)] enum DraftCommands { /// Show network rules for a sandbox. @@ -2255,6 +2390,11 @@ async fn run_async() -> Result<()> { CompleteEnv::with_factory(Cli::command).complete(); let cli = Cli::parse(); + + // Resolve colorization before anything is printed, so no command can emit + // escape sequences into a pipe. + color::init(cli.color); + let mut tls = TlsOptions::default(); tls.gateway_insecure = cli.gateway_insecure; @@ -2266,7 +2406,11 @@ async fn run_async() -> Result<()> { _ => "trace", }; + // The fmt formatter defaults to ANSI on with no terminal detection, and it + // writes to stdout, so without this `openshell -v ... | ...` pipes escapes + // to the caller. tracing_subscriber::fmt() + .with_ansi(color::stdout_enabled()) .with_env_filter( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new(log_level)), @@ -3043,6 +3187,7 @@ async fn run_async() -> Result<()> { match command { SandboxCommands::Create { name, + template, from, upload, no_git_ignore, @@ -3136,6 +3281,7 @@ async fn run_async() -> Result<()> { &ctx.name, run::SandboxCreateConfig { name: name.as_deref(), + template: template.as_deref(), from: from.as_deref(), uploads: &upload_specs, keep, @@ -3372,6 +3518,89 @@ async fn run_async() -> Result<()> { .await?; } }, + SandboxCommands::Template(command) => match command { + SandboxTemplateCommands::Create { + name, + image, + cpu, + memory, + gpu, + driver_config_json, + ready_within, + max_burst, + labels, + annotations, + envs, + no_credential_warnings, + output, + } => { + let labels = run::parse_key_value_pairs(&labels, "--label")?; + let annotations = + run::parse_key_value_pairs(&annotations, "--annotation")?; + let environment = run::parse_env_pairs(&envs)?; + run::warn_credential_env_vars(&environment, no_credential_warnings); + let gpu_requirements: Option = + gpu.map(Into::into); + run::sandbox_template_create( + endpoint, + &name, + image.as_deref(), + cpu.as_deref(), + memory.as_deref(), + gpu_requirements, + driver_config_json.as_deref(), + ready_within.as_deref(), + max_burst, + labels, + annotations, + environment, + output.as_str(), + &cli.workspace, + &tls, + ) + .await?; + } + SandboxTemplateCommands::Get { name, output } => { + run::sandbox_template_get( + endpoint, + &name, + output.as_str(), + &cli.workspace, + &tls, + ) + .await?; + } + SandboxTemplateCommands::List { + limit, + offset, + label_selector, + names, + output, + all_workspaces, + } => { + run::sandbox_template_list( + endpoint, + limit, + offset, + label_selector.as_deref(), + names, + output.as_str(), + &cli.workspace, + all_workspaces, + &tls, + ) + .await?; + } + SandboxTemplateCommands::Delete { names } => { + run::sandbox_template_delete( + endpoint, + &names, + &cli.workspace, + &tls, + ) + .await?; + } + }, } } } @@ -5590,6 +5819,226 @@ mod tests { } } + #[test] + fn sandbox_create_template_flag_parses() { + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "create", + "--template", + "gpu-kata", + "--provider", + "github", + ]) + .expect("sandbox create template flag should parse"); + + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Create { + template, + providers, + .. + }), + .. + }) => { + assert_eq!(template.as_deref(), Some("gpu-kata")); + assert_eq!(providers, vec!["github".to_string()]); + } + other => panic!("expected SandboxCommands::Create, got: {other:?}"), + } + } + + #[test] + fn sandbox_create_template_conflicts_with_inline_workload_flags() { + for (label, extra_args) in [ + ("--from", &["--from", "python:3.12"][..]), + ("--gpu", &["--gpu"][..]), + ("--cpu", &["--cpu", "1"][..]), + ("--memory", &["--memory", "2Gi"][..]), + ("--env", &["--env", "FOO=bar"][..]), + ( + "--driver-config-json", + &["--driver-config-json", r#"{"kubernetes":{}}"#][..], + ), + ] { + let args = ["openshell", "sandbox", "create", "--template", "base"] + .into_iter() + .chain(extra_args.iter().copied()); + let result = Cli::try_parse_from(args); + assert!(result.is_err(), "--template should conflict with {label}"); + } + } + + #[test] + fn sandbox_template_create_parses_workload_flags() { + let json = r#"{"kubernetes":{"pod":{"node_selector":{"pool":"gpu"}}}}"#; + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "template", + "create", + "gpu-kata", + "--image", + "registry.example.com/agent:latest", + "--cpu", + "2", + "--memory", + "4Gi", + "--gpu", + "1", + "--driver-config-json", + json, + "--ready-within", + "5m", + "--max-burst", + "3", + "--label", + "team=runtime", + "--annotation", + "owner=platform", + "--env", + "FEATURE_FLAG=on", + "--no-credential-warnings", + "--output", + "json", + ]) + .expect("sandbox template create should parse"); + + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Template(SandboxTemplateCommands::Create { + name, + image, + cpu, + memory, + gpu, + driver_config_json, + ready_within, + max_burst, + labels, + annotations, + envs, + no_credential_warnings, + output, + })), + .. + }) => { + assert_eq!(name, "gpu-kata"); + assert_eq!(image.as_deref(), Some("registry.example.com/agent:latest")); + assert_eq!(cpu.as_deref(), Some("2")); + assert_eq!(memory.as_deref(), Some("4Gi")); + assert_eq!(gpu, Some(GpuCliRequest::Count(1))); + assert_eq!(driver_config_json.as_deref(), Some(json)); + assert_eq!(ready_within.as_deref(), Some("5m")); + assert_eq!(max_burst, Some(3)); + assert_eq!(labels, vec!["team=runtime".to_string()]); + assert_eq!(annotations, vec!["owner=platform".to_string()]); + assert_eq!(envs, vec!["FEATURE_FLAG=on".to_string()]); + assert!(no_credential_warnings); + assert!(matches!(output, OutputFormat::Json)); + } + other => panic!("expected SandboxTemplateCommands::Create, got: {other:?}"), + } + } + + #[test] + fn sandbox_template_list_parses_names_and_all_workspaces() { + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "template", + "list", + "--names", + "--all-workspaces", + "--label-selector", + "team=runtime", + "--limit", + "25", + "--offset", + "5", + ]) + .expect("sandbox template list should parse"); + + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Template(SandboxTemplateCommands::List { + limit, + offset, + label_selector, + names, + all_workspaces, + .. + })), + .. + }) => { + assert_eq!(limit, 25); + assert_eq!(offset, 5); + assert_eq!(label_selector.as_deref(), Some("team=runtime")); + assert!(names); + assert!(all_workspaces); + } + other => panic!("expected SandboxTemplateCommands::List, got: {other:?}"), + } + } + + #[test] + fn sandbox_template_list_names_conflicts_with_output() { + let result = Cli::try_parse_from([ + "openshell", + "sandbox", + "template", + "list", + "--names", + "--output", + "json", + ]); + assert!(result.is_err()); + } + + #[test] + fn sandbox_template_create_image_is_optional() { + let cli = Cli::try_parse_from(["openshell", "sandbox", "template", "create", "base"]) + .expect("sandbox template create without --image should parse"); + + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Template(SandboxTemplateCommands::Create { image, .. })), + .. + }) => { + assert_eq!(image, None); + } + other => panic!("expected SandboxTemplateCommands::Create, got: {other:?}"), + } + } + + #[test] + fn sandbox_template_create_gpu_parses_driver_default() { + let cli = Cli::try_parse_from([ + "openshell", + "sandbox", + "template", + "create", + "gpu-kata", + "--gpu", + ]) + .expect("sandbox template create --gpu should parse"); + + match cli.command { + Some(Commands::Sandbox { + command: + Some(SandboxCommands::Template(SandboxTemplateCommands::Create { gpu, .. })), + .. + }) => { + assert_eq!(gpu, Some(GpuCliRequest::DriverDefault)); + } + other => panic!("expected SandboxTemplateCommands::Create, got: {other:?}"), + } + } + #[test] fn sandbox_create_gpu_parses_driver_default() { let cli = Cli::try_parse_from(["openshell", "sandbox", "create", "--gpu"]) diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index ea495d5c04..619a8bbd22 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -22,6 +22,7 @@ pub use crate::commands::gateway::{ gateway_logout, gateway_remove, gateway_select, gateway_status, gateway_use, }; +use crate::color::Colorize; use crate::policy_update::build_policy_update_plan; use crate::tls::{TlsOptions, grpc_client, grpc_inference_client}; use dialoguer::Confirm; @@ -36,26 +37,28 @@ use openshell_core::proto::ProviderProfileCategory; use openshell_core::proto::{ ApproveAllDraftChunksRequest, ApproveDraftChunkRequest, AttachSandboxProviderRequest, ClearDraftChunksRequest, ConfigureProviderRefreshRequest, CreateProviderRequest, - CreateSandboxRequest, CreateSshSessionRequest, DeleteInferenceRouteRequest, - DeleteProviderProfileRequest, DeleteProviderRefreshRequest, DeleteProviderRequest, - DeleteSandboxRequest, DeleteServiceRequest, DetachSandboxProviderRequest, ExecSandboxRequest, - ExposeServiceRequest, GetCurrentUserRequest, GetDraftHistoryRequest, GetDraftPolicyRequest, - GetGatewayConfigRequest, GetInferenceRouteRequest, GetProviderProfileRequest, - GetProviderRefreshStatusRequest, GetProviderRequest, GetSandboxConfigRequest, - GetSandboxConfigResponse, GetSandboxLogsRequest, GetSandboxPolicyStatusRequest, - GetSandboxRequest, GetServiceRequest, GpuResourceRequirements, ImportProviderProfilesRequest, - LintProviderProfilesRequest, ListProviderProfilesRequest, ListProvidersRequest, - ListSandboxPoliciesRequest, ListSandboxProvidersRequest, ListSandboxesRequest, + CreateSandboxRequest, CreateSandboxTemplateRequest, CreateSshSessionRequest, + DeleteInferenceRouteRequest, DeleteProviderProfileRequest, DeleteProviderRefreshRequest, + DeleteProviderRequest, DeleteSandboxRequest, DeleteSandboxTemplateRequest, + DeleteServiceRequest, DetachSandboxProviderRequest, ExecSandboxRequest, ExposeServiceRequest, + GetCurrentUserRequest, GetDraftHistoryRequest, GetDraftPolicyRequest, GetGatewayConfigRequest, + GetInferenceRouteRequest, GetProviderProfileRequest, GetProviderRefreshStatusRequest, + GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest, + GetSandboxPolicyStatusRequest, GetSandboxRequest, GetSandboxTemplateRequest, GetServiceRequest, + GpuResourceRequirements, ImportProviderProfilesRequest, LintProviderProfilesRequest, + ListProviderProfilesRequest, ListProvidersRequest, ListSandboxPoliciesRequest, + ListSandboxProvidersRequest, ListSandboxTemplatesRequest, ListSandboxesRequest, ListServicesRequest, PolicySource, PolicyStatus, Provider, ProviderCredentialRefreshRecoveryAction, ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrantType, ProviderProfile, ProviderProfileDiagnostic, ProviderProfileImportItem, RejectDraftChunkRequest, ResourceRequirements, RevokeSshSessionRequest, RotateProviderCredentialRequest, Sandbox, - SandboxPhase, SandboxPolicy, SandboxSpec, SandboxTemplate, ServiceEndpointResponse, - SetInferenceRouteRequest, SettingScope, StartSandboxRequest, StopSandboxRequest, - TcpForwardFrame, TcpForwardInit, TcpRelayTarget, UpdateConfigRequest, - UpdateProviderProfilesRequest, UpdateProviderRequest, WatchSandboxRequest, exec_sandbox_event, - tcp_forward_init, + SandboxPhase, SandboxPolicy, SandboxResources, SandboxServiceLevel, SandboxSpec, + SandboxStartup, SandboxTemplate, SandboxWorkloadConfig, SandboxWorkloadTemplate, + SandboxWorkloadTemplateSpec, ServiceEndpointResponse, SetInferenceRouteRequest, SettingScope, + StartSandboxRequest, StopSandboxRequest, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, + UpdateConfigRequest, UpdateProviderProfilesRequest, UpdateProviderRequest, WatchSandboxRequest, + exec_sandbox_event, tcp_forward_init, }; use openshell_core::settings; use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; @@ -64,7 +67,6 @@ use openshell_providers::{ normalize_profile_id, normalize_provider_type, parse_profile_json, parse_profile_yaml, profile_to_json, profile_to_yaml, profiles_to_json, profiles_to_yaml, }; -use owo_colors::OwoColorize; use std::borrow::Cow; use std::collections::{HashMap, HashSet}; use std::io::{ErrorKind, IsTerminal, Read, Write}; @@ -119,6 +121,20 @@ impl ProgressOutput { } } +fn aggregate_delete_failures(resource: &str, failures: &[String]) -> Result<()> { + if failures.is_empty() { + Ok(()) + } else { + Err(miette!( + "failed to delete {} {}{}: {}", + failures.len(), + resource, + if failures.len() == 1 { "" } else { "s" }, + failures.join(", ") + )) + } +} + #[derive(Debug, Clone)] struct CurrentUserView { subject: String, @@ -386,6 +402,7 @@ async fn finalize_sandbox_create_session( #[derive(Debug)] pub struct SandboxCreateConfig<'a> { pub name: Option<&'a str>, + pub template: Option<&'a str>, pub from: Option<&'a str>, pub uploads: &'a [(String, Option, bool)], pub keep: bool, @@ -411,6 +428,7 @@ impl Default for SandboxCreateConfig<'_> { fn default() -> Self { Self { name: None, + template: None, from: None, uploads: &[], keep: false, @@ -444,6 +462,7 @@ pub async fn sandbox_create( ) -> Result { let SandboxCreateConfig { name, + template, from, uploads, keep, @@ -497,23 +516,42 @@ pub async fn sandbox_create( let effective_server = server.to_string(); let effective_tls = tls.clone(); + if template.is_some() + && (from.is_some() + || gpu_requirements.is_some() + || cpu.is_some() + || memory.is_some() + || driver_config_json.is_some() + || !environment.is_empty()) + { + return Err(miette::miette!( + "--template cannot be combined with inline workload flags" + )); + } + // Resolve the --from flag into a container image reference, building from - // a Dockerfile first if necessary. - let image: Option = match from { - Some(val) => { - let resolved = resolve_from(val)?; - match resolved { - ResolvedSource::Image(img) => Some(img), - ResolvedSource::Dockerfile { - dockerfile, - context, - } => { - let tag = build_from_dockerfile(&dockerfile, &context, gateway_name).await?; - Some(tag) + // a Dockerfile first if necessary. Template creates resolve workload shape + // on the gateway and skip local image handling. + let image: Option = if template.is_some() { + None + } else { + match from { + Some(val) => { + let resolved = resolve_from(val)?; + match resolved { + ResolvedSource::Image(img) => Some(img), + ResolvedSource::Dockerfile { + dockerfile, + context, + } => { + let tag = + build_from_dockerfile(&dockerfile, &context, gateway_name).await?; + Some(tag) + } } } + None => None, } - None => None, }; let inferred_types: Vec = inferred_provider_type(command).into_iter().collect(); let configured_providers = ensure_required_providers( @@ -526,12 +564,21 @@ pub async fn sandbox_create( .await?; let policy = load_sandbox_policy(policy)?; - let resource_limits = build_sandbox_resource_limits(cpu, memory)?; - let driver_config = driver_config_json - .map(parse_driver_config_json) - .transpose()?; + let resource_limits = if template.is_none() { + build_sandbox_resource_limits(cpu, memory)? + } else { + None + }; + let driver_config = if template.is_none() { + driver_config_json + .map(parse_driver_config_json) + .transpose()? + } else { + None + }; - let template = if image.is_some() || resource_limits.is_some() || driver_config.is_some() { + let inline_template = if image.is_some() || resource_limits.is_some() || driver_config.is_some() + { Some(SandboxTemplate { image: image.unwrap_or_default(), resources: resource_limits, @@ -568,10 +615,14 @@ pub async fn sandbox_create( let request = CreateSandboxRequest { spec: Some(SandboxSpec { resource_requirements, - environment, + environment: if template.is_none() { + environment + } else { + HashMap::new() + }, policy, providers: configured_providers, - template, + template: inline_template, command: main_command, tty: main_terminal, ..SandboxSpec::default() @@ -581,6 +632,7 @@ pub async fn sandbox_create( annotations, workspace: workspace.to_string(), await_main_process_attachment, + workload_template_name: template.unwrap_or_default().to_string(), }; let response = match client.create_sandbox(request).await { @@ -1427,6 +1479,15 @@ pub async fn sandbox_get( } } + if let Some(provenance) = &sandbox.created_from_workload_template { + println!( + " {} {}@{}", + "Workload template:".dimmed(), + provenance.name, + provenance.resource_version + ); + } + let policy_from_global = config.policy_source == PolicySource::Global as i32; println!( " {} {}", @@ -2212,6 +2273,16 @@ fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value { || serde_json::json!({}), |m| serde_json::json!(m.annotations), ); + let created_from_workload_template = + sandbox + .created_from_workload_template + .as_ref() + .map(|provenance| { + serde_json::json!({ + "name": provenance.name, + "resource_version": provenance.resource_version, + }) + }); serde_json::json!({ "id": sandbox.object_id(), "name": sandbox.object_name(), @@ -2223,6 +2294,7 @@ fn sandbox_to_json(sandbox: &Sandbox) -> serde_json::Value { "phase": phase_name(sandbox.phase()), "current_policy_version": sandbox.current_policy_version(), "exit_code": sandbox.status.as_ref().and_then(|status| status.exit_code), + "created_from_workload_template": created_from_workload_template, }) } @@ -2482,6 +2554,583 @@ fn format_provider_attachment_table(providers: &[Provider], color: bool) -> Stri output } +#[allow(clippy::too_many_arguments, clippy::implicit_hasher)] +pub async fn sandbox_template_create( + server: &str, + name: &str, + image: Option<&str>, + cpu: Option<&str>, + memory: Option<&str>, + gpu_requirements: Option, + driver_config_json: Option<&str>, + ready_within: Option<&str>, + max_burst: Option, + labels: HashMap, + annotations: HashMap, + environment: HashMap, + output: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let resources = if cpu.is_some() || memory.is_some() || gpu_requirements.is_some() { + Some(SandboxResources { + cpu: cpu + .map(validate_cpu_quantity) + .transpose()? + .unwrap_or_default(), + memory: memory + .map(validate_memory_quantity) + .transpose()? + .unwrap_or_default(), + gpu: gpu_requirements, + }) + } else { + None + }; + let driver_config = driver_config_json + .map(parse_driver_config_json) + .transpose()?; + let desired_service_level = build_template_service_level(ready_within, max_burst)?; + + let mut client = grpc_client(server, tls).await?; + let response = client + .create_sandbox_template(CreateSandboxTemplateRequest { + template: Some(SandboxWorkloadTemplate { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: String::new(), + name: name.to_string(), + created_at_ms: 0, + labels, + resource_version: 0, + annotations, + workspace: String::new(), + deletion_timestamp_ms: 0, + }), + spec: Some(SandboxWorkloadTemplateSpec { + workload: Some(SandboxWorkloadConfig { + image: image.unwrap_or_default().to_string(), + environment, + resources, + }), + driver_config, + desired_service_level, + }), + }), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + + let template = response + .into_inner() + .template + .ok_or_else(|| miette!("sandbox template missing from response"))?; + if crate::output::print_output_single(output, &template, sandbox_template_to_json)? { + return Ok(()); + } + println!( + "{} Created sandbox template {}", + "✓".green().bold(), + template.object_name().bold() + ); + Ok(()) +} + +fn build_template_service_level( + ready_within: Option<&str>, + max_burst: Option, +) -> Result> { + if ready_within.is_none() && max_burst.is_none() { + return Ok(None); + } + let ready_within = ready_within + .map(parse_duration_to_ms) + .transpose()? + .map(|ms| { + if ms <= 0 { + Err(miette!("--ready-within must be greater than zero")) + } else { + Ok(duration_ms_to_proto(ms)) + } + }) + .transpose()?; + Ok(Some(SandboxServiceLevel { + startup: Some(SandboxStartup { + ready_within, + max_burst: max_burst.unwrap_or_default(), + }), + })) +} + +fn duration_ms_to_proto(ms: i64) -> prost_types::Duration { + prost_types::Duration { + seconds: ms / 1_000, + nanos: i32::try_from((ms % 1_000) * 1_000_000) + .expect("duration millisecond remainder fits in protobuf nanos"), + } +} + +pub async fn sandbox_template_get( + server: &str, + name: &str, + output: &str, + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .get_sandbox_template(GetSandboxTemplateRequest { + name: name.to_string(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + let template = response + .into_inner() + .template + .ok_or_else(|| miette!("sandbox template missing from response"))?; + + if crate::output::print_output_single(output, &template, sandbox_template_to_json)? { + return Ok(()); + } + + print_sandbox_template_detail(&template); + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +pub async fn sandbox_template_list( + server: &str, + limit: u32, + offset: u32, + label_selector: Option<&str>, + names_only: bool, + output: &str, + workspace: &str, + all_workspaces: bool, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + let response = client + .list_sandbox_templates(ListSandboxTemplatesRequest { + limit, + offset, + workspace: if all_workspaces { + String::new() + } else { + workspace.to_string() + }, + all_workspaces, + label_selector: label_selector.unwrap_or_default().to_string(), + }) + .await + .into_diagnostic()?; + let templates = response.into_inner().templates; + + if crate::output::print_output_collection(output, &templates, sandbox_template_to_json)? { + return Ok(()); + } + + if templates.is_empty() { + if !names_only { + println!("No sandbox templates found."); + } + return Ok(()); + } + + if names_only { + for template in &templates { + if all_workspaces { + println!("{}/{}", template.object_workspace(), template.object_name()); + } else { + println!("{}", template.object_name()); + } + } + return Ok(()); + } + + print_sandbox_template_table(&templates, all_workspaces); + Ok(()) +} + +pub async fn sandbox_template_delete( + server: &str, + names: &[String], + workspace: &str, + tls: &TlsOptions, +) -> Result<()> { + let mut client = grpc_client(server, tls).await?; + for name in names { + let response = client + .delete_sandbox_template(DeleteSandboxTemplateRequest { + name: name.clone(), + workspace: workspace.to_string(), + }) + .await + .into_diagnostic()?; + if response.into_inner().deleted { + println!("{} Deleted sandbox template {name}", "✓".green().bold()); + } else { + println!("Sandbox template {name} not found."); + } + } + Ok(()) +} + +fn sandbox_template_to_json(template: &SandboxWorkloadTemplate) -> serde_json::Value { + let mut obj = serde_json::Map::new(); + obj.insert("id".to_string(), serde_json::json!(template.object_id())); + obj.insert( + "name".to_string(), + serde_json::json!(template.object_name()), + ); + obj.insert( + "workspace".to_string(), + serde_json::json!(template.object_workspace()), + ); + + if let Some(metadata) = &template.metadata { + if metadata.resource_version != 0 { + obj.insert( + "resource_version".to_string(), + serde_json::json!(metadata.resource_version), + ); + } + if metadata.created_at_ms != 0 { + obj.insert( + "created_at".to_string(), + serde_json::json!(format_epoch_ms(metadata.created_at_ms)), + ); + } + if !metadata.labels.is_empty() { + obj.insert("labels".to_string(), serde_json::json!(metadata.labels)); + } + if !metadata.annotations.is_empty() { + obj.insert( + "annotations".to_string(), + serde_json::json!(metadata.annotations), + ); + } + } + + if let Some(spec) = &template.spec { + if let Some(workload) = &spec.workload { + obj.insert("image".to_string(), serde_json::json!(workload.image)); + if !workload.environment.is_empty() { + obj.insert( + "environment".to_string(), + serde_json::json!(workload.environment), + ); + } + if let Some(resources) = &workload.resources { + let mut resources_json = serde_json::Map::new(); + if !resources.cpu.is_empty() { + resources_json.insert("cpu".to_string(), serde_json::json!(resources.cpu)); + } + if !resources.memory.is_empty() { + resources_json + .insert("memory".to_string(), serde_json::json!(resources.memory)); + } + if let Some(gpu) = &resources.gpu { + let value = gpu + .count + .map_or_else(|| serde_json::json!("default"), serde_json::Value::from); + resources_json.insert("gpu".to_string(), value); + } + if !resources_json.is_empty() { + obj.insert( + "resources".to_string(), + serde_json::Value::Object(resources_json), + ); + } + } + } + if let Some(driver_config) = &spec.driver_config { + obj.insert( + "driver_config".to_string(), + openshell_core::proto_struct::struct_to_json_value(driver_config), + ); + } + if let Some(service_level) = &spec.desired_service_level + && let Some(startup) = &service_level.startup + { + let mut startup_json = serde_json::Map::new(); + if let Some(ready_within) = &startup.ready_within { + startup_json.insert( + "ready_within_ms".to_string(), + serde_json::json!(duration_to_ms(ready_within)), + ); + } + if startup.max_burst != 0 { + startup_json.insert( + "max_burst".to_string(), + serde_json::json!(startup.max_burst), + ); + } + if !startup_json.is_empty() { + obj.insert( + "startup".to_string(), + serde_json::Value::Object(startup_json), + ); + } + } + } + + serde_json::Value::Object(obj) +} + +fn print_sandbox_template_detail(template: &SandboxWorkloadTemplate) { + println!("{}", "Sandbox template:".cyan().bold()); + println!(); + println!(" {} {}", "Name:".dimmed(), template.object_name()); + println!( + " {} {}", + "Workspace:".dimmed(), + template.object_workspace() + ); + if let Some(metadata) = &template.metadata { + println!(" {} {}", "Id:".dimmed(), metadata.id); + println!( + " {} {}", + "Resource version:".dimmed(), + metadata.resource_version + ); + if metadata.created_at_ms != 0 { + println!( + " {} {}", + "Created:".dimmed(), + format_epoch_ms(metadata.created_at_ms) + ); + } + let labels = labels_display(&metadata.labels); + println!( + " {} {}", + "Labels:".dimmed(), + non_empty_or(&labels, "") + ); + } + if let Some(spec) = &template.spec + && let Some(workload) = &spec.workload + { + println!( + " {} {}", + "Image:".dimmed(), + non_empty_or(&workload.image, "") + ); + println!( + " {} {}", + "Environment:".dimmed(), + workload.environment.len() + ); + if let Some(resources) = &workload.resources { + println!( + " {} {}", + "CPU:".dimmed(), + non_empty_or(&resources.cpu, "") + ); + println!( + " {} {}", + "Memory:".dimmed(), + non_empty_or(&resources.memory, "") + ); + println!( + " {} {}", + "GPU:".dimmed(), + template_resources_gpu_display(resources).unwrap_or_else(|| "".to_string()) + ); + } + } + if let Some(startup) = template_startup(template) { + println!( + " {} {}", + "Ready within:".dimmed(), + startup + .ready_within + .as_ref() + .map_or_else(|| "".to_string(), duration_display) + ); + println!( + " {} {}", + "Max burst:".dimmed(), + if startup.max_burst == 0 { + "".to_string() + } else { + startup.max_burst.to_string() + } + ); + } +} + +fn print_sandbox_template_table(templates: &[SandboxWorkloadTemplate], show_workspace: bool) { + let name_width = templates + .iter() + .map(|template| template.object_name().len()) + .max() + .unwrap_or(4) + .max(4); + let workspace_width = if show_workspace { + templates + .iter() + .map(|template| template.object_workspace().len()) + .max() + .unwrap_or(9) + .max(9) + } else { + 0 + }; + let image_width = templates + .iter() + .map(|template| template_image(template).len()) + .max() + .unwrap_or(5) + .clamp(5, 48); + + if show_workspace { + println!( + "{: String { + template + .spec + .as_ref() + .and_then(|spec| spec.workload.as_ref()) + .map_or_else( + || "".to_string(), + |workload| non_empty_or(&workload.image, "").to_string(), + ) +} + +fn template_resources(template: &SandboxWorkloadTemplate) -> Option<&SandboxResources> { + template + .spec + .as_ref() + .and_then(|spec| spec.workload.as_ref()) + .and_then(|workload| workload.resources.as_ref()) +} + +fn template_resources_gpu_display(resources: &SandboxResources) -> Option { + if let Some(gpu) = &resources.gpu { + return Some( + gpu.count + .map_or_else(|| "default".to_string(), |count| count.to_string()), + ); + } + None +} + +fn template_startup(template: &SandboxWorkloadTemplate) -> Option<&SandboxStartup> { + template + .spec + .as_ref() + .and_then(|spec| spec.desired_service_level.as_ref()) + .and_then(|service_level| service_level.startup.as_ref()) +} + +fn duration_to_ms(duration: &prost_types::Duration) -> i64 { + duration.seconds.saturating_mul(1_000) + i64::from(duration.nanos / 1_000_000) +} + +fn duration_display(duration: &prost_types::Duration) -> String { + let total_ms = duration_to_ms(duration); + if total_ms % 3_600_000 == 0 { + format!("{}h", total_ms / 3_600_000) + } else if total_ms % 60_000 == 0 { + format!("{}m", total_ms / 60_000) + } else if total_ms % 1_000 == 0 { + format!("{}s", total_ms / 1_000) + } else { + format!("{total_ms}ms") + } +} + +fn labels_display(labels: &HashMap) -> String { + let mut pairs = labels + .iter() + .map(|(key, value)| format!("{key}={value}")) + .collect::>(); + pairs.sort(); + pairs.join(", ") +} + /// Delete a sandbox by name, or all sandboxes when `all` is true. pub async fn sandbox_delete( server: &str, @@ -2518,6 +3167,7 @@ pub async fn sandbox_delete( names.to_vec() }; + let mut failures = Vec::new(); for name in &names_to_delete { // Stop any background port forwards for this sandbox before deleting. if let Ok(stopped) = stop_forwards_for_sandbox(name) { @@ -2542,7 +3192,14 @@ pub async fn sandbox_delete( println!("{} Sandbox {name} already deleted", "✓".green().bold()); continue; } - Err(status) => return Err(status).into_diagnostic(), + Err(status) => { + eprintln!( + "{} Failed to delete sandbox {name}: {status}", + "!".red().bold() + ); + failures.push(name.clone()); + continue; + } }; let deleted = response.into_inner().deleted; @@ -2554,7 +3211,7 @@ pub async fn sandbox_delete( } } - Ok(()) + aggregate_delete_failures("sandbox", &failures) } /// Stop a sandbox while retaining its persistent workspace. @@ -4423,22 +5080,32 @@ pub async fn provider_profile_delete( tls: &TlsOptions, ) -> Result<()> { let mut client = grpc_client(server, tls).await?; + let mut failures = Vec::new(); for id in ids { - let response = client + let response = match client .delete_provider_profile(DeleteProviderProfileRequest { id: id.clone(), workspace: workspace.to_string(), }) .await - .into_diagnostic()? - .into_inner(); + { + Ok(response) => response.into_inner(), + Err(status) => { + eprintln!( + "{} Failed to delete provider profile {id}: {status}", + "!".red().bold() + ); + failures.push(id.clone()); + continue; + } + }; if response.deleted { println!("{} Deleted provider profile {id}", "✓".green().bold()); } else { println!("{} Provider profile {id} not found", "!".yellow()); } } - Ok(()) + aggregate_delete_failures("provider profile", &failures) } pub async fn provider_refresh_status( @@ -5070,21 +5737,32 @@ pub async fn provider_delete( tls: &TlsOptions, ) -> Result<()> { let mut client = grpc_client(server, tls).await?; + let mut failures = Vec::new(); for name in names { - let response = client + let response = match client .delete_provider(DeleteProviderRequest { name: name.clone(), workspace: workspace.to_string(), }) .await - .into_diagnostic()?; + { + Ok(response) => response, + Err(status) => { + eprintln!( + "{} Failed to delete provider {name}: {status}", + "!".red().bold() + ); + failures.push(name.clone()); + continue; + } + }; if response.into_inner().deleted { println!("{} Deleted provider {name}", "✓".green().bold()); } else { println!("{} Provider {name} not found", "!".yellow()); } } - Ok(()) + aggregate_delete_failures("provider", &failures) } // --------------------------------------------------------------------------- @@ -7632,8 +8310,10 @@ mod tests { ProviderCredentialRefreshStatus, ProviderCredentialRefreshStrategy, ProviderCredentialTokenGrant, ProviderProfile, ProviderProfileCredential, ResourceRequirements, Sandbox, SandboxCondition, SandboxPhase, SandboxPolicy, - SandboxPolicyRevision, SandboxStatus, ServiceEndpoint, ServiceEndpointResponse, - WorkspaceMember, WorkspaceRole, datamodel::v1::ObjectMeta, + SandboxPolicyRevision, SandboxResources, SandboxStatus, SandboxWorkloadConfig, + SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec, + ServiceEndpoint, ServiceEndpointResponse, WorkspaceMember, WorkspaceRole, + datamodel::v1::ObjectMeta, }; #[test] @@ -9096,6 +9776,74 @@ mod tests { assert_eq!(json["labels"]["env"], "prod"); } + #[test] + fn sandbox_template_to_json_includes_metadata_labels_and_annotations() { + let template = SandboxWorkloadTemplate { + metadata: Some(ObjectMeta { + id: "template-123".to_string(), + name: "gpu-kata".to_string(), + labels: std::collections::HashMap::from([( + "team".to_string(), + "runtime".to_string(), + )]), + annotations: std::collections::HashMap::from([( + "owner".to_string(), + "platform".to_string(), + )]), + workspace: "default".to_string(), + ..Default::default() + }), + ..Default::default() + }; + + let json = super::sandbox_template_to_json(&template); + + assert_eq!(json["labels"]["team"], "runtime"); + assert_eq!(json["annotations"]["owner"], "platform"); + } + + #[test] + fn sandbox_template_to_json_formats_default_gpu_like_display_output() { + let template = SandboxWorkloadTemplate { + spec: Some(SandboxWorkloadTemplateSpec { + workload: Some(SandboxWorkloadConfig { + resources: Some(SandboxResources { + gpu: Some(GpuResourceRequirements { count: None }), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }; + + let json = super::sandbox_template_to_json(&template); + + assert_eq!(json["resources"]["gpu"], "default"); + } + + #[test] + fn sandbox_template_to_json_preserves_explicit_gpu_count_as_number() { + let template = SandboxWorkloadTemplate { + spec: Some(SandboxWorkloadTemplateSpec { + workload: Some(SandboxWorkloadConfig { + resources: Some(SandboxResources { + gpu: Some(GpuResourceRequirements { count: Some(2) }), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }; + + let json = super::sandbox_template_to_json(&template); + + assert_eq!(json["resources"]["gpu"], 2); + } + #[test] fn provider_to_json_omits_zero_metadata_fields() { let metadata = ObjectMeta { @@ -9194,6 +9942,10 @@ mod tests { created_at_ms: 1_609_459_200_000, ..Default::default() }), + created_from_workload_template: Some(SandboxWorkloadTemplateProvenance { + name: "gpu-kata".to_string(), + resource_version: "7".to_string(), + }), ..Default::default() }; sandbox.set_phase(SandboxPhase::Ready as i32); @@ -9213,6 +9965,11 @@ mod tests { assert_eq!(json["policy_source"], "global"); assert_eq!(json["revision"], 3); assert!(json["policy"].is_null()); + assert_eq!(json["created_from_workload_template"]["name"], "gpu-kata"); + assert_eq!( + json["created_from_workload_template"]["resource_version"], + "7" + ); } #[test] diff --git a/crates/openshell-cli/src/ssh.rs b/crates/openshell-cli/src/ssh.rs index 1e1e48257a..126cea652d 100644 --- a/crates/openshell-cli/src/ssh.rs +++ b/crates/openshell-cli/src/ssh.rs @@ -3,6 +3,7 @@ //! SSH connection and proxy utilities. +use crate::color::Colorize; use crate::tls::{TlsOptions, grpc_client}; use miette::{IntoDiagnostic, Result, WrapErr}; #[cfg(unix)] @@ -16,7 +17,6 @@ use openshell_core::proto::{ tcp_forward_init, }; use openshell_core::{ObjectId, driver_mounts}; -use owo_colors::OwoColorize; use std::fs; use std::future::Future; use std::io::{IsTerminal, Write}; diff --git a/crates/openshell-cli/tests/cli_color_integration.rs b/crates/openshell-cli/tests/cli_color_integration.rs new file mode 100644 index 0000000000..23109e9774 --- /dev/null +++ b/crates/openshell-cli/tests/cli_color_integration.rs @@ -0,0 +1,315 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! End-to-end checks that `openshell` does not write ANSI escape sequences into +//! a pipe. +//! +//! `Command::output` gives the child a pipe rather than a terminal, which is +//! exactly the situation these tests care about: a supervisor script parsing +//! output. The unit tests in `color` cover the precedence rules; these cover the +//! wiring from flag to rendered byte, across both styling paths that reach +//! stdout — the styled tables and the `tracing` formatter. + +#![cfg(unix)] + +use std::path::Path; +use std::process::Command; + +const ESC: char = '\u{1b}'; +const SANDBOX: &str = "openclaw-saw"; +const PORT: u16 = 8443; + +/// Seed a forward PID file so `forward list` has a row to render. +/// +/// The PID is one that cannot be running, so the row reports `dead`. Status text +/// is irrelevant here — both states go through the same styling path. +fn config_dir_with_forward(root: &Path) { + let forwards = root.join("openshell").join("forwards"); + std::fs::create_dir_all(&forwards).expect("create forwards dir"); + std::fs::write( + forwards.join(format!("{SANDBOX}-{PORT}.pid")), + // Format: \t\t + "4000000\tsbx-test\t0.0.0.0", + ) + .expect("write forward pid file"); +} + +fn forward_list(config_dir: &Path, args: &[&str], no_color: Option<&str>) -> String { + let mut command = Command::new(env!("CARGO_BIN_EXE_openshell")); + command + .args(["forward", "list"]) + .args(args) + .env("XDG_CONFIG_HOME", config_dir) + .env_remove("NO_COLOR") + .env_remove("FORCE_COLOR") + .env_remove("OPENSHELL_COLOR"); + if let Some(value) = no_color { + command.env("NO_COLOR", value); + } + + let output = command.output().expect("run openshell forward list"); + let stdout = String::from_utf8(output.stdout).expect("stdout is utf-8"); + assert!( + stdout.contains(SANDBOX), + "expected the seeded forward in the table, got: {stdout:?}" + ); + stdout +} + +#[test] +fn piped_output_is_free_of_escape_sequences_by_default() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + config_dir_with_forward(tmpdir.path()); + + let stdout = forward_list(tmpdir.path(), &[], None); + + assert!( + !stdout.contains(ESC), + "piped `forward list` must not emit ANSI escapes, got: {stdout:?}" + ); +} + +#[test] +fn no_color_environment_variable_is_honored() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + config_dir_with_forward(tmpdir.path()); + + let stdout = forward_list(tmpdir.path(), &[], Some("1")); + + assert!(!stdout.contains(ESC), "NO_COLOR ignored, got: {stdout:?}"); +} + +#[test] +fn color_never_suppresses_escape_sequences() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + config_dir_with_forward(tmpdir.path()); + + let stdout = forward_list(tmpdir.path(), &["--color", "never"], None); + + assert!( + !stdout.contains(ESC), + "--color never ignored, got: {stdout:?}" + ); +} + +#[test] +fn color_always_emits_escape_sequences_into_a_pipe() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + config_dir_with_forward(tmpdir.path()); + + // The opt-in escape hatch for callers who pipe into a pager and still want + // styling. Also proves the other cases are suppressing real output rather + // than rendering an empty table. + let stdout = forward_list(tmpdir.path(), &["--color", "always"], None); + + assert!( + stdout.contains(ESC), + "--color always must still colorize, got: {stdout:?}" + ); +} + +#[test] +fn explicit_color_flag_overrides_no_color() { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + config_dir_with_forward(tmpdir.path()); + + let stdout = forward_list(tmpdir.path(), &["--color", "always"], Some("1")); + + assert!( + stdout.contains(ESC), + "--color always must outrank NO_COLOR, got: {stdout:?}" + ); +} + +/// Run a command that fails to connect, with logging turned up so the `tracing` +/// formatter produces output. +/// +/// `tracing_subscriber::fmt` writes to stdout with ANSI enabled and does no +/// terminal detection of its own, so this is a second, independent way for +/// escapes to reach a pipe. +fn failing_connect(args: &[&str]) -> (String, String) { + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + let output = Command::new(env!("CARGO_BIN_EXE_openshell")) + .args([ + "sandbox", + "list", + "--gateway", + "test-gateway", + // Nothing listens on port 1; the connection is refused immediately. + "--gateway-endpoint", + "http://127.0.0.1:1", + ]) + .args(args) + .env("XDG_CONFIG_HOME", tmpdir.path()) + .env("RUST_LOG", "debug") + .env_remove("NO_COLOR") + .env_remove("FORCE_COLOR") + .env_remove("OPENSHELL_COLOR") + .output() + .expect("run openshell sandbox list"); + + ( + String::from_utf8_lossy(&output.stdout).into_owned(), + String::from_utf8_lossy(&output.stderr).into_owned(), + ) +} + +fn verbose_log_output(args: &[&str]) -> String { + failing_connect(args).0 +} + +#[test] +fn tracing_output_is_free_of_escape_sequences_when_piped() { + let plain = verbose_log_output(&[]); + let styled = verbose_log_output(&["--color", "always"]); + + // Positive control. If this fails, the command stopped emitting logs at + // debug level — fix the invocation rather than deleting the assertion + // below, which would otherwise pass vacuously. + assert!( + styled.contains(ESC), + "expected `--color always` to style log output; got: {styled:?}" + ); + assert!( + !plain.contains(ESC), + "piped log output must not emit ANSI escapes, got: {plain:?}" + ); +} + +/// Run a failing command with stdout attached to a pseudo-terminal and stderr +/// on a pipe, returning what each stream received. +/// +/// `Command::output` gives both streams pipes, so it cannot distinguish a +/// per-stream decision from a single one resolved off stdout. This asymmetric +/// setup is the only way to catch a stream being handed the other stream's +/// answer. +#[cfg(target_os = "linux")] +fn split_streams_stdout_tty(args: &[&str]) -> (String, String) { + use std::io::Read; + use std::os::fd::{AsRawFd, OwnedFd}; + + let pty = nix::pty::openpty(None, None).expect("openpty"); + let controller: OwnedFd = pty.master; + let follower: OwnedFd = pty.slave; + + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + let mut child = Command::new(env!("CARGO_BIN_EXE_openshell")) + .args([ + "sandbox", + "list", + "--gateway", + "test-gateway", + "--gateway-endpoint", + "http://127.0.0.1:1", + ]) + .args(args) + .env("XDG_CONFIG_HOME", tmpdir.path()) + .env("RUST_LOG", "debug") + .env_remove("NO_COLOR") + .env_remove("FORCE_COLOR") + .env_remove("OPENSHELL_COLOR") + .stdout(follower.try_clone().expect("dup pty follower")) + .stderr(std::process::Stdio::piped()) + .spawn() + .expect("spawn openshell"); + + // Drop every follower handle in this process, or reading the controller + // blocks forever instead of returning EIO once the child exits. + drop(follower); + + let mut stderr_buf = String::new(); + child + .stderr + .take() + .expect("stderr pipe") + .read_to_string(&mut stderr_buf) + .expect("read stderr"); + child.wait().expect("wait for openshell"); + + // The pty read ends with EIO rather than a clean EOF; treat that as done. + let mut stdout_buf = Vec::new(); + let mut chunk = [0u8; 4096]; + loop { + match nix::unistd::read(controller.as_raw_fd(), &mut chunk) { + Ok(0) | Err(_) => break, + Ok(n) => stdout_buf.extend_from_slice(&chunk[..n]), + } + } + + ( + String::from_utf8_lossy(&stdout_buf).into_owned(), + stderr_buf, + ) +} + +/// Regression test for a redirected stream inheriting the other stream's +/// terminal check. +/// +/// With stdout on a terminal and stderr redirected, `openshell ... 2> build.log` +/// must leave the log free of escapes while stdout stays styled. +#[cfg(target_os = "linux")] +#[test] +fn redirected_stderr_stays_plain_while_stdout_is_a_terminal() { + let (stdout, stderr) = split_streams_stdout_tty(&[]); + + // Positive control: stdout really is a terminal here, so something must be + // styled. Otherwise the stderr assertion could pass for the wrong reason. + assert!( + stdout.contains(ESC), + "expected styled stdout on a pty; got: {stdout:?}" + ); + assert!( + !stderr.contains(ESC), + "redirected stderr must not receive escapes, got: {stderr:?}" + ); +} + +#[test] +fn error_output_follows_the_color_setting() { + // miette renders errors to stderr through its own handler. It already + // suppresses color when stderr is redirected, but it has no way to learn + // about `--color`, so `init` installs a handler built from the setting. + let (_, plain) = failing_connect(&[]); + let (_, styled) = failing_connect(&["--color", "always"]); + + assert!( + styled.contains(ESC), + "expected `--color always` to style error output; got: {styled:?}" + ); + assert!( + !plain.contains(ESC), + "piped error output must not emit ANSI escapes, got: {plain:?}" + ); +} + +#[test] +fn status_column_is_matchable_by_a_whitespace_anchored_pattern() { + // The regression this whole change exists for: a supervisor deciding whether + // a forward is alive by matching the STATUS column. Colorized output put an + // escape byte immediately before the status word, so a pattern requiring + // whitespace ahead of it could never match. + let tmpdir = tempfile::tempdir().expect("create tmpdir"); + config_dir_with_forward(tmpdir.path()); + + let stdout = forward_list(tmpdir.path(), &[], None); + let row = stdout + .lines() + .find(|line| line.starts_with(SANDBOX)) + .unwrap_or_else(|| panic!("no row for {SANDBOX} in: {stdout:?}")); + + let status = row + .split_whitespace() + .next_back() + .expect("row has a status column"); + assert_eq!(status, "dead"); + + // Whitespace, not an escape byte, separates the PID from the status. + let boundary = row + .rfind(status) + .and_then(|index| row[..index].chars().next_back()) + .expect("status is preceded by the rest of the row"); + assert!( + boundary.is_whitespace(), + "expected whitespace before the status column, found {boundary:?} in {row:?}" + ); +} diff --git a/crates/openshell-cli/tests/ensure_providers_integration.rs b/crates/openshell-cli/tests/ensure_providers_integration.rs index 743cfec42c..2a4801b143 100644 --- a/crates/openshell-cli/tests/ensure_providers_integration.rs +++ b/crates/openshell-cli/tests/ensure_providers_integration.rs @@ -154,6 +154,8 @@ impl OpenShell for TestOpenShell { Ok(Response::new(ListSandboxesResponse::default())) } + unimplemented_sandbox_template_rpcs!(); + async fn list_sandbox_providers( &self, _request: tonic::Request, diff --git a/crates/openshell-cli/tests/helpers/mod.rs b/crates/openshell-cli/tests/helpers/mod.rs index a58e750b91..c4e9b4b75a 100644 --- a/crates/openshell-cli/tests/helpers/mod.rs +++ b/crates/openshell-cli/tests/helpers/mod.rs @@ -8,6 +8,95 @@ //! mod helpers; //! ``` +#[macro_export] +macro_rules! unimplemented_sandbox_template_rpcs { + () => { + fn create_sandbox_template<'life0, 'async_trait>( + &'life0 self, + _request: tonic::Request, + ) -> std::pin::Pin< + Box< + dyn std::future::Future< + Output = Result< + tonic::Response, + tonic::Status, + >, + > + Send + + 'async_trait, + >, + > + where + 'life0: 'async_trait, + Self: 'async_trait, + { + Box::pin(async { Err(tonic::Status::unimplemented("unused")) }) + } + + fn get_sandbox_template<'life0, 'async_trait>( + &'life0 self, + _request: tonic::Request, + ) -> std::pin::Pin< + Box< + dyn std::future::Future< + Output = Result< + tonic::Response, + tonic::Status, + >, + > + Send + + 'async_trait, + >, + > + where + 'life0: 'async_trait, + Self: 'async_trait, + { + Box::pin(async { Err(tonic::Status::unimplemented("unused")) }) + } + + fn list_sandbox_templates<'life0, 'async_trait>( + &'life0 self, + _request: tonic::Request, + ) -> std::pin::Pin< + Box< + dyn std::future::Future< + Output = Result< + tonic::Response, + tonic::Status, + >, + > + Send + + 'async_trait, + >, + > + where + 'life0: 'async_trait, + Self: 'async_trait, + { + Box::pin(async { Err(tonic::Status::unimplemented("unused")) }) + } + + fn delete_sandbox_template<'life0, 'async_trait>( + &'life0 self, + _request: tonic::Request, + ) -> std::pin::Pin< + Box< + dyn std::future::Future< + Output = Result< + tonic::Response, + tonic::Status, + >, + > + Send + + 'async_trait, + >, + > + where + 'life0: 'async_trait, + Self: 'async_trait, + { + Box::pin(async { Err(tonic::Status::unimplemented("unused")) }) + } + }; +} + use rcgen::{ BasicConstraints, Certificate, CertificateParams, ExtendedKeyUsagePurpose, IsCa, KeyPair, }; diff --git a/crates/openshell-cli/tests/mtls_integration.rs b/crates/openshell-cli/tests/mtls_integration.rs index e4735ac4c1..12c838baf1 100644 --- a/crates/openshell-cli/tests/mtls_integration.rs +++ b/crates/openshell-cli/tests/mtls_integration.rs @@ -113,6 +113,8 @@ impl OpenShell for TestOpenShell { )) } + unimplemented_sandbox_template_rpcs!(); + async fn list_sandbox_providers( &self, _request: tonic::Request, diff --git a/crates/openshell-cli/tests/provider_commands_integration.rs b/crates/openshell-cli/tests/provider_commands_integration.rs index d198c1e37a..39452b6de5 100644 --- a/crates/openshell-cli/tests/provider_commands_integration.rs +++ b/crates/openshell-cli/tests/provider_commands_integration.rs @@ -51,9 +51,11 @@ struct ProviderState { provider_update_requests: Arc>>, deny_provider_reads: Arc, delete_provider_requests: Arc>>, + delete_provider_profile_requests: Arc>>, fail_configure_refresh_message: Arc>>, fail_rotate_refresh_message: Arc>>, fail_delete_provider_message: Arc>>, + fail_delete_provider_profile_message: Arc>>, sandbox_providers: Arc>>>, sandbox_provider_requests: Arc>>, global_settings: Arc>>, @@ -183,6 +185,7 @@ impl OpenShell for TestOpenShell { }), spec: None, status: None, + ..Sandbox::default() }), })) } @@ -194,6 +197,8 @@ impl OpenShell for TestOpenShell { Ok(Response::new(ListSandboxesResponse::default())) } + unimplemented_sandbox_template_rpcs!(); + async fn list_sandbox_providers( &self, request: tonic::Request, @@ -888,6 +893,20 @@ impl OpenShell for TestOpenShell { request: tonic::Request, ) -> Result, Status> { let id = request.into_inner().id; + self.state + .delete_provider_profile_requests + .lock() + .await + .push(id.clone()); + let delete_failure = self + .state + .fail_delete_provider_profile_message + .lock() + .await + .take(); + if let Some(message) = delete_failure { + return Err(Status::internal(message)); + } let deleted = self.state.profiles.lock().await.remove(&id).is_some(); Ok(Response::new( openshell_core::proto::DeleteProviderProfileResponse { deleted }, @@ -1202,6 +1221,62 @@ async fn install_test_profile(ts: &TestServer, id: &str, credential_key: &str) { ); } +#[tokio::test] +async fn provider_delete_continues_after_entry_failure() { + let ts = run_server().await; + *ts.state.fail_delete_provider_message.lock().await = + Some("simulated provider delete failure".to_string()); + + let err = run::provider_delete( + &ts.endpoint, + &["failing-provider".to_string(), "later-provider".to_string()], + "default", + &ts.tls, + ) + .await + .expect_err("provider delete should report aggregate failure"); + + let msg = err.to_string(); + assert!( + msg.contains("failed to delete 1 provider: failing-provider"), + "unexpected error: {msg}" + ); + assert_eq!( + ts.state.delete_provider_requests.lock().await.clone(), + vec!["failing-provider".to_string(), "later-provider".to_string()] + ); +} + +#[tokio::test] +async fn provider_profile_delete_continues_after_entry_failure() { + let ts = run_server().await; + *ts.state.fail_delete_provider_profile_message.lock().await = + Some("simulated provider profile delete failure".to_string()); + + let err = run::provider_profile_delete( + &ts.endpoint, + &["failing-profile".to_string(), "later-profile".to_string()], + "default", + &ts.tls, + ) + .await + .expect_err("provider profile delete should report aggregate failure"); + + let msg = err.to_string(); + assert!( + msg.contains("failed to delete 1 provider profile: failing-profile"), + "unexpected error: {msg}" + ); + assert_eq!( + ts.state + .delete_provider_profile_requests + .lock() + .await + .clone(), + vec!["failing-profile".to_string(), "later-profile".to_string()] + ); +} + #[tokio::test] async fn provider_cli_run_functions_support_full_crud_flow() { let ts = run_server().await; diff --git a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs index e712e5291e..7be771c442 100644 --- a/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs +++ b/crates/openshell-cli/tests/sandbox_create_lifecycle_integration.rs @@ -14,20 +14,22 @@ use openshell_cli::tls::TlsOptions; use openshell_core::proto::open_shell_server::{OpenShell, OpenShellServer}; use openshell_core::proto::{ AttachSandboxProviderRequest, AttachSandboxProviderResponse, CreateProviderRequest, - CreateSandboxRequest, CreateSshSessionRequest, CreateSshSessionResponse, DeleteProviderRequest, - DeleteProviderResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DetachSandboxProviderRequest, DetachSandboxProviderResponse, - ExchangeProviderSubjectTokenRequest, ExchangeProviderSubjectTokenResponse, ExecSandboxEvent, - ExecSandboxInput, ExecSandboxRequest, GatewayMessage, GetGatewayConfigRequest, - GetGatewayConfigResponse, GetProviderRequest, GetSandboxConfigRequest, - GetSandboxConfigResponse, GetSandboxProviderEnvironmentRequest, - GetSandboxProviderEnvironmentResponse, GetSandboxRequest, GpuResourceRequirements, - HealthRequest, HealthResponse, ListProvidersRequest, ListProvidersResponse, - ListSandboxProvidersRequest, ListSandboxProvidersResponse, ListSandboxesRequest, - ListSandboxesResponse, PlatformEvent, ProviderResponse, RevokeSshSessionRequest, + CreateSandboxRequest, CreateSandboxTemplateRequest, CreateSshSessionRequest, + CreateSshSessionResponse, DeleteProviderRequest, DeleteProviderResponse, DeleteSandboxRequest, + DeleteSandboxResponse, DeleteSandboxTemplateRequest, DetachSandboxProviderRequest, + DetachSandboxProviderResponse, ExchangeProviderSubjectTokenRequest, + ExchangeProviderSubjectTokenResponse, ExecSandboxEvent, ExecSandboxInput, ExecSandboxRequest, + GatewayMessage, GetGatewayConfigRequest, GetGatewayConfigResponse, GetProviderRequest, + GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxProviderEnvironmentRequest, + GetSandboxProviderEnvironmentResponse, GetSandboxRequest, GetSandboxTemplateRequest, + GpuResourceRequirements, HealthRequest, HealthResponse, ListProvidersRequest, + ListProvidersResponse, ListSandboxProvidersRequest, ListSandboxProvidersResponse, + ListSandboxTemplatesRequest, ListSandboxTemplatesResponse, ListSandboxesRequest, + ListSandboxesResponse, PlatformEvent, Provider, ProviderResponse, RevokeSshSessionRequest, RevokeSshSessionResponse, Sandbox, SandboxCondition, SandboxLogLine, SandboxPhase, - SandboxResponse, SandboxStatus, SandboxStreamEvent, ServiceStatus, SettingValue, - SupervisorMessage, UpdateProviderRequest, WatchSandboxRequest, sandbox_stream_event, + SandboxResponse, SandboxStatus, SandboxStreamEvent, SandboxTemplateResponse, + SandboxWorkloadTemplate, ServiceStatus, SettingValue, SupervisorMessage, UpdateProviderRequest, + WatchSandboxRequest, sandbox_stream_event, }; use std::collections::HashMap; use std::fs; @@ -46,6 +48,7 @@ use tonic::{Response, Status}; struct SandboxState { deleted_names: Arc>>>, create_requests: Arc>>, + fail_delete_sandbox_message: Arc>>, vm_error_after_started: Arc, vm_error_with_observed_exit: Arc, vm_slow_progress_before_ready: Arc, @@ -55,6 +58,11 @@ struct SandboxState { ssh_session_requests: Arc, global_settings: Arc>>, gateway_config_requests: Arc, + providers: Arc>>, + template_create_requests: Arc>>, + template_get_requests: Arc>>, + template_list_requests: Arc>>, + template_delete_requests: Arc>>, } #[derive(Clone, Default)] @@ -179,6 +187,95 @@ impl OpenShell for TestOpenShell { Ok(Response::new(ListSandboxesResponse::default())) } + async fn create_sandbox_template( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + let mut template = request.template.clone().unwrap_or_default(); + let name = template + .metadata + .as_ref() + .map_or_else(|| "template".to_string(), |metadata| metadata.name.clone()); + template.metadata = Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: format!("template-{name}"), + name, + created_at_ms: 0, + labels: template + .metadata + .as_ref() + .map(|metadata| metadata.labels.clone()) + .unwrap_or_default(), + resource_version: 1, + annotations: HashMap::new(), + workspace: request.workspace.clone(), + deletion_timestamp_ms: 0, + }); + self.state + .template_create_requests + .lock() + .await + .push(request); + Ok(Response::new(SandboxTemplateResponse { + template: Some(template), + })) + } + + async fn get_sandbox_template( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + self.state + .template_get_requests + .lock() + .await + .push(request.clone()); + Ok(Response::new(SandboxTemplateResponse { + template: Some(SandboxWorkloadTemplate { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: format!("template-{}", request.name), + name: request.name, + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 1, + annotations: HashMap::new(), + workspace: request.workspace, + deletion_timestamp_ms: 0, + }), + spec: None, + }), + })) + } + + async fn list_sandbox_templates( + &self, + request: tonic::Request, + ) -> Result, Status> { + self.state + .template_list_requests + .lock() + .await + .push(request.into_inner()); + Ok(Response::new(ListSandboxTemplatesResponse { + templates: Vec::new(), + })) + } + + async fn delete_sandbox_template( + &self, + request: tonic::Request, + ) -> Result, Status> { + self.state + .template_delete_requests + .lock() + .await + .push(request.into_inner()); + Ok(Response::new( + openshell_core::proto::DeleteSandboxTemplateResponse { deleted: true }, + )) + } + async fn list_sandbox_providers( &self, _request: tonic::Request, @@ -209,7 +306,11 @@ impl OpenShell for TestOpenShell { .deleted_names .lock() .await - .push(vec![request.name]); + .push(vec![request.name.clone()]); + let delete_failure = self.state.fail_delete_sandbox_message.lock().await.take(); + if let Some(message) = delete_failure { + return Err(Status::internal(message)); + } Ok(Response::new(DeleteSandboxResponse { deleted: true })) } @@ -332,7 +433,9 @@ impl OpenShell for TestOpenShell { &self, _request: tonic::Request, ) -> Result, Status> { - Ok(Response::new(ListProvidersResponse::default())) + Ok(Response::new(ListProvidersResponse { + providers: self.state.providers.lock().await.clone(), + })) } async fn list_provider_profiles( @@ -1204,6 +1307,63 @@ async fn create_requests(server: &TestServer) -> Vec { server.openshell.state.create_requests.lock().await.clone() } +async fn template_create_requests(server: &TestServer) -> Vec { + server + .openshell + .state + .template_create_requests + .lock() + .await + .clone() +} + +async fn template_list_requests(server: &TestServer) -> Vec { + server + .openshell + .state + .template_list_requests + .lock() + .await + .clone() +} + +async fn template_delete_requests(server: &TestServer) -> Vec { + server + .openshell + .state + .template_delete_requests + .lock() + .await + .clone() +} + +async fn add_provider(server: &TestServer, name: &str, provider_type: &str) { + server + .openshell + .state + .providers + .lock() + .await + .push(Provider { + metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + id: format!("provider-{name}"), + name: name.to_string(), + created_at_ms: 0, + labels: HashMap::new(), + resource_version: 0, + annotations: HashMap::new(), + workspace: "default".to_string(), + deletion_timestamp_ms: 0, + }), + r#type: provider_type.to_string(), + credentials: HashMap::new(), + config: HashMap::new(), + credential_expires_at_ms: HashMap::new(), + profile_workspace: "default".to_string(), + credential_handles: HashMap::new(), + }); +} + fn test_tls(server: &TestServer) -> TlsOptions { server.tls.with_gateway_name("openshell") } @@ -1225,6 +1385,42 @@ fn test_config() -> run::SandboxCreateConfig<'static> { } } +#[tokio::test] +async fn sandbox_delete_continues_after_entry_failure() { + let server = run_server().await; + let tls = test_tls(&server); + *server + .openshell + .state + .fail_delete_sandbox_message + .lock() + .await = Some("simulated sandbox delete failure".to_string()); + + let err = run::sandbox_delete( + &server.endpoint, + &["failing-sandbox".to_string(), "later-sandbox".to_string()], + false, + "default", + &tls, + "openshell", + ) + .await + .expect_err("sandbox delete should report aggregate failure"); + + let msg = err.to_string(); + assert!( + msg.contains("failed to delete 1 sandbox: failing-sandbox"), + "unexpected error: {msg}" + ); + assert_eq!( + deleted_names(&server).await, + vec![ + vec!["failing-sandbox".to_string()], + vec!["later-sandbox".to_string()] + ] + ); +} + #[tokio::test] async fn sandbox_create_keeps_command_sessions_by_default() { let server = run_server().await; @@ -1488,6 +1684,201 @@ async fn sandbox_create_sends_driver_config_json() { ); } +#[tokio::test] +async fn sandbox_create_with_template_sends_workload_template_name() { + let server = run_server().await; + add_provider(&server, "github", "github").await; + let fake_ssh_dir = tempfile::tempdir().unwrap(); + let xdg_dir = tempfile::tempdir().unwrap(); + let _env = test_env(&fake_ssh_dir, &xdg_dir); + let tls = test_tls(&server); + install_fake_ssh(&fake_ssh_dir); + + run::sandbox_create( + &server.endpoint, + "openshell", + run::SandboxCreateConfig { + name: Some("from-template"), + template: Some("gpu-kata"), + providers: &["github".to_string()], + command: &["echo".into(), "OK".into()], + ..test_config() + }, + "default", + &tls, + ) + .await + .expect("sandbox create should succeed"); + + let requests = create_requests(&server).await; + let request = requests.first().expect("create request should be recorded"); + assert_eq!(request.workload_template_name, "gpu-kata"); + let spec = request + .spec + .as_ref() + .expect("governance spec should be sent"); + assert_eq!(spec.providers, vec!["github".to_string()]); + assert!(spec.template.is_none()); + assert!(spec.environment.is_empty()); + assert!(spec.resource_requirements.is_none()); +} + +#[tokio::test] +async fn sandbox_template_create_sends_workload_template_resource() { + let server = run_server().await; + let fake_ssh_dir = tempfile::tempdir().unwrap(); + let xdg_dir = tempfile::tempdir().unwrap(); + let _env = test_env(&fake_ssh_dir, &xdg_dir); + let tls = test_tls(&server); + + run::sandbox_template_create( + &server.endpoint, + "gpu-kata", + Some("registry.example.com/agent:latest"), + Some("2"), + Some("4Gi"), + Some(GpuResourceRequirements { count: Some(1) }), + Some(r#"{"kubernetes":{"pod":{"node_selector":{"pool":"gpu"}}}}"#), + Some("5m"), + Some(3), + HashMap::from([("team".to_string(), "runtime".to_string())]), + HashMap::from([("owner".to_string(), "platform".to_string())]), + HashMap::from([("FEATURE_FLAG".to_string(), "on".to_string())]), + "table", + "default", + &tls, + ) + .await + .expect("template create should succeed"); + + let requests = template_create_requests(&server).await; + let request = requests + .first() + .expect("template create request should be recorded"); + assert_eq!(request.workspace, "default"); + let template = request.template.as_ref().expect("template should be sent"); + let metadata = template.metadata.as_ref().expect("metadata should be sent"); + assert_eq!(metadata.name, "gpu-kata"); + assert_eq!(metadata.labels.get("team"), Some(&"runtime".to_string())); + assert_eq!( + metadata.annotations.get("owner"), + Some(&"platform".to_string()) + ); + + let spec = template.spec.as_ref().expect("spec should be sent"); + let workload = spec.workload.as_ref().expect("workload should be sent"); + assert_eq!(workload.image, "registry.example.com/agent:latest"); + assert_eq!( + workload.environment.get("FEATURE_FLAG"), + Some(&"on".to_string()) + ); + let resources = workload + .resources + .as_ref() + .expect("resources should be sent"); + assert_eq!(resources.cpu, "2"); + assert_eq!(resources.memory, "4Gi"); + assert_eq!(resources.gpu.as_ref().and_then(|gpu| gpu.count), Some(1)); + assert!(spec.driver_config.is_some()); + let startup = spec + .desired_service_level + .as_ref() + .and_then(|service_level| service_level.startup.as_ref()) + .expect("startup service level should be sent"); + assert_eq!(startup.max_burst, 3); + assert_eq!( + startup + .ready_within + .as_ref() + .map(|duration| duration.seconds), + Some(300) + ); +} + +#[tokio::test] +async fn sandbox_template_list_and_delete_send_workspace_requests() { + let server = run_server().await; + let fake_ssh_dir = tempfile::tempdir().unwrap(); + let xdg_dir = tempfile::tempdir().unwrap(); + let _env = test_env(&fake_ssh_dir, &xdg_dir); + let tls = test_tls(&server); + + run::sandbox_template_list( + &server.endpoint, + 25, + 5, + Some("team=runtime"), + false, + "table", + "default", + false, + &tls, + ) + .await + .expect("template list should succeed"); + run::sandbox_template_delete(&server.endpoint, &["gpu-kata".to_string()], "default", &tls) + .await + .expect("template delete should succeed"); + + let list_requests = template_list_requests(&server).await; + let list_request = list_requests + .first() + .expect("template list request should be recorded"); + assert_eq!(list_request.limit, 25); + assert_eq!(list_request.offset, 5); + assert_eq!(list_request.label_selector, "team=runtime"); + assert_eq!(list_request.workspace, "default"); + assert!(!list_request.all_workspaces); + + let delete_requests = template_delete_requests(&server).await; + let delete_request = delete_requests + .first() + .expect("template delete request should be recorded"); + assert_eq!(delete_request.name, "gpu-kata"); + assert_eq!(delete_request.workspace, "default"); +} + +#[tokio::test] +async fn sandbox_template_create_allows_omitted_image() { + let server = run_server().await; + let fake_ssh_dir = tempfile::tempdir().unwrap(); + let xdg_dir = tempfile::tempdir().unwrap(); + let _env = test_env(&fake_ssh_dir, &xdg_dir); + let tls = test_tls(&server); + + run::sandbox_template_create( + &server.endpoint, + "base", + None, + None, + None, + None, + None, + None, + None, + HashMap::new(), + HashMap::new(), + HashMap::new(), + "table", + "default", + &tls, + ) + .await + .expect("template create without image should succeed"); + + let requests = template_create_requests(&server).await; + let request = requests + .first() + .expect("template create request should be recorded"); + let workload = request + .template + .as_ref() + .and_then(|template| template.spec.as_ref()) + .and_then(|spec| spec.workload.as_ref()) + .expect("workload should be sent"); + assert_eq!(workload.image, ""); +} + #[tokio::test] async fn sandbox_create_sends_gpu_default_request() { let server = run_server().await; @@ -2217,6 +2608,44 @@ async fn run_cli_sandbox_create( .unwrap() } +async fn run_cli_sandbox_template_create( + server: &TestServer, + name: &str, + extra_args: &[&str], +) -> std::process::Output { + let xdg_dir = tempfile::tempdir().unwrap(); + let tls_dir = xdg_dir.path().join("openshell/gateways/openshell/mtls"); + fs::create_dir_all(&tls_dir).unwrap(); + for filename in ["ca.crt", "tls.crt", "tls.key"] { + fs::copy(server.dir.path().join(filename), tls_dir.join(filename)).unwrap(); + } + + let mut cmd = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell")); + for (key, _) in std::env::vars().filter(|(k, _)| k.starts_with("OPENSHELL_")) { + cmd.env_remove(&key); + } + cmd.args([ + "--gateway", + "openshell", + "--gateway-endpoint", + &server.endpoint, + "sandbox", + "template", + "create", + name, + "--image", + "registry.example.com/agent:latest", + "--output=json", + ]) + .args(extra_args) + .env("XDG_CONFIG_HOME", xdg_dir.path()) + .env("HOME", xdg_dir.path()) + .env("OPENSHELL_PROVISION_TIMEOUT", "5") + .output() + .await + .unwrap() +} + #[tokio::test] async fn sandbox_create_json_stdout_is_parseable() { let server = run_server().await; @@ -2246,3 +2675,63 @@ async fn sandbox_create_yaml_stdout_is_parseable() { serde_yml::from_str::(&stdout) .unwrap_or_else(|err| panic!("stdout should contain only YAML: {err}\n{stdout}")); } + +#[tokio::test] +async fn sandbox_template_create_warns_for_credential_env_vars() { + let server = run_server().await; + + let result = run_cli_sandbox_template_create( + &server, + "credential-env", + &["--env", "OPENAI_API_KEY=plain-secret"], + ) + .await; + + assert!( + result.status.success(), + "sandbox template create failed:\n{}", + String::from_utf8_lossy(&result.stderr) + ); + let stderr = String::from_utf8_lossy(&result.stderr); + assert!( + stderr.contains("OPENAI_API_KEY looks like a credential"), + "template create should warn for credential-looking --env values: {stderr}" + ); + assert!( + stderr.contains("To hide it from the agent, use a provider instead"), + "warning should point users toward providers: {stderr}" + ); + + let requests = template_create_requests(&server).await; + assert_eq!(requests.len(), 1); +} + +#[tokio::test] +async fn sandbox_template_create_suppresses_credential_env_warnings() { + let server = run_server().await; + + let result = run_cli_sandbox_template_create( + &server, + "credential-env-suppressed", + &[ + "--env", + "OPENAI_API_KEY=plain-secret", + "--no-credential-warnings", + ], + ) + .await; + + assert!( + result.status.success(), + "sandbox template create failed:\n{}", + String::from_utf8_lossy(&result.stderr) + ); + let stderr = String::from_utf8_lossy(&result.stderr); + assert!( + !stderr.contains("OPENAI_API_KEY looks like a credential"), + "template create should suppress credential-looking --env warnings: {stderr}" + ); + + let requests = template_create_requests(&server).await; + assert_eq!(requests.len(), 1); +} diff --git a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs index ee72728aa9..5b62c7c15c 100644 --- a/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs +++ b/crates/openshell-cli/tests/sandbox_name_fallback_integration.rs @@ -138,6 +138,8 @@ impl OpenShell for TestOpenShell { Ok(Response::new(ListSandboxesResponse::default())) } + unimplemented_sandbox_template_rpcs!(); + async fn list_sandbox_providers( &self, _request: tonic::Request, diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index a1f1a6c84f..3507011120 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -6,16 +6,10 @@ use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::collections::BTreeMap; -use std::fmt; -#[cfg(unix)] -use std::io::{Read, Write}; use std::net::SocketAddr; -#[cfg(unix)] -use std::os::unix::fs::FileTypeExt; -use std::path::{Path, PathBuf}; -use std::process::{Command, Stdio}; +use std::path::PathBuf; use std::str::FromStr; -use std::time::{Duration, Instant}; +use std::time::Duration; // ── Public default constants ──────────────────────────────────────────── // @@ -35,9 +29,6 @@ pub const DEFAULT_GATEWAY_NAME: &str = "openshell"; /// Default container stop timeout in seconds (SIGTERM → SIGKILL). pub const DEFAULT_STOP_TIMEOUT_SECS: u32 = 10; -/// Default Docker bridge network name for local sandboxes. -pub const DEFAULT_DOCKER_NETWORK_NAME: &str = "openshell-docker"; - /// Default domain used for browser-facing sandbox service URLs. pub const DEFAULT_SERVICE_ROUTING_DOMAIN: &str = "openshell.localhost"; @@ -118,34 +109,9 @@ pub const CDI_GPU_DEVICE_ALL: &str = "nvidia.com/gpu=all"; /// Default maximum number of processes (PIDs) allowed inside a sandbox container. /// -/// Shared by the Docker and Podman drivers; override via driver config. +/// Compute drivers may override this through backend configuration. pub const DEFAULT_SANDBOX_PIDS_LIMIT: i64 = 2048; -/// Compute backends the gateway can orchestrate sandboxes through. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub enum ComputeDriverKind { - Kubernetes, - Vm, - Docker, - Podman, - /// Microsoft MXC isolation session (Windows only). - Mxc, -} - -impl ComputeDriverKind { - #[must_use] - pub const fn as_str(self) -> &'static str { - match self { - Self::Kubernetes => "kubernetes", - Self::Vm => "vm", - Self::Docker => "docker", - Self::Podman => "podman", - Self::Mxc => "mxc", - } - } -} - /// Normalize a configured compute driver name. /// /// Built-in driver names and custom remote driver names share the same @@ -167,594 +133,6 @@ pub fn normalize_compute_driver_name(value: &str) -> Result { Ok(value.to_ascii_lowercase()) } -impl fmt::Display for ComputeDriverKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_str(self.as_str()) - } -} - -impl FromStr for ComputeDriverKind { - type Err = String; - - fn from_str(value: &str) -> Result { - match value.trim().to_ascii_lowercase().as_str() { - "kubernetes" => Ok(Self::Kubernetes), - "vm" => Ok(Self::Vm), - "docker" => Ok(Self::Docker), - "podman" => Ok(Self::Podman), - "mxc" => Ok(Self::Mxc), - other => Err(format!( - "unsupported compute driver '{other}'. expected one of: kubernetes, vm, docker, podman, mxc" - )), - } - } -} - -/// Auto-detect the appropriate compute driver based on the runtime environment. -/// -/// Priority order: Kubernetes → Podman → Docker. -/// VM is never auto-detected (requires explicit `--drivers vm`). -/// -/// Returns the first driver where the environment check passes. -/// Returns `None` if no compatible driver is found. -pub fn detect_driver() -> Option { - // Kubernetes: check for KUBERNETES_SERVICE_HOST env var (set inside pods) - if std::env::var_os("KUBERNETES_SERVICE_HOST").is_some() { - return Some(ComputeDriverKind::Kubernetes); - } - - // Podman: check for a reachable local API socket. - if is_podman_available() { - return Some(ComputeDriverKind::Podman); - } - - // Docker: check for a reachable local API socket. - if is_docker_available() { - return Some(ComputeDriverKind::Docker); - } - - None -} - -/// Return whether a responsive local Podman API socket is available. -#[must_use] -pub fn is_podman_available() -> bool { - detect_podman_socket().is_some() -} - -/// Return the Podman API socket, or `None` if Podman is not available. -/// -/// Probes the well-known socket candidates first, then falls back to asking -/// the Podman CLI where its socket lives. The symlink at a well-known path is -/// not always present — it varies by Podman version, machine provider, and -/// platform — so the CLI fallback is what makes detection work on hosts where -/// Podman is functional but the socket is somewhere else. -pub fn detect_podman_socket() -> Option { - detect_podman_socket_from_candidates(&podman_socket_candidates()) - .or_else(discover_podman_socket) -} - -fn detect_podman_socket_from_candidates(candidates: &[PathBuf]) -> Option { - candidates - .iter() - .find(|path| podman_socket_responds(path)) - .cloned() -} - -/// Maximum time to wait for a Podman discovery subprocess. -/// -/// Driver auto-detection runs `podman info`, `podman machine inspect`, and -/// `podman system connection list` during gateway startup. A stalled Podman -/// machine, SSH connection, provider, or helper must not block startup forever, -/// so each probe is bounded and treated as "not found" on expiry — detection -/// then continues to the next candidate driver or fails with an actionable -/// error. -const PODMAN_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5); - -/// How often the bounded runner polls the child for completion. -const PODMAN_DISCOVERY_POLL_INTERVAL: Duration = Duration::from_millis(25); - -/// Run `podman ` with a bounded deadline, returning captured stdout on a -/// successful exit. Returns `None` on spawn failure, non-zero exit, or timeout. -fn run_podman_capture(args: &[&str]) -> Option> { - run_bounded_command("podman", args, PODMAN_DISCOVERY_TIMEOUT) -} - -/// Run `program ` with a deadline, capturing stdout. -/// -/// Unlike `Command::output()`, which blocks until the child exits, the deadline -/// is absolute: the call returns within `timeout` no matter what the probe or -/// its descendants do. A Podman probe can leave a daemonized descendant (an SSH -/// multiplexer, `gvproxy`, etc.) that inherited the stdout pipe, so -/// `read_to_end` would otherwise wait for EOF forever even after the direct -/// child exits — and such a descendant may even have escaped the probe's -/// process group. To stay bounded, the deadline covers both waiting for the -/// child and draining its stdout; on expiry the call best-effort kills the -/// process group (cleaning up in-group descendants) and gives up immediately, -/// abandoning the reader thread rather than waiting on it again. The abandoned -/// reader exits on its own once the pipe finally closes. Returns the captured -/// stdout only on a successful exit whose output was fully drained within the -/// deadline; otherwise `None`. -fn run_bounded_command(program: &str, args: &[&str], timeout: Duration) -> Option> { - use std::io::Read as _; - use std::sync::mpsc; - - let mut command = Command::new(program); - command - .args(args) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()); - // Run the probe as its own process-group leader so in-group descendants that - // inherited the stdout pipe can be terminated as a group on timeout. - set_new_process_group(&mut command); - let mut child = command.spawn().ok()?; - - // Drain stdout on a separate thread so a child that fills the pipe buffer - // cannot deadlock against the polling loop below. The reader reports through - // a channel so the drain can be bounded by the deadline and abandoned if it - // outlives it. - let mut stdout = child.stdout.take()?; - let (tx, rx) = mpsc::channel(); - std::thread::spawn(move || { - let mut buf = Vec::new(); - let _ = stdout.read_to_end(&mut buf); - let _ = tx.send(buf); - }); - - let deadline = Instant::now() + timeout; - - // Wait for the direct child to exit, bounded by the deadline. - let status = loop { - match child.try_wait() { - Ok(Some(status)) => break Some(status), - Ok(None) => { - if Instant::now() >= deadline { - break None; - } - std::thread::sleep(PODMAN_DISCOVERY_POLL_INTERVAL); - } - Err(_) => break None, - } - }; - - // The child never exited within the deadline: kill the group, reap the - // (now-killed) direct child, and give up. `wait()` is bounded because the - // direct child is dead. - let Some(status) = status else { - terminate_process_group(&mut child); - let _ = child.wait(); - return None; - }; - - // The direct child exited (already reaped by `try_wait`). Collect its stdout - // without ever blocking past the deadline. A surviving descendant — possibly - // one that escaped the process group — can hold the pipe open indefinitely, - // so on expiry best-effort kill the group for cleanup and return None rather - // than waiting on the reader again. - let remaining = deadline.saturating_duration_since(Instant::now()); - match rx.recv_timeout(remaining) { - Ok(stdout) if status.success() => Some(stdout), - Ok(_) => None, - Err(_) => { - terminate_process_group(&mut child); - None - } - } -} - -/// Configure `command` to start its child as a new process-group leader so the -/// group can be signaled as a unit. No-op on non-Unix platforms. -#[cfg(unix)] -fn set_new_process_group(command: &mut Command) { - use std::os::unix::process::CommandExt as _; - command.process_group(0); -} - -#[cfg(not(unix))] -fn set_new_process_group(_command: &mut Command) {} - -/// Kill the child's whole process group so daemonized descendants that inherited -/// the stdout pipe are terminated too. Falls back to killing just the child. -#[cfg(unix)] -fn terminate_process_group(child: &mut std::process::Child) { - // `set_new_process_group` made the child a group leader, so its PID doubles - // as the group ID; signaling the negated PID targets the entire group. The - // group stays valid while a descendant is alive, so this reaches survivors - // even after the leader has been reaped. - let raw_pid = i32::try_from(child.id()).unwrap_or(i32::MAX); - let pgid = nix::unistd::Pid::from_raw(-raw_pid); - let _ = nix::sys::signal::kill(pgid, nix::sys::signal::Signal::SIGKILL); - let _ = child.kill(); -} - -#[cfg(not(unix))] -fn terminate_process_group(child: &mut std::process::Child) { - let _ = child.kill(); -} - -/// Query the Podman CLI to discover the host-side API socket path. -/// -/// Strategy: -/// 1. Run `podman info --format json` to check connectivity and whether -/// the service is remote (macOS/Windows VM) or local (native Linux). -/// 2. If `CONTAINER_HOST` explicitly points at a Unix socket, `podman info` -/// just connected through it — use that path directly (a raw unix:// URL -/// has no machine to inspect and reports the VM-internal socket). -/// 3. If `serviceIsRemote` is true, run `podman machine inspect` to get -/// the host-side forwarded socket (the `remoteSocket` from `podman info` -/// is the VM-internal path, which is not reachable from the host). -/// 4. If `serviceIsRemote` is false, use `remoteSocket.path` directly -/// (on native Linux this IS the real local socket). -fn discover_podman_socket() -> Option { - let stdout = run_podman_capture(&["info", "--format", "json"])?; - - // podman info succeeded, so an explicit unix:// CONTAINER_HOST is the exact - // working host-side socket. This must be checked before the machine path, - // which cannot map a raw unix:// endpoint to a machine. - if let Some(path) = explicit_unix_container_host() { - return Some(path); - } - - let info: serde_json::Value = serde_json::from_slice(&stdout).ok()?; - let is_remote = info["host"]["serviceIsRemote"].as_bool().unwrap_or(false); - - if is_remote { - discover_podman_machine_socket() - } else { - parse_podman_info_socket(&info) - } -} - -/// Return the socket path when `CONTAINER_HOST` is an explicit `unix://` URL. -/// -/// Honors Podman's precedence: `CONTAINER_CONNECTION` outranks `CONTAINER_HOST`, -/// so a set `CONTAINER_CONNECTION` means `podman info` did not use -/// `CONTAINER_HOST` and this returns `None`. -fn explicit_unix_container_host() -> Option { - if env_var_nonempty("CONTAINER_CONNECTION").is_some() { - return None; - } - let host = env_var_nonempty("CONTAINER_HOST")?; - unix_url_socket_path(&host) -} - -/// Parse the socket path from a `unix://` URL, or `None` for other schemes. -fn unix_url_socket_path(url: &str) -> Option { - let path = url.trim().strip_prefix("unix://")?; - (!path.is_empty()).then(|| PathBuf::from(path)) -} - -/// Extract the socket path from `podman info` JSON output. -/// Used on native Linux where `remoteSocket.path` is the real local socket. -fn parse_podman_info_socket(info: &serde_json::Value) -> Option { - let path_str = info["host"]["remoteSocket"]["path"].as_str()?; - let path = path_str.strip_prefix("unix://").unwrap_or(path_str); - if path.is_empty() { - return None; - } - Some(PathBuf::from(path)) -} - -/// Which Podman machine `podman info` connected through. -/// -/// Podman resolves its endpoint (highest precedence first) from -/// `CONTAINER_CONNECTION` (a named connection), then `CONTAINER_HOST` (a URL), -/// then the default connection in `containers.conf`. -#[derive(Debug, PartialEq, Eq)] -enum ActiveMachine { - /// An explicit selector (`CONTAINER_CONNECTION`, or `CONTAINER_HOST` mapped - /// to a connection by URL) named this connection. It must match a machine - /// exactly; guessing another machine would connect to the wrong socket. - Explicit(String), - /// An explicit `CONTAINER_HOST` is set but maps to no known connection - /// (e.g. a plain remote server, not a local machine). The active machine - /// cannot be determined and must not be guessed. - UnresolvedExplicit, - /// No explicit selector; the `containers.conf` default connection name, if - /// any. When absent, Podman's built-in default machine is inspected by name. - Default(Option), -} - -/// Run `podman machine inspect ` to discover the host-side forwarded -/// socket. Used on macOS/Windows where the Podman service runs inside a VM. -/// -/// The active machine is resolved first and inspected *by name*: a no-argument -/// `podman machine inspect` inspects only `podman-machine-default`, so a host -/// whose default connection is a different machine would otherwise be pointed -/// at the wrong machine's socket. When the active machine cannot be mapped to a -/// name, this returns `None` rather than substituting an unrelated machine. -fn discover_podman_machine_socket() -> Option { - let targets = podman_machine_inspect_targets(&active_podman_machine())?; - targets.iter().find_map(|name| { - let stdout = run_podman_capture(&["machine", "inspect", name])?; - let machines: serde_json::Value = serde_json::from_slice(&stdout).ok()?; - parse_podman_machine_inspect_socket(&machines) - }) -} - -/// Machine names to try with `podman machine inspect`, most specific first. -/// -/// `None` means the active machine cannot be determined; inspection must not -/// guess, since picking an unrelated machine would return the wrong socket. A -/// rootful connection is named `-root` while the machine itself is -/// ``, so the `-root`-stripped name is offered as a fallback. -fn podman_machine_inspect_targets(active: &ActiveMachine) -> Option> { - fn names_for(connection: &str) -> Vec { - let mut names = vec![connection.to_string()]; - if let Some(stripped) = connection.strip_suffix("-root") - && !stripped.is_empty() - { - names.push(stripped.to_string()); - } - names - } - - match active { - ActiveMachine::Explicit(name) | ActiveMachine::Default(Some(name)) => Some(names_for(name)), - ActiveMachine::UnresolvedExplicit => None, - // No explicit selector and no default connection: `podman info` used - // Podman's built-in default machine, so inspect it by name rather than - // guessing an arbitrary entry. - ActiveMachine::Default(None) => Some(vec!["podman-machine-default".to_string()]), - } -} - -/// Determine which machine `podman info` connected through. -fn active_podman_machine() -> ActiveMachine { - if let Some(name) = env_var_nonempty("CONTAINER_CONNECTION") { - return ActiveMachine::Explicit(name); - } - let container_host = env_var_nonempty("CONTAINER_HOST"); - resolve_active_podman_machine(container_host.as_deref(), podman_connection_list().as_ref()) -} - -/// Resolve the active machine from `CONTAINER_HOST` and the connection list. -/// -/// `CONTAINER_CONNECTION` is handled by the caller (it needs no connection -/// list). This is split out as a pure function for testing. -fn resolve_active_podman_machine( - container_host: Option<&str>, - connections: Option<&serde_json::Value>, -) -> ActiveMachine { - if let Some(host) = container_host { - return connections - .and_then(|c| podman_connection_name_for_uri(c, host)) - .map_or(ActiveMachine::UnresolvedExplicit, ActiveMachine::Explicit); - } - ActiveMachine::Default(connections.and_then(parse_default_podman_connection)) -} - -fn env_var_nonempty(key: &str) -> Option { - std::env::var(key) - .ok() - .filter(|value| !value.trim().is_empty()) -} - -/// Run `podman system connection list --format json`. -fn podman_connection_list() -> Option { - let stdout = run_podman_capture(&["system", "connection", "list", "--format", "json"])?; - serde_json::from_slice(&stdout).ok() -} - -/// Extract the default machine connection name from -/// `podman system connection list --format json`. -fn parse_default_podman_connection(connections: &serde_json::Value) -> Option { - connections - .as_array()? - .iter() - .find(|c| { - c["Default"].as_bool().unwrap_or(false) && c["IsMachine"].as_bool().unwrap_or(false) - }) - .and_then(|c| c["Name"].as_str()) - .map(str::to_string) -} - -/// Find the machine connection whose URI matches `CONTAINER_HOST`. -/// -/// Only machine connections (`IsMachine: true`) map to a local socket, so a -/// `CONTAINER_HOST` pointing at a plain remote server yields `None`. -fn podman_connection_name_for_uri(connections: &serde_json::Value, uri: &str) -> Option { - connections - .as_array()? - .iter() - .find(|c| c["IsMachine"].as_bool().unwrap_or(false) && c["URI"].as_str() == Some(uri)) - .and_then(|c| c["Name"].as_str()) - .map(str::to_string) -} - -/// Extract the host-side socket path from a `podman machine inspect ` -/// JSON array (which contains only the inspected machine). -fn parse_podman_machine_inspect_socket(machines: &serde_json::Value) -> Option { - let machine = machines.as_array()?.first()?; - let path_str = machine["ConnectionInfo"]["PodmanSocket"]["Path"].as_str()?; - if path_str.is_empty() { - return None; - } - Some(PathBuf::from(path_str)) -} - -fn podman_socket_candidates() -> Vec { - let socket = std::env::var("OPENSHELL_PODMAN_SOCKET") - .ok() - .filter(|path| !path.trim().is_empty()) - .map(PathBuf::from); - podman_socket_candidates_from_env( - socket, - std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from), - std::env::var_os("HOME").map(PathBuf::from), - ) -} - -fn podman_socket_candidates_from_env( - socket: Option, - runtime_dir: Option, - home: Option, -) -> Vec { - let mut candidates = Vec::new(); - - if let Some(path) = socket { - candidates.push(path); - } - - if let Some(runtime_dir) = runtime_dir { - candidates.push(runtime_dir.join("podman/podman.sock")); - } - - #[cfg(target_os = "linux")] - { - candidates.push(PathBuf::from(format!( - "/run/user/{}/podman/podman.sock", - current_uid() - ))); - } - - if let Some(home) = home { - candidates.push(home.join(".local/share/containers/podman/machine/podman.sock")); - } - - candidates -} - -/// Return whether a responsive local Docker API socket is available. -#[must_use] -pub fn is_docker_available() -> bool { - detect_docker_socket().is_some() -} - -pub fn detect_docker_socket() -> Option { - detect_docker_socket_from_candidates(&docker_socket_candidates()) -} - -fn detect_docker_socket_from_candidates(candidates: &[PathBuf]) -> Option { - candidates - .iter() - .find(|path| docker_socket_responds(path)) - .cloned() -} - -fn docker_socket_candidates() -> Vec { - let mut candidates = Vec::new(); - - if let Ok(host) = std::env::var("DOCKER_HOST") - && let Some(path) = docker_host_unix_socket_path(&host) - { - candidates.push(path); - } - - candidates.push(PathBuf::from("/var/run/docker.sock")); - - if let Some(home) = std::env::var_os("HOME") { - candidates.push(PathBuf::from(home).join(".docker/run/docker.sock")); - } - - if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") { - candidates.push(PathBuf::from(runtime_dir).join("docker.sock")); - } - - candidates -} - -fn docker_host_unix_socket_path(host: &str) -> Option { - let path = host.trim().strip_prefix("unix://")?; - (!path.is_empty()).then(|| PathBuf::from(path)) -} - -#[cfg(unix)] -fn is_unix_socket(path: &Path) -> bool { - path.metadata() - .is_ok_and(|metadata| metadata.file_type().is_socket()) -} - -#[cfg(unix)] -fn podman_socket_responds(path: &Path) -> bool { - unix_socket_http_ping(path, |response| { - http_response_is_success(response) && contains_ascii(response, b"Libpod-Api-Version:") - }) -} - -#[cfg(unix)] -fn docker_socket_responds(path: &Path) -> bool { - unix_socket_http_ping(path, |response| { - http_response_is_success(response) - && contains_ascii(response, b"Api-Version:") - && !contains_ascii(response, b"Libpod-Api-Version:") - }) -} - -#[cfg(unix)] -fn unix_socket_http_ping(path: &Path, accepts_response: impl FnOnce(&[u8]) -> bool) -> bool { - const PROBE_TIMEOUT: Duration = Duration::from_secs(1); - const PING_REQUEST: &[u8] = - b"GET /_ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; - - if !is_unix_socket(path) { - return false; - } - - let Ok(mut stream) = std::os::unix::net::UnixStream::connect(path) else { - return false; - }; - if stream.set_read_timeout(Some(PROBE_TIMEOUT)).is_err() - || stream.set_write_timeout(Some(PROBE_TIMEOUT)).is_err() - || stream.write_all(PING_REQUEST).is_err() - { - return false; - } - - let mut response = [0_u8; 512]; - let mut total = 0; - while total < response.len() { - let Ok(n) = stream.read(&mut response[total..]) else { - return false; - }; - if n == 0 { - break; - } - total += n; - if contains_ascii(&response[..total], b"\r\n\r\n") { - break; - } - } - total > 0 && accepts_response(&response[..total]) -} - -#[cfg(unix)] -fn http_response_is_success(response: &[u8]) -> bool { - response.starts_with(b"HTTP/1.1 200") || response.starts_with(b"HTTP/1.0 200") -} - -#[cfg(unix)] -fn contains_ascii(haystack: &[u8], needle: &[u8]) -> bool { - haystack - .windows(needle.len()) - .any(|window| window.eq_ignore_ascii_case(needle)) -} - -#[cfg(all(unix, test))] -fn is_reachable_unix_socket(path: &Path) -> bool { - is_unix_socket(path) && std::os::unix::net::UnixStream::connect(path).is_ok() -} - -#[cfg(all(unix, target_os = "linux"))] -fn current_uid() -> u32 { - use std::os::unix::fs::MetadataExt; - - std::fs::metadata("/proc/self").map_or(0, |metadata| metadata.uid()) -} - -#[cfg(not(unix))] -fn podman_socket_responds(path: &Path) -> bool { - let _ = path; - false -} - -#[cfg(not(unix))] -fn docker_socket_responds(path: &Path) -> bool { - let _ = path; - false -} - /// Server configuration. /// /// Built programmatically in [`crate::Config::new`] and the gateway CLI from @@ -1447,53 +825,13 @@ const fn default_ssh_session_ttl_secs() -> u64 { #[cfg(test)] mod tests { use super::{ - ActiveMachine, ComputeDriverKind, Config, DEFAULT_SERVICE_ROUTING_DOMAIN, - GatewayInterceptorBindingPolicy, GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, - GatewayJwtConfig, GatewayProviderProfileSourceConfig, PolicyValidationFailureMode, - detect_docker_socket_from_candidates, detect_driver, detect_podman_socket_from_candidates, - docker_host_unix_socket_path, docker_socket_responds, explicit_unix_container_host, - normalize_compute_driver_name, parse_default_podman_connection, parse_podman_info_socket, - parse_podman_machine_inspect_socket, podman_connection_name_for_uri, - podman_machine_inspect_targets, podman_socket_candidates_from_env, podman_socket_responds, - resolve_active_podman_machine, run_bounded_command, unix_url_socket_path, + Config, DEFAULT_SERVICE_ROUTING_DOMAIN, GatewayInterceptorBindingPolicy, + GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, GatewayJwtConfig, + GatewayProviderProfileSourceConfig, PolicyValidationFailureMode, + normalize_compute_driver_name, }; - #[cfg(unix)] - use super::{is_reachable_unix_socket, is_unix_socket}; - #[cfg(unix)] - use std::io::{Read as _, Write as _}; use std::net::SocketAddr; - #[cfg(unix)] - use std::os::unix::net::UnixListener; - use std::path::PathBuf; use std::time::Duration; - #[cfg(unix)] - use std::time::Instant; - - #[test] - fn compute_driver_kind_parses_supported_values() { - assert_eq!( - "kubernetes".parse::().unwrap(), - ComputeDriverKind::Kubernetes - ); - assert_eq!( - "vm".parse::().unwrap(), - ComputeDriverKind::Vm - ); - assert_eq!( - "podman".parse::().unwrap(), - ComputeDriverKind::Podman - ); - assert_eq!( - "docker".parse::().unwrap(), - ComputeDriverKind::Docker - ); - } - - #[test] - fn compute_driver_kind_rejects_unknown_values() { - let err = "firecracker".parse::().unwrap_err(); - assert!(err.contains("unsupported compute driver 'firecracker'")); - } #[test] fn policy_validation_failure_mode_is_secure_by_default() { @@ -1714,244 +1052,6 @@ mod tests { assert_eq!(cfg.health_bind_address, Some(addr)); } - #[test] - fn detect_driver_returns_none_without_k8s_env_or_local_runtime() { - // When KUBERNETES_SERVICE_HOST is not set, no Docker binary/socket is - // available, and no Podman API socket is available, detect_driver - // should return None. - // This test may pass or fail depending on the test environment, - // but it documents the expected behavior. - let _ = detect_driver(); // Returns Some or None based on environment - } - - #[test] - fn docker_host_unix_socket_path_parses_unix_hosts() { - assert_eq!( - docker_host_unix_socket_path("unix:///var/run/docker.sock"), - Some(PathBuf::from("/var/run/docker.sock")) - ); - assert_eq!(docker_host_unix_socket_path("tcp://127.0.0.1:2375"), None); - assert_eq!(docker_host_unix_socket_path("unix://"), None); - } - - #[cfg(unix)] - #[test] - fn is_unix_socket_detects_socket_files() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let socket_path = temp_dir.path().join("docker.sock"); - let _listener = UnixListener::bind(&socket_path).expect("bind unix socket"); - - assert!(is_unix_socket(&socket_path)); - assert!(is_reachable_unix_socket(&socket_path)); - - let regular_file = temp_dir.path().join("not-a-socket"); - std::fs::write(®ular_file, b"not a socket").expect("write regular file"); - assert!(!is_unix_socket(®ular_file)); - assert!(!is_reachable_unix_socket(®ular_file)); - } - - #[cfg(unix)] - #[test] - #[ignore = "flaky under concurrent test execution"] - fn podman_socket_probe_accepts_successful_ping_response() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let socket_path = temp_dir.path().join("podman.sock"); - let listener = UnixListener::bind(&socket_path).expect("bind podman socket"); - - let handle = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept podman probe"); - let mut request = [0_u8; 128]; - let n = stream.read(&mut request).expect("read podman probe"); - assert!(request[..n].starts_with(b"GET /_ping HTTP/1.1\r\n")); - stream - .write_all( - b"HTTP/1.1 200 OK\r\nLibpod-Api-Version: 5.8.2\r\nContent-Length: 2\r\n\r\nOK", - ) - .expect("write podman ping response"); - }); - - assert!(podman_socket_responds(&socket_path)); - handle.join().expect("probe server exits"); - } - - #[cfg(unix)] - #[test] - #[ignore = "flaky under concurrent test execution"] - fn podman_socket_probe_rejects_docker_ping_response() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let socket_path = temp_dir.path().join("podman.sock"); - let listener = UnixListener::bind(&socket_path).expect("bind podman socket"); - - let handle = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept podman probe"); - let mut request = [0_u8; 128]; - let n = stream.read(&mut request).expect("read podman probe"); - assert!(request[..n].starts_with(b"GET /_ping HTTP/1.1\r\n")); - stream - .write_all( - b"HTTP/1.1 200 OK\r\nServer: Docker/29.2.1\r\nContent-Length: 2\r\n\r\nOK", - ) - .expect("write docker ping response"); - }); - - assert!(!podman_socket_responds(&socket_path)); - handle.join().expect("probe server exits"); - } - - #[cfg(unix)] - #[test] - #[ignore = "flaky under concurrent test execution"] - fn docker_socket_probe_accepts_successful_ping_response() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let socket_path = temp_dir.path().join("docker.sock"); - let listener = UnixListener::bind(&socket_path).expect("bind docker socket"); - - let handle = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept docker probe"); - let mut request = [0_u8; 128]; - let n = stream.read(&mut request).expect("read docker probe"); - assert!(request[..n].starts_with(b"GET /_ping HTTP/1.1\r\n")); - stream - .write_all( - b"HTTP/1.1 200 OK\r\nApi-Version: 1.51\r\nDocker-Experimental: false\r\nContent-Length: 2\r\n\r\nOK", - ) - .expect("write docker ping response"); - }); - - assert!(docker_socket_responds(&socket_path)); - handle.join().expect("probe server exits"); - } - - #[cfg(unix)] - #[test] - #[ignore = "flaky under concurrent test execution"] - fn docker_socket_probe_rejects_podman_ping_response() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let socket_path = temp_dir.path().join("podman.sock"); - let listener = UnixListener::bind(&socket_path).expect("bind podman socket"); - - let handle = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept docker probe"); - let mut request = [0_u8; 128]; - let n = stream.read(&mut request).expect("read docker probe"); - assert!(request[..n].starts_with(b"GET /_ping HTTP/1.1\r\n")); - stream - .write_all( - b"HTTP/1.1 200 OK\r\nLibpod-Api-Version: 5.8.2\r\nContent-Length: 2\r\n\r\nOK", - ) - .expect("write podman ping response"); - }); - - assert!(!docker_socket_responds(&socket_path)); - handle.join().expect("probe server exits"); - } - - #[cfg(unix)] - #[test] - fn docker_socket_probe_rejects_inactive_socket() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let socket_path = temp_dir.path().join("docker.sock"); - let listener = UnixListener::bind(&socket_path).expect("bind docker socket"); - drop(listener); - - assert!(is_unix_socket(&socket_path)); - assert!(!docker_socket_responds(&socket_path)); - } - - #[cfg(unix)] - #[test] - #[ignore = "flaky under concurrent test execution"] - fn docker_socket_detection_returns_the_responsive_candidate() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let inactive_path = temp_dir.path().join("inactive.sock"); - let inactive_listener = UnixListener::bind(&inactive_path).expect("bind inactive socket"); - drop(inactive_listener); - - let responsive_path = temp_dir.path().join("responsive.sock"); - let listener = UnixListener::bind(&responsive_path).expect("bind responsive socket"); - let handle = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept docker probe"); - let mut request = [0_u8; 128]; - let _ = stream.read(&mut request).expect("read docker probe"); - stream - .write_all(b"HTTP/1.1 200 OK\r\nApi-Version: 1.51\r\nContent-Length: 2\r\n\r\nOK") - .expect("write docker ping response"); - }); - - assert_eq!( - detect_docker_socket_from_candidates(&[inactive_path, responsive_path.clone(),]), - Some(responsive_path) - ); - handle.join().expect("probe server exits"); - } - - #[test] - fn podman_socket_candidates_include_env_runtime_and_home_paths() { - let candidates = podman_socket_candidates_from_env( - Some(PathBuf::from("/tmp/custom-podman.sock")), - Some(PathBuf::from("/tmp/runtime")), - Some(PathBuf::from("/tmp/home")), - ); - - assert!(candidates.contains(&PathBuf::from("/tmp/custom-podman.sock"))); - assert!(candidates.contains(&PathBuf::from("/tmp/runtime/podman/podman.sock"))); - assert!(candidates.contains(&PathBuf::from( - "/tmp/home/.local/share/containers/podman/machine/podman.sock" - ))); - } - - #[cfg(unix)] - #[test] - #[ignore = "flaky under concurrent test execution"] - fn podman_socket_detection_returns_the_responsive_candidate() { - let temp_dir = tempfile::tempdir().expect("create temp dir"); - let inactive_path = temp_dir.path().join("inactive.sock"); - let inactive_listener = UnixListener::bind(&inactive_path).expect("bind inactive socket"); - drop(inactive_listener); - - let responsive_path = temp_dir.path().join("responsive.sock"); - let listener = UnixListener::bind(&responsive_path).expect("bind responsive socket"); - let handle = std::thread::spawn(move || { - let (mut stream, _) = listener.accept().expect("accept podman probe"); - let mut request = [0_u8; 128]; - let _ = stream.read(&mut request).expect("read podman probe"); - stream - .write_all( - b"HTTP/1.1 200 OK\r\nLibpod-Api-Version: 5.8.2\r\nContent-Length: 2\r\n\r\nOK", - ) - .expect("write podman ping response"); - }); - - assert_eq!( - detect_podman_socket_from_candidates(&[inactive_path, responsive_path.clone(),]), - Some(responsive_path) - ); - handle.join().expect("probe server exits"); - } - - #[test] - #[allow(unsafe_code)] // std::env::set_var/remove_var require unsafe in Rust 2024 - fn detect_driver_prefers_kubernetes_when_k8s_env_is_set() { - // Save the original env var - let original = std::env::var("KUBERNETES_SERVICE_HOST").ok(); - - // Set the env var - unsafe { - std::env::set_var("KUBERNETES_SERVICE_HOST", "127.0.0.1"); - } - - let result = detect_driver(); - assert_eq!(result, Some(ComputeDriverKind::Kubernetes)); - - // Restore the original env var - unsafe { - match original { - Some(val) => std::env::set_var("KUBERNETES_SERVICE_HOST", val), - None => std::env::remove_var("KUBERNETES_SERVICE_HOST"), - } - } - } - #[test] fn supervisor_image_tag_prefers_explicit_build_tags() { use super::resolve_supervisor_image_tag; @@ -1968,23 +1068,6 @@ mod tests { ); } - #[test] - fn parse_podman_info_socket_extracts_linux_local_socket() { - let info: serde_json::Value = serde_json::json!({ - "host": { - "serviceIsRemote": false, - "remoteSocket": { - "path": "unix:///run/user/1000/podman/podman.sock", - "exists": true - } - } - }); - assert_eq!( - parse_podman_info_socket(&info), - Some(PathBuf::from("/run/user/1000/podman/podman.sock")) - ); - } - #[test] fn supervisor_image_tag_sanitizes_build_metadata_for_oci() { use super::resolve_supervisor_image_tag; @@ -1998,22 +1081,6 @@ mod tests { ); } - #[test] - fn parse_podman_info_socket_handles_path_without_unix_prefix() { - let info: serde_json::Value = serde_json::json!({ - "host": { - "remoteSocket": { - "path": "/run/user/1000/podman/podman.sock", - "exists": true - } - } - }); - assert_eq!( - parse_podman_info_socket(&info), - Some(PathBuf::from("/run/user/1000/podman/podman.sock")) - ); - } - #[test] fn default_supervisor_image_is_version_pinned() { use super::default_supervisor_image; @@ -2022,348 +1089,4 @@ mod tests { let tag = image.rsplit_once(':').unwrap().1; assert!(!tag.is_empty()); } - - #[test] - fn parse_podman_info_socket_returns_none_for_missing_path() { - let info: serde_json::Value = serde_json::json!({ - "host": { - "remoteSocket": {} - } - }); - assert_eq!(parse_podman_info_socket(&info), None); - } - - #[test] - fn parse_podman_info_socket_returns_none_for_empty_path() { - let info: serde_json::Value = serde_json::json!({ - "host": { - "remoteSocket": { - "path": "", - "exists": false - } - } - }); - assert_eq!(parse_podman_info_socket(&info), None); - } - - #[test] - fn parse_podman_machine_inspect_socket_extracts_macos_socket() { - // `podman machine inspect ` returns only the inspected machine. - let machines: serde_json::Value = serde_json::json!([ - { - "ConnectionInfo": { - "PodmanSocket": { - "Path": "/var/folders/1q/jx7s14b928n8zvstgfk98lj00000gn/T/podman/podman-machine-default-api.sock" - }, - "PodmanPipe": null - }, - "Name": "podman-machine-default" - } - ]); - assert_eq!( - parse_podman_machine_inspect_socket(&machines), - Some(PathBuf::from( - "/var/folders/1q/jx7s14b928n8zvstgfk98lj00000gn/T/podman/podman-machine-default-api.sock" - )) - ); - } - - #[test] - fn parse_podman_machine_inspect_socket_returns_none_for_empty_array() { - let machines: serde_json::Value = serde_json::json!([]); - assert_eq!(parse_podman_machine_inspect_socket(&machines), None); - } - - #[test] - fn parse_podman_machine_inspect_socket_returns_none_for_missing_socket() { - let machines: serde_json::Value = serde_json::json!([ - { - "ConnectionInfo": {}, - "Name": "podman-machine-default" - } - ]); - assert_eq!(parse_podman_machine_inspect_socket(&machines), None); - } - - #[test] - fn podman_machine_inspect_targets_uses_explicit_machine_by_name() { - // The active connection points at `work`; discovery must inspect `work` - // explicitly rather than the no-argument default machine, which would - // return a different machine's socket. - assert_eq!( - podman_machine_inspect_targets(&ActiveMachine::Explicit("work".to_string())), - Some(vec!["work".to_string()]) - ); - } - - #[test] - fn podman_machine_inspect_targets_strips_rootful_suffix() { - // Rootful connections are named `-root`; the machine itself is - // ``, offered as a fallback after the connection name. - assert_eq!( - podman_machine_inspect_targets(&ActiveMachine::Explicit("work-root".to_string())), - Some(vec!["work-root".to_string(), "work".to_string()]) - ); - } - - #[test] - fn podman_machine_inspect_targets_uses_default_connection_name() { - assert_eq!( - podman_machine_inspect_targets(&ActiveMachine::Default(Some("work".to_string()))), - Some(vec!["work".to_string()]) - ); - } - - #[test] - fn podman_machine_inspect_targets_falls_back_to_builtin_default() { - // No explicit selector and no default connection: inspect Podman's own - // built-in default machine by name. - assert_eq!( - podman_machine_inspect_targets(&ActiveMachine::Default(None)), - Some(vec!["podman-machine-default".to_string()]) - ); - } - - #[test] - fn podman_machine_inspect_targets_does_not_guess_for_unresolved_explicit() { - // CONTAINER_HOST pointing at a non-machine endpoint cannot be mapped to - // a machine; discovery must not guess an unrelated one. - assert_eq!( - podman_machine_inspect_targets(&ActiveMachine::UnresolvedExplicit), - None - ); - } - - #[cfg(unix)] - #[test] - fn run_bounded_command_captures_stdout_on_success() { - assert_eq!( - run_bounded_command("printf", &["hello"], Duration::from_secs(5)), - Some(b"hello".to_vec()) - ); - } - - #[cfg(unix)] - #[test] - fn run_bounded_command_returns_none_on_nonzero_exit() { - assert_eq!( - run_bounded_command("false", &[], Duration::from_secs(5)), - None - ); - } - - #[cfg(unix)] - #[test] - fn run_bounded_command_kills_child_that_exceeds_deadline() { - // A process that would otherwise block startup indefinitely must be - // bounded: `run_bounded_command` returns within the deadline instead of - // hanging until the child exits. - let start = Instant::now(); - let result = run_bounded_command("sleep", &["30"], Duration::from_millis(200)); - let elapsed = start.elapsed(); - assert_eq!(result, None); - assert!( - elapsed < Duration::from_secs(5), - "bounded command did not return promptly: {elapsed:?}" - ); - } - - #[cfg(unix)] - #[test] - fn run_bounded_command_bounds_drain_when_in_group_descendant_holds_stdout() { - // The shell exits immediately after `echo`, but the backgrounded child - // (in the same process group) inherits and holds the stdout pipe open. - // Without a bounded drain, `read_to_end` would wait ~30s for EOF even - // though the direct child already exited. - let start = Instant::now(); - let result = run_bounded_command( - "sh", - &["-c", "sleep 30 & echo done"], - Duration::from_millis(300), - ); - let elapsed = start.elapsed(); - assert!( - elapsed < Duration::from_secs(2), - "drain blocked on a descendant holding stdout: {elapsed:?}" - ); - // Draining hit the deadline, so the probe is treated as "not found". - assert_eq!(result, None); - } - - #[cfg(unix)] - #[test] - fn run_bounded_command_bounds_drain_when_descendant_escapes_process_group() { - // `set -m` runs the background job in its OWN process group, so it - // survives the group kill while still holding the stdout pipe. The - // deadline must remain absolute: the call must not fall back to an - // untimed receive that waits for the escaped descendant's EOF. - let start = Instant::now(); - let result = run_bounded_command( - "bash", - &["-c", "set -m; sleep 5 & echo done"], - Duration::from_millis(300), - ); - let elapsed = start.elapsed(); - // A regression (blocking receive after the timeout) would wait ~5s for - // the escaped `sleep`; the bounded implementation returns promptly. - assert!( - elapsed < Duration::from_secs(2), - "drain blocked on a descendant that escaped the process group: {elapsed:?}" - ); - assert_eq!(result, None); - } - - #[cfg(unix)] - #[test] - fn run_bounded_command_returns_none_for_missing_program() { - assert_eq!( - run_bounded_command( - "openshell-nonexistent-binary-xyz", - &[], - Duration::from_secs(5) - ), - None - ); - } - - #[test] - fn resolve_active_podman_machine_maps_container_host_to_connection() { - let connections: serde_json::Value = serde_json::json!([ - { "Name": "work", "IsMachine": true, "Default": false, - "URI": "ssh://core@127.0.0.1:5555/run/user/1000/podman/podman.sock" }, - { "Name": "podman-machine-default", "IsMachine": true, "Default": true, - "URI": "ssh://core@127.0.0.1:4444/run/user/1000/podman/podman.sock" } - ]); - // CONTAINER_HOST pointing at the non-default machine's URI resolves to - // that machine, not the default. - assert_eq!( - resolve_active_podman_machine( - Some("ssh://core@127.0.0.1:5555/run/user/1000/podman/podman.sock"), - Some(&connections) - ), - ActiveMachine::Explicit("work".to_string()) - ); - } - - #[test] - fn resolve_active_podman_machine_unmatched_host_is_unresolved() { - let connections: serde_json::Value = serde_json::json!([ - { "Name": "podman-machine-default", "IsMachine": true, "Default": true, - "URI": "ssh://core@127.0.0.1:4444/run/user/1000/podman/podman.sock" } - ]); - // A CONTAINER_HOST that matches no machine connection is unresolved, - // never silently mapped to the default machine. - assert_eq!( - resolve_active_podman_machine(Some("tcp://192.0.2.10:2375"), Some(&connections)), - ActiveMachine::UnresolvedExplicit - ); - } - - #[test] - fn resolve_active_podman_machine_defaults_without_host() { - let connections: serde_json::Value = serde_json::json!([ - { "Name": "podman-machine-default", "IsMachine": true, "Default": true, - "URI": "ssh://core@127.0.0.1:4444/run/user/1000/podman/podman.sock" } - ]); - assert_eq!( - resolve_active_podman_machine(None, Some(&connections)), - ActiveMachine::Default(Some("podman-machine-default".to_string())) - ); - } - - #[test] - fn podman_connection_name_for_uri_ignores_non_machine_matches() { - let connections: serde_json::Value = serde_json::json!([ - { "Name": "remote", "IsMachine": false, "Default": false, - "URI": "tcp://192.0.2.10:2375" } - ]); - // A URI match against a non-machine connection does not map to a local - // machine socket. - assert_eq!( - podman_connection_name_for_uri(&connections, "tcp://192.0.2.10:2375"), - None - ); - } - - #[test] - fn unix_url_socket_path_parses_unix_urls() { - assert_eq!( - unix_url_socket_path("unix:///run/user/1000/podman/podman.sock"), - Some(PathBuf::from("/run/user/1000/podman/podman.sock")) - ); - // Non-unix schemes and empty paths are not sockets. - assert_eq!(unix_url_socket_path("ssh://core@127.0.0.1:22/x"), None); - assert_eq!(unix_url_socket_path("tcp://127.0.0.1:2375"), None); - assert_eq!(unix_url_socket_path("unix://"), None); - } - - #[test] - #[allow(unsafe_code)] // std::env::set_var/remove_var require unsafe in Rust 2024 - fn explicit_unix_container_host_honors_scheme_and_precedence() { - fn set(key: &str, value: Option<&str>) { - unsafe { - match value { - Some(v) => std::env::set_var(key, v), - None => std::env::remove_var(key), - } - } - } - - let original_host = std::env::var("CONTAINER_HOST").ok(); - let original_connection = std::env::var("CONTAINER_CONNECTION").ok(); - - // A unix:// CONTAINER_HOST with no CONTAINER_CONNECTION is used directly. - set("CONTAINER_CONNECTION", None); - set("CONTAINER_HOST", Some("unix:///tmp/podman/custom.sock")); - assert_eq!( - explicit_unix_container_host(), - Some(PathBuf::from("/tmp/podman/custom.sock")) - ); - - // CONTAINER_CONNECTION outranks CONTAINER_HOST. - set("CONTAINER_CONNECTION", Some("work")); - assert_eq!(explicit_unix_container_host(), None); - - // A non-unix CONTAINER_HOST is not a direct socket. - set("CONTAINER_CONNECTION", None); - set( - "CONTAINER_HOST", - Some("ssh://core@127.0.0.1:5555/run/podman.sock"), - ); - assert_eq!(explicit_unix_container_host(), None); - - // Nothing set. - set("CONTAINER_HOST", None); - assert_eq!(explicit_unix_container_host(), None); - - set("CONTAINER_HOST", original_host.as_deref()); - set("CONTAINER_CONNECTION", original_connection.as_deref()); - } - - #[test] - fn parse_default_podman_connection_picks_default_machine() { - let connections: serde_json::Value = serde_json::json!([ - { "Name": "podman-machine-default", "IsMachine": true, "Default": true }, - { "Name": "podman-machine-default-root", "IsMachine": true, "Default": false } - ]); - assert_eq!( - parse_default_podman_connection(&connections), - Some("podman-machine-default".to_string()) - ); - } - - #[test] - fn parse_default_podman_connection_ignores_non_machine_and_missing_default() { - // Default connection that is not a machine is ignored. - let non_machine: serde_json::Value = serde_json::json!([ - { "Name": "remote-host", "IsMachine": false, "Default": true } - ]); - assert_eq!(parse_default_podman_connection(&non_machine), None); - - // No default at all. - let no_default: serde_json::Value = serde_json::json!([ - { "Name": "work", "IsMachine": true, "Default": false } - ]); - assert_eq!(parse_default_podman_connection(&no_default), None); - } } diff --git a/crates/openshell-core/src/driver_utils.rs b/crates/openshell-core/src/driver_utils.rs index f3279d8105..c8be114ebd 100644 --- a/crates/openshell-core/src/driver_utils.rs +++ b/crates/openshell-core/src/driver_utils.rs @@ -437,9 +437,9 @@ pub const PROVIDER_SPIFFE_WORKLOAD_API_SOCKET_MOUNT_DIR: &str = "/spiffe-workloa /// /// The resulting path is `$XDG_STATE_HOME/openshell/[/]//sandbox.jwt`. /// -/// `driver_subdir` is driver-specific, e.g. `"docker-sandbox-tokens"` or -/// `"podman-sandbox-tokens"`. When `namespace` is `Some`, it is appended as -/// an additional path component (with `/` and `\` replaced by `-`). +/// `driver_subdir` is driver-specific. When `namespace` is `Some`, it is +/// appended as an additional path component (with `/` and `\` replaced by +/// `-`). /// /// # Errors /// Returns an error if the XDG state directory cannot be resolved. @@ -472,7 +472,7 @@ pub fn sandbox_log_level(sandbox: &DriverSandbox, default_level: &str) -> String } // --------------------------------------------------------------------------- -// Supervisor image helpers (shared by Docker and Podman drivers) +// Supervisor image helpers shared by container-backed drivers // --------------------------------------------------------------------------- /// Return the tag portion of a supervisor image reference, or `None` if the @@ -507,7 +507,7 @@ pub fn supervisor_image_should_refresh(image: &str) -> bool { } // --------------------------------------------------------------------------- -// Supervisor binary extraction helpers (shared by Docker and Podman drivers) +// Supervisor binary extraction helpers shared by container-backed drivers // --------------------------------------------------------------------------- #[cfg(feature = "driver-extraction")] @@ -584,8 +584,7 @@ pub fn write_cache_binary_atomic(final_path: &Path, bytes: &[u8]) -> Result<(), /// Return the host-side cache path for an extracted supervisor binary. /// /// The path is `$XDG_DATA_HOME/openshell///openshell-sandbox`. -/// `driver_subdir` distinguishes caches across drivers (e.g. `"docker-supervisor"`, -/// `"podman-supervisor"`). +/// `driver_subdir` distinguishes caches across drivers. pub fn supervisor_cache_path(driver_subdir: &str, digest: &str) -> Result { let base = crate::paths::xdg_data_dir() .map_err(|err| format!("failed to resolve XDG data dir: {err}"))?; diff --git a/crates/openshell-core/src/operator_namespace_allowlist.rs b/crates/openshell-core/src/dynamic_string_allowlist.rs similarity index 84% rename from crates/openshell-core/src/operator_namespace_allowlist.rs rename to crates/openshell-core/src/dynamic_string_allowlist.rs index c8f0f7f3de..1a2968188f 100644 --- a/crates/openshell-core/src/operator_namespace_allowlist.rs +++ b/crates/openshell-core/src/dynamic_string_allowlist.rs @@ -4,16 +4,13 @@ use std::collections::BTreeSet; use std::sync::{Arc, RwLock}; -/// Thread-safe dynamic allowlist of Kubernetes operator-mode namespaces. -/// -/// This type lives in the public core API because both the Kubernetes driver -/// and gateway authentication boundary consume it. +/// Thread-safe dynamic allowlist of strings shared across component boundaries. #[derive(Debug, Clone)] -pub struct OperatorNamespaceAllowlist { +pub struct DynamicStringAllowlist { inner: Arc>>, } -impl OperatorNamespaceAllowlist { +impl DynamicStringAllowlist { fn read_guard(&self) -> std::sync::RwLockReadGuard<'_, BTreeSet> { self.inner .read() @@ -71,7 +68,7 @@ impl OperatorNamespaceAllowlist { } } -impl Default for OperatorNamespaceAllowlist { +impl Default for DynamicStringAllowlist { fn default() -> Self { Self::new() } diff --git a/crates/openshell-core/src/error.rs b/crates/openshell-core/src/error.rs index 8c23e30198..145106012d 100644 --- a/crates/openshell-core/src/error.rs +++ b/crates/openshell-core/src/error.rs @@ -106,8 +106,8 @@ impl Error { /// Error type shared by all compute driver implementations. /// -/// Both the Podman and Kubernetes drivers map their backend-specific -/// errors into these variants before crossing crate boundaries. +/// Drivers map backend-specific errors into these variants before crossing +/// crate boundaries. #[derive(Debug, Error)] pub enum ComputeDriverError { /// The requested sandbox already exists. diff --git a/crates/openshell-core/src/lib.rs b/crates/openshell-core/src/lib.rs index 315bb319bb..9aecfcb1f1 100644 --- a/crates/openshell-core/src/lib.rs +++ b/crates/openshell-core/src/lib.rs @@ -16,6 +16,7 @@ pub mod container_paths; pub mod denial; pub mod driver_mounts; pub mod driver_utils; +pub mod dynamic_string_allowlist; pub mod endpoint_path; pub mod error; #[cfg(unix)] @@ -28,12 +29,12 @@ pub mod host_pattern; pub mod image; pub mod inference; pub mod jwt; +pub mod local_api_socket; pub mod metadata; pub mod middleware; pub mod net; #[cfg(feature = "oauth")] pub mod oauth; -pub mod operator_namespace_allowlist; pub mod paths; pub mod policy; pub mod progress; @@ -50,16 +51,16 @@ pub mod time; pub mod transport_errors; pub use config::{ - ComputeDriverKind, Config, GatewayAuthConfig, GatewayInterceptorBindingOverride, - GatewayInterceptorBindingPolicy, GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, - GatewayInterceptorPhaseConfig, GatewayJwtConfig, GatewayProviderProfileSourceConfig, - MtlsAuthConfig, OidcConfig, PolicyValidationFailureMode, TlsConfig, + Config, GatewayAuthConfig, GatewayInterceptorBindingOverride, GatewayInterceptorBindingPolicy, + GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, GatewayInterceptorPhaseConfig, + GatewayJwtConfig, GatewayProviderProfileSourceConfig, MtlsAuthConfig, OidcConfig, + PolicyValidationFailureMode, TlsConfig, }; +pub use dynamic_string_allowlist::DynamicStringAllowlist; pub use error::{ComputeDriverError, Error, Result}; pub use metadata::{ GetResourceVersion, ObjectId, ObjectLabels, ObjectName, ObjectWorkspace, SetResourceVersion, }; -pub use operator_namespace_allowlist::OperatorNamespaceAllowlist; /// Build version string derived from git metadata. /// diff --git a/crates/openshell-core/src/local_api_socket.rs b/crates/openshell-core/src/local_api_socket.rs new file mode 100644 index 0000000000..6804ae513a --- /dev/null +++ b/crates/openshell-core/src/local_api_socket.rs @@ -0,0 +1,81 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Generic discovery and probing for local HTTP APIs over Unix sockets. + +use std::path::{Path, PathBuf}; + +/// Return the first candidate whose HTTP ping response is accepted. +#[must_use] +pub fn first_responsive_socket( + candidates: &[PathBuf], + accepts_response: impl Fn(&[u8]) -> bool, +) -> Option { + candidates + .iter() + .find(|path| socket_responds(path, &accepts_response)) + .cloned() +} + +/// Return whether a byte slice contains another, ignoring ASCII case. +#[must_use] +pub fn contains_ascii(haystack: &[u8], needle: &[u8]) -> bool { + haystack + .windows(needle.len()) + .any(|window| window.eq_ignore_ascii_case(needle)) +} + +/// Return whether an HTTP response starts with a successful status line. +#[must_use] +pub fn http_response_is_success(response: &[u8]) -> bool { + response.starts_with(b"HTTP/1.1 200") || response.starts_with(b"HTTP/1.0 200") +} + +#[cfg(unix)] +fn socket_responds(path: &Path, accepts_response: &impl Fn(&[u8]) -> bool) -> bool { + use std::io::{Read as _, Write as _}; + use std::os::unix::fs::FileTypeExt as _; + use std::time::Duration; + + const PROBE_TIMEOUT: Duration = Duration::from_secs(1); + const PING_REQUEST: &[u8] = + b"GET /_ping HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; + + if !path + .metadata() + .is_ok_and(|metadata| metadata.file_type().is_socket()) + { + return false; + } + let Ok(mut stream) = std::os::unix::net::UnixStream::connect(path) else { + return false; + }; + if stream.set_read_timeout(Some(PROBE_TIMEOUT)).is_err() + || stream.set_write_timeout(Some(PROBE_TIMEOUT)).is_err() + || stream.write_all(PING_REQUEST).is_err() + { + return false; + } + + let mut response = [0_u8; 512]; + let mut total = 0; + while total < response.len() { + let Ok(read) = stream.read(&mut response[total..]) else { + return false; + }; + if read == 0 { + break; + } + total += read; + if contains_ascii(&response[..total], b"\r\n\r\n") { + break; + } + } + total > 0 && accepts_response(&response[..total]) +} + +#[cfg(not(unix))] +fn socket_responds(path: &Path, accepts_response: &impl Fn(&[u8]) -> bool) -> bool { + let _ = (path, accepts_response); + false +} diff --git a/crates/openshell-core/src/metadata.rs b/crates/openshell-core/src/metadata.rs index 8794c11d5d..f885812c4e 100644 --- a/crates/openshell-core/src/metadata.rs +++ b/crates/openshell-core/src/metadata.rs @@ -6,8 +6,9 @@ //! These traits provide uniform access to `ObjectMeta` fields across all resource types. use crate::proto::{ - InferenceRoute, ObjectForTest, Provider, Sandbox, SandboxStatus, ServiceEndpoint, SshSession, - StoredProviderCredentialRefreshState, StoredProviderProfile, Workspace, WorkspaceMember, + InferenceRoute, ObjectForTest, Provider, Sandbox, SandboxStatus, SandboxWorkloadTemplate, + ServiceEndpoint, SshSession, StoredProviderCredentialRefreshState, StoredProviderProfile, + Workspace, WorkspaceMember, }; use std::collections::HashMap; @@ -104,6 +105,49 @@ impl Sandbox { } } +// Implementations for SandboxWorkloadTemplate +impl ObjectId for SandboxWorkloadTemplate { + fn object_id(&self) -> &str { + self.metadata.as_ref().map_or("", |m| m.id.as_str()) + } +} + +impl ObjectName for SandboxWorkloadTemplate { + fn object_name(&self) -> &str { + self.metadata.as_ref().map_or("", |m| m.name.as_str()) + } +} + +impl ObjectLabels for SandboxWorkloadTemplate { + fn object_labels(&self) -> Option> { + self.metadata.as_ref().map(|m| m.labels.clone()) + } +} + +impl SetResourceVersion for SandboxWorkloadTemplate { + fn set_resource_version(&mut self, version: u64) { + if let Some(meta) = self.metadata.as_mut() { + meta.resource_version = version; + } + } +} + +impl GetResourceVersion for SandboxWorkloadTemplate { + fn get_resource_version(&self) -> u64 { + self.metadata.as_ref().map_or(0, |m| m.resource_version) + } +} + +impl ObjectWorkspace for SandboxWorkloadTemplate { + fn object_workspace(&self) -> &str { + self.metadata.as_ref().map_or("", |m| m.workspace.as_str()) + } + + fn requires_workspace() -> bool { + true + } +} + // Implementations for Workspace impl ObjectId for Workspace { fn object_id(&self) -> &str { diff --git a/crates/openshell-core/src/sandbox_env.rs b/crates/openshell-core/src/sandbox_env.rs index 8da9a7d2a8..99ac55fe6e 100644 --- a/crates/openshell-core/src/sandbox_env.rs +++ b/crates/openshell-core/src/sandbox_env.rs @@ -105,7 +105,7 @@ impl MainProcessConfig { } /// Encode the versioned transport without whitespace for constrained - /// environment-variable transports such as libkrun. + /// environment-variable transports used by embedded runtimes. pub fn encode_driver_spec_base64url( spec: Option<&crate::proto::compute::v1::DriverSandboxSpec>, ) -> Result { diff --git a/crates/openshell-core/src/settings.rs b/crates/openshell-core/src/settings.rs index 625ba4c856..b7bf72c3d3 100644 --- a/crates/openshell-core/src/settings.rs +++ b/crates/openshell-core/src/settings.rs @@ -65,7 +65,7 @@ impl RegisteredSetting { /// /// 1. Add a [`RegisteredSetting`] entry to this array with the key name and /// [`SettingValueKind`]. -/// 2. Recompile `openshell-server` (gateway) and `openshell-sandbox` +/// 2. Recompile `openshell-gateway` and `openshell-sandbox` /// (supervisor). No database migration is needed -- new keys are stored in /// the existing settings JSON blob. /// 3. Add sandbox-side consumption in `openshell-sandbox` to read and act on diff --git a/crates/openshell-core/src/telemetry.rs b/crates/openshell-core/src/telemetry.rs index ad15989944..63aa5f9181 100644 --- a/crates/openshell-core/src/telemetry.rs +++ b/crates/openshell-core/src/telemetry.rs @@ -145,6 +145,7 @@ impl PolicyDecisionOperation { pub enum SandboxTemplateSource { Default, Image, + WorkloadTemplate, Undefined, } @@ -154,56 +155,41 @@ impl SandboxTemplateSource { match self { Self::Default => "default", Self::Image => "image", + Self::WorkloadTemplate => "workload_template", Self::Undefined => "undefined", } } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum TelemetryComputeDriver { - Docker, - Kubernetes, - Podman, - Vm, - Mxc, - Unknown, -} +pub struct TelemetryComputeDriver(&'static str); impl TelemetryComputeDriver { #[must_use] pub const fn as_str(self) -> &'static str { - match self { - Self::Docker => "docker", - Self::Kubernetes => "kubernetes", - Self::Podman => "podman", - Self::Vm => "vm", - Self::Mxc => "mxc", - Self::Unknown => "unknown", - } + self.0 } + /// Classify an unregistered compute driver without exposing its configured + /// name. #[must_use] - pub fn from_raw(raw: &str) -> Self { - match raw.trim().to_ascii_lowercase().as_str() { - "docker" => Self::Docker, - "k8s" | "kubernetes" => Self::Kubernetes, - "podman" => Self::Podman, - "vm" => Self::Vm, - "mxc" => Self::Mxc, - _ => Self::Unknown, - } + pub const fn custom() -> Self { + Self("custom") } + /// Define a bounded, anonymous category at a binary composition boundary. + /// + /// The category must be a static operational label. Never construct it + /// from user input, configuration, resource names, or other runtime data. #[must_use] - pub const fn from_driver_kind(driver_kind: Option) -> Self { - match driver_kind { - Some(crate::ComputeDriverKind::Docker) => Self::Docker, - Some(crate::ComputeDriverKind::Kubernetes) => Self::Kubernetes, - Some(crate::ComputeDriverKind::Podman) => Self::Podman, - Some(crate::ComputeDriverKind::Vm) => Self::Vm, - Some(crate::ComputeDriverKind::Mxc) => Self::Mxc, - None => Self::Unknown, - } + pub const fn anonymous_category(category: &'static str) -> Self { + Self(category) + } +} + +impl Default for TelemetryComputeDriver { + fn default() -> Self { + Self::custom() } } @@ -688,27 +674,11 @@ mod tests { } #[test] - fn compute_driver_values_are_sanitized() { - assert_eq!( - TelemetryComputeDriver::from_raw("docker").as_str(), - "docker" - ); - assert_eq!( - TelemetryComputeDriver::from_raw("k8s").as_str(), - "kubernetes" - ); - assert_eq!( - TelemetryComputeDriver::from_raw("KUBERNETES").as_str(), - "kubernetes" - ); - assert_eq!(TelemetryComputeDriver::from_raw("vm").as_str(), "vm"); - assert_eq!( - TelemetryComputeDriver::from_raw("podman").as_str(), - "podman" - ); + fn compute_driver_values_are_bounded_by_the_composition_boundary() { + assert_eq!(TelemetryComputeDriver::custom().as_str(), "custom"); assert_eq!( - TelemetryComputeDriver::from_raw("private-driver").as_str(), - "unknown" + TelemetryComputeDriver::anonymous_category("first_party").as_str(), + "first_party" ); } @@ -797,7 +767,7 @@ mod disabled_tests { 1, false, SandboxTemplateSource::Default, - TelemetryComputeDriver::Docker, + TelemetryComputeDriver::custom(), ); emit_policy_decision( PolicyDecisionOperation::Approve, diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index 3941819c61..d599cac169 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -21,9 +21,7 @@ use bollard::query_parameters::{ }; use bytes::Bytes; use futures::{Stream, StreamExt}; -use openshell_core::config::{ - DEFAULT_DOCKER_NETWORK_NAME, DEFAULT_SANDBOX_PIDS_LIMIT, DEFAULT_STOP_TIMEOUT_SECS, -}; +use openshell_core::config::{DEFAULT_SANDBOX_PIDS_LIMIT, DEFAULT_STOP_TIMEOUT_SECS}; use openshell_core::driver_mounts; use openshell_core::driver_utils::{ CONDITION_EXITED, CONDITION_RUNTIME_RESTART, LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, @@ -56,7 +54,7 @@ use openshell_core::proto::compute::v1::{ use openshell_core::proto_struct::{ deserialize_optional_non_empty_string_list, struct_to_json_value, }; -use openshell_core::{Config, Error, Result as CoreResult}; +use openshell_core::{Error, Result as CoreResult}; use opentelemetry::trace::TraceContextExt as _; use std::collections::{HashMap, HashSet}; use std::future::Future; @@ -528,12 +526,45 @@ impl ComputeDriverService { } } +/// Return the first responsive local Docker API socket. +#[must_use] +pub fn detect_socket() -> Option { + let mut candidates = Vec::new(); + if let Ok(host) = std::env::var("DOCKER_HOST") + && let Some(path) = host.trim().strip_prefix("unix://") + && !path.is_empty() + { + candidates.push(PathBuf::from(path)); + } + candidates.push(PathBuf::from("/var/run/docker.sock")); + if let Some(home) = std::env::var_os("HOME") { + candidates.push(PathBuf::from(home).join(".docker/run/docker.sock")); + } + if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") { + candidates.push(PathBuf::from(runtime_dir).join("docker.sock")); + } + openshell_core::local_api_socket::first_responsive_socket(&candidates, |response| { + openshell_core::local_api_socket::http_response_is_success(response) + && openshell_core::local_api_socket::contains_ascii(response, b"Api-Version:") + && !openshell_core::local_api_socket::contains_ascii(response, b"Libpod-Api-Version:") + }) +} + +#[must_use] +pub fn is_available() -> bool { + detect_socket().is_some() +} + impl DockerComputeDriver { - pub async fn new(config: &Config, docker_config: &DockerComputeConfig) -> CoreResult { + pub async fn new( + gateway_bind_address: SocketAddr, + gateway_log_level: &str, + docker_config: &DockerComputeConfig, + ) -> CoreResult { let socket_path = docker_config .socket_path .clone() - .or_else(openshell_core::config::detect_docker_socket) + .or_else(detect_socket) .unwrap_or_else(|| PathBuf::from("/var/run/docker.sock")); let socket_path_str = socket_path.to_str().ok_or_else(|| { Error::config(format!( @@ -559,7 +590,7 @@ impl DockerComputeDriver { let cdi_gpu_inventory = docker_cdi_gpu_inventory(&info); let allow_all_default_gpu = docker_info_reports_wsl2(&info); validate_sandbox_pids_limit(docker_config.sandbox_pids_limit)?; - let gateway_port = config.bind_address.port(); + let gateway_port = gateway_bind_address.port(); if gateway_port == 0 { return Err(Error::config( "docker compute driver requires a fixed non-zero gateway bind port", @@ -571,7 +602,7 @@ impl DockerComputeDriver { let gateway_route = docker_gateway_route(&info, bridge_gateway_ip, gateway_port, host_gateway_ip); let gateway_callback_bind_address = - docker_gateway_callback_bind_address(&gateway_route, config.bind_address); + docker_gateway_callback_bind_address(&gateway_route, gateway_bind_address); let mut docker_config = docker_config.clone(); if docker_config.grpc_endpoint.trim().is_empty() { let scheme = if docker_guest_tls_configured(&docker_config) { @@ -603,7 +634,7 @@ impl DockerComputeDriver { gateway_callback_bind_address, ssh_socket_path: docker_config.ssh_socket_path.clone(), stop_timeout_secs: DEFAULT_STOP_TIMEOUT_SECS, - log_level: config.log_level.clone(), + log_level: gateway_log_level.to_string(), supervisor_bin, guest_tls, daemon_version: version.version.unwrap_or_else(|| "unknown".to_string()), @@ -636,6 +667,7 @@ impl DockerComputeDriver { default_image: self.config.default_image.clone(), gateway_manages_lifecycle: true, supports_sandbox_authentication: false, + driver_reports_runtime_readiness: false, } } @@ -4140,3 +4172,4 @@ fn internal_status(operation: &str, err: BollardError) -> Status { #[cfg(test)] mod tests; +pub const DEFAULT_DOCKER_NETWORK_NAME: &str = "openshell-docker"; diff --git a/crates/openshell-driver-docker/src/main.rs b/crates/openshell-driver-docker/src/main.rs index 2c6dbfd4c1..11a2762849 100644 --- a/crates/openshell-driver-docker/src/main.rs +++ b/crates/openshell-driver-docker/src/main.rs @@ -6,8 +6,8 @@ use std::path::PathBuf; use clap::Parser; use miette::{IntoDiagnostic, Result}; +use openshell_core::VERSION; use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; -use openshell_core::{Config, VERSION}; use openshell_driver_docker::otel_tracing::compute_driver_rpc_layer; use openshell_driver_docker::{ComputeDriverService, DockerComputeConfig, DockerComputeDriver}; use tracing::info; @@ -67,8 +67,7 @@ async fn main() -> Result<()> { let config_source = std::fs::read_to_string(&args.config).into_diagnostic()?; let docker_config: DockerComputeConfig = toml::from_str(&config_source).into_diagnostic()?; - let gateway_config = Config::new(None).with_bind_address(args.gateway_bind); - let driver = DockerComputeDriver::new(&gateway_config, &docker_config) + let driver = DockerComputeDriver::new(args.gateway_bind, &args.log_level, &docker_config) .await .into_diagnostic()?; diff --git a/crates/openshell-driver-docker/src/tests.rs b/crates/openshell-driver-docker/src/tests.rs index fd81c9b638..07fb2b0ffb 100644 --- a/crates/openshell-driver-docker/src/tests.rs +++ b/crates/openshell-driver-docker/src/tests.rs @@ -43,6 +43,7 @@ fn test_sandbox() -> DriverSandbox { environment: HashMap::from([("TEMPLATE_ENV".to_string(), "template".to_string())]), ..Default::default() }), + policy: None, resource_requirements: None, sandbox_token: String::new(), command: Vec::new(), diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index aadcb1342a..805c0314b0 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -pub use openshell_core::OperatorNamespaceAllowlist; +pub use openshell_core::DynamicStringAllowlist as OperatorNamespaceAllowlist; use openshell_core::config; use serde::{Deserialize, Deserializer, Serialize}; use std::collections::BTreeMap; diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 484cd07708..afe3f579e0 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -575,6 +575,7 @@ impl KubernetesComputeDriver { default_image: self.config.default_image.clone(), gateway_manages_lifecycle: false, supports_sandbox_authentication: true, + driver_reports_runtime_readiness: false, }) } @@ -3864,9 +3865,14 @@ fn sandbox_template_to_k8s_with_validated_config( } apply_pod_driver_config(&mut spec, &driver_config.pod); - // Per-sandbox platform_config.host_users overrides the cluster-wide default. - let use_user_namespaces = platform_config_bool(template, "host_users") - .map_or(params.enable_user_namespaces, |host_users| !host_users); + // Per-sandbox portable intent overrides the cluster-wide default. This + // driver owns the Kubernetes-specific `hostUsers` translation. Accept the + // former platform_config encoding during rolling upgrades from gateways + // that predate the typed field. + let use_user_namespaces = template + .user_namespaces + .or_else(|| platform_config_bool(template, "host_users").map(|host_users| !host_users)) + .unwrap_or(params.enable_user_namespaces); if use_user_namespaces { spec.insert("hostUsers".to_string(), serde_json::json!(false)); @@ -4482,7 +4488,7 @@ fn platform_config_bool(template: &SandboxTemplate, key: &str) -> Option { let config = template.platform_config.as_ref()?; let value = config.fields.get(key)?; match value.kind.as_ref() { - Some(prost_types::value::Kind::BoolValue(b)) => Some(*b), + Some(prost_types::value::Kind::BoolValue(value)) => Some(*value), _ => None, } } @@ -7610,15 +7616,7 @@ mod tests { #[test] fn user_namespaces_per_sandbox_override_enables() { let template = SandboxTemplate { - platform_config: Some(Struct { - fields: std::iter::once(( - "host_users".to_string(), - Value { - kind: Some(Kind::BoolValue(false)), - }, - )) - .collect(), - }), + user_namespaces: Some(true), ..SandboxTemplate::default() }; @@ -7634,7 +7632,7 @@ mod tests { assert_eq!( pod_template["spec"]["hostUsers"], serde_json::json!(false), - "per-sandbox host_users: false must enable user namespaces" + "per-sandbox user namespace intent must set hostUsers: false" ); let caps = pod_template["spec"]["containers"][0]["securityContext"]["capabilities"]["add"] .as_array() @@ -7645,15 +7643,7 @@ mod tests { #[test] fn user_namespaces_per_sandbox_override_disables() { let template = SandboxTemplate { - platform_config: Some(Struct { - fields: std::iter::once(( - "host_users".to_string(), - Value { - kind: Some(Kind::BoolValue(true)), - }, - )) - .collect(), - }), + user_namespaces: Some(false), ..SandboxTemplate::default() }; @@ -7671,7 +7661,7 @@ mod tests { assert!( pod_template["spec"]["hostUsers"].is_null(), - "per-sandbox host_users: true must disable user namespaces even when cluster default is on" + "per-sandbox user namespace intent must override the cluster default" ); let caps = pod_template["spec"]["containers"][0]["securityContext"]["capabilities"]["add"] .as_array() @@ -7683,6 +7673,37 @@ mod tests { ); } + #[test] + fn user_namespaces_accepts_legacy_host_users_encoding() { + let template = SandboxTemplate { + platform_config: Some(Struct { + fields: std::iter::once(( + "host_users".to_string(), + Value { + kind: Some(Kind::BoolValue(false)), + }, + )) + .collect(), + }), + ..SandboxTemplate::default() + }; + + let params = SandboxPodParams::default(); + let pod_template = sandbox_template_to_k8s( + &template, + false, + &std::collections::HashMap::new(), + true, + ¶ms, + ); + + assert_eq!( + pod_template["spec"]["hostUsers"], + serde_json::json!(false), + "legacy host_users: false must still enable user namespaces" + ); + } + #[test] fn automount_service_account_token_is_disabled() { let pod_template = { @@ -7866,43 +7887,6 @@ mod tests { ); } - #[test] - fn platform_config_bool_extracts_value() { - let template = SandboxTemplate { - platform_config: Some(Struct { - fields: std::iter::once(( - "my_bool".to_string(), - Value { - kind: Some(Kind::BoolValue(true)), - }, - )) - .collect(), - }), - ..SandboxTemplate::default() - }; - - assert_eq!(platform_config_bool(&template, "my_bool"), Some(true)); - assert_eq!(platform_config_bool(&template, "missing"), None); - } - - #[test] - fn platform_config_bool_returns_none_for_non_bool() { - let template = SandboxTemplate { - platform_config: Some(Struct { - fields: std::iter::once(( - "a_string".to_string(), - Value { - kind: Some(Kind::StringValue("hello".to_string())), - }, - )) - .collect(), - }), - ..SandboxTemplate::default() - }; - - assert_eq!(platform_config_bool(&template, "a_string"), None); - } - #[test] fn log_level_propagates_as_env_var_to_sandbox_pod() { let spec = SandboxSpec { diff --git a/crates/openshell-driver-kubernetes/src/lib.rs b/crates/openshell-driver-kubernetes/src/lib.rs index edc0a3e97e..28d3c77a7d 100644 --- a/crates/openshell-driver-kubernetes/src/lib.rs +++ b/crates/openshell-driver-kubernetes/src/lib.rs @@ -14,4 +14,4 @@ pub use config::{ }; pub use driver::{KubernetesComputeDriver, KubernetesDriverError}; pub use grpc::ComputeDriverService; -pub use openshell_core::OperatorNamespaceAllowlist; +pub use openshell_core::DynamicStringAllowlist as OperatorNamespaceAllowlist; diff --git a/crates/openshell-driver-mxc/README.md b/crates/openshell-driver-mxc/README.md index 6496dfe286..bd0b51f48b 100644 --- a/crates/openshell-driver-mxc/README.md +++ b/crates/openshell-driver-mxc/README.md @@ -4,8 +4,11 @@ OpenShell compute driver backed by **Microsoft MXC** (`wxc-exec`) on Windows. ## Design -This driver implements the gateway's `ComputeDriver` contract as an in-process -library linked into `openshell-gateway`. `process_container` launches a one-shot +This driver implements the gateway's ordinary in-process `ComputeDriver` +contract and is linked into `openshell-gateway`. It sets +`driver_reports_runtime_readiness`, so the gateway accepts driver-reported +readiness without a supervisor session. The canonical create-time +`SandboxPolicy` is carried by `DriverSandboxSpec.policy`. `process_container` launches a one-shot AppContainer and is the default. The opt-in `isolation_session` backend uses the state-aware `provision` → `start` → `exec` → `stop` → `deprovision` lifecycle. The driver launches and monitors the configured workload itself and self-reports @@ -51,7 +54,9 @@ openshell sandbox create --name mxc-demo --policy demo.yaml ` The `command` array is required and preserves Windows argument boundaries. `cwd` is optional. Environment variables come from the standard sandbox and template environment maps; the driver never copies values from the gateway host environment. -Network policy and live policy replacement or merge updates are rejected while the gateway uses MXC. Delete and recreate the sandbox to apply a different filesystem policy. +Network policy support depends on the selected containment path. Policy +replacement and merge updates use the gateway's standard sandbox configuration +revision contract. ## Prerequisites (live runs) @@ -64,7 +69,11 @@ no isolation session needed), set `OPENSHELL_MXC_MOCK_WXC=1`. ## Policy mapping -The production driver maps the typed `SandboxPolicy` to MXC configuration before it inserts a registry entry or invokes `wxc-exec`. Mapping failure therefore returns from `CreateSandbox` without leaving a partial sandbox. +The production driver maps the typed `SandboxPolicy` carried by the standard +driver request to MXC configuration before it inserts a registry entry or +invokes `wxc-exec`. Mapping failure therefore returns from `CreateSandbox` +without leaving a partial sandbox. There is no in-process policy side channel +or MXC-specific gateway composition variant. `EmbeddedPolicyMapper` calls the embedded [`policy_map`](src/policy_map/) module directly and normalizes filesystem paths to Windows form. It does not add gateway-configured host paths. The policy supplied for the sandbox is the only source of filesystem grants. diff --git a/crates/openshell-driver-mxc/src/driver.rs b/crates/openshell-driver-mxc/src/driver.rs index d8e981a46d..1ded7130c4 100644 --- a/crates/openshell-driver-mxc/src/driver.rs +++ b/crates/openshell-driver-mxc/src/driver.rs @@ -177,13 +177,6 @@ pub struct MxcComputeBackend { registry: Arc>>, watch_tx: Arc>, policy_mapper: Arc, - /// Out-of-band side channel for the `SandboxPolicy` (A1). The proto driver - /// contract has no `policy` field and there is no driver-side - /// `GetSandboxConfig`, so `ComputeRuntime::create_sandbox` stages the policy - /// here keyed by sandbox id (mirroring the `sandbox_token` injection), - /// immediately before dispatching to this backend's `create_sandbox`, which - /// removes/consumes it. - pending_policies: Arc>>, } impl std::fmt::Debug for MxcComputeBackend { @@ -279,17 +272,9 @@ impl MxcComputeBackend { // Production policy translation is always handled by the embedded // mapper before any MXC lifecycle side effects begin. policy_mapper: Arc::new(EmbeddedPolicyMapper), - pending_policies: Arc::new(Mutex::new(HashMap::new())), } } - /// Returns a clone of the `pending_policies` side channel so the gateway's - /// `ComputeRuntime` can stage the typed `SandboxPolicy` by sandbox id right - /// before dispatching `create_sandbox` (A1 wiring). - pub fn policy_sink(&self) -> Arc>> { - self.pending_policies.clone() - } - /// Test-only constructor wiring the in-process mock `wxc-exec` shim. #[cfg(test)] pub(crate) fn new_mocked(config: MxcComputeConfig) -> Self { @@ -304,10 +289,12 @@ impl MxcComputeBackend { driver_version: DRIVER_VERSION.to_string(), default_image: DEFAULT_IMAGE_SENTINEL.to_string(), gateway_manages_lifecycle: false, + supports_sandbox_authentication: false, + driver_reports_runtime_readiness: true, } } - pub fn validate_sandbox_create(&self, sandbox: &DriverSandbox) -> Result<(), tonic::Status> { + fn validate_sandbox_fields(&self, sandbox: &DriverSandbox) -> Result<(), tonic::Status> { if let Some(spec) = &sandbox.spec { if effective_driver_gpu_count(driver_gpu_requirements( spec.resource_requirements.as_ref(), @@ -330,6 +317,29 @@ impl MxcComputeBackend { sandbox_config(sandbox)?; Ok(()) } + + fn map_sandbox_policy( + &self, + sandbox_id: &str, + policy: Option<&SandboxPolicy>, + ) -> Result { + self.policy_mapper + .map( + policy, + &MapCtx { + sandbox_id: sandbox_id.to_string(), + egress: None, + }, + ) + .map_err(|error| tonic::Status::invalid_argument(error.to_string())) + } + + pub fn validate_sandbox_create(&self, sandbox: &DriverSandbox) -> Result<(), tonic::Status> { + self.validate_sandbox_fields(sandbox)?; + let policy = sandbox.spec.as_ref().and_then(|spec| spec.policy.as_ref()); + self.map_sandbox_policy(&sandbox.id, policy)?; + Ok(()) + } pub async fn get_sandbox(&self, sandbox_name: &str) -> Option { let registry = self.registry.lock().await; registry @@ -346,25 +356,14 @@ impl MxcComputeBackend { pub async fn create_sandbox(&self, sandbox: &DriverSandbox) -> Result<(), tonic::Status> { let sandbox_id = sandbox.id.clone(); - // Consume the out-of-band policy staged by `ComputeRuntime::create_sandbox` - // (A1). Always remove so rejected creates cannot leak policy state. - let policy = self.pending_policies.lock().await.remove(&sandbox_id); - self.validate_sandbox_create(sandbox)?; + self.validate_sandbox_fields(sandbox)?; let sandbox_config = sandbox_config(sandbox)?; // Policy translation is deterministic and side-effect free. Do it before // inserting the registry entry or launching MXC so invalid requests fail // synchronously at the CreateSandbox boundary. - let mapped = self - .policy_mapper - .map( - policy.as_ref(), - &MapCtx { - sandbox_id: sandbox_id.clone(), - egress: None, - }, - ) - .map_err(|error| tonic::Status::invalid_argument(error.to_string()))?; + let policy = sandbox.spec.as_ref().and_then(|spec| spec.policy.as_ref()); + let mapped = self.map_sandbox_policy(&sandbox_id, policy)?; if sandbox .spec @@ -941,6 +940,11 @@ mod lifecycle_tests { } } + fn with_policy(mut sandbox: DriverSandbox, policy: SandboxPolicy) -> DriverSandbox { + sandbox.spec.as_mut().unwrap().policy = Some(policy); + sandbox + } + fn ready_condition(sb: &DriverSandbox) -> Option { sb.status .as_ref()? @@ -1027,13 +1031,8 @@ mod lifecycle_tests { ]; let backend = MxcComputeBackend::new_mocked(MxcComputeConfig::default()); - // Stage the policy via the A1 side channel (as ComputeRuntime would). - let sink = backend.policy_sink(); - sink.lock() - .await - .insert("sb-pos".into(), fs_policy(&[&share])); - - let sb = driver_sandbox_with_command("sb-pos", &share, cmd); + let policy = fs_policy(&[&share]); + let sb = with_policy(driver_sandbox_with_command("sb-pos", &share, cmd), policy); backend.create_sandbox(&sb).await.expect("create accepted"); // Self-reported Ready=True (no supervisor) once the agent exec launches. @@ -1085,12 +1084,8 @@ mod lifecycle_tests { ]; let backend = MxcComputeBackend::new_mocked(MxcComputeConfig::default()); - let sink = backend.policy_sink(); - sink.lock() - .await - .insert("sb-pc".into(), fs_policy(&[&share])); - - let sb = driver_sandbox_with_command("sb-pc", &share, cmd); + let policy = fs_policy(&[&share]); + let sb = with_policy(driver_sandbox_with_command("sb-pc", &share, cmd), policy); backend.create_sandbox(&sb).await.expect("create accepted"); let ready = wait_for(&backend, "sb-pc", |s| { @@ -1142,12 +1137,10 @@ mod lifecycle_tests { // Subscribe to the watch stream BEFORE create so we catch the denial event. let mut stream = backend.watch_sandboxes().await; - let sink = backend.policy_sink(); - sink.lock() - .await - .insert("sb-neg".into(), fs_policy(&[&share])); + let policy = fs_policy(&[&share]); + let sandbox = with_policy(driver_sandbox_with_command("sb-neg", &share, cmd), policy); backend - .create_sandbox(&driver_sandbox_with_command("sb-neg", &share, cmd)) + .create_sandbox(&sandbox) .await .expect("create accepted"); @@ -1199,13 +1192,10 @@ mod lifecycle_tests { format!("$null = '{share}'; Start-Sleep -Seconds 60"), ]; let backend = MxcComputeBackend::new_mocked(MxcComputeConfig::default()); + let policy = fs_policy(&[&share]); + let sandbox = with_policy(driver_sandbox_with_command("sb-stop", "", command), policy); backend - .policy_sink() - .lock() - .await - .insert("sb-stop".into(), fs_policy(&[&share])); - backend - .create_sandbox(&driver_sandbox_with_command("sb-stop", "", command)) + .create_sandbox(&sandbox) .await .expect("create accepted"); wait_for(&backend, "sb-stop", |sandbox| { @@ -1245,13 +1235,9 @@ mod lifecycle_tests { binaries: Vec::new(), }, ); - backend - .policy_sink() - .lock() - .await - .insert("sb-net".into(), policy); + let sandbox = with_policy(driver_sandbox("sb-net"), policy); let error = backend - .create_sandbox(&driver_sandbox("sb-net")) + .create_sandbox(&sandbox) .await .expect_err("unmappable policy must fail CreateSandbox synchronously"); assert_eq!(error.code(), tonic::Code::InvalidArgument); diff --git a/crates/openshell-driver-mxc/src/grpc.rs b/crates/openshell-driver-mxc/src/grpc.rs index 9e7dada94f..0fa23f7ac9 100644 --- a/crates/openshell-driver-mxc/src/grpc.rs +++ b/crates/openshell-driver-mxc/src/grpc.rs @@ -56,8 +56,8 @@ impl ComputeDriver for ComputeDriverService { &self, request: Request, ) -> Result, Status> { + let request = request.into_inner(); let sandbox = request - .into_inner() .sandbox .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; self.backend.validate_sandbox_create(&sandbox)?; @@ -99,8 +99,8 @@ impl ComputeDriver for ComputeDriverService { &self, request: Request, ) -> Result, Status> { + let request = request.into_inner(); let sandbox = request - .into_inner() .sandbox .ok_or_else(|| Status::invalid_argument("sandbox is required"))?; self.backend.create_sandbox(&sandbox).await?; diff --git a/crates/openshell-driver-mxc/src/policy.rs b/crates/openshell-driver-mxc/src/policy.rs index 1f26d186e5..a909238851 100644 --- a/crates/openshell-driver-mxc/src/policy.rs +++ b/crates/openshell-driver-mxc/src/policy.rs @@ -78,8 +78,8 @@ fn format_loss(items: &[LossItem]) -> String { /// Translates an `OpenShell` `SandboxPolicy` into an MXC `ContainerConfig` /// fragment, returning a loss report of anything unrepresentable. pub trait PolicyMapper: Send + Sync { - /// `policy` is `None` only when the gateway failed to stage one (the MXC - /// path treats that as a hard error — the demo's whole point is enforcement). + /// `policy` is `None` only when the create request omitted it. The MXC path + /// treats that as a hard error because it cannot launch without enforcement. fn map(&self, policy: Option<&SandboxPolicy>, ctx: &MapCtx) -> Result; } diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md index ccd4413b3f..e53ddc9f3f 100644 --- a/crates/openshell-driver-podman/README.md +++ b/crates/openshell-driver-podman/README.md @@ -457,11 +457,11 @@ matter compared to cluster or rootful runtimes: ## Implementation References -- Gateway integration: `crates/openshell-server/src/compute/mod.rs` - (`new_podman` and `PodmanComputeDriver` wiring). -- Server configuration: `crates/openshell-server/src/lib.rs` - (`ComputeDriverKind::Podman` builds `PodmanComputeConfig` including - `sandbox_ssh_socket_path` from gateway `Config`). +- Gateway integration: `crates/openshell-gateway/src/lib.rs` registers the + driver factory and constructs `PodmanComputeConfig` from the generic server + build context. +- Server configuration: `crates/openshell-server/src/lib.rs` exposes the + backend-agnostic registry and factory context. - Gateway relay path: `openshell-core` `Config::sandbox_ssh_socket_path` in `crates/openshell-core/src/config.rs`. - SSRF mitigation: `crates/openshell-core/src/net.rs`, diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index 8f7c0d32f6..aa41017663 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -311,11 +311,21 @@ fn podman_gpu_selection_error(err: CdiGpuSelectionError) -> ComputeDriverError { ComputeDriverError::Precondition(err.to_string()) } +/// Return the first responsive local Podman API socket. +#[must_use] +pub fn detect_socket() -> Option { + crate::socket_discovery::detect_socket() +} + +#[must_use] +pub fn is_available() -> bool { + detect_socket().is_some() +} + /// Resolve the socket to connect to: explicit configuration wins, otherwise /// fall back to `detect`. Returns an error if neither resolves. /// -/// Takes `detect` as a parameter (rather than calling -/// [`openshell_core::config::detect_podman_socket`] directly) so tests can +/// Takes `detect` as a parameter so tests can /// exercise the precedence deterministically, without touching real /// environment variables or the filesystem. fn resolve_socket_path( @@ -337,10 +347,7 @@ impl PodmanComputeDriver { const MAX_PING_RETRIES: u32 = 5; const PING_RETRY_DELAY: Duration = Duration::from_secs(2); - let socket_path = resolve_socket_path( - config.socket_path.clone(), - openshell_core::config::detect_podman_socket, - )?; + let socket_path = resolve_socket_path(config.socket_path.clone(), detect_socket)?; config.socket_path = Some(socket_path.clone()); if !socket_path.exists() { @@ -508,6 +515,7 @@ impl PodmanComputeDriver { default_image: self.config.default_image.clone(), gateway_manages_lifecycle: true, supports_sandbox_authentication: false, + driver_reports_runtime_readiness: false, }) } diff --git a/crates/openshell-driver-podman/src/lib.rs b/crates/openshell-driver-podman/src/lib.rs index 7a78cf5d92..115e64eb2f 100644 --- a/crates/openshell-driver-podman/src/lib.rs +++ b/crates/openshell-driver-podman/src/lib.rs @@ -7,6 +7,7 @@ pub(crate) mod container; pub mod driver; pub mod grpc; pub mod otel_tracing; +mod socket_discovery; #[cfg(test)] pub(crate) mod test_utils; pub(crate) mod watcher; diff --git a/crates/openshell-driver-podman/src/socket_discovery.rs b/crates/openshell-driver-podman/src/socket_discovery.rs new file mode 100644 index 0000000000..e7a6c79e74 --- /dev/null +++ b/crates/openshell-driver-podman/src/socket_discovery.rs @@ -0,0 +1,402 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Podman socket discovery for local and machine-backed installations. + +use std::path::PathBuf; +use std::process::{Command, Stdio}; +use std::time::{Duration, Instant}; + +const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(5); +const DISCOVERY_POLL_INTERVAL: Duration = Duration::from_millis(25); + +/// Return the first responsive well-known socket, then ask the Podman CLI for +/// the active native or machine-backed connection. +pub fn detect_socket() -> Option { + openshell_core::local_api_socket::first_responsive_socket(&socket_candidates(), |response| { + openshell_core::local_api_socket::http_response_is_success(response) + && openshell_core::local_api_socket::contains_ascii(response, b"Libpod-Api-Version:") + }) + .or_else(discover_socket) +} + +fn socket_candidates() -> Vec { + let mut candidates = Vec::new(); + if let Some(path) = env_var_nonempty("OPENSHELL_PODMAN_SOCKET") { + candidates.push(PathBuf::from(path)); + } + if let Some(runtime_dir) = std::env::var_os("XDG_RUNTIME_DIR") { + candidates.push(PathBuf::from(runtime_dir).join("podman/podman.sock")); + } + #[cfg(target_os = "linux")] + candidates.push(PathBuf::from(format!( + "/run/user/{}/podman/podman.sock", + rustix::process::geteuid().as_raw() + ))); + if let Some(home) = std::env::var_os("HOME") { + candidates + .push(PathBuf::from(home).join(".local/share/containers/podman/machine/podman.sock")); + } + candidates +} + +/// Query the same active connection selected by the Podman CLI. This covers +/// named/rootful machines and provider-specific forwarded socket locations that +/// do not have a stable well-known path. +fn discover_socket() -> Option { + let stdout = run_podman_capture(&["info", "--format", "json"])?; + + // A successful `podman info` proves this explicit socket is usable. A named + // connection has higher precedence, so only honor CONTAINER_HOST directly + // when no CONTAINER_CONNECTION is set. + if env_var_nonempty("CONTAINER_CONNECTION").is_none() + && let Some(path) = env_var_nonempty("CONTAINER_HOST") + .as_deref() + .and_then(unix_url_socket_path) + { + return Some(path); + } + + let info: serde_json::Value = serde_json::from_slice(&stdout).ok()?; + if !info["host"]["serviceIsRemote"].as_bool().unwrap_or(false) { + return parse_info_socket(&info); + } + + discover_machine_socket() +} + +fn discover_machine_socket() -> Option { + let connections = connection_list(); + let active = active_machine( + env_var_nonempty("CONTAINER_CONNECTION").as_deref(), + env_var_nonempty("CONTAINER_HOST").as_deref(), + connections.as_ref(), + )?; + machine_inspect_targets(&active) + .into_iter() + .find_map(|name| { + let stdout = run_podman_capture(&["machine", "inspect", &name])?; + let machines: serde_json::Value = serde_json::from_slice(&stdout).ok()?; + parse_machine_socket(&machines) + }) +} + +fn active_machine( + container_connection: Option<&str>, + container_host: Option<&str>, + connections: Option<&serde_json::Value>, +) -> Option { + if let Some(name) = container_connection.filter(|name| !name.trim().is_empty()) { + return Some(name.to_string()); + } + if let Some(host) = container_host.filter(|host| !host.trim().is_empty()) { + // An explicit non-machine endpoint must not fall back to an unrelated + // local machine. + return connection_name_for_uri(connections?, host); + } + default_machine_connection(connections).or_else(|| Some("podman-machine-default".to_string())) +} + +fn machine_inspect_targets(connection: &str) -> Vec { + let mut names = vec![connection.to_string()]; + if let Some(machine) = connection.strip_suffix("-root") + && !machine.is_empty() + { + names.push(machine.to_string()); + } + names +} + +fn connection_list() -> Option { + let stdout = run_podman_capture(&["system", "connection", "list", "--format", "json"])?; + serde_json::from_slice(&stdout).ok() +} + +fn default_machine_connection(connections: Option<&serde_json::Value>) -> Option { + connections? + .as_array()? + .iter() + .find(|connection| { + connection["Default"].as_bool().unwrap_or(false) + && connection["IsMachine"].as_bool().unwrap_or(false) + }) + .and_then(|connection| connection["Name"].as_str()) + .map(str::to_string) +} + +fn connection_name_for_uri(connections: &serde_json::Value, uri: &str) -> Option { + connections + .as_array()? + .iter() + .find(|connection| { + connection["IsMachine"].as_bool().unwrap_or(false) + && connection["URI"].as_str() == Some(uri) + }) + .and_then(|connection| connection["Name"].as_str()) + .map(str::to_string) +} + +fn parse_info_socket(info: &serde_json::Value) -> Option { + let path = info["host"]["remoteSocket"]["path"].as_str()?; + unix_url_socket_path(path).or_else(|| (!path.is_empty()).then(|| PathBuf::from(path))) +} + +fn parse_machine_socket(machines: &serde_json::Value) -> Option { + let path = machines.as_array()?.first()?["ConnectionInfo"]["PodmanSocket"]["Path"].as_str()?; + (!path.is_empty()).then(|| PathBuf::from(path)) +} + +fn unix_url_socket_path(url: &str) -> Option { + let path = url.trim().strip_prefix("unix://")?; + (!path.is_empty()).then(|| PathBuf::from(path)) +} + +fn env_var_nonempty(key: &str) -> Option { + std::env::var(key) + .ok() + .filter(|value| !value.trim().is_empty()) +} + +fn run_podman_capture(args: &[&str]) -> Option> { + run_bounded_command("podman", args, DISCOVERY_TIMEOUT) +} + +/// Capture stdout without allowing a stalled Podman machine, SSH transport, or +/// descendant holding the stdout pipe open to block gateway startup forever. +fn run_bounded_command(program: &str, args: &[&str], timeout: Duration) -> Option> { + use std::io::Read as _; + use std::sync::mpsc; + + let mut command = Command::new(program); + command + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + set_new_process_group(&mut command); + let mut child = command.spawn().ok()?; + + let mut stdout = child.stdout.take()?; + let (sender, receiver) = mpsc::channel(); + std::thread::spawn(move || { + let mut output = Vec::new(); + let _ = stdout.read_to_end(&mut output); + let _ = sender.send(output); + }); + + let deadline = Instant::now() + timeout; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) if Instant::now() < deadline => { + std::thread::sleep(DISCOVERY_POLL_INTERVAL); + } + Ok(None) | Err(_) => break None, + } + }; + + let Some(status) = status else { + terminate_process_group(&mut child); + let _ = child.wait(); + return None; + }; + + match receiver.recv_timeout(deadline.saturating_duration_since(Instant::now())) { + Ok(output) if status.success() => Some(output), + Ok(_) => None, + Err(_) => { + terminate_process_group(&mut child); + None + } + } +} + +#[cfg(unix)] +fn set_new_process_group(command: &mut Command) { + use std::os::unix::process::CommandExt as _; + command.process_group(0); +} + +#[cfg(not(unix))] +fn set_new_process_group(_command: &mut Command) {} + +#[cfg(unix)] +fn terminate_process_group(child: &mut std::process::Child) { + let pid = i32::try_from(child.id()).unwrap_or(i32::MAX); + let group = nix::unistd::Pid::from_raw(-pid); + let _ = nix::sys::signal::kill(group, nix::sys::signal::Signal::SIGKILL); + let _ = child.kill(); +} + +#[cfg(not(unix))] +fn terminate_process_group(child: &mut std::process::Child) { + let _ = child.kill(); +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn parse_info_socket_rejects_missing_or_empty_paths() { + assert_eq!( + parse_info_socket(&json!({"host": {"remoteSocket": {}}})), + None + ); + assert_eq!( + parse_info_socket(&json!({"host": {"remoteSocket": {"path": ""}}})), + None + ); + } + + #[test] + fn parse_machine_socket_rejects_missing_socket_or_machine() { + assert_eq!(parse_machine_socket(&json!([])), None); + assert_eq!(parse_machine_socket(&json!([{"ConnectionInfo": {}}])), None); + } + + #[test] + fn parses_native_and_machine_socket_paths() { + let info = json!({"host": {"remoteSocket": {"path": "unix:///run/user/1000/podman.sock"}}}); + assert_eq!( + parse_info_socket(&info), + Some(PathBuf::from("/run/user/1000/podman.sock")) + ); + + let machine = json!([{"ConnectionInfo": {"PodmanSocket": {"Path": "/tmp/machine.sock"}}}]); + assert_eq!( + parse_machine_socket(&machine), + Some(PathBuf::from("/tmp/machine.sock")) + ); + } + + #[test] + fn resolves_named_rootful_and_default_machine_connections() { + let connections = json!([ + {"Name": "team-machine-root", "URI": "ssh://team", "Default": true, "IsMachine": true}, + {"Name": "remote", "URI": "ssh://remote", "Default": false, "IsMachine": false} + ]); + assert_eq!( + active_machine(Some("team-machine-root"), None, Some(&connections)), + Some("team-machine-root".to_string()) + ); + assert_eq!( + machine_inspect_targets("team-machine-root"), + ["team-machine-root", "team-machine"] + ); + assert_eq!( + active_machine(None, None, Some(&connections)), + Some("team-machine-root".to_string()) + ); + } + + #[test] + fn explicit_non_machine_endpoint_does_not_guess_a_machine() { + let connections = json!([ + {"Name": "local", "URI": "ssh://local", "Default": true, "IsMachine": true}, + {"Name": "remote", "URI": "ssh://remote", "Default": false, "IsMachine": false} + ]); + assert_eq!( + active_machine(None, Some("ssh://remote"), Some(&connections)), + None + ); + } + + #[test] + fn container_host_maps_to_the_matching_machine_connection() { + let connections = json!([ + {"Name": "work", "URI": "ssh://core@127.0.0.1:5555/run/podman.sock", "Default": false, "IsMachine": true}, + {"Name": "podman-machine-default", "URI": "ssh://core@127.0.0.1:4444/run/podman.sock", "Default": true, "IsMachine": true} + ]); + assert_eq!( + active_machine( + None, + Some("ssh://core@127.0.0.1:5555/run/podman.sock"), + Some(&connections), + ), + Some("work".to_string()) + ); + } + + #[test] + fn unix_url_socket_path_only_accepts_nonempty_unix_urls() { + assert_eq!( + unix_url_socket_path("unix:///run/user/1000/podman.sock"), + Some(PathBuf::from("/run/user/1000/podman.sock")) + ); + assert_eq!(unix_url_socket_path("ssh://core@127.0.0.1/x"), None); + assert_eq!(unix_url_socket_path("tcp://127.0.0.1:2375"), None); + assert_eq!(unix_url_socket_path("unix://"), None); + } + + #[cfg(unix)] + #[test] + fn bounded_command_captures_stdout_on_success() { + assert_eq!( + run_bounded_command("printf", &["hello"], Duration::from_secs(5)), + Some(b"hello".to_vec()) + ); + } + + #[cfg(unix)] + #[test] + fn bounded_command_returns_none_on_nonzero_exit_or_missing_program() { + assert_eq!( + run_bounded_command("false", &[], Duration::from_secs(5)), + None + ); + assert_eq!( + run_bounded_command( + "openshell-nonexistent-binary-xyz", + &[], + Duration::from_secs(5), + ), + None + ); + } + + #[cfg(unix)] + #[test] + fn bounded_command_kills_child_that_exceeds_deadline() { + let start = Instant::now(); + let result = run_bounded_command("sleep", &["30"], Duration::from_millis(200)); + assert_eq!(result, None); + assert!( + start.elapsed() < Duration::from_secs(5), + "bounded command did not return promptly" + ); + } + + #[cfg(unix)] + #[test] + fn bounded_command_bounds_drain_when_in_group_descendant_holds_stdout() { + let start = Instant::now(); + let result = run_bounded_command( + "sh", + &["-c", "sleep 30 & echo done"], + Duration::from_millis(300), + ); + assert_eq!(result, None); + assert!( + start.elapsed() < Duration::from_secs(2), + "drain blocked on a descendant holding stdout" + ); + } + + #[cfg(unix)] + #[test] + fn bounded_command_bounds_drain_when_descendant_escapes_process_group() { + let start = Instant::now(); + let result = run_bounded_command( + "bash", + &["-c", "set -m; sleep 5 & echo done"], + Duration::from_millis(300), + ); + assert_eq!(result, None); + assert!( + start.elapsed() < Duration::from_secs(2), + "drain blocked on a descendant that escaped the process group" + ); + } +} diff --git a/crates/openshell-driver-podman/src/watcher.rs b/crates/openshell-driver-podman/src/watcher.rs index 0c94bf72b2..c3903a0067 100644 --- a/crates/openshell-driver-podman/src/watcher.rs +++ b/crates/openshell-driver-podman/src/watcher.rs @@ -122,15 +122,12 @@ fn deleted_event(sandbox_id: String) -> WatchSandboxesEvent { /// drops (daemon restart, socket error, or clean shutdown), the stream /// terminates with a final error item and stops producing events. /// -/// Callers are responsible for reconnecting by calling [`start_watch`] again. -/// The server's `ComputeRuntime::watch_loop` in `openshell-server` provides -/// this behaviour with a 2-second backoff: when the stream terminates with an -/// error, `watch_loop` sleeps and then calls `watch_sandboxes()` again, which -/// ultimately calls `start_watch()` again and re-syncs state. +/// Callers are responsible for reconnecting by calling [`start_watch`] again +/// and re-synchronizing state. /// /// **Do not add reconnection logic inside this function.** A local reconnect -/// would race with `watch_loop`'s retry and produce duplicate initial-sync -/// events that corrupt the server's sandbox index. +/// would race with the consumer's retry and produce duplicate initial-sync +/// events. pub async fn start_watch( client: PodmanClient, lifecycle_event_fences: LifecycleEventFences, diff --git a/crates/openshell-driver-vm/Cargo.toml b/crates/openshell-driver-vm/Cargo.toml index ebcb9d2bc2..0d250b6e71 100644 --- a/crates/openshell-driver-vm/Cargo.toml +++ b/crates/openshell-driver-vm/Cargo.toml @@ -22,6 +22,7 @@ path = "src/main.rs" openshell-core = { path = "../openshell-core", default-features = false } openshell-otel = { path = "../openshell-otel" } openshell-policy = { path = "../openshell-policy" } +openshell-driver-podman = { path = "../openshell-driver-podman" } openshell-vfio = { path = "../openshell-vfio" } bollard = { version = "0.20", features = ["ssh"] } @@ -59,6 +60,15 @@ default = ["telemetry"] ## default; build with `--no-default-features` for a telemetry-free VM driver ## that reports telemetry disabled to the sandboxes it launches. telemetry = ["openshell-core/telemetry"] +## Convenience alias: every default feature except `telemetry`. Build a +## telemetry-free VM driver with +## `--no-default-features --features defaults-without-telemetry` and stay +## correct as new default features are added. Cargo cannot subtract a single +## default feature, so this alias must be paired with `--no-default-features`; +## enabling it alongside `telemetry` is a compile error rather than a silent +## telemetry-on build. Kept in sync with `default` by +## `rust:verify:defaults-without-telemetry`. +defaults-without-telemetry = [] [dev-dependencies] openshell-otel-test-support = { path = "../openshell-otel-test-support" } diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md index f455beaeb5..4fc9ace415 100644 --- a/crates/openshell-driver-vm/README.md +++ b/crates/openshell-driver-vm/README.md @@ -9,7 +9,7 @@ Standalone libkrun-backed [`ComputeDriver`](../../proto/compute_driver.proto) fo ```mermaid flowchart LR subgraph host["Host process"] - gateway["openshell-server
(compute::vm::spawn)"] + gateway["openshell-gateway
(vm::spawn)"] driver["openshell-driver-vm
├── libkrun (VM)
├── gvproxy (net)
└── openshell-sandbox.zst"] gateway <-->|"gRPC over UDS
compute-driver.sock"| driver end @@ -102,7 +102,7 @@ mise run vm:supervisor # if openshell-sandbox.zst is not already presen # 2. Build both binaries with the staged artifacts embedded OPENSHELL_VM_RUNTIME_COMPRESSED_DIR=$PWD/target/vm-runtime-compressed \ - cargo build -p openshell-server -p openshell-driver-vm + cargo build -p openshell-gateway -p openshell-driver-vm # 3. macOS only: codesign the driver for Hypervisor.framework codesign \ @@ -291,5 +291,5 @@ the user explicitly overrides it. ## TODOs -- The gateway still configures the driver via CLI args; this will move to a gRPC bootstrap call so the driver interface is uniform across backends. See the `TODO(driver-abstraction)` notes in `crates/openshell-server/src/lib.rs` and `crates/openshell-server/src/compute/vm.rs`. +- The gateway still configures the driver via CLI args; this will move to a gRPC bootstrap call so the driver interface is uniform across backends. See the `TODO(driver-abstraction)` note in `crates/openshell-gateway/src/vm.rs`. - macOS local builds are codesigned by `tasks/scripts/gateway-vm.sh`; the generated Homebrew formula signs the release tarball driver for local installs. diff --git a/crates/openshell-driver-vm/runtime/README.md b/crates/openshell-driver-vm/runtime/README.md index 11aab67f43..b686874ba2 100644 --- a/crates/openshell-driver-vm/runtime/README.md +++ b/crates/openshell-driver-vm/runtime/README.md @@ -41,7 +41,7 @@ mise run vm:supervisor # Build the gateway and VM driver with embedded runtime artifacts OPENSHELL_VM_RUNTIME_COMPRESSED_DIR=$PWD/target/vm-runtime-compressed \ - cargo build -p openshell-server -p openshell-driver-vm + cargo build -p openshell-gateway -p openshell-driver-vm ``` Use `FROM_SOURCE=1 mise run vm:setup` to build the runtime from source instead diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index 2de65c3add..8adcc79f92 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -525,6 +525,7 @@ impl VmDriver { default_image: self.config.default_image.clone(), gateway_manages_lifecycle: true, supports_sandbox_authentication: false, + driver_reports_runtime_readiness: false, } } @@ -3663,7 +3664,7 @@ async fn connect_local_container_engine() -> Option { return Some(docker); } - let podman_socket = openshell_core::config::detect_podman_socket()?; + let podman_socket = detect_podman_socket()?; if let Ok(docker) = Docker::connect_with_unix(podman_socket.to_str()?, 120, bollard::API_DEFAULT_VERSION) && docker.ping().await.is_ok() @@ -3678,6 +3679,10 @@ async fn connect_local_container_engine() -> Option { None } +fn detect_podman_socket() -> Option { + openshell_driver_podman::driver::detect_socket() +} + fn is_openshell_local_build_image_ref(image_ref: &str) -> bool { image_ref.starts_with("openshell/sandbox-from:") } diff --git a/crates/openshell-driver-vm/src/lib.rs b/crates/openshell-driver-vm/src/lib.rs index 98ba6b0c9a..f34c7dda8d 100644 --- a/crates/openshell-driver-vm/src/lib.rs +++ b/crates/openshell-driver-vm/src/lib.rs @@ -1,6 +1,16 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +// `defaults-without-telemetry` is an alias for the default feature set minus +// `telemetry`, not a switch that turns telemetry off. Cargo cannot subtract a +// default feature, so adding it on top of the defaults would otherwise produce +// a telemetry-on build that reads as telemetry-free. Fail the build instead. +#[cfg(all(feature = "telemetry", feature = "defaults-without-telemetry"))] +compile_error!( + "features `telemetry` and `defaults-without-telemetry` are mutually exclusive; \ + build a telemetry-free VM driver with `--no-default-features --features defaults-without-telemetry`" +); + pub mod driver; mod embedded_runtime; mod ffi; diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index b0d6b0f53d..d7ea5a241c 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -317,6 +317,7 @@ mod tests { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }; let bytes = request.encode_to_vec(); let json = codec diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index 02afddab75..cd0f59ea3c 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -1076,6 +1076,7 @@ mod tests { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }; let bytes = request.encode_to_vec(); diff --git a/crates/openshell-gateway/Cargo.toml b/crates/openshell-gateway/Cargo.toml new file mode 100644 index 0000000000..f9d02027e0 --- /dev/null +++ b/crates/openshell-gateway/Cargo.toml @@ -0,0 +1,72 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-gateway" +description = "OpenShell gateway binary composition" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[[bin]] +name = "openshell-gateway" +path = "src/main.rs" + +[dependencies] +openshell-core = { path = "../openshell-core", default-features = false } +openshell-server = { path = "../openshell-server", default-features = false } +openshell-otel = { path = "../openshell-otel", optional = true } +async-trait = "0.1" +miette = { workspace = true } +tokio = { workspace = true } + +[target.'cfg(not(target_os = "windows"))'.dependencies] +openshell-driver-docker = { path = "../openshell-driver-docker", optional = true } +openshell-driver-kubernetes = { path = "../openshell-driver-kubernetes", optional = true } +openshell-driver-podman = { path = "../openshell-driver-podman", optional = true } +hyper-util = { workspace = true, optional = true } +nix = { workspace = true, optional = true } +serde = { workspace = true, optional = true } +rustix = { workspace = true, optional = true } +tonic = { workspace = true, optional = true } +tower = { workspace = true, optional = true } +tracing = { workspace = true, optional = true } + +[target.'cfg(target_os = "windows")'.dependencies] +openshell-driver-mxc = { path = "../openshell-driver-mxc", optional = true } + +[features] +default = ["telemetry", "in-tree-compute-drivers"] +in-tree-compute-drivers = [ + "dep:openshell-driver-docker", + "dep:openshell-driver-kubernetes", + "dep:openshell-driver-podman", + "dep:openshell-otel", + "dep:hyper-util", + "dep:nix", + "dep:serde", + "dep:rustix", + "dep:tonic", + "dep:tower", + "dep:tracing", + "dep:openshell-driver-mxc", +] +telemetry = ["openshell-core/telemetry", "openshell-server/telemetry"] +## Convenience alias: every default feature except `telemetry`. Build a +## telemetry-free gateway with +## `--no-default-features --features defaults-without-telemetry` and stay +## correct as new default features are added. Cargo cannot subtract a single +## default feature, so this alias must be paired with `--no-default-features`; +## enabling it alongside `telemetry` is a compile error rather than a silent +## telemetry-on build. Kept in sync with `default` by +## `rust:verify:defaults-without-telemetry`. +defaults-without-telemetry = ["in-tree-compute-drivers"] +bundled-z3 = ["openshell-server/bundled-z3"] + +[lints] +workspace = true + +[dev-dependencies] +tempfile = "3" diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs new file mode 100644 index 0000000000..c5a7ebe0e7 --- /dev/null +++ b/crates/openshell-gateway/src/lib.rs @@ -0,0 +1,452 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Standard gateway binary composition. +//! +//! The server remains backend-agnostic. This crate is the composition boundary +//! that links first-party compute drivers into the distributed gateway binary. + +// `defaults-without-telemetry` is an alias for the default feature set minus +// `telemetry`, not a switch that turns telemetry off. Cargo cannot subtract a +// default feature, so adding it on top of the defaults would otherwise produce +// a telemetry-on build that reads as telemetry-free. Fail the build instead. +#[cfg(all(feature = "telemetry", feature = "defaults-without-telemetry"))] +compile_error!( + "features `telemetry` and `defaults-without-telemetry` are mutually exclusive; \ + build a telemetry-free gateway with `--no-default-features --features defaults-without-telemetry`" +); + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +mod vm; + +#[cfg(feature = "in-tree-compute-drivers")] +use openshell_core::telemetry::TelemetryComputeDriver; +#[cfg(feature = "in-tree-compute-drivers")] +use openshell_server::ComputeDriverRegistration; +use openshell_server::ComputeDriverRegistry; + +/// Install every first-party compute driver linked into the standard gateway. +#[must_use] +pub fn install_default_compute_drivers() -> ComputeDriverRegistry { + #[allow(unused_mut)] + let mut registry = ComputeDriverRegistry::new(); + #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] + install_in_tree_compute_drivers(&mut registry); + #[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] + install_mxc_compute_driver(&mut registry); + registry +} + +#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +fn install_mxc_compute_driver(registry: &mut ComputeDriverRegistry) { + let registration = ComputeDriverRegistration::new("mxc", u16::MAX, None, MxcFactory) + .expect("first-party driver name is valid") + .with_telemetry_category(TelemetryComputeDriver::anonymous_category("mxc")) + .with_local_singleplayer(); + registry + .install(registration) + .expect("first-party driver names are unique"); + + for name in ["docker", "kubernetes", "podman", "vm"] { + let registration = ComputeDriverRegistration::new( + name, + u16::MAX, + None, + UnsupportedWindowsFactory { name }, + ) + .expect("first-party driver name is valid"); + registry + .install(registration) + .expect("first-party driver names are unique"); + } +} + +#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[derive(Clone, Copy)] +struct UnsupportedWindowsFactory { + name: &'static str, +} + +#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[async_trait::async_trait] +impl openshell_server::ComputeDriverFactory for UnsupportedWindowsFactory { + async fn build( + &self, + _context: openshell_server::ComputeDriverBuildContext<'_>, + ) -> openshell_core::Result { + Err(unsupported_windows_compute_driver(self.name)) + } +} + +#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +fn unsupported_windows_compute_driver(name: &str) -> openshell_core::Error { + openshell_core::Error::config(format!("compute driver '{name}' is unsupported on Windows")) +} + +#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[derive(Clone, Copy)] +struct MxcFactory; + +#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] +#[async_trait::async_trait] +impl openshell_server::ComputeDriverFactory for MxcFactory { + async fn build( + &self, + context: openshell_server::ComputeDriverBuildContext<'_>, + ) -> openshell_core::Result { + let config: openshell_driver_mxc::MxcComputeConfig = context.driver_config()?; + let backend = openshell_driver_mxc::MxcComputeBackend::new(config); + let driver = openshell_driver_mxc::ComputeDriverService::new(backend); + Ok(openshell_server::ComputeDriverInstance::InProcess( + std::sync::Arc::new(driver), + )) + } +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { + for registration in [ + ComputeDriverRegistration::new( + "kubernetes", + 100, + Some(|| std::env::var_os("KUBERNETES_SERVICE_HOST").is_some()), + KubernetesFactory, + ) + .map(|registration| { + registration + .with_telemetry_category(TelemetryComputeDriver::anonymous_category("kubernetes")) + .without_mtls_user_auth() + .with_tracing_setup(kubernetes_tracing_setup) + .with_inherited_config_keys(&[ + "namespace", + "default_image", + "supervisor_image", + "client_tls_secret_name", + "service_account_name", + "host_gateway_ip", + "enable_user_namespaces", + "sa_token_ttl_secs", + ]) + }), + ComputeDriverRegistration::new( + "podman", + 200, + Some(openshell_driver_podman::driver::is_available), + PodmanFactory, + ) + .map(|registration| { + registration + .with_telemetry_category(TelemetryComputeDriver::anonymous_category("podman")) + .with_local_singleplayer() + .with_tracing_setup(podman_tracing_setup) + .with_inherited_config_keys(&[ + "default_image", + "supervisor_image", + "host_gateway_ip", + "guest_tls_ca", + "guest_tls_cert", + "guest_tls_key", + ]) + }), + ComputeDriverRegistration::new( + "docker", + 300, + Some(openshell_driver_docker::is_available), + DockerFactory, + ) + .map(|registration| { + registration + .with_telemetry_category(TelemetryComputeDriver::anonymous_category("docker")) + .with_local_singleplayer() + .with_tracing_setup(docker_tracing_setup) + .with_inherited_config_keys(&[ + "sandbox_namespace", + "default_image", + "supervisor_image", + "host_gateway_ip", + "guest_tls_ca", + "guest_tls_cert", + "guest_tls_key", + ]) + }), + ComputeDriverRegistration::new("vm", u16::MAX, None, VmFactory).map(|registration| { + registration + .with_telemetry_category(TelemetryComputeDriver::anonymous_category("vm")) + .with_local_singleplayer() + .with_inherited_config_keys(&[ + "default_image", + "guest_tls_ca", + "guest_tls_cert", + "guest_tls_key", + ]) + }), + ] { + registry + .install(registration.expect("first-party driver name is valid")) + .expect("first-party driver names are unique"); + } +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +fn kubernetes_tracing_setup( + otlp_endpoint: Option<&str>, + gateway_name: Option<&str>, +) -> openshell_server::ComputeDriverTracingSetup { + let (provider, error) = + openshell_driver_kubernetes::otel_tracing::provider_for(otlp_endpoint, gateway_name); + let layer = provider.as_ref().map(|provider| { + let layer: openshell_server::ComputeDriverTracingLayer = Box::new( + openshell_driver_kubernetes::otel_tracing::in_process_layer(provider), + ); + layer + }); + let shutdown = provider.map(|provider| { + let shutdown: openshell_server::ComputeDriverTracingShutdown = + Box::new(move || provider.shutdown().map_err(|error| error.to_string())); + shutdown + }); + openshell_server::ComputeDriverTracingSetup::new( + layer, + shutdown, + error.map(|error| error.to_string()), + Some(openshell_driver_kubernetes::otel_tracing::IN_PROCESS_TARGET_PREFIX), + ) +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +fn podman_tracing_setup( + otlp_endpoint: Option<&str>, + gateway_name: Option<&str>, +) -> openshell_server::ComputeDriverTracingSetup { + let (provider, error) = + openshell_driver_podman::otel_tracing::provider_for(otlp_endpoint, gateway_name); + let layer = provider.as_ref().map(|provider| { + let layer: openshell_server::ComputeDriverTracingLayer = Box::new( + openshell_driver_podman::otel_tracing::in_process_layer(provider), + ); + layer + }); + let shutdown = provider.map(|provider| { + let shutdown: openshell_server::ComputeDriverTracingShutdown = + Box::new(move || provider.shutdown().map_err(|error| error.to_string())); + shutdown + }); + openshell_server::ComputeDriverTracingSetup::new( + layer, + shutdown, + error.map(|error| error.to_string()), + Some(openshell_driver_podman::otel_tracing::IN_PROCESS_TARGET_PREFIX), + ) +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +fn docker_tracing_setup( + otlp_endpoint: Option<&str>, + gateway_name: Option<&str>, +) -> openshell_server::ComputeDriverTracingSetup { + let (provider, error) = + openshell_driver_docker::otel_tracing::provider_for(otlp_endpoint, gateway_name); + let layer = provider.as_ref().map(|provider| { + let layer: openshell_server::ComputeDriverTracingLayer = Box::new( + openshell_driver_docker::otel_tracing::in_process_layer(provider), + ); + layer + }); + let shutdown = provider.map(|provider| { + let shutdown: openshell_server::ComputeDriverTracingShutdown = + Box::new(move || provider.shutdown().map_err(|error| error.to_string())); + shutdown + }); + openshell_server::ComputeDriverTracingSetup::new( + layer, + shutdown, + error.map(|error| error.to_string()), + Some(openshell_driver_docker::otel_tracing::IN_PROCESS_TARGET_PREFIX), + ) +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[derive(Clone, Copy)] +struct KubernetesFactory; + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[async_trait::async_trait] +impl openshell_server::ComputeDriverFactory for KubernetesFactory { + async fn build( + &self, + context: openshell_server::ComputeDriverBuildContext<'_>, + ) -> openshell_core::Result { + let mut config: openshell_driver_kubernetes::KubernetesComputeConfig = + context.driver_config()?; + if let Ok(size) = std::env::var("OPENSHELL_K8S_WORKSPACE_DEFAULT_STORAGE_SIZE") { + config.workspace_default_storage_size = size; + } + if let Ok(storage_class) = std::env::var("OPENSHELL_K8S_WORKSPACE_STORAGE_CLASS") { + config.workspace_storage_class = storage_class; + } + let driver = openshell_driver_kubernetes::KubernetesComputeDriver::new( + config, + context.shutdown_receiver(), + ) + .await + .map_err(|error| openshell_core::Error::execution(error.to_string()))?; + let driver = openshell_driver_kubernetes::ComputeDriverService::new_in_process(driver); + Ok(openshell_server::ComputeDriverInstance::InProcess( + std::sync::Arc::new(driver), + )) + } +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[derive(Clone, Copy)] +struct DockerFactory; + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[async_trait::async_trait] +impl openshell_server::ComputeDriverFactory for DockerFactory { + async fn build( + &self, + context: openshell_server::ComputeDriverBuildContext<'_>, + ) -> openshell_core::Result { + let mut config: openshell_driver_docker::DockerComputeConfig = context.driver_config()?; + apply_guest_tls( + &mut config.guest_tls_ca, + &mut config.guest_tls_cert, + &mut config.guest_tls_key, + context.guest_tls_paths(), + ); + let driver = openshell_driver_docker::DockerComputeDriver::new( + context.gateway_bind_address(), + context.gateway_log_level(), + &config, + ) + .await + .map_err(|error| openshell_core::Error::execution(error.to_string()))?; + let driver = openshell_driver_docker::ComputeDriverService::new_in_process(driver); + Ok(openshell_server::ComputeDriverInstance::InProcess( + std::sync::Arc::new(driver), + )) + } +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[derive(Clone, Copy)] +struct PodmanFactory; + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[async_trait::async_trait] +impl openshell_server::ComputeDriverFactory for PodmanFactory { + async fn build( + &self, + context: openshell_server::ComputeDriverBuildContext<'_>, + ) -> openshell_core::Result { + let mut config: openshell_driver_podman::PodmanComputeConfig = context.driver_config()?; + config.gateway_port = context.gateway_port(); + if let Ok(path) = std::env::var("OPENSHELL_PODMAN_SOCKET") { + config.socket_path = Some(path.into()); + } + if let Ok(ip) = std::env::var("OPENSHELL_PODMAN_HOST_GATEWAY_IP") { + config.host_gateway_ip = ip; + } + if let Ok(mode) = std::env::var("OPENSHELL_PODMAN_USERNS") { + config.userns = Some(mode); + } + apply_guest_tls( + &mut config.guest_tls_ca, + &mut config.guest_tls_cert, + &mut config.guest_tls_key, + context.guest_tls_paths(), + ); + let driver = openshell_driver_podman::PodmanComputeDriver::new(config) + .await + .map_err(|error| openshell_core::Error::execution(error.to_string()))?; + let driver = openshell_driver_podman::ComputeDriverService::new_in_process(driver); + Ok(openshell_server::ComputeDriverInstance::InProcess( + std::sync::Arc::new(driver), + )) + } +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[derive(Clone, Copy)] +struct VmFactory; + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +#[async_trait::async_trait] +impl openshell_server::ComputeDriverFactory for VmFactory { + async fn build( + &self, + context: openshell_server::ComputeDriverBuildContext<'_>, + ) -> openshell_core::Result { + let mut config: vm::VmComputeConfig = context.driver_config()?; + if config.state_dir.as_os_str().is_empty() { + config.state_dir = vm::VmComputeConfig::default_state_dir(); + } + if config.grpc_endpoint.trim().is_empty() + && (!context.gateway_tls_enabled() || context.guest_tls_paths().is_some()) + { + let scheme = if context.gateway_tls_enabled() { + "https" + } else { + "http" + }; + config.grpc_endpoint = format!("{scheme}://127.0.0.1:{}", context.gateway_port()); + } + apply_guest_tls( + &mut config.guest_tls_ca, + &mut config.guest_tls_cert, + &mut config.guest_tls_key, + context.guest_tls_paths(), + ); + let endpoint = vm::spawn( + context.gateway_log_level(), + context.gateway_name(), + &config, + context.otlp_config(), + ) + .await?; + Ok(openshell_server::ComputeDriverInstance::ManagedRemote( + endpoint, + )) + } +} + +#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] +fn apply_guest_tls( + ca: &mut Option, + cert: &mut Option, + key: &mut Option, + defaults: Option<(&std::path::Path, &std::path::Path, &std::path::Path)>, +) { + if ca.is_none() + && cert.is_none() + && key.is_none() + && let Some((default_ca, default_cert, default_key)) = defaults + { + *ca = Some(default_ca.to_owned()); + *cert = Some(default_cert.to_owned()); + *key = Some(default_key.to_owned()); + } +} + +#[cfg(all(test, target_os = "windows", feature = "in-tree-compute-drivers"))] +mod windows_tests { + use super::*; + + #[test] + fn windows_builtin_compute_drivers_report_unsupported() { + let registry = install_default_compute_drivers(); + assert_eq!( + registry.installed_driver_names().collect::>(), + ["docker", "kubernetes", "mxc", "podman", "vm"] + ); + + for name in ["docker", "kubernetes", "podman", "vm"] { + let message = unsupported_windows_compute_driver(name).to_string(); + assert!( + message.contains("unsupported on Windows"), + "{name} rejection should be explicit, got: {message}" + ); + } + } +} diff --git a/crates/openshell-server/src/main.rs b/crates/openshell-gateway/src/main.rs similarity index 59% rename from crates/openshell-server/src/main.rs rename to crates/openshell-gateway/src/main.rs index c76761016d..85d0611867 100644 --- a/crates/openshell-server/src/main.rs +++ b/crates/openshell-gateway/src/main.rs @@ -1,14 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! `OpenShell` Gateway binary entrypoint. - -use miette::Result; - #[tokio::main] -async fn main() -> Result<()> { +async fn main() -> miette::Result<()> { openshell_server::cli::run_cli_with_compute_drivers( - openshell_server::install_default_compute_drivers(), + openshell_gateway::install_default_compute_drivers(), ) .await } diff --git a/crates/openshell-server/src/compute/vm.rs b/crates/openshell-gateway/src/vm.rs similarity index 92% rename from crates/openshell-server/src/compute/vm.rs rename to crates/openshell-gateway/src/vm.rs index 6a66fc8aa5..e86de28c12 100644 --- a/crates/openshell-server/src/compute/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -20,28 +20,24 @@ //! [`openshell_core::Config`] so the shared core stays free of driver-specific //! plumbing. //! -//! TODO(driver-abstraction): this module still assumes the concrete VM driver -//! (argv shape, guest-TLS flags, libkrun-specific settings). Once we land the -//! generalized compute-driver interface, the CLI-arg plumbing below should -//! be replaced with a driver-agnostic launcher that speaks gRPC to -//! configure the driver — and this file should collapse to the types that -//! are genuinely VM-specific (libkrun log level, vCPU / memory shape) plus a -//! trait implementation registering the VM driver against the generic -//! interface. - -use super::AcquiredRemoteDriverEndpoint; -#[cfg(unix)] -use super::ManagedDriverProcess; -use crate::config_file::OtlpConfig; -#[cfg(unix)] -use crate::otel_tracing::TraceContextInterceptor; +//! Process launch remains deliberately VM-specific at this binary composition +//! boundary: it translates gateway configuration into the standalone driver's +//! argv and then connects through the same public compute-driver RPC interface +//! used by operator-managed external drivers. + #[cfg(unix)] use hyper_util::rt::TokioIo; #[cfg(unix)] use openshell_core::proto::compute::v1::{ GetCapabilitiesRequest, compute_driver_client::ComputeDriverClient, }; -use openshell_core::{ComputeDriverKind, Config, Error, Result}; +use openshell_core::{Error, Result}; +#[cfg(unix)] +use openshell_otel::TraceContextInterceptor; +use openshell_server::AcquiredRemoteDriverEndpoint; +#[cfg(unix)] +use openshell_server::ManagedDriverProcess; +use openshell_server::config_file::OtlpConfig; #[cfg(unix)] use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; #[cfg(unix)] @@ -453,7 +449,8 @@ pub fn compute_driver_guest_tls_paths( /// kills the subprocess and removes the socket on drop. #[cfg(unix)] pub async fn spawn( - config: &Config, + gateway_log_level: &str, + gateway_name: &str, vm_config: &VmComputeConfig, otlp_config: Option<&OtlpConfig>, ) -> Result { @@ -477,8 +474,8 @@ pub async fn spawn( command .arg("--expected-peer-pid") .arg(std::process::id().to_string()); - command.arg("--log-level").arg(&config.log_level); - append_otlp_args(&mut command, otlp_config, &config.name); + command.arg("--log-level").arg(gateway_log_level); + append_otlp_args(&mut command, otlp_config, gateway_name); command .arg("--openshell-endpoint") .arg(&vm_config.grpc_endpoint); @@ -513,10 +510,8 @@ pub async fn spawn( })?; let channel = wait_for_compute_driver(&socket_path, &mut child).await?; let process = Arc::new(ManagedDriverProcess::new(child, socket_path)); - Ok(AcquiredRemoteDriverEndpoint::managed_builtin( - ComputeDriverKind::Vm, - channel, - process, + Ok(AcquiredRemoteDriverEndpoint::managed( + "vm", channel, process, )) } @@ -530,7 +525,8 @@ fn append_otlp_args(command: &mut Command, otlp_config: Option<&OtlpConfig>, gat #[cfg(not(unix))] pub async fn spawn( - _config: &Config, + _gateway_log_level: &str, + _gateway_name: &str, _vm_config: &VmComputeConfig, _otlp_config: Option<&OtlpConfig>, ) -> Result { @@ -613,9 +609,8 @@ mod tests { VmComputeConfig, append_otlp_args, compute_driver_guest_tls_paths, compute_driver_socket_path, current_euid, prepare_compute_driver_socket_path, prepare_vm_state_dir, resolve_compute_driver_bin, resolve_driver_search_dirs, - wait_for_compute_driver, }; - use crate::config_file::OtlpConfig; + use openshell_server::config_file::OtlpConfig; use std::os::unix::fs::PermissionsExt; use std::os::unix::net::UnixListener as StdUnixListener; use std::path::PathBuf; @@ -649,43 +644,6 @@ mod tests { ); } - #[tokio::test] - async fn readiness_probe_propagates_the_active_trace() { - use crate::otel_tracing::test_exporter; - use crate::test_support::FakeComputeDriver; - - let dir = tempdir().unwrap(); - let socket_path = dir.path().join("compute-driver.sock"); - let driver = FakeComputeDriver::new(); - let _server = driver.serve_uds(&socket_path).unwrap(); - let mut child = tokio::process::Command::new("sh") - .arg("-c") - .arg("read _") - .stdin(std::process::Stdio::piped()) - .kill_on_drop(true) - .spawn() - .unwrap(); - - let traced = test_exporter::install_traced(); - wait_for_compute_driver(&socket_path, &mut child) - .await - .unwrap(); - - let readiness = traced.spans_named("driver.wait_for_ready"); - assert_eq!(readiness.len(), 1, "one readiness operation should finish"); - test_exporter::assert_is_root(&readiness[0]); - let trace_id = readiness[0].span_context.trace_id().to_string(); - assert_eq!( - driver.traceparents().len(), - 1, - "the readiness capability probe should carry trace context" - ); - assert!( - driver.traceparents()[0].contains(&trace_id), - "the readiness probe should be part of the active trace" - ); - } - #[test] fn resolve_driver_bin_uses_driver_dir_when_binary_present() { let dir = tempdir().unwrap(); diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index c653db84dd..3463f03767 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -60,6 +60,17 @@ default = ["telemetry", "bundled-ca-roots"] ## `--no-default-features --features system-ca-roots` to build a supervisor ## that uses the platform trust store with telemetry intact. system-ca-roots = ["telemetry"] +## Convenience alias: every default feature except `telemetry`. Build a +## telemetry-free supervisor with +## `--no-default-features --features defaults-without-telemetry` and stay +## correct as new default features are added. Cargo cannot subtract a single +## default feature, so this alias must be paired with `--no-default-features`; +## enabling it alongside `telemetry` is a compile error rather than a silent +## telemetry-on build. Kept in sync with `default` by +## `rust:verify:defaults-without-telemetry`. Do not pair it with +## `system-ca-roots`, which re-enables `telemetry`; a build with neither +## telemetry nor bundled CA roots is plain `--no-default-features`. +defaults-without-telemetry = ["bundled-ca-roots"] telemetry = ["openshell-core/telemetry"] bundled-ca-roots = ["openshell-supervisor-network/bundled-ca-roots"] diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index e70aac7a9f..41c6ca3c94 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -5,6 +5,16 @@ //! //! This crate provides process sandboxing and monitoring capabilities. +// `defaults-without-telemetry` is an alias for the default feature set minus +// `telemetry`, not a switch that turns telemetry off. Cargo cannot subtract a +// default feature, so adding it on top of the defaults would otherwise produce +// a telemetry-on build that reads as telemetry-free. Fail the build instead. +#[cfg(all(feature = "telemetry", feature = "defaults-without-telemetry"))] +compile_error!( + "features `telemetry` and `defaults-without-telemetry` are mutually exclusive; \ + build a telemetry-free supervisor with `--no-default-features --features defaults-without-telemetry`" +); + mod activity_aggregator; mod denial_aggregator; #[cfg_attr(not(target_os = "linux"), allow(dead_code))] diff --git a/crates/openshell-sdk/README.md b/crates/openshell-sdk/README.md index 93afc5359e..cb42e12dc1 100644 --- a/crates/openshell-sdk/README.md +++ b/crates/openshell-sdk/README.md @@ -9,7 +9,8 @@ gateway-name resolution. ## Two layers - `OpenShellClient` — the curated, sandbox-focused surface: health, sandbox - CRUD, readiness/deletion waits, and non-streaming exec. + CRUD, reusable sandbox template CRUD, readiness/deletion waits, and + non-streaming exec. - `raw` — direct access to the generated tonic clients for RPCs the curated surface doesn't yet cover (inference, providers, policy, logs, settings, SSH, forwarding). @@ -44,10 +45,53 @@ mTLS (client certificates) is not supported. `OpenShellClient::connect(ClientConfig)` returns a connected client exposing `health`, `create_sandbox`, `get_sandbox`, `list_sandboxes`, `delete_sandbox`, +`create_sandbox_from_template`, `create_sandbox_template`, +`get_sandbox_template`, `list_sandbox_templates`, `delete_sandbox_template`, `wait_ready`, `wait_deleted`, and `exec`. Curated types (`SandboxSpec`, -`SandboxRef`, `Health`, `ListOptions`, `ExecOptions`, `SandboxPhase`) use -SDK-shaped enums rather than raw proto integers. Failures map to a typed -`SdkError` with a discriminable kind. +`SandboxRef`, `Health`, `ListOptions`, `SandboxTemplateListOptions`, +`ExecOptions`, `SandboxPhase`) use SDK-shaped enums rather than raw proto +integers where practical. Reusable template resources are exposed as +`SandboxWorkloadTemplate` proto aliases so callers can populate the full +portable workload shape and driver config. Failures map to a typed `SdkError` +with a discriminable kind. + +```rust +use openshell_sdk::{ + ClientConfig, OpenShellClient, SandboxTemplateCreateSpec, + SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateSpec, +}; + +# async fn run() -> Result<(), openshell_sdk::SdkError> { +let client = OpenShellClient::connect(ClientConfig::new("http://127.0.0.1:8080")).await?; +client + .create_sandbox_template(SandboxWorkloadTemplate { + metadata: Some(openshell_sdk::raw::proto::datamodel::v1::ObjectMeta { + name: "python".to_string(), + ..Default::default() + }), + spec: Some(SandboxWorkloadTemplateSpec { + workload: Some(SandboxWorkloadConfig { + image: "ghcr.io/nvidia/openshell-community/sandboxes/python:latest".to_string(), + ..Default::default() + }), + ..Default::default() + }), + }) + .await?; + +let _sandbox = client + .create_sandbox_from_template(SandboxTemplateCreateSpec { + template_name: "python".to_string(), + policy: Some(openshell_sdk::raw::proto::SandboxPolicy { + version: 1, + ..Default::default() + }), + ..Default::default() + }) + .await?; +# Ok(()) +# } +``` ## Modules diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index a02b5735ae..b5486812f7 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -16,7 +16,7 @@ use crate::refresh::{RefreshedToken, TokenSource}; use crate::transport; use crate::types::{ ExecOptions, ExecResult, Health, ListOptions, SandboxPhase, SandboxRef, SandboxSpec, - WorkspaceRef, + SandboxTemplateCreateSpec, SandboxTemplateListOptions, SandboxWorkloadTemplate, WorkspaceRef, }; use futures::StreamExt; use openshell_core::proto; @@ -163,6 +163,86 @@ impl OpenShellClient { sandbox_from_response(response.sandbox) } + /// Create a new sandbox from a workspace-scoped workload template name. + pub async fn create_sandbox_from_template( + &self, + spec: SandboxTemplateCreateSpec, + ) -> Result { + let request = create_sandbox_from_template_request(spec); + let response = self + .unary(|mut grpc| { + let request = request.clone(); + async move { grpc.create_sandbox(request).await } + }) + .await?; + sandbox_from_response(response.sandbox) + } + + /// Create a reusable sandbox template in the default workspace. + pub async fn create_sandbox_template( + &self, + template: SandboxWorkloadTemplate, + ) -> Result { + let response = self + .unary(|mut grpc| { + let request = proto::CreateSandboxTemplateRequest { + template: Some(template.clone()), + workspace: String::new(), + }; + async move { grpc.create_sandbox_template(request).await } + }) + .await?; + sandbox_template_from_response(response.template) + } + + /// Fetch a reusable sandbox template by name from the default workspace. + pub async fn get_sandbox_template(&self, name: &str) -> Result { + let response = self + .unary(|mut grpc| { + let request = proto::GetSandboxTemplateRequest { + name: name.to_string(), + workspace: String::new(), + }; + async move { grpc.get_sandbox_template(request).await } + }) + .await?; + sandbox_template_from_response(response.template) + } + + /// List reusable sandbox templates in the default workspace or across all workspaces. + pub async fn list_sandbox_templates( + &self, + opts: SandboxTemplateListOptions, + ) -> Result> { + let response = self + .unary(|mut grpc| { + let request = proto::ListSandboxTemplatesRequest { + limit: opts.limit, + offset: opts.offset, + workspace: String::new(), + all_workspaces: opts.all_workspaces, + label_selector: opts.label_selector.clone(), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + Ok(response.templates) + } + + /// Delete a reusable sandbox template by name from the default workspace. + pub async fn delete_sandbox_template(&self, name: &str) -> Result { + let response = self + .unary(|mut grpc| { + let request = proto::DeleteSandboxTemplateRequest { + name: name.to_string(), + workspace: String::new(), + }; + async move { grpc.delete_sandbox_template(request).await } + }) + .await?; + Ok(response.deleted) + } + /// Fetch a sandbox by name. pub async fn get_sandbox(&self, name: &str) -> Result { let response = self @@ -567,6 +647,96 @@ impl WorkspaceScopedClient { sandbox_from_response(response.sandbox) } + /// Create a new sandbox from a template in this workspace. + pub async fn create_sandbox_from_template( + &self, + spec: SandboxTemplateCreateSpec, + ) -> Result { + let mut request = create_sandbox_from_template_request(spec); + request.workspace = self.workspace.clone(); + let response = self + .client + .unary(|mut grpc| { + let request = request.clone(); + async move { grpc.create_sandbox(request).await } + }) + .await?; + sandbox_from_response(response.sandbox) + } + + /// Create a reusable sandbox template in this workspace. + pub async fn create_sandbox_template( + &self, + template: SandboxWorkloadTemplate, + ) -> Result { + let response = self + .client + .unary(|mut grpc| { + let request = proto::CreateSandboxTemplateRequest { + template: Some(template.clone()), + workspace: self.workspace.clone(), + }; + async move { grpc.create_sandbox_template(request).await } + }) + .await?; + sandbox_template_from_response(response.template) + } + + /// Fetch a reusable sandbox template by name in this workspace. + pub async fn get_sandbox_template(&self, name: &str) -> Result { + let response = self + .client + .unary(|mut grpc| { + let request = proto::GetSandboxTemplateRequest { + name: name.to_string(), + workspace: self.workspace.clone(), + }; + async move { grpc.get_sandbox_template(request).await } + }) + .await?; + sandbox_template_from_response(response.template) + } + + /// List reusable sandbox templates in this workspace, or across all workspaces. + pub async fn list_sandbox_templates( + &self, + opts: SandboxTemplateListOptions, + ) -> Result> { + let response = self + .client + .unary(|mut grpc| { + let request = proto::ListSandboxTemplatesRequest { + limit: opts.limit, + offset: opts.offset, + workspace: if opts.all_workspaces { + String::new() + } else { + self.workspace.clone() + }, + all_workspaces: opts.all_workspaces, + label_selector: opts.label_selector.clone(), + }; + async move { grpc.list_sandbox_templates(request).await } + }) + .await?; + Ok(response.templates) + } + + /// Delete a reusable sandbox template by name in this workspace. + pub async fn delete_sandbox_template(&self, name: &str) -> Result { + let response = self + .client + .unary(|mut grpc| { + let request = proto::DeleteSandboxTemplateRequest { + name: name.to_string(), + workspace: self.workspace.clone(), + }; + async move { grpc.delete_sandbox_template(request).await } + }) + .await?; + Ok(response.deleted) + } + /// Fetch a sandbox by name in this workspace. pub async fn get_sandbox(&self, name: &str) -> Result { let response = self @@ -837,6 +1007,36 @@ fn create_sandbox_request(spec: SandboxSpec) -> proto::CreateSandboxRequest { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), + } +} + +fn create_sandbox_from_template_request( + spec: SandboxTemplateCreateSpec, +) -> proto::CreateSandboxRequest { + let SandboxTemplateCreateSpec { + name, + template_name, + labels, + providers, + command, + tty, + policy, + } = spec; + proto::CreateSandboxRequest { + spec: Some(proto::SandboxSpec { + providers, + command, + tty, + policy, + ..proto::SandboxSpec::default() + }), + name: name.unwrap_or_default(), + labels, + annotations: HashMap::new(), + workspace: String::new(), + workload_template_name: template_name, + await_main_process_attachment: false, } } @@ -846,6 +1046,13 @@ fn sandbox_from_response(sandbox: Option) -> Result .ok_or_else(|| SdkError::invalid_config("sandbox missing from gateway response")) } +fn sandbox_template_from_response( + template: Option, +) -> Result { + template + .ok_or_else(|| SdkError::invalid_config("sandbox template missing from gateway response")) +} + fn map_status(status: tonic::Status) -> SdkError { let message = status.message().to_string(); match status.code() { diff --git a/crates/openshell-sdk/src/lib.rs b/crates/openshell-sdk/src/lib.rs index dbf2524a2a..985c7ecc05 100644 --- a/crates/openshell-sdk/src/lib.rs +++ b/crates/openshell-sdk/src/lib.rs @@ -6,7 +6,8 @@ //! Two layers: //! //! - [`OpenShellClient`] — the high-level sandbox-focused MVP surface: -//! health, sandbox CRUD, readiness/deletion waits, non-streaming exec. +//! health, sandbox CRUD, reusable sandbox templates, readiness/deletion +//! waits, and non-streaming exec. //! - [`raw`] — direct access to the generated tonic clients for RPCs the //! curated surface doesn't yet cover (inference, providers, policy, logs, //! settings, SSH, forwarding). @@ -46,6 +47,8 @@ pub use config::{AuthConfig, ClientConfig}; pub use error::SdkError; pub use refresh::{Refresh, RefreshError, RefreshedToken, TokenSource}; pub use types::{ - ExecOptions, ExecResult, Health, ListOptions, SandboxPhase, SandboxRef, SandboxSpec, - ServiceStatus, WorkspaceRef, + ExecOptions, ExecResult, Health, ListOptions, SandboxPhase, SandboxRef, SandboxResources, + SandboxServiceLevel, SandboxSpec, SandboxStartup, SandboxTemplateCreateSpec, + SandboxTemplateListOptions, SandboxWorkloadConfig, SandboxWorkloadTemplate, + SandboxWorkloadTemplateProvenance, SandboxWorkloadTemplateSpec, ServiceStatus, WorkspaceRef, }; diff --git a/crates/openshell-sdk/src/raw.rs b/crates/openshell-sdk/src/raw.rs index e974b19259..35d91f3325 100644 --- a/crates/openshell-sdk/src/raw.rs +++ b/crates/openshell-sdk/src/raw.rs @@ -22,11 +22,15 @@ pub use openshell_core::proto; pub use openshell_core::proto::inference_client::InferenceClient; pub use openshell_core::proto::open_shell_client::OpenShellClient as GrpcClient; pub use openshell_core::proto::{ - CreateSandboxRequest, CreateWorkspaceRequest, DeleteSandboxRequest, DeleteWorkspaceRequest, - ExecSandboxRequest, GetSandboxRequest, GetWorkspaceRequest, HealthRequest, - ListProvidersRequest, ListSandboxesRequest, ListWorkspacesRequest, Sandbox, - SandboxPhase as ProtoSandboxPhase, SandboxSpec as ProtoSandboxSpec, SandboxTemplate, - ServiceStatus as ProtoServiceStatus, StartSandboxRequest, StopSandboxRequest, Workspace, + CreateSandboxRequest, CreateSandboxTemplateRequest, CreateWorkspaceRequest, + DeleteSandboxRequest, DeleteSandboxTemplateRequest, DeleteWorkspaceRequest, ExecSandboxRequest, + GetSandboxRequest, GetSandboxTemplateRequest, GetWorkspaceRequest, HealthRequest, + ListProvidersRequest, ListSandboxTemplatesRequest, ListSandboxesRequest, ListWorkspacesRequest, + Sandbox, SandboxPhase as ProtoSandboxPhase, SandboxResources, SandboxServiceLevel, + SandboxSpec as ProtoSandboxSpec, SandboxStartup, SandboxTemplate, SandboxTemplateResponse, + SandboxWorkloadConfig, SandboxWorkloadTemplate, SandboxWorkloadTemplateProvenance, + SandboxWorkloadTemplateSpec, ServiceStatus as ProtoServiceStatus, StartSandboxRequest, + StopSandboxRequest, Workspace, }; /// Type alias for the gRPC client wrapped in the SDK's auth interceptor. diff --git a/crates/openshell-sdk/src/types.rs b/crates/openshell-sdk/src/types.rs index 9cb7171fd4..db2944474b 100644 --- a/crates/openshell-sdk/src/types.rs +++ b/crates/openshell-sdk/src/types.rs @@ -117,6 +117,60 @@ pub struct SandboxSpec { pub tty: bool, } +/// Caller intent for creating a sandbox from a named workload template. +#[derive(Clone, Debug, Default)] +pub struct SandboxTemplateCreateSpec { + /// Optional user-supplied sandbox name. When empty the server generates one. + pub name: Option, + /// Workspace-scoped template name to resolve at creation time. + pub template_name: String, + /// Labels attached to the sandbox. + pub labels: HashMap, + /// Provider names to attach. + pub providers: Vec, + /// Exact canonical command. Empty selects the gateway's scratch login shell. + pub command: Vec, + /// Allocate a retained pseudo-terminal for the canonical command. + pub tty: bool, + /// Create-time sandbox policy. The named workload template supplies runtime + /// workload fields; policy remains part of the sandbox's governance spec. + pub policy: Option, +} + +/// Reusable sandbox workload template resource. +/// +/// This is a raw proto alias because template specs intentionally expose the +/// full portable workload shape plus driver-owned config. +pub type SandboxWorkloadTemplate = proto::SandboxWorkloadTemplate; + +/// Desired reusable workload shape for a [`SandboxWorkloadTemplate`]. +pub type SandboxWorkloadTemplateSpec = proto::SandboxWorkloadTemplateSpec; + +/// Portable sandbox workload configuration for template-backed sandboxes. +pub type SandboxWorkloadConfig = proto::SandboxWorkloadConfig; + +/// Portable resource requirements for template-backed sandboxes. +pub type SandboxResources = proto::SandboxResources; + +/// Desired service level for sandboxes created from a template. +pub type SandboxServiceLevel = proto::SandboxServiceLevel; + +/// Startup service-level settings for template-backed sandboxes. +pub type SandboxStartup = proto::SandboxStartup; + +/// Options for listing reusable sandbox templates. +#[derive(Clone, Debug, Default)] +pub struct SandboxTemplateListOptions { + /// Maximum templates to return. `0` defers to the server default. + pub limit: u32, + /// Offset into the result list. + pub offset: u32, + /// Optional label selector in `key=value,key2=value2` form. + pub label_selector: String, + /// List templates across all workspaces. + pub all_workspaces: bool, +} + /// Reference to a sandbox owned by the gateway. #[derive(Clone, Debug)] #[non_exhaustive] @@ -128,12 +182,28 @@ pub struct SandboxRef { pub labels: HashMap, pub resource_version: u64, pub exit_code: Option, + pub created_from_workload_template: Option, +} + +/// Reusable workload template revision used to create a sandbox. +#[derive(Clone, Debug, Eq, PartialEq)] +#[non_exhaustive] +pub struct SandboxWorkloadTemplateProvenance { + pub name: String, + pub resource_version: String, } impl SandboxRef { pub(crate) fn from_proto(sandbox: proto::Sandbox) -> Self { let phase = sandbox.phase().into(); let exit_code = sandbox.status.as_ref().and_then(|status| status.exit_code); + let created_from_workload_template = + sandbox + .created_from_workload_template + .map(|p| SandboxWorkloadTemplateProvenance { + name: p.name, + resource_version: p.resource_version, + }); let meta = sandbox.metadata.unwrap_or_default(); Self { id: meta.id, @@ -143,6 +213,7 @@ impl SandboxRef { labels: meta.labels, resource_version: meta.resource_version, exit_code, + created_from_workload_template, } } } diff --git a/crates/openshell-sdk/tests/client_mock.rs b/crates/openshell-sdk/tests/client_mock.rs index 1cdac7da41..58633ceb17 100644 --- a/crates/openshell-sdk/tests/client_mock.rs +++ b/crates/openshell-sdk/tests/client_mock.rs @@ -12,7 +12,8 @@ use openshell_core::proto; use openshell_core::proto::open_shell_server::{OpenShell, OpenShellServer}; use openshell_sdk::{ AuthConfig, ClientConfig, ExecOptions, ListOptions, OpenShellClient, Refresh, RefreshError, - RefreshedToken, SandboxPhase, SandboxSpec, ServiceStatus as SdkServiceStatus, + RefreshedToken, SandboxPhase, SandboxSpec, SandboxTemplateCreateSpec, + SandboxTemplateListOptions, ServiceStatus as SdkServiceStatus, }; use std::collections::HashMap; use std::sync::Arc; @@ -29,6 +30,10 @@ struct MockState { last_get_name: Mutex>, last_get_workspace: Mutex>, last_create: Mutex>, + last_template_create: Mutex>, + last_template_get: Mutex>, + last_template_list: Mutex>, + last_template_delete: Mutex>, last_delete_name: Mutex>, last_delete_workspace: Mutex>, last_stop: Mutex>, @@ -61,6 +66,11 @@ fn sandbox_with_phase_ws( phase: proto::SandboxPhase, workspace: &str, ) -> proto::Sandbox { + let created_from_workload_template = + (name == "from-template").then(|| proto::SandboxWorkloadTemplateProvenance { + name: "python".to_string(), + resource_version: "7".to_string(), + }); proto::Sandbox { metadata: Some(proto::datamodel::v1::ObjectMeta { id: format!("id-{name}"), @@ -77,6 +87,7 @@ fn sandbox_with_phase_ws( phase: phase.into(), ..Default::default() }), + created_from_workload_template, } } @@ -98,6 +109,34 @@ fn workspace_proto(name: &str, phase: proto::datamodel::v1::WorkspacePhase) -> p } } +fn workload_template_proto(name: &str, workspace: &str) -> proto::SandboxWorkloadTemplate { + proto::SandboxWorkloadTemplate { + metadata: Some(proto::datamodel::v1::ObjectMeta { + id: format!("template-{workspace}-{name}"), + name: name.to_string(), + created_at_ms: 1_000_000, + labels: HashMap::new(), + annotations: HashMap::new(), + resource_version: 1, + deletion_timestamp_ms: 0, + workspace: workspace.to_string(), + }), + spec: Some(proto::SandboxWorkloadTemplateSpec { + workload: Some(proto::SandboxWorkloadConfig { + image: format!("ghcr.io/test/{name}:latest"), + environment: HashMap::new(), + resources: Some(proto::SandboxResources { + cpu: "1".to_string(), + memory: "512Mi".to_string(), + ..proto::SandboxResources::default() + }), + }), + driver_config: None, + desired_service_level: None, + }), + } +} + #[tonic::async_trait] impl OpenShell for TestOpenShell { async fn report_main_process_exit( @@ -177,6 +216,62 @@ impl OpenShell for TestOpenShell { })) } + async fn create_sandbox_template( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + let template = request + .template + .clone() + .ok_or_else(|| Status::invalid_argument("missing template"))?; + *self.state.last_template_create.lock().await = Some(request); + Ok(Response::new(proto::SandboxTemplateResponse { + template: Some(template), + })) + } + + async fn get_sandbox_template( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + let workspace = if request.workspace.is_empty() { + "default" + } else { + &request.workspace + }; + let template = workload_template_proto(&request.name, workspace); + *self.state.last_template_get.lock().await = Some(request); + Ok(Response::new(proto::SandboxTemplateResponse { + template: Some(template), + })) + } + + async fn list_sandbox_templates( + &self, + request: tonic::Request, + ) -> Result, Status> { + let request = request.into_inner(); + *self.state.last_template_list.lock().await = Some(request); + Ok(Response::new(proto::ListSandboxTemplatesResponse { + templates: vec![ + workload_template_proto("python", "default"), + workload_template_proto("cuda", "gpu"), + ], + })) + } + + async fn delete_sandbox_template( + &self, + request: tonic::Request, + ) -> Result, Status> { + *self.state.last_template_delete.lock().await = Some(request.into_inner()); + Ok(Response::new(proto::DeleteSandboxTemplateResponse { + deleted: true, + })) + } + async fn stop_sandbox( &self, request: tonic::Request, @@ -817,6 +912,92 @@ async fn create_sandbox_passes_spec_through() { ); } +#[tokio::test] +async fn create_sandbox_from_template_passes_template_name() { + let state = Arc::new(MockState::default()); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + + let sandbox = client + .create_sandbox_from_template(SandboxTemplateCreateSpec { + name: Some("from-template".to_string()), + template_name: "python".to_string(), + providers: vec!["openai".to_string()], + command: vec!["python".to_string(), "-m".to_string(), "agent".to_string()], + tty: false, + policy: Some(proto::SandboxPolicy { + version: 1, + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(sandbox.name, "from-template"); + + let observed = state.last_create.lock().await.clone().unwrap(); + assert_eq!(observed.name, "from-template"); + assert_eq!(observed.workload_template_name, "python"); + let observed_spec = observed.spec.unwrap(); + assert_eq!(observed_spec.providers, vec!["openai".to_string()]); + assert_eq!(observed_spec.command, vec!["python", "-m", "agent"]); + assert!(!observed_spec.tty); + assert_eq!(observed_spec.policy.unwrap().version, 1); +} + +#[tokio::test] +async fn sandbox_template_crud_uses_default_workspace() { + let state = Arc::new(MockState::default()); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + + let created = client + .create_sandbox_template(workload_template_proto("python", "")) + .await + .unwrap(); + assert_eq!(created.metadata.as_ref().unwrap().name, "python"); + + let observed_create = state.last_template_create.lock().await.clone().unwrap(); + assert!(observed_create.workspace.is_empty()); + assert_eq!( + observed_create + .template + .as_ref() + .and_then(|template| template.metadata.as_ref()) + .unwrap() + .name, + "python" + ); + + let fetched = client.get_sandbox_template("python").await.unwrap(); + assert_eq!(fetched.metadata.as_ref().unwrap().name, "python"); + let observed_get = state.last_template_get.lock().await.clone().unwrap(); + assert_eq!(observed_get.name, "python"); + assert!(observed_get.workspace.is_empty()); + + let listed = client + .list_sandbox_templates(SandboxTemplateListOptions { + limit: 10, + offset: 2, + label_selector: String::new(), + all_workspaces: true, + }) + .await + .unwrap(); + assert_eq!(listed.len(), 2); + let observed_list = state.last_template_list.lock().await.clone().unwrap(); + assert_eq!(observed_list.limit, 10); + assert_eq!(observed_list.offset, 2); + assert!(observed_list.workspace.is_empty()); + assert!(observed_list.all_workspaces); + + let deleted = client.delete_sandbox_template("python").await.unwrap(); + assert!(deleted); + let observed_delete = state.last_template_delete.lock().await.clone().unwrap(); + assert_eq!(observed_delete.name, "python"); + assert!(observed_delete.workspace.is_empty()); +} + #[tokio::test] async fn get_sandbox_sends_name_and_maps_phase() { let state = Arc::new(MockState { @@ -835,6 +1016,21 @@ async fn get_sandbox_sends_name_and_maps_phase() { assert_eq!(observed.as_deref(), Some("my-box")); } +#[tokio::test] +async fn get_sandbox_preserves_workload_template_provenance() { + let state = Arc::new(MockState::default()); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + + let sandbox = client.get_sandbox("from-template").await.unwrap(); + + let provenance = sandbox + .created_from_workload_template + .expect("template provenance"); + assert_eq!(provenance.name, "python"); + assert_eq!(provenance.resource_version, "7"); +} + #[tokio::test] async fn list_sandboxes_propagates_filters() { let state = Arc::new(MockState::default()); @@ -1137,6 +1333,33 @@ async fn workspace_scoped_create_passes_workspace() { assert_eq!(observed.workspace, "staging"); } +#[tokio::test] +async fn workspace_scoped_create_from_template_passes_workspace() { + let state = Arc::new(MockState::default()); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + + let sandbox = client + .workspace("staging") + .create_sandbox_from_template(SandboxTemplateCreateSpec { + name: Some("from-template".to_string()), + template_name: "python".to_string(), + policy: Some(proto::SandboxPolicy { + version: 2, + ..Default::default() + }), + ..Default::default() + }) + .await + .unwrap(); + assert_eq!(sandbox.name, "from-template"); + + let observed = state.last_create.lock().await.clone().unwrap(); + assert_eq!(observed.workspace, "staging"); + assert_eq!(observed.workload_template_name, "python"); + assert_eq!(observed.spec.unwrap().policy.unwrap().version, 2); +} + #[tokio::test] async fn workspace_scoped_get_passes_workspace() { let state = Arc::new(MockState { @@ -1169,6 +1392,50 @@ async fn workspace_scoped_list_passes_workspace() { assert!(!observed.all_workspaces); } +#[tokio::test] +async fn workspace_scoped_sandbox_template_crud_passes_workspace() { + let state = Arc::new(MockState::default()); + let endpoint = start_mock(state.clone()).await; + let client = connect(&endpoint).await; + let ws = client.workspace("staging"); + + ws.create_sandbox_template(workload_template_proto("python", "staging")) + .await + .unwrap(); + let observed_create = state.last_template_create.lock().await.clone().unwrap(); + assert_eq!(observed_create.workspace, "staging"); + + ws.get_sandbox_template("python").await.unwrap(); + let observed_get = state.last_template_get.lock().await.clone().unwrap(); + assert_eq!(observed_get.name, "python"); + assert_eq!(observed_get.workspace, "staging"); + + let listed = ws + .list_sandbox_templates(SandboxTemplateListOptions::default()) + .await + .unwrap(); + assert_eq!(listed.len(), 2); + let observed_list = state.last_template_list.lock().await.clone().unwrap(); + assert_eq!(observed_list.workspace, "staging"); + assert!(!observed_list.all_workspaces); + + ws.list_sandbox_templates(SandboxTemplateListOptions { + all_workspaces: true, + ..Default::default() + }) + .await + .unwrap(); + let observed_all = state.last_template_list.lock().await.clone().unwrap(); + assert!(observed_all.workspace.is_empty()); + assert!(observed_all.all_workspaces); + + let deleted = ws.delete_sandbox_template("python").await.unwrap(); + assert!(deleted); + let observed_delete = state.last_template_delete.lock().await.clone().unwrap(); + assert_eq!(observed_delete.name, "python"); + assert_eq!(observed_delete.workspace, "staging"); +} + #[tokio::test] async fn workspace_scoped_delete_passes_workspace() { let state = Arc::new(MockState::default()); diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index ae35fc0fbf..898eef334d 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -10,10 +10,6 @@ rust-version.workspace = true license.workspace = true repository.workspace = true -[[bin]] -name = "openshell-gateway" -path = "src/main.rs" - [dependencies] openshell-bootstrap = { path = "../openshell-bootstrap" } openshell-core = { path = "../openshell-core", default-features = false, features = ["oauth"] } @@ -31,7 +27,8 @@ openshell-router = { path = "../openshell-router" } openshell-supervisor-middleware = { path = "../openshell-supervisor-middleware" } openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" } -# Kubernetes client (used by the `generate-certs` subcommand) +# Kubernetes client used by ServiceAccount bootstrap authentication and the +# `generate-certs` subcommand. kube = { workspace = true } k8s-openapi = { workspace = true } @@ -115,25 +112,8 @@ x509-parser = "0.16" arc-swap = "1" notify = "8" -[target.'cfg(not(target_os = "windows"))'.dependencies] -openshell-driver-docker = { path = "../openshell-driver-docker", optional = true } -openshell-driver-kubernetes = { path = "../openshell-driver-kubernetes", optional = true } -openshell-driver-podman = { path = "../openshell-driver-podman", optional = true } - -# MXC is the Windows-only in-process compute backend (openshell-driver-mxc is a -# no-op stub on other targets). It is only linked into the gateway on Windows. -[target.'cfg(target_os = "windows")'.dependencies] -openshell-driver-mxc = { path = "../openshell-driver-mxc" } - [features] -default = ["telemetry", "in-tree-compute-drivers"] -## Link the first-party compute drivers into the standard gateway binary. -## Disable this feature for a protocol-only gateway that uses external drivers. -in-tree-compute-drivers = [ - "dep:openshell-driver-docker", - "dep:openshell-driver-kubernetes", - "dep:openshell-driver-podman", -] +default = ["telemetry"] ## Compile in anonymous telemetry emission (forwards to openshell-core/telemetry). ## On by default; build with `--no-default-features` for a telemetry-free gateway ## that contains no telemetry endpoint, HTTP client, or emission code. diff --git a/crates/openshell-server/src/auth/compute_driver.rs b/crates/openshell-server/src/auth/compute_driver.rs index cedc2115b5..04caee61b1 100644 --- a/crates/openshell-server/src/auth/compute_driver.rs +++ b/crates/openshell-server/src/auth/compute_driver.rs @@ -52,7 +52,7 @@ impl Authenticator for ComputeDriverAuthenticator { Ok(Some(Principal::Sandbox(SandboxPrincipal { sandbox_id, source: SandboxIdentitySource::ComputeDriver { - driver_name: self.compute.selected_driver_name().to_string(), + driver_name: self.compute.configured_driver_name().to_string(), }, trust_domain: Some("openshell".to_string()), }))) diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index f22e1355e4..f18dbe07aa 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -6,7 +6,6 @@ use clap::parser::ValueSource; use clap::{ArgAction, ArgMatches, Command, CommandFactory, FromArgMatches, Parser}; use miette::{IntoDiagnostic, Result}; -use openshell_core::ComputeDriverKind; use openshell_core::config::{DEFAULT_GATEWAY_NAME, DEFAULT_SERVER_PORT}; use std::net::{IpAddr, SocketAddr}; use std::path::PathBuf; @@ -17,10 +16,7 @@ use crate::certgen; use crate::compute::driver_config::GuestTlsPaths; use crate::config_file::{self, ConfigFile, GatewayFileSection}; use crate::defaults::{self, LocalTlsPaths}; -use crate::{ - ComputeDriverRegistry, ServerStartupConfig, configured_compute_driver_for_startup, - install_default_compute_drivers, run_server, tracing_bus::TracingLogBus, -}; +use crate::{ComputeDriverRegistry, ServerStartupConfig, run_server, tracing_bus::TracingLogBus}; /// `OpenShell` gateway process - gRPC and HTTP server with protocol multiplexing. /// @@ -107,12 +103,10 @@ struct RunArgs { /// Compute drivers configured for this gateway. /// - /// Accepts a comma-delimited list such as `kubernetes` or - /// `kubernetes,podman`. The configuration format is future-proofed for - /// multiple drivers, but the gateway currently requires exactly one. - /// When unset, the gateway auto-detects the driver based on the runtime - /// environment (Kubernetes → Podman → Docker). VM is never - /// auto-detected and requires explicit configuration. + /// Accepts a comma-delimited list of registered driver names. The + /// configuration format is future-proofed for multiple drivers, but the + /// gateway currently requires exactly one. When unset, the gateway runs + /// detection probes supplied by the drivers compiled into the binary. #[arg( long, alias = "driver", @@ -127,9 +121,9 @@ struct RunArgs { /// /// When set, the socket is associated with the single driver name supplied /// by `--drivers` or `OPENSHELL_DRIVERS` and replaces normal construction - /// for that selected name, including canonical built-in names. The gateway - /// connects to this operator-provided endpoint; it does not provision the - /// remote driver. + /// for that selected name, including a compiled registration with the same + /// name. The gateway connects to this operator-provided endpoint; it does + /// not provision the remote driver. #[arg(long, env = "OPENSHELL_COMPUTE_DRIVER_SOCKET")] compute_driver_socket: Option, @@ -147,9 +141,9 @@ struct RunArgs { /// Enable mTLS client certificate authentication for local single-user gateways. /// - /// When unset, this defaults on for Docker, Podman, and VM gateways that - /// have client certificate verification configured and no OIDC issuer. - /// Kubernetes deployments must use OIDC or fronting-proxy auth instead. + /// When unset, this defaults on for drivers registered as local + /// single-player backends when client certificate verification is + /// configured and no OIDC issuer is present. #[arg( long = "enable-mtls-auth", env = "OPENSHELL_ENABLE_MTLS_AUTH", @@ -231,7 +225,7 @@ pub fn command() -> Command { } pub async fn run_cli() -> Result<()> { - run_cli_with_compute_drivers(install_default_compute_drivers()).await + run_cli_with_compute_drivers(ComputeDriverRegistry::new()).await } /// Run the gateway CLI with the compute drivers linked by the binary. @@ -249,7 +243,12 @@ pub async fn run_cli_with_compute_drivers(compute_drivers: ComputeDriverRegistry } } -fn prepare_server_config( +#[cfg(test)] +fn prepare_server_config(args: &mut RunArgs, matches: &ArgMatches) -> Result { + prepare_server_config_with_drivers(args, matches, &ComputeDriverRegistry::new()) +} + +fn prepare_server_config_with_drivers( args: &mut RunArgs, matches: &ArgMatches, compute_drivers: &ComputeDriverRegistry, @@ -270,7 +269,7 @@ fn prepare_server_config( let compute_driver = compute_drivers .select(&args.drivers) .map_err(|error| miette::miette!("{error}"))?; - let compute_driver_kind = compute_driver.name().parse::().ok(); + let selected_registration = compute_drivers.get(compute_driver.name()); let local_tls = apply_runtime_defaults(args)?; let guest_tls = local_tls.as_ref().map(GuestTlsPaths::from); @@ -281,7 +280,7 @@ fn prepare_server_config( let has_client_ca = args.tls_client_ca.is_some(); let has_oidc = args.oidc_issuer.is_some(); let mtls_auth_enabled = - resolve_mtls_auth_enabled(args, matches, file.as_ref(), compute_driver_kind); + resolve_mtls_auth_enabled(args, matches, file.as_ref(), selected_registration); if args.disable_tls && has_client_ca { return Err(miette::miette!( @@ -298,9 +297,11 @@ fn prepare_server_config( "mTLS user authentication requires --tls-client-ca so client certificates can be verified." )); } - if mtls_auth_enabled && matches!(compute_driver_kind, Some(ComputeDriverKind::Kubernetes)) { + if mtls_auth_enabled + && selected_registration.is_some_and(|registration| !registration.supports_mtls_user_auth()) + { return Err(miette::miette!( - "mTLS user authentication is not supported with the Kubernetes compute driver. Configure OIDC or a trusted fronting proxy for user authentication." + "mTLS user authentication is not supported with the selected compute driver. Configure OIDC or a trusted fronting proxy for user authentication." )); } @@ -501,8 +502,7 @@ async fn run_from_args( matches: ArgMatches, compute_drivers: ComputeDriverRegistry, ) -> Result<()> { - let prepared = prepare_server_config(&mut args, &matches, &compute_drivers)?; - let compute_driver = configured_compute_driver_for_startup(&compute_drivers, &prepared)?; + let prepared = prepare_server_config_with_drivers(&mut args, &matches, &compute_drivers)?; let tracing_log_bus = TracingLogBus::new(); let otlp_config = prepared @@ -511,14 +511,20 @@ async fn run_from_args( .and_then(|f| f.openshell.gateway.otlp.as_ref()); let gateway_resource = crate::otel_tracing::GatewayResourceAttributes::new( Some(prepared.config.name.as_str()), - Some(compute_driver.name()), + Some(prepared.compute_driver.name()), + ); + let compute_driver_tracing = compute_drivers.tracing_setup( + &prepared.compute_driver, + &prepared.config.compute_driver_endpoints, + otlp_config.map(|config| config.endpoint.as_str()), + Some(prepared.config.name.as_str()), ); let (tracing_handle, setup_error) = crate::tracing_setup::install( EnvFilter::try_from_default_env() .unwrap_or_else(|_| EnvFilter::new(&prepared.config.log_level)), &tracing_log_bus, otlp_config, - &compute_driver, + compute_driver_tracing, gateway_resource, ); @@ -576,7 +582,7 @@ async fn run_from_args( info!(bind = %prepared.config.bind_address, "Starting OpenShell server"); - let result = Box::pin(run_server(prepared, compute_driver, tracing_log_bus)).await; + let result = Box::pin(run_server(prepared, tracing_log_bus, compute_drivers)).await; tracing_handle.shutdown(); @@ -817,23 +823,15 @@ fn normalize_compute_driver_socket_args(args: &mut RunArgs, matches: &ArgMatches } } -fn is_singleplayer_driver(driver: Option) -> bool { - matches!( - driver, - Some( - ComputeDriverKind::Docker - | ComputeDriverKind::Podman - | ComputeDriverKind::Vm - | ComputeDriverKind::Mxc - ) - ) +fn is_singleplayer_driver(registration: Option<&crate::ComputeDriverRegistration>) -> bool { + registration.is_some_and(crate::ComputeDriverRegistration::is_local_singleplayer) } fn resolve_mtls_auth_enabled( args: &RunArgs, matches: &ArgMatches, file: Option<&ConfigFile>, - compute_driver: Option, + selected_registration: Option<&crate::ComputeDriverRegistration>, ) -> bool { let file_configured = file .and_then(|f| f.openshell.gateway.mtls_auth.as_ref()) @@ -846,7 +844,7 @@ fn resolve_mtls_auth_enabled( return false; } - is_singleplayer_driver(compute_driver) + is_singleplayer_driver(selected_registration) } #[cfg(test)] @@ -859,37 +857,49 @@ mod tests { static REGISTRY_DETECTION_CALLS: AtomicUsize = AtomicUsize::new(0); - fn detect_registered_docker() -> bool { + fn detect_registered_local() -> bool { REGISTRY_DETECTION_CALLS.fetch_add(1, Ordering::SeqCst); true } #[derive(Clone, Copy)] - struct TestComputeDriverFactory; + struct TestFactory; #[async_trait::async_trait] - impl crate::ComputeDriverFactory for TestComputeDriverFactory { + impl crate::ComputeDriverFactory for TestFactory { async fn build( &self, _context: crate::ComputeDriverBuildContext<'_>, - ) -> openshell_core::Result { - unreachable!("configuration tests do not construct the driver") + ) -> openshell_core::Result { + unreachable!("CLI metadata tests do not build drivers") } } - fn detected_docker_registry() -> crate::ComputeDriverRegistry { + fn test_registry(name: &str, singleplayer: bool, mtls: bool) -> crate::ComputeDriverRegistry { + let mut registration = + crate::ComputeDriverRegistration::new(name, 100, None, TestFactory).unwrap(); + if singleplayer { + registration = registration.with_local_singleplayer(); + } + if !mtls { + registration = registration.without_mtls_user_auth(); + } let mut registry = crate::ComputeDriverRegistry::new(); + registry.install(registration).unwrap(); registry - .install( - crate::ComputeDriverRegistration::new( - "docker", - 100, - Some(detect_registered_docker), - TestComputeDriverFactory, - ) - .unwrap(), - ) - .unwrap(); + } + + fn detected_local_registry() -> crate::ComputeDriverRegistry { + let registration = crate::ComputeDriverRegistration::new( + "local", + 100, + Some(detect_registered_local), + TestFactory, + ) + .unwrap() + .with_local_singleplayer(); + let mut registry = crate::ComputeDriverRegistry::new(); + registry.install(registration).unwrap(); registry } @@ -1350,7 +1360,7 @@ mod tests { "--db-url", "sqlite::memory:", "--drivers", - "docker", + "local", "--tls-cert", "/tmp/server.crt", "--tls-key", @@ -1363,7 +1373,7 @@ mod tests { &args, &matches, None, - Some(openshell_core::ComputeDriverKind::Docker) + test_registry("local", true, true).get("local") )); } @@ -1376,7 +1386,6 @@ mod tests { let config = tempfile::tempdir().unwrap(); let _state = EnvVarGuard::set("XDG_STATE_HOME", state.path().to_str().unwrap()); let _config = EnvVarGuard::set("XDG_CONFIG_HOME", config.path().to_str().unwrap()); - let _kubernetes = EnvVarGuard::set("KUBERNETES_SERVICE_HOST", "10.0.0.1"); let _mtls = EnvVarGuard::remove("OPENSHELL_ENABLE_MTLS_AUTH"); let _drivers = EnvVarGuard::remove("OPENSHELL_DRIVERS"); REGISTRY_DETECTION_CALLS.store(0, Ordering::SeqCst); @@ -1392,18 +1401,19 @@ mod tests { "--tls-client-ca", "/tmp/ca.crt", ]); - let registry = detected_docker_registry(); + let registry = detected_local_registry(); - let prepared = super::prepare_server_config(&mut args, &matches, ®istry).unwrap(); + let prepared = + super::prepare_server_config_with_drivers(&mut args, &matches, ®istry).unwrap(); - assert_eq!(prepared.compute_driver.name(), "docker"); + assert_eq!(prepared.compute_driver.name(), "local"); assert!(prepared.config.compute_drivers.is_empty()); assert!(prepared.config.mtls_auth.enabled); assert_eq!(REGISTRY_DETECTION_CALLS.load(Ordering::SeqCst), 1); } #[test] - fn mtls_auth_does_not_auto_default_for_kubernetes_driver() { + fn mtls_auth_does_not_auto_default_for_shared_driver() { let _lock = ENV_LOCK .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); @@ -1414,7 +1424,7 @@ mod tests { "--db-url", "sqlite::memory:", "--drivers", - "kubernetes", + "shared", "--tls-cert", "/tmp/server.crt", "--tls-key", @@ -1427,7 +1437,7 @@ mod tests { &args, &matches, None, - Some(openshell_core::ComputeDriverKind::Kubernetes) + test_registry("shared", false, false).get("shared") )); } @@ -1443,7 +1453,7 @@ mod tests { "--db-url", "sqlite::memory:", "--drivers", - "docker", + "local", "--tls-cert", "/tmp/server.crt", "--tls-key", @@ -1464,7 +1474,7 @@ enabled = false &args, &matches, Some(&file), - Some(openshell_core::ComputeDriverKind::Docker) + test_registry("local", true, true).get("local") )); } @@ -1702,23 +1712,12 @@ ssh_session_ttl_secs = 1234 } #[test] - fn singleplayer_driver_matches_only_one_local_driver() { - for driver in [ - openshell_core::ComputeDriverKind::Docker, - openshell_core::ComputeDriverKind::Podman, - openshell_core::ComputeDriverKind::Vm, - openshell_core::ComputeDriverKind::Mxc, - ] { - assert!( - super::is_singleplayer_driver(Some(driver)), - "{driver} should be singleplayer" - ); - } + fn singleplayer_behavior_comes_from_registration() { + let local = test_registry("local", true, true); + assert!(super::is_singleplayer_driver(local.get("local"))); - assert!(!super::is_singleplayer_driver(Some( - openshell_core::ComputeDriverKind::Kubernetes - ))); - assert!(!super::is_singleplayer_driver(None)); + let shared = test_registry("shared", false, true); + assert!(!super::is_singleplayer_driver(shared.get("shared"))); } #[test] @@ -1744,11 +1743,6 @@ ssh_session_ttl_secs = 1234 Some(std::path::Path::new("/run/openshell/kyma.sock")) ); assert_eq!(args.drivers, ["kyma"]); - assert!( - args.drivers[0] - .parse::() - .is_err() - ); } #[test] @@ -1928,12 +1922,8 @@ mem_mib = "not-a-number" "--disable-tls", ]); - let prepared = super::prepare_server_config( - &mut args, - &matches, - &crate::install_default_compute_drivers(), - ) - .expect("server config is prepared"); + let prepared = + super::prepare_server_config(&mut args, &matches).expect("server config is prepared"); assert_eq!(prepared.config.compute_drivers, vec!["podman".to_string()]); assert_eq!( @@ -1944,53 +1934,4 @@ mem_mib = "not-a-number" assert!(file.openshell.drivers.contains_key("docker")); assert!(file.openshell.drivers.contains_key("vm")); } - - #[test] - #[cfg(not(target_os = "windows"))] - fn driver_inherits_shared_image_from_gateway_section() { - // [openshell.gateway].default_image inherits into the K8s driver - // table when the driver-specific table does not set it. - let file = config_file_from_toml( - r#" -[openshell.gateway] -default_image = "ghcr.io/nvidia/openshell/sandbox:1.0" - -[openshell.drivers.kubernetes] -namespace = "agents" -"#, - ); - let merged = crate::config_file::driver_table( - super::ComputeDriverKind::Kubernetes.as_str(), - &file.openshell.gateway, - file.openshell.drivers.get("kubernetes"), - ); - let parsed = merged - .try_into::() - .expect("merged table deserializes"); - assert_eq!(parsed.default_image, "ghcr.io/nvidia/openshell/sandbox:1.0"); - assert_eq!(parsed.namespace, "agents"); - } - - #[test] - #[cfg(not(target_os = "windows"))] - fn driver_specific_value_overrides_gateway_inheritance() { - let file = config_file_from_toml( - r#" -[openshell.gateway] -default_image = "gateway-default:1.0" - -[openshell.drivers.kubernetes] -default_image = "k8s-specific:1.0" -"#, - ); - let merged = crate::config_file::driver_table( - super::ComputeDriverKind::Kubernetes.as_str(), - &file.openshell.gateway, - file.openshell.drivers.get("kubernetes"), - ); - let parsed = merged - .try_into::() - .expect("deserializes"); - assert_eq!(parsed.default_image, "k8s-specific:1.0"); - } } diff --git a/crates/openshell-server/src/compute/driver_config.rs b/crates/openshell-server/src/compute/driver_config.rs index c25c63ded2..d06e6fbc8f 100644 --- a/crates/openshell-server/src/compute/driver_config.rs +++ b/crates/openshell-server/src/compute/driver_config.rs @@ -3,20 +3,13 @@ //! Selected compute-driver config construction. //! -//! This module owns loading the selected driver config from TOML, applying -//! driver-specific environment overrides, and applying gateway startup defaults. -//! It does not acquire, connect to, or start compute drivers. - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -pub mod builtin; +//! This module owns loading the selected driver config from TOML and applying +//! gateway startup defaults and endpoint overrides. It does not acquire, +//! connect to, or start compute drivers. use crate::config_file; use crate::defaults::LocalTlsPaths; -#[cfg(target_os = "windows")] -use openshell_core::ComputeDriverKind; use openshell_core::{Error, Result}; -#[cfg(target_os = "windows")] -use openshell_driver_mxc::MxcComputeConfig; use serde::Deserialize; use std::collections::BTreeMap; use std::path::PathBuf; @@ -53,15 +46,6 @@ pub struct DriverStartupContext<'a> { pub endpoint_overrides: &'a BTreeMap, } -/// Build the selected MXC config from TOML. MXC is Windows-only and has no -/// runtime-default overlay; the driver reads its own settings from the config. -/// The Linux built-in driver configs now live in the `builtin` submodule -/// (compiled only off Windows). -#[cfg(target_os = "windows")] -pub fn mxc_config_from_context(context: DriverStartupContext<'_>) -> Result { - driver_config_from_context(context, ComputeDriverKind::Mxc.as_str()) -} - pub fn remote_driver_config_from_context( context: DriverStartupContext<'_>, name: &str, @@ -91,16 +75,18 @@ pub struct RemoteDriverConfig { pub fn driver_config_from_context( context: DriverStartupContext<'_>, driver_name: &str, + inherited_config_keys: &[&str], ) -> Result where T: Default + serde::de::DeserializeOwned, { - driver_config_from_file(context.file, driver_name) + driver_config_from_file(context.file, driver_name, inherited_config_keys) } fn driver_config_from_file( file: Option<&config_file::ConfigFile>, driver_name: &str, + inherited_config_keys: &[&str], ) -> Result where T: Default + serde::de::DeserializeOwned, @@ -108,10 +94,11 @@ where let Some(file) = file else { return Ok(T::default()); }; - let merged = config_file::driver_table( + let merged = config_file::driver_table_with_inherited_keys( driver_name, &file.openshell.gateway, file.openshell.drivers.get(driver_name), + inherited_config_keys, ); merged.try_into().map_err(|e| { Error::config(format!( diff --git a/crates/openshell-server/src/compute/driver_config/builtin.rs b/crates/openshell-server/src/compute/driver_config/builtin.rs deleted file mode 100644 index dea867237d..0000000000 --- a/crates/openshell-server/src/compute/driver_config/builtin.rs +++ /dev/null @@ -1,231 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Configuration construction for built-in compute drivers. - -use super::{DriverStartupContext, GuestTlsPaths, driver_config_from_context}; -use crate::compute::VmComputeConfig; -#[cfg(test)] -use crate::config_file; -use openshell_core::{ComputeDriverKind, Result}; -use openshell_driver_docker::DockerComputeConfig; -use openshell_driver_kubernetes::KubernetesComputeConfig; -use openshell_driver_podman::PodmanComputeConfig; -use std::path::PathBuf; - -/// Build the selected Kubernetes config from TOML plus runtime defaults. -pub fn kubernetes_config_from_context( - context: DriverStartupContext<'_>, -) -> Result { - let mut cfg = driver_config_from_context(context, ComputeDriverKind::Kubernetes.as_str())?; - apply_kubernetes_runtime_defaults(&mut cfg); - Ok(cfg) -} - -/// Build the selected Podman config from TOML plus runtime defaults. -pub fn podman_config_from_context( - context: DriverStartupContext<'_>, -) -> Result { - let mut podman = driver_config_from_context(context, ComputeDriverKind::Podman.as_str())?; - apply_podman_runtime_defaults(&mut podman, context); - Ok(podman) -} - -/// Build the selected Docker config from TOML plus runtime defaults. -pub fn docker_config_from_context( - context: DriverStartupContext<'_>, -) -> Result { - let mut cfg = driver_config_from_context(context, ComputeDriverKind::Docker.as_str())?; - apply_docker_runtime_defaults(&mut cfg, context); - Ok(cfg) -} - -/// Build the selected VM config from TOML plus runtime defaults. -pub fn vm_config_from_context(context: DriverStartupContext<'_>) -> Result { - let mut cfg = driver_config_from_context(context, ComputeDriverKind::Vm.as_str())?; - apply_vm_runtime_defaults(&mut cfg, context); - Ok(cfg) -} - -fn apply_kubernetes_runtime_defaults(k8s: &mut KubernetesComputeConfig) { - if let Ok(size) = std::env::var("OPENSHELL_K8S_WORKSPACE_DEFAULT_STORAGE_SIZE") { - k8s.workspace_default_storage_size = size; - } - if let Ok(storage_class) = std::env::var("OPENSHELL_K8S_WORKSPACE_STORAGE_CLASS") { - k8s.workspace_storage_class = storage_class; - } -} - -fn apply_podman_runtime_defaults( - podman: &mut PodmanComputeConfig, - context: DriverStartupContext<'_>, -) { - podman.gateway_port = context.gateway_port; - apply_podman_env_overrides(podman); - apply_guest_tls_defaults_to_split_fields( - &mut podman.guest_tls_ca, - &mut podman.guest_tls_cert, - &mut podman.guest_tls_key, - context.guest_tls, - ); -} - -fn apply_docker_runtime_defaults(cfg: &mut DockerComputeConfig, context: DriverStartupContext<'_>) { - apply_guest_tls_defaults_to_split_fields( - &mut cfg.guest_tls_ca, - &mut cfg.guest_tls_cert, - &mut cfg.guest_tls_key, - context.guest_tls, - ); -} - -fn apply_vm_runtime_defaults(cfg: &mut VmComputeConfig, context: DriverStartupContext<'_>) { - if cfg.state_dir.as_os_str().is_empty() { - cfg.state_dir = VmComputeConfig::default_state_dir(); - } - if cfg.grpc_endpoint.trim().is_empty() - && (!context.gateway_tls_enabled || context.guest_tls.is_some()) - { - let scheme = if context.gateway_tls_enabled { - "https" - } else { - "http" - }; - cfg.grpc_endpoint = format!("{scheme}://127.0.0.1:{}", context.gateway_port); - } - - apply_guest_tls_defaults_to_split_fields( - &mut cfg.guest_tls_ca, - &mut cfg.guest_tls_cert, - &mut cfg.guest_tls_key, - context.guest_tls, - ); -} - -fn apply_guest_tls_defaults_to_split_fields( - ca: &mut Option, - cert: &mut Option, - key: &mut Option, - defaults: Option<&GuestTlsPaths>, -) { - if ca.is_none() - && cert.is_none() - && key.is_none() - && let Some(paths) = defaults - { - *ca = Some(paths.ca.clone()); - *cert = Some(paths.cert.clone()); - *key = Some(paths.key.clone()); - } -} - -fn apply_podman_env_overrides(podman: &mut PodmanComputeConfig) { - if let Ok(p) = std::env::var("OPENSHELL_PODMAN_SOCKET") { - podman.socket_path = Some(PathBuf::from(p)); - } - if let Ok(ip) = std::env::var("OPENSHELL_PODMAN_HOST_GATEWAY_IP") { - podman.host_gateway_ip = ip; - } - if let Ok(mode) = std::env::var("OPENSHELL_PODMAN_USERNS") { - podman.userns = Some(mode); - } -} - -#[cfg(test)] -mod tests { - use super::*; - use std::collections::BTreeMap; - - fn test_context(file: Option<&config_file::ConfigFile>) -> DriverStartupContext<'_> { - static EMPTY_ENDPOINT_OVERRIDES: std::sync::LazyLock> = - std::sync::LazyLock::new(BTreeMap::new); - DriverStartupContext { - file, - guest_tls: None, - gateway_port: openshell_core::config::DEFAULT_SERVER_PORT, - gateway_tls_enabled: false, - endpoint_overrides: &EMPTY_ENDPOINT_OVERRIDES, - } - } - - #[test] - fn podman_config_reads_bind_mount_opt_in_from_driver_table() { - let file: config_file::ConfigFile = toml::from_str( - r" -[openshell.drivers.podman] -enable_bind_mounts = true -", - ) - .expect("valid config"); - - let cfg = podman_config_from_context(test_context(Some(&file))).expect("podman config"); - - assert!(cfg.enable_bind_mounts); - } - - #[test] - fn docker_config_reads_bind_mount_opt_in_from_driver_table() { - let file: config_file::ConfigFile = toml::from_str( - r" -[openshell.drivers.docker] -enable_bind_mounts = true -", - ) - .expect("valid config"); - - let cfg = docker_config_from_context(test_context(Some(&file))).expect("docker config"); - - assert!(cfg.enable_bind_mounts); - } - - #[test] - fn docker_config_reads_socket_path_from_driver_table() { - let file: config_file::ConfigFile = toml::from_str( - r#" -[openshell.drivers.docker] -socket_path = "/tmp/docker.sock" -"#, - ) - .expect("valid config"); - - let cfg = docker_config_from_context(test_context(Some(&file))).expect("docker config"); - - assert_eq!(cfg.socket_path, Some(PathBuf::from("/tmp/docker.sock"))); - } - - #[test] - fn docker_config_reports_selected_invalid_driver_table() { - let file: config_file::ConfigFile = toml::from_str( - r" -[openshell.drivers.docker] -unknown_docker_key = true -", - ) - .expect("valid config"); - - let err = docker_config_from_context(test_context(Some(&file))).unwrap_err(); - - assert!( - err.to_string() - .contains("invalid [openshell.drivers.docker] table") - ); - } - - #[test] - fn vm_config_reports_selected_invalid_driver_table() { - let file: config_file::ConfigFile = toml::from_str( - r#" -[openshell.drivers.vm] -mem_mib = "not-a-number" -"#, - ) - .expect("valid config"); - - let err = vm_config_from_context(test_context(Some(&file))).unwrap_err(); - - assert!( - err.to_string() - .contains("invalid [openshell.drivers.vm] table") - ); - } -} diff --git a/crates/openshell-server/src/compute/lease.rs b/crates/openshell-server/src/compute/lease.rs index bf58fae48b..3310946dab 100644 --- a/crates/openshell-server/src/compute/lease.rs +++ b/crates/openshell-server/src/compute/lease.rs @@ -242,10 +242,10 @@ impl ReconcilerLease { /// Derive a stable replica identity for lease ownership. /// -/// Kubernetes sets `HOSTNAME` to the pod name, Docker sets it to the -/// container ID, and systemd units inherit the machine hostname. -/// `OPENSHELL_REPLICA_ID` allows explicit override. The UUID fallback -/// handles edge cases where neither env var is set. +/// Managed workloads commonly receive a stable runtime identity through +/// `HOSTNAME`, while systemd units inherit the machine hostname. +/// `OPENSHELL_REPLICA_ID` allows an explicit override. The UUID fallback +/// handles environments where neither variable is set. pub fn replica_id() -> String { std::env::var("OPENSHELL_REPLICA_ID") .or_else(|_| std::env::var("HOSTNAME")) diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 78ae6fddb3..4fdae8c38e 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -5,17 +5,6 @@ pub mod driver_config; pub mod lease; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -pub mod vm; - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -pub use openshell_driver_docker::DockerComputeConfig; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -pub use openshell_driver_kubernetes::KubernetesComputeConfig; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -pub use openshell_driver_podman::PodmanComputeConfig; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -pub use vm::VmComputeConfig; use crate::grpc::policy::SANDBOX_SETTINGS_OBJECT_TYPE; use crate::otel_tracing::TraceContextInterceptor; @@ -30,9 +19,6 @@ use crate::tracing_bus::TracingLogBus; use futures::{Stream, StreamExt}; #[cfg(unix)] use hyper_util::rt::TokioIo; -use openshell_core::ComputeDriverKind; -#[cfg(target_os = "windows")] -use openshell_core::proto::SandboxPolicy; use openshell_core::proto::compute::v1::{ AuthenticateSandboxRequest, CreateSandboxRequest, DeleteSandboxRequest, DeleteWorkspaceRequest, DeleteWorkspaceResponse, DriverCondition, DriverPlatformEvent, DriverResourceRequirements, @@ -49,20 +35,10 @@ use openshell_core::proto::compute::v1::{ }; use openshell_core::proto::{ PlatformEvent, Sandbox, SandboxCondition, SandboxPhase, SandboxSpec, SandboxStatus, - SandboxTemplate, ServiceEndpoint, SshSession, + SandboxTemplate, SandboxWorkloadTemplate, ServiceEndpoint, SshSession, }; +use openshell_core::telemetry::TelemetryComputeDriver; use openshell_core::{ObjectLabels, ObjectWorkspace}; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -use openshell_driver_docker::{ComputeDriverService as DockerDriverService, DockerComputeDriver}; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -use openshell_driver_kubernetes::{ - ComputeDriverService as KubernetesDriverService, KubernetesComputeDriver, - OperatorNamespaceAllowlist, -}; -#[cfg(target_os = "windows")] -use openshell_driver_mxc::{ComputeDriverService as MxcDriverService, MxcComputeConfig}; -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -use openshell_driver_podman::{ComputeDriverService as PodmanDriverService, PodmanComputeDriver}; use prost::Message; use std::collections::HashMap; use std::fmt; @@ -287,6 +263,8 @@ pub struct ComputeDriverInfoSnapshot { pub gateway_manages_lifecycle: bool, /// Whether the driver authenticates driver-native sandbox credentials. pub supports_sandbox_authentication: bool, + /// Whether the driver reports runtime readiness without a supervisor session. + pub driver_reports_runtime_readiness: bool, } /// Interval between store-vs-backend reconciliation sweeps. @@ -306,8 +284,8 @@ pub struct ManagedDriverProcess { } impl ManagedDriverProcess { - #[cfg(all(unix, any(test, feature = "in-tree-compute-drivers")))] - pub(crate) fn new(child: tokio::process::Child, socket_path: PathBuf) -> Self { + #[cfg(unix)] + pub fn new(child: tokio::process::Child, socket_path: PathBuf) -> Self { Self { child: std::sync::Mutex::new(Some(child)), socket_path, @@ -404,14 +382,13 @@ pub struct AcquiredRemoteDriverEndpoint { } impl AcquiredRemoteDriverEndpoint { - #[cfg(any(test, feature = "in-tree-compute-drivers"))] - pub(crate) fn managed_builtin( - driver_kind: ComputeDriverKind, + pub fn managed( + name: impl Into, channel: Channel, driver_process: Arc, ) -> Self { Self { - name: driver_kind.as_str().to_string(), + name: name.into(), channel, driver_process: Some(driver_process), } @@ -575,6 +552,7 @@ impl ComputeDriver for RemoteComputeDriver { pub struct ComputeRuntime { driver: TracedDriver, driver_info: ComputeDriverInfoSnapshot, + telemetry_compute_driver: TelemetryComputeDriver, driver_process: Option>, default_image: String, store: Arc, @@ -586,14 +564,6 @@ pub struct ComputeRuntime { lifecycle_gates: Arc, gateway_listener_requirements: Vec, replica_id: String, - /// A1 policy side channel for the in-process MXC driver. `create_sandbox` - /// stages the typed `SandboxPolicy` here by sandbox id immediately before - /// dispatching to the driver, which consumes it. `None` for all other - /// drivers. The proto driver contract has no `policy` field and there is no - /// driver-side `GetSandboxConfig`, so this in-process map is how the policy - /// reaches the MXC backend without changing the cross-process contract. - #[cfg(target_os = "windows")] - mxc_policy_sink: Option>>>, } impl fmt::Debug for ComputeRuntime { @@ -631,11 +601,9 @@ impl ComputeRuntime { compute_error_from_status(status) })? .into_inner(); - let driver_kind = driver_name.parse::().ok(); info!( configured_driver = %driver_name, advertised_driver = %capabilities.driver_name, - in_tree = driver_kind.is_some(), "Compute driver connected" ); let driver_info = ComputeDriverInfoSnapshot { @@ -644,6 +612,7 @@ impl ComputeRuntime { driver_version: capabilities.driver_version, gateway_manages_lifecycle: capabilities.gateway_manages_lifecycle, supports_sandbox_authentication: capabilities.supports_sandbox_authentication, + driver_reports_runtime_readiness: capabilities.driver_reports_runtime_readiness, }; let default_image = capabilities.default_image; let gateway_listener_requirements = match driver @@ -702,6 +671,7 @@ impl ComputeRuntime { Ok(Self { driver: TracedDriver::new(driver, driver_name), driver_info, + telemetry_compute_driver: TelemetryComputeDriver::custom(), driver_process, default_image, store, @@ -713,8 +683,6 @@ impl ComputeRuntime { lifecycle_gates: Arc::new(LifecycleGateRegistry::default()), gateway_listener_requirements, replica_id: lease::replica_id(), - #[cfg(target_os = "windows")] - mxc_policy_sink: None, }) } @@ -743,62 +711,6 @@ impl ComputeRuntime { self.lifecycle_gates.entry_count() } - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - pub async fn new_docker( - config: openshell_core::Config, - docker_config: DockerComputeConfig, - store: Arc, - sandbox_index: SandboxIndex, - sandbox_watch_bus: SandboxWatchBus, - tracing_log_bus: TracingLogBus, - supervisor_sessions: Arc, - ) -> Result { - let driver = DockerComputeDriver::new(&config, &docker_config) - .await - .map_err(|err| ComputeError::Message(err.to_string()))?; - let driver: SharedComputeDriver = Arc::new(DockerDriverService::new_in_process(driver)); - Self::from_driver( - ComputeDriverKind::Docker.as_str().to_string(), - driver, - None, - store, - sandbox_index, - sandbox_watch_bus, - tracing_log_bus, - supervisor_sessions, - ) - .await - } - - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - pub async fn new_kubernetes( - config: KubernetesComputeConfig, - store: Arc, - sandbox_index: SandboxIndex, - sandbox_watch_bus: SandboxWatchBus, - tracing_log_bus: TracingLogBus, - supervisor_sessions: Arc, - shutdown_rx: watch::Receiver, - ) -> Result<(Self, Option), ComputeError> { - let driver = KubernetesComputeDriver::new(config, shutdown_rx) - .await - .map_err(|err| ComputeError::Message(err.to_string()))?; - let operator_allowlist_arc = driver.operator_allowlist().cloned(); - let driver: SharedComputeDriver = Arc::new(KubernetesDriverService::new_in_process(driver)); - let runtime = Self::from_driver( - ComputeDriverKind::Kubernetes.as_str().to_string(), - driver, - None, - store, - sandbox_index, - sandbox_watch_bus, - tracing_log_bus, - supervisor_sessions, - ) - .await?; - Ok((runtime, operator_allowlist_arc)) - } - pub(crate) async fn new_remote_driver( endpoint: AcquiredRemoteDriverEndpoint, store: Arc, @@ -821,64 +733,6 @@ impl ComputeRuntime { .await } - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - pub async fn new_podman( - config: PodmanComputeConfig, - store: Arc, - sandbox_index: SandboxIndex, - sandbox_watch_bus: SandboxWatchBus, - tracing_log_bus: TracingLogBus, - supervisor_sessions: Arc, - ) -> Result { - let driver = PodmanComputeDriver::new(config) - .await - .map_err(|err| ComputeError::Message(err.to_string()))?; - let driver: SharedComputeDriver = Arc::new(PodmanDriverService::new_in_process(driver)); - Self::from_driver( - ComputeDriverKind::Podman.as_str().to_string(), - driver, - None, - store, - sandbox_index, - sandbox_watch_bus, - tracing_log_bus, - supervisor_sessions, - ) - .await - } - - /// Construct a `ComputeRuntime` backed by the MXC compute driver. - /// - /// MXC is Windows-only, in-process, and self-reports `Ready` — there is - /// no supervisor session argument because no surrogate or relay is used. - #[cfg(target_os = "windows")] - pub async fn new_mxc( - mxc_config: MxcComputeConfig, - store: Arc, - sandbox_index: SandboxIndex, - sandbox_watch_bus: SandboxWatchBus, - tracing_log_bus: TracingLogBus, - supervisor_sessions: Arc, - ) -> Result { - let backend = openshell_driver_mxc::MxcComputeBackend::new(mxc_config); - // Grab the A1 policy side channel before moving `backend` into the service. - let sink = backend.policy_sink(); - let service: SharedComputeDriver = Arc::new(MxcDriverService::new(backend)); - let mut runtime = Self::from_driver( - ComputeDriverKind::Mxc.as_str().to_string(), - service, - None, - store, - sandbox_index, - sandbox_watch_bus, - tracing_log_bus, - supervisor_sessions, - ) - .await?; - runtime.mxc_policy_sink = Some(sink); - Ok(runtime) - } - #[must_use] pub fn default_image(&self) -> &str { &self.default_image @@ -890,12 +744,7 @@ impl ComputeRuntime { } #[must_use] - pub fn driver_kind(&self) -> Option { - self.driver_info.name.parse().ok() - } - - #[must_use] - pub fn selected_driver_name(&self) -> &str { + pub fn configured_driver_name(&self) -> &str { &self.driver_info.name } @@ -921,6 +770,20 @@ impl ComputeRuntime { .map(|response| response.into_inner().sandbox_id) } + #[must_use] + pub(crate) fn telemetry_compute_driver(&self) -> TelemetryComputeDriver { + self.telemetry_compute_driver + } + + #[must_use] + pub(crate) fn with_telemetry_compute_driver( + mut self, + telemetry_compute_driver: TelemetryComputeDriver, + ) -> Self { + self.telemetry_compute_driver = telemetry_compute_driver; + self + } + #[must_use] pub(crate) fn gateway_listener_requirements(&self) -> &[GatewayListenerRequirement] { &self.gateway_listener_requirements @@ -1035,16 +898,6 @@ impl ComputeRuntime { if let Some(spec) = driver_sandbox.spec.as_mut() { spec.await_main_process_attachment = await_main_process_attachment; } - // A1: stage the typed SandboxPolicy out-of-band into the MXC backend's - // side channel, keyed by sandbox id (== DriverSandbox.id), immediately - // before dispatch. The driver removes/consumes it in create_sandbox. The - // proto driver contract has no policy field, so this is the only path. - #[cfg(target_os = "windows")] - if let Some(sink) = &self.mxc_policy_sink - && let Some(p) = sandbox.spec.as_ref().and_then(|s| s.policy.clone()) - { - sink.lock().await.insert(sandbox_id.clone(), p); - } match self .driver .call( @@ -1421,12 +1274,11 @@ impl ComputeRuntime { let runtime_restart_during_stop = expected_stopped && driver_snapshot_reports_runtime_restart(&snapshot); if suspension_progressing || runtime_restart_during_stop { - // The Kubernetes controller has accepted the stop and - // is waiting for its pod to terminate. A container - // runtime restart can likewise be the expected SIGTERM - // exit from an in-flight stop. Preserve the durable - // transition so completion or recovery, rather than the - // watcher, determines its terminal state. + // The backend has accepted the stop but has not finished + // terminating the sandbox. A runtime restart can likewise + // be the expected exit from an in-flight stop. Preserve the + // durable transition so completion or recovery, rather than + // a watch snapshot, determines its terminal state. debug!(sandbox_id, "Sandbox stop is still progressing"); } else if backend_phase == SandboxPhase::Error || observed_stopped == expected_stopped @@ -1471,7 +1323,12 @@ impl ComputeRuntime { match self .store .update_message_cas::(&sandbox_id, expected_resource_version, |sandbox| { - apply_driver_snapshot(sandbox, snapshot, session_connected); + apply_driver_snapshot( + sandbox, + snapshot, + session_connected, + self.driver_info.driver_reports_runtime_readiness, + ); }) .await { @@ -1919,7 +1776,14 @@ impl ComputeRuntime { sandbox_id, deleting_resource_version, "reconcile observed backend snapshot", - |sandbox| apply_driver_snapshot(sandbox, &snapshot, session_connected), + |sandbox| { + apply_driver_snapshot( + sandbox, + &snapshot, + session_connected, + self.driver_info.driver_reports_runtime_readiness, + ); + }, ) .await; } @@ -2131,7 +1995,7 @@ impl ComputeRuntime { let watch_runtime = runtime.clone(); let watch_shutdown = shutdown_rx.clone(); tokio::spawn(async move { - watch_runtime.watch_loop(watch_shutdown).await; + Box::pin(watch_runtime.watch_loop(watch_shutdown)).await; }); tokio::spawn(async move { runtime.reconcile_loop(shutdown_rx).await; @@ -2657,7 +2521,7 @@ impl ComputeRuntime { let runtime = self.clone(); let watch_cancel = cancel_rx.clone(); let watch_handle = tokio::spawn(async move { - runtime.watch_loop(watch_cancel).await; + Box::pin(runtime.watch_loop(watch_cancel)).await; }); let runtime = self.clone(); @@ -2959,7 +2823,14 @@ impl ComputeRuntime { .update_message_cas::( &incoming.id, expected_resource_version, - |sandbox| apply_driver_snapshot(sandbox, &incoming, session_connected), + |sandbox| { + apply_driver_snapshot( + sandbox, + &incoming, + session_connected, + self.driver_info.driver_reports_runtime_readiness, + ); + }, ) .await .map_err(|e| match e { @@ -3867,6 +3738,7 @@ fn driver_sandbox_spec_from_public( .as_ref() .map(|template| driver_sandbox_template_from_public(template, driver_name)) .transpose()?, + policy: spec.policy.clone(), resource_requirements: spec.resource_requirements.as_ref().map(|requirements| { DriverSandboxResourceRequirements { gpu: requirements @@ -3894,6 +3766,7 @@ fn driver_sandbox_template_from_public( resources: extract_typed_resources(&template.resources), platform_config: build_platform_config(template), driver_config: select_driver_config(&template.driver_config, driver_name)?, + user_namespaces: template.user_namespaces, }) } @@ -3999,19 +3872,6 @@ fn build_platform_config(template: &SandboxTemplate) -> Option &'static str { + "sandbox_workload_template" + } +} + fn compute_error_from_status(status: Status) -> ComputeError { match status.code() { Code::AlreadyExists => ComputeError::AlreadyExists, @@ -4155,7 +4021,12 @@ fn public_status_from_driver( } } -fn apply_driver_snapshot(sandbox: &mut Sandbox, incoming: &DriverSandbox, session_connected: bool) { +fn apply_driver_snapshot( + sandbox: &mut Sandbox, + incoming: &DriverSandbox, + session_connected: bool, + driver_reports_runtime_readiness: bool, +) { let old_phase = SandboxPhase::try_from(sandbox.phase()).unwrap_or(SandboxPhase::Unknown); let sandbox_name = &incoming.name; @@ -4190,7 +4061,11 @@ fn apply_driver_snapshot(sandbox: &mut Sandbox, incoming: &DriverSandbox, sessio (phase, status) }, |incoming_status| { - let composed = ComposedPhase::new(incoming_status, session_connected); + let composed = ComposedPhase::new( + incoming_status, + session_connected, + driver_reports_runtime_readiness, + ); let mut status = Some(public_status_from_driver( incoming_status, composed.phase, @@ -4341,7 +4216,11 @@ struct ComposedPhase { } impl ComposedPhase { - fn new(incoming_status: &DriverSandboxStatus, session_connected: bool) -> Self { + fn new( + incoming_status: &DriverSandboxStatus, + session_connected: bool, + driver_reports_runtime_readiness: bool, + ) -> Self { let backend_phase = derive_phase(Some(incoming_status)); // A live supervisor session is a stronger readiness signal than the backend phase. // set_supervisor_session_state may have already promoted the store record to Ready @@ -4349,13 +4228,15 @@ impl ComposedPhase { // backend phase overwrite it. let phase = match backend_phase { SandboxPhase::Error | SandboxPhase::Deleting | SandboxPhase::Stopped => backend_phase, + SandboxPhase::Ready if driver_reports_runtime_readiness => SandboxPhase::Ready, _ if session_connected => SandboxPhase::Ready, _ => SandboxPhase::Provisioning, }; Self { phase, session_connected, - backend_ready_without_session: backend_phase == SandboxPhase::Ready + backend_ready_without_session: !driver_reports_runtime_readiness + && backend_phase == SandboxPhase::Ready && !session_connected, } } @@ -4639,6 +4520,7 @@ impl ComputeDriver for NoopTestDriver { default_image: "openshell/sandbox:test".to_string(), gateway_manages_lifecycle: false, supports_sandbox_authentication: self.sandbox_authentication.is_some(), + driver_reports_runtime_readiness: false, }, )) } @@ -4782,7 +4664,9 @@ pub async fn new_test_runtime_with_driver( driver_version: "test".to_string(), gateway_manages_lifecycle: false, supports_sandbox_authentication, + driver_reports_runtime_readiness: false, }, + telemetry_compute_driver: TelemetryComputeDriver::custom(), driver_process: None, default_image: "openshell/sandbox:test".to_string(), store, @@ -4794,8 +4678,6 @@ pub async fn new_test_runtime_with_driver( lifecycle_gates: Arc::new(LifecycleGateRegistry::default()), gateway_listener_requirements: Vec::new(), replica_id: "test-replica".to_string(), - #[cfg(target_os = "windows")] - mxc_policy_sink: None, } } @@ -4960,6 +4842,7 @@ mod tests { default_image: "openshell/sandbox:test".to_string(), gateway_manages_lifecycle: false, supports_sandbox_authentication: false, + driver_reports_runtime_readiness: false, })) } @@ -5300,6 +5183,7 @@ mod tests { default_image: "openshell/sandbox:test".to_string(), gateway_manages_lifecycle: false, supports_sandbox_authentication: false, + driver_reports_runtime_readiness: false, })) } @@ -5509,7 +5393,9 @@ mod tests { driver_version: "test".to_string(), gateway_manages_lifecycle: false, supports_sandbox_authentication: false, + driver_reports_runtime_readiness: false, }, + telemetry_compute_driver: TelemetryComputeDriver::custom(), driver_process: None, default_image: "openshell/sandbox:test".to_string(), store, @@ -5521,8 +5407,6 @@ mod tests { lifecycle_gates: Arc::new(LifecycleGateRegistry::default()), gateway_listener_requirements: Vec::new(), replica_id: "test-replica".to_string(), - #[cfg(target_os = "windows")] - mxc_policy_sink: None, } } @@ -6141,7 +6025,7 @@ mod tests { ) -> (watch::Sender, tokio::task::JoinHandle<()>) { let (shutdown_tx, shutdown_rx) = watch::channel(false); let runtime = Arc::new(runtime.clone()); - let handle = tokio::spawn(async move { runtime.watch_loop(shutdown_rx).await }); + let handle = tokio::spawn(async move { Box::pin(runtime.watch_loop(shutdown_rx)).await }); tokio::time::timeout(Duration::from_secs(1), driver.watch_started.notified()) .await .expect("watch loop did not start"); @@ -6165,6 +6049,22 @@ mod tests { assert!(store.is_single_replica()); } + #[test] + fn driver_reported_runtime_uses_driver_readiness() { + let status = make_driver_status(DriverCondition { + r#type: "Ready".to_string(), + status: "True".to_string(), + reason: "AgentRunning".to_string(), + message: "MXC workload is running".to_string(), + last_transition_time: String::new(), + }); + + let composed = ComposedPhase::new(&status, false, true); + + assert_eq!(composed.phase, SandboxPhase::Ready); + assert!(!composed.backend_ready_without_session); + } + #[test] fn delete_gate_registry_removes_stale_entries() { let registry = LifecycleGateRegistry::default(); @@ -6480,8 +6380,7 @@ mod tests { )); } - /// Driver calls are a remote boundary even in-process: they reach the - /// Docker daemon, the Kubernetes API, or a Podman socket. + /// Driver calls are a remote boundary even when the driver is in-process. #[tokio::test] async fn driver_calls_export_spans_with_parents() { use tracing::Instrument as _; @@ -9239,7 +9138,7 @@ mod tests { #[tokio::test] async fn backend_not_ready_with_supervisor_becomes_ready() { - // VM path: supervisor connects before backend reports Ready. + // The supervisor may connect before the backend reports Ready. let runtime = test_runtime(Arc::new(TestDriver::default())).await; let sandbox = sandbox_record("sb-1", "sandbox-a", SandboxPhase::Provisioning); runtime.store.put_message(&sandbox).await.unwrap(); @@ -10401,45 +10300,16 @@ mod tests { } #[test] - fn build_platform_config_inverts_user_namespaces_to_host_users() { - use prost_types::value::Kind; - - // user_namespaces: true → host_users: false - let mut template = SandboxTemplate { + fn driver_template_preserves_user_namespace_intent() { + let template = SandboxTemplate { user_namespaces: Some(true), ..SandboxTemplate::default() }; - let config = build_platform_config(&template).expect("config should be Some"); - let host_users = config - .fields - .get("host_users") - .expect("host_users must exist"); - assert_eq!( - host_users.kind, - Some(Kind::BoolValue(false)), - "user_namespaces: true must produce host_users: false" - ); - - // user_namespaces: false → host_users: true - template.user_namespaces = Some(false); - let config = build_platform_config(&template).expect("config should be Some"); - let host_users = config - .fields - .get("host_users") - .expect("host_users must exist"); - assert_eq!( - host_users.kind, - Some(Kind::BoolValue(true)), - "user_namespaces: false must produce host_users: true" - ); + let driver_template = driver_sandbox_template_from_public(&template, "test") + .expect("template conversion should succeed"); - // user_namespaces: None → host_users absent - template.user_namespaces = None; - let config = build_platform_config(&template); - assert!( - config.is_none() || !config.as_ref().unwrap().fields.contains_key("host_users"), - "unset user_namespaces must not produce host_users" - ); + assert_eq!(driver_template.user_namespaces, Some(true)); + assert!(driver_template.platform_config.is_none()); } #[tokio::test] @@ -10645,6 +10515,10 @@ mod tests { let mut sandbox = sandbox_record("sb-uds", "uds-sandbox", SandboxPhase::Provisioning); sandbox.spec = Some(SandboxSpec { log_level: "debug".to_string(), + policy: Some(openshell_core::proto::SandboxPolicy { + version: 42, + ..Default::default() + }), template: Some(SandboxTemplate { image: "ghcr.io/nvidia/openshell/sandbox:test".to_string(), driver_config: Some(prost_types::Struct { @@ -10684,6 +10558,20 @@ mod tests { .expect("selected driver_config should be forwarded"); assert!(driver_config.fields.contains_key("pool")); assert!(!driver_config.fields.contains_key("network_mode")); + assert_eq!( + validated + .spec + .as_ref() + .and_then(|spec| spec.policy.as_ref()) + .map(|policy| policy.version), + Some(42) + ); + assert!(matches!( + &calls[3], + FakeComputeDriverCall::CreateSandbox { sandbox: Some(sandbox) } + if sandbox.spec.as_ref().and_then(|spec| spec.policy.as_ref()) + .is_some_and(|policy| policy.version == 42) + )); driver.clear_calls(); runtime diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index 74b6aad01b..65709748b1 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -26,7 +26,6 @@ use std::net::SocketAddr; use std::path::{Path, PathBuf}; use base64::Engine as _; -use openshell_core::config::ComputeDriverKind; use openshell_core::proto::SupervisorMiddlewareService; use openshell_core::{ GatewayAuthConfig, GatewayInterceptorConfig, GatewayJwtConfig, @@ -432,13 +431,22 @@ pub fn driver_table( driver_name: &str, gateway: &GatewayFileSection, raw: Option<&toml::Value>, +) -> toml::Value { + driver_table_with_inherited_keys(driver_name, gateway, raw, &[]) +} + +pub(crate) fn driver_table_with_inherited_keys( + _driver_name: &str, + gateway: &GatewayFileSection, + raw: Option<&toml::Value>, + inheritable_keys: &[&str], ) -> toml::Value { let mut merged = match raw { Some(toml::Value::Table(table)) => table.clone(), _ => toml::Table::new(), }; - for key in inheritable_keys(driver_name) { + for key in inheritable_keys { if merged.contains_key(*key) { continue; } @@ -450,50 +458,6 @@ pub fn driver_table( toml::Value::Table(merged) } -/// Inheritance allowlist (the Q4 "high-overlap set"). Each driver opts in -/// to a specific subset so a gateway-wide default does not accidentally land -/// in a driver table that does not understand the field. -fn inheritable_keys(driver_name: &str) -> &'static [&'static str] { - match driver_name.parse::().ok() { - Some(ComputeDriverKind::Kubernetes) => &[ - "namespace", - "default_image", - "supervisor_image", - "client_tls_secret_name", - "service_account_name", - "host_gateway_ip", - "enable_user_namespaces", - "sa_token_ttl_secs", - ], - Some(ComputeDriverKind::Docker) => &[ - "sandbox_namespace", - "default_image", - "supervisor_image", - "host_gateway_ip", - "guest_tls_ca", - "guest_tls_cert", - "guest_tls_key", - ], - Some(ComputeDriverKind::Podman) => &[ - "default_image", - "supervisor_image", - "host_gateway_ip", - "guest_tls_ca", - "guest_tls_cert", - "guest_tls_key", - ], - Some(ComputeDriverKind::Vm) => &[ - "default_image", - "guest_tls_ca", - "guest_tls_cert", - "guest_tls_key", - ], - // MXC reads its own settings from the driver config table and has no - // gateway-inherited required fields. - Some(ComputeDriverKind::Mxc) | None => &[], - } -} - fn gateway_inherited_value(g: &GatewayFileSection, key: &str) -> Option { match key { "namespace" | "sandbox_namespace" => g.sandbox_namespace.as_deref().map(string_value), @@ -986,10 +950,11 @@ version = 2 let raw = toml::toml! { namespace = "agents" }; - let merged = driver_table( - ComputeDriverKind::Kubernetes.as_str(), + let merged = driver_table_with_inherited_keys( + "alpha", &gateway, Some(&toml::Value::Table(raw)), + &["default_image", "supervisor_image"], ); let table = merged.as_table().expect("table"); assert_eq!( @@ -1007,14 +972,19 @@ version = 2 } #[test] - fn docker_driver_table_inherits_gateway_defaults() { + fn registered_driver_table_inherits_selected_gateway_defaults() { let gateway = GatewayFileSection { sandbox_namespace: Some("agents".to_string()), default_image: Some("ghcr.io/nvidia/openshell/sandbox:0.9".to_string()), host_gateway_ip: Some("10.0.0.1".to_string()), ..Default::default() }; - let merged = driver_table(ComputeDriverKind::Docker.as_str(), &gateway, None); + let merged = driver_table_with_inherited_keys( + "alpha", + &gateway, + None, + &["sandbox_namespace", "default_image", "host_gateway_ip"], + ); let table = merged.as_table().expect("table"); assert_eq!( table.get("sandbox_namespace").and_then(|v| v.as_str()), @@ -1031,13 +1001,18 @@ version = 2 } #[test] - fn podman_driver_table_inherits_gateway_host_gateway_ip() { + fn registered_driver_table_can_select_network_defaults() { let gateway = GatewayFileSection { default_image: Some("ghcr.io/nvidia/openshell/sandbox:0.9".to_string()), host_gateway_ip: Some("192.168.127.254".to_string()), ..Default::default() }; - let merged = driver_table(ComputeDriverKind::Podman.as_str(), &gateway, None); + let merged = driver_table_with_inherited_keys( + "beta", + &gateway, + None, + &["default_image", "host_gateway_ip"], + ); let table = merged.as_table().expect("table"); assert_eq!( table.get("default_image").and_then(|v| v.as_str()), @@ -1058,10 +1033,11 @@ version = 2 let raw = toml::toml! { default_image = "driver-specific" }; - let merged = driver_table( - ComputeDriverKind::Podman.as_str(), + let merged = driver_table_with_inherited_keys( + "alpha", &gateway, Some(&toml::Value::Table(raw)), + &["default_image"], ); assert_eq!( merged @@ -1075,13 +1051,12 @@ version = 2 #[test] fn driver_table_does_not_leak_keys_outside_allowlist() { - // `client_tls_secret_name` is K8s-only; Docker must not receive it - // even when set at gateway scope. + // Fields not selected by the registration must remain gateway-only. let gateway = GatewayFileSection { client_tls_secret_name: Some("openshell-sandbox-tls".to_string()), ..Default::default() }; - let merged = driver_table(ComputeDriverKind::Docker.as_str(), &gateway, None); + let merged = driver_table_with_inherited_keys("alpha", &gateway, None, &["default_image"]); assert!( !merged .as_table() diff --git a/crates/openshell-server/src/gateway_listener.rs b/crates/openshell-server/src/gateway_listener.rs index 640757bfb3..b638fc33e4 100644 --- a/crates/openshell-server/src/gateway_listener.rs +++ b/crates/openshell-server/src/gateway_listener.rs @@ -386,10 +386,10 @@ mod tests { #[test] fn gateway_listener_specs_reuse_primary_when_wildcard_covers_driver_address() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); - let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); + let callback: SocketAddr = "172.18.0.1:8080".parse().unwrap(); let requirements = [ - docker_listener_requirement(docker), - docker_listener_requirement(docker), + exact_listener_requirement(callback), + exact_listener_requirement(callback), ]; assert_eq!( @@ -401,15 +401,15 @@ mod tests { #[test] fn gateway_listener_scope_for_reused_primary_remains_primary() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); - let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); + let callback: SocketAddr = "172.18.0.1:8080".parse().unwrap(); let loopback: SocketAddr = "127.0.0.1:8080".parse().unwrap(); - let [spec] = gateway_listener_specs(primary, &[docker_listener_requirement(docker)]) + let [spec] = gateway_listener_specs(primary, &[exact_listener_requirement(callback)]) .unwrap() .try_into() .unwrap(); assert_eq!( - spec.scope_for_local_addr(docker), + spec.scope_for_local_addr(callback), GatewayListenerScope::Primary, ); assert_eq!( @@ -421,10 +421,10 @@ mod tests { #[test] fn gateway_listener_specs_preserve_driver_callback_scope() { let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); - let docker: SocketAddr = "172.18.0.1:8080".parse().unwrap(); + let callback: SocketAddr = "172.18.0.1:8080".parse().unwrap(); let requirements = [ - docker_listener_requirement(docker), - docker_listener_requirement(docker), + exact_listener_requirement(callback), + exact_listener_requirement(callback), ]; assert_eq!( @@ -437,11 +437,11 @@ mod tests { provenance: None, }, GatewayListenerSpec { - address: docker, + address: callback, scope: GatewayListenerScope::ComputeDriverCallback, covered_addresses: Vec::new(), provenance: Some(GatewayListenerProvenance { - driver_name: "docker".to_string(), + driver_name: "alpha".to_string(), reason: "managed bridge".to_string(), }), }, @@ -473,7 +473,7 @@ mod tests { "172.18.0.1:0", "172.18.0.1:9090", ] { - let requirement = docker_listener_requirement(address.parse().unwrap()); + let requirement = exact_listener_requirement(address.parse().unwrap()); assert!( gateway_listener_specs(primary, &[requirement]).is_err(), "{address} should be rejected" @@ -482,41 +482,41 @@ mod tests { } #[test] - fn gateway_listener_specs_use_exact_podman_network_gateway() { + fn gateway_listener_specs_use_exact_network_gateway() { let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); - let podman_gateway: SocketAddr = "10.89.1.1:8080".parse().unwrap(); + let network_gateway: SocketAddr = "10.89.1.1:8080".parse().unwrap(); assert_eq!( - gateway_listener_specs(primary, &[podman_listener_requirement(podman_gateway)]) + gateway_listener_specs(primary, &[network_listener_requirement(network_gateway)]) .unwrap(), vec![ primary_listener_spec(primary), - callback_listener_spec(podman_gateway, "podman", "Podman managed bridge",), + callback_listener_spec(network_gateway, "beta", "managed bridge",), ] ); } #[test] - fn gateway_listener_specs_reuse_primary_when_it_covers_podman_exact() { + fn gateway_listener_specs_reuse_primary_when_it_covers_exact_requirement() { let primary: SocketAddr = "0.0.0.0:8080".parse().unwrap(); - let podman_gateway: SocketAddr = "10.89.1.1:8080".parse().unwrap(); + let network_gateway: SocketAddr = "10.89.1.1:8080".parse().unwrap(); assert_eq!( - gateway_listener_specs(primary, &[podman_listener_requirement(podman_gateway)],) + gateway_listener_specs(primary, &[network_listener_requirement(network_gateway)],) .unwrap(), vec![primary_listener_spec(primary)] ); } #[test] - fn gateway_listener_specs_resolve_podman_default_route_source() { + fn gateway_listener_specs_resolve_default_route_source() { let primary: SocketAddr = "127.0.0.1:8080".parse().unwrap(); let default_route_ip = "192.168.20.20".parse().unwrap(); assert_eq!( gateway_listener_specs_with_default_route_ip( primary, - &[podman_default_route_listener_requirement()], + &[default_route_listener_requirement()], Some(default_route_ip), ) .unwrap(), @@ -524,8 +524,8 @@ mod tests { primary_listener_spec(primary), callback_listener_spec( "192.168.20.20:8080".parse().unwrap(), - "podman", - "rootless pasta upstream interface", + "beta", + "default route interface", ), ] ); @@ -537,7 +537,7 @@ mod tests { let err = gateway_listener_specs_with_default_route_ip( primary, - &[podman_default_route_listener_requirement()], + &[default_route_listener_requirement()], Some("203.0.113.20".parse().unwrap()), ) .unwrap_err(); @@ -552,7 +552,7 @@ mod tests { assert_eq!( gateway_listener_specs_with_default_route_ip( primary, - &[podman_default_route_listener_requirement()], + &[default_route_listener_requirement()], Some(default_route_ip), ) .unwrap(), @@ -561,28 +561,24 @@ mod tests { } #[test] - fn gateway_listener_specs_resolve_podman_loopback_separately() { + fn gateway_listener_specs_resolve_loopback_separately() { let primary: SocketAddr = "192.168.20.20:8080".parse().unwrap(); assert_eq!( - gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(), + gateway_listener_specs(primary, &[loopback_listener_requirement()]).unwrap(), vec![ primary_listener_spec(primary), - callback_listener_spec( - "127.0.0.1:8080".parse().unwrap(), - "podman", - "Podman machine host forwarder", - ), + callback_listener_spec("127.0.0.1:8080".parse().unwrap(), "beta", "host forwarder",), ] ); } #[test] - fn gateway_listener_specs_reuse_wildcard_primary_for_podman_loopback() { + fn gateway_listener_specs_reuse_wildcard_primary_for_loopback() { let primary = "0.0.0.0:8080".parse().unwrap(); assert_eq!( - gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(), + gateway_listener_specs(primary, &[loopback_listener_requirement()]).unwrap(), vec![primary_listener_spec(primary)] ); } @@ -592,7 +588,7 @@ mod tests { let primary = "127.0.0.1:8080".parse().unwrap(); assert_eq!( - gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(), + gateway_listener_specs(primary, &[loopback_listener_requirement()]).unwrap(), vec![primary_listener_spec(primary)] ); } @@ -602,7 +598,7 @@ mod tests { for primary in ["[::1]:8080", "[::]:8080"] { let primary = primary.parse().unwrap(); let specs = - gateway_listener_specs(primary, &[podman_loopback_listener_requirement()]).unwrap(); + gateway_listener_specs(primary, &[loopback_listener_requirement()]).unwrap(); assert_eq!(specs.len(), 2); assert_eq!(specs[1].address, SocketAddr::from(([127, 0, 0, 1], 8080))); @@ -613,7 +609,7 @@ mod tests { fn gateway_listener_specs_validate_selector_independently_of_driver_name() { let primary: SocketAddr = "192.168.20.20:8080".parse().unwrap(); let requirement = GatewayListenerRequirement::LoopbackInterface { - driver_name: "docker".to_string(), + driver_name: "alpha".to_string(), reason: "wrong selector".to_string(), }; @@ -634,7 +630,7 @@ mod tests { let result: openshell_core::Result<()> = async { let _listeners = bind_gateway_listeners( primary_address, - &[docker_listener_requirement(occupied_address)], + &[exact_listener_requirement(occupied_address)], ) .await?; continuation_reached.store(true, Ordering::SeqCst); @@ -663,7 +659,7 @@ mod tests { drop(probe); let primary = format!("[::]:{port}").parse().unwrap(); - let listeners = bind_gateway_listeners(primary, &[podman_loopback_listener_requirement()]) + let listeners = bind_gateway_listeners(primary, &[loopback_listener_requirement()]) .await .expect("IPv6 wildcard and IPv4 callback listeners should both bind"); @@ -675,33 +671,33 @@ mod tests { ); } - fn docker_listener_requirement(address: SocketAddr) -> GatewayListenerRequirement { + fn exact_listener_requirement(address: SocketAddr) -> GatewayListenerRequirement { GatewayListenerRequirement::Exact { address, - driver_name: "docker".to_string(), + driver_name: "alpha".to_string(), reason: "managed bridge".to_string(), } } - fn podman_listener_requirement(address: SocketAddr) -> GatewayListenerRequirement { + fn network_listener_requirement(address: SocketAddr) -> GatewayListenerRequirement { GatewayListenerRequirement::Exact { address, - driver_name: "podman".to_string(), - reason: "Podman managed bridge".to_string(), + driver_name: "beta".to_string(), + reason: "managed bridge".to_string(), } } - fn podman_default_route_listener_requirement() -> GatewayListenerRequirement { + fn default_route_listener_requirement() -> GatewayListenerRequirement { GatewayListenerRequirement::DefaultRouteInterface { - driver_name: "podman".to_string(), - reason: "rootless pasta upstream interface".to_string(), + driver_name: "beta".to_string(), + reason: "default route interface".to_string(), } } - fn podman_loopback_listener_requirement() -> GatewayListenerRequirement { + fn loopback_listener_requirement() -> GatewayListenerRequirement { GatewayListenerRequirement::LoopbackInterface { - driver_name: "podman".to_string(), - reason: "Podman machine host forwarder".to_string(), + driver_name: "beta".to_string(), + reason: "host forwarder".to_string(), } } diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 957a77cbac..8143e6058e 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -17,29 +17,31 @@ use openshell_core::proto::{ AttachSandboxProviderRequest, AttachSandboxProviderResponse, ClearDraftChunksRequest, ClearDraftChunksResponse, ComputeDriverCapabilities, ComputeDriverInfo, ConfigureProviderRefreshRequest, ConfigureProviderRefreshResponse, CreateProviderRequest, - CreateSandboxRequest, CreateSshSessionRequest, CreateSshSessionResponse, - CreateWorkspaceRequest, CreateWorkspaceResponse, DeleteProviderProfileRequest, - DeleteProviderProfileResponse, DeleteProviderRefreshRequest, DeleteProviderRefreshResponse, - DeleteProviderRequest, DeleteProviderResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DeleteServiceRequest, DeleteServiceResponse, DeleteWorkspaceRequest, DeleteWorkspaceResponse, - DetachSandboxProviderRequest, DetachSandboxProviderResponse, EditDraftChunkRequest, - EditDraftChunkResponse, ExchangeProviderSubjectTokenRequest, - ExchangeProviderSubjectTokenResponse, ExecSandboxEvent, ExecSandboxInput, ExecSandboxRequest, - ExposeServiceRequest, FinalizeMainProcessExitRequest, FinalizeMainProcessExitResponse, - GatewayMessage, GetCurrentUserRequest, GetCurrentUserResponse, GetDraftHistoryRequest, - GetDraftHistoryResponse, GetDraftPolicyRequest, GetDraftPolicyResponse, + CreateSandboxRequest, CreateSandboxTemplateRequest, CreateSshSessionRequest, + CreateSshSessionResponse, CreateWorkspaceRequest, CreateWorkspaceResponse, + DeleteProviderProfileRequest, DeleteProviderProfileResponse, DeleteProviderRefreshRequest, + DeleteProviderRefreshResponse, DeleteProviderRequest, DeleteProviderResponse, + DeleteSandboxRequest, DeleteSandboxResponse, DeleteSandboxTemplateRequest, + DeleteSandboxTemplateResponse, DeleteServiceRequest, DeleteServiceResponse, + DeleteWorkspaceRequest, DeleteWorkspaceResponse, DetachSandboxProviderRequest, + DetachSandboxProviderResponse, EditDraftChunkRequest, EditDraftChunkResponse, + ExchangeProviderSubjectTokenRequest, ExchangeProviderSubjectTokenResponse, ExecSandboxEvent, + ExecSandboxInput, ExecSandboxRequest, ExposeServiceRequest, FinalizeMainProcessExitRequest, + FinalizeMainProcessExitResponse, GatewayMessage, GetCurrentUserRequest, GetCurrentUserResponse, + GetDraftHistoryRequest, GetDraftHistoryResponse, GetDraftPolicyRequest, GetDraftPolicyResponse, GetGatewayConfigRequest, GetGatewayConfigResponse, GetGatewayInfoRequest, GetGatewayInfoResponse, GetProviderProfileRequest, GetProviderRefreshStatusRequest, GetProviderRefreshStatusResponse, GetProviderRequest, GetSandboxConfigRequest, GetSandboxConfigResponse, GetSandboxLogsRequest, GetSandboxLogsResponse, GetSandboxPolicyStatusRequest, GetSandboxPolicyStatusResponse, GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, GetSandboxRequest, - GetServiceRequest, GetWorkspaceRequest, GetWorkspaceResponse, HealthRequest, HealthResponse, - ImportProviderProfilesRequest, ImportProviderProfilesResponse, IssueSandboxTokenRequest, - IssueSandboxTokenResponse, LintProviderProfilesRequest, LintProviderProfilesResponse, - ListProviderProfilesRequest, ListProviderProfilesResponse, ListProvidersRequest, - ListProvidersResponse, ListSandboxPoliciesRequest, ListSandboxPoliciesResponse, - ListSandboxProvidersRequest, ListSandboxProvidersResponse, ListSandboxesRequest, + GetSandboxTemplateRequest, GetServiceRequest, GetWorkspaceRequest, GetWorkspaceResponse, + HealthRequest, HealthResponse, ImportProviderProfilesRequest, ImportProviderProfilesResponse, + IssueSandboxTokenRequest, IssueSandboxTokenResponse, LintProviderProfilesRequest, + LintProviderProfilesResponse, ListProviderProfilesRequest, ListProviderProfilesResponse, + ListProvidersRequest, ListProvidersResponse, ListSandboxPoliciesRequest, + ListSandboxPoliciesResponse, ListSandboxProvidersRequest, ListSandboxProvidersResponse, + ListSandboxTemplatesRequest, ListSandboxTemplatesResponse, ListSandboxesRequest, ListSandboxesResponse, ListServicesRequest, ListServicesResponse, ListWorkspaceMembersRequest, ListWorkspaceMembersResponse, ListWorkspacesRequest, ListWorkspacesResponse, ProviderProfileResponse, ProviderResponse, PushSandboxLogsRequest, PushSandboxLogsResponse, @@ -48,12 +50,12 @@ use openshell_core::proto::{ RemoveWorkspaceMemberResponse, ReportMainProcessExitRequest, ReportMainProcessExitResponse, ReportPolicyStatusRequest, ReportPolicyStatusResponse, RevokeSshSessionRequest, RevokeSshSessionResponse, RotateProviderCredentialRequest, RotateProviderCredentialResponse, - SandboxResponse, ServiceEndpointResponse, ServiceStatus, StartSandboxRequest, - StopSandboxRequest, SubmitPolicyAnalysisRequest, SubmitPolicyAnalysisResponse, - SupervisorMessage, TcpForwardFrame, UndoDraftChunkRequest, UndoDraftChunkResponse, - UpdateConfigRequest, UpdateConfigResponse, UpdateProviderProfilesRequest, - UpdateProviderProfilesResponse, UpdateProviderRequest, WatchSandboxRequest, - open_shell_server::OpenShell, + SandboxResponse, SandboxTemplateResponse, ServiceEndpointResponse, ServiceStatus, + StartSandboxRequest, StopSandboxRequest, SubmitPolicyAnalysisRequest, + SubmitPolicyAnalysisResponse, SupervisorMessage, TcpForwardFrame, UndoDraftChunkRequest, + UndoDraftChunkResponse, UpdateConfigRequest, UpdateConfigResponse, + UpdateProviderProfilesRequest, UpdateProviderProfilesResponse, UpdateProviderRequest, + WatchSandboxRequest, open_shell_server::OpenShell, }; use serde::{Deserialize, Serialize}; use std::collections::BTreeMap; @@ -299,6 +301,34 @@ impl OpenShell for OpenShellService { sandbox::handle_list_sandboxes(&self.state, request).await } + async fn create_sandbox_template( + &self, + request: Request, + ) -> Result, Status> { + sandbox::handle_create_sandbox_template(&self.state, request).await + } + + async fn get_sandbox_template( + &self, + request: Request, + ) -> Result, Status> { + sandbox::handle_get_sandbox_template(&self.state, request).await + } + + async fn list_sandbox_templates( + &self, + request: Request, + ) -> Result, Status> { + sandbox::handle_list_sandbox_templates(&self.state, request).await + } + + async fn delete_sandbox_template( + &self, + request: Request, + ) -> Result, Status> { + sandbox::handle_delete_sandbox_template(&self.state, request).await + } + async fn list_sandbox_providers( &self, request: Request, diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 83bdc0b00b..0e4c74af95 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -3135,20 +3135,6 @@ pub(super) async fn handle_get_sandbox_provider_environment( // Update config handler (policy + settings mutations) // --------------------------------------------------------------------------- -fn validate_live_policy_update_support( - driver_kind: Option, - has_policy: bool, - has_merge_ops: bool, -) -> Result<(), Status> { - if (has_policy || has_merge_ops) && driver_kind == Some(openshell_core::ComputeDriverKind::Mxc) - { - return Err(Status::failed_precondition( - "live policy updates are not supported for MXC sandboxes; recreate the sandbox so the new policy is mapped before launch", - )); - } - Ok(()) -} - pub(super) async fn handle_update_config( state: &Arc, request: Request, @@ -3223,7 +3209,6 @@ async fn handle_update_config_inner( "one of policy, setting_key, or merge_operations must be provided", )); } - validate_live_policy_update_support(state.compute.driver_kind(), has_policy, has_merge_ops)?; if req.global { if !req.annotations.is_empty() { return Err(Status::invalid_argument( @@ -6911,27 +6896,6 @@ mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use tonic::Code; - #[test] - fn mxc_rejects_sandbox_policy_replacement_and_merge_updates() { - for (has_policy, has_merge_ops) in [(true, false), (false, true)] { - let error = validate_live_policy_update_support( - Some(openshell_core::ComputeDriverKind::Mxc), - has_policy, - has_merge_ops, - ) - .expect_err("MXC must reject policy mutations after launch"); - assert_eq!(error.code(), Code::FailedPrecondition); - } - - let error = validate_live_policy_update_support( - Some(openshell_core::ComputeDriverKind::Mxc), - true, - false, - ) - .expect_err("global policy replacement also changes desired state for live MXC sandboxes"); - assert_eq!(error.code(), Code::FailedPrecondition); - } - /// Wrap a request with a user `Principal` so handler scope guards treat /// the test caller as a CLI user. Most handler tests exercise /// user-facing behavior and should not trip sandbox equality checks. diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 35765781c4..764c0bbfde 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -11365,6 +11365,7 @@ mod tests { ..SandboxSpec::default() }), status: None, + ..Sandbox::default() }; sandbox.set_phase(SandboxPhase::Ready as i32); store.put_message(&sandbox).await.unwrap(); @@ -11401,6 +11402,7 @@ mod tests { }), spec: Some(SandboxSpec::default()), status: None, + ..Sandbox::default() }; sandbox.set_phase(SandboxPhase::Ready as i32); store.put_message(&sandbox).await.unwrap(); diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index de658909b0..d4d08da251 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -16,24 +16,29 @@ use crate::auth::workspace_authz::{ use crate::persistence::{ObjectLabels, ObjectType, WriteCondition, generate_name}; use futures::future; use openshell_core::net::set_tcp_nodelay_best_effort; +use openshell_core::proto::datamodel::v1::ObjectMeta; use openshell_core::proto::{ AttachSandboxProviderRequest, AttachSandboxProviderResponse, CreateSandboxRequest, - CreateSshSessionRequest, CreateSshSessionResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DetachSandboxProviderRequest, DetachSandboxProviderResponse, ExecSandboxEvent, ExecSandboxExit, - ExecSandboxInput, ExecSandboxRequest, ExecSandboxStderr, ExecSandboxStdout, GetSandboxRequest, - ListSandboxProvidersRequest, ListSandboxProvidersResponse, ListSandboxesRequest, - ListSandboxesResponse, Provider, RevokeSshSessionRequest, RevokeSshSessionResponse, - SandboxResponse, SandboxStreamEvent, SshRelayTarget, StartSandboxRequest, StopSandboxRequest, + CreateSandboxTemplateRequest, CreateSshSessionRequest, CreateSshSessionResponse, + DeleteSandboxRequest, DeleteSandboxResponse, DeleteSandboxTemplateRequest, + DeleteSandboxTemplateResponse, DetachSandboxProviderRequest, DetachSandboxProviderResponse, + ExecSandboxEvent, ExecSandboxExit, ExecSandboxInput, ExecSandboxRequest, ExecSandboxStderr, + ExecSandboxStdout, GetSandboxRequest, GetSandboxTemplateRequest, ListSandboxProvidersRequest, + ListSandboxProvidersResponse, ListSandboxTemplatesRequest, ListSandboxTemplatesResponse, + ListSandboxesRequest, ListSandboxesResponse, Provider, ResourceRequirements, + RevokeSshSessionRequest, RevokeSshSessionResponse, SandboxResources, SandboxResponse, + SandboxSpec, SandboxStreamEvent, SandboxTemplateResponse, SandboxWorkloadTemplate, + SandboxWorkloadTemplateProvenance, SshRelayTarget, StartSandboxRequest, StopSandboxRequest, TcpForwardFrame, TcpForwardInit, TcpRelayTarget, WatchSandboxRequest, relay_open, tcp_forward_init, }; use openshell_core::proto::{Sandbox, SandboxPhase, SandboxTemplate, SshSession}; use openshell_core::telemetry::{ - LifecycleOperation, LifecycleResource, SandboxTemplateSource, TelemetryComputeDriver, - TelemetryOutcome, + LifecycleOperation, LifecycleResource, SandboxTemplateSource, TelemetryOutcome, }; -use openshell_core::{ObjectId, ObjectName, ObjectWorkspace}; +use openshell_core::{GetResourceVersion, ObjectId, ObjectName, ObjectWorkspace}; use prost::Message; +use prost_types::{Struct, Value, value::Kind}; use std::collections::HashMap; use std::net::IpAddr; use std::pin::Pin; @@ -53,14 +58,16 @@ use super::provider::{ get_provider_record, is_valid_env_key, validate_provider_environment_keys_unique_with_catalog, }; use super::validation::{ - level_matches, source_matches, validate_exec_request_fields, - validate_no_reserved_provider_policy_keys, validate_policy_safety, validate_sandbox_spec, + level_matches, source_matches, validate_dns1123_label, validate_exec_request_fields, + validate_no_reserved_provider_policy_keys, validate_policy_safety, + validate_sandbox_governance_spec, validate_sandbox_spec, }; use super::{MAX_PAGE_SIZE, MAX_PROVIDERS, MAX_ROUTABLE_NAME_LEN, clamp_limit}; use crate::persistence::current_time_ms; const TCP_FORWARD_CHUNK_SIZE: usize = 64 * 1024; const NO_LOGIN_SHELL_ENV: (&str, &str) = ("OPENSHELL_NO_LOGIN_SHELL", "1"); +const MAX_TEMPLATES_PER_WORKSPACE: u32 = 1000; #[derive(Debug)] pub struct WatchSandboxStream { @@ -159,30 +166,69 @@ pub(super) async fn handle_create_sandbox( ) -> Result, Status> { let create_request = request.get_ref().clone(); let result = handle_create_sandbox_inner(state, request).await; + let created_sandbox = result + .as_ref() + .ok() + .and_then(|response| response.get_ref().sandbox.as_ref()); emit_sandbox_create_telemetry( state, &create_request, + created_sandbox, TelemetryOutcome::from_success(result.is_ok()), ); result } +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct SandboxCreateTelemetryAttrs { + requested_gpu: bool, + provider_count: u64, + has_custom_policy: bool, + template_source: SandboxTemplateSource, +} + fn emit_sandbox_create_telemetry( state: &Arc, request: &CreateSandboxRequest, + created_sandbox: Option<&Sandbox>, outcome: TelemetryOutcome, ) { - let compute_driver = telemetry_compute_driver(state.compute.driver_kind()); + let compute_driver = state.compute.telemetry_compute_driver(); + let attrs = sandbox_create_telemetry_attrs(request, created_sandbox); + openshell_core::telemetry::emit_sandbox_create( + outcome, + attrs.requested_gpu, + attrs.provider_count, + attrs.has_custom_policy, + attrs.template_source, + compute_driver, + ); +} + +fn sandbox_create_telemetry_attrs( + request: &CreateSandboxRequest, + created_sandbox: Option<&Sandbox>, +) -> SandboxCreateTelemetryAttrs { + if !request.workload_template_name.trim().is_empty() { + let spec = created_sandbox + .and_then(|sandbox| sandbox.spec.as_ref()) + .or(request.spec.as_ref()); + return SandboxCreateTelemetryAttrs { + requested_gpu: spec.is_some_and(|spec| { + openshell_core::gpu::sandbox_gpu_requested(spec.resource_requirements.as_ref()) + }), + provider_count: spec.map_or(0, |spec| spec.providers.len() as u64), + has_custom_policy: spec.is_some_and(|spec| spec.policy.is_some()), + template_source: SandboxTemplateSource::WorkloadTemplate, + }; + } let Some(spec) = request.spec.as_ref() else { - openshell_core::telemetry::emit_sandbox_create( - outcome, - false, - 0, - false, - SandboxTemplateSource::Undefined, - compute_driver, - ); - return; + return SandboxCreateTelemetryAttrs { + requested_gpu: false, + provider_count: 0, + has_custom_policy: false, + template_source: SandboxTemplateSource::Undefined, + }; }; let template_source = if spec .template @@ -195,20 +241,12 @@ fn emit_sandbox_create_telemetry( }; let gpu_requested = openshell_core::gpu::sandbox_gpu_requested(spec.resource_requirements.as_ref()); - openshell_core::telemetry::emit_sandbox_create( - outcome, - gpu_requested, - spec.providers.len() as u64, - spec.policy.is_some(), + SandboxCreateTelemetryAttrs { + requested_gpu: gpu_requested, + provider_count: spec.providers.len() as u64, + has_custom_policy: spec.policy.is_some(), template_source, - compute_driver, - ); -} - -fn telemetry_compute_driver( - driver_kind: Option, -) -> TelemetryComputeDriver { - TelemetryComputeDriver::from_driver_kind(driver_kind) + } } async fn handle_create_sandbox_inner( @@ -218,27 +256,9 @@ async fn handle_create_sandbox_inner( let principal = super::extract_principal(&request)?; let request = request.into_inner(); let await_main_process_attachment = request.await_main_process_attachment; - let mut spec = request - .spec - .ok_or_else(|| Status::invalid_argument("spec is required"))?; - - // Every newly persisted sandbox has one explicit canonical process. This - // portable default also preserves compatibility with callers compiled - // before the main-process field was introduced. - if spec.command.is_empty() { - spec.command = vec!["/bin/bash".to_string(), "-l".to_string()]; - spec.tty = true; - } - - // Validate field sizes before any I/O (fail fast on oversized payloads). - validate_sandbox_spec(&request.name, &spec)?; + let workload_template_name = request.workload_template_name.trim().to_string(); - // Validate labels (keys and values must meet Kubernetes requirements). - for (key, value) in &request.labels { - crate::grpc::validation::validate_label_key(key)?; - crate::grpc::validation::validate_label_value(value)?; - } - crate::grpc::validation::validate_annotations(&request.annotations, "annotations")?; + validate_create_sandbox_request_pre_io(&request, &workload_template_name)?; let authz = authorize_workspace( &state.store, @@ -252,6 +272,42 @@ async fn handle_create_sandbox_inner( .await? .ensure_active()?; + let (mut spec, created_from_workload_template) = if workload_template_name.is_empty() { + let spec = request + .spec + .ok_or_else(|| Status::invalid_argument("spec is required"))?; + (spec, None) + } else { + let governance_spec = request.spec.unwrap_or_default(); + let template = state + .store + .get_message_by_name::(&workspace, &workload_template_name) + .await + .map_err(|e| Status::internal(format!("fetch sandbox template failed: {e}")))? + .ok_or_else(|| Status::not_found("sandbox template not found"))?; + let provenance = SandboxWorkloadTemplateProvenance { + name: template.object_name().to_string(), + resource_version: template.get_resource_version().to_string(), + }; + let mut resolved = sandbox_spec_from_stored_workload_template(&template)?; + resolved.policy = governance_spec.policy; + resolved.providers = governance_spec.providers; + resolved.command = governance_spec.command; + resolved.tty = governance_spec.tty; + (resolved, Some(provenance)) + }; + + // Every newly persisted sandbox has one explicit canonical process. This + // portable default also preserves compatibility with callers compiled + // before the main-process field was introduced. + if spec.command.is_empty() { + spec.command = vec!["/bin/bash".to_string(), "-l".to_string()]; + spec.tty = true; + } + + // Validate field sizes before any create-side effects. + validate_sandbox_spec(&request.name, &spec)?; + let _sandbox_sync_guard = if spec.providers.is_empty() { None } else { @@ -281,7 +337,7 @@ async fn handle_create_sandbox_inner( // Ensure the template always carries the resolved image. let template = spec.template.get_or_insert_with(SandboxTemplate::default); - if template.image.is_empty() { + if template.image.trim().is_empty() { template.image = state.compute.default_image().to_string(); } @@ -309,7 +365,7 @@ async fn handle_create_sandbox_inner( let now_ms = current_time_ms(); let mut sandbox = Sandbox { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + metadata: Some(ObjectMeta { id: id.clone(), name: name.clone(), created_at_ms: now_ms, @@ -321,6 +377,7 @@ async fn handle_create_sandbox_inner( }), spec: Some(spec), status: None, + created_from_workload_template, }; sandbox.set_phase(SandboxPhase::Provisioning as i32); @@ -347,11 +404,8 @@ async fn handle_create_sandbox_inner( status })?; - // Mint the gateway JWT for singleplayer drivers. K8s sandboxes skip - // this mint and bootstrap via `IssueSandboxToken` at supervisor - // startup; identifying "is this K8s?" lives in the compute layer, so - // we mint unconditionally here when the issuer is configured and let - // the K8s driver simply ignore the field. + // Mint a gateway JWT whenever the issuer is configured. Compute runtimes + // that bootstrap through another authentication mechanism may ignore it. let sandbox_token = state.sandbox_jwt_issuer.as_ref().map(|issuer| { issuer.mint(&id).map(|minted| { tracing::info!( @@ -382,6 +436,135 @@ async fn handle_create_sandbox_inner( })) } +fn validate_create_sandbox_request_pre_io( + request: &CreateSandboxRequest, + workload_template_name: &str, +) -> Result<(), Status> { + // Validate labels (keys and values must meet Kubernetes requirements). + for (key, value) in &request.labels { + crate::grpc::validation::validate_label_key(key)?; + crate::grpc::validation::validate_label_value(value)?; + } + crate::grpc::validation::validate_annotations(&request.annotations, "annotations")?; + + if workload_template_name.is_empty() { + let spec = request + .spec + .as_ref() + .ok_or_else(|| Status::invalid_argument("spec is required"))?; + return validate_sandbox_spec(&request.name, spec); + } + + validate_dns1123_label(workload_template_name, "workload_template_name")?; + if let Some(spec) = request.spec.as_ref() { + validate_template_create_governance_spec(spec)?; + validate_sandbox_governance_spec(&request.name, spec)?; + } else { + validate_sandbox_governance_spec(&request.name, &SandboxSpec::default())?; + } + Ok(()) +} + +fn validate_template_create_governance_spec(spec: &SandboxSpec) -> Result<(), Status> { + if !spec.log_level.is_empty() { + return Err(Status::invalid_argument( + "spec.log_level cannot be set when workload_template_name is set", + )); + } + if !spec.environment.is_empty() { + return Err(Status::invalid_argument( + "spec.environment cannot be set when workload_template_name is set", + )); + } + if spec.template.is_some() { + return Err(Status::invalid_argument( + "spec.template cannot be set when workload_template_name is set", + )); + } + if spec.resource_requirements.is_some() { + return Err(Status::invalid_argument( + "spec.resource_requirements cannot be set when workload_template_name is set", + )); + } + Ok(()) +} + +fn sandbox_spec_from_stored_workload_template( + template: &SandboxWorkloadTemplate, +) -> Result { + sandbox_spec_from_workload_template(template, tonic::Code::Internal) +} + +fn sandbox_spec_from_user_workload_template( + template: &SandboxWorkloadTemplate, +) -> Result { + sandbox_spec_from_workload_template(template, tonic::Code::InvalidArgument) +} + +fn sandbox_spec_from_workload_template( + template: &SandboxWorkloadTemplate, + missing_field_code: tonic::Code, +) -> Result { + let spec = template + .spec + .as_ref() + .ok_or_else(|| Status::new(missing_field_code, "sandbox template spec is required"))?; + let workload = spec + .workload + .as_ref() + .ok_or_else(|| Status::new(missing_field_code, "sandbox template workload is required"))?; + let resources = workload.resources.as_ref(); + Ok(SandboxSpec { + environment: workload.environment.clone(), + template: Some(SandboxTemplate { + image: workload.image.clone(), + resources: resources.and_then(template_resource_struct), + driver_config: spec.driver_config.clone(), + ..SandboxTemplate::default() + }), + resource_requirements: resources.and_then(template_gpu_requirements), + ..SandboxSpec::default() + }) +} + +fn template_gpu_requirements(resources: &SandboxResources) -> Option { + Some(ResourceRequirements { + gpu: Some(resources.gpu?), + }) +} + +fn template_resource_struct(resources: &SandboxResources) -> Option { + let mut limits = std::collections::BTreeMap::new(); + if !resources.cpu.is_empty() { + limits.insert( + "cpu".to_string(), + Value { + kind: Some(Kind::StringValue(resources.cpu.clone())), + }, + ); + } + if !resources.memory.is_empty() { + limits.insert( + "memory".to_string(), + Value { + kind: Some(Kind::StringValue(resources.memory.clone())), + }, + ); + } + if limits.is_empty() { + None + } else { + let mut fields = std::collections::BTreeMap::new(); + fields.insert( + "limits".to_string(), + Value { + kind: Some(Kind::StructValue(Struct { fields: limits })), + }, + ); + Some(Struct { fields }) + } +} + pub(super) async fn handle_get_sandbox( state: &Arc, request: Request, @@ -482,66 +665,346 @@ pub(super) async fn handle_list_sandboxes( Ok(Response::new(ListSandboxesResponse { sandboxes })) } -pub(super) async fn handle_list_sandbox_providers( +pub(super) async fn handle_create_sandbox_template( state: &Arc, - request: Request, -) -> Result, Status> { + request: Request, +) -> Result, Status> { let principal = super::extract_principal(&request)?; let req = request.into_inner(); + let template = req + .template + .ok_or_else(|| Status::invalid_argument("template is required"))?; + let metadata = template.metadata.clone().unwrap_or_default(); let authz = authorize_workspace( &state.store, &state.admin_role, &principal, &req.workspace, - MinWorkspaceRole::User, + MinWorkspaceRole::Admin, ) .await?; let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? - .name; - let sandbox = sandbox_by_name(state, &workspace, &req.sandbox_name).await?; - let providers = providers_for_sandbox(state, &sandbox, &workspace).await?; - Ok(Response::new(ListSandboxProvidersResponse { providers })) + .ensure_active()?; + if !metadata.workspace.is_empty() && metadata.workspace != workspace { + return Err(Status::invalid_argument( + "template.metadata.workspace must match request workspace", + )); + } + if metadata.name.is_empty() { + return Err(Status::invalid_argument( + "template.metadata.name is required", + )); + } + + let mut resolved = template; + resolved.metadata = Some(ObjectMeta { + id: uuid::Uuid::new_v4().to_string(), + name: metadata.name, + created_at_ms: current_time_ms(), + labels: metadata.labels, + resource_version: 0, + annotations: metadata.annotations, + workspace: workspace.clone(), + deletion_timestamp_ms: 0, + }); + validate_sandbox_workload_template(&resolved)?; + + let labels_map = resolved.object_labels(); + let labels_json = if labels_map.as_ref().is_none_or(HashMap::is_empty) { + None + } else { + Some( + serde_json::to_string(&labels_map) + .map_err(|e| Status::internal(format!("failed to serialize labels: {e}")))?, + ) + }; + let write = state + .store + .create_if_workspace_count_below( + SandboxWorkloadTemplate::object_type(), + resolved.object_id(), + resolved.object_name(), + &workspace, + &resolved.encode_to_vec(), + labels_json.as_deref(), + u64::from(MAX_TEMPLATES_PER_WORKSPACE), + ) + .await; + let write = match write { + Ok(Some(write)) => write, + Ok(None) => { + return Err(Status::resource_exhausted(format!( + "workspace has reached the maximum of {MAX_TEMPLATES_PER_WORKSPACE} sandbox templates" + ))); + } + Err(crate::persistence::PersistenceError::UniqueViolation { .. }) => { + return Err(Status::already_exists("sandbox template already exists")); + } + Err(err) => { + return Err(Status::internal(format!( + "persist sandbox template failed: {err}" + ))); + } + }; + if let Some(metadata) = resolved.metadata.as_mut() { + metadata.resource_version = write.resource_version; + } + + Ok(Response::new(SandboxTemplateResponse { + template: Some(resolved), + })) } -pub(super) async fn handle_attach_sandbox_provider( +pub(super) async fn handle_get_sandbox_template( state: &Arc, - request: Request, -) -> Result, Status> { + request: Request, +) -> Result, Status> { let principal = super::extract_principal(&request)?; - let request = request.into_inner(); + let req = request.into_inner(); + if req.name.is_empty() { + return Err(Status::invalid_argument("name is required")); + } let authz = authorize_workspace( &state.store, &state.admin_role, &principal, - &request.workspace, + &req.workspace, MinWorkspaceRole::User, ) .await?; let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) .await? - .ensure_active()?; - if request.provider_name.is_empty() { - return Err(Status::invalid_argument("provider_name is required")); - } + .name; + let template = state + .store + .get_message_by_name::(&workspace, &req.name) + .await + .map_err(|e| Status::internal(format!("fetch sandbox template failed: {e}")))? + .ok_or_else(|| Status::not_found("sandbox template not found"))?; + Ok(Response::new(SandboxTemplateResponse { + template: Some(template), + })) +} - // Validate provider name would not violate sandbox spec constraints if added - // (pre-validation ensures CAS mutations preserve invariants) - if request.provider_name.len() > super::MAX_NAME_LEN { - return Err(Status::invalid_argument(format!( - "provider_name exceeds maximum length ({} > {})", - request.provider_name.len(), - super::MAX_NAME_LEN - ))); +pub(super) async fn handle_list_sandbox_templates( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let request = request.into_inner(); + if request.all_workspaces && !request.workspace.is_empty() { + return Err(Status::invalid_argument( + "all_workspaces and workspace are mutually exclusive", + )); } + let limit = clamp_limit(request.limit, 100, MAX_PAGE_SIZE); + let templates = if request.all_workspaces { + require_platform_admin(&state.admin_role, &principal)?; + if request.label_selector.is_empty() { + state + .store + .list_all_messages::(limit, request.offset) + .await + .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))? + } else { + crate::grpc::validation::validate_label_selector(&request.label_selector)?; + state + .store + .list_all_messages_with_selector::( + &request.label_selector, + limit, + request.offset, + ) + .await + .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))? + } + } else { + let authz = authorize_workspace( + &state.store, + &state.admin_role, + &principal, + &request.workspace, + MinWorkspaceRole::User, + ) + .await?; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + if request.label_selector.is_empty() { + state + .store + .list_messages::(&workspace, limit, request.offset) + .await + .map_err(|e| Status::internal(format!("list sandbox templates failed: {e}")))? + } else { + crate::grpc::validation::validate_label_selector(&request.label_selector)?; + state + .store + .list_messages_with_selector::( + &workspace, + &request.label_selector, + limit, + request.offset, + ) + .await + .map_err(|e| { + Status::internal(format!("list sandbox templates with selector failed: {e}")) + })? + } + }; + Ok(Response::new(ListSandboxTemplatesResponse { templates })) +} - get_provider_record(state.store.as_ref(), &workspace, &request.provider_name) +pub(super) async fn handle_delete_sandbox_template( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + if req.name.is_empty() { + return Err(Status::invalid_argument("name is required")); + } + let authz = authorize_workspace( + &state.store, + &state.admin_role, + &principal, + &req.workspace, + MinWorkspaceRole::Admin, + ) + .await?; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + let deleted = state + .store + .delete_by_name( + SandboxWorkloadTemplate::object_type(), + &workspace, + &req.name, + ) .await - .map_err(|err| { - if err.code() == tonic::Code::NotFound { - Status::failed_precondition(format!( - "provider '{}' not found", - request.provider_name + .map_err(|e| Status::internal(format!("delete sandbox template failed: {e}")))?; + Ok(Response::new(DeleteSandboxTemplateResponse { deleted })) +} + +fn validate_sandbox_workload_template(template: &SandboxWorkloadTemplate) -> Result<(), Status> { + super::validation::validate_object_metadata(template.metadata.as_ref(), "sandbox_template")?; + let name = template.object_name().to_string(); + validate_dns1123_label(&name, "template.metadata.name")?; + validate_sandbox_workload_template_service_level(template)?; + let spec = sandbox_spec_from_user_workload_template(template)?; + validate_sandbox_spec(&name, &spec)?; + Ok(()) +} + +fn validate_sandbox_workload_template_service_level( + template: &SandboxWorkloadTemplate, +) -> Result<(), Status> { + let Some(startup) = template + .spec + .as_ref() + .and_then(|spec| spec.desired_service_level.as_ref()) + .and_then(|service_level| service_level.startup.as_ref()) + else { + return Ok(()); + }; + if let Some(ready_within) = &startup.ready_within { + validate_positive_normalized_duration( + ready_within, + "template.spec.desired_service_level.startup.ready_within", + )?; + } + Ok(()) +} + +fn validate_positive_normalized_duration( + duration: &prost_types::Duration, + field: &str, +) -> Result<(), Status> { + const MAX_DURATION_SECONDS: u64 = 315_576_000_000; + if duration.seconds.unsigned_abs() > MAX_DURATION_SECONDS + || duration.nanos.unsigned_abs() >= 1_000_000_000 + { + return Err(Status::invalid_argument(format!( + "{field} must be a valid protobuf Duration" + ))); + } + if (duration.seconds > 0 && duration.nanos < 0) || (duration.seconds < 0 && duration.nanos > 0) + { + return Err(Status::invalid_argument(format!( + "{field} must be a normalized protobuf Duration" + ))); + } + if duration.seconds < 0 || duration.nanos < 0 || (duration.seconds == 0 && duration.nanos == 0) + { + return Err(Status::invalid_argument(format!( + "{field} must be greater than zero" + ))); + } + Ok(()) +} + +pub(super) async fn handle_list_sandbox_providers( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let req = request.into_inner(); + let authz = authorize_workspace( + &state.store, + &state.admin_role, + &principal, + &req.workspace, + MinWorkspaceRole::User, + ) + .await?; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .name; + let sandbox = sandbox_by_name(state, &workspace, &req.sandbox_name).await?; + let providers = providers_for_sandbox(state, &sandbox, &workspace).await?; + Ok(Response::new(ListSandboxProvidersResponse { providers })) +} + +pub(super) async fn handle_attach_sandbox_provider( + state: &Arc, + request: Request, +) -> Result, Status> { + let principal = super::extract_principal(&request)?; + let request = request.into_inner(); + let authz = authorize_workspace( + &state.store, + &state.admin_role, + &principal, + &request.workspace, + MinWorkspaceRole::User, + ) + .await?; + let workspace = super::workspace::resolve_workspace(state.store.as_ref(), &authz.workspace) + .await? + .ensure_active()?; + if request.provider_name.is_empty() { + return Err(Status::invalid_argument("provider_name is required")); + } + + // Validate provider name would not violate sandbox spec constraints if added + // (pre-validation ensures CAS mutations preserve invariants) + if request.provider_name.len() > super::MAX_NAME_LEN { + return Err(Status::invalid_argument(format!( + "provider_name exceeds maximum length ({} > {})", + request.provider_name.len(), + super::MAX_NAME_LEN + ))); + } + + get_provider_record(state.store.as_ref(), &workspace, &request.provider_name) + .await + .map_err(|err| { + if err.code() == tonic::Code::NotFound { + Status::failed_precondition(format!( + "provider '{}' not found", + request.provider_name )) } else { err @@ -1763,7 +2226,7 @@ pub(super) async fn handle_create_ssh_session( 0 }; let session = SshSession { - metadata: Some(openshell_core::proto::datamodel::v1::ObjectMeta { + metadata: Some(ObjectMeta { id: token.clone(), name: generate_name(), created_at_ms: now_ms, @@ -2542,6 +3005,7 @@ mod tests { }; use crate::provider_profile_sources::ProviderProfileSources; use openshell_core::GatewayProviderProfileSourceConfig; + use openshell_core::proto::GpuResourceRequirements; use openshell_core::proto::datamodel::v1::ObjectMeta; async fn test_server_state_with_user_only_github_profile() -> Arc { @@ -2601,26 +3065,62 @@ mod tests { } #[test] - fn telemetry_compute_driver_uses_resolved_driver_kind() { - assert_eq!( - telemetry_compute_driver(Some(openshell_core::ComputeDriverKind::Docker)), - TelemetryComputeDriver::Docker - ); - assert_eq!( - telemetry_compute_driver(Some(openshell_core::ComputeDriverKind::Kubernetes)), - TelemetryComputeDriver::Kubernetes - ); - assert_eq!( - telemetry_compute_driver(Some(openshell_core::ComputeDriverKind::Podman)), - TelemetryComputeDriver::Podman - ); + fn sandbox_create_telemetry_uses_resolved_template_gpu_request() { + let request = CreateSandboxRequest { + spec: Some(SandboxSpec { + providers: vec!["github".to_string()], + policy: Some(openshell_core::proto::SandboxPolicy::default()), + ..SandboxSpec::default() + }), + workload_template_name: "gpu-kata".to_string(), + ..CreateSandboxRequest::default() + }; + let created = Sandbox { + spec: Some(SandboxSpec { + providers: vec!["github".to_string()], + policy: Some(openshell_core::proto::SandboxPolicy::default()), + resource_requirements: Some(ResourceRequirements { + gpu: Some(GpuResourceRequirements { count: Some(1) }), + }), + ..SandboxSpec::default() + }), + created_from_workload_template: Some(SandboxWorkloadTemplateProvenance { + name: "gpu-kata".to_string(), + resource_version: "7".to_string(), + }), + ..Sandbox::default() + }; + assert_eq!( - telemetry_compute_driver(Some(openshell_core::ComputeDriverKind::Vm)), - TelemetryComputeDriver::Vm + sandbox_create_telemetry_attrs(&request, Some(&created)), + SandboxCreateTelemetryAttrs { + requested_gpu: true, + provider_count: 1, + has_custom_policy: true, + template_source: SandboxTemplateSource::WorkloadTemplate, + } ); + } + + #[test] + fn sandbox_create_telemetry_falls_back_to_request_for_unresolved_template() { + let request = CreateSandboxRequest { + spec: Some(SandboxSpec { + providers: vec!["github".to_string()], + ..SandboxSpec::default() + }), + workload_template_name: "missing-template".to_string(), + ..CreateSandboxRequest::default() + }; + assert_eq!( - telemetry_compute_driver(None), - TelemetryComputeDriver::Unknown + sandbox_create_telemetry_attrs(&request, None), + SandboxCreateTelemetryAttrs { + requested_gpu: false, + provider_count: 1, + has_custom_policy: false, + template_source: SandboxTemplateSource::WorkloadTemplate, + } ); } @@ -2933,7 +3433,7 @@ mod tests { workspace: "default".to_string(), deletion_timestamp_ms: 0, }), - spec: Some(openshell_core::proto::SandboxSpec { + spec: Some(SandboxSpec { log_level: "debug".to_string(), policy: Some(openshell_core::proto::SandboxPolicy::default()), providers, @@ -2946,6 +3446,41 @@ mod tests { sandbox } + fn test_workload_template(name: &str) -> SandboxWorkloadTemplate { + SandboxWorkloadTemplate { + metadata: Some(ObjectMeta { + id: String::new(), + name: name.to_string(), + created_at_ms: 0, + labels: HashMap::from([("team".to_string(), "runtime".to_string())]), + resource_version: 0, + annotations: HashMap::new(), + workspace: String::new(), + deletion_timestamp_ms: 0, + }), + spec: Some(openshell_core::proto::SandboxWorkloadTemplateSpec { + workload: Some(openshell_core::proto::SandboxWorkloadConfig { + image: "registry.example.com/agent:latest".to_string(), + environment: HashMap::from([("FEATURE_FLAG".to_string(), "on".to_string())]), + resources: Some(SandboxResources { + cpu: "2".to_string(), + memory: "4Gi".to_string(), + gpu: Some(GpuResourceRequirements { count: Some(1) }), + }), + }), + driver_config: None, + desired_service_level: None, + }), + } + } + + fn proto_string_value(value: &Value) -> Option<&str> { + match value.kind.as_ref() { + Some(Kind::StringValue(value)) => Some(value.as_str()), + _ => None, + } + } + #[tokio::test] #[ignore = "flaky under concurrent test execution"] async fn watch_producer_releases_request_span_when_client_disconnects() { @@ -3505,7 +4040,7 @@ mod tests { &state, authed_request(CreateSandboxRequest { name: "collision".to_string(), - spec: Some(openshell_core::proto::SandboxSpec { + spec: Some(SandboxSpec { providers: vec!["provider-a".to_string(), "provider-b".to_string()], ..Default::default() }), @@ -3513,6 +4048,7 @@ mod tests { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3532,11 +4068,12 @@ mod tests { &state, authed_request(CreateSandboxRequest { name: "user-catalog".to_string(), - spec: Some(openshell_core::proto::SandboxSpec::default()), + spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3565,7 +4102,7 @@ mod tests { &state, authed_request(CreateSandboxRequest { name: "reserved-policy-key".to_string(), - spec: Some(openshell_core::proto::SandboxSpec { + spec: Some(SandboxSpec { policy: Some(policy), ..Default::default() }), @@ -3573,6 +4110,7 @@ mod tests { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3593,11 +4131,12 @@ mod tests { &state, authed_request(CreateSandboxRequest { name: "annotated".to_string(), - spec: Some(openshell_core::proto::SandboxSpec::default()), + spec: Some(SandboxSpec::default()), labels: HashMap::new(), annotations: HashMap::from([(annotation_key.clone(), annotation_value.clone())]), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3636,8 +4175,7 @@ mod tests { #[tokio::test] async fn create_and_get_preserve_partial_process_identity() { - let state = - test_server_state_with_driver(openshell_core::ComputeDriverKind::Docker.as_str()).await; + let state = test_server_state_with_driver("docker").await; let policy = openshell_core::proto::SandboxPolicy { version: 1, process: Some(openshell_core::proto::ProcessPolicy { @@ -3651,7 +4189,7 @@ mod tests { &state, authed_request(CreateSandboxRequest { name: "partial-id".to_string(), - spec: Some(openshell_core::proto::SandboxSpec { + spec: Some(SandboxSpec { policy: Some(policy), ..Default::default() }), @@ -3659,6 +4197,7 @@ mod tests { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3701,9 +4240,7 @@ mod tests { #[tokio::test] async fn create_and_get_preserve_partial_process_identity_for_kubernetes() { - let state = - test_server_state_with_driver(openshell_core::ComputeDriverKind::Kubernetes.as_str()) - .await; + let state = test_server_state_with_driver("kubernetes").await; let policy = openshell_core::proto::SandboxPolicy { version: 1, process: Some(openshell_core::proto::ProcessPolicy { @@ -3717,7 +4254,7 @@ mod tests { &state, authed_request(CreateSandboxRequest { name: "kube-partial-id".to_string(), - spec: Some(openshell_core::proto::SandboxSpec { + spec: Some(SandboxSpec { policy: Some(policy), ..Default::default() }), @@ -3725,6 +4262,7 @@ mod tests { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3751,11 +4289,12 @@ mod tests { &state, authed_request(CreateSandboxRequest { name: "bad-label".to_string(), - spec: Some(openshell_core::proto::SandboxSpec::default()), + spec: Some(SandboxSpec::default()), labels: HashMap::from([("team".to_string(), "x".repeat(512))]), annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3781,7 +4320,7 @@ mod tests { &task_state, authed_request(CreateSandboxRequest { name: "guarded-create".to_string(), - spec: Some(openshell_core::proto::SandboxSpec { + spec: Some(SandboxSpec { providers: vec!["work-github".to_string()], ..Default::default() }), @@ -3789,6 +4328,7 @@ mod tests { annotations: HashMap::new(), workspace: String::new(), await_main_process_attachment: false, + workload_template_name: String::new(), }), ) .await @@ -3813,6 +4353,815 @@ mod tests { ); } + #[tokio::test] + async fn sandbox_template_handlers_create_get_list_and_delete_workspace_resource() { + let state = test_server_state().await; + + let created = handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(test_workload_template("gpu-kata")), + workspace: "default".to_string(), + }), + ) + .await + .expect("template create should succeed") + .into_inner() + .template + .expect("template response"); + + let metadata = created.metadata.as_ref().expect("metadata"); + assert_eq!(metadata.name, "gpu-kata"); + assert_eq!(metadata.workspace, "default"); + assert!(!metadata.id.is_empty()); + assert_ne!(metadata.resource_version, 0); + + let fetched = handle_get_sandbox_template( + &state, + authed_request(GetSandboxTemplateRequest { + name: "gpu-kata".to_string(), + workspace: "default".to_string(), + }), + ) + .await + .expect("template get should succeed") + .into_inner() + .template + .expect("fetched template"); + assert_eq!(fetched.object_name(), "gpu-kata"); + assert_eq!(fetched.object_workspace(), "default"); + + let listed = handle_list_sandbox_templates( + &state, + authed_request(ListSandboxTemplatesRequest { + limit: 100, + offset: 0, + workspace: "default".to_string(), + all_workspaces: false, + label_selector: String::new(), + }), + ) + .await + .expect("template list should succeed") + .into_inner() + .templates; + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].object_name(), "gpu-kata"); + + let deleted = handle_delete_sandbox_template( + &state, + authed_request(DeleteSandboxTemplateRequest { + name: "gpu-kata".to_string(), + workspace: "default".to_string(), + }), + ) + .await + .expect("template delete should succeed") + .into_inner(); + assert!(deleted.deleted); + + let missing = handle_get_sandbox_template( + &state, + authed_request(GetSandboxTemplateRequest { + name: "gpu-kata".to_string(), + workspace: "default".to_string(), + }), + ) + .await + .expect_err("deleted template should not be fetchable"); + assert_eq!(missing.code(), tonic::Code::NotFound); + } + + #[tokio::test] + async fn sandbox_template_list_filters_by_label_selector() { + let state = test_server_state().await; + + let mut gpu = test_workload_template("gpu-kata"); + gpu.metadata + .as_mut() + .expect("metadata") + .labels + .insert("team".to_string(), "runtime".to_string()); + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(gpu), + workspace: "default".to_string(), + }), + ) + .await + .expect("gpu template create should succeed"); + + let mut cpu = test_workload_template("cpu-base"); + cpu.metadata + .as_mut() + .expect("metadata") + .labels + .insert("team".to_string(), "batch".to_string()); + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(cpu), + workspace: "default".to_string(), + }), + ) + .await + .expect("cpu template create should succeed"); + + let listed = handle_list_sandbox_templates( + &state, + authed_request(ListSandboxTemplatesRequest { + limit: 100, + offset: 0, + workspace: "default".to_string(), + all_workspaces: false, + label_selector: "team=runtime".to_string(), + }), + ) + .await + .expect("template list with label selector should succeed") + .into_inner() + .templates; + + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].object_name(), "gpu-kata"); + } + + #[tokio::test] + async fn sandbox_template_create_rejects_whitespace_name() { + let state = test_server_state().await; + + let err = handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(test_workload_template(" gpu-kata ")), + workspace: "default".to_string(), + }), + ) + .await + .expect_err("template names must be canonical DNS-1123 labels"); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("template.metadata.name")); + + let listed = handle_list_sandbox_templates( + &state, + authed_request(ListSandboxTemplatesRequest { + limit: 100, + offset: 0, + workspace: "default".to_string(), + all_workspaces: false, + label_selector: String::new(), + }), + ) + .await + .expect("template list should succeed") + .into_inner() + .templates; + assert!(listed.is_empty()); + } + + #[tokio::test] + async fn sandbox_template_create_empty_workspace_ignores_metadata_workspace() { + use openshell_core::proto::CreateWorkspaceRequest; + + let state = test_server_state().await; + crate::grpc::workspace::handle_create_workspace( + &state, + Request::new(CreateWorkspaceRequest { + name: "beta".to_string(), + labels: HashMap::new(), + }), + ) + .await + .expect("beta workspace should be created"); + + let mut template = test_workload_template("copied-template"); + template.metadata.as_mut().unwrap().workspace = "beta".to_string(); + + let err = handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(template), + workspace: String::new(), + }), + ) + .await + .expect_err("empty request workspace must default to default, not metadata workspace"); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("template.metadata.workspace")); + + let listed = handle_list_sandbox_templates( + &state, + authed_request(ListSandboxTemplatesRequest { + limit: 100, + offset: 0, + workspace: "beta".to_string(), + all_workspaces: false, + label_selector: String::new(), + }), + ) + .await + .expect("template list should succeed") + .into_inner() + .templates; + assert!(listed.is_empty()); + } + + #[tokio::test] + async fn sandbox_template_create_rejects_missing_spec_as_invalid_argument() { + let state = test_server_state().await; + let mut template = test_workload_template("missing-spec"); + template.spec = None; + + let err = handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(template), + workspace: "default".to_string(), + }), + ) + .await + .expect_err("template create should reject missing spec"); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("sandbox template spec")); + } + + #[test] + fn sandbox_template_validation_allows_positive_ready_within() { + let mut template = test_workload_template("gpu-kata"); + template.metadata.as_mut().unwrap().id = "template-gpu-kata".to_string(); + template.spec.as_mut().unwrap().desired_service_level = + Some(openshell_core::proto::SandboxServiceLevel { + startup: Some(openshell_core::proto::SandboxStartup { + ready_within: Some(prost_types::Duration { + seconds: 1, + nanos: 0, + }), + max_burst: 1, + }), + }); + + validate_sandbox_workload_template(&template).expect("positive ready_within should pass"); + } + + #[test] + fn sandbox_template_validation_rejects_non_positive_ready_within() { + for (duration, expected) in [ + ( + prost_types::Duration { + seconds: 0, + nanos: 0, + }, + "greater than zero", + ), + ( + prost_types::Duration { + seconds: -1, + nanos: 0, + }, + "greater than zero", + ), + ( + prost_types::Duration { + seconds: 0, + nanos: -1, + }, + "greater than zero", + ), + ] { + let mut template = test_workload_template("gpu-kata"); + template.metadata.as_mut().unwrap().id = "template-gpu-kata".to_string(); + template.spec.as_mut().unwrap().desired_service_level = + Some(openshell_core::proto::SandboxServiceLevel { + startup: Some(openshell_core::proto::SandboxStartup { + ready_within: Some(duration), + max_burst: 1, + }), + }); + + let err = validate_sandbox_workload_template(&template) + .expect_err("non-positive ready_within should be rejected"); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains(expected), "{err:?}"); + assert!( + err.message() + .contains("template.spec.desired_service_level.startup.ready_within"), + "{err:?}" + ); + } + } + + #[test] + fn sandbox_template_validation_rejects_malformed_ready_within() { + for (duration, expected) in [ + ( + prost_types::Duration { + seconds: 1, + nanos: -1, + }, + "normalized", + ), + ( + prost_types::Duration { + seconds: 0, + nanos: 1_000_000_000, + }, + "valid protobuf Duration", + ), + ( + prost_types::Duration { + seconds: 315_576_000_001, + nanos: 0, + }, + "valid protobuf Duration", + ), + ] { + let mut template = test_workload_template("gpu-kata"); + template.metadata.as_mut().unwrap().id = "template-gpu-kata".to_string(); + template.spec.as_mut().unwrap().desired_service_level = + Some(openshell_core::proto::SandboxServiceLevel { + startup: Some(openshell_core::proto::SandboxStartup { + ready_within: Some(duration), + max_burst: 1, + }), + }); + + let err = validate_sandbox_workload_template(&template) + .expect_err("malformed ready_within should be rejected"); + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains(expected), "{err:?}"); + assert!( + err.message() + .contains("template.spec.desired_service_level.startup.ready_within"), + "{err:?}" + ); + } + } + + #[tokio::test] + async fn sandbox_template_create_rejects_workspace_quota() { + let state = test_server_state().await; + for index in 0..MAX_TEMPLATES_PER_WORKSPACE { + let mut template = test_workload_template(&format!("tmpl-{index}")); + let metadata = template.metadata.as_mut().expect("metadata"); + metadata.id = format!("template-{index}"); + metadata.workspace = "default".to_string(); + state.store.put_message(&template).await.unwrap(); + } + + let err = handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(test_workload_template("overflow")), + workspace: "default".to_string(), + }), + ) + .await + .expect_err("template create must reject a full workspace"); + + assert_eq!(err.code(), tonic::Code::ResourceExhausted); + assert!(err.message().contains("1000 sandbox templates")); + } + + #[tokio::test] + async fn sandbox_template_create_enforces_workspace_quota_concurrently() { + let state = test_server_state().await; + for index in 0..(MAX_TEMPLATES_PER_WORKSPACE - 1) { + let mut template = test_workload_template(&format!("tmpl-{index}")); + let metadata = template.metadata.as_mut().expect("metadata"); + metadata.id = format!("template-{index}"); + metadata.workspace = "default".to_string(); + state.store.put_message(&template).await.unwrap(); + } + + let mut handles = vec![]; + for index in 0..8 { + let state = Arc::clone(&state); + let handle = tokio::spawn(async move { + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(test_workload_template(&format!("overflow-{index}"))), + workspace: "default".to_string(), + }), + ) + .await + }); + handles.push(handle); + } + + let results: Vec<_> = future::join_all(handles) + .await + .into_iter() + .map(|r| r.unwrap()) + .collect(); + + let successes = results.iter().filter(|r| r.is_ok()).count(); + let exhausted = results + .iter() + .filter(|r| { + r.as_ref() + .err() + .is_some_and(|e| e.code() == tonic::Code::ResourceExhausted) + }) + .count(); + + assert_eq!(successes, 1); + assert_eq!(exhausted, 7); + let count = state + .store + .count_in_workspace(SandboxWorkloadTemplate::object_type(), "default") + .await + .unwrap(); + assert_eq!(count, u64::from(MAX_TEMPLATES_PER_WORKSPACE)); + } + + #[test] + fn template_create_sandbox_spec_field_policy_is_exhaustive() { + assert_proto_fields_classified( + "openshell.v1.SandboxSpec", + &["policy", "providers", "command", "tty"], + &[ + "log_level", + "environment", + "template", + "resource_requirements", + ], + ); + } + + fn assert_proto_fields_classified( + message_name: &str, + copied_from_create_request: &[&str], + rejected_template_workload_overrides: &[&str], + ) { + let pool = prost_reflect::DescriptorPool::decode(openshell_core::FILE_DESCRIPTOR_SET) + .expect("decode descriptor set"); + let message = pool + .get_message_by_name(message_name) + .expect("message descriptor"); + let classified: std::collections::HashSet<&str> = copied_from_create_request + .iter() + .chain(rejected_template_workload_overrides.iter()) + .copied() + .collect(); + let actual: std::collections::HashSet = message + .fields() + .map(|field| field.name().to_string()) + .collect(); + + for field in &actual { + assert!( + classified.contains(field.as_str()), + "{message_name}.{field} is not classified for template-backed sandbox creates. \ + Add it to copied_from_create_request when callers own the create-time value, \ + or to rejected_template_workload_overrides when the workload template owns it." + ); + } + + for field in classified { + assert!( + actual.contains(field), + "{message_name}.{field} is classified for template-backed sandbox creates, \ + but the proto field no longer exists" + ); + } + } + + #[tokio::test] + async fn create_sandbox_from_workload_template_resolves_workload_and_preserves_governance() { + let state = test_server_state().await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(test_workload_template("gpu-kata")), + workspace: "default".to_string(), + }), + ) + .await + .expect("template create should succeed"); + + let mut policy = openshell_core::proto::SandboxPolicy { + version: 1, + ..Default::default() + }; + policy.network_policies.insert( + "example".to_string(), + openshell_core::proto::NetworkPolicyRule { + name: "example".to_string(), + ..Default::default() + }, + ); + + let created = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "from-template".to_string(), + spec: Some(SandboxSpec { + providers: vec!["work-github".to_string()], + policy: Some(policy), + command: vec!["echo".to_string(), "template-create".to_string()], + tty: false, + ..Default::default() + }), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "default".to_string(), + workload_template_name: "gpu-kata".to_string(), + await_main_process_attachment: false, + }), + ) + .await + .expect("sandbox create from template should succeed") + .into_inner() + .sandbox + .expect("created sandbox"); + + let provenance = created + .created_from_workload_template + .expect("template provenance"); + assert_eq!(provenance.name, "gpu-kata"); + assert!(!provenance.resource_version.is_empty()); + + let spec = created.spec.expect("resolved sandbox spec"); + assert_eq!(spec.providers, vec!["work-github".to_string()]); + assert!(spec.policy.is_some()); + assert_eq!( + spec.command, + vec!["echo".to_string(), "template-create".to_string()] + ); + assert!(!spec.tty); + assert_eq!( + spec.environment.get("FEATURE_FLAG"), + Some(&"on".to_string()) + ); + + let template = spec.template.expect("resolved inline template"); + assert_eq!(template.image, "registry.example.com/agent:latest"); + let limits = template + .resources + .as_ref() + .and_then(|resources| resources.fields.get("limits")) + .and_then(|limits| limits.kind.as_ref()) + .and_then(|kind| match kind { + Kind::StructValue(value) => Some(&value.fields), + _ => None, + }) + .expect("resource limits"); + assert_eq!(limits.get("cpu").and_then(proto_string_value), Some("2")); + assert_eq!( + limits.get("memory").and_then(proto_string_value), + Some("4Gi") + ); + assert_eq!( + spec.resource_requirements + .and_then(|requirements| requirements.gpu) + .and_then(|gpu| gpu.count), + Some(1) + ); + } + + #[tokio::test] + async fn create_sandbox_from_workload_template_defaults_whitespace_image() { + let state = test_server_state().await; + let mut template = test_workload_template("default-image"); + template + .spec + .as_mut() + .and_then(|spec| spec.workload.as_mut()) + .expect("test template workload") + .image = " ".to_string(); + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(template), + workspace: "default".to_string(), + }), + ) + .await + .expect("template create should succeed"); + + let created = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "from-template".to_string(), + spec: Some(SandboxSpec::default()), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "default".to_string(), + workload_template_name: "default-image".to_string(), + await_main_process_attachment: false, + }), + ) + .await + .expect("sandbox create from template should succeed") + .into_inner() + .sandbox + .expect("created sandbox"); + + let image = created + .spec + .and_then(|spec| spec.template) + .map(|template| template.image) + .expect("resolved template image"); + assert_eq!(image, state.compute.default_image()); + } + + #[tokio::test] + async fn create_sandbox_from_workload_template_preserves_default_gpu_request() { + let state = test_server_state().await; + let mut template = test_workload_template("default-gpu"); + template + .spec + .as_mut() + .and_then(|spec| spec.workload.as_mut()) + .and_then(|workload| workload.resources.as_mut()) + .expect("test template resources") + .gpu = Some(GpuResourceRequirements { count: None }); + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(template), + workspace: "default".to_string(), + }), + ) + .await + .expect("template create should succeed"); + + let created = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "from-template".to_string(), + spec: Some(SandboxSpec::default()), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "default".to_string(), + workload_template_name: "default-gpu".to_string(), + await_main_process_attachment: false, + }), + ) + .await + .expect("sandbox create from template should succeed") + .into_inner() + .sandbox + .expect("created sandbox"); + + let gpu = created + .spec + .as_ref() + .and_then(|spec| spec.resource_requirements.as_ref()) + .and_then(|requirements| requirements.gpu.as_ref()) + .expect("default GPU request should be preserved"); + assert_eq!(gpu.count, None); + } + + #[tokio::test] + async fn create_sandbox_from_corrupted_workload_template_returns_internal() { + let state = test_server_state().await; + let mut template = test_workload_template("corrupt-template"); + let metadata = template.metadata.as_mut().expect("metadata"); + metadata.id = "template-corrupt-template".to_string(); + metadata.workspace = "default".to_string(); + template.spec = None; + state.store.put_message(&template).await.unwrap(); + + let err = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "from-corrupt".to_string(), + spec: Some(SandboxSpec::default()), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "default".to_string(), + workload_template_name: "corrupt-template".to_string(), + await_main_process_attachment: false, + }), + ) + .await + .expect_err("corrupted stored template should fail as server data corruption"); + + assert_eq!(err.code(), tonic::Code::Internal, "{}", err.message()); + assert!(err.message().contains("sandbox template spec")); + } + + #[tokio::test] + async fn create_sandbox_from_workload_template_rejects_inline_workload_overrides() { + let state = test_server_state().await; + handle_create_sandbox_template( + &state, + authed_request(CreateSandboxTemplateRequest { + template: Some(test_workload_template("gpu-kata")), + workspace: "default".to_string(), + }), + ) + .await + .expect("template create should succeed"); + + let err = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "bad-template-create".to_string(), + spec: Some(SandboxSpec { + environment: HashMap::from([("INLINE".to_string(), "blocked".to_string())]), + ..Default::default() + }), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "default".to_string(), + workload_template_name: "gpu-kata".to_string(), + await_main_process_attachment: false, + }), + ) + .await + .expect_err("inline workload overrides should be rejected"); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("spec.environment")); + } + + #[tokio::test] + async fn create_sandbox_from_workload_template_rejects_malformed_template_name() { + let state = test_server_state().await; + + let err = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "bad-template-create".to_string(), + spec: Some(SandboxSpec::default()), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "default".to_string(), + workload_template_name: "Invalid_Template_Name".to_string(), + await_main_process_attachment: false, + }), + ) + .await + .expect_err("malformed template name should be rejected before lookup"); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("workload_template_name")); + } + + #[tokio::test] + async fn create_sandbox_from_workload_template_rejects_oversized_governance_before_lookup() { + let state = test_server_state().await; + + let err = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "bad-template-create".to_string(), + spec: Some(SandboxSpec { + providers: (0..=MAX_PROVIDERS).map(|i| format!("p-{i}")).collect(), + ..Default::default() + }), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "default".to_string(), + workload_template_name: "missing-template".to_string(), + await_main_process_attachment: false, + }), + ) + .await + .expect_err("oversized governance spec should be rejected before template lookup"); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("providers")); + } + + #[tokio::test] + async fn create_sandbox_rejects_oversized_direct_spec_before_workspace_lookup() { + let state = test_server_state().await; + + let err = handle_create_sandbox( + &state, + authed_request(CreateSandboxRequest { + name: "bad-direct-create".to_string(), + spec: Some(SandboxSpec { + providers: (0..=MAX_PROVIDERS).map(|i| format!("p-{i}")).collect(), + ..Default::default() + }), + labels: HashMap::new(), + annotations: HashMap::new(), + workspace: "missing-workspace".to_string(), + workload_template_name: String::new(), + await_main_process_attachment: false, + }), + ) + .await + .expect_err("oversized direct spec should be rejected before workspace lookup"); + + assert_eq!(err.code(), tonic::Code::InvalidArgument); + assert!(err.message().contains("providers")); + } + #[tokio::test] async fn attach_sandbox_provider_rejects_credential_key_collisions() { let state = test_server_state().await; @@ -4715,7 +6064,7 @@ mod tests { &state, non_member_request(CreateSandboxRequest { workspace: "no-such-ws".into(), - spec: Some(openshell_core::proto::SandboxSpec::default()), + spec: Some(SandboxSpec::default()), ..Default::default() }), ) diff --git a/crates/openshell-server/src/grpc/validation.rs b/crates/openshell-server/src/grpc/validation.rs index eb53c80f29..c20dad7780 100644 --- a/crates/openshell-server/src/grpc/validation.rs +++ b/crates/openshell-server/src/grpc/validation.rs @@ -10,7 +10,7 @@ use openshell_core::proto::{ CredentialHandle, ExecSandboxRequest, Provider, SandboxPolicy as ProtoSandboxPolicy, - SandboxTemplate, + SandboxSpec, SandboxTemplate, }; use prost::Message; use tonic::Status; @@ -150,26 +150,12 @@ pub(super) fn validate_dns1123_label(name: &str, field: &str) -> Result<(), Stat /// Validate field sizes on a `CreateSandboxRequest` before persisting. /// /// Returns `INVALID_ARGUMENT` on the first field that exceeds its limit. -pub(super) fn validate_sandbox_spec( - name: &str, - spec: &openshell_core::proto::SandboxSpec, -) -> Result<(), Status> { +pub(super) fn validate_sandbox_spec(name: &str, spec: &SandboxSpec) -> Result<(), Status> { // --- request.name --- - if !name.is_empty() && name.len() > MAX_ROUTABLE_NAME_LEN { - return Err(Status::invalid_argument(format!( - "name exceeds maximum length ({} > {MAX_ROUTABLE_NAME_LEN})", - name.len() - ))); - } - validate_dns1123_label(name, "name")?; + validate_sandbox_name(name)?; // --- spec.providers --- - if spec.providers.len() > MAX_PROVIDERS { - return Err(Status::invalid_argument(format!( - "providers list exceeds maximum ({} > {MAX_PROVIDERS})", - spec.providers.len() - ))); - } + validate_sandbox_provider_count(spec)?; // --- spec.log_level --- if spec.log_level.len() > MAX_LOG_LEVEL_LEN { @@ -203,6 +189,45 @@ pub(super) fn validate_sandbox_spec( } // --- spec.policy serialized size --- + validate_sandbox_policy_size(spec)?; + + Ok(()) +} + +pub(super) fn validate_sandbox_governance_spec( + name: &str, + spec: &SandboxSpec, +) -> Result<(), Status> { + validate_sandbox_name(name)?; + validate_sandbox_provider_count(spec)?; + if !spec.command.is_empty() { + validate_main_process_command(&spec.command)?; + } + validate_sandbox_policy_size(spec)?; + Ok(()) +} + +fn validate_sandbox_name(name: &str) -> Result<(), Status> { + if !name.is_empty() && name.len() > MAX_ROUTABLE_NAME_LEN { + return Err(Status::invalid_argument(format!( + "name exceeds maximum length ({} > {MAX_ROUTABLE_NAME_LEN})", + name.len() + ))); + } + validate_dns1123_label(name, "name") +} + +fn validate_sandbox_provider_count(spec: &SandboxSpec) -> Result<(), Status> { + if spec.providers.len() > MAX_PROVIDERS { + return Err(Status::invalid_argument(format!( + "providers list exceeds maximum ({} > {MAX_PROVIDERS})", + spec.providers.len() + ))); + } + Ok(()) +} + +fn validate_sandbox_policy_size(spec: &SandboxSpec) -> Result<(), Status> { if let Some(ref policy) = spec.policy { let size = policy.encoded_len(); if size > MAX_POLICY_SIZE { @@ -244,7 +269,7 @@ fn validate_main_process_command(command: &[String]) -> Result<(), Status> { Ok(()) } -fn validate_gpu_request_fields(spec: &openshell_core::proto::SandboxSpec) -> Result<(), Status> { +fn validate_gpu_request_fields(spec: &SandboxSpec) -> Result<(), Status> { if openshell_core::gpu::sandbox_gpu_count(spec.resource_requirements.as_ref()) == Some(0) { return Err(Status::invalid_argument("gpu count must be greater than 0")); } diff --git a/crates/openshell-server/src/grpc/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index d83ffab0e8..7446938156 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -14,9 +14,9 @@ use openshell_core::proto::{ CreateWorkspaceResponse, DeleteWorkspaceRequest, DeleteWorkspaceResponse, GetWorkspaceRequest, GetWorkspaceResponse, InferenceRoute, ListWorkspaceMembersRequest, ListWorkspaceMembersResponse, ListWorkspacesRequest, ListWorkspacesResponse, Provider, - RemoveWorkspaceMemberRequest, RemoveWorkspaceMemberResponse, Sandbox, ServiceEndpoint, - SshSession, StoredProviderCredentialRefreshState, StoredProviderProfile, Workspace, - WorkspaceMember, WorkspaceRole, + RemoveWorkspaceMemberRequest, RemoveWorkspaceMemberResponse, Sandbox, SandboxWorkloadTemplate, + ServiceEndpoint, SshSession, StoredProviderCredentialRefreshState, StoredProviderProfile, + Workspace, WorkspaceMember, WorkspaceRole, }; use prost::Message; use tonic::{Request, Response, Status}; @@ -375,6 +375,7 @@ pub(super) async fn handle_delete_workspace( let mut blocking = Vec::new(); for (object_type, label) in [ (Sandbox::object_type(), "sandbox"), + (SandboxWorkloadTemplate::object_type(), "sandbox template"), (Provider::object_type(), "provider"), (StoredProviderProfile::object_type(), "provider profile"), (ServiceEndpoint::object_type(), "service"), @@ -819,6 +820,72 @@ mod tests { assert!(resp.deleted); } + #[tokio::test] + async fn delete_workspace_blocked_by_sandbox_template() { + let state = test_server_state().await; + + handle_create_workspace( + &state, + Request::new(CreateWorkspaceRequest { + name: "templated".to_string(), + labels: HashMap::new(), + }), + ) + .await + .unwrap(); + + let template = SandboxWorkloadTemplate { + metadata: Some(ObjectMeta { + id: "template-1".to_string(), + name: "gpu-kata".to_string(), + created_at_ms: 1_000_000, + labels: HashMap::new(), + annotations: HashMap::new(), + resource_version: 0, + workspace: "templated".to_string(), + deletion_timestamp_ms: 0, + }), + spec: None, + }; + state.store.put_message(&template).await.unwrap(); + + let err = handle_delete_workspace( + &state, + Request::new(DeleteWorkspaceRequest { + name: "templated".to_string(), + }), + ) + .await + .unwrap_err(); + assert_eq!(err.code(), Code::FailedPrecondition); + assert!( + err.message().contains("sandbox template"), + "error should name sandbox templates as blocking resources: {}", + err.message() + ); + + state + .store + .delete_by_name( + SandboxWorkloadTemplate::object_type(), + "templated", + "gpu-kata", + ) + .await + .unwrap(); + + let resp = handle_delete_workspace( + &state, + Request::new(DeleteWorkspaceRequest { + name: "templated".to_string(), + }), + ) + .await + .unwrap() + .into_inner(); + assert!(resp.deleted); + } + #[tokio::test] async fn delete_workspace_blocked_by_ssh_session() { let state = test_server_state().await; diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 591eeab214..2acd34fc44 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -48,9 +48,8 @@ mod tracing_setup; mod ws_tunnel; use metrics_exporter_prometheus::PrometheusBuilder; -#[cfg(target_os = "windows")] -use openshell_core::ComputeDriverKind; use openshell_core::net::set_tcp_nodelay_best_effort; +use openshell_core::telemetry::TelemetryComputeDriver; use openshell_core::{Config, Error, ObjectLabels, Result}; use openshell_extension_core::{ BearerTokenSlot, ExtensionAudience, ExtensionCallerKind, ExtensionKind, MAX_EXTENSION_TOKEN_TTL, @@ -59,7 +58,7 @@ use openshell_supervisor_middleware::MiddlewareRegistry; use std::collections::{BTreeMap, HashMap}; use std::io::ErrorKind; use std::net::SocketAddr; -use std::path::Path; +use std::path::{Path, PathBuf}; #[cfg(test)] use std::sync::LazyLock; use std::sync::{ @@ -293,8 +292,8 @@ pub struct ServerState { /// Registry of active supervisor sessions and pending relay channels. /// - /// Stored as `Arc` so compute drivers (e.g. the Docker driver) - /// can be constructed before `ServerState` and still + /// Stored as `Arc` so compiled compute drivers can be constructed before + /// `ServerState` and still /// query session state to surface supervisor readiness. pub supervisor_sessions: Arc, @@ -442,14 +441,14 @@ impl ServerState { /// Returns an error if the server fails to start or encounters a fatal error. pub(crate) async fn run_server( startup: ServerStartupConfig, - compute_driver: ConfiguredComputeDriver, tracing_log_bus: TracingLogBus, + compute_drivers: ComputeDriverRegistry, ) -> Result<()> { let ServerStartupConfig { config, config_file, guest_tls, - compute_driver: _, + compute_driver, } = startup; let (shutdown_tx, shutdown_rx) = watch::channel(false); @@ -590,12 +589,18 @@ pub(crate) async fn run_server( let sandbox_index = SandboxIndex::new(); let sandbox_watch_bus = SandboxWatchBus::new(); let supervisor_sessions = Arc::new(supervisor_session::SupervisorSessionRegistry::new()); - let driver_startup = - compute_driver_startup_context(&config, config_file.as_ref(), guest_tls.as_ref()); - let (compute, _operator_allowlist) = build_compute_runtime( + let driver_startup = compute::driver_config::DriverStartupContext { + file: config_file.as_ref(), + guest_tls: guest_tls.as_ref(), + gateway_port: config.bind_address.port(), + gateway_tls_enabled: config.tls.is_some(), + endpoint_overrides: &config.compute_driver_endpoints, + }; + let compute = build_compute_runtime( + &compute_drivers, + &compute_driver, &config, driver_startup, - compute_driver, store.clone(), sandbox_index.clone(), sandbox_watch_bus.clone(), @@ -667,7 +672,7 @@ pub(crate) async fn run_server( auth::compute_driver::ComputeDriverAuthenticator::new(state.compute.clone()), )); info!( - driver = state.compute.selected_driver_name(), + driver = state.compute.configured_driver_name(), "compute-driver sandbox bootstrap authenticator enabled" ); } @@ -1038,30 +1043,59 @@ async fn terminate_signal() { let _ = signal.recv().await; } -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] -fn unsupported_builtin_compute_driver(driver: ComputeDriverKind) -> compute::ComputeError { - compute::ComputeError::Message(format!( - "{} compute driver is unsupported on Windows", - driver.as_str() - )) +pub use compute::{ + AcquiredRemoteDriverEndpoint, DriverWatchStream, ManagedDriverProcess, SharedComputeDriver, +}; + +/// Driver instance returned by a compiled compute-driver factory. +pub enum ComputeDriverInstance { + /// A driver hosted in the gateway process. + InProcess(SharedComputeDriver), + /// A driver process launched and owned by the gateway. + ManagedRemote(AcquiredRemoteDriverEndpoint), } -type OperatorAllowlistArc = Option; -pub use compute::{DriverWatchStream, SharedComputeDriver}; +/// Type-erased tracing layer contributed by a compiled compute driver. +pub type ComputeDriverTracingLayer = + Box + Send + Sync>; + +/// Shutdown callback for resources owned by a compute-driver tracing layer. +pub type ComputeDriverTracingShutdown = + Box std::result::Result<(), String> + Send + Sync>; + +/// Optional process-wide tracing integration supplied by a compiled driver. +#[derive(Default)] +pub struct ComputeDriverTracingSetup { + layer: Option, + shutdown: Option, + error: Option, + target_prefix: Option<&'static str>, +} -/// Opaque result returned by a compiled compute-driver factory. -pub struct ComputeDriverBuildOutput { - runtime: ComputeRuntime, - operator_allowlist: OperatorAllowlistArc, +impl ComputeDriverTracingSetup { + #[must_use] + pub fn new( + layer: Option, + shutdown: Option, + error: Option, + target_prefix: Option<&'static str>, + ) -> Self { + Self { + layer, + shutdown, + error, + target_prefix, + } + } } +/// Factory for a compiled driver's optional tracing integration. +pub type ComputeDriverTracingFactory = fn(Option<&str>, Option<&str>) -> ComputeDriverTracingSetup; + /// Factory for a compute driver linked into a gateway binary. #[async_trait::async_trait] pub trait ComputeDriverFactory: Send + Sync { - async fn build( - &self, - context: ComputeDriverBuildContext<'_>, - ) -> Result; + async fn build(&self, context: ComputeDriverBuildContext<'_>) -> Result; } /// One named compiled-driver registration. @@ -1071,6 +1105,11 @@ pub struct ComputeDriverRegistration { detection_priority: u16, detect: Option bool>, factory: Arc, + telemetry_category: TelemetryComputeDriver, + inherited_config_keys: &'static [&'static str], + local_singleplayer: bool, + supports_mtls_user_auth: bool, + tracing_setup: Option, } impl std::fmt::Debug for ComputeDriverRegistration { @@ -1099,8 +1138,59 @@ impl ComputeDriverRegistration { detection_priority, detect, factory: Arc::new(factory), + telemetry_category: TelemetryComputeDriver::custom(), + inherited_config_keys: &[], + local_singleplayer: false, + supports_mtls_user_auth: true, + tracing_setup: None, }) } + + /// Select gateway-wide defaults understood by this driver's config type. + #[must_use] + pub fn with_inherited_config_keys(mut self, keys: &'static [&'static str]) -> Self { + self.inherited_config_keys = keys; + self + } + + /// Assign a bounded telemetry category chosen by the binary composition + /// boundary. Runtime driver names are never used as telemetry values. + #[must_use] + pub fn with_telemetry_category(mut self, category: TelemetryComputeDriver) -> Self { + self.telemetry_category = category; + self + } + + /// Mark a backend whose local deployment should use single-player defaults. + #[must_use] + pub fn with_local_singleplayer(mut self) -> Self { + self.local_singleplayer = true; + self + } + + /// Mark a backend that requires user authentication other than mTLS. + #[must_use] + pub fn without_mtls_user_auth(mut self) -> Self { + self.supports_mtls_user_auth = false; + self + } + + /// Attach optional process-wide tracing for this compiled driver. + #[must_use] + pub fn with_tracing_setup(mut self, setup: ComputeDriverTracingFactory) -> Self { + self.tracing_setup = Some(setup); + self + } + + #[must_use] + pub(crate) fn is_local_singleplayer(&self) -> bool { + self.local_singleplayer + } + + #[must_use] + pub(crate) fn supports_mtls_user_auth(&self) -> bool { + self.supports_mtls_user_auth + } } /// Registry of compute drivers compiled into this gateway binary. @@ -1165,10 +1255,28 @@ impl ComputeDriverRegistry { self.drivers.keys().map(String::as_str) } - fn get(&self, name: &str) -> Option<&ComputeDriverRegistration> { + pub(crate) fn get(&self, name: &str) -> Option<&ComputeDriverRegistration> { self.drivers.get(name) } + fn tracing_setup( + &self, + selection: &ComputeDriverSelection, + endpoint_overrides: &BTreeMap, + otlp_endpoint: Option<&str>, + gateway_name: Option<&str>, + ) -> ComputeDriverTracingSetup { + let name = selection.name(); + if endpoint_overrides.contains_key(name) { + return ComputeDriverTracingSetup::default(); + } + self.get(name) + .and_then(|registration| registration.tracing_setup) + .map_or_else(ComputeDriverTracingSetup::default, |setup| { + setup(otlp_endpoint, gateway_name) + }) + } + fn detect(&self) -> ComputeDriverDetection { let mut candidates = self .drivers @@ -1195,7 +1303,7 @@ impl ComputeDriverRegistry { if detection.selected().is_none() { return Err(Error::config( "no compute driver configured and auto-detection found no suitable installed \ - driver; set --drivers or OPENSHELL_DRIVERS=", + driver; set --drivers or OPENSHELL_DRIVERS=", )); } Ok(ComputeDriverSelection::AutoDetected(detection)) @@ -1213,88 +1321,14 @@ impl ComputeDriverRegistry { } } -/// Install every first-party compute driver linked into the standard gateway. -#[must_use] -pub fn install_default_compute_drivers() -> ComputeDriverRegistry { - #[allow(unused_mut)] - let mut registry = ComputeDriverRegistry::new(); - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - { - registry - .install( - ComputeDriverRegistration::new( - "kubernetes", - 100, - Some(|| std::env::var_os("KUBERNETES_SERVICE_HOST").is_some()), - KubernetesComputeDriverFactory, - ) - .expect("valid kubernetes registration"), - ) - .expect("unique kubernetes registration"); - registry - .install( - ComputeDriverRegistration::new( - "podman", - 200, - Some(openshell_core::config::is_podman_available), - PodmanComputeDriverFactory, - ) - .expect("valid podman registration"), - ) - .expect("unique podman registration"); - registry - .install( - ComputeDriverRegistration::new( - "docker", - 300, - Some(openshell_core::config::is_docker_available), - DockerComputeDriverFactory, - ) - .expect("valid docker registration"), - ) - .expect("unique docker registration"); - registry - .install( - ComputeDriverRegistration::new("vm", u16::MAX, None, VmComputeDriverFactory) - .expect("valid vm registration"), - ) - .expect("unique vm registration"); - } - #[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] - { - registry - .install( - ComputeDriverRegistration::new("mxc", u16::MAX, None, MxcComputeDriverFactory) - .expect("valid mxc registration"), - ) - .expect("unique mxc registration"); - for name in ["kubernetes", "podman", "docker", "vm"] { - registry - .install( - ComputeDriverRegistration::new( - name, - u16::MAX, - None, - UnsupportedComputeDriverFactory, - ) - .expect("valid unsupported registration"), - ) - .expect("unique unsupported registration"); - } - } - registry -} - pub struct ComputeDriverBuildContext<'a> { driver_name: String, - config: &'a Config, + gateway_name: &'a str, + gateway_bind_address: SocketAddr, + gateway_log_level: &'a str, driver_startup: compute::driver_config::DriverStartupContext<'a>, - store: Arc, - sandbox_index: SandboxIndex, - sandbox_watch_bus: SandboxWatchBus, - tracing_log_bus: TracingLogBus, - supervisor_sessions: Arc, shutdown_rx: watch::Receiver, + inherited_config_keys: &'static [&'static str], } impl ComputeDriverBuildContext<'_> { @@ -1304,8 +1338,18 @@ impl ComputeDriverBuildContext<'_> { } #[must_use] - pub fn gateway_config(&self) -> &Config { - self.config + pub fn gateway_name(&self) -> &str { + self.gateway_name + } + + #[must_use] + pub fn gateway_bind_address(&self) -> SocketAddr { + self.gateway_bind_address + } + + #[must_use] + pub fn gateway_log_level(&self) -> &str { + self.gateway_log_level } #[must_use] @@ -1331,7 +1375,11 @@ impl ComputeDriverBuildContext<'_> { where T: Default + serde::de::DeserializeOwned, { - compute::driver_config::driver_config_from_context(self.driver_startup, &self.driver_name) + compute::driver_config::driver_config_from_context( + self.driver_startup, + &self.driver_name, + self.inherited_config_keys, + ) } #[must_use] @@ -1339,242 +1387,84 @@ impl ComputeDriverBuildContext<'_> { self.shutdown_rx.clone() } - /// Finish construction of an in-process driver through the common runtime path. - pub async fn finish_in_process( - self, - driver: SharedComputeDriver, - ) -> Result { - let runtime = ComputeRuntime::from_driver( - self.driver_name, - driver, - None, - self.store, - self.sandbox_index, - self.sandbox_watch_bus, - self.tracing_log_bus, - self.supervisor_sessions, - ) - .await - .map_err(|error| Error::execution(format!("failed to create compute runtime: {error}")))?; - Ok(ComputeDriverBuildOutput { - runtime, - operator_allowlist: None, - }) - } -} - -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] -#[derive(Clone, Copy)] -struct MxcComputeDriverFactory; - -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] -#[async_trait::async_trait] -impl ComputeDriverFactory for MxcComputeDriverFactory { - async fn build( - &self, - context: ComputeDriverBuildContext<'_>, - ) -> Result { - let mxc_config = compute::driver_config::mxc_config_from_context(context.driver_startup)?; - let runtime = ComputeRuntime::new_mxc( - mxc_config, - context.store, - context.sandbox_index, - context.sandbox_watch_bus, - context.tracing_log_bus, - context.supervisor_sessions, - ) - .await - .map_err(|error| Error::execution(format!("failed to create compute runtime: {error}")))?; - Ok(ComputeDriverBuildOutput { - runtime, - operator_allowlist: None, - }) - } -} - -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] -#[derive(Clone, Copy)] -struct UnsupportedComputeDriverFactory; - -#[cfg(all(target_os = "windows", feature = "in-tree-compute-drivers"))] -#[async_trait::async_trait] -impl ComputeDriverFactory for UnsupportedComputeDriverFactory { - async fn build( - &self, - context: ComputeDriverBuildContext<'_>, - ) -> Result { - Err(Error::execution( - unsupported_builtin_compute_driver( - context - .driver_name - .parse() - .expect("default driver names are valid"), - ) - .to_string(), - )) - } -} - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[derive(Clone, Copy)] -struct KubernetesComputeDriverFactory; - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[async_trait::async_trait] -impl ComputeDriverFactory for KubernetesComputeDriverFactory { - async fn build( - &self, - context: ComputeDriverBuildContext<'_>, - ) -> Result { - warn_if_kubernetes_sandbox_jwt_expiry_disabled(context.config); - let config = compute::driver_config::builtin::kubernetes_config_from_context( - context.driver_startup, - )?; - let (runtime, operator_allowlist) = ComputeRuntime::new_kubernetes( - config, - context.store, - context.sandbox_index, - context.sandbox_watch_bus, - context.tracing_log_bus, - context.supervisor_sessions, - context.shutdown_rx, - ) - .await - .map_err(|error| Error::execution(format!("failed to create compute runtime: {error}")))?; - Ok(ComputeDriverBuildOutput { - runtime, - operator_allowlist, - }) - } -} - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[derive(Clone, Copy)] -struct DockerComputeDriverFactory; - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[async_trait::async_trait] -impl ComputeDriverFactory for DockerComputeDriverFactory { - async fn build( - &self, - context: ComputeDriverBuildContext<'_>, - ) -> Result { - let driver_config = - compute::driver_config::builtin::docker_config_from_context(context.driver_startup)?; - let runtime = ComputeRuntime::new_docker( - context.config.clone(), - driver_config, - context.store, - context.sandbox_index, - context.sandbox_watch_bus, - context.tracing_log_bus, - context.supervisor_sessions, - ) - .await - .map_err(|error| Error::execution(format!("failed to create compute runtime: {error}")))?; - Ok(ComputeDriverBuildOutput { - runtime, - operator_allowlist: None, - }) - } -} - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[derive(Clone, Copy)] -struct PodmanComputeDriverFactory; - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[async_trait::async_trait] -impl ComputeDriverFactory for PodmanComputeDriverFactory { - async fn build( - &self, - context: ComputeDriverBuildContext<'_>, - ) -> Result { - let driver_config = - compute::driver_config::builtin::podman_config_from_context(context.driver_startup)?; - let runtime = ComputeRuntime::new_podman( - driver_config, - context.store, - context.sandbox_index, - context.sandbox_watch_bus, - context.tracing_log_bus, - context.supervisor_sessions, - ) - .await - .map_err(|error| Error::execution(format!("failed to create compute runtime: {error}")))?; - Ok(ComputeDriverBuildOutput { - runtime, - operator_allowlist: None, - }) - } -} - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[derive(Clone, Copy)] -struct VmComputeDriverFactory; - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -#[async_trait::async_trait] -impl ComputeDriverFactory for VmComputeDriverFactory { - async fn build( - &self, - context: ComputeDriverBuildContext<'_>, - ) -> Result { - let driver_config = - compute::driver_config::builtin::vm_config_from_context(context.driver_startup)?; - let otlp_config = context - .driver_startup + #[must_use] + pub fn otlp_config(&self) -> Option<&config_file::OtlpConfig> { + self.driver_startup .file - .and_then(|file| file.openshell.gateway.otlp.as_ref()); - let endpoint = compute::vm::spawn(context.config, &driver_config, otlp_config).await?; - let runtime = ComputeRuntime::new_remote_driver( - endpoint, - context.store, - context.sandbox_index, - context.sandbox_watch_bus, - context.tracing_log_bus, - context.supervisor_sessions, - ) - .await - .map_err(|error| Error::execution(format!("failed to create compute runtime: {error}")))?; - Ok(ComputeDriverBuildOutput { - runtime, - operator_allowlist: None, - }) + .and_then(|file| file.openshell.gateway.otlp.as_ref()) } } #[allow(clippy::too_many_arguments)] async fn build_compute_runtime( + registry: &ComputeDriverRegistry, + selection: &ComputeDriverSelection, config: &Config, driver_startup: compute::driver_config::DriverStartupContext<'_>, - driver: ConfiguredComputeDriver, store: Arc, sandbox_index: SandboxIndex, sandbox_watch_bus: SandboxWatchBus, tracing_log_bus: TracingLogBus, supervisor_sessions: Arc, shutdown_rx: watch::Receiver, -) -> Result<(ComputeRuntime, OperatorAllowlistArc)> { +) -> Result { + let driver = resolve_configured_compute_driver(registry, selection.name(), driver_startup)?; + let telemetry_compute_driver = driver.telemetry_compute_driver(registry); info!(driver = %driver.name(), "Using compute driver"); + if config + .gateway_jwt + .as_ref() + .is_some_and(|jwt| jwt.ttl_secs == 0) + && !driver.is_local_singleplayer(registry) + { + warn!( + "Gateway configured with non-expiring sandbox JWTs; set gateway_jwt.ttl_secs > 0 for shared deployments" + ); + } - let (runtime, operator_allowlist) = match driver { + let runtime = match driver { ConfiguredComputeDriver::Registered(registration) => { - let output = registration - .factory - .build(ComputeDriverBuildContext { - driver_name: registration.name, - config, - driver_startup, + let build_context = ComputeDriverBuildContext { + driver_name: registration.name.clone(), + gateway_name: &config.name, + gateway_bind_address: config.bind_address, + gateway_log_level: &config.log_level, + driver_startup, + shutdown_rx, + inherited_config_keys: registration.inherited_config_keys, + }; + let instance = registration.factory.build(build_context).await?; + match instance { + ComputeDriverInstance::InProcess(driver) => ComputeRuntime::from_driver( + registration.name, + driver, + None, store, sandbox_index, sandbox_watch_bus, tracing_log_bus, supervisor_sessions, - shutdown_rx, - }) - .await?; - (output.runtime, output.operator_allowlist) + ) + .await + .map_err(|error| { + Error::execution(format!("failed to create compute runtime: {error}")) + })?, + ComputeDriverInstance::ManagedRemote(mut endpoint) => { + endpoint.name = registration.name; + ComputeRuntime::new_remote_driver( + endpoint, + store, + sandbox_index, + sandbox_watch_bus, + tracing_log_bus, + supervisor_sessions, + ) + .await + .map_err(|error| { + Error::execution(format!("failed to create compute runtime: {error}")) + })? + } + } } ConfiguredComputeDriver::Remote { name } => { let remote_config = @@ -1587,7 +1477,7 @@ async fn build_compute_runtime( let endpoint = compute::connect_remote_compute_driver(name, &remote_config.socket_path) .await .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; - let rt = ComputeRuntime::new_remote_driver( + ComputeRuntime::new_remote_driver( endpoint, store, sandbox_index, @@ -1596,58 +1486,56 @@ async fn build_compute_runtime( supervisor_sessions, ) .await - .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; - (rt, None) + .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))? } }; - Ok((runtime, operator_allowlist)) -} - -fn compute_driver_startup_context<'a>( - config: &'a Config, - config_file: Option<&'a config_file::ConfigFile>, - guest_tls: Option<&'a compute::driver_config::GuestTlsPaths>, -) -> compute::driver_config::DriverStartupContext<'a> { - compute::driver_config::DriverStartupContext { - file: config_file, - guest_tls, - gateway_port: config.bind_address.port(), - gateway_tls_enabled: config.tls.is_some(), - endpoint_overrides: &config.compute_driver_endpoints, - } + Ok(runtime.with_telemetry_compute_driver(telemetry_compute_driver)) } #[derive(Debug, Clone)] -pub(crate) enum ConfiguredComputeDriver { +enum ConfiguredComputeDriver { Registered(ComputeDriverRegistration), Remote { name: String }, } impl ConfiguredComputeDriver { - pub(crate) fn name(&self) -> &str { + fn name(&self) -> &str { match self { Self::Registered(registration) => ®istration.name, Self::Remote { name } => name, } } + + fn is_local_singleplayer(&self, registry: &ComputeDriverRegistry) -> bool { + match self { + Self::Registered(registration) => registration.is_local_singleplayer(), + Self::Remote { name } => registry + .get(name) + .is_some_and(ComputeDriverRegistration::is_local_singleplayer), + } + } + + fn telemetry_compute_driver(&self, registry: &ComputeDriverRegistry) -> TelemetryComputeDriver { + match self { + Self::Registered(registration) => registration.telemetry_category, + Self::Remote { name } => registry + .get(name) + .map_or_else(TelemetryComputeDriver::custom, |registration| { + registration.telemetry_category + }), + } + } } -pub(crate) fn configured_compute_driver_for_startup( +#[cfg(test)] +fn configured_compute_driver( registry: &ComputeDriverRegistry, - startup: &ServerStartupConfig, + config: &Config, + driver_startup: compute::driver_config::DriverStartupContext<'_>, ) -> Result { - resolve_configured_compute_driver( - registry, - startup.compute_driver.name(), - compute::driver_config::DriverStartupContext { - file: startup.config_file.as_ref(), - guest_tls: startup.guest_tls.as_ref(), - gateway_port: startup.config.bind_address.port(), - gateway_tls_enabled: startup.config.tls.is_some(), - endpoint_overrides: &startup.config.compute_driver_endpoints, - }, - ) + let selection = registry.select(&config.compute_drivers)?; + resolve_configured_compute_driver(registry, selection.name(), driver_startup) } fn resolve_configured_compute_driver( @@ -1671,23 +1559,6 @@ fn resolve_configured_compute_driver( Ok(ConfiguredComputeDriver::Remote { name }) } -#[cfg(any(test, feature = "in-tree-compute-drivers"))] -fn kubernetes_sandbox_jwt_expiry_disabled(config: &Config) -> bool { - config - .gateway_jwt - .as_ref() - .is_some_and(|jwt| jwt.ttl_secs == 0) -} - -#[cfg(feature = "in-tree-compute-drivers")] -fn warn_if_kubernetes_sandbox_jwt_expiry_disabled(config: &Config) { - if kubernetes_sandbox_jwt_expiry_disabled(config) { - warn!( - "Kubernetes gateway configured with non-expiring sandbox JWTs (gateway_jwt.ttl_secs = 0); set ttl_secs > 0 for shared Kubernetes deployments" - ); - } -} - pub(crate) async fn ensure_default_workspace(store: &Store) -> Result<()> { use grpc::workspace::{DEFAULT_WORKSPACE_NAME, WORKSPACE_OBJECT_TYPE}; use openshell_core::proto::Workspace; @@ -1753,11 +1624,11 @@ mod tests { BoundGatewayListener, ConfiguredComputeDriver, ConnectionProtocol, ExtensionKind, GatewayListenerScope, MultiplexService, ServerState, TlsAcceptor, allow_plaintext_service_http, bind_gateway_listeners, classify_initial_bytes, - is_benign_tls_handshake_failure, kubernetes_sandbox_jwt_expiry_disabled, + configured_compute_driver, is_benign_tls_handshake_failure, mint_gateway_extension_credential, serve_gateway_listener, }; use openshell_core::{ - ComputeDriverKind, Config, + Config, proto::{HealthRequest, open_shell_client::OpenShellClient}, }; use std::io::{Error, ErrorKind}; @@ -1778,6 +1649,26 @@ mod tests { tls_test_utils::{generate_test_certs_with_ca, install_rustls_provider}, }; + static DETECTION_PROBE_ORDER: LazyLock>> = + LazyLock::new(|| Mutex::new(Vec::new())); + + fn record_detection_probe(name: &'static str, available: bool) -> bool { + DETECTION_PROBE_ORDER.lock().unwrap().push(name); + available + } + + fn unavailable_first_probe() -> bool { + record_detection_probe("first", false) + } + + fn available_second_probe() -> bool { + record_detection_probe("second", true) + } + + fn available_third_probe() -> bool { + record_detection_probe("third", true) + } + fn extension_test_issuer() -> Arc { let material = openshell_bootstrap::jwt::generate_jwt_key().expect("jwt key"); Arc::new( @@ -1880,47 +1771,37 @@ mod tests { } fn test_compute_drivers() -> super::ComputeDriverRegistry { - super::install_default_compute_drivers() - } - - fn select_compute_driver( - registry: &super::ComputeDriverRegistry, - config: &Config, - driver_startup: crate::compute::driver_config::DriverStartupContext<'_>, - ) -> openshell_core::Result { - let selection = registry.select(&config.compute_drivers)?; - super::resolve_configured_compute_driver(registry, selection.name(), driver_startup) + let mut registry = super::ComputeDriverRegistry::new(); + for (name, priority) in [("alpha", 100), ("beta", 200), ("gamma", 300)] { + registry + .install( + super::ComputeDriverRegistration::new( + name, + priority, + None, + TestComputeDriverFactory, + ) + .unwrap() + .with_telemetry_category( + openshell_core::telemetry::TelemetryComputeDriver::anonymous_category( + "registered", + ), + ), + ) + .unwrap(); + } + registry } #[derive(Clone, Copy)] struct TestComputeDriverFactory; - static DETECTION_PROBE_ORDER: LazyLock>> = - LazyLock::new(|| Mutex::new(Vec::new())); - - fn record_detection_probe(name: &'static str, available: bool) -> bool { - DETECTION_PROBE_ORDER.lock().unwrap().push(name); - available - } - - fn unavailable_first_probe() -> bool { - record_detection_probe("first", false) - } - - fn available_second_probe() -> bool { - record_detection_probe("second", true) - } - - fn available_third_probe() -> bool { - record_detection_probe("third", true) - } - #[async_trait::async_trait] impl super::ComputeDriverFactory for TestComputeDriverFactory { async fn build( &self, _context: super::ComputeDriverBuildContext<'_>, - ) -> openshell_core::Result { + ) -> openshell_core::Result { unreachable!("selection tests do not construct the driver") } } @@ -2234,38 +2115,31 @@ mod tests { #[test] fn configured_compute_driver_triggers_auto_detection_when_empty() { - let config = Config::new(None).with_compute_drivers(std::iter::empty::()); - // Empty drivers triggers auto-detection, which may return Some or None - // depending on the environment. This test verifies the auto-detection path - // is taken rather than immediately returning an error. - let result = select_compute_driver( - &test_compute_drivers(), - &config, - test_driver_startup(&config, None), - ); - // Either we get a detected driver or an error about none being detected. - match result { - Ok(ConfiguredComputeDriver::Registered(registration)) => { - assert!( - matches!( - registration.name.as_str(), - "kubernetes" | "docker" | "podman" - ), - "auto-detected unexpected driver: {}", - registration.name - ); - } - Ok(ConfiguredComputeDriver::Remote { name }) => { - panic!("auto-detection returned remote driver: {name}"); - } - Err(e) => { - assert!( - e.to_string() - .contains("auto-detection found no suitable installed driver"), - "unexpected error: {e}" - ); - } + fn available() -> bool { + true } + + let mut registry = super::ComputeDriverRegistry::new(); + registry + .install( + super::ComputeDriverRegistration::new( + "detected", + 100, + Some(available), + TestComputeDriverFactory, + ) + .unwrap(), + ) + .unwrap(); + let config = Config::new(None).with_compute_drivers(std::iter::empty::()); + let result = + configured_compute_driver(®istry, &config, test_driver_startup(&config, None)) + .unwrap(); + + let ConfiguredComputeDriver::Registered(registration) = result else { + panic!("auto-detection must select a registered driver"); + }; + assert_eq!(registration.name, "detected"); } #[test] @@ -2328,9 +2202,8 @@ mod tests { #[test] fn configured_compute_driver_rejects_multiple_entries() { - let config = Config::new(None) - .with_compute_drivers([ComputeDriverKind::Kubernetes, ComputeDriverKind::Podman]); - let err = select_compute_driver( + let config = Config::new(None).with_compute_drivers(["alpha", "beta"]); + let err = configured_compute_driver( &test_compute_drivers(), &config, test_driver_startup(&config, None), @@ -2340,64 +2213,38 @@ mod tests { err.to_string() .contains("multiple compute drivers are not supported yet") ); - assert!(err.to_string().contains("kubernetes,podman")); - } - - #[test] - fn configured_compute_driver_accepts_podman() { - let config = Config::new(None).with_compute_drivers([ComputeDriverKind::Podman]); - let driver = select_compute_driver( - &test_compute_drivers(), - &config, - test_driver_startup(&config, None), - ) - .unwrap(); - assert!(matches!( - driver, - ConfiguredComputeDriver::Registered(registration) if registration.name == "podman" - )); - } - - #[test] - fn configured_compute_driver_accepts_vm() { - let config = Config::new(None).with_compute_drivers([ComputeDriverKind::Vm]); - let driver = select_compute_driver( - &test_compute_drivers(), - &config, - test_driver_startup(&config, None), - ) - .unwrap(); - assert!(matches!( - driver, - ConfiguredComputeDriver::Registered(registration) if registration.name == "vm" - )); + assert!(err.to_string().contains("alpha,beta")); } #[test] - fn configured_compute_driver_accepts_docker() { - let config = Config::new(None).with_compute_drivers([ComputeDriverKind::Docker]); - let driver = select_compute_driver( - &test_compute_drivers(), - &config, - test_driver_startup(&config, None), - ) - .unwrap(); + fn configured_compute_driver_accepts_registered_name() { + let config = Config::new(None).with_compute_drivers(["beta"]); + let registry = test_compute_drivers(); + let driver = + configured_compute_driver(®istry, &config, test_driver_startup(&config, None)) + .unwrap(); + assert_eq!( + driver.telemetry_compute_driver(®istry).as_str(), + "registered" + ); assert!(matches!( driver, - ConfiguredComputeDriver::Registered(registration) if registration.name == "docker" + ConfiguredComputeDriver::Registered(registration) if registration.name == "beta" )); } #[test] fn configured_compute_driver_resolves_named_remote() { let config = Config::new(None).with_compute_drivers(["kyma"]); + let registry = test_compute_drivers(); - let driver = select_compute_driver( - &test_compute_drivers(), - &config, - test_driver_startup(&config, None), - ) - .unwrap(); + let driver = + configured_compute_driver(®istry, &config, test_driver_startup(&config, None)) + .unwrap(); + assert_eq!( + driver.telemetry_compute_driver(®istry).as_str(), + "custom" + ); match driver { ConfiguredComputeDriver::Remote { name } => { @@ -2413,30 +2260,32 @@ mod tests { } #[test] - fn configured_compute_driver_uses_vm_endpoint_override() { + fn configured_compute_driver_uses_endpoint_override() { let config = Config::new(None) - .with_compute_drivers([ComputeDriverKind::Vm]) - .with_compute_driver_endpoint("vm", "/run/openshell/vm.sock"); + .with_compute_drivers(["alpha"]) + .with_compute_driver_endpoint("alpha", "/run/openshell/alpha.sock"); + let registry = test_compute_drivers(); - let driver = select_compute_driver( - &test_compute_drivers(), - &config, - test_driver_startup(&config, None), - ) - .unwrap(); + let driver = + configured_compute_driver(®istry, &config, test_driver_startup(&config, None)) + .unwrap(); + assert_eq!( + driver.telemetry_compute_driver(®istry).as_str(), + "registered" + ); assert!(matches!( driver, - ConfiguredComputeDriver::Remote { name } if name == "vm" + ConfiguredComputeDriver::Remote { name } if name == "alpha" )); } #[test] fn configured_compute_driver_uses_builtin_endpoint_override() { let config = Config::new(None) - .with_compute_drivers([ComputeDriverKind::Docker]) - .with_compute_driver_endpoint("docker", "/run/openshell/docker.sock"); + .with_compute_drivers(["beta"]) + .with_compute_driver_endpoint("beta", "/run/openshell/beta.sock"); - let driver = select_compute_driver( + let driver = configured_compute_driver( &test_compute_drivers(), &config, test_driver_startup(&config, None), @@ -2444,48 +2293,8 @@ mod tests { .unwrap(); assert!(matches!( driver, - ConfiguredComputeDriver::Remote { name } if name == "docker" - )); - } - - #[test] - fn kubernetes_sandbox_jwt_expiry_disabled_warns_for_zero_ttl() { - fn config_with_jwt_ttl(ttl_secs: u64) -> Config { - let mut config = Config::new(None); - config.gateway_jwt = Some(openshell_core::GatewayJwtConfig { - signing_key_path: "/tmp/signing.pem".into(), - public_key_path: "/tmp/public.pem".into(), - kid_path: "/tmp/kid".into(), - gateway_id: "openshell".to_string(), - ttl_secs, - }); - config - } - - assert!(kubernetes_sandbox_jwt_expiry_disabled( - &config_with_jwt_ttl(0) - )); - assert!(!kubernetes_sandbox_jwt_expiry_disabled( - &config_with_jwt_ttl(3600) + ConfiguredComputeDriver::Remote { name } if name == "beta" )); - assert!(!kubernetes_sandbox_jwt_expiry_disabled(&Config::new(None))); - } - - #[cfg(target_os = "windows")] - #[test] - fn windows_builtin_compute_drivers_report_unsupported() { - for driver in [ - ComputeDriverKind::Docker, - ComputeDriverKind::Kubernetes, - ComputeDriverKind::Podman, - ComputeDriverKind::Vm, - ] { - let message = super::unsupported_builtin_compute_driver(driver).to_string(); - assert!( - message.contains("unsupported on Windows"), - "{driver} rejection should be explicit, got: {message}" - ); - } } #[tokio::test] diff --git a/crates/openshell-server/src/otel_tracing.rs b/crates/openshell-server/src/otel_tracing.rs index b4e8d9e506..16a94a7321 100644 --- a/crates/openshell-server/src/otel_tracing.rs +++ b/crates/openshell-server/src/otel_tracing.rs @@ -51,11 +51,6 @@ impl<'a> GatewayResourceAttributes<'a> { compute_driver, } } - - /// The configured gateway installation name, if any. - pub fn name(&self) -> Option<&'a str> { - self.name - } } fn trace_config<'cfg>( @@ -134,11 +129,13 @@ pub fn provider_for( openshell_otel::provider_for(cfg.map(|cfg| trace_config(cfg, gateway))) } -/// Build the gateway layer while routing one selected in-process driver to -/// its own tracer provider. -pub fn layer_excluding_driver( +/// Build the `tracing` layer that forwards spans to `provider`. +/// +/// Events stay on the gateway's logging layers. Spans emitted by the +/// OpenTelemetry crates are excluded to prevent recursive export traffic. +pub fn layer( provider: &SdkTracerProvider, - driver_target_prefix: Option<&'static str>, + excluded_target_prefix: Option<&'static str>, ) -> openshell_otel::TargetOtlpLayer where S: Subscriber + for<'span> LookupSpan<'span>, @@ -146,7 +143,7 @@ where openshell_otel::layer_excluding_target_prefix( provider, INSTRUMENTATION_SCOPE, - driver_target_prefix, + excluded_target_prefix, ) } @@ -180,8 +177,7 @@ pub mod test_exporter { let provider = opentelemetry_sdk::trace::SdkTracerProvider::builder() .with_simple_exporter(exporter.clone()) .build(); - let subscriber = - tracing_subscriber::registry().with(super::layer_excluding_driver(&provider, None)); + let subscriber = tracing_subscriber::registry().with(super::layer(&provider, None)); let dispatch = tracing::Dispatch::new(subscriber); TracingTestGuard { _default: tracing::dispatcher::set_default(&dispatch), diff --git a/crates/openshell-server/src/persistence/mod.rs b/crates/openshell-server/src/persistence/mod.rs index 6934630110..716f26dad9 100644 --- a/crates/openshell-server/src/persistence/mod.rs +++ b/crates/openshell-server/src/persistence/mod.rs @@ -401,6 +401,39 @@ impl Store { )) } + /// Atomically insert a named object only if its workspace has fewer than + /// `max_count` objects of the same type. + /// + /// Returns `Ok(None)` when the quota is already full. A duplicate id or + /// `(object_type, workspace, name)` still returns + /// [`PersistenceError::UniqueViolation`]. + #[allow(clippy::too_many_arguments)] + #[tracing::instrument( + name = "store", + skip_all, + fields(otel.name = "store.create_if_workspace_count_below", otel.status_code = tracing::field::Empty, object_type = %object_type, object.id = %id, object.name = %name, workspace = %workspace, max_count = max_count) + )] + pub async fn create_if_workspace_count_below( + &self, + object_type: &str, + id: &str, + name: &str, + workspace: &str, + payload: &[u8], + labels: Option<&str>, + max_count: u64, + ) -> PersistenceResult> { + store_dispatch_traced!(self.create_if_workspace_count_below( + object_type, + id, + name, + workspace, + payload, + labels, + max_count + )) + } + /// Fetch an object by id. #[tracing::instrument( name = "store", diff --git a/crates/openshell-server/src/persistence/postgres.rs b/crates/openshell-server/src/persistence/postgres.rs index 89fe442695..19c50c6187 100644 --- a/crates/openshell-server/src/persistence/postgres.rs +++ b/crates/openshell-server/src/persistence/postgres.rs @@ -337,6 +337,73 @@ RETURNING resource_version, created_at_ms, updated_at_ms }) } + #[allow(clippy::too_many_arguments)] + pub async fn create_if_workspace_count_below( + &self, + object_type: &str, + id: &str, + name: &str, + workspace: &str, + payload: &[u8], + labels: Option<&str>, + max_count: u64, + ) -> PersistenceResult> { + let now_ms = current_time_ms(); + let labels_jsonb: Option = labels + .map(serde_json::from_str) + .transpose() + .map_err(|e| PersistenceError::Encode(format!("invalid labels JSON: {e}")))?; + let mut tx = self.pool.begin().await.map_err(|e| map_db_error(&e))?; + + sqlx::query("SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))") + .bind(object_type) + .bind(workspace) + .execute(&mut *tx) + .await + .map_err(|e| map_db_error(&e))?; + + let row: (i64,) = sqlx::query_as( + "SELECT COUNT(*) FROM objects WHERE object_type = $1 AND workspace = $2", + ) + .bind(object_type) + .bind(workspace) + .fetch_one(&mut *tx) + .await + .map_err(|e| map_db_error(&e))?; + let count = u64::try_from(row.0).unwrap_or(0); + if count >= max_count { + tx.commit().await.map_err(|e| map_db_error(&e))?; + return Ok(None); + } + + let row = sqlx::query( + r" +INSERT INTO objects (object_type, id, name, workspace, payload, created_at_ms, updated_at_ms, labels, resource_version) +VALUES ($1, $2, $3, $4, $5, $6, $6, COALESCE($7, '{}'::jsonb), 1) +RETURNING resource_version, created_at_ms, updated_at_ms +", + ) + .bind(object_type) + .bind(id) + .bind(name) + .bind(workspace) + .bind(payload) + .bind(now_ms) + .bind(labels_jsonb) + .fetch_one(&mut *tx) + .await + .map_err(|e| map_db_error(&e))?; + + tx.commit().await.map_err(|e| map_db_error(&e))?; + + let resource_version_i64: i64 = row.try_get("resource_version").unwrap_or(1); + Ok(Some(WriteResult { + resource_version: resource_version_i64.max(1).cast_unsigned(), + created_at_ms: row.get("created_at_ms"), + updated_at_ms: row.get("updated_at_ms"), + })) + } + pub async fn get( &self, object_type: &str, diff --git a/crates/openshell-server/src/persistence/sqlite.rs b/crates/openshell-server/src/persistence/sqlite.rs index c28318d261..c945c417f9 100644 --- a/crates/openshell-server/src/persistence/sqlite.rs +++ b/crates/openshell-server/src/persistence/sqlite.rs @@ -357,6 +357,67 @@ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7, ?8, 1) }) } + #[allow(clippy::too_many_arguments)] + pub async fn create_if_workspace_count_below( + &self, + object_type: &str, + id: &str, + name: &str, + workspace: &str, + payload: &[u8], + labels: Option<&str>, + max_count: u64, + ) -> PersistenceResult> { + let now_ms = current_time_ms(); + let mut tx = self + .pool + .begin_with("BEGIN IMMEDIATE") + .await + .map_err(|e| map_db_error(&e))?; + + let row: (i64,) = sqlx::query_as( + r#" +SELECT COUNT(*) FROM "objects" +WHERE "object_type" = ?1 AND "workspace" = ?2 +"#, + ) + .bind(object_type) + .bind(workspace) + .fetch_one(&mut *tx) + .await + .map_err(|e| map_db_error(&e))?; + let count = u64::try_from(row.0).unwrap_or(0); + if count >= max_count { + tx.commit().await.map_err(|e| map_db_error(&e))?; + return Ok(None); + } + + sqlx::query( + r#" +INSERT INTO "objects" ("object_type", "id", "name", "workspace", "payload", "created_at_ms", "updated_at_ms", "labels", "resource_version") +VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, 1) +"#, + ) + .bind(object_type) + .bind(id) + .bind(name) + .bind(workspace) + .bind(payload) + .bind(now_ms) + .bind(labels.unwrap_or("{}")) + .execute(&mut *tx) + .await + .map_err(|e| map_db_error(&e))?; + + tx.commit().await.map_err(|e| map_db_error(&e))?; + + Ok(Some(WriteResult { + resource_version: 1, + created_at_ms: now_ms, + updated_at_ms: now_ms, + })) + } + pub async fn get( &self, object_type: &str, diff --git a/crates/openshell-server/src/persistence/tests.rs b/crates/openshell-server/src/persistence/tests.rs index 479f46e493..7882c9246c 100644 --- a/crates/openshell-server/src/persistence/tests.rs +++ b/crates/openshell-server/src/persistence/tests.rs @@ -1819,6 +1819,7 @@ async fn cas_update_message_cas_succeeds() { }), spec: None, status: None, + ..Sandbox::default() }; store.put_message(&sandbox).await.unwrap(); @@ -1861,6 +1862,7 @@ async fn cas_update_message_cas_conflicts_on_concurrent_updates() { }), spec: None, status: None, + ..Sandbox::default() }; store.put_message(&sandbox).await.unwrap(); @@ -1931,6 +1933,7 @@ async fn cas_update_message_cas_rejects_workspace_change() { }), spec: None, status: None, + ..Sandbox::default() }; store.put_message(&sandbox).await.unwrap(); @@ -1973,6 +1976,7 @@ async fn cas_update_message_cas_rejects_name_change() { }), spec: None, status: None, + ..Sandbox::default() }; store.put_message(&sandbox).await.unwrap(); diff --git a/crates/openshell-server/src/sandbox_index.rs b/crates/openshell-server/src/sandbox_index.rs index 589f88fd88..c119ca6889 100644 --- a/crates/openshell-server/src/sandbox_index.rs +++ b/crates/openshell-server/src/sandbox_index.rs @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! In-memory indexes for correlating Kubernetes objects back to sandbox ids. +//! In-memory indexes for correlating compute resources back to sandbox ids. use std::collections::HashMap; use std::sync::{Arc, RwLock}; diff --git a/crates/openshell-server/src/test_support.rs b/crates/openshell-server/src/test_support.rs index 5f4063ae45..0e4c318192 100644 --- a/crates/openshell-server/src/test_support.rs +++ b/crates/openshell-server/src/test_support.rs @@ -96,6 +96,7 @@ impl FakeComputeDriver { default_image: "openshell/sandbox:test".to_string(), gateway_manages_lifecycle: false, supports_sandbox_authentication: false, + driver_reports_runtime_readiness: false, }, gateway_listener_requirements: Vec::new(), gateway_listener_requirements_supported: true, @@ -284,11 +285,13 @@ impl ComputeDriver for FakeComputeDriver { request: Request, ) -> Result, Status> { self.record_traceparent(request.metadata()); - let sandbox = request.into_inner().sandbox; + let request = request.into_inner(); self.with_state(|state| { state .calls - .push(FakeComputeDriverCall::ValidateSandboxCreate { sandbox }); + .push(FakeComputeDriverCall::ValidateSandboxCreate { + sandbox: request.sandbox, + }); }); Ok(Response::new(ValidateSandboxCreateResponse {})) } @@ -337,7 +340,8 @@ impl ComputeDriver for FakeComputeDriver { request: Request, ) -> Result, Status> { self.record_traceparent(request.metadata()); - let sandbox = request.into_inner().sandbox; + let request = request.into_inner(); + let sandbox = request.sandbox; self.with_state(|state| { if let Some(sandbox) = sandbox.as_ref() { state.sandboxes.insert(sandbox.id.clone(), sandbox.clone()); diff --git a/crates/openshell-server/src/tracing_setup.rs b/crates/openshell-server/src/tracing_setup.rs index edcf303072..2bc583dac7 100644 --- a/crates/openshell-server/src/tracing_setup.rs +++ b/crates/openshell-server/src/tracing_setup.rs @@ -11,14 +11,14 @@ use opentelemetry_sdk::trace::SdkTracerProvider; use tracing_subscriber::EnvFilter; use tracing_subscriber::prelude::*; -use crate::ConfiguredComputeDriver; use crate::config_file::OtlpConfig; -use crate::otel_tracing::{GatewayResourceAttributes, SetupError}; +use crate::otel_tracing::GatewayResourceAttributes; use crate::tracing_bus::TracingLogBus; +use crate::{ComputeDriverTracingSetup, ComputeDriverTracingShutdown}; pub struct TracingHandle { tracer_provider: Option, - driver_tracer_provider: Option, + compute_driver_shutdown: Option, } impl TracingHandle { @@ -28,205 +28,46 @@ impl TracingHandle { { tracing::warn!(error = %err, "OTLP tracer provider shutdown failed"); } - if let Some(provider) = &self.driver_tracer_provider - && let Err(err) = provider.shutdown() + if let Some(shutdown) = &self.compute_driver_shutdown + && let Err(err) = shutdown() { - tracing::warn!(error = %err, "compute-driver OTLP tracer provider shutdown failed"); - } - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum InProcessDriverTracing { - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - Docker, - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - Kubernetes, - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - Podman, -} - -impl InProcessDriverTracing { - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - fn target_prefix(self) -> &'static str { - match self { - Self::Docker => openshell_driver_docker::otel_tracing::IN_PROCESS_TARGET_PREFIX, - Self::Kubernetes => openshell_driver_kubernetes::otel_tracing::IN_PROCESS_TARGET_PREFIX, - Self::Podman => openshell_driver_podman::otel_tracing::IN_PROCESS_TARGET_PREFIX, + tracing::warn!(error = %err, "Compute driver tracing shutdown failed"); } } } -fn in_process_driver_tracing(driver: &ConfiguredComputeDriver) -> Option { - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - match driver { - ConfiguredComputeDriver::Registered(registration) if registration.name == "docker" => { - Some(InProcessDriverTracing::Docker) - } - ConfiguredComputeDriver::Registered(registration) if registration.name == "podman" => { - Some(InProcessDriverTracing::Podman) - } - ConfiguredComputeDriver::Registered(registration) if registration.name == "kubernetes" => { - Some(InProcessDriverTracing::Kubernetes) - } - _ => None, - } - #[cfg(not(all(not(target_os = "windows"), feature = "in-tree-compute-drivers")))] - { - let _ = driver; - None - } -} - -fn in_process_driver_target_prefix(driver: Option) -> Option<&'static str> { - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - { - driver.map(InProcessDriverTracing::target_prefix) - } - #[cfg(not(all(not(target_os = "windows"), feature = "in-tree-compute-drivers")))] - { - let _ = driver; - None - } -} - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -fn in_process_driver_provider( - driver: Option, - endpoint: Option<&str>, - gateway_name: Option<&str>, -) -> (Option, Option) { - match driver { - Some(InProcessDriverTracing::Docker) => { - openshell_driver_docker::otel_tracing::provider_for(endpoint, gateway_name) - } - Some(InProcessDriverTracing::Kubernetes) => { - openshell_driver_kubernetes::otel_tracing::provider_for(endpoint, gateway_name) - } - Some(InProcessDriverTracing::Podman) => { - openshell_driver_podman::otel_tracing::provider_for(endpoint, gateway_name) - } - None => (None, None), - } -} - -#[cfg(not(all(not(target_os = "windows"), feature = "in-tree-compute-drivers")))] -fn in_process_driver_provider( - _driver: Option, - _endpoint: Option<&str>, - _gateway_name: Option<&str>, -) -> (Option, Option) { - (None, None) -} - -#[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] -fn in_process_driver_layer( - provider: &Option, - driver: Option, -) -> Option> -where - S: tracing::Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>, -{ - provider.as_ref().map(|provider| match driver { - Some(InProcessDriverTracing::Docker) => { - openshell_driver_docker::otel_tracing::in_process_layer(provider) - } - Some(InProcessDriverTracing::Kubernetes) => { - openshell_driver_kubernetes::otel_tracing::in_process_layer(provider) - } - Some(InProcessDriverTracing::Podman) => { - openshell_driver_podman::otel_tracing::in_process_layer(provider) - } - None => unreachable!("a driver provider requires a selected driver"), - }) -} - -#[cfg(not(all(not(target_os = "windows"), feature = "in-tree-compute-drivers")))] -fn in_process_driver_layer( - _provider: &Option, - _driver: Option, -) -> Option> -where - S: tracing::Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>, -{ - None -} - pub fn install( env_filter: EnvFilter, tracing_log_bus: &TracingLogBus, otlp_config: Option<&OtlpConfig>, - driver: &ConfiguredComputeDriver, + compute_driver_tracing: ComputeDriverTracingSetup, gateway: GatewayResourceAttributes<'_>, -) -> (TracingHandle, Option) { +) -> (TracingHandle, Option) { let (tracer_provider, setup_error) = crate::otel_tracing::provider_for(otlp_config, gateway); - let selected_driver = in_process_driver_tracing(driver); - let driver_endpoint = selected_driver - .is_some() - .then_some(otlp_config) - .flatten() - .map(|config| config.endpoint.as_str()); - let (driver_tracer_provider, driver_setup_error) = - in_process_driver_provider(selected_driver, driver_endpoint, gateway.name()); + let ComputeDriverTracingSetup { + layer, + shutdown, + error, + target_prefix, + } = compute_driver_tracing; tracing_subscriber::registry() + .with(layer) .with(env_filter) .with(tracing_subscriber::fmt::layer()) .with(tracing_log_bus.layer()) - .with(tracer_provider.as_ref().map(|provider| { - crate::otel_tracing::layer_excluding_driver( - provider, - in_process_driver_target_prefix(selected_driver), - ) - })) - .with(in_process_driver_layer( - &driver_tracer_provider, - selected_driver, - )) + .with( + tracer_provider + .as_ref() + .map(|provider| crate::otel_tracing::layer(provider, target_prefix)), + ) .init(); ( TracingHandle { tracer_provider, - driver_tracer_provider, + compute_driver_shutdown: shutdown, }, - setup_error.or(driver_setup_error), + setup_error.map(|error| error.to_string()).or(error), ) } - -#[cfg(test)] -mod tests { - use super::*; - - #[cfg(all(not(target_os = "windows"), feature = "in-tree-compute-drivers"))] - #[test] - fn in_process_driver_tracing_selects_registered_compute_drivers() { - let registry = crate::install_default_compute_drivers(); - let registered = |name| { - ConfiguredComputeDriver::Registered( - registry - .get(name) - .unwrap_or_else(|| panic!("{name} driver is registered")) - .clone(), - ) - }; - assert_eq!( - in_process_driver_tracing(®istered("podman")), - Some(InProcessDriverTracing::Podman) - ); - assert_eq!( - in_process_driver_tracing(®istered("docker")), - Some(InProcessDriverTracing::Docker) - ); - assert_eq!( - in_process_driver_tracing(®istered("kubernetes")), - Some(InProcessDriverTracing::Kubernetes) - ); - assert_eq!( - in_process_driver_tracing(&ConfiguredComputeDriver::Remote { - name: "custom".to_string(), - }), - None - ); - } -} diff --git a/crates/openshell-server/tests/common/mod.rs b/crates/openshell-server/tests/common/mod.rs index 9e3957abb6..a60fc8696b 100644 --- a/crates/openshell-server/tests/common/mod.rs +++ b/crates/openshell-server/tests/common/mod.rs @@ -98,6 +98,34 @@ impl OpenShell for TestOpenShell { Ok(Response::new(SandboxResponse::default())) } + async fn create_sandbox_template( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + + async fn get_sandbox_template( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + + async fn list_sandbox_templates( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + + async fn delete_sandbox_template( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + async fn stop_sandbox( &self, _request: tonic::Request, diff --git a/crates/openshell-server/tests/supervisor_relay_integration.rs b/crates/openshell-server/tests/supervisor_relay_integration.rs index 6cfd3b009b..91ac50dcbd 100644 --- a/crates/openshell-server/tests/supervisor_relay_integration.rs +++ b/crates/openshell-server/tests/supervisor_relay_integration.rs @@ -82,6 +82,34 @@ impl OpenShell for RelayGateway { // ------ unused stubs ------ + async fn create_sandbox_template( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + + async fn get_sandbox_template( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + + async fn list_sandbox_templates( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + + async fn delete_sandbox_template( + &self, + _request: tonic::Request, + ) -> Result, Status> { + Err(Status::unimplemented("unused")) + } + type ConnectSupervisorStream = ReceiverStream>; async fn connect_supervisor( &self, diff --git a/crates/openshell-tui/src/app.rs b/crates/openshell-tui/src/app.rs index 13a00aaca3..cf7464fcd8 100644 --- a/crates/openshell-tui/src/app.rs +++ b/crates/openshell-tui/src/app.rs @@ -1407,6 +1407,9 @@ impl App { self.input_mode = InputMode::Command; self.command_input.clear(); } + KeyCode::Char('w') => { + self.cycle_workspace(); + } KeyCode::Char('j') | KeyCode::Down => { if self.provider_count > 0 && self.provider_selected < self.provider_count - 1 { self.provider_selected += 1; @@ -3825,6 +3828,32 @@ mod tests { assert_eq!(gateway.source_label(), "unknown"); } + #[tokio::test] + async fn providers_workspace_shortcut_cycles_scope_and_resets_selections() { + let mut app = test_app(); + app.screen = Screen::Dashboard; + app.focus = Focus::Providers; + app.workspace_names = vec!["default".to_string(), "team-b".to_string()]; + app.provider_selected = 3; + app.sandbox_selected = 4; + + app.handle_key(key(KeyCode::Char('w'))); + + assert_eq!(app.current_workspace, "team-b"); + assert!(!app.all_workspaces); + assert_eq!(app.provider_selected, 0); + assert_eq!(app.sandbox_selected, 0); + assert!(app.pending_workspace_refresh); + + app.handle_key(key(KeyCode::Char('w'))); + assert!(app.all_workspaces); + assert_eq!(app.workspace_display(), "all"); + + app.handle_key(key(KeyCode::Char('w'))); + assert!(!app.all_workspaces); + assert_eq!(app.current_workspace, "default"); + } + // -- selected_sandbox_workspace ---------------------------------------- #[test] diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index f08f44a3ac..174f9910d0 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -1405,6 +1405,7 @@ fn spawn_create_sandbox(app: &mut App, tx: mpsc::UnboundedSender) { annotations: HashMap::new(), workspace: workspace.clone(), await_main_process_attachment: false, + workload_template_name: String::new(), }; let sandbox_name = diff --git a/crates/openshell-tui/src/ui/mod.rs b/crates/openshell-tui/src/ui/mod.rs index 7ad1589186..01171fdb5d 100644 --- a/crates/openshell-tui/src/ui/mod.rs +++ b/crates/openshell-tui/src/ui/mod.rs @@ -223,6 +223,9 @@ fn draw_nav_bar(frame: &mut Frame<'_>, app: &App, area: Rect) { Span::styled(" ", t.text), Span::styled("[c/u/d]", t.key_hint), Span::styled(" Create/Update/Delete", t.text), + Span::styled(" ", t.text), + Span::styled("[w]", t.key_hint), + Span::styled(" Workspace", t.text), Span::styled(" | ", t.border), Span::styled("[:]", t.muted), Span::styled(" Command ", t.muted), @@ -662,3 +665,46 @@ pub fn centered_popup(percent_x: u16, height: u16, area: Rect) -> Rect { ]) .split(vert[1])[1] } + +#[cfg(test)] +mod tests { + use super::*; + use openshell_core::auth::EdgeAuthInterceptor; + use openshell_core::proto::open_shell_client::OpenShellClient; + use ratatui::Terminal; + use ratatui::backend::TestBackend; + + fn test_app() -> App { + let channel = tonic::transport::Endpoint::from_static("http://127.0.0.1:1").connect_lazy(); + let client = OpenShellClient::with_interceptor(channel, EdgeAuthInterceptor::noop()); + let mut app = App::new( + client, + "test".to_string(), + "http://127.0.0.1:1".to_string(), + "default".to_string(), + Theme::dark(), + ); + app.screen = Screen::Dashboard; + app.focus = Focus::Providers; + app + } + + #[tokio::test] + async fn providers_navigation_advertises_workspace_shortcut() { + let app = test_app(); + let mut terminal = Terminal::new(TestBackend::new(180, 1)).unwrap(); + + terminal + .draw(|frame| draw_nav_bar(frame, &app, frame.size())) + .unwrap(); + + let text: String = terminal + .backend() + .buffer() + .content() + .iter() + .map(ratatui::buffer::Cell::symbol) + .collect(); + assert!(text.contains("[w] Workspace"), "nav bar was: {text:?}"); + } +} diff --git a/deploy/docker/Dockerfile.gateway-macos b/deploy/docker/Dockerfile.gateway-macos index 122f16eba8..c7d526a039 100644 --- a/deploy/docker/Dockerfile.gateway-macos +++ b/deploy/docker/Dockerfile.gateway-macos @@ -53,6 +53,7 @@ ENV BINDGEN_EXTRA_CLANG_ARGS_aarch64_apple_darwin=--target=arm64-apple-macosx\ - COPY Cargo.toml Cargo.lock ./ COPY crates/openshell-core/Cargo.toml crates/openshell-core/Cargo.toml +COPY crates/openshell-gateway/Cargo.toml crates/openshell-gateway/Cargo.toml COPY crates/openshell-driver-kubernetes/Cargo.toml crates/openshell-driver-kubernetes/Cargo.toml COPY crates/openshell-policy/Cargo.toml crates/openshell-policy/Cargo.toml COPY crates/openshell-prover/Cargo.toml crates/openshell-prover/Cargo.toml @@ -61,39 +62,42 @@ COPY crates/openshell-server/Cargo.toml crates/openshell-server/Cargo.toml COPY crates/openshell-core/build.rs crates/openshell-core/build.rs COPY proto/ proto/ -RUN sed -i 's|members = \["crates/\*"\]|members = ["crates/openshell-server", "crates/openshell-core", "crates/openshell-driver-kubernetes", "crates/openshell-policy", "crates/openshell-prover", "crates/openshell-router"]|' Cargo.toml +RUN sed -i 's|members = \["crates/\*"\]|members = ["crates/openshell-gateway", "crates/openshell-server", "crates/openshell-core", "crates/openshell-driver-kubernetes", "crates/openshell-policy", "crates/openshell-prover", "crates/openshell-router"]|' Cargo.toml RUN mkdir -p crates/openshell-core/src \ + crates/openshell-gateway/src \ crates/openshell-driver-kubernetes/src \ crates/openshell-policy/src \ crates/openshell-prover/src \ crates/openshell-router/src \ crates/openshell-server/src && \ touch crates/openshell-core/src/lib.rs && \ + touch crates/openshell-gateway/src/lib.rs && \ + printf 'fn main() {}\n' > crates/openshell-gateway/src/main.rs && \ touch crates/openshell-driver-kubernetes/src/lib.rs && \ printf 'fn main() {}\n' > crates/openshell-driver-kubernetes/src/main.rs && \ touch crates/openshell-policy/src/lib.rs && \ touch crates/openshell-prover/src/lib.rs && \ touch crates/openshell-router/src/lib.rs && \ - touch crates/openshell-server/src/lib.rs && \ - printf 'fn main() {}\n' > crates/openshell-server/src/main.rs + touch crates/openshell-server/src/lib.rs RUN --mount=type=cache,id=cargo-registry-gateway-macos,sharing=locked,target=/root/.cargo/registry \ --mount=type=cache,id=cargo-git-gateway-macos,sharing=locked,target=/root/.cargo/git \ --mount=type=cache,id=cargo-target-gateway-macos-${CARGO_TARGET_CACHE_SCOPE},sharing=locked,target=/build/target \ - cargo build --release --target aarch64-apple-darwin -p openshell-server --features bundled-z3 2>/dev/null || true + cargo build --release --target aarch64-apple-darwin -p openshell-gateway --features bundled-z3 2>/dev/null || true COPY crates/ crates/ COPY providers/ providers/ RUN touch crates/openshell-core/src/lib.rs \ + crates/openshell-gateway/src/lib.rs \ + crates/openshell-gateway/src/main.rs \ crates/openshell-driver-kubernetes/src/lib.rs \ crates/openshell-driver-kubernetes/src/main.rs \ crates/openshell-policy/src/lib.rs \ crates/openshell-prover/src/lib.rs \ crates/openshell-router/src/lib.rs \ crates/openshell-server/src/lib.rs \ - crates/openshell-server/src/main.rs \ crates/openshell-core/build.rs \ proto/*.proto @@ -105,7 +109,7 @@ RUN --mount=type=cache,id=cargo-registry-gateway-macos,sharing=locked,target=/ro if [ -n "${OPENSHELL_CARGO_VERSION:-}" ]; then \ sed -i -E '/^\[workspace\.package\]/,/^\[/{s/^version[[:space:]]*=[[:space:]]*".*"/version = "'"${OPENSHELL_CARGO_VERSION}"'"/}' Cargo.toml; \ fi && \ - cargo build --release --target aarch64-apple-darwin -p openshell-server --features bundled-z3 && \ + cargo build --release --target aarch64-apple-darwin -p openshell-gateway --features bundled-z3 && \ cp target/aarch64-apple-darwin/release/openshell-gateway /openshell-gateway FROM scratch AS binary diff --git a/deploy/helm/openshell-workspace/Chart.yaml b/deploy/helm/openshell-workspace/Chart.yaml new file mode 100644 index 0000000000..03a3919d46 --- /dev/null +++ b/deploy/helm/openshell-workspace/Chart.yaml @@ -0,0 +1,9 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +apiVersion: v2 +name: openshell-workspace +description: Namespace-scoped prerequisites for OpenShell Kubernetes sandboxes +type: application +version: 0.0.0 +appVersion: "0.0.0" diff --git a/deploy/helm/openshell-workspace/README.md b/deploy/helm/openshell-workspace/README.md new file mode 100644 index 0000000000..96ae4ca6e4 --- /dev/null +++ b/deploy/helm/openshell-workspace/README.md @@ -0,0 +1,47 @@ +# OpenShell Workspace Helm Chart + + + +> **Experimental** - the shared-gateway, multi-namespace deployment path is +> under active design. + +This chart installs the namespace-scoped ServiceAccount, RBAC, and NetworkPolicy +needed for OpenShell Kubernetes sandboxes. Install it once in every +platform-managed workspace namespace. It does not create a namespace or deploy +an OpenShell gateway. + +Install the gateway chart with `workspaceResources.enabled=false`, then install +this chart with the gateway ServiceAccount identity. Configure the gateway's +Kubernetes driver in `operator` workspace mode when it serves more than one +pre-provisioned workspace namespace: + +```shell +helm install openshell-workspace ./deploy/helm/openshell-workspace \ + --namespace app-a \ + --set gateway.serviceAccount.name=openshell \ + --set gateway.serviceAccount.namespace=openshell +``` + +Keep `sandboxServiceAccount.name` aligned with the gateway chart's +`sandboxServiceAccount.name`. The defaults for both charts are +`openshell-sandbox`. + +## Values + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| fullnameOverride | string | `""` | Override the full generated resource name. | +| gateway.networkPolicy.podSelector | object | `{"app.kubernetes.io/instance":"openshell","app.kubernetes.io/name":"openshell"}` | Labels selecting gateway pods allowed to reach sandbox SSH. | +| gateway.serviceAccount.name | string | `"openshell"` | Name of the shared gateway ServiceAccount. | +| gateway.serviceAccount.namespace | string | `"openshell"` | Namespace containing the shared gateway ServiceAccount. | +| nameOverride | string | `""` | Override the chart name used in generated resource names. | +| networkPolicy.enabled | bool | `true` | Restrict sandbox SSH ingress to the shared gateway pods. | +| sandboxServiceAccount.annotations | object | `{}` | Annotations added to the generated sandbox ServiceAccount. | +| sandboxServiceAccount.create | bool | `true` | Create the ServiceAccount assigned to sandbox pods. | +| sandboxServiceAccount.name | string | `"openshell-sandbox"` | Sandbox ServiceAccount name. | + +---------------------------------------------- +Autogenerated from chart metadata using [helm-docs v1.14.2](https://github.com/norwoodj/helm-docs/releases/v1.14.2) diff --git a/deploy/helm/openshell-workspace/README.md.gotmpl b/deploy/helm/openshell-workspace/README.md.gotmpl new file mode 100644 index 0000000000..a233eef165 --- /dev/null +++ b/deploy/helm/openshell-workspace/README.md.gotmpl @@ -0,0 +1,33 @@ +# OpenShell Workspace Helm Chart + + + +> **Experimental** - the shared-gateway, multi-namespace deployment path is +> under active design. + +This chart installs the namespace-scoped ServiceAccount, RBAC, and NetworkPolicy +needed for OpenShell Kubernetes sandboxes. Install it once in every +platform-managed workspace namespace. It does not create a namespace or deploy +an OpenShell gateway. + +Install the gateway chart with `workspaceResources.enabled=false`, then install +this chart with the gateway ServiceAccount identity. Configure the gateway's +Kubernetes driver in `operator` workspace mode when it serves more than one +pre-provisioned workspace namespace: + +```shell +helm install openshell-workspace ./deploy/helm/openshell-workspace \ + --namespace app-a \ + --set gateway.serviceAccount.name=openshell \ + --set gateway.serviceAccount.namespace=openshell +``` + +Keep `sandboxServiceAccount.name` aligned with the gateway chart's +`sandboxServiceAccount.name`. The defaults for both charts are +`openshell-sandbox`. + +{{ template "chart.valuesSection" . }} +{{ template "helm-docs.versionFooter" . }} diff --git a/deploy/helm/openshell-workspace/templates/_helpers.tpl b/deploy/helm/openshell-workspace/templates/_helpers.tpl new file mode 100644 index 0000000000..eb948b9907 --- /dev/null +++ b/deploy/helm/openshell-workspace/templates/_helpers.tpl @@ -0,0 +1,44 @@ +{{/* +Expand the name of the chart. +*/}} +{{- define "openshell-workspace.name" -}} +{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} +{{- end }} + +{{/* +Create a default fully qualified app name. +*/}} +{{- define "openshell-workspace.fullname" -}} +{{- if .Values.fullnameOverride }} +{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- $name := default .Chart.Name .Values.nameOverride }} +{{- if contains $name .Release.Name }} +{{- .Release.Name | trunc 63 | trimSuffix "-" }} +{{- else }} +{{- printf "%s-%s" .Release.Name $name | trunc 63 | trimSuffix "-" }} +{{- end }} +{{- end }} +{{- end }} + +{{/* +Common labels. +*/}} +{{- define "openshell-workspace.labels" -}} +helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} +app.kubernetes.io/name: {{ include "openshell-workspace.name" . }} +app.kubernetes.io/instance: {{ .Release.Name }} +{{- if .Chart.AppVersion }} +app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} +{{- end }} +app.kubernetes.io/managed-by: {{ .Release.Service }} +{{- end }} + +{{/* +Validate required cross-namespace gateway identity values. +*/}} +{{- define "openshell-workspace.validateValues" -}} +{{- $gatewayServiceAccountName := required "gateway.serviceAccount.name is required" .Values.gateway.serviceAccount.name -}} +{{- $gatewayServiceAccountNamespace := required "gateway.serviceAccount.namespace is required" .Values.gateway.serviceAccount.namespace -}} +{{- $sandboxServiceAccountName := required "sandboxServiceAccount.name is required" .Values.sandboxServiceAccount.name -}} +{{- end }} diff --git a/deploy/helm/openshell-workspace/templates/networkpolicy.yaml b/deploy/helm/openshell-workspace/templates/networkpolicy.yaml new file mode 100644 index 0000000000..f88cf84d04 --- /dev/null +++ b/deploy/helm/openshell-workspace/templates/networkpolicy.yaml @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +{{- include "openshell-workspace.validateValues" . }} +{{- if .Values.networkPolicy.enabled }} +apiVersion: networking.k8s.io/v1 +kind: NetworkPolicy +metadata: + name: {{ include "openshell-workspace.fullname" . }}-sandbox-ssh + namespace: {{ .Release.Namespace }} + labels: + {{- include "openshell-workspace.labels" . | nindent 4 }} +spec: + podSelector: + matchLabels: + openshell.ai/managed-by: openshell + policyTypes: + - Ingress + ingress: + - from: + - namespaceSelector: + matchLabels: + kubernetes.io/metadata.name: {{ .Values.gateway.serviceAccount.namespace }} + podSelector: + matchLabels: + {{- toYaml .Values.gateway.networkPolicy.podSelector | nindent 14 }} + ports: + - protocol: TCP + port: 2222 +{{- end }} diff --git a/deploy/helm/openshell-workspace/templates/role.yaml b/deploy/helm/openshell-workspace/templates/role.yaml new file mode 100644 index 0000000000..45b3beb831 --- /dev/null +++ b/deploy/helm/openshell-workspace/templates/role.yaml @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +{{- include "openshell-workspace.validateValues" . }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "openshell-workspace.fullname" . }}-sandbox + namespace: {{ .Release.Namespace }} + labels: + {{- include "openshell-workspace.labels" . | nindent 4 }} +rules: + - apiGroups: + - agents.x-k8s.io + resources: + - sandboxes + - sandboxes/status + verbs: + - create + - delete + - get + - list + - patch + - update + - watch + - apiGroups: + - "" + resources: + - events + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - pods + verbs: + - get diff --git a/deploy/helm/openshell-workspace/templates/rolebinding.yaml b/deploy/helm/openshell-workspace/templates/rolebinding.yaml new file mode 100644 index 0000000000..669ec47628 --- /dev/null +++ b/deploy/helm/openshell-workspace/templates/rolebinding.yaml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +{{- include "openshell-workspace.validateValues" . }} +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "openshell-workspace.fullname" . }}-sandbox + namespace: {{ .Release.Namespace }} + labels: + {{- include "openshell-workspace.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "openshell-workspace.fullname" . }}-sandbox +subjects: + - kind: ServiceAccount + name: {{ .Values.gateway.serviceAccount.name }} + namespace: {{ .Values.gateway.serviceAccount.namespace }} diff --git a/deploy/helm/openshell-workspace/templates/serviceaccount.yaml b/deploy/helm/openshell-workspace/templates/serviceaccount.yaml new file mode 100644 index 0000000000..20bb263b54 --- /dev/null +++ b/deploy/helm/openshell-workspace/templates/serviceaccount.yaml @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +{{- include "openshell-workspace.validateValues" . }} +{{- if .Values.sandboxServiceAccount.create }} +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ .Values.sandboxServiceAccount.name }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openshell-workspace.labels" . | nindent 4 }} + {{- with .Values.sandboxServiceAccount.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} +{{- end }} diff --git a/deploy/helm/openshell-workspace/tests/workspace_test.yaml b/deploy/helm/openshell-workspace/tests/workspace_test.yaml new file mode 100644 index 0000000000..2f71920eaf --- /dev/null +++ b/deploy/helm/openshell-workspace/tests/workspace_test.yaml @@ -0,0 +1,61 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +suite: workspace namespace resources +templates: + - templates/serviceaccount.yaml + - templates/role.yaml + - templates/rolebinding.yaml + - templates/networkpolicy.yaml +release: + name: tenant-a + namespace: app-a + +tests: + - it: creates the workspace role in the release namespace + template: templates/role.yaml + asserts: + - hasDocuments: + count: 1 + - equal: + path: metadata.namespace + value: app-a + + - it: binds the shared gateway service account + template: templates/rolebinding.yaml + set: + gateway.serviceAccount.name: shared-gateway + gateway.serviceAccount.namespace: openshell-system + asserts: + - equal: + path: metadata.namespace + value: app-a + - equal: + path: subjects[0].name + value: shared-gateway + - equal: + path: subjects[0].namespace + value: openshell-system + + - it: selects gateway pods in the gateway namespace + template: templates/networkpolicy.yaml + set: + gateway.serviceAccount.namespace: openshell-system + gateway.networkPolicy.podSelector: + app.kubernetes.io/name: openshell + app.kubernetes.io/instance: central + asserts: + - equal: + path: spec.ingress[0].from[0].namespaceSelector.matchLabels["kubernetes.io/metadata.name"] + value: openshell-system + - equal: + path: spec.ingress[0].from[0].podSelector.matchLabels["app.kubernetes.io/instance"] + value: central + + - it: supports a pre-existing sandbox service account + template: templates/serviceaccount.yaml + set: + sandboxServiceAccount.create: false + asserts: + - hasDocuments: + count: 0 diff --git a/deploy/helm/openshell-workspace/values.yaml b/deploy/helm/openshell-workspace/values.yaml new file mode 100644 index 0000000000..2c52b0460d --- /dev/null +++ b/deploy/helm/openshell-workspace/values.yaml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# -- Override the chart name used in generated resource names. +nameOverride: "" +# -- Override the full generated resource name. +fullnameOverride: "" + +gateway: + serviceAccount: + # -- Name of the shared gateway ServiceAccount. + name: openshell + # -- Namespace containing the shared gateway ServiceAccount. + namespace: openshell + networkPolicy: + # -- Labels selecting gateway pods allowed to reach sandbox SSH. + podSelector: + app.kubernetes.io/name: openshell + app.kubernetes.io/instance: openshell + +sandboxServiceAccount: + # -- Create the ServiceAccount assigned to sandbox pods. + create: true + # -- Sandbox ServiceAccount name. + name: openshell-sandbox + # -- Annotations added to the generated sandbox ServiceAccount. + annotations: {} + +networkPolicy: + # -- Restrict sandbox SSH ingress to the shared gateway pods. + enabled: true diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 9d1b9cd7dd..7dbd7964d0 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -9,6 +9,14 @@ Edit README.md.gotmpl and values.yaml, then run `mise run helm:docs`. This chart deploys the OpenShell gateway into a Kubernetes cluster. It is published as an OCI artifact to GHCR at `oci://ghcr.io/nvidia/openshell/helm-chart`. +By default, this chart also creates the namespace-scoped resources needed by +sandboxes. For a shared-gateway deployment, install it with +`workspaceResources.enabled=false`, then install the +`deploy/helm/openshell-workspace` chart in every pre-provisioned workspace +namespace. The gateway and workspace releases can then be upgraded and removed +independently. Use Kubernetes `operator` workspace mode when one gateway serves +multiple pre-provisioned workspace namespaces. + ## Prerequisites The Kubernetes Agent Sandbox CRDs and controller must be installed on the cluster before deploying OpenShell. Install them with: @@ -306,6 +314,7 @@ discovery endpoint or its TLS CA. | upstreamProxy.url | string | `""` | HTTP proxy URL in http://host:port form. HTTPS-to-proxy is not supported. | | workload.allowMultiReplicaStatefulSet | bool | `false` | Allow replicaCount > 1 while rendering a StatefulSet. Prefer workload.kind=deployment for external database-backed multi-replica gateways; this override exists for operators who explicitly require StatefulSet identity or storage semantics. | | workload.kind | string | `"statefulset"` | Gateway workload controller kind. Use `statefulset` for the default SQLite database, or `deployment` when server.externalDbSecret points at an external database. | +| workspaceResources.enabled | bool | `true` | Create the sandbox ServiceAccount, Role, RoleBinding, and NetworkPolicy from this chart. Disable for a gateway-only release. | ---------------------------------------------- Autogenerated from chart metadata using [helm-docs v1.14.2](https://github.com/norwoodj/helm-docs/releases/v1.14.2) diff --git a/deploy/helm/openshell/README.md.gotmpl b/deploy/helm/openshell/README.md.gotmpl index 73ebb39c88..cf8677741e 100644 --- a/deploy/helm/openshell/README.md.gotmpl +++ b/deploy/helm/openshell/README.md.gotmpl @@ -9,6 +9,14 @@ Edit README.md.gotmpl and values.yaml, then run `mise run helm:docs`. This chart deploys the OpenShell gateway into a Kubernetes cluster. It is published as an OCI artifact to GHCR at `oci://ghcr.io/nvidia/openshell/helm-chart`. +By default, this chart also creates the namespace-scoped resources needed by +sandboxes. For a shared-gateway deployment, install it with +`workspaceResources.enabled=false`, then install the +`deploy/helm/openshell-workspace` chart in every pre-provisioned workspace +namespace. The gateway and workspace releases can then be upgraded and removed +independently. Use Kubernetes `operator` workspace mode when one gateway serves +multiple pre-provisioned workspace namespaces. + ## Prerequisites The Kubernetes Agent Sandbox CRDs and controller must be installed on the cluster before deploying OpenShell. Install them with: diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index 5b67c018c4..3d9f2f3e0b 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -70,6 +70,19 @@ Create the name of the service account assigned to sandbox pods {{- end }} {{- end }} +{{/* +Whether this chart owns workspace-scoped resources. Missing legacy values +default to enabled so upgrades with --reuse-values preserve the old topology. +*/}} +{{- define "openshell.workspaceResourcesEnabled" -}} +{{- $workspaceResources := .Values.workspaceResources | default dict -}} +{{- $enabled := true -}} +{{- if hasKey $workspaceResources "enabled" -}} +{{- $enabled = get $workspaceResources "enabled" -}} +{{- end -}} +{{- if $enabled -}}true{{- end -}} +{{- end }} + {{/* Gateway image reference. Uses image.tag when set; falls back to .Chart.AppVersion so a released chart automatically pulls the matching image without extra overrides. diff --git a/deploy/helm/openshell/templates/networkpolicy.yaml b/deploy/helm/openshell/templates/networkpolicy.yaml index e85571e5f5..c9e4a760e3 100644 --- a/deploy/helm/openshell/templates/networkpolicy.yaml +++ b/deploy/helm/openshell/templates/networkpolicy.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -{{- if .Values.networkPolicy.enabled }} +{{- if and (include "openshell.workspaceResourcesEnabled" .) .Values.networkPolicy.enabled }} # NetworkPolicy restricting SSH ingress on sandbox pods to the gateway pod. # Sandbox pods are dynamically created by the server and labelled with # openshell.ai/managed-by=openshell. This policy ensures only the gateway diff --git a/deploy/helm/openshell/templates/role.yaml b/deploy/helm/openshell/templates/role.yaml index 8def13f310..dfd6423615 100644 --- a/deploy/helm/openshell/templates/role.yaml +++ b/deploy/helm/openshell/templates/role.yaml @@ -1,5 +1,5 @@ {{- $workspaceMode := .Values.server.drivers.kubernetes.workspaceMode | default "shared" -}} -{{- if eq $workspaceMode "shared" }} +{{- if and (eq $workspaceMode "shared") (include "openshell.workspaceResourcesEnabled" .) }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 apiVersion: rbac.authorization.k8s.io/v1 diff --git a/deploy/helm/openshell/templates/rolebinding.yaml b/deploy/helm/openshell/templates/rolebinding.yaml index 381473a58b..32f11644bf 100644 --- a/deploy/helm/openshell/templates/rolebinding.yaml +++ b/deploy/helm/openshell/templates/rolebinding.yaml @@ -1,5 +1,5 @@ {{- $workspaceMode := .Values.server.drivers.kubernetes.workspaceMode | default "shared" -}} -{{- if eq $workspaceMode "shared" }} +{{- if and (eq $workspaceMode "shared") (include "openshell.workspaceResourcesEnabled" .) }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 apiVersion: rbac.authorization.k8s.io/v1 diff --git a/deploy/helm/openshell/templates/serviceaccount.yaml b/deploy/helm/openshell/templates/serviceaccount.yaml index a98ad5363e..1a9245d4dc 100644 --- a/deploy/helm/openshell/templates/serviceaccount.yaml +++ b/deploy/helm/openshell/templates/serviceaccount.yaml @@ -13,10 +13,10 @@ metadata: {{- toYaml . | nindent 4 }} {{- end }} {{- end }} -{{- if and .Values.serviceAccount.create .Values.sandboxServiceAccount.create }} +{{- if and .Values.serviceAccount.create (include "openshell.workspaceResourcesEnabled" .) .Values.sandboxServiceAccount.create }} --- {{- end }} -{{- if .Values.sandboxServiceAccount.create }} +{{- if and (include "openshell.workspaceResourcesEnabled" .) .Values.sandboxServiceAccount.create }} apiVersion: v1 kind: ServiceAccount metadata: diff --git a/deploy/helm/openshell/tests/sandbox_namespace_test.yaml b/deploy/helm/openshell/tests/sandbox_namespace_test.yaml index ee89fce53d..864e3a8512 100644 --- a/deploy/helm/openshell/tests/sandbox_namespace_test.yaml +++ b/deploy/helm/openshell/tests/sandbox_namespace_test.yaml @@ -75,3 +75,21 @@ tests: path: metadata.namespace value: other-ns documentIndex: 1 + + - it: omits workspace resources in gateway-only mode + set: + workspaceResources.enabled: false + networkPolicy.enabled: true + asserts: + - hasDocuments: + count: 1 + template: templates/gateway-config.yaml + - hasDocuments: + count: 0 + template: templates/networkpolicy.yaml + - hasDocuments: + count: 0 + template: templates/role.yaml + - hasDocuments: + count: 0 + template: templates/rolebinding.yaml diff --git a/deploy/helm/openshell/tests/sandbox_service_account_test.yaml b/deploy/helm/openshell/tests/sandbox_service_account_test.yaml index c426415823..c9f10868fe 100644 --- a/deploy/helm/openshell/tests/sandbox_service_account_test.yaml +++ b/deploy/helm/openshell/tests/sandbox_service_account_test.yaml @@ -29,3 +29,13 @@ tests: asserts: - hasDocuments: count: 1 + + - it: renders only the gateway service account in gateway-only mode + set: + workspaceResources.enabled: false + asserts: + - hasDocuments: + count: 1 + - equal: + path: metadata.name + value: openshell diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 25236eb474..8f5b6fa51a 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -102,6 +102,14 @@ sandboxServiceAccount: # -- Existing service account name for sandbox pods when sandboxServiceAccount.create is false. name: "" +# Namespace-scoped resources needed to run sandboxes. Disable this when the +# gateway and workspace prerequisites are managed as separate Helm releases +# using the openshell-workspace chart. +workspaceResources: + # -- Create the sandbox ServiceAccount, Role, RoleBinding, and NetworkPolicy + # from this chart. Disable for a gateway-only release. + enabled: true + # -- Extra annotations to add to the gateway pod. podAnnotations: {} # -- Extra labels to add to the gateway pod. diff --git a/deploy/helm/test-split-ownership.sh b/deploy/helm/test-split-ownership.sh new file mode 100755 index 0000000000..30fd7360d4 --- /dev/null +++ b/deploy/helm/test-split-ownership.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd -P)" +work_dir="$(mktemp -d)" +trap 'rm -rf "${work_dir}"' EXIT + +helm template openshell "${repo_root}/deploy/helm/openshell" \ + --namespace openshell \ + --set agentSandbox.preflight.enabled=false \ + --set workspaceResources.enabled=false \ + >"${work_dir}/gateway.yaml" + +if yq ea -e \ + 'select(.kind == "Role" and .metadata.name == "openshell-sandbox")' \ + "${work_dir}/gateway.yaml" >/dev/null 2>&1; then + echo "gateway chart rendered workspace resources despite workspaceResources.enabled=false" >&2 + exit 1 +fi + +helm template openshell-workspace "${repo_root}/deploy/helm/openshell-workspace" \ + --namespace app-a \ + --set gateway.serviceAccount.name=openshell \ + --set gateway.serviceAccount.namespace=openshell \ + >"${work_dir}/workspace.yaml" + +invalid_workspace_docs="$( + yq ea -N -r \ + 'select(. != null and (.apiVersion == null or .kind == null)) | document_index' \ + "${work_dir}/workspace.yaml" +)" +if [[ -n "${invalid_workspace_docs}" ]]; then + echo "workspace chart rendered documents without apiVersion or kind: ${invalid_workspace_docs}" >&2 + exit 1 +fi + +helm template openshell "${repo_root}/deploy/helm/openshell" \ + --namespace openshell \ + --set agentSandbox.preflight.enabled=false \ + --set-json workspaceResources=null \ + >"${work_dir}/legacy-reuse-values.yaml" + +yq ea -e \ + 'select(.kind == "Role" and .metadata.name == "openshell-sandbox") | + .apiVersion == "rbac.authorization.k8s.io/v1"' \ + "${work_dir}/legacy-reuse-values.yaml" >/dev/null + +yq ea -N -r \ + 'select(.kind != null) | [.apiVersion, .kind, (.metadata.namespace // "openshell"), .metadata.name] | @tsv' \ + "${work_dir}/gateway.yaml" | sort -u >"${work_dir}/gateway.objects" +yq ea -N -r \ + 'select(.kind != null) | [.apiVersion, .kind, (.metadata.namespace // "app-a"), .metadata.name] | @tsv' \ + "${work_dir}/workspace.yaml" | sort -u >"${work_dir}/workspace.objects" + +comm -12 "${work_dir}/gateway.objects" "${work_dir}/workspace.objects" \ + >"${work_dir}/overlap.objects" +if [[ -s "${work_dir}/overlap.objects" ]]; then + echo "gateway and workspace charts claim the same Kubernetes objects:" >&2 + cat "${work_dir}/overlap.objects" >&2 + exit 1 +fi + +echo "gateway and workspace chart object ownership is disjoint" diff --git a/docs/kubernetes/setup.mdx b/docs/kubernetes/setup.mdx index 221f935eb6..fb7881af2d 100644 --- a/docs/kubernetes/setup.mdx +++ b/docs/kubernetes/setup.mdx @@ -99,6 +99,36 @@ helm upgrade --install openshell \ The chart automatically generates PKI secrets on first install using pre-install Helm hooks. No manual secret creation is required. +### Split gateway and workspace releases + +For a platform-managed namespace, install the gateway without namespace-scoped +sandbox resources, then install the workspace chart in the sandbox namespace: + +```shell +helm upgrade --install openshell \ + oci://ghcr.io/nvidia/openshell/helm-chart \ + --version \ + --namespace openshell \ + --set workspaceResources.enabled=false \ + --set server.sandboxNamespace=app-a + +helm upgrade --install openshell-workspace \ + oci://ghcr.io/nvidia/openshell/openshell-workspace \ + --version \ + --namespace app-a \ + --set gateway.serviceAccount.name=openshell \ + --set gateway.serviceAccount.namespace=openshell +``` + +The workspace chart does not create the namespace or deploy a gateway. It owns +only the sandbox ServiceAccount, Role, RoleBinding, and NetworkPolicy in its +release namespace. For one pre-provisioned namespace, keep +`server.drivers.kubernetes.workspaceMode=shared` and set +`server.sandboxNamespace=app-a`. To map multiple workspaces to separately +provisioned namespaces, use `workspaceMode=operator`, configure exactly one of +`operatorNamespaceLabel` or `operatorNamespaceFile`, and install the workspace +chart in every allowlisted namespace. + ## Wait for the gateway to be ready ```shell @@ -163,6 +193,7 @@ The most commonly changed values are: | `workload.kind` | Gateway workload controller. Use `statefulset` for SQLite or `deployment` with `server.externalDbSecret`. | | `workload.allowMultiReplicaStatefulSet` | Allow `replicaCount > 1` with `workload.kind=statefulset`. Prefer Deployment for external database-backed multi-replica gateways. | | `server.sandboxNamespace` | Namespace where sandbox pods are created. Defaults to the Helm release namespace when left empty. | +| `workspaceResources.enabled` | Create namespace-scoped sandbox prerequisites from the gateway chart. Disable when installing the workspace chart separately. | | `server.externalDbSecret` | Secret containing a PostgreSQL connection URI in the `uri` key. Use when the database is managed outside the chart. | | `server.telemetryEnabled` | Enable anonymous OpenShell telemetry from the gateway and its sandbox supervisors. Set to `false` to opt out. | | `server.sandboxImage` | Default sandbox image used when a sandbox does not specify one. | diff --git a/docs/reference/sandbox-compute-drivers.mdx b/docs/reference/sandbox-compute-drivers.mdx index 82aa68a956..f00c49afd6 100644 --- a/docs/reference/sandbox-compute-drivers.mdx +++ b/docs/reference/sandbox-compute-drivers.mdx @@ -3,14 +3,21 @@ # SPDX-License-Identifier: Apache-2.0 title: "Sandbox Compute Drivers" sidebar-title: "Compute Drivers" -description: "Reference for Docker, Podman, MicroVM, and Kubernetes sandbox compute drivers." -keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Docker, Podman, MicroVM, Kubernetes, Reference" +description: "Reference for Docker, Podman, MicroVM, Kubernetes, and Windows MXC sandbox compute drivers." +keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Docker, Podman, MicroVM, Kubernetes, MXC, Reference" position: 4 --- The gateway's configured compute driver determines how OpenShell creates each sandbox. The CLI workflow stays the same across drivers: you create, connect to, inspect, stop, start, and delete sandboxes through the gateway API. -Every compute driver runs the OpenShell supervisor inside the sandbox workload. The supervisor launches the agent process, applies policy, routes egress through the proxy, injects configured credentials, and maintains the gateway session. +Most compute drivers run the OpenShell supervisor inside the sandbox workload. +The supervisor launches the agent process, applies policy, routes egress through +the proxy, injects configured credentials, and maintains the gateway session. +A driver may instead set `driver_reports_runtime_readiness`. In that mode, +driver-reported readiness does not require a supervisor session. The canonical +create-time policy is part of `DriverSandboxSpec`; a driver that enforces policy +outside the standard supervisor fetches later revisions through the existing +sandbox configuration API. The Windows MXC driver reports its own readiness. Stop stops compute but retains the sandbox record and the driver's persistent workspace boundary. Start reactivates the same driver resource. @@ -42,11 +49,12 @@ Configure the compute driver on the gateway. Current releases accept one driver compute_drivers = ["docker"] ``` -Reserved built-in values are `docker`, `podman`, `kubernetes`, and `vm`. +Reserved built-in values are `docker`, `podman`, `kubernetes`, `vm`, and `mxc`. +The `mxc` driver is available only in native Windows gateway builds. Non-reserved names select an extension driver and require a `socket_path` in `[openshell.drivers.]`. -When `compute_drivers` is unset, the gateway auto-detects Kubernetes, then Podman, then Docker. Local container runtimes must respond to an API probe before the gateway selects them. The VM driver is never auto-detected; configure it explicitly with `compute_drivers = ["vm"]` or set `OPENSHELL_DRIVERS=vm` in the launch environment. +When `compute_drivers` is unset, the gateway auto-detects Kubernetes, then Podman, then Docker. Docker must respond on a known API socket. Podman first probes known API sockets and then asks the `podman` CLI for the active native or machine-backed socket. The VM driver is never auto-detected; configure it explicitly with `compute_drivers = ["vm"]` or set `OPENSHELL_DRIVERS=vm` in the launch environment. Common gateway options: @@ -227,7 +235,7 @@ namespace roots. These checks do not make host bind mounts safe. [Podman](https://podman.io/)-backed sandboxes run as rootless containers on the gateway host. Use Podman for Linux workstation workflows that avoid a rootful Docker daemon. -The gateway talks to the Podman API socket. The Podman driver requires Podman 5.x, cgroups v2, rootless networking, and an active Podman user socket. When `socket_path` is not set, the driver probes for a responsive Podman socket and fails to start if none respond. +The gateway talks to the Podman API socket. The Podman driver requires Podman 5.x, cgroups v2, rootless networking, and an active Podman user socket. When `socket_path` is not set, the driver probes known socket paths, then uses the `podman` CLI to resolve the active native or machine-backed connection. It fails to start if neither method finds a socket. For maintainer-level implementation details, refer to the [Podman driver README](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-podman/README.md) and [Podman networking notes](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-podman/NETWORKING.md). @@ -340,7 +348,7 @@ The gateway starts `openshell-driver-vm` over a private Unix socket and passes i ### Local image resolution -The VM driver resolves sandbox images from a local container engine before falling back to registry pulls. It tries Docker first, then falls back to the Podman socket (Docker-compatible API). On Linux with Podman, enable the API socket so the driver can find local images: +The VM driver resolves sandbox images from a local container engine before falling back to registry pulls. It tries Docker first, then uses the same Podman socket discovery as the Podman driver. On Linux with Podman, enable the API socket so the driver can find local images: ```shell systemctl --user start podman.socket diff --git a/docs/sandboxes/manage-providers.mdx b/docs/sandboxes/manage-providers.mdx index ad162eca12..6146ab8d39 100644 --- a/docs/sandboxes/manage-providers.mdx +++ b/docs/sandboxes/manage-providers.mdx @@ -122,6 +122,16 @@ read-only. The target ID must match the profile ID in the file. Update accepts one file at a time and rejects stale resource versions. Updated profile policy applies to all provider instances of that type on the next sandbox config sync. +Delete one or more custom provider profiles by ID: + +```shell +openshell provider profile delete custom-api custom-alt +``` + +When a multi-profile delete fails for one entry, the CLI reports that profile's +failure and continues with the remaining IDs. The command exits with an error +after it attempts every requested deletion if any entry failed. + Static credentials require a built-in or imported provider profile. Profiles normally define at least one endpoint. An endpointless profile requires an @@ -277,6 +287,16 @@ Delete a provider: openshell provider delete my-claude ``` +Delete multiple providers by listing their names in one command: + +```shell +openshell provider delete my-claude my-github +``` + +When a multi-provider delete fails for one entry, the CLI reports that +provider's failure and continues with the remaining names. The command exits +with an error after it attempts every requested deletion if any entry failed. + ## Attach Providers to Sandboxes Pass one or more `--provider` flags when creating a sandbox: diff --git a/docs/sandboxes/manage-sandboxes.mdx b/docs/sandboxes/manage-sandboxes.mdx index f1948e3aff..47853b189d 100644 --- a/docs/sandboxes/manage-sandboxes.mdx +++ b/docs/sandboxes/manage-sandboxes.mdx @@ -157,6 +157,59 @@ Local directories and Dockerfiles require a local gateway because the CLI builds through the local Docker daemon. Use a registry image reference for remote gateways. +## Reuse Workload Templates + +Sandbox workload templates let workspace admins define reusable runtime shapes for a workspace. A template stores the image, environment, resource requests, and driver-specific configuration that sandboxes should inherit. When you create a sandbox from a template, the create request can still attach providers, labels, and policy, but the workload comes from the named template. + +Create a template: + +```shell +openshell sandbox template create gpu-kata \ + --image registry.example.com/agent:latest \ + --cpu 2 \ + --memory 4Gi \ + --gpu 1 \ + --label team=runtime \ + --env FEATURE_FLAG=on +``` + +Use `--gpu` without a count when the template should request the active +driver's default GPU assignment. Use `--gpu COUNT` when the template needs a +specific number of GPUs. + +Add driver-specific settings when the active compute driver needs them: + +```shell +openshell sandbox template create gpu-kata \ + --image registry.example.com/agent:latest \ + --driver-config-json '{"kubernetes":{"pod":{"runtime_class_name":"kata-containers","node_selector":{"pool":"gpu"}}}}' +``` + +If you omit `--image`, the gateway applies its default sandbox image when a sandbox is created from the template. Use this when the template should only define resource, environment, or driver settings. + +Create a sandbox from a template: + +```shell +openshell sandbox create --template gpu-kata --provider github -- claude +``` + +The `--template` flag cannot be combined with inline workload flags such as `--from`, `--cpu`, `--memory`, `--gpu`, `--env`, or `--driver-config-json`. Put those values on the template instead. Create-time policy and provider attachments remain part of the sandbox request, so each sandbox can keep its own access boundary. + +Inspect and manage templates: + +```shell +openshell sandbox template list +openshell sandbox template list --label-selector team=runtime +openshell sandbox template get gpu-kata +openshell sandbox template delete gpu-kata +``` + +Use `--all-workspaces` with `sandbox template list` when you need an admin view across workspaces: + +```shell +openshell sandbox template list --all-workspaces +``` + ## Base Sandbox Container The `base` sandbox container is the default runtime image for standard OpenShell sandboxes unless the gateway overrides its default sandbox image. It is published as `ghcr.io/nvidia/openshell-community/sandboxes/base:latest` and maintained in the [OpenShell Community](https://github.com/NVIDIA/OpenShell-Community/tree/main/sandboxes/base) repository. @@ -295,6 +348,24 @@ with SandboxClient.from_active_cluster() as client: assert sandbox.id in {s.id for s in matches} ``` +Create reusable sandbox templates through the Python SDK when several runs +should share the same workload shape: + +```python +from openshell import SandboxClient + +with SandboxClient.from_active_cluster() as client: + templates = client.sandbox_templates() + + templates.create( + workspace="default", + name="python", + image="ghcr.io/nvidia/openshell-community/sandboxes/python:latest", + ) + + sandbox = client.create_from_template(workspace="default", template_name="python") +``` + For non-interactive automation, pass a renewable client-credentials provider. Omitted issuer, client ID, audience, and scopes are read from the active gateway's metadata. The client requires TLS for non-loopback gateways: @@ -456,6 +527,8 @@ Structured output includes `sandbox`, `bind_address`, `port`, `pid`, and expected OpenShell SSH forward; it does not probe the forwarded socket. When no forwards are tracked, structured output returns an empty collection. +The default table colorizes the `STATUS` column, but only when the stream it is written to is a terminal, so piping or redirecting gives plain text. Each stream is decided on its own, so redirecting one leaves the other styled. Prefer `--output json` for automation rather than matching on the table. Set `NO_COLOR` to any non-empty value or pass `--color never` to suppress color, and `--color always` to keep it when piping into a pager. `--color` applies to every `openshell` command and covers all styled output: tables, log lines from `-v`, progress spinners, prompts, and error messages. + You can also forward a port at creation time with `--forward`: @@ -555,6 +628,16 @@ Deleting a sandbox stops all processes, releases resources, and purges injected openshell sandbox delete my-sandbox ``` +Delete multiple sandboxes by listing their names in one command: + +```shell +openshell sandbox delete sandbox-a sandbox-b +``` + +When a multi-sandbox delete fails for one entry, the CLI reports that sandbox's +failure and continues with the remaining names. The command exits with an error +after it attempts every requested deletion if any entry failed. + ## Sandbox Lifecycle Every sandbox moves through a defined set of phases: diff --git a/docs/sandboxes/manage-workspaces.mdx b/docs/sandboxes/manage-workspaces.mdx index 05378af5f5..86da25fbb9 100644 --- a/docs/sandboxes/manage-workspaces.mdx +++ b/docs/sandboxes/manage-workspaces.mdx @@ -9,8 +9,9 @@ position: 3 --- An OpenShell workspace is an access and resource isolation boundary. Sandboxes, -providers, services, policies, settings, and inference routes belong to a -workspace and are not visible to members of other workspaces. +sandbox workload templates, providers, services, policies, settings, and +inference routes belong to a workspace and are not visible to members of other +workspaces. The CLI targets the `default` workspace unless you set `--workspace` or `OPENSHELL_WORKSPACE`. The logical OpenShell workspace described here is @@ -49,6 +50,8 @@ The following table summarizes common operations. | Add Workspace Users or remove members | Any workspace | Assigned workspace | No | | Assign the Workspace Admin role | Any workspace | No | No | | Create, use, or delete sandboxes and services | Any workspace | Assigned workspace | Assigned workspace | +| Create or delete sandbox workload templates | Any workspace | Assigned workspace | No | +| Read or list sandbox workload templates | Any workspace | Assigned workspace | Assigned workspace | | Create, update, or delete providers | Any workspace | Assigned workspace | No | | Change workspace policy or settings | Any workspace | Assigned workspace | No | | Manage platform profiles or global configuration | Yes | No | No | @@ -187,11 +190,11 @@ be deleted. openshell workspace delete team-ml ``` -A custom workspace must not contain sandboxes, providers, provider profiles, -services, SSH sessions, settings, policies, draft policy chunks, or credential -refresh state. Remove those resources before retrying deletion. OpenShell -removes membership records and inference routes as part of successful -workspace deletion. +A custom workspace must not contain sandboxes, sandbox workload templates, +providers, provider profiles, services, SSH sessions, settings, policies, draft +policy chunks, or credential refresh state. Remove those resources before +retrying deletion. OpenShell removes membership records and inference routes as +part of successful workspace deletion. ## Next Steps diff --git a/e2e/no-compute-driver-gateway.sh b/e2e/no-compute-driver-gateway.sh index 7ad3896ca1..baa4a7d193 100755 --- a/e2e/no-compute-driver-gateway.sh +++ b/e2e/no-compute-driver-gateway.sh @@ -8,11 +8,13 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "${ROOT}" echo "Building gateway without compiled compute drivers..." -cargo build -p openshell-server --bin openshell-gateway \ +cargo build -p openshell-gateway --bin openshell-gateway \ --no-default-features --features telemetry +cargo check -p openshell-core --no-default-features --all-targets -dependency_tree="$(cargo tree -p openshell-server \ +dependency_tree="$(cargo tree -p openshell-gateway \ --no-default-features --features telemetry --edges normal)" +server_dependency_tree="$(cargo tree -p openshell-server --edges normal)" for driver in \ openshell-driver-docker \ openshell-driver-kubernetes \ @@ -22,7 +24,18 @@ for driver in \ echo "ERROR: driver-free gateway dependency graph contains ${driver}" >&2 exit 1 fi + if grep -q "${driver} v" <<<"${server_dependency_tree}"; then + echo "ERROR: openshell-server dependency graph contains ${driver}" >&2 + exit 1 + fi done +if rg -n \ + 'ComputeDriverKind|openshell_driver_(docker|podman|kubernetes)([^_[:alnum:]]|$)|ComputeRuntime::new_(docker|podman|kubernetes)|VmComputeConfig|compute::vm|driver_config::builtin|libkrun|gvproxy|qemu' \ + crates/openshell-core crates/openshell-server; then + echo "ERROR: backend-specific compute-driver knowledge leaked into core/server" >&2 + exit 1 +fi + "${ROOT}/target/debug/openshell-gateway" --version echo "Driver-free gateway build passed." diff --git a/e2e/run.sh b/e2e/run.sh index 0505730f05..875186394c 100755 --- a/e2e/run.sh +++ b/e2e/run.sh @@ -250,7 +250,7 @@ guest_gateway_bin= if [ "${mode}" = host ]; then echo "==> Building native host openshell-gateway" mise x -- cargo build "${cargo_jobs[@]}" \ - -p openshell-server \ + -p openshell-gateway \ --bin openshell-gateway \ --features bundled-z3 host_gateway_bin="${target_dir}/debug/openshell-gateway" @@ -268,7 +268,7 @@ else mise x -- cargo zigbuild "${cargo_jobs[@]}" \ --release \ --target "${linux_gateway_zig_target}" \ - -p openshell-server \ + -p openshell-gateway \ --bin openshell-gateway \ --features bundled-z3 ) diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 6dca586879..6dbf46a392 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -168,6 +168,11 @@ name = "workspace_lifecycle" path = "tests/workspace_lifecycle.rs" required-features = ["e2e"] +[[test]] +name = "sandbox_templates" +path = "tests/sandbox_templates.rs" +required-features = ["e2e"] + [[test]] name = "proxy_egress_pipeline" path = "tests/proxy_egress_pipeline.rs" diff --git a/e2e/rust/e2e-vm.sh b/e2e/rust/e2e-vm.sh index de7e3ad09d..9acc633d65 100755 --- a/e2e/rust/e2e-vm.sh +++ b/e2e/rust/e2e-vm.sh @@ -103,10 +103,10 @@ if [ -z "${OPENSHELL_GATEWAY_BIN:-}" ]; then if [ "${OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER:-0}" = "1" ]; then echo "==> Building driver-free openshell-gateway" cargo build \ - -p openshell-server --bin openshell-gateway \ - --no-default-features + -p openshell-gateway --bin openshell-gateway \ + --no-default-features --features telemetry else - build_packages+=(-p openshell-server) + build_packages+=(-p openshell-gateway) fi else echo "==> Using prebuilt openshell-gateway at ${GATEWAY_BIN}" diff --git a/e2e/rust/tests/sandbox_templates.rs b/e2e/rust/tests/sandbox_templates.rs new file mode 100644 index 0000000000..21c9233daf --- /dev/null +++ b/e2e/rust/tests/sandbox_templates.rs @@ -0,0 +1,275 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e")] + +//! E2E coverage for reusable sandbox workload templates. + +use std::process::Stdio; +use std::time::{SystemTime, UNIX_EPOCH}; + +use openshell_e2e::harness::binary::{openshell_bin, openshell_cmd}; +use openshell_e2e::harness::output::strip_ansi; +use openshell_e2e::harness::sandbox::SandboxGuard; +use serde_json::Value; + +struct CliResult { + output: String, + success: bool, +} + +struct TemplateGuard { + name: String, +} + +impl TemplateGuard { + fn new(name: String) -> Self { + Self { name } + } + + async fn cleanup(mut self) { + delete_template(&self.name).await; + self.name.clear(); + } +} + +impl Drop for TemplateGuard { + fn drop(&mut self) { + if self.name.is_empty() { + return; + } + let bin = openshell_bin(); + let _ = std::process::Command::new(&bin) + .args(["sandbox", "template", "delete", &self.name]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } +} + +async fn run_cli(args: &[&str]) -> CliResult { + let mut cmd = openshell_cmd(); + cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped()); + + let output = cmd.output().await.expect("spawn openshell command"); + let stdout = String::from_utf8_lossy(&output.stdout).to_string(); + let stderr = String::from_utf8_lossy(&output.stderr).to_string(); + let combined = format!("{stdout}{stderr}"); + + CliResult { + output: strip_ansi(&combined), + success: output.status.success(), + } +} + +async fn delete_template(name: &str) { + let mut cmd = openshell_cmd(); + cmd.args(["sandbox", "template", "delete", name]) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + let _ = cmd.status().await; +} + +fn unique_name(prefix: &str) -> String { + let millis = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("system clock before epoch") + .as_millis(); + let suffix = millis % 1_000_000; + format!("{prefix}-{suffix:06}") +} + +fn output_contains(output: &str, needle: &str) -> bool { + output.to_lowercase().contains(&needle.to_lowercase()) +} + +fn output_mentions_template_not_found(output: &str) -> bool { + output_contains(output, "sandbox template") && output_contains(output, "not found") +} + +#[tokio::test] +async fn sandbox_create_from_template_uses_reusable_workload() { + let template_name = unique_name("tmpl"); + let sandbox_name = unique_name("sb-tmpl"); + let template = TemplateGuard::new(template_name.clone()); + + let create_template = run_cli(&[ + "sandbox", + "template", + "create", + &template_name, + "--cpu", + "500m", + "--memory", + "512Mi", + "--label", + "e2e=sandbox-template", + "--env", + "FEATURE_FLAG=on", + ]) + .await; + assert!( + create_template.success, + "sandbox template create failed:\n{}", + create_template.output + ); + + let get_template = run_cli(&[ + "sandbox", + "template", + "get", + &template_name, + "--output", + "json", + ]) + .await; + assert!( + get_template.success, + "sandbox template get failed:\n{}", + get_template.output + ); + let template_json: Value = + serde_json::from_str(&get_template.output).expect("template JSON output"); + assert_eq!(template_json["name"].as_str(), Some(template_name.as_str())); + assert_eq!( + template_json["labels"]["e2e"].as_str(), + Some("sandbox-template") + ); + assert_eq!( + template_json["environment"]["FEATURE_FLAG"].as_str(), + Some("on") + ); + assert_eq!(template_json["resources"]["cpu"].as_str(), Some("500m")); + assert_eq!(template_json["resources"]["memory"].as_str(), Some("512Mi")); + + let list_templates = run_cli(&["sandbox", "template", "list", "--names"]).await; + assert!( + list_templates.success, + "sandbox template list failed:\n{}", + list_templates.output + ); + assert!( + list_templates + .output + .lines() + .any(|line| line.trim() == template_name), + "template list should include {template_name}:\n{}", + list_templates.output + ); + + let mut sandbox = SandboxGuard::create(&[ + "--name", + &sandbox_name, + "--template", + &template_name, + "--", + "sh", + "-lc", + "test \"$FEATURE_FLAG\" = on && echo template-env-ok", + ]) + .await + .expect("sandbox create from template should succeed"); + + assert!( + sandbox.create_output.contains("template-env-ok"), + "sandbox should inherit template environment:\n{}", + sandbox.create_output + ); + + sandbox.cleanup().await; + template.cleanup().await; +} + +#[tokio::test] +async fn sandbox_template_get_after_delete_returns_not_found() { + let template_name = unique_name("tmpl-del"); + let template = TemplateGuard::new(template_name.clone()); + + let create_template = run_cli(&["sandbox", "template", "create", &template_name]).await; + assert!( + create_template.success, + "sandbox template create failed:\n{}", + create_template.output + ); + + let delete_template = run_cli(&["sandbox", "template", "delete", &template_name]).await; + assert!( + delete_template.success, + "sandbox template delete failed:\n{}", + delete_template.output + ); + + let get_deleted = run_cli(&["sandbox", "template", "get", &template_name]).await; + assert!( + !get_deleted.success, + "deleted template should not be fetchable:\n{}", + get_deleted.output + ); + assert!( + output_mentions_template_not_found(&get_deleted.output), + "deleted template should return not-found:\n{}", + get_deleted.output + ); + + template.cleanup().await; +} + +#[tokio::test] +async fn sandbox_template_create_rejects_duplicate_name() { + let template_name = unique_name("tmpl-dupe"); + let template = TemplateGuard::new(template_name.clone()); + + let create_template = run_cli(&["sandbox", "template", "create", &template_name]).await; + assert!( + create_template.success, + "sandbox template create failed:\n{}", + create_template.output + ); + + let duplicate = run_cli(&["sandbox", "template", "create", &template_name]).await; + assert!( + !duplicate.success, + "duplicate sandbox template create should fail:\n{}", + duplicate.output + ); + assert!( + output_contains(&duplicate.output, "already exists"), + "duplicate sandbox template create should report already-exists:\n{}", + duplicate.output + ); + + template.cleanup().await; +} + +#[tokio::test] +async fn sandbox_create_from_missing_template_returns_not_found() { + let template_name = unique_name("tmpl-missing"); + let sandbox_name = unique_name("sb-missing"); + + let create_sandbox = run_cli(&[ + "sandbox", + "create", + "--name", + &sandbox_name, + "--template", + &template_name, + "--", + "true", + ]) + .await; + + if create_sandbox.success { + let _ = run_cli(&["sandbox", "delete", &sandbox_name]).await; + } + + assert!( + !create_sandbox.success, + "sandbox create from missing template should fail:\n{}", + create_sandbox.output + ); + assert!( + output_mentions_template_not_found(&create_sandbox.output), + "sandbox create from missing template should report not-found:\n{}", + create_sandbox.output + ); +} diff --git a/e2e/support/gateway-common.sh b/e2e/support/gateway-common.sh index c512dab60a..b1f62e380b 100644 --- a/e2e/support/gateway-common.sh +++ b/e2e/support/gateway-common.sh @@ -219,11 +219,11 @@ e2e_build_gateway_binaries() { echo "Building openshell-gateway..." if [ "${OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER:-0}" = "1" ]; then cargo build "${jobs[@]}" \ - -p openshell-server --bin openshell-gateway \ - --no-default-features + -p openshell-gateway --bin openshell-gateway \ + --no-default-features --features telemetry else cargo build "${jobs[@]}" \ - -p openshell-server --bin openshell-gateway + -p openshell-gateway --bin openshell-gateway fi else echo "Using prebuilt openshell gateway at ${OPENSHELL_GATEWAY_BIN}" diff --git a/e2e/with-kube-gateway.sh b/e2e/with-kube-gateway.sh index 08dd08113e..bd7f246d24 100755 --- a/e2e/with-kube-gateway.sh +++ b/e2e/with-kube-gateway.sh @@ -642,9 +642,12 @@ if [ "${OPENSHELL_E2E_KUBE_BUILD_IMAGES}" = "1" ]; then fi external_gateway="${OPENSHELL_GATEWAY_BIN:-${ROOT}/target/debug/openshell-gateway}" external_driver="${OPENSHELL_EXTERNAL_DRIVER_BIN:-${ROOT}/target/debug/openshell-driver-kubernetes}" + # The test image uses a distroless runtime, so keep Z3 self-contained just + # like the production gateway image artifact. A host-linked debug binary + # would otherwise require libz3.so from the CI build machine at runtime. if [ -z "${OPENSHELL_GATEWAY_BIN:-}" ]; then - cargo build -p openshell-server --bin openshell-gateway \ - --no-default-features --features bundled-z3 + cargo build -p openshell-gateway --bin openshell-gateway \ + --no-default-features --features telemetry,bundled-z3 fi if [ -z "${OPENSHELL_EXTERNAL_DRIVER_BIN:-}" ]; then cargo build -p openshell-driver-kubernetes --bin openshell-driver-kubernetes diff --git a/examples/governance-interceptor/smoke.sh b/examples/governance-interceptor/smoke.sh index feaa42df05..e25ee0d3cb 100755 --- a/examples/governance-interceptor/smoke.sh +++ b/examples/governance-interceptor/smoke.sh @@ -649,7 +649,7 @@ wait_until_stopped() { cd "$ROOT" -run_setup_step "building gateway" cargo build --quiet -p openshell-server --bin openshell-gateway +run_setup_step "building gateway" cargo build --quiet -p openshell-gateway --bin openshell-gateway run_setup_step "building governance interceptor" cargo build --quiet --manifest-path "$EXAMPLE_DIR/Cargo.toml" run_setup_step "building CLI" cargo build --quiet -p openshell-cli --bin openshell diff --git a/examples/supervisor-middleware-content-guard/smoke.sh b/examples/supervisor-middleware-content-guard/smoke.sh index 509ffd403d..b30475c8ca 100755 --- a/examples/supervisor-middleware-content-guard/smoke.sh +++ b/examples/supervisor-middleware-content-guard/smoke.sh @@ -444,7 +444,7 @@ EXAMPLE_TARGET_DIR="$(cargo_target_dir "$EXAMPLE_DIR/Cargo.toml")" GATEWAY_BIN="$ROOT_TARGET_DIR/debug/openshell-gateway" CLI_BIN="$ROOT_TARGET_DIR/debug/openshell" MIDDLEWARE_BIN="$EXAMPLE_TARGET_DIR/debug/supervisor-middleware-content-guard" -run_setup_step "building gateway" cargo build --quiet -p openshell-server --bin openshell-gateway +run_setup_step "building gateway" cargo build --quiet -p openshell-gateway --bin openshell-gateway run_setup_step "building content guard" cargo build --quiet --manifest-path "$EXAMPLE_DIR/Cargo.toml" run_setup_step "building CLI" cargo build --quiet -p openshell-cli --bin openshell generate_gateway_jwt_bundle diff --git a/mise.lock b/mise.lock index 23ce8b24e0..3a57cbf0e0 100644 --- a/mise.lock +++ b/mise.lock @@ -438,6 +438,34 @@ url = "https://github.com/astral-sh/uv/releases/download/0.10.12/uv-x86_64-pc-wi url_api = "https://api.github.com/repos/astral-sh/uv/releases/assets/377491992" provenance = "github-attestations" +[[tools.yq]] +version = "4.53.6" +backend = "aqua:mikefarah/yq" + +[tools.yq."platforms.linux-arm64"] +checksum = "sha256:88a1016bc1d657375a35864e4f44b6f333df8ff97b559f51bba0adcb2169df09" +url = "https://github.com/mikefarah/yq/releases/download/v4.53.6/yq_linux_arm64" +url_api = "https://api.github.com/repos/mikefarah/yq/releases/assets/522028007" +provenance = "cosign" + +[tools.yq."platforms.linux-x64"] +checksum = "sha256:c5f056448f973ae7d39b5401949648a78f2dc1947d6a8eb65be60d5c504b9385" +url = "https://github.com/mikefarah/yq/releases/download/v4.53.6/yq_linux_amd64" +url_api = "https://api.github.com/repos/mikefarah/yq/releases/assets/522028022" +provenance = "cosign" + +[tools.yq."platforms.macos-arm64"] +checksum = "sha256:cceb0b8d71ea5294334121f8429f33f92b920e7217d904a2f9f35443968ac424" +url = "https://github.com/mikefarah/yq/releases/download/v4.53.6/yq_darwin_arm64" +url_api = "https://api.github.com/repos/mikefarah/yq/releases/assets/522028033" +provenance = "cosign" + +[tools.yq."platforms.windows-x64"] +checksum = "sha256:ece3dd8bb50d39f93610506273ea262feb91e5c486bbddbb10abf91b2a6c0f14" +url = "https://github.com/mikefarah/yq/releases/download/v4.53.6/yq_windows_amd64.exe" +url_api = "https://api.github.com/repos/mikefarah/yq/releases/assets/522027974" +provenance = "cosign" + [[tools.zig]] version = "0.14.1" backend = "core:zig" diff --git a/mise.toml b/mise.toml index ec643ed08e..bd36408b80 100644 --- a/mise.toml +++ b/mise.toml @@ -33,6 +33,7 @@ go = "1.26" buf = "1.72.0" helm = { version = "4.2.0", version_prefix = "v" } helm-docs = "1.14.2" +yq = "4.53.6" skaffold = { version = "2.20.0", os = ["linux", "macos"], version_prefix = "v" } # Keep k3d out of Linux CI images until upstream ships a release rebuilt with # patched Go/container dependencies. Linux Kubernetes E2E uses kind or an diff --git a/proto/compute_driver.proto b/proto/compute_driver.proto index eff5cfa5ea..b737e7de62 100644 --- a/proto/compute_driver.proto +++ b/proto/compute_driver.proto @@ -7,6 +7,7 @@ package openshell.compute.v1; import "google/protobuf/struct.proto"; import "options.proto"; +import "sandbox.proto"; // Gateway/compute-driver extension contract. // @@ -86,6 +87,10 @@ message GetCapabilitiesResponse { bool gateway_manages_lifecycle = 6; // Whether AuthenticateSandbox is implemented by this driver. bool supports_sandbox_authentication = 7; + // Whether the driver reports runtime readiness itself. When false, the + // gateway waits for the standard OpenShell supervisor session in addition + // to the driver's platform-ready observation. + bool driver_reports_runtime_readiness = 8; } message AuthenticateSandboxRequest { @@ -154,6 +159,10 @@ message DriverSandboxSpec { map environment = 5; // Runtime template consumed by the driver during provisioning. DriverSandboxTemplate template = 6; + // Canonical effective policy supplied to the driver for validation and + // provisioning. Drivers that enforce policy outside the standard supervisor + // use GetSandboxConfig to fetch later revisions. + openshell.sandbox.v1.SandboxPolicy policy = 7; // Portable resource requirements used by the gateway for driver selection // and by drivers for provisioning. ResourceRequirements resource_requirements = 9; @@ -214,6 +223,10 @@ message DriverSandboxTemplate { // This is the inner block selected from public SandboxTemplate.driver_config. // The selected driver owns nested schema validation. google.protobuf.Struct driver_config = 12; + // Enable Linux user namespace isolation for the sandbox workload. Drivers + // map this portable intent to their compute platform; when unset, the + // driver's configured default applies. + optional bool user_namespaces = 13; } // Typed compute-resource requirements. diff --git a/proto/openshell.proto b/proto/openshell.proto index a2d7a0ad02..138b973474 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -6,6 +6,7 @@ syntax = "proto3"; package openshell.v1; import "datamodel.proto"; +import "google/protobuf/duration.proto"; import "google/protobuf/struct.proto"; import "options.proto"; import "sandbox.proto"; @@ -69,6 +70,46 @@ service OpenShell { }; } + // Create a reusable sandbox workload template. + rpc CreateSandboxTemplate(CreateSandboxTemplateRequest) + returns (SandboxTemplateResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:write" + workspace_role: "admin" + }; + } + + // Fetch a reusable sandbox workload template by name. + rpc GetSandboxTemplate(GetSandboxTemplateRequest) + returns (SandboxTemplateResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:read" + workspace_role: "user" + }; + } + + // List reusable sandbox workload templates. + rpc ListSandboxTemplates(ListSandboxTemplatesRequest) + returns (ListSandboxTemplatesResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:read" + workspace_role: "user" + }; + } + + // Delete a reusable sandbox workload template by name. + rpc DeleteSandboxTemplate(DeleteSandboxTemplateRequest) + returns (DeleteSandboxTemplateResponse) { + option (openshell.options.v1.authorization) = { + auth_mode: "bearer" + scope: "sandbox:write" + workspace_role: "admin" + }; + } + // List provider records attached to a sandbox. rpc ListSandboxProviders(ListSandboxProvidersRequest) returns (ListSandboxProvidersResponse) { @@ -813,6 +854,8 @@ message Sandbox { SandboxSpec spec = 2; // Latest user-facing observed status derived by the gateway. SandboxStatus status = 3; + // Read-only provenance for sandboxes created from a reusable workload template. + SandboxWorkloadTemplateProvenance created_from_workload_template = 20; reserved 4, 5; reserved "phase", "current_policy_version"; @@ -861,7 +904,12 @@ message GpuResourceRequirements { optional uint32 count = 1; } -// Public sandbox template mapped onto compute-driver template inputs. +// Historical inline compute template mapped onto compute-driver template inputs. +// +// Despite its name, this is not a reusable named sandbox template resource. It +// is an inline part of `SandboxSpec` kept for v1 compatibility. A future +// breaking API cleanup may rename this message to free `SandboxTemplate` for +// the reusable template resource now represented by `SandboxWorkloadTemplate`. message SandboxTemplate { // Fully-qualified OCI image reference used to boot the sandbox. string image = 1; @@ -892,6 +940,62 @@ message SandboxTemplate { google.protobuf.Struct driver_config = 11; } +// Reusable named sandbox workload template resource. +// +// This is the actual workspace-scoped template resource used to create +// sandboxes by reference. It uses the longer name in v1 to avoid colliding with +// the historical inline `SandboxTemplate` message. A future breaking API +// cleanup may rename this resource to `SandboxTemplate`. +message SandboxWorkloadTemplate { + // Kubernetes-style metadata (id, name, labels, timestamps, resource version). + openshell.datamodel.v1.ObjectMeta metadata = 1; + // Desired reusable workload shape and template-owned driver config. + SandboxWorkloadTemplateSpec spec = 2; +} + +message SandboxWorkloadTemplateSpec { + // Portable workload shape. + SandboxWorkloadConfig workload = 1; + // Driver-keyed opaque config envelope supplied by the template owner. + google.protobuf.Struct driver_config = 2; + // Desired service level associated with this template. + SandboxServiceLevel desired_service_level = 3; +} + +message SandboxWorkloadConfig { + // Fully-qualified OCI image reference used to boot the sandbox. + string image = 1; + // Environment variables injected into the sandbox runtime. + map environment = 2; + // Portable resource requirements for sandboxes created from this workload. + SandboxResources resources = 3; +} + +message SandboxResources { + // Portable CPU quantity, for example "500m" or "2". + string cpu = 1; + // Portable memory quantity, for example "512Mi" or "2Gi". + string memory = 2; + // GPU requirements for the sandbox workload. Presence indicates a GPU + // request. When count is omitted, the request uses the selected driver's + // default GPU assignment behavior. + GpuResourceRequirements gpu = 3; +} + +message SandboxServiceLevel { + SandboxStartup startup = 1; +} + +message SandboxStartup { + google.protobuf.Duration ready_within = 1; + uint32 max_burst = 2; +} + +message SandboxWorkloadTemplateProvenance { + string name = 1; + string resource_version = 2; +} + // User-facing sandbox status derived by the gateway from compute-driver observations. // // Public status does not embed driver-only flags such as `deleting`. @@ -982,6 +1086,49 @@ message CreateSandboxRequest { // the canonical main process. The supervisor keeps the terminal transport // alive until that attachment connects and closes naturally. bool await_main_process_attachment = 6; + // Workspace-scoped SandboxWorkloadTemplate name to resolve at creation time. + string workload_template_name = 7; +} + +message CreateSandboxTemplateRequest { + SandboxWorkloadTemplate template = 1; + // Workspace for the template. Empty defaults to "default". + string workspace = 2; +} + +message GetSandboxTemplateRequest { + string name = 1; + // Workspace scope. Empty defaults to "default". + string workspace = 2; +} + +message ListSandboxTemplatesRequest { + uint32 limit = 1; + uint32 offset = 2; + // Workspace scope. Empty defaults to "default". + string workspace = 3; + // List across all workspaces. Mutually exclusive with workspace. + bool all_workspaces = 4; + // Optional label selector in key=value comma-separated form. + string label_selector = 5; +} + +message DeleteSandboxTemplateRequest { + string name = 1; + // Workspace scope. Empty defaults to "default". + string workspace = 2; +} + +message SandboxTemplateResponse { + SandboxWorkloadTemplate template = 1; +} + +message ListSandboxTemplatesResponse { + repeated SandboxWorkloadTemplate templates = 1; +} + +message DeleteSandboxTemplateResponse { + bool deleted = 1; } // Get sandbox request. diff --git a/python/openshell/__init__.py b/python/openshell/__init__.py index 27f317578b..4001d2fb70 100644 --- a/python/openshell/__init__.py +++ b/python/openshell/__init__.py @@ -17,6 +17,8 @@ SandboxRef, SandboxSession, SandboxStatusRef, + SandboxTemplateClient, + SandboxWorkloadTemplateProvenanceRef, TlsConfig, WorkspaceClient, WorkspaceRef, @@ -41,6 +43,8 @@ "SandboxRef", "SandboxSession", "SandboxStatusRef", + "SandboxTemplateClient", + "SandboxWorkloadTemplateProvenanceRef", "TlsConfig", "WorkspaceClient", "WorkspaceRef", diff --git a/python/openshell/openshell_test.py b/python/openshell/openshell_test.py index 66daac6ee1..101b7b6833 100644 --- a/python/openshell/openshell_test.py +++ b/python/openshell/openshell_test.py @@ -9,3 +9,7 @@ def test_version() -> None: """Test that version is defined.""" assert openshell.__version__ + + +def test_sandbox_template_client_exported() -> None: + assert openshell.SandboxTemplateClient diff --git a/python/openshell/sandbox.py b/python/openshell/sandbox.py index 5653d8dc5e..07eeb6480e 100644 --- a/python/openshell/sandbox.py +++ b/python/openshell/sandbox.py @@ -394,6 +394,12 @@ def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: return type(self), (dict(self),) +@dataclass(frozen=True) +class SandboxWorkloadTemplateProvenanceRef: + name: str + resource_version: str + + @dataclass(frozen=True) class SandboxRef: id: str @@ -403,6 +409,7 @@ class SandboxRef: # Excluded from equality/hash to preserve the original identity while the # immutable mapping remains safe for deepcopy, pickle, and asdict. labels: Mapping[str, str] = field(default_factory=_ImmutableLabels, compare=False) + created_from_workload_template: SandboxWorkloadTemplateProvenanceRef | None = None def __post_init__(self) -> None: object.__setattr__(self, "labels", _ImmutableLabels(self.labels)) @@ -726,6 +733,33 @@ def create( raise SandboxError("CreateSandbox returned empty sandbox id") return sandbox_ref + def create_from_template( + self, + *, + workspace: str, + template_name: str, + spec: openshell_pb2.SandboxSpec | None = None, + name: str | None = None, + labels: Mapping[str, str] | None = None, + ) -> SandboxRef: + if not template_name.strip(): + raise SandboxError("template_name is required") + request_spec = spec if spec is not None else openshell_pb2.SandboxSpec() + response = self._stub.CreateSandbox( + openshell_pb2.CreateSandboxRequest( + spec=request_spec, + name=name or "", + labels=dict(labels) if labels else {}, + workspace=workspace, + workload_template_name=template_name, + ), + timeout=self._timeout, + ) + sandbox_ref = _sandbox_ref(response.sandbox) + if sandbox_ref.id == "": + raise SandboxError("CreateSandbox returned empty sandbox id") + return sandbox_ref + def create_session( self, *, @@ -738,6 +772,29 @@ def create_session( self, self.create(workspace=workspace, spec=spec, name=name, labels=labels) ) + def create_session_from_template( + self, + *, + workspace: str, + template_name: str, + spec: openshell_pb2.SandboxSpec | None = None, + name: str | None = None, + labels: Mapping[str, str] | None = None, + ) -> SandboxSession: + return SandboxSession( + self, + self.create_from_template( + workspace=workspace, + template_name=template_name, + spec=spec, + name=name, + labels=labels, + ), + ) + + def sandbox_templates(self) -> SandboxTemplateClient: + return SandboxTemplateClient(self._channel, timeout=self._timeout) + def get(self, sandbox_name: str, *, workspace: str) -> SandboxRef: response = self._stub.GetSandbox( openshell_pb2.GetSandboxRequest(name=sandbox_name, workspace=workspace), @@ -1027,6 +1084,126 @@ def exec_python( ) +class SandboxTemplateClient: + """gRPC client for reusable sandbox template lifecycle operations.""" + + def __init__(self, channel: grpc.Channel, *, timeout: float = 30.0) -> None: + self._stub = openshell_pb2_grpc.OpenShellStub(channel) + self._timeout = timeout + + @classmethod + def from_sandbox_client(cls, client: SandboxClient) -> SandboxTemplateClient: + return client.sandbox_templates() + + def create( + self, + *, + workspace: str, + template: openshell_pb2.SandboxWorkloadTemplate | None = None, + name: str | None = None, + image: str | None = None, + labels: Mapping[str, str] | None = None, + annotations: Mapping[str, str] | None = None, + environment: Mapping[str, str] | None = None, + cpu: str | None = None, + memory: str | None = None, + gpu_count: int | None = None, + gpu: bool = False, + driver_config: Mapping[str, Any] | None = None, + ) -> openshell_pb2.SandboxWorkloadTemplate: + if template is None: + if name is None or not name.strip(): + raise SandboxError("name is required when template is omitted") + template = _sandbox_workload_template( + name=name, + image=image, + labels=labels, + annotations=annotations, + environment=environment, + cpu=cpu, + memory=memory, + gpu_count=gpu_count, + gpu=gpu, + driver_config=driver_config, + ) + elif ( + any(value is not None for value in (name, image, cpu, memory, gpu_count)) + or any( + bool(value) + for value in (labels, annotations, environment, driver_config) + ) + or gpu + ): + raise SandboxError( + "template cannot be combined with template builder fields" + ) + + response = self._stub.CreateSandboxTemplate( + openshell_pb2.CreateSandboxTemplateRequest( + workspace=workspace, + template=template, + ), + timeout=self._timeout, + ) + return response.template + + def get( + self, + name: str, + *, + workspace: str, + ) -> openshell_pb2.SandboxWorkloadTemplate: + response = self._stub.GetSandboxTemplate( + openshell_pb2.GetSandboxTemplateRequest(name=name, workspace=workspace), + timeout=self._timeout, + ) + return response.template + + def list( + self, + *, + workspace: str, + limit: int = 100, + offset: int = 0, + label_selector: str = "", + ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: + response = self._stub.ListSandboxTemplates( + openshell_pb2.ListSandboxTemplatesRequest( + workspace=workspace, + limit=limit, + offset=offset, + label_selector=label_selector, + ), + timeout=self._timeout, + ) + return list(response.templates) + + def list_for_all_workspaces( + self, + *, + limit: int = 100, + offset: int = 0, + label_selector: str = "", + ) -> builtins.list[openshell_pb2.SandboxWorkloadTemplate]: + response = self._stub.ListSandboxTemplates( + openshell_pb2.ListSandboxTemplatesRequest( + all_workspaces=True, + limit=limit, + offset=offset, + label_selector=label_selector, + ), + timeout=self._timeout, + ) + return list(response.templates) + + def delete(self, name: str, *, workspace: str) -> bool: + response = self._stub.DeleteSandboxTemplate( + openshell_pb2.DeleteSandboxTemplateRequest(name=name, workspace=workspace), + timeout=self._timeout, + ) + return bool(response.deleted) + + @dataclass(frozen=True) class InferenceRouteConfig: provider_name: str @@ -1182,6 +1359,7 @@ def __init__( spec: openshell_pb2.SandboxSpec | None = None, name: str | None = None, labels: Mapping[str, str] | None = None, + template_name: str | None = None, timeout: float = 30.0, ready_timeout_seconds: float = 120.0, auto_refresh: bool = True, @@ -1207,6 +1385,7 @@ def __init__( self._name = name # Copy so later caller mutation cannot change what gets sent on enter. self._labels = dict(labels) if labels is not None else None + self._template_name = template_name self._timeout = timeout self._ready_timeout_seconds = ready_timeout_seconds self._auto_refresh = auto_refresh @@ -1232,10 +1411,12 @@ def __enter__(self) -> Sandbox: # Creation metadata cannot be applied when attaching to an existing # sandbox; reject it before opening a connection. if self._sandbox_input is not None and ( - self._name is not None or self._labels is not None + self._name is not None + or self._labels is not None + or self._template_name is not None ): raise SandboxError( - "name and labels cannot be set when attaching to an existing sandbox" + "name, labels, and template_name cannot be set when attaching to an existing sandbox" ) client = SandboxClient.from_active_cluster( @@ -1248,7 +1429,15 @@ def __enter__(self) -> Sandbox: ) self._client = client - if self._sandbox_input is None: + if self._sandbox_input is None and self._template_name is not None: + self._session = client.create_session_from_template( + workspace=self._workspace, + template_name=self._template_name, + spec=self._spec, + name=self._name, + labels=self._labels, + ) + elif self._sandbox_input is None: self._session = client.create_session( workspace=self._workspace, spec=self._spec, @@ -1374,6 +1563,14 @@ def _serialize_python_callable( def _sandbox_ref(sandbox: openshell_pb2.Sandbox) -> SandboxRef: status = sandbox.status if sandbox.HasField("status") else None + provenance = ( + SandboxWorkloadTemplateProvenanceRef( + name=sandbox.created_from_workload_template.name, + resource_version=sandbox.created_from_workload_template.resource_version, + ) + if sandbox.HasField("created_from_workload_template") + else None + ) return SandboxRef( id=sandbox.metadata.id if sandbox.metadata else "", name=sandbox.metadata.name if sandbox.metadata else "", @@ -1386,6 +1583,7 @@ def _sandbox_ref(sandbox: openshell_pb2.Sandbox) -> SandboxRef: else None, ), labels=sandbox.metadata.labels if sandbox.metadata else {}, + created_from_workload_template=provenance, ) @@ -1398,6 +1596,50 @@ def _default_spec() -> openshell_pb2.SandboxSpec: return openshell_pb2.SandboxSpec() +def _sandbox_workload_template( + *, + name: str, + image: str | None = None, + labels: Mapping[str, str] | None = None, + annotations: Mapping[str, str] | None = None, + environment: Mapping[str, str] | None = None, + cpu: str | None = None, + memory: str | None = None, + gpu_count: int | None = None, + gpu: bool = False, + driver_config: Mapping[str, Any] | None = None, +) -> openshell_pb2.SandboxWorkloadTemplate: + if gpu_count is not None and gpu_count <= 0: + raise SandboxError("gpu_count must be greater than zero") + + template = openshell_pb2.SandboxWorkloadTemplate() + template.metadata.name = name + # The gateway permits an empty workload so it can apply the default image + # at sandbox create time, but the workload message itself is required. + template.spec.workload.SetInParent() + if labels: + template.metadata.labels.update(dict(labels)) + if annotations: + template.metadata.annotations.update(dict(annotations)) + + if image is not None: + template.spec.workload.image = image + if environment: + template.spec.workload.environment.update(dict(environment)) + if cpu is not None: + template.spec.workload.resources.cpu = cpu + if memory is not None: + template.spec.workload.resources.memory = memory + if gpu or gpu_count is not None: + template.spec.workload.resources.gpu.SetInParent() + if gpu_count is not None: + template.spec.workload.resources.gpu.count = gpu_count + if driver_config: + template.spec.driver_config.update(dict(driver_config)) + + return template + + def _xdg_config_home() -> pathlib.Path: configured = os.environ.get("XDG_CONFIG_HOME") if configured: diff --git a/python/openshell/sandbox_test.py b/python/openshell/sandbox_test.py index 23382d1093..5e12d0c8a3 100644 --- a/python/openshell/sandbox_test.py +++ b/python/openshell/sandbox_test.py @@ -29,6 +29,7 @@ SandboxError, SandboxRef, SandboxStatusRef, + SandboxTemplateClient, TlsConfig, _atomic_replace, _BearerAuthInterceptor, @@ -437,6 +438,13 @@ def _client_with_fake_stub(stub: object) -> SandboxClient: return client +def _template_client_with_fake_stub(stub: object) -> SandboxTemplateClient: + client = cast("SandboxTemplateClient", object.__new__(SandboxTemplateClient)) + client._timeout = 30.0 + client._stub = cast("Any", stub) + return client + + def test_exec_sends_stdin_payload() -> None: stub = _FakeStub() client = _client_with_fake_stub(stub) @@ -1991,6 +1999,20 @@ def _make_sandbox_proto( return sandbox +def _make_workload_template_proto( + name: str, + *, + workspace: str = "default", +) -> openshell_pb2.SandboxWorkloadTemplate: + template = openshell_pb2.SandboxWorkloadTemplate() + template.metadata.name = name + template.metadata.workspace = workspace + template.spec.workload.image = f"ghcr.io/test/{name}:latest" + template.spec.workload.resources.cpu = "1" + template.spec.workload.resources.memory = "512Mi" + return template + + class _FakeSandboxStub: def __init__(self, listed: list[openshell_pb2.Sandbox] | None = None) -> None: self.create_request: openshell_pb2.CreateSandboxRequest | None = None @@ -1999,7 +2021,18 @@ def __init__(self, listed: list[openshell_pb2.Sandbox] | None = None) -> None: self.delete_request: openshell_pb2.DeleteSandboxRequest | None = None self.stop_request: openshell_pb2.StopSandboxRequest | None = None self.start_request: openshell_pb2.StartSandboxRequest | None = None + self.create_template_request: ( + openshell_pb2.CreateSandboxTemplateRequest | None + ) = None + self.get_template_request: openshell_pb2.GetSandboxTemplateRequest | None = None + self.list_template_request: openshell_pb2.ListSandboxTemplatesRequest | None = ( + None + ) + self.delete_template_request: ( + openshell_pb2.DeleteSandboxTemplateRequest | None + ) = None self._listed = listed or [] + self._templates: list[openshell_pb2.SandboxWorkloadTemplate] = [] def GetSandbox( self, @@ -2080,12 +2113,55 @@ def ListSandboxes( _ = timeout return SimpleNamespace(sandboxes=list(self._listed)) + def CreateSandboxTemplate( + self, + request: openshell_pb2.CreateSandboxTemplateRequest, + timeout: float | None = None, + ) -> Any: + self.create_template_request = request + _ = timeout + self._templates.append(request.template) + return SimpleNamespace(template=request.template) + + def GetSandboxTemplate( + self, + request: openshell_pb2.GetSandboxTemplateRequest, + timeout: float | None = None, + ) -> Any: + self.get_template_request = request + _ = timeout + return SimpleNamespace( + template=_make_workload_template_proto( + request.name, + workspace=request.workspace or "default", + ) + ) + + def ListSandboxTemplates( + self, + request: openshell_pb2.ListSandboxTemplatesRequest, + timeout: float | None = None, + ) -> Any: + self.list_template_request = request + _ = timeout + return SimpleNamespace(templates=list(self._templates)) + + def DeleteSandboxTemplate( + self, + request: openshell_pb2.DeleteSandboxTemplateRequest, + timeout: float | None = None, + ) -> Any: + self.delete_template_request = request + _ = timeout + return SimpleNamespace(deleted=True) + class _RecordingHighLevelClient: """A stand-in for SandboxClient used to observe high-level forwarding.""" def __init__(self) -> None: self.create_kwargs: dict[str, Any] | None = None + self.create_template_kwargs: dict[str, Any] | None = None def create_session( self, @@ -2103,6 +2179,24 @@ def create_session( } return SimpleNamespace(sandbox=SimpleNamespace(name=name or "generated")) + def create_session_from_template( + self, + *, + workspace: str, + template_name: str, + spec: Any = None, + name: str | None = None, + labels: Any = None, + ) -> Any: + self.create_template_kwargs = { + "workspace": workspace, + "template_name": template_name, + "spec": spec, + "name": name, + "labels": labels, + } + return SimpleNamespace(sandbox=SimpleNamespace(name=name or "generated")) + def wait_ready( self, name: str, *, workspace: str, timeout_seconds: float = 300.0 ) -> SandboxRef: @@ -2129,6 +2223,255 @@ def test_create_forwards_name_and_labels() -> None: assert dict(ref.labels) == {"aiq": "deep-research"} +def test_create_from_template_forwards_workload_template_name() -> None: + stub = _FakeSandboxStub() + client = _client_with_fake_stub(stub) + spec = openshell_pb2.SandboxSpec( + providers=["github"], + command=["/opt/worker", "--serve"], + tty=True, + ) + + ref = client.create_from_template( + workspace="default", + template_name="gpu-kata", + spec=spec, + name="job-1", + labels={"team": "runtime"}, + ) + + assert stub.create_request is not None + assert stub.create_request.name == "job-1" + assert stub.create_request.workload_template_name == "gpu-kata" + assert dict(stub.create_request.labels) == {"team": "runtime"} + assert list(stub.create_request.spec.providers) == ["github"] + assert list(stub.create_request.spec.command) == ["/opt/worker", "--serve"] + assert stub.create_request.spec.tty is True + assert dict(ref.labels) == {"team": "runtime"} + + +def test_create_from_template_rejects_empty_template_name() -> None: + stub = _FakeSandboxStub() + client = _client_with_fake_stub(stub) + + with pytest.raises(SandboxError): + client.create_from_template(workspace="default", template_name=" ") + + assert stub.create_request is None + + +def test_sandbox_template_create_builds_template_from_public_fields() -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + + created = client.create( + workspace="default", + name="gpu-kata", + image="ghcr.io/test/gpu-kata:latest", + labels={"team": "runtime"}, + annotations={"owner": "platform"}, + environment={"FEATURE_FLAG": "on"}, + cpu="1", + memory="512Mi", + gpu_count=2, + driver_config={"kubernetes": {"runtime_class_name": "kata"}}, + ) + + assert created.metadata.name == "gpu-kata" + assert stub.create_template_request is not None + assert stub.create_template_request.workspace == "default" + template = stub.create_template_request.template + assert template.metadata.name == "gpu-kata" + assert dict(template.metadata.labels) == {"team": "runtime"} + assert dict(template.metadata.annotations) == {"owner": "platform"} + assert template.spec.workload.image == "ghcr.io/test/gpu-kata:latest" + assert dict(template.spec.workload.environment) == {"FEATURE_FLAG": "on"} + assert template.spec.workload.resources.cpu == "1" + assert template.spec.workload.resources.memory == "512Mi" + assert template.spec.workload.resources.gpu.count == 2 + assert template.spec.driver_config["kubernetes"]["runtime_class_name"] == "kata" + + +def test_sandbox_template_create_materializes_default_workload() -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + + client.create(workspace="default", name="base") + + assert stub.create_template_request is not None + template = stub.create_template_request.template + assert template.HasField("spec") + assert template.spec.HasField("workload") + assert template.spec.workload.image == "" + + +def test_sandbox_template_create_materializes_workload_with_driver_config_only() -> ( + None +): + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + + client.create( + workspace="default", + name="kata-default-image", + driver_config={"kubernetes": {"runtime_class_name": "kata"}}, + ) + + assert stub.create_template_request is not None + template = stub.create_template_request.template + assert template.HasField("spec") + assert template.spec.HasField("workload") + assert template.spec.workload.image == "" + assert template.spec.driver_config["kubernetes"]["runtime_class_name"] == "kata" + + +def test_sandbox_template_create_rejects_missing_public_name() -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + + with pytest.raises(SandboxError): + client.create(workspace="default", image="ghcr.io/test/python:latest") + + assert stub.create_template_request is None + + +def test_sandbox_template_create_rejects_template_and_builder_fields() -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + template = _make_workload_template_proto("gpu-kata") + + with pytest.raises(SandboxError): + client.create(workspace="default", template=template, image="override") + + assert stub.create_template_request is None + + +@pytest.mark.parametrize( + "builder_kwargs", + ( + {"labels": {}}, + {"annotations": {}}, + {"environment": {}}, + {"driver_config": {}}, + ), +) +def test_sandbox_template_create_allows_template_and_empty_builder_mappings( + builder_kwargs: dict[str, Any], +) -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + template = _make_workload_template_proto("gpu-kata") + + created = client.create( + workspace="default", + template=template, + **builder_kwargs, + ) + + assert created.metadata.name == "gpu-kata" + assert stub.create_template_request is not None + assert stub.create_template_request.template.metadata.name == template.metadata.name + assert ( + stub.create_template_request.template.spec.workload.image + == template.spec.workload.image + ) + + +@pytest.mark.parametrize( + "builder_kwargs", + ( + {"labels": {"team": "runtime"}}, + {"annotations": {"owner": "platform"}}, + {"environment": {"FEATURE_FLAG": "on"}}, + {"driver_config": {"kubernetes": {"runtime_class_name": "kata"}}}, + ), +) +def test_sandbox_template_create_rejects_template_and_non_empty_builder_mappings( + builder_kwargs: dict[str, Any], +) -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + template = _make_workload_template_proto("gpu-kata") + + with pytest.raises(SandboxError): + client.create( + workspace="default", + template=template, + **builder_kwargs, + ) + + assert stub.create_template_request is None + + +def test_sandbox_template_create_rejects_non_positive_gpu_count() -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + + with pytest.raises(SandboxError): + client.create(workspace="default", name="gpu-kata", gpu_count=0) + + assert stub.create_template_request is None + + +def test_sandbox_template_client_crud_forwards_requests() -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + template = _make_workload_template_proto("gpu-kata") + template.spec.driver_config.update({"kubernetes": {"runtime_class_name": "kata"}}) + + created = client.create(workspace="default", template=template) + + assert created.metadata.name == "gpu-kata" + assert stub.create_template_request is not None + assert stub.create_template_request.workspace == "default" + assert ( + stub.create_template_request.template.spec.workload.image + == "ghcr.io/test/gpu-kata:latest" + ) + assert ( + stub.create_template_request.template.spec.driver_config["kubernetes"][ + "runtime_class_name" + ] + == "kata" + ) + + got = client.get("gpu-kata", workspace="default") + assert got.metadata.name == "gpu-kata" + assert stub.get_template_request is not None + assert stub.get_template_request.name == "gpu-kata" + assert stub.get_template_request.workspace == "default" + + listed = client.list( + workspace="default", limit=50, offset=10, label_selector="team=runtime" + ) + assert len(listed) == 1 + assert stub.list_template_request is not None + assert stub.list_template_request.workspace == "default" + assert stub.list_template_request.limit == 50 + assert stub.list_template_request.offset == 10 + assert stub.list_template_request.label_selector == "team=runtime" + assert not stub.list_template_request.all_workspaces + + assert client.delete("gpu-kata", workspace="default") is True + assert stub.delete_template_request is not None + assert stub.delete_template_request.name == "gpu-kata" + assert stub.delete_template_request.workspace == "default" + + +def test_sandbox_template_list_for_all_workspaces_clears_workspace() -> None: + stub = _FakeSandboxStub() + client = _template_client_with_fake_stub(stub) + + client.list_for_all_workspaces(limit=100, offset=5, label_selector="team=runtime") + + assert stub.list_template_request is not None + assert stub.list_template_request.all_workspaces + assert stub.list_template_request.workspace == "" + assert stub.list_template_request.limit == 100 + assert stub.list_template_request.offset == 5 + assert stub.list_template_request.label_selector == "team=runtime" + + def test_stop_and_start_forward_workspace_and_return_phase() -> None: stub = _FakeSandboxStub() client = _client_with_fake_stub(stub) @@ -2365,6 +2708,44 @@ def test_high_level_creation_forwards_name_and_labels( } +def test_high_level_template_creation_forwards_template_name( + monkeypatch: pytest.MonkeyPatch, +) -> None: + recording = _RecordingHighLevelClient() + monkeypatch.setattr( + SandboxClient, + "from_active_cluster", + classmethod(lambda _cls, **_kwargs: recording), + ) + + spec = openshell_pb2.SandboxSpec( + providers=["github"], + command=["/opt/worker", "--serve"], + tty=True, + ) + sandbox = Sandbox( + workspace="staging", + template_name="gpu-kata", + spec=spec, + name="job-1", + labels={"team": "runtime"}, + delete_on_exit=False, + ) + sandbox.__enter__() + + assert recording.create_template_kwargs == { + "workspace": "staging", + "template_name": "gpu-kata", + "spec": spec, + "name": "job-1", + "labels": {"team": "runtime"}, + } + assert recording.create_template_kwargs is not None + forwarded_spec = recording.create_template_kwargs["spec"] + assert list(forwarded_spec.command) == ["/opt/worker", "--serve"] + assert forwarded_spec.tty is True + + def test_high_level_attach_rejects_name() -> None: sandbox = Sandbox(workspace="default", sandbox="existing-sandbox", name="job-1") @@ -2385,6 +2766,15 @@ def test_high_level_attach_rejects_labels() -> None: sandbox.__enter__() +def test_high_level_attach_rejects_template_name() -> None: + sandbox = Sandbox( + workspace="default", sandbox="existing-sandbox", template_name="gpu-kata" + ) + + with pytest.raises(SandboxError): + sandbox.__enter__() + + # --------------------------------------------------------------------------- # Workspace support # --------------------------------------------------------------------------- @@ -2453,6 +2843,18 @@ def test_sandbox_ref_includes_workspace_from_proto() -> None: assert ref.workspace == "production" +def test_sandbox_ref_includes_workload_template_provenance() -> None: + proto = _make_sandbox_proto("sandbox-1", "job-1") + proto.created_from_workload_template.name = "gpu-kata" + proto.created_from_workload_template.resource_version = "7" + + ref = _sandbox_ref(proto) + + assert ref.created_from_workload_template is not None + assert ref.created_from_workload_template.name == "gpu-kata" + assert ref.created_from_workload_template.resource_version == "7" + + def test_sandbox_session_delete_passes_workspace() -> None: from openshell.sandbox import SandboxSession diff --git a/scripts/agents/gator/agent.yaml b/scripts/agents/gator/agent.yaml index 363cea207f..dc225669c9 100644 --- a/scripts/agents/gator/agent.yaml +++ b/scripts/agents/gator/agent.yaml @@ -2,7 +2,7 @@ # SPDX-License-Identifier: Apache-2.0 id: gator -payload_version: 7 +payload_version: 8 display_name: Gator Gate Agent description: Validate and monitor OpenShell GitHub issues and pull requests through the gator state machine. diff --git a/scripts/agents/gator/skills/gator-gate/SKILL.md b/scripts/agents/gator/skills/gator-gate/SKILL.md index 99ab8304f5..d66d5029ea 100644 --- a/scripts/agents/gator/skills/gator-gate/SKILL.md +++ b/scripts/agents/gator/skills/gator-gate/SKILL.md @@ -531,9 +531,9 @@ Validate small and concentrated work when it has clear motivation and one of the Documentation changes from non-maintainers must not reorder ToC items, change fundamental hierarchy, or restructure docs without a clear maintainer-approved reason. -### Provider V2 and Credential Support +### Provider Profiles and Credential Support -Provider V2 work is a supported high-traction area, but require all of the following: +Provider-profile work is a supported high-traction area, but requires all of the following: - Clear UX path for how users configure and use the provider feature in OpenShell - Clear statement of why the change is important @@ -541,7 +541,13 @@ Provider V2 work is a supported high-traction area, but require all of the follo - Security boundary analysis for credential handling - Explanation of whether secrets remain hidden from the sandbox agent -Provider additions and updates must use providers v2 through provider profiles. Treat any new or modified legacy `ProviderDiscoverySpec` entries as a blocking review finding unless a maintainer explicitly requests the legacy path. Do not ask contributors to update both systems for compatibility; the provider profile is the source of truth for new provider network policy, credentials, discovery, and refresh metadata. +Provider profiles are the authoritative provider model. Provider additions and +updates must define their network policy, credentials, discovery, refresh +metadata, and user-facing semantics through a built-in or imported profile. +Treat any new or modified legacy `ProviderDiscoverySpec` entries as a blocking +review finding unless a maintainer explicitly requests the legacy path. Do not +ask contributors to update both systems for compatibility or to enable a +gateway feature switch; profile-backed behavior is always active. Be skeptical of changes that expose raw credentials to agents or weaken the credential proxy model, even if the user story is clear. diff --git a/sdk/go/docs/src/SUMMARY.md b/sdk/go/docs/src/SUMMARY.md index 7a0915bfeb..bf500f68eb 100644 --- a/sdk/go/docs/src/SUMMARY.md +++ b/sdk/go/docs/src/SUMMARY.md @@ -15,6 +15,7 @@ - [Overview](api/overview.md) - [Client](api/client.md) - [Sandboxes](api/sandboxes.md) +- [Sandbox Templates](api/sandbox-templates.md) - [Exec](api/exec.md) - [Providers](api/providers.md) - [Profiles](api/profiles.md) diff --git a/sdk/go/docs/src/api/client.md b/sdk/go/docs/src/api/client.md index 748de5327e..9fe8b4aed9 100644 --- a/sdk/go/docs/src/api/client.md +++ b/sdk/go/docs/src/api/client.md @@ -2,14 +2,17 @@ Constructor: `v1.NewClient(config)` -The `ClientInterface` is the root entry point for all SDK operations. It provides -typed accessors for each resource domain and manages the underlying gRPC connection. +`Client` is the root entry point for SDK operations. It provides typed accessors +for each resource domain and manages the underlying gRPC connection. The +`ClientInterface` covers the stable core accessors; additive helpers such as +`SandboxTemplates()` are available on the concrete client. ## Methods | Accessor | Returns | Description | |----------|---------|-------------| | `Sandboxes()` | `SandboxInterface` | Sandbox lifecycle management | +| `SandboxTemplates()` | `SandboxTemplateInterface` | Reusable sandbox template management | | `Providers()` | `ProviderInterface` | Provider CRUD and idempotent ensure | | `Services()` | `ServiceInterface` | Service exposure and management | | `Exec()` | `ExecInterface` | Command execution (run, stream, interactive) | diff --git a/sdk/go/docs/src/api/fake.md b/sdk/go/docs/src/api/fake.md index 084858c542..ae96fc9d39 100644 --- a/sdk/go/docs/src/api/fake.md +++ b/sdk/go/docs/src/api/fake.md @@ -61,6 +61,13 @@ client.AddSandbox("default", &types.Sandbox{ Status: types.SandboxStatus{Phase: types.SandboxReady}, }) +client.AddSandboxTemplate("default", &types.SandboxWorkloadTemplate{ + Name: "gpu-kata", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + }, +}) + client.AddProvider("default", &types.Provider{ Name: "my-provider", Spec: types.ProviderSpec{Type: "docker"}, @@ -78,11 +85,13 @@ insertion does not affect the stored object. ## Sub-Client Coverage -The fake client implements every interface in `v1.ClientInterface`: +The fake client implements every stable accessor in `v1.ClientInterface` plus +additive concrete-client accessors such as `SandboxTemplates()`: | Accessor | Interface | Behavior | |----------|-----------|----------| | `Sandboxes()` | `SandboxInterface` | Full CRUD, Watch, WaitReady | +| `SandboxTemplates()` | `SandboxTemplateInterface` | Full CRUD | | `Providers()` | `ProviderInterface` | Full CRUD, Ensure | | `Workspaces()` | `WorkspaceInterface` | Full CRUD, Members | | `Health()` | `HealthInterface` | Configurable result | diff --git a/sdk/go/docs/src/api/overview.md b/sdk/go/docs/src/api/overview.md index d96bbd747a..0ff01c4ce4 100644 --- a/sdk/go/docs/src/api/overview.md +++ b/sdk/go/docs/src/api/overview.md @@ -1,6 +1,7 @@ # API Overview -The OpenShell Go SDK exposes 12 interfaces through the sub-client pattern. You access each interface through a typed accessor on the `Client`. +The OpenShell Go SDK exposes typed interfaces through the sub-client pattern. +You access each interface through a typed accessor on the concrete `Client`. ## Interface Summary @@ -9,6 +10,7 @@ The OpenShell Go SDK exposes 12 interfaces through the sub-client pattern. You a | Interface | Accessor | Description | |-----------|----------|-------------| | [SandboxInterface](sandboxes.md) | `client.Sandboxes()` | Create, manage, and watch sandbox lifecycle | +| [SandboxTemplateInterface](sandbox-templates.md) | `client.SandboxTemplates()` | Manage reusable sandbox templates | | [ExecInterface](exec.md) | `client.Exec()` | Run commands, stream output, interactive sessions | | [ProviderInterface](providers.md) | `client.Providers()` | Manage compute providers and their lifecycle | | [ServiceInterface](services.md) | `client.Services()` | Expose and manage HTTP services inside sandboxes | @@ -39,6 +41,7 @@ These are accessed through `client.Providers()`: Each interface has a reference page with method signatures and usage examples: - **[Sandboxes](sandboxes.md)**: Create sandboxes, wait for readiness, watch state changes, manage providers, retrieve logs. +- **[Sandbox Templates](sandbox-templates.md)**: Create reusable workload templates and launch sandboxes from them. - **[Exec](exec.md)**: Execute commands with one-shot, streaming, or interactive modes. - **[Providers](providers.md)**: Register and manage compute providers. Includes sub-clients for profiles and credential refresh. - **[Services](services.md)**: Expose and manage HTTP services inside sandboxes. diff --git a/sdk/go/docs/src/api/sandbox-templates.md b/sdk/go/docs/src/api/sandbox-templates.md new file mode 100644 index 0000000000..d1dcc86e47 --- /dev/null +++ b/sdk/go/docs/src/api/sandbox-templates.md @@ -0,0 +1,127 @@ +# Sandbox Templates + +Accessor: `client.SandboxTemplates()` + +Manage reusable, workspace-scoped sandbox workload templates. Templates own the +portable workload shape and optional driver-specific config. Sandbox creation +can reference a template by name while supplying only governance fields such as +providers or policy. + +The Go SDK names the reusable resource `SandboxWorkloadTemplate` because +`SandboxTemplate` already represents the legacy inline compute template inside +`SandboxSpec`. + +## Create + +Creates a reusable template in a workspace. + +```go +gpuCount := uint32(1) + +template, err := client.SandboxTemplates().Create(ctx, "default", &v1.SandboxWorkloadTemplate{ + Name: "gpu-kata", + Labels: map[string]string{ + "team": "platform", + }, + Spec: v1.SandboxWorkloadTemplateSpec{ + Workload: &v1.SandboxWorkloadConfig{ + Image: "nvcr.io/nvidia/openshell:latest", + Environment: map[string]string{ + "NVIDIA_VISIBLE_DEVICES": "all", + }, + Resources: &v1.SandboxResources{ + CPU: "2", + Memory: "8Gi", + GPU: &v1.SandboxGPURequirements{Count: &gpuCount}, + }, + }, + DriverConfig: map[string]any{ + "kubernetes": map[string]any{ + "pod": map[string]any{ + "runtime_class_name": "kata", + }, + }, + }, + DesiredServiceLevel: &v1.SandboxServiceLevel{ + Startup: &v1.SandboxStartup{ + ReadyWithin: 45 * time.Second, + MaxBurst: 2, + }, + }, + }, +}) +``` + +Set `GPU: &v1.SandboxGPURequirements{}` to request the active driver's default +GPU assignment without specifying a count. + +## Create a Sandbox From a Template + +Use `CreateSandboxFromTemplate` to create a sandbox from a named reusable +template without changing the legacy `Sandboxes()` interface. + +```go +sb, err := client.CreateSandboxFromTemplate( + ctx, + "default", + "training-run", + "gpu-kata", + &v1.SandboxSpec{ + Providers: []string{"openai"}, + Policy: policy, + }, + map[string]string{"job": "training"}, +) +``` + +When creating from a template, the spec should only include governance fields: +`Providers`, `Policy`, `Command`, and `TTY`. Workload fields such as image, +environment, CPU, memory, GPU, and driver config come from the template. + +## Get + +Retrieves a template by name. + +```go +template, err := client.SandboxTemplates().Get(ctx, "default", "gpu-kata") +fmt.Println(template.Spec.Workload.Image) +``` + +## List + +Lists templates in one workspace or across all workspaces. + +```go +templates, err := client.SandboxTemplates().List(ctx, "default", v1.ListOptions{ + Limit: 50, + Offset: 0, +}) + +allTemplates, err := client.SandboxTemplates().List(ctx, "", v1.ListOptions{ + AllWorkspaces: true, +}) +``` + +## Delete + +Deletes a template by name. Existing sandboxes created from the template are not +deleted. + +```go +deleted, err := client.SandboxTemplates().Delete(ctx, "default", "gpu-kata") +``` + +## Fake Client + +The fake client includes the same template sub-client and can be pre-populated +for tests. + +```go +client := fake.NewClient() +client.AddSandboxTemplate("default", &types.SandboxWorkloadTemplate{ + Name: "gpu-kata", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + }, +}) +``` diff --git a/sdk/go/docs/src/api/sandboxes.md b/sdk/go/docs/src/api/sandboxes.md index a9db856786..698982fe13 100644 --- a/sdk/go/docs/src/api/sandboxes.md +++ b/sdk/go/docs/src/api/sandboxes.md @@ -20,6 +20,32 @@ sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSp }) ``` +Set `GPU: true` to request the active driver's default GPU assignment. Set +`GPUCount` when the sandbox needs a specific GPU count; a non-nil `GPUCount` +also implies `GPU`. + +## Create From Template + +Creates a new sandbox from a reusable sandbox workload template. The template +provides workload fields such as image, environment, resources, and driver +config. The create request supplies governance fields such as providers, +policy, command, and TTY. + +```go +sb, err := client.CreateSandboxFromTemplate(ctx, + "default", + "my-sandbox", + "gpu-kata", + &v1.SandboxSpec{ + Providers: []string{"openai"}, + Policy: policy, + }, + map[string]string{"team": "platform"}, +) +``` + +See [Sandbox Templates](sandbox-templates.md) for template CRUD. + ## Get Retrieves a sandbox by name. diff --git a/sdk/go/docs/src/introduction.md b/sdk/go/docs/src/introduction.md index 61f3a05ca2..fbe63dbb7f 100644 --- a/sdk/go/docs/src/introduction.md +++ b/sdk/go/docs/src/introduction.md @@ -4,7 +4,7 @@ The OpenShell Go SDK provides an idiomatic Go client for the OpenShell gateway A ## Key Features -- **Sub-client pattern**: A single `Client` provides typed accessors for each API domain (Sandboxes, Exec, Providers, Files, Health, SSH, TCP, Config, Policy, Services) +- **Sub-client pattern**: A single `Client` provides typed accessors for each API domain (Sandboxes, SandboxTemplates, Exec, Providers, Files, Health, SSH, TCP, Config, Policy, Services) - **Clean types**: SDK types are self-contained, so your code works with idiomatic Go types without extra dependencies - **Fake client for testing**: An in-memory implementation of the full `ClientInterface` for testing without a live gateway - **Watch and streaming**: First-class support for watching sandbox state changes and streaming command output diff --git a/sdk/go/openshell/v1/client.go b/sdk/go/openshell/v1/client.go index bc3ee43165..06d8183360 100644 --- a/sdk/go/openshell/v1/client.go +++ b/sdk/go/openshell/v1/client.go @@ -4,6 +4,7 @@ package v1 import ( + "context" "sync" "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" @@ -18,6 +19,8 @@ type Config = types.Config // ClientInterface defines the top-level SDK surface. type ClientInterface interface { Sandboxes() SandboxInterface + SandboxTemplates() SandboxTemplateInterface + CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error) Providers() ProviderInterface Services() ServiceInterface Exec() ExecInterface @@ -49,18 +52,20 @@ type Client struct { closeOnce sync.Once closeErr error - sandboxes SandboxInterface - providers ProviderInterface - services ServiceInterface - exec ExecInterface - files FileInterface - health HealthInterface - ssh SSHInterface - tcp TCPInterface - cfg ConfigInterface - policy PolicyInterface - workspaces WorkspaceInterface - inference InferenceInterface + sandboxes SandboxInterface + templateCreate SandboxTemplateCreateInterface + templates SandboxTemplateInterface + providers ProviderInterface + services ServiceInterface + exec ExecInterface + files FileInterface + health HealthInterface + ssh SSHInterface + tcp TCPInterface + cfg ConfigInterface + policy PolicyInterface + workspaces WorkspaceInterface + inference InferenceInterface } // NewClient creates a new SDK client connected to the given gateway. @@ -93,7 +98,10 @@ func NewClient(cfg Config) (*Client, error) { config: cfg, } - c.sandboxes = newSandboxClient(conn) + sandboxes := newSandboxClient(conn) + c.sandboxes = sandboxes + c.templateCreate = sandboxes + c.templates = newSandboxTemplateClient(conn) c.providers = newProviderClient(conn) c.services = newServiceClient(conn) c.exec = newExecClient(conn, c.sandboxes) @@ -112,6 +120,15 @@ func NewClient(cfg Config) (*Client, error) { // Sandboxes returns the sandbox sub-client. func (c *Client) Sandboxes() SandboxInterface { return c.sandboxes } +// SandboxTemplates returns the reusable sandbox template sub-client. +func (c *Client) SandboxTemplates() SandboxTemplateInterface { return c.templates } + +// CreateSandboxFromTemplate creates a sandbox from a named workload template +// without changing the legacy Sandboxes() interface. +func (c *Client) CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error) { + return c.templateCreate.CreateFromTemplate(ctx, workspace, name, templateName, spec, labels, opts...) +} + // Providers returns the provider sub-client. func (c *Client) Providers() ProviderInterface { return c.providers } diff --git a/sdk/go/openshell/v1/fake/fake.go b/sdk/go/openshell/v1/fake/fake.go index d2978bc08c..16a35fed8a 100644 --- a/sdk/go/openshell/v1/fake/fake.go +++ b/sdk/go/openshell/v1/fake/fake.go @@ -4,6 +4,7 @@ package fake import ( + "context" "sync" v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1" @@ -15,23 +16,26 @@ import ( // real gRPC connection. Create one with NewClient. type Client struct { sandboxStore *objectStore[*types.Sandbox] + templateStore *objectStore[*types.SandboxWorkloadTemplate] providerStore *objectStore[*types.Provider] workspaceStore *objectStore[*types.Workspace] memberStore *objectStore[*types.WorkspaceMember] sandboxBroadcaster *watchBroadcaster[*types.Sandbox] - sandboxes v1.SandboxInterface - providers v1.ProviderInterface - services v1.ServiceInterface - exec v1.ExecInterface - files v1.FileInterface - health v1.HealthInterface - ssh v1.SSHInterface - tcp v1.TCPInterface - cfg v1.ConfigInterface - policy v1.PolicyInterface - workspaces v1.WorkspaceInterface - inference v1.InferenceInterface + sandboxes v1.SandboxInterface + templateCreate v1.SandboxTemplateCreateInterface + templates v1.SandboxTemplateInterface + providers v1.ProviderInterface + services v1.ServiceInterface + exec v1.ExecInterface + files v1.FileInterface + health v1.HealthInterface + ssh v1.SSHInterface + tcp v1.TCPInterface + cfg v1.ConfigInterface + policy v1.PolicyInterface + workspaces v1.WorkspaceInterface + inference v1.InferenceInterface closeOnce sync.Once closed bool @@ -70,13 +74,17 @@ func WithCurrentUser(user *types.CurrentUser) ClientOption { func NewClient(opts ...ClientOption) *Client { fc := &Client{ sandboxStore: newobjectStore(sandboxName, copySandbox), + templateStore: newobjectStore(sandboxWorkloadTemplateName, copySandboxWorkloadTemplate), providerStore: newobjectStore(providerName, copyProvider), workspaceStore: newobjectStore(workspaceName, copyWorkspace), memberStore: newobjectStore(memberName, copyMember), sandboxBroadcaster: newWatchBroadcaster[*types.Sandbox](), } - fc.sandboxes = newFakeSandboxClient(fc.sandboxStore, fc.sandboxBroadcaster, fc.isClosed) + sandboxes := newFakeSandboxClient(fc.sandboxStore, fc.templateStore, fc.sandboxBroadcaster, fc.isClosed) + fc.sandboxes = sandboxes + fc.templateCreate = sandboxes + fc.templates = newFakeSandboxTemplateClient(fc.templateStore, fc.isClosed) fc.providers = newFakeProviderClient(fc.providerStore, fc.isClosed) fc.services = newFakeServiceClient(fc.isClosed) fc.exec = newFakeExecClient(fc.isClosed) @@ -107,6 +115,15 @@ func (fc *Client) isClosed() bool { // Sandboxes returns the sandbox sub-client. func (fc *Client) Sandboxes() v1.SandboxInterface { return fc.sandboxes } +// SandboxTemplates returns the reusable sandbox template sub-client. +func (fc *Client) SandboxTemplates() v1.SandboxTemplateInterface { return fc.templates } + +// CreateSandboxFromTemplate creates a sandbox from a named workload template +// without changing the legacy Sandboxes() interface. +func (fc *Client) CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *types.SandboxSpec, labels map[string]string, opts ...types.CreateOptions) (*types.Sandbox, error) { + return fc.templateCreate.CreateFromTemplate(ctx, workspace, name, templateName, spec, labels, opts...) +} + // Providers returns the provider sub-client. func (fc *Client) Providers() v1.ProviderInterface { return fc.providers } @@ -164,6 +181,16 @@ func (fc *Client) AddSandbox(workspace string, sb *types.Sandbox) { fc.sandboxStore.Insert(workspace, sb) } +// AddSandboxTemplate inserts a sandbox workload template directly into the store. +// This is intended for pre-seeding test fixtures before the test begins. The +// template is deep-copied on insert. +func (fc *Client) AddSandboxTemplate(workspace string, template *types.SandboxWorkloadTemplate) { + if template == nil { + return + } + fc.templateStore.Insert(workspace, template) +} + // AddProvider inserts a provider directly into the store without triggering // any side effects. This is intended for pre-seeding test fixtures before // the test begins. The provider is deep-copied on insert. diff --git a/sdk/go/openshell/v1/fake/sandbox.go b/sdk/go/openshell/v1/fake/sandbox.go index 6fa0c316a9..5de3062d96 100644 --- a/sdk/go/openshell/v1/fake/sandbox.go +++ b/sdk/go/openshell/v1/fake/sandbox.go @@ -32,6 +32,10 @@ func copySandbox(sb *types.Sandbox) *types.Sandbox { t := *sb.DeletionTimestamp cp.DeletionTimestamp = &t } + if sb.CreatedFromWorkloadTemplate != nil { + provenance := *sb.CreatedFromWorkloadTemplate + cp.CreatedFromWorkloadTemplate = &provenance + } cp.Spec = copySandboxSpec(sb.Spec) cp.Status = copySandboxStatus(sb.Status) return &cp @@ -40,6 +44,7 @@ func copySandbox(sb *types.Sandbox) *types.Sandbox { func copySandboxSpec(s types.SandboxSpec) types.SandboxSpec { s.Environment = copyStringMap(s.Environment) s.Providers = copyStringSlice(s.Providers) + s.Command = copyStringSlice(s.Command) if s.Template != nil { t := copySandboxTemplate(*s.Template) s.Template = &t @@ -255,21 +260,27 @@ func copyStringSlice(s []string) []string { // fakeSandboxClient implements v1.SandboxInterface backed by an in-memory // objectStore and watchBroadcaster. type fakeSandboxClient struct { - store *objectStore[*types.Sandbox] - broadcaster *watchBroadcaster[*types.Sandbox] - closedFunc func() bool + store *objectStore[*types.Sandbox] + templateStore *objectStore[*types.SandboxWorkloadTemplate] + broadcaster *watchBroadcaster[*types.Sandbox] + closedFunc func() bool } +var _ v1.SandboxInterface = (*fakeSandboxClient)(nil) +var _ v1.SandboxTemplateCreateInterface = (*fakeSandboxClient)(nil) + // newFakeSandboxClient creates a new fakeSandboxClient. func newFakeSandboxClient( store *objectStore[*types.Sandbox], + templateStore *objectStore[*types.SandboxWorkloadTemplate], broadcaster *watchBroadcaster[*types.Sandbox], closedFunc func() bool, ) *fakeSandboxClient { return &fakeSandboxClient{ - store: store, - broadcaster: broadcaster, - closedFunc: closedFunc, + store: store, + templateStore: templateStore, + broadcaster: broadcaster, + closedFunc: closedFunc, } } @@ -315,6 +326,117 @@ func (c *fakeSandboxClient) Create(_ context.Context, workspace, name string, sp return result, nil } +// CreateFromTemplate creates a new sandbox from a named template with Provisioning phase. +func (c *fakeSandboxClient) CreateFromTemplate(_ context.Context, workspace, name, templateName string, spec *types.SandboxSpec, labels map[string]string, opts ...types.CreateOptions) (*types.Sandbox, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + if templateName == "" { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "template name is required"} + } + if err := validateTemplateCreateSpec(spec); err != nil { + return nil, err + } + template, err := c.templateStore.Get(workspace, templateName) + if err != nil { + return nil, err + } + if spec == nil { + spec = &types.SandboxSpec{} + } + + var annotations map[string]string + if len(opts) > 0 { + annotations = copyStringMap(opts[0].Annotations) + } + + resolvedSpec := sandboxSpecFromWorkloadTemplate(template) + resolvedSpec.Providers = copyStringSlice(spec.Providers) + resolvedSpec.Policy = copySandboxPolicy(spec.Policy) + resolvedSpec.Command = copyStringSlice(spec.Command) + resolvedSpec.TTY = spec.TTY + + sb := &types.Sandbox{ + Name: name, + Workspace: workspace, + CreatedAt: time.Now(), + Labels: copyStringMap(labels), + Annotations: annotations, + ResourceVersion: 1, + Spec: resolvedSpec, + CreatedFromWorkloadTemplate: &types.SandboxWorkloadTemplateProvenance{ + Name: template.Name, + ResourceVersion: fmt.Sprint(template.ResourceVersion), + }, + Status: types.SandboxStatus{ + SandboxName: name, + Phase: types.SandboxProvisioning, + }, + } + + result, err := c.store.Create(workspace, sb) + if err != nil { + return nil, err + } + + c.broadcaster.Broadcast(types.Event[*types.Sandbox]{ + Type: types.EventAdded, + Object: copySandbox(result), + }, name) + + return result, nil +} + +func validateTemplateCreateSpec(spec *types.SandboxSpec) error { + if spec == nil { + return nil + } + if spec.LogLevel != "" || len(spec.Environment) > 0 || spec.Template != nil || spec.GPU || spec.GPUCount != nil { + return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "template creates only allow policy, providers, command, and tty in spec"} + } + return nil +} + +func sandboxSpecFromWorkloadTemplate(template *types.SandboxWorkloadTemplate) types.SandboxSpec { + var spec types.SandboxSpec + if template == nil || template.Spec.Workload == nil { + return spec + } + + workload := template.Spec.Workload + spec.Environment = copyStringMap(workload.Environment) + spec.Template = &types.SandboxTemplate{ + Image: workload.Image, + Resources: sandboxTemplateResources(workload.Resources), + DriverConfig: copyAnyMap(template.Spec.DriverConfig), + } + if workload.Resources != nil && workload.Resources.GPU != nil { + spec.GPU = true + if workload.Resources.GPU.Count != nil { + count := *workload.Resources.GPU.Count + spec.GPUCount = &count + } + } + return spec +} + +func sandboxTemplateResources(resources *types.SandboxResources) map[string]any { + if resources == nil { + return nil + } + limits := make(map[string]any) + if resources.CPU != "" { + limits["cpu"] = resources.CPU + } + if resources.Memory != "" { + limits["memory"] = resources.Memory + } + if len(limits) == 0 { + return nil + } + return map[string]any{"limits": limits} +} + // Get retrieves a sandbox by name. func (c *fakeSandboxClient) Get(_ context.Context, workspace, name string) (*types.Sandbox, error) { if c.closedFunc() { diff --git a/sdk/go/openshell/v1/fake/sandbox_template.go b/sdk/go/openshell/v1/fake/sandbox_template.go new file mode 100644 index 0000000000..8dbf68cc12 --- /dev/null +++ b/sdk/go/openshell/v1/fake/sandbox_template.go @@ -0,0 +1,301 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package fake + +import ( + "context" + "slices" + "strings" + "time" + + v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1" + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" +) + +func sandboxWorkloadTemplateName(template *types.SandboxWorkloadTemplate) string { + return template.Name +} + +func copySandboxWorkloadTemplate(template *types.SandboxWorkloadTemplate) *types.SandboxWorkloadTemplate { + if template == nil { + return nil + } + copied := *template + copied.Labels = copyStringMap(template.Labels) + copied.Annotations = copyStringMap(template.Annotations) + if template.DeletionTimestamp != nil { + t := *template.DeletionTimestamp + copied.DeletionTimestamp = &t + } + copied.Spec = copySandboxWorkloadTemplateSpec(template.Spec) + return &copied +} + +func copySandboxWorkloadTemplateSpec(spec types.SandboxWorkloadTemplateSpec) types.SandboxWorkloadTemplateSpec { + if spec.Workload != nil { + workload := *spec.Workload + workload.Environment = copyStringMap(spec.Workload.Environment) + if spec.Workload.Resources != nil { + resources := *spec.Workload.Resources + if spec.Workload.Resources.GPU != nil { + gpu := *spec.Workload.Resources.GPU + if spec.Workload.Resources.GPU.Count != nil { + count := *spec.Workload.Resources.GPU.Count + gpu.Count = &count + } + resources.GPU = &gpu + } + workload.Resources = &resources + } + spec.Workload = &workload + } + spec.DriverConfig = copyAnyMap(spec.DriverConfig) + if spec.DesiredServiceLevel != nil { + level := *spec.DesiredServiceLevel + if spec.DesiredServiceLevel.Startup != nil { + startup := *spec.DesiredServiceLevel.Startup + level.Startup = &startup + } + spec.DesiredServiceLevel = &level + } + return spec +} + +type fakeSandboxTemplateClient struct { + store *objectStore[*types.SandboxWorkloadTemplate] + closedFunc func() bool +} + +var _ v1.SandboxTemplateInterface = (*fakeSandboxTemplateClient)(nil) + +func newFakeSandboxTemplateClient( + store *objectStore[*types.SandboxWorkloadTemplate], + closedFunc func() bool, +) *fakeSandboxTemplateClient { + return &fakeSandboxTemplateClient{ + store: store, + closedFunc: closedFunc, + } +} + +func (c *fakeSandboxTemplateClient) Create(_ context.Context, workspace string, template *types.SandboxWorkloadTemplate) (*types.SandboxWorkloadTemplate, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + if template == nil { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "template must not be nil"} + } + if err := validateSandboxWorkloadTemplate(template); err != nil { + return nil, err + } + + t := copySandboxWorkloadTemplate(template) + t.Workspace = workspace + t.CreatedAt = time.Now() + t.ResourceVersion = 1 + + return c.store.Create(workspace, t) +} + +func (c *fakeSandboxTemplateClient) Get(_ context.Context, workspace, name string) (*types.SandboxWorkloadTemplate, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + return c.store.Get(workspace, name) +} + +func (c *fakeSandboxTemplateClient) List(_ context.Context, workspace string, opts ...v1.ListOptions) ([]*types.SandboxWorkloadTemplate, error) { + if c.closedFunc() { + return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + var options v1.ListOptions + if len(opts) > 0 { + options = opts[0] + if options.Limit < 0 { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "limit must not be negative"} + } + if options.Offset < 0 { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "offset must not be negative"} + } + } + var templates []*types.SandboxWorkloadTemplate + if options.AllWorkspaces { + templates = c.store.ListAll() + } else { + templates = c.store.List(workspace) + } + slices.SortFunc(templates, compareSandboxWorkloadTemplatesForList) + templates, err := filterSandboxWorkloadTemplatesByLabelSelector(templates, options.LabelSelector) + if err != nil { + return nil, err + } + return paginateSandboxWorkloadTemplates(templates, options), nil +} + +func (c *fakeSandboxTemplateClient) Delete(_ context.Context, workspace, name string) (bool, error) { + if c.closedFunc() { + return false, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"} + } + _, existed := c.store.DeleteAndGet(workspace, name) + return existed, nil +} + +func validateSandboxWorkloadTemplate(template *types.SandboxWorkloadTemplate) error { + if template.Name == "" { + return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox_template.metadata.name is required"} + } + if !isDNS1123Label(template.Name) { + return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "template.metadata.name must be a DNS-1123 label"} + } + if template.Spec.Workload == nil { + return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "sandbox template workload is required"} + } + if err := validateSandboxWorkloadEnvironment(template.Spec.Workload.Environment); err != nil { + return err + } + if resources := template.Spec.Workload.Resources; resources != nil && resources.GPU != nil && resources.GPU.Count != nil && *resources.GPU.Count == 0 { + return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "gpu count must be greater than 0"} + } + return nil +} + +func validateSandboxWorkloadEnvironment(environment map[string]string) error { + for key := range environment { + if !isValidEnvKey(key) { + return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "spec.template.environment keys must match ^[A-Za-z_][A-Za-z0-9_]*$"} + } + if len(key) >= len("OPENSHELL_") && key[:len("OPENSHELL_")] == "OPENSHELL_" { + return &types.StatusError{Code: types.ErrorInvalidArgument, Message: "spec.template.environment keys starting with OPENSHELL_ are reserved"} + } + } + return nil +} + +func filterSandboxWorkloadTemplatesByLabelSelector( + templates []*types.SandboxWorkloadTemplate, + selector string, +) ([]*types.SandboxWorkloadTemplate, error) { + selector = strings.TrimSpace(selector) + if selector == "" { + return templates, nil + } + labels, err := parseSimpleLabelSelector(selector) + if err != nil { + return nil, err + } + filtered := make([]*types.SandboxWorkloadTemplate, 0, len(templates)) + for _, template := range templates { + if labelsMatchSelector(template.Labels, labels) { + filtered = append(filtered, template) + } + } + return filtered, nil +} + +func parseSimpleLabelSelector(selector string) (map[string]string, error) { + labels := make(map[string]string) + for _, part := range strings.Split(selector, ",") { + part = strings.TrimSpace(part) + if part == "" { + continue + } + key, value, ok := strings.Cut(part, "=") + if !ok || strings.TrimSpace(key) == "" { + return nil, &types.StatusError{Code: types.ErrorInvalidArgument, Message: "label selector must use key=value pairs"} + } + labels[strings.TrimSpace(key)] = strings.TrimSpace(value) + } + return labels, nil +} + +func labelsMatchSelector(labels map[string]string, selector map[string]string) bool { + for key, value := range selector { + if labels[key] != value { + return false + } + } + return true +} + +func compareSandboxWorkloadTemplatesForList(a, b *types.SandboxWorkloadTemplate) int { + if a.CreatedAt.Before(b.CreatedAt) { + return -1 + } + if a.CreatedAt.After(b.CreatedAt) { + return 1 + } + if a.Name < b.Name { + return -1 + } + if a.Name > b.Name { + return 1 + } + if a.Workspace < b.Workspace { + return -1 + } + if a.Workspace > b.Workspace { + return 1 + } + return 0 +} + +func paginateSandboxWorkloadTemplates( + templates []*types.SandboxWorkloadTemplate, + options v1.ListOptions, +) []*types.SandboxWorkloadTemplate { + if options.Offset >= len(templates) { + return templates[:0] + } + templates = templates[options.Offset:] + if options.Limit > 0 && options.Limit < len(templates) { + return templates[:options.Limit] + } + return templates +} + +func isDNS1123Label(name string) bool { + if len(name) == 0 || len(name) > 63 || name[0] == '-' || name[len(name)-1] == '-' { + return false + } + previousHyphen := false + for i := 0; i < len(name); i++ { + b := name[i] + if b == '-' { + if previousHyphen { + return false + } + previousHyphen = true + continue + } + previousHyphen = false + if !isASCIIDigit(b) && (b < 'a' || b > 'z') { + return false + } + } + return true +} + +func isValidEnvKey(key string) bool { + if key == "" { + return false + } + for i := 0; i < len(key); i++ { + b := key[i] + if i == 0 && b != '_' && !isASCIIAlpha(b) { + return false + } + if i > 0 && b != '_' && !isASCIIAlpha(b) && !isASCIIDigit(b) { + return false + } + } + return true +} + +func isASCIIAlpha(b byte) bool { + return (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') +} + +func isASCIIDigit(b byte) bool { + return b >= '0' && b <= '9' +} diff --git a/sdk/go/openshell/v1/fake/sandbox_template_test.go b/sdk/go/openshell/v1/fake/sandbox_template_test.go new file mode 100644 index 0000000000..06a5187227 --- /dev/null +++ b/sdk/go/openshell/v1/fake/sandbox_template_test.go @@ -0,0 +1,481 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package fake + +import ( + "context" + "testing" + "time" + + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func newTestSandboxTemplateClient() *fakeSandboxTemplateClient { + store := newobjectStore(sandboxWorkloadTemplateName, copySandboxWorkloadTemplate) + return newFakeSandboxTemplateClient(store, func() bool { return false }) +} + +func testSandboxWorkloadTemplate(name string) *types.SandboxWorkloadTemplate { + return &types.SandboxWorkloadTemplate{ + Name: name, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "registry.example.com/agent:latest"}, + }, + } +} + +func TestIsDNS1123Label(t *testing.T) { + tests := map[string]bool{ + "": false, + "gpu-kata": true, + "Invalid_Template_Name": false, + "-gpu": false, + "gpu-": false, + "gpu--kata": false, + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa": false, + } + + for name, want := range tests { + assert.Equal(t, want, isDNS1123Label(name), "name %q", name) + } +} + +func TestSandboxTemplate_CreateGetListDelete(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + template := &types.SandboxWorkloadTemplate{ + Name: "gpu-kata", + Labels: map[string]string{"team": "platform"}, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + DriverConfig: map[string]any{"kubernetes": map[string]any{"runtime_class_name": "kata"}}, + DesiredServiceLevel: &types.SandboxServiceLevel{ + Startup: &types.SandboxStartup{ReadyWithin: 30 * time.Second, MaxBurst: 4}, + }, + }, + } + + created, err := tc.Create(ctx, "default", template) + require.NoError(t, err) + assert.Equal(t, "gpu-kata", created.Name) + assert.Equal(t, "default", created.Workspace) + assert.Equal(t, uint64(1), created.ResourceVersion) + assert.NotZero(t, created.CreatedAt) + + got, err := tc.Get(ctx, "default", "gpu-kata") + require.NoError(t, err) + assert.Equal(t, "python:3.12", got.Spec.Workload.Image) + assert.Equal(t, "kata", got.Spec.DriverConfig["kubernetes"].(map[string]any)["runtime_class_name"]) + + listed, err := tc.List(ctx, "default") + require.NoError(t, err) + require.Len(t, listed, 1) + assert.Equal(t, "gpu-kata", listed[0].Name) + + deleted, err := tc.Delete(ctx, "default", "gpu-kata") + require.NoError(t, err) + assert.True(t, deleted) + _, err = tc.Get(ctx, "default", "gpu-kata") + require.Error(t, err) + assert.True(t, types.IsNotFound(err)) + + deleted, err = tc.Delete(ctx, "default", "gpu-kata") + require.NoError(t, err) + assert.False(t, deleted) +} + +func TestSandboxTemplate_CreateAlreadyExists(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + template := testSandboxWorkloadTemplate("gpu-kata") + _, err := tc.Create(ctx, "default", template) + require.NoError(t, err) + + _, err = tc.Create(ctx, "default", template) + require.Error(t, err) + assert.True(t, types.IsAlreadyExists(err)) +} + +func TestSandboxTemplate_ListAllWorkspaces(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + _, _ = tc.Create(ctx, "default", testSandboxWorkloadTemplate("default-template")) + _, _ = tc.Create(ctx, "team-a", testSandboxWorkloadTemplate("team-template")) + + listed, err := tc.List(ctx, "default", types.ListOptions{AllWorkspaces: true}) + require.NoError(t, err) + assert.Len(t, listed, 2) +} + +func TestSandboxTemplate_ListFiltersByLabelSelector(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + _, _ = tc.Create(ctx, "default", &types.SandboxWorkloadTemplate{ + Name: "runtime-template", + Labels: map[string]string{"team": "runtime"}, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + }, + }) + _, _ = tc.Create(ctx, "default", &types.SandboxWorkloadTemplate{ + Name: "batch-template", + Labels: map[string]string{"team": "batch"}, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + }, + }) + + listed, err := tc.List(ctx, "default", types.ListOptions{LabelSelector: "team=runtime"}) + + require.NoError(t, err) + require.Len(t, listed, 1) + assert.Equal(t, "runtime-template", listed[0].Name) +} + +func TestSandboxTemplate_ListRejectsNegativePagination(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + _, err := tc.List(ctx, "default", types.ListOptions{Limit: -1}) + require.Error(t, err) + assert.True(t, types.IsInvalidArgument(err)) + + _, err = tc.List(ctx, "default", types.ListOptions{Offset: -1}) + require.Error(t, err) + assert.True(t, types.IsInvalidArgument(err)) +} + +func TestSandboxTemplate_ListAppliesPaginationAfterFiltering(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + _, _ = tc.Create(ctx, "default", &types.SandboxWorkloadTemplate{ + Name: "runtime-a", + Labels: map[string]string{"team": "runtime"}, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + }, + }) + _, _ = tc.Create(ctx, "default", &types.SandboxWorkloadTemplate{ + Name: "batch-a", + Labels: map[string]string{"team": "batch"}, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + }, + }) + _, _ = tc.Create(ctx, "default", &types.SandboxWorkloadTemplate{ + Name: "runtime-b", + Labels: map[string]string{"team": "runtime"}, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "python:3.12"}, + }, + }) + + listed, err := tc.List(ctx, "default", types.ListOptions{ + LabelSelector: "team=runtime", + Offset: 1, + Limit: 1, + }) + + require.NoError(t, err) + require.Len(t, listed, 1) + assert.Equal(t, "runtime-b", listed[0].Name) + + listed, err = tc.List(ctx, "default", types.ListOptions{ + LabelSelector: "team=runtime", + Offset: 2, + }) + + require.NoError(t, err) + assert.Empty(t, listed) +} + +func TestSandboxTemplate_CreateSandboxFromTemplateRequiresExistingTemplate(t *testing.T) { + client := NewClient() + ctx := context.Background() + + _, err := client.CreateSandboxFromTemplate(ctx, "default", "job-1", "missing", nil, nil) + + require.Error(t, err) + assert.True(t, types.IsNotFound(err)) +} + +func TestSandboxTemplate_CreateSandboxFromTemplateResolvesWorkloadAndGovernance(t *testing.T) { + client := NewClient() + ctx := context.Background() + gpuCount := uint32(1) + policy := &types.SandboxPolicy{ + Version: 1, + NetworkPolicies: map[string]types.NetworkPolicyRule{ + "api": {Name: "api"}, + }, + } + client.AddSandboxTemplate("default", &types.SandboxWorkloadTemplate{ + Name: "gpu-kata", + ResourceVersion: 7, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Image: "registry.example.com/agent:latest", + Environment: map[string]string{"FEATURE_FLAG": "on"}, + Resources: &types.SandboxResources{ + CPU: "2", + Memory: "4Gi", + GPU: &types.SandboxGPURequirements{Count: &gpuCount}, + }, + }, + DriverConfig: map[string]any{ + "kubernetes": map[string]any{"runtime_class_name": "kata-containers"}, + }, + }, + }) + + created, err := client.CreateSandboxFromTemplate( + ctx, + "default", + "job-1", + "gpu-kata", + &types.SandboxSpec{ + Providers: []string{"github"}, + Policy: policy, + }, + map[string]string{"team": "runtime"}, + ) + + require.NoError(t, err) + assert.Equal(t, "job-1", created.Name) + assert.Equal(t, map[string]string{"team": "runtime"}, created.Labels) + assert.Equal(t, map[string]string{"FEATURE_FLAG": "on"}, created.Spec.Environment) + require.NotNil(t, created.Spec.Template) + assert.Equal(t, "registry.example.com/agent:latest", created.Spec.Template.Image) + assert.Equal(t, map[string]any{"limits": map[string]any{"cpu": "2", "memory": "4Gi"}}, created.Spec.Template.Resources) + assert.Equal(t, "kata-containers", created.Spec.Template.DriverConfig["kubernetes"].(map[string]any)["runtime_class_name"]) + assert.True(t, created.Spec.GPU) + require.NotNil(t, created.Spec.GPUCount) + assert.Equal(t, uint32(1), *created.Spec.GPUCount) + assert.Equal(t, []string{"github"}, created.Spec.Providers) + require.NotNil(t, created.Spec.Policy) + assert.Equal(t, uint32(1), created.Spec.Policy.Version) + require.NotNil(t, created.CreatedFromWorkloadTemplate) + assert.Equal(t, "gpu-kata", created.CreatedFromWorkloadTemplate.Name) + assert.Equal(t, "7", created.CreatedFromWorkloadTemplate.ResourceVersion) +} + +func TestSandboxTemplate_CreateSandboxFromTemplateRejectsWorkloadOverrides(t *testing.T) { + client := NewClient() + ctx := context.Background() + gpuCount := uint32(1) + client.AddSandboxTemplate("default", &types.SandboxWorkloadTemplate{ + Name: "gpu-kata", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "registry.example.com/agent:latest"}, + }, + }) + + tests := map[string]*types.SandboxSpec{ + "log_level": { + LogLevel: "debug", + }, + "environment": { + Environment: map[string]string{"FEATURE_FLAG": "off"}, + }, + "template": { + Template: &types.SandboxTemplate{Image: "registry.example.com/override:latest"}, + }, + "gpu_count": { + GPUCount: &gpuCount, + }, + "gpu": { + GPU: true, + }, + } + + for name, spec := range tests { + t.Run(name, func(t *testing.T) { + _, err := client.CreateSandboxFromTemplate(ctx, "default", "job-"+name, "gpu-kata", spec, nil) + + require.Error(t, err) + assert.True(t, types.IsInvalidArgument(err)) + }) + } + + listed, err := client.Sandboxes().List(ctx, "default") + require.NoError(t, err) + assert.Empty(t, listed) +} + +func TestSandboxTemplate_DefaultGpuRequestRoundTripsTemplate(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + created, err := tc.Create(ctx, "default", &types.SandboxWorkloadTemplate{ + Name: "default-gpu", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Resources: &types.SandboxResources{ + GPU: &types.SandboxGPURequirements{}, + }, + }, + }, + }) + + require.NoError(t, err) + require.NotNil(t, created.Spec.Workload.Resources.GPU) + assert.Nil(t, created.Spec.Workload.Resources.GPU.Count) + + got, err := tc.Get(ctx, "default", "default-gpu") + require.NoError(t, err) + require.NotNil(t, got.Spec.Workload.Resources.GPU) + assert.Nil(t, got.Spec.Workload.Resources.GPU.Count) +} + +func TestSandboxTemplate_CreateSandboxFromTemplatePreservesDefaultGPURequest(t *testing.T) { + client := NewClient() + ctx := context.Background() + + client.AddSandboxTemplate("default", &types.SandboxWorkloadTemplate{ + Name: "default-gpu", + ResourceVersion: 3, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Image: "registry.example.com/agent:latest", + Resources: &types.SandboxResources{ + GPU: &types.SandboxGPURequirements{}, + }, + }, + }, + }) + + created, err := client.CreateSandboxFromTemplate( + ctx, + "default", + "job-default-gpu", + "default-gpu", + nil, + nil, + ) + + require.NoError(t, err) + assert.True(t, created.Spec.GPU) + assert.Nil(t, created.Spec.GPUCount) +} + +func TestSandboxTemplate_DeepCopy(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + template := &types.SandboxWorkloadTemplate{ + Name: "gpu-kata", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Image: "python:3.12", + Environment: map[string]string{"KEY": "value"}, + }, + DriverConfig: map[string]any{"kubernetes": map[string]any{"runtime_class_name": "kata"}}, + }, + } + + created, err := tc.Create(ctx, "default", template) + require.NoError(t, err) + + template.Spec.Workload.Image = "mutated" + template.Spec.Workload.Environment["KEY"] = "mutated" + template.Spec.DriverConfig["kubernetes"].(map[string]any)["runtime_class_name"] = "mutated" + created.Spec.Workload.Image = "mutated-return" + + got, err := tc.Get(ctx, "default", "gpu-kata") + require.NoError(t, err) + assert.Equal(t, "python:3.12", got.Spec.Workload.Image) + assert.Equal(t, "value", got.Spec.Workload.Environment["KEY"]) + assert.Equal(t, "kata", got.Spec.DriverConfig["kubernetes"].(map[string]any)["runtime_class_name"]) +} + +func TestSandboxTemplate_CreateNil(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + + _, err := tc.Create(ctx, "default", nil) + require.Error(t, err) + assert.True(t, types.IsInvalidArgument(err)) +} + +func TestSandboxTemplate_CreateRejectsInvalidTemplate(t *testing.T) { + tc := newTestSandboxTemplateClient() + ctx := context.Background() + zeroGPUCount := uint32(0) + + tests := map[string]*types.SandboxWorkloadTemplate{ + "missing_name": { + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "registry.example.com/agent:latest"}, + }, + }, + "invalid_name": { + Name: "Invalid_Template_Name", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{Image: "registry.example.com/agent:latest"}, + }, + }, + "missing_workload": { + Name: "missing-workload", + }, + "invalid_environment": { + Name: "invalid-env", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Image: "registry.example.com/agent:latest", + Environment: map[string]string{"BAD KEY": "value"}, + }, + }, + }, + "reserved_environment": { + Name: "reserved-env", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Image: "registry.example.com/agent:latest", + Environment: map[string]string{"OPENSHELL_TOKEN": "value"}, + }, + }, + }, + "zero_gpu": { + Name: "zero-gpu", + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Image: "registry.example.com/agent:latest", + Resources: &types.SandboxResources{ + GPU: &types.SandboxGPURequirements{Count: &zeroGPUCount}, + }, + }, + }, + }, + } + + for name, template := range tests { + t.Run(name, func(t *testing.T) { + _, err := tc.Create(ctx, "default", template) + + require.Error(t, err) + assert.True(t, types.IsInvalidArgument(err)) + }) + } + + listed, err := tc.List(ctx, "default") + require.NoError(t, err) + assert.Empty(t, listed) +} + +func TestSandboxTemplate_ClosedReturnsUnavailable(t *testing.T) { + store := newobjectStore(sandboxWorkloadTemplateName, copySandboxWorkloadTemplate) + tc := newFakeSandboxTemplateClient(store, func() bool { return true }) + ctx := context.Background() + + _, err := tc.Create(ctx, "default", &types.SandboxWorkloadTemplate{Name: "gpu-kata"}) + require.Error(t, err) + assert.True(t, types.IsUnavailable(err)) +} diff --git a/sdk/go/openshell/v1/fake/sandbox_test.go b/sdk/go/openshell/v1/fake/sandbox_test.go index b675621891..75ff32da2d 100644 --- a/sdk/go/openshell/v1/fake/sandbox_test.go +++ b/sdk/go/openshell/v1/fake/sandbox_test.go @@ -20,8 +20,9 @@ import ( // helper to build a minimal fake sandbox client for testing. func newTestSandboxClient() *fakeSandboxClient { store := newobjectStore(sandboxName, copySandbox) + templateStore := newobjectStore(sandboxWorkloadTemplateName, copySandboxWorkloadTemplate) broadcaster := newWatchBroadcaster[*types.Sandbox]() - return newFakeSandboxClient(store, broadcaster, func() bool { return false }) + return newFakeSandboxClient(store, templateStore, broadcaster, func() bool { return false }) } // --- T008: Sandbox CRUD tests --- @@ -913,6 +914,41 @@ func TestFakeSandboxCreateWithNilPolicy(t *testing.T) { assert.Nil(t, got.Spec.Policy) } +func TestFakeSandboxCreateFromTemplatePreservesCommandAndTTY(t *testing.T) { + sc := newTestSandboxClient() + ctx := context.Background() + sc.templateStore.Insert("default", &types.SandboxWorkloadTemplate{ + Name: "gpu-kata", + ResourceVersion: 7, + Spec: types.SandboxWorkloadTemplateSpec{ + Workload: &types.SandboxWorkloadConfig{ + Image: "registry.example.com/agent:latest", + }, + }, + }) + spec := &types.SandboxSpec{ + Providers: []string{"github"}, + Command: []string{"/opt/worker", "--serve"}, + TTY: true, + } + + created, err := sc.CreateFromTemplate(ctx, "default", "job-1", "gpu-kata", spec, map[string]string{"team": "runtime"}) + + require.NoError(t, err) + assert.Equal(t, []string{"/opt/worker", "--serve"}, created.Spec.Command) + assert.True(t, created.Spec.TTY) + assert.Equal(t, []string{"github"}, created.Spec.Providers) + require.NotNil(t, created.CreatedFromWorkloadTemplate) + assert.Equal(t, "gpu-kata", created.CreatedFromWorkloadTemplate.Name) + assert.Equal(t, "7", created.CreatedFromWorkloadTemplate.ResourceVersion) + + spec.Command[0] = "mutated" + got, err := sc.Get(ctx, "default", "job-1") + require.NoError(t, err) + assert.Equal(t, []string{"/opt/worker", "--serve"}, got.Spec.Command) + assert.True(t, got.Spec.TTY) +} + // --- T032: GetLogs stub tests --- func TestSandbox_GetLogs_ReturnsUnimplemented(t *testing.T) { @@ -924,8 +960,9 @@ func TestSandbox_GetLogs_ReturnsUnimplemented(t *testing.T) { func TestSandbox_GetLogs_ClosedReturnsUnavailable(t *testing.T) { store := newobjectStore(sandboxName, copySandbox) + templateStore := newobjectStore(sandboxWorkloadTemplateName, copySandboxWorkloadTemplate) broadcaster := newWatchBroadcaster[*types.Sandbox]() - sc := newFakeSandboxClient(store, broadcaster, func() bool { return true }) + sc := newFakeSandboxClient(store, templateStore, broadcaster, func() bool { return true }) _, err := sc.GetLogs(context.Background(), "default", "sb-1") require.Error(t, err) assert.True(t, types.IsUnavailable(err)) diff --git a/sdk/go/openshell/v1/internal/converter/coverage_test.go b/sdk/go/openshell/v1/internal/converter/coverage_test.go index ea9add6d21..ad20aca260 100644 --- a/sdk/go/openshell/v1/internal/converter/coverage_test.go +++ b/sdk/go/openshell/v1/internal/converter/coverage_test.go @@ -52,6 +52,62 @@ func TestConverterCoversAllProtoFields_SandboxTemplate(t *testing.T) { assertAllFieldsCovered(t, (&pb.SandboxTemplate{}).ProtoReflect().Descriptor(), handled, nil) } +func TestConverterCoversAllProtoFields_SandboxWorkloadTemplate(t *testing.T) { + handled := fieldSet{ + "metadata": true, + "spec": true, + } + + assertAllFieldsCovered(t, (&pb.SandboxWorkloadTemplate{}).ProtoReflect().Descriptor(), handled, nil) +} + +func TestConverterCoversAllProtoFields_SandboxWorkloadTemplateSpec(t *testing.T) { + handled := fieldSet{ + "workload": true, + "driver_config": true, + "desired_service_level": true, + } + + assertAllFieldsCovered(t, (&pb.SandboxWorkloadTemplateSpec{}).ProtoReflect().Descriptor(), handled, nil) +} + +func TestConverterCoversAllProtoFields_SandboxWorkloadConfig(t *testing.T) { + handled := fieldSet{ + "image": true, + "environment": true, + "resources": true, + } + + assertAllFieldsCovered(t, (&pb.SandboxWorkloadConfig{}).ProtoReflect().Descriptor(), handled, nil) +} + +func TestConverterCoversAllProtoFields_SandboxResources(t *testing.T) { + handled := fieldSet{ + "cpu": true, + "memory": true, + "gpu": true, + } + + assertAllFieldsCovered(t, (&pb.SandboxResources{}).ProtoReflect().Descriptor(), handled, nil) +} + +func TestConverterCoversAllProtoFields_SandboxServiceLevel(t *testing.T) { + handled := fieldSet{ + "startup": true, + } + + assertAllFieldsCovered(t, (&pb.SandboxServiceLevel{}).ProtoReflect().Descriptor(), handled, nil) +} + +func TestConverterCoversAllProtoFields_SandboxStartup(t *testing.T) { + handled := fieldSet{ + "ready_within": true, + "max_burst": true, + } + + assertAllFieldsCovered(t, (&pb.SandboxStartup{}).ProtoReflect().Descriptor(), handled, nil) +} + func TestConverterCoversAllProtoFields_SandboxStatus(t *testing.T) { handled := fieldSet{ "sandbox_name": true, diff --git a/sdk/go/openshell/v1/internal/converter/sandbox.go b/sdk/go/openshell/v1/internal/converter/sandbox.go index 6b61053295..bf15f11059 100644 --- a/sdk/go/openshell/v1/internal/converter/sandbox.go +++ b/sdk/go/openshell/v1/internal/converter/sandbox.go @@ -5,10 +5,12 @@ package converter import ( "fmt" + "time" "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1" pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1" + "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/structpb" ) @@ -31,6 +33,13 @@ func SandboxFromProto(s *pb.Sandbox) *types.Sandbox { result.DeletionTimestamp = TimeFromMillisPtr(m.GetDeletionTimestampMs()) } + if provenance := s.GetCreatedFromWorkloadTemplate(); provenance != nil { + result.CreatedFromWorkloadTemplate = &types.SandboxWorkloadTemplateProvenance{ + Name: provenance.GetName(), + ResourceVersion: provenance.GetResourceVersion(), + } + } + if spec := s.GetSpec(); spec != nil { result.Spec = sandboxSpecFromProto(spec) } @@ -72,8 +81,11 @@ func sandboxSpecFromProto(spec *pb.SandboxSpec) types.SandboxSpec { } if rr := spec.GetResourceRequirements(); rr != nil { - if gpu := rr.GetGpu(); gpu != nil && gpu.Count != nil { - result.GPUCount = gpu.Count + if gpu := rr.GetGpu(); gpu != nil { + result.GPU = true + if gpu.Count != nil { + result.GPUCount = gpu.Count + } } } result.Command = CopyStringSlice(spec.GetCommand()) @@ -219,7 +231,7 @@ func SandboxSpecToProto(spec *types.SandboxSpec) *pb.SandboxSpec { result.Template = tmpl } - if spec.GPUCount != nil { + if spec.GPU || spec.GPUCount != nil { result.ResourceRequirements = &pb.ResourceRequirements{ Gpu: &pb.GpuResourceRequirements{ Count: spec.GPUCount, @@ -264,3 +276,221 @@ func SandboxSpecToProtoChecked(spec *types.SandboxSpec) (*pb.SandboxSpec, error) } return result, nil } + +// SandboxWorkloadTemplateFromProto converts a reusable template proto to an SDK template. +func SandboxWorkloadTemplateFromProto(t *pb.SandboxWorkloadTemplate) *types.SandboxWorkloadTemplate { + if t == nil { + return nil + } + + result := &types.SandboxWorkloadTemplate{} + if m := t.GetMetadata(); m != nil { + result.ID = m.GetId() + result.Name = m.GetName() + result.CreatedAt = TimeFromMillis(m.GetCreatedAtMs()) + result.Labels = CopyStringMap(m.GetLabels()) + result.Annotations = CopyStringMap(m.GetAnnotations()) + result.ResourceVersion = m.GetResourceVersion() + result.Workspace = m.GetWorkspace() + result.DeletionTimestamp = TimeFromMillisPtr(m.GetDeletionTimestampMs()) + } + if spec := t.GetSpec(); spec != nil { + result.Spec = SandboxWorkloadTemplateSpecFromProto(spec) + } + return result +} + +// SandboxWorkloadTemplateSpecFromProto converts a reusable template spec proto. +func SandboxWorkloadTemplateSpecFromProto(spec *pb.SandboxWorkloadTemplateSpec) types.SandboxWorkloadTemplateSpec { + result := types.SandboxWorkloadTemplateSpec{} + if spec == nil { + return result + } + result.Workload = SandboxWorkloadConfigFromProto(spec.GetWorkload()) + result.DesiredServiceLevel = SandboxServiceLevelFromProto(spec.GetDesiredServiceLevel()) + if dc := spec.GetDriverConfig(); dc != nil { + result.DriverConfig = dc.AsMap() + } + return result +} + +// SandboxWorkloadConfigFromProto converts a portable workload proto. +func SandboxWorkloadConfigFromProto(workload *pb.SandboxWorkloadConfig) *types.SandboxWorkloadConfig { + if workload == nil { + return nil + } + return &types.SandboxWorkloadConfig{ + Image: workload.GetImage(), + Environment: CopyStringMap(workload.GetEnvironment()), + Resources: SandboxResourcesFromProto(workload.GetResources()), + } +} + +// SandboxResourcesFromProto converts portable resource requirements. +func SandboxResourcesFromProto(resources *pb.SandboxResources) *types.SandboxResources { + if resources == nil { + return nil + } + return &types.SandboxResources{ + CPU: resources.GetCpu(), + Memory: resources.GetMemory(), + GPU: sandboxResourceGpuFromProto(resources), + } +} + +// SandboxServiceLevelFromProto converts template service-level hints. +func SandboxServiceLevelFromProto(level *pb.SandboxServiceLevel) *types.SandboxServiceLevel { + if level == nil { + return nil + } + return &types.SandboxServiceLevel{ + Startup: SandboxStartupFromProto(level.GetStartup()), + } +} + +// SandboxStartupFromProto converts startup service-level hints. +func SandboxStartupFromProto(startup *pb.SandboxStartup) *types.SandboxStartup { + if startup == nil { + return nil + } + return &types.SandboxStartup{ + ReadyWithin: durationFromProto(startup.GetReadyWithin()), + MaxBurst: startup.GetMaxBurst(), + } +} + +// SandboxWorkloadTemplateToProto converts an SDK reusable template to proto. +func SandboxWorkloadTemplateToProto(t *types.SandboxWorkloadTemplate) *pb.SandboxWorkloadTemplate { + if t == nil { + return nil + } + return &pb.SandboxWorkloadTemplate{ + Metadata: &dm.ObjectMeta{ + Id: t.ID, + Name: t.Name, + CreatedAtMs: MillisFromTime(t.CreatedAt), + Labels: CopyStringMap(t.Labels), + Annotations: CopyStringMap(t.Annotations), + ResourceVersion: t.ResourceVersion, + Workspace: t.Workspace, + DeletionTimestampMs: MillisFromTimePtr(t.DeletionTimestamp), + }, + Spec: SandboxWorkloadTemplateSpecToProto(&t.Spec), + } +} + +// SandboxWorkloadTemplateSpecToProto converts an SDK reusable template spec to proto. +func SandboxWorkloadTemplateSpecToProto(spec *types.SandboxWorkloadTemplateSpec) *pb.SandboxWorkloadTemplateSpec { + if spec == nil { + return nil + } + result := &pb.SandboxWorkloadTemplateSpec{ + Workload: SandboxWorkloadConfigToProto(spec.Workload), + DesiredServiceLevel: SandboxServiceLevelToProto(spec.DesiredServiceLevel), + } + if spec.DriverConfig != nil { + if driverConfig, err := structpb.NewStruct(spec.DriverConfig); err == nil { + result.DriverConfig = driverConfig + } + } + return result +} + +// SandboxWorkloadConfigToProto converts an SDK portable workload to proto. +func SandboxWorkloadConfigToProto(workload *types.SandboxWorkloadConfig) *pb.SandboxWorkloadConfig { + if workload == nil { + return nil + } + return &pb.SandboxWorkloadConfig{ + Image: workload.Image, + Environment: CopyStringMap(workload.Environment), + Resources: SandboxResourcesToProto(workload.Resources), + } +} + +// SandboxResourcesToProto converts portable resource requirements. +func SandboxResourcesToProto(resources *types.SandboxResources) *pb.SandboxResources { + if resources == nil { + return nil + } + return &pb.SandboxResources{ + Cpu: resources.CPU, + Memory: resources.Memory, + Gpu: sandboxResourceGpuToProto(resources), + } +} + +func sandboxResourceGpuToProto(resources *types.SandboxResources) *pb.GpuResourceRequirements { + if resources == nil || resources.GPU == nil { + return nil + } + return &pb.GpuResourceRequirements{Count: CopyUint32Ptr(resources.GPU.Count)} +} + +func sandboxResourceGpuFromProto(resources *pb.SandboxResources) *types.SandboxGPURequirements { + if resources == nil || resources.GetGpu() == nil { + return nil + } + return &types.SandboxGPURequirements{Count: CopyUint32Ptr(resources.GetGpu().Count)} +} + +// SandboxServiceLevelToProto converts template service-level hints. +func SandboxServiceLevelToProto(level *types.SandboxServiceLevel) *pb.SandboxServiceLevel { + if level == nil { + return nil + } + return &pb.SandboxServiceLevel{ + Startup: SandboxStartupToProto(level.Startup), + } +} + +// SandboxStartupToProto converts startup service-level hints. +func SandboxStartupToProto(startup *types.SandboxStartup) *pb.SandboxStartup { + if startup == nil { + return nil + } + return &pb.SandboxStartup{ + ReadyWithin: durationToProto(startup.ReadyWithin), + MaxBurst: startup.MaxBurst, + } +} + +// SandboxWorkloadTemplateToProtoChecked converts an SDK reusable template and +// reports driver config values that protobuf Struct cannot represent. +func SandboxWorkloadTemplateToProtoChecked(t *types.SandboxWorkloadTemplate) (*pb.SandboxWorkloadTemplate, error) { + result := SandboxWorkloadTemplateToProto(t) + if t == nil { + return result, nil + } + if t.Spec.DriverConfig != nil { + driverConfig, err := structpb.NewStruct(t.Spec.DriverConfig) + if err != nil { + return nil, fmt.Errorf("driver config: %w", err) + } + result.Spec.DriverConfig = driverConfig + } + return result, nil +} + +// CopyUint32Ptr returns a copy of a *uint32 pointer. +func CopyUint32Ptr(p *uint32) *uint32 { + if p == nil { + return nil + } + v := *p + return &v +} + +func durationFromProto(d *durationpb.Duration) time.Duration { + if d == nil { + return 0 + } + return d.AsDuration() +} + +func durationToProto(d time.Duration) *durationpb.Duration { + if d == 0 { + return nil + } + return durationpb.New(d) +} diff --git a/sdk/go/openshell/v1/internal/converter/sandbox_test.go b/sdk/go/openshell/v1/internal/converter/sandbox_test.go index 9f68013845..e1687464b5 100644 --- a/sdk/go/openshell/v1/internal/converter/sandbox_test.go +++ b/sdk/go/openshell/v1/internal/converter/sandbox_test.go @@ -13,6 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" "google.golang.org/protobuf/types/known/structpb" ) @@ -60,6 +61,10 @@ func TestSandboxFromProto(t *testing.T) { Command: []string{"/opt/agent", "--serve"}, Tty: false, }, + CreatedFromWorkloadTemplate: &pb.SandboxWorkloadTemplateProvenance{ + Name: "gpu-kata", + ResourceVersion: "7", + }, Status: &pb.SandboxStatus{ SandboxName: "sb-compute-1", AgentPod: "agent-pod-xyz", @@ -93,11 +98,15 @@ func TestSandboxFromProto(t *testing.T) { assert.Equal(t, "prod", s.Workspace) require.NotNil(t, s.DeletionTimestamp) assert.Equal(t, time.UnixMilli(1700000060000).UTC(), *s.DeletionTimestamp) + require.NotNil(t, s.CreatedFromWorkloadTemplate) + assert.Equal(t, "gpu-kata", s.CreatedFromWorkloadTemplate.Name) + assert.Equal(t, "7", s.CreatedFromWorkloadTemplate.ResourceVersion) // Spec assert.Equal(t, "debug", s.Spec.LogLevel) assert.Equal(t, map[string]string{"FOO": "bar"}, s.Spec.Environment) assert.Equal(t, []string{"claude", "github"}, s.Spec.Providers) + assert.True(t, s.Spec.GPU) require.NotNil(t, s.Spec.GPUCount) assert.Equal(t, uint32(2), *s.Spec.GPUCount) assert.Equal(t, []string{"/opt/agent", "--serve"}, s.Spec.Command) @@ -173,10 +182,27 @@ func TestSandboxFromProto_NilFields(t *testing.T) { assert.Empty(t, s.Name) assert.True(t, s.CreatedAt.IsZero()) assert.Nil(t, s.Spec.Template) + assert.False(t, s.Spec.GPU) assert.Nil(t, s.Spec.GPUCount) assert.Equal(t, v1.SandboxUnknown, s.Status.Phase) } +func TestSandboxFromProto_DefaultGPURequest(t *testing.T) { + proto := &pb.Sandbox{ + Spec: &pb.SandboxSpec{ + ResourceRequirements: &pb.ResourceRequirements{ + Gpu: &pb.GpuResourceRequirements{}, + }, + }, + } + + s := SandboxFromProto(proto) + + require.NotNil(t, s) + assert.True(t, s.Spec.GPU) + assert.Nil(t, s.Spec.GPUCount) +} + func TestSandboxFromProto_Nil(t *testing.T) { s := SandboxFromProto(nil) assert.Nil(t, s) @@ -314,6 +340,137 @@ func TestSandboxToProto_NilTemplate(t *testing.T) { assert.Nil(t, p.Spec.ResourceRequirements) } +func TestSandboxToProto_DefaultGPURequest(t *testing.T) { + s := &v1.Sandbox{ + Spec: v1.SandboxSpec{ + GPU: true, + }, + } + + p := SandboxToProto(s) + + require.NotNil(t, p) + require.NotNil(t, p.Spec) + require.NotNil(t, p.Spec.ResourceRequirements) + require.NotNil(t, p.Spec.ResourceRequirements.Gpu) + assert.Nil(t, p.Spec.ResourceRequirements.Gpu.Count) +} + +func TestSandboxWorkloadTemplateRoundTrip(t *testing.T) { + gpuCount := uint32(2) + delTime := time.UnixMilli(1700000060000).UTC() + original := &v1.SandboxWorkloadTemplate{ + ID: "tmpl-1", + Name: "gpu-kata", + CreatedAt: time.UnixMilli(1700000000000).UTC(), + Labels: map[string]string{"team": "platform"}, + Annotations: map[string]string{"note": "fast-start"}, + ResourceVersion: 9, + Workspace: "prod", + DeletionTimestamp: &delTime, + Spec: v1.SandboxWorkloadTemplateSpec{ + Workload: &v1.SandboxWorkloadConfig{ + Image: "nvcr.io/nvidia/openshell:latest", + Environment: map[string]string{"CUDA_VISIBLE_DEVICES": "all"}, + Resources: &v1.SandboxResources{ + CPU: "2", + Memory: "8Gi", + GPU: &v1.SandboxGPURequirements{Count: &gpuCount}, + }, + }, + DriverConfig: map[string]any{ + "kubernetes": map[string]any{"runtimeClassName": "kata"}, + }, + DesiredServiceLevel: &v1.SandboxServiceLevel{ + Startup: &v1.SandboxStartup{ + ReadyWithin: 30 * time.Second, + MaxBurst: 3, + }, + }, + }, + } + + protoTemplate, err := SandboxWorkloadTemplateToProtoChecked(original) + require.NoError(t, err) + + require.NotNil(t, protoTemplate.Metadata) + assert.Equal(t, "gpu-kata", protoTemplate.Metadata.Name) + require.NotNil(t, protoTemplate.Spec) + require.NotNil(t, protoTemplate.Spec.Workload) + assert.Equal(t, "nvcr.io/nvidia/openshell:latest", protoTemplate.Spec.Workload.Image) + assert.Equal(t, map[string]string{"CUDA_VISIBLE_DEVICES": "all"}, protoTemplate.Spec.Workload.Environment) + require.NotNil(t, protoTemplate.Spec.Workload.Resources) + assert.Equal(t, "2", protoTemplate.Spec.Workload.Resources.Cpu) + assert.Equal(t, "8Gi", protoTemplate.Spec.Workload.Resources.Memory) + require.NotNil(t, protoTemplate.Spec.Workload.Resources.Gpu) + require.NotNil(t, protoTemplate.Spec.Workload.Resources.Gpu.Count) + assert.Equal(t, uint32(2), *protoTemplate.Spec.Workload.Resources.Gpu.Count) + require.NotNil(t, protoTemplate.Spec.DriverConfig) + require.NotNil(t, protoTemplate.Spec.DesiredServiceLevel) + require.NotNil(t, protoTemplate.Spec.DesiredServiceLevel.Startup) + assert.Equal(t, durationpb.New(30*time.Second), protoTemplate.Spec.DesiredServiceLevel.Startup.ReadyWithin) + assert.Equal(t, uint32(3), protoTemplate.Spec.DesiredServiceLevel.Startup.MaxBurst) + + back := SandboxWorkloadTemplateFromProto(protoTemplate) + require.NotNil(t, back) + assert.Equal(t, original.ID, back.ID) + assert.Equal(t, original.Name, back.Name) + assert.Equal(t, original.CreatedAt, back.CreatedAt) + assert.Equal(t, original.Labels, back.Labels) + assert.Equal(t, original.Annotations, back.Annotations) + assert.Equal(t, original.ResourceVersion, back.ResourceVersion) + assert.Equal(t, original.Workspace, back.Workspace) + require.NotNil(t, back.DeletionTimestamp) + assert.Equal(t, *original.DeletionTimestamp, *back.DeletionTimestamp) + require.NotNil(t, back.Spec.Workload) + assert.Equal(t, original.Spec.Workload.Image, back.Spec.Workload.Image) + assert.Equal(t, original.Spec.Workload.Environment, back.Spec.Workload.Environment) + require.NotNil(t, back.Spec.Workload.Resources) + assert.Equal(t, original.Spec.Workload.Resources.CPU, back.Spec.Workload.Resources.CPU) + assert.Equal(t, original.Spec.Workload.Resources.Memory, back.Spec.Workload.Resources.Memory) + require.NotNil(t, back.Spec.Workload.Resources.GPU) + require.NotNil(t, back.Spec.Workload.Resources.GPU.Count) + assert.Equal(t, *original.Spec.Workload.Resources.GPU.Count, *back.Spec.Workload.Resources.GPU.Count) + assert.Equal(t, "kata", back.Spec.DriverConfig["kubernetes"].(map[string]any)["runtimeClassName"]) + require.NotNil(t, back.Spec.DesiredServiceLevel) + require.NotNil(t, back.Spec.DesiredServiceLevel.Startup) + assert.Equal(t, 30*time.Second, back.Spec.DesiredServiceLevel.Startup.ReadyWithin) + assert.Equal(t, uint32(3), back.Spec.DesiredServiceLevel.Startup.MaxBurst) +} + +func TestSandboxWorkloadTemplateRoundTrip_DefaultGpuRequest(t *testing.T) { + original := &v1.SandboxWorkloadTemplate{ + Name: "default-gpu", + Spec: v1.SandboxWorkloadTemplateSpec{ + Workload: &v1.SandboxWorkloadConfig{ + Resources: &v1.SandboxResources{ + GPU: &v1.SandboxGPURequirements{}, + }, + }, + }, + } + + protoTemplate, err := SandboxWorkloadTemplateToProtoChecked(original) + require.NoError(t, err) + require.NotNil(t, protoTemplate.GetSpec().GetWorkload().GetResources().GetGpu()) + assert.Nil(t, protoTemplate.GetSpec().GetWorkload().GetResources().GetGpu().Count) + + back := SandboxWorkloadTemplateFromProto(protoTemplate) + require.NotNil(t, back.Spec.Workload.Resources.GPU) + assert.Nil(t, back.Spec.Workload.Resources.GPU.Count) +} + +func TestSandboxWorkloadTemplateToProtoChecked_RejectsUnrepresentableDriverConfig(t *testing.T) { + _, err := SandboxWorkloadTemplateToProtoChecked(&v1.SandboxWorkloadTemplate{ + Name: "bad", + Spec: v1.SandboxWorkloadTemplateSpec{ + DriverConfig: map[string]any{"invalid": make(chan int)}, + }, + }) + require.Error(t, err) + assert.Contains(t, err.Error(), "driver config") +} + func TestSandboxRoundTrip(t *testing.T) { userNS := false gpuCount := uint32(1) @@ -384,6 +541,7 @@ func TestSandboxRoundTrip(t *testing.T) { assert.Equal(t, original.Spec.LogLevel, back.Spec.LogLevel) assert.Equal(t, original.Spec.Environment, back.Spec.Environment) assert.Equal(t, original.Spec.Providers, back.Spec.Providers) + assert.True(t, back.Spec.GPU) require.NotNil(t, back.Spec.GPUCount) assert.Equal(t, *original.Spec.GPUCount, *back.Spec.GPUCount) require.NotNil(t, back.Spec.Template) diff --git a/sdk/go/openshell/v1/sandbox.go b/sdk/go/openshell/v1/sandbox.go index 871bbb1bf3..79174ac7f3 100644 --- a/sdk/go/openshell/v1/sandbox.go +++ b/sdk/go/openshell/v1/sandbox.go @@ -67,3 +67,9 @@ type SandboxInterface interface { Watch(ctx context.Context, workspace, name string, opts ...WatchOptions) (WatchInterface[*Sandbox], error) GetLogs(ctx context.Context, workspace, sandboxName string, opts ...LogOption) (*LogResult, error) } + +// SandboxTemplateCreateInterface defines additive sandbox creation from named +// workload templates without widening SandboxInterface. +type SandboxTemplateCreateInterface interface { + CreateFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error) +} diff --git a/sdk/go/openshell/v1/sandbox_client.go b/sdk/go/openshell/v1/sandbox_client.go index f31cd40af9..75d8d4caa3 100644 --- a/sdk/go/openshell/v1/sandbox_client.go +++ b/sdk/go/openshell/v1/sandbox_client.go @@ -21,6 +21,9 @@ type sandboxClient struct { client pb.OpenShellClient } +var _ SandboxInterface = (*sandboxClient)(nil) +var _ SandboxTemplateCreateInterface = (*sandboxClient)(nil) + func newSandboxClient(conn grpc.ClientConnInterface) *sandboxClient { return &sandboxClient{client: pb.NewOpenShellClient(conn)} } @@ -46,6 +49,44 @@ func (s *sandboxClient) Create(ctx context.Context, workspace, name string, spec return converter.SandboxFromProto(resp.GetSandbox()), nil } +func (s *sandboxClient) CreateFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error) { + if templateName == "" { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "template name is required"} + } + if err := validateTemplateCreateSpec(spec); err != nil { + return nil, err + } + protoSpec, err := converter.SandboxSpecToProtoChecked(spec) + if err != nil { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: err.Error()} + } + req := &pb.CreateSandboxRequest{ + Name: name, + Spec: protoSpec, + Labels: labels, + Workspace: workspace, + WorkloadTemplateName: templateName, + } + if len(opts) > 0 { + req.Annotations = converter.CopyStringMap(opts[0].Annotations) + } + resp, err := s.client.CreateSandbox(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + return converter.SandboxFromProto(resp.GetSandbox()), nil +} + +func validateTemplateCreateSpec(spec *SandboxSpec) error { + if spec == nil { + return nil + } + if spec.LogLevel != "" || len(spec.Environment) > 0 || spec.Template != nil || spec.GPU || spec.GPUCount != nil { + return &StatusError{Code: ErrorInvalidArgument, Message: "template creates only allow policy, providers, command, and tty in spec"} + } + return nil +} + func (s *sandboxClient) Get(ctx context.Context, workspace, name string) (*Sandbox, error) { resp, err := s.client.GetSandbox(ctx, &pb.GetSandboxRequest{ Name: name, diff --git a/sdk/go/openshell/v1/sandbox_client_test.go b/sdk/go/openshell/v1/sandbox_client_test.go index 91e80db148..7926b28a16 100644 --- a/sdk/go/openshell/v1/sandbox_client_test.go +++ b/sdk/go/openshell/v1/sandbox_client_test.go @@ -34,6 +34,7 @@ type mockSandboxServer struct { attachErr error detachErr error listProvErr error + createRequest *pb.CreateSandboxRequest watchEvents []*pb.SandboxStreamEvent watchErr error watchPostEventsErr error @@ -56,6 +57,7 @@ func newMockSandboxServer() *mockSandboxServer { func (s *mockSandboxServer) CreateSandbox(_ context.Context, req *pb.CreateSandboxRequest) (*pb.SandboxResponse, error) { s.mu.Lock() defer s.mu.Unlock() + s.createRequest = proto.Clone(req).(*pb.CreateSandboxRequest) if s.createErr != nil { return nil, s.createErr } @@ -265,6 +267,29 @@ func TestSandboxCreate(t *testing.T) { assert.Equal(t, SandboxProvisioning, result.Status.Phase) } +func TestSandboxCreate_DefaultGPURequest(t *testing.T) { + mock := newMockSandboxServer() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + result, err := client.Create(context.Background(), "default", "gpu-sandbox", &SandboxSpec{ + GPU: true, + }, nil) + + require.NoError(t, err) + require.NotNil(t, result) + assert.True(t, result.Spec.GPU) + assert.Nil(t, result.Spec.GPUCount) + + mock.mu.Lock() + defer mock.mu.Unlock() + require.NotNil(t, mock.createRequest) + require.NotNil(t, mock.createRequest.Spec) + require.NotNil(t, mock.createRequest.Spec.ResourceRequirements) + require.NotNil(t, mock.createRequest.Spec.ResourceRequirements.Gpu) + assert.Nil(t, mock.createRequest.Spec.ResourceRequirements.Gpu.Count) +} + func TestSandboxCreate_RejectsUnrepresentableResourcesBeforeRPC(t *testing.T) { mock := newMockSandboxServer() client, cleanup := setupSandboxTest(t, mock) @@ -280,6 +305,47 @@ func TestSandboxCreate_RejectsUnrepresentableResourcesBeforeRPC(t *testing.T) { assert.Empty(t, mock.sandboxes) } +func TestSandboxCreateFromTemplateRejectsGPUOverrideBeforeRPC(t *testing.T) { + mock := newMockSandboxServer() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + _, err := client.CreateFromTemplate(context.Background(), "default", "bad", "gpu-kata", &SandboxSpec{ + GPU: true, + }, nil) + + require.Error(t, err) + assert.True(t, IsInvalidArgument(err)) + mock.mu.Lock() + defer mock.mu.Unlock() + assert.Nil(t, mock.createRequest) +} + +func TestSandboxCreateFromTemplateSendsCommandAndTTY(t *testing.T) { + mock := newMockSandboxServer() + client, cleanup := setupSandboxTest(t, mock) + defer cleanup() + + result, err := client.CreateFromTemplate(context.Background(), "default", "job-1", "gpu-kata", &SandboxSpec{ + Providers: []string{"github"}, + Command: []string{"/opt/worker", "--serve"}, + TTY: true, + }, map[string]string{"team": "runtime"}) + + require.NoError(t, err) + require.NotNil(t, result) + assert.Equal(t, []string{"/opt/worker", "--serve"}, result.Spec.Command) + assert.True(t, result.Spec.TTY) + + mock.mu.Lock() + defer mock.mu.Unlock() + require.NotNil(t, mock.createRequest) + assert.Equal(t, "gpu-kata", mock.createRequest.GetWorkloadTemplateName()) + require.NotNil(t, mock.createRequest.GetSpec()) + assert.Equal(t, []string{"/opt/worker", "--serve"}, mock.createRequest.GetSpec().GetCommand()) + assert.True(t, mock.createRequest.GetSpec().GetTty()) +} + func TestSandboxCreate_AlreadyExists(t *testing.T) { mock := newMockSandboxServer() mock.createErr = status.Error(codes.AlreadyExists, "sandbox already exists") diff --git a/sdk/go/openshell/v1/sandbox_template.go b/sdk/go/openshell/v1/sandbox_template.go new file mode 100644 index 0000000000..e2f2d71874 --- /dev/null +++ b/sdk/go/openshell/v1/sandbox_template.go @@ -0,0 +1,45 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types" +) + +// SandboxWorkloadTemplate is a reusable workspace-scoped sandbox template resource. +type SandboxWorkloadTemplate = types.SandboxWorkloadTemplate + +// SandboxWorkloadTemplateSpec holds reusable sandbox template settings. +type SandboxWorkloadTemplateSpec = types.SandboxWorkloadTemplateSpec + +// SandboxWorkloadConfig defines the portable workload for a reusable template. +type SandboxWorkloadConfig = types.SandboxWorkloadConfig + +// SandboxResources defines portable sandbox resource requirements. +type SandboxResources = types.SandboxResources + +// SandboxGPURequirements defines template GPU requirements. +type SandboxGPURequirements = types.SandboxGPURequirements + +// SandboxServiceLevel describes desired operational characteristics. +type SandboxServiceLevel = types.SandboxServiceLevel + +// SandboxStartup describes desired startup characteristics. +type SandboxStartup = types.SandboxStartup + +// SandboxWorkloadTemplateProvenance identifies the reusable template revision used to create a sandbox. +type SandboxWorkloadTemplateProvenance = types.SandboxWorkloadTemplateProvenance + +// SandboxTemplateInterface defines CRUD operations on reusable sandbox templates. +// +// The resource type is named SandboxWorkloadTemplate in the v1 Go SDK so it does +// not collide with the legacy inline SandboxTemplate field on SandboxSpec. +type SandboxTemplateInterface interface { + Create(ctx context.Context, workspace string, template *SandboxWorkloadTemplate) (*SandboxWorkloadTemplate, error) + Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error) + List(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) + Delete(ctx context.Context, workspace, name string) (bool, error) +} diff --git a/sdk/go/openshell/v1/sandbox_template_client.go b/sdk/go/openshell/v1/sandbox_template_client.go new file mode 100644 index 0000000000..de6e19237c --- /dev/null +++ b/sdk/go/openshell/v1/sandbox_template_client.go @@ -0,0 +1,94 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + + "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter" + pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1" + "google.golang.org/grpc" +) + +type sandboxTemplateClient struct { + client pb.OpenShellClient +} + +var _ SandboxTemplateInterface = (*sandboxTemplateClient)(nil) + +func newSandboxTemplateClient(conn grpc.ClientConnInterface) *sandboxTemplateClient { + return &sandboxTemplateClient{client: pb.NewOpenShellClient(conn)} +} + +func (s *sandboxTemplateClient) Create(ctx context.Context, workspace string, template *SandboxWorkloadTemplate) (*SandboxWorkloadTemplate, error) { + if template == nil { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "template must not be nil"} + } + protoTemplate, err := converter.SandboxWorkloadTemplateToProtoChecked(template) + if err != nil { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: err.Error()} + } + resp, err := s.client.CreateSandboxTemplate(ctx, &pb.CreateSandboxTemplateRequest{ + Template: protoTemplate, + Workspace: workspace, + }) + if err != nil { + return nil, converter.FromGRPCError(err) + } + return converter.SandboxWorkloadTemplateFromProto(resp.GetTemplate()), nil +} + +func (s *sandboxTemplateClient) Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error) { + resp, err := s.client.GetSandboxTemplate(ctx, &pb.GetSandboxTemplateRequest{ + Name: name, + Workspace: workspace, + }) + if err != nil { + return nil, converter.FromGRPCError(err) + } + return converter.SandboxWorkloadTemplateFromProto(resp.GetTemplate()), nil +} + +func (s *sandboxTemplateClient) List(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error) { + req := &pb.ListSandboxTemplatesRequest{ + Workspace: workspace, + } + if len(opts) > 0 { + if opts[0].Limit < 0 { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "limit must not be negative"} + } + if opts[0].Offset < 0 { + return nil, &StatusError{Code: ErrorInvalidArgument, Message: "offset must not be negative"} + } + req.Limit = uint32(opts[0].Limit) + req.Offset = uint32(opts[0].Offset) + req.LabelSelector = opts[0].LabelSelector + req.AllWorkspaces = opts[0].AllWorkspaces + if req.AllWorkspaces { + req.Workspace = "" + } + } + + resp, err := s.client.ListSandboxTemplates(ctx, req) + if err != nil { + return nil, converter.FromGRPCError(err) + } + + templates := make([]*SandboxWorkloadTemplate, 0, len(resp.GetTemplates())) + for _, protoTemplate := range resp.GetTemplates() { + templates = append(templates, converter.SandboxWorkloadTemplateFromProto(protoTemplate)) + } + return templates, nil +} + +func (s *sandboxTemplateClient) Delete(ctx context.Context, workspace, name string) (bool, error) { + resp, err := s.client.DeleteSandboxTemplate(ctx, &pb.DeleteSandboxTemplateRequest{ + Name: name, + Workspace: workspace, + }) + if err != nil { + return false, converter.FromGRPCError(err) + } + return resp.GetDeleted(), nil +} diff --git a/sdk/go/openshell/v1/sandbox_template_client_test.go b/sdk/go/openshell/v1/sandbox_template_client_test.go new file mode 100644 index 0000000000..4f9e3058c0 --- /dev/null +++ b/sdk/go/openshell/v1/sandbox_template_client_test.go @@ -0,0 +1,265 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +package v1 + +import ( + "context" + "net" + "sync" + "testing" + "time" + + dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1" + pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/durationpb" +) + +type mockSandboxTemplateServer struct { + pb.UnimplementedOpenShellServer + mu sync.Mutex + + templates map[string]*pb.SandboxWorkloadTemplate + + createRequest *pb.CreateSandboxTemplateRequest + getRequest *pb.GetSandboxTemplateRequest + listRequest *pb.ListSandboxTemplatesRequest + deleteRequest *pb.DeleteSandboxTemplateRequest + + createErr error + getErr error + listErr error + deleteErr error +} + +func newMockSandboxTemplateServer() *mockSandboxTemplateServer { + return &mockSandboxTemplateServer{ + templates: make(map[string]*pb.SandboxWorkloadTemplate), + } +} + +func (s *mockSandboxTemplateServer) CreateSandboxTemplate(_ context.Context, req *pb.CreateSandboxTemplateRequest) (*pb.SandboxTemplateResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.createRequest = proto.Clone(req).(*pb.CreateSandboxTemplateRequest) + if s.createErr != nil { + return nil, s.createErr + } + template := proto.Clone(req.GetTemplate()).(*pb.SandboxWorkloadTemplate) + if template.Metadata == nil { + template.Metadata = &dm.ObjectMeta{} + } + template.Metadata.Workspace = req.GetWorkspace() + template.Metadata.ResourceVersion = 1 + s.templates[template.Metadata.GetName()] = template + return &pb.SandboxTemplateResponse{Template: proto.Clone(template).(*pb.SandboxWorkloadTemplate)}, nil +} + +func (s *mockSandboxTemplateServer) GetSandboxTemplate(_ context.Context, req *pb.GetSandboxTemplateRequest) (*pb.SandboxTemplateResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.getRequest = proto.Clone(req).(*pb.GetSandboxTemplateRequest) + if s.getErr != nil { + return nil, s.getErr + } + template, ok := s.templates[req.GetName()] + if !ok { + return nil, status.Errorf(codes.NotFound, "template %q not found", req.GetName()) + } + return &pb.SandboxTemplateResponse{Template: proto.Clone(template).(*pb.SandboxWorkloadTemplate)}, nil +} + +func (s *mockSandboxTemplateServer) ListSandboxTemplates(_ context.Context, req *pb.ListSandboxTemplatesRequest) (*pb.ListSandboxTemplatesResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.listRequest = proto.Clone(req).(*pb.ListSandboxTemplatesRequest) + if s.listErr != nil { + return nil, s.listErr + } + templates := make([]*pb.SandboxWorkloadTemplate, 0, len(s.templates)) + for _, template := range s.templates { + templates = append(templates, proto.Clone(template).(*pb.SandboxWorkloadTemplate)) + } + return &pb.ListSandboxTemplatesResponse{Templates: templates}, nil +} + +func (s *mockSandboxTemplateServer) DeleteSandboxTemplate(_ context.Context, req *pb.DeleteSandboxTemplateRequest) (*pb.DeleteSandboxTemplateResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.deleteRequest = proto.Clone(req).(*pb.DeleteSandboxTemplateRequest) + if s.deleteErr != nil { + return nil, s.deleteErr + } + delete(s.templates, req.GetName()) + return &pb.DeleteSandboxTemplateResponse{Deleted: true}, nil +} + +func setupSandboxTemplateTest(t *testing.T, mock *mockSandboxTemplateServer) (*sandboxTemplateClient, func()) { + t.Helper() + lis := bufconn.Listen(bufSize) + srv := grpc.NewServer() + pb.RegisterOpenShellServer(srv, mock) + go func() { _ = srv.Serve(lis) }() + + conn, err := grpc.NewClient("passthrough:///bufconn", + grpc.WithContextDialer(func(_ context.Context, _ string) (net.Conn, error) { + return lis.Dial() + }), + grpc.WithTransportCredentials(insecure.NewCredentials()), + ) + require.NoError(t, err) + + return newSandboxTemplateClient(conn), func() { + _ = conn.Close() + srv.Stop() + } +} + +func TestSandboxTemplateCreate(t *testing.T) { + mock := newMockSandboxTemplateServer() + client, cleanup := setupSandboxTemplateTest(t, mock) + defer cleanup() + gpuCount := uint32(1) + + template, err := client.Create(context.Background(), "default", &SandboxWorkloadTemplate{ + Name: "gpu-kata", + Labels: map[string]string{ + "team": "platform", + }, + Spec: SandboxWorkloadTemplateSpec{ + Workload: &SandboxWorkloadConfig{ + Image: "nvcr.io/nvidia/openshell:latest", + Environment: map[string]string{"NVIDIA_VISIBLE_DEVICES": "all"}, + Resources: &SandboxResources{ + CPU: "2", + Memory: "8Gi", + GPU: &SandboxGPURequirements{Count: &gpuCount}, + }, + }, + DriverConfig: map[string]any{ + "kubernetes": map[string]any{"runtimeClassName": "kata"}, + }, + DesiredServiceLevel: &SandboxServiceLevel{ + Startup: &SandboxStartup{ + ReadyWithin: 45 * time.Second, + MaxBurst: 2, + }, + }, + }, + }) + + require.NoError(t, err) + require.NotNil(t, template) + assert.Equal(t, "gpu-kata", template.Name) + assert.Equal(t, "default", template.Workspace) + assert.Equal(t, uint64(1), template.ResourceVersion) + mock.mu.Lock() + defer mock.mu.Unlock() + require.NotNil(t, mock.createRequest) + assert.Equal(t, "default", mock.createRequest.Workspace) + assert.Equal(t, "gpu-kata", mock.createRequest.Template.Metadata.Name) + assert.Equal(t, "2", mock.createRequest.Template.Spec.Workload.Resources.Cpu) + assert.Equal(t, "8Gi", mock.createRequest.Template.Spec.Workload.Resources.Memory) + require.NotNil(t, mock.createRequest.Template.Spec.Workload.Resources.Gpu) + require.NotNil(t, mock.createRequest.Template.Spec.Workload.Resources.Gpu.Count) + assert.Equal(t, uint32(1), *mock.createRequest.Template.Spec.Workload.Resources.Gpu.Count) + assert.Equal(t, durationpb.New(45*time.Second), mock.createRequest.Template.Spec.DesiredServiceLevel.Startup.ReadyWithin) +} + +func TestSandboxTemplateCreate_RejectsNilTemplate(t *testing.T) { + mock := newMockSandboxTemplateServer() + client, cleanup := setupSandboxTemplateTest(t, mock) + defer cleanup() + + _, err := client.Create(context.Background(), "default", nil) + + require.Error(t, err) + assert.True(t, IsInvalidArgument(err)) +} + +func TestSandboxTemplateCreate_RejectsUnrepresentableDriverConfigBeforeRPC(t *testing.T) { + mock := newMockSandboxTemplateServer() + client, cleanup := setupSandboxTemplateTest(t, mock) + defer cleanup() + + _, err := client.Create(context.Background(), "default", &SandboxWorkloadTemplate{ + Name: "bad", + Spec: SandboxWorkloadTemplateSpec{ + DriverConfig: map[string]any{"invalid": make(chan int)}, + }, + }) + + require.Error(t, err) + assert.True(t, IsInvalidArgument(err)) + mock.mu.Lock() + defer mock.mu.Unlock() + assert.Nil(t, mock.createRequest) +} + +func TestSandboxTemplateGetListDelete(t *testing.T) { + mock := newMockSandboxTemplateServer() + mock.templates["gpu-kata"] = &pb.SandboxWorkloadTemplate{ + Metadata: &dm.ObjectMeta{Name: "gpu-kata", Workspace: "default"}, + Spec: &pb.SandboxWorkloadTemplateSpec{ + Workload: &pb.SandboxWorkloadConfig{Image: "img:v1"}, + }, + } + client, cleanup := setupSandboxTemplateTest(t, mock) + defer cleanup() + + got, err := client.Get(context.Background(), "default", "gpu-kata") + require.NoError(t, err) + assert.Equal(t, "gpu-kata", got.Name) + assert.Equal(t, "img:v1", got.Spec.Workload.Image) + + list, err := client.List(context.Background(), "default", ListOptions{ + Limit: 10, + Offset: 2, + LabelSelector: "team=runtime", + AllWorkspaces: true, + }) + require.NoError(t, err) + require.Len(t, list, 1) + assert.Equal(t, "gpu-kata", list[0].Name) + + deleted, err := client.Delete(context.Background(), "default", "gpu-kata") + require.NoError(t, err) + assert.True(t, deleted) + + mock.mu.Lock() + defer mock.mu.Unlock() + require.NotNil(t, mock.getRequest) + assert.Equal(t, "default", mock.getRequest.Workspace) + assert.Equal(t, "gpu-kata", mock.getRequest.Name) + require.NotNil(t, mock.listRequest) + assert.Empty(t, mock.listRequest.Workspace) + assert.Equal(t, uint32(10), mock.listRequest.Limit) + assert.Equal(t, uint32(2), mock.listRequest.Offset) + assert.Equal(t, "team=runtime", mock.listRequest.LabelSelector) + assert.True(t, mock.listRequest.AllWorkspaces) + require.NotNil(t, mock.deleteRequest) + assert.Equal(t, "default", mock.deleteRequest.Workspace) + assert.Equal(t, "gpu-kata", mock.deleteRequest.Name) +} + +func TestSandboxTemplateList_RejectsNegativePagination(t *testing.T) { + mock := newMockSandboxTemplateServer() + client, cleanup := setupSandboxTemplateTest(t, mock) + defer cleanup() + + _, err := client.List(context.Background(), "default", ListOptions{Limit: -1}) + require.Error(t, err) + assert.True(t, IsInvalidArgument(err)) + + _, err = client.List(context.Background(), "default", ListOptions{Offset: -1}) + require.Error(t, err) + assert.True(t, IsInvalidArgument(err)) +} diff --git a/sdk/go/openshell/v1/types/sandbox.go b/sdk/go/openshell/v1/types/sandbox.go index 6ce51d84a1..8be13888ba 100644 --- a/sdk/go/openshell/v1/types/sandbox.go +++ b/sdk/go/openshell/v1/types/sandbox.go @@ -7,16 +7,17 @@ import "time" // Sandbox represents a sandbox instance. type Sandbox struct { - ID string - Name string - CreatedAt time.Time - Labels map[string]string - Annotations map[string]string - ResourceVersion uint64 - Workspace string - DeletionTimestamp *time.Time - Spec SandboxSpec - Status SandboxStatus + ID string + Name string + CreatedAt time.Time + Labels map[string]string + Annotations map[string]string + ResourceVersion uint64 + Workspace string + DeletionTimestamp *time.Time + CreatedFromWorkloadTemplate *SandboxWorkloadTemplateProvenance + Spec SandboxSpec + Status SandboxStatus } // SandboxSpec holds the desired state of a sandbox. @@ -25,7 +26,10 @@ type SandboxSpec struct { Environment map[string]string Template *SandboxTemplate Providers []string - GPUCount *uint32 + // GPU requests GPU resources using the active driver's default GPU assignment + // when GPUCount is nil. GPUCount implies GPU for backward compatibility. + GPU bool + GPUCount *uint32 // Policy is the security policy for the sandbox. Nil means no policy specified. Policy *SandboxPolicy Command []string @@ -45,6 +49,64 @@ type SandboxTemplate struct { DriverConfig map[string]any } +// SandboxWorkloadTemplate is a reusable workspace-scoped sandbox template resource. +type SandboxWorkloadTemplate struct { + ID string + Name string + CreatedAt time.Time + Labels map[string]string + Annotations map[string]string + ResourceVersion uint64 + Workspace string + DeletionTimestamp *time.Time + Spec SandboxWorkloadTemplateSpec +} + +// SandboxWorkloadTemplateSpec holds reusable sandbox template settings. +type SandboxWorkloadTemplateSpec struct { + Workload *SandboxWorkloadConfig + DriverConfig map[string]any + DesiredServiceLevel *SandboxServiceLevel +} + +// SandboxWorkloadConfig defines the portable workload for a reusable template. +type SandboxWorkloadConfig struct { + Image string + Environment map[string]string + Resources *SandboxResources +} + +// SandboxResources defines portable sandbox resource requirements. +type SandboxResources struct { + CPU string + Memory string + // GPU requests GPU resources for template-backed sandboxes. A non-nil GPU + // with nil Count requests the active driver's default GPU assignment. + GPU *SandboxGPURequirements +} + +// SandboxGPURequirements defines template GPU requirements. +type SandboxGPURequirements struct { + Count *uint32 +} + +// SandboxServiceLevel describes desired operational characteristics. +type SandboxServiceLevel struct { + Startup *SandboxStartup +} + +// SandboxStartup describes desired startup characteristics. +type SandboxStartup struct { + ReadyWithin time.Duration + MaxBurst uint32 +} + +// SandboxWorkloadTemplateProvenance identifies the reusable template revision used to create a sandbox. +type SandboxWorkloadTemplateProvenance struct { + Name string + ResourceVersion string +} + // SandboxStatus holds the observed state of a sandbox. type SandboxStatus struct { SandboxName string diff --git a/sdk/go/proto/openshellv1/openshell.pb.go b/sdk/go/proto/openshellv1/openshell.pb.go index 0d2b86fce0..f9e7f39030 100644 --- a/sdk/go/proto/openshellv1/openshell.pb.go +++ b/sdk/go/proto/openshellv1/openshell.pb.go @@ -15,6 +15,7 @@ import ( sandboxv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" + durationpb "google.golang.org/protobuf/types/known/durationpb" structpb "google.golang.org/protobuf/types/known/structpb" reflect "reflect" sync "sync" @@ -1155,9 +1156,11 @@ type Sandbox struct { // Desired sandbox configuration submitted through the API. Spec *SandboxSpec `protobuf:"bytes,2,opt,name=spec,proto3" json:"spec,omitempty"` // Latest user-facing observed status derived by the gateway. - Status *SandboxStatus `protobuf:"bytes,3,opt,name=status,proto3" json:"status,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Status *SandboxStatus `protobuf:"bytes,3,opt,name=status,proto3" json:"status,omitempty"` + // Read-only provenance for sandboxes created from a reusable workload template. + CreatedFromWorkloadTemplate *SandboxWorkloadTemplateProvenance `protobuf:"bytes,20,opt,name=created_from_workload_template,json=createdFromWorkloadTemplate,proto3" json:"created_from_workload_template,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Sandbox) Reset() { @@ -1211,6 +1214,13 @@ func (x *Sandbox) GetStatus() *SandboxStatus { return nil } +func (x *Sandbox) GetCreatedFromWorkloadTemplate() *SandboxWorkloadTemplateProvenance { + if x != nil { + return x.CreatedFromWorkloadTemplate + } + return nil +} + // Desired sandbox configuration provided through the public API. type SandboxSpec struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -1415,7 +1425,12 @@ func (x *GpuResourceRequirements) GetCount() uint32 { return 0 } -// Public sandbox template mapped onto compute-driver template inputs. +// Historical inline compute template mapped onto compute-driver template inputs. +// +// Despite its name, this is not a reusable named sandbox template resource. It +// is an inline part of `SandboxSpec` kept for v1 compatibility. A future +// breaking API cleanup may rename this message to free `SandboxTemplate` for +// the reusable template resource now represented by `SandboxWorkloadTemplate`. type SandboxTemplate struct { state protoimpl.MessageState `protogen:"open.v1"` // Fully-qualified OCI image reference used to boot the sandbox. @@ -1540,50 +1555,36 @@ func (x *SandboxTemplate) GetDriverConfig() *structpb.Struct { return nil } -// User-facing sandbox status derived by the gateway from compute-driver observations. +// Reusable named sandbox workload template resource. // -// Public status does not embed driver-only flags such as `deleting`. -type SandboxStatus struct { +// This is the actual workspace-scoped template resource used to create +// sandboxes by reference. It uses the longer name in v1 to avoid colliding with +// the historical inline `SandboxTemplate` message. A future breaking API +// cleanup may rename this resource to `SandboxTemplate`. +type SandboxWorkloadTemplate struct { state protoimpl.MessageState `protogen:"open.v1"` - // Compute-platform sandbox object name. - SandboxName string `protobuf:"bytes,1,opt,name=sandbox_name,json=sandboxName,proto3" json:"sandbox_name,omitempty"` - // Name of the agent pod or equivalent runtime instance. - AgentPod string `protobuf:"bytes,2,opt,name=agent_pod,json=agentPod,proto3" json:"agent_pod,omitempty"` - // File descriptor or endpoint for reaching the agent service, when available. - AgentFd string `protobuf:"bytes,3,opt,name=agent_fd,json=agentFd,proto3" json:"agent_fd,omitempty"` - // File descriptor or endpoint for reaching the sandbox service, when available. - SandboxFd string `protobuf:"bytes,4,opt,name=sandbox_fd,json=sandboxFd,proto3" json:"sandbox_fd,omitempty"` - // Latest user-facing readiness and lifecycle conditions. - Conditions []*SandboxCondition `protobuf:"bytes,5,rep,name=conditions,proto3" json:"conditions,omitempty"` - // Gateway-derived lifecycle summary. - Phase SandboxPhase `protobuf:"varint,6,opt,name=phase,proto3,enum=openshell.v1.SandboxPhase" json:"phase,omitempty"` - // Currently active policy version (updated when sandbox reports loaded). - CurrentPolicyVersion uint32 `protobuf:"varint,7,opt,name=current_policy_version,json=currentPolicyVersion,proto3" json:"current_policy_version,omitempty"` - // Supervisor instance currently associated with the canonical main process. - // The gateway uses this to reject stale exit reports after a restart. - MainProcessInstanceId string `protobuf:"bytes,8,opt,name=main_process_instance_id,json=mainProcessInstanceId,proto3" json:"main_process_instance_id,omitempty"` - // Normalized main process result. Signal exits use 128 + signal number. - // Presence indicates that the canonical main process exited. Exit code 0 - // produces Completed; nonzero and signal-normalized exits produce Error. - ExitCode *int32 `protobuf:"varint,9,opt,name=exit_code,json=exitCode,proto3,oneof" json:"exit_code,omitempty"` + // Kubernetes-style metadata (id, name, labels, timestamps, resource version). + Metadata *datamodelv1.ObjectMeta `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` + // Desired reusable workload shape and template-owned driver config. + Spec *SandboxWorkloadTemplateSpec `protobuf:"bytes,2,opt,name=spec,proto3" json:"spec,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *SandboxStatus) Reset() { - *x = SandboxStatus{} +func (x *SandboxWorkloadTemplate) Reset() { + *x = SandboxWorkloadTemplate{} mi := &file_openshell_proto_msgTypes[17] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *SandboxStatus) String() string { +func (x *SandboxWorkloadTemplate) String() string { return protoimpl.X.MessageStringOf(x) } -func (*SandboxStatus) ProtoMessage() {} +func (*SandboxWorkloadTemplate) ProtoMessage() {} -func (x *SandboxStatus) ProtoReflect() protoreflect.Message { +func (x *SandboxWorkloadTemplate) ProtoReflect() protoreflect.Message { mi := &file_openshell_proto_msgTypes[17] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -1595,106 +1596,115 @@ func (x *SandboxStatus) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use SandboxStatus.ProtoReflect.Descriptor instead. -func (*SandboxStatus) Descriptor() ([]byte, []int) { +// Deprecated: Use SandboxWorkloadTemplate.ProtoReflect.Descriptor instead. +func (*SandboxWorkloadTemplate) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{17} } -func (x *SandboxStatus) GetSandboxName() string { +func (x *SandboxWorkloadTemplate) GetMetadata() *datamodelv1.ObjectMeta { if x != nil { - return x.SandboxName + return x.Metadata } - return "" + return nil } -func (x *SandboxStatus) GetAgentPod() string { +func (x *SandboxWorkloadTemplate) GetSpec() *SandboxWorkloadTemplateSpec { if x != nil { - return x.AgentPod + return x.Spec } - return "" + return nil } -func (x *SandboxStatus) GetAgentFd() string { - if x != nil { - return x.AgentFd - } - return "" +type SandboxWorkloadTemplateSpec struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Portable workload shape. + Workload *SandboxWorkloadConfig `protobuf:"bytes,1,opt,name=workload,proto3" json:"workload,omitempty"` + // Driver-keyed opaque config envelope supplied by the template owner. + DriverConfig *structpb.Struct `protobuf:"bytes,2,opt,name=driver_config,json=driverConfig,proto3" json:"driver_config,omitempty"` + // Desired service level associated with this template. + DesiredServiceLevel *SandboxServiceLevel `protobuf:"bytes,3,opt,name=desired_service_level,json=desiredServiceLevel,proto3" json:"desired_service_level,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SandboxWorkloadTemplateSpec) Reset() { + *x = SandboxWorkloadTemplateSpec{} + mi := &file_openshell_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) } -func (x *SandboxStatus) GetSandboxFd() string { - if x != nil { - return x.SandboxFd - } - return "" +func (x *SandboxWorkloadTemplateSpec) String() string { + return protoimpl.X.MessageStringOf(x) } -func (x *SandboxStatus) GetConditions() []*SandboxCondition { +func (*SandboxWorkloadTemplateSpec) ProtoMessage() {} + +func (x *SandboxWorkloadTemplateSpec) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[18] if x != nil { - return x.Conditions + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms } - return nil + return mi.MessageOf(x) } -func (x *SandboxStatus) GetPhase() SandboxPhase { - if x != nil { - return x.Phase - } - return SandboxPhase_SANDBOX_PHASE_UNSPECIFIED +// Deprecated: Use SandboxWorkloadTemplateSpec.ProtoReflect.Descriptor instead. +func (*SandboxWorkloadTemplateSpec) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{18} } -func (x *SandboxStatus) GetCurrentPolicyVersion() uint32 { +func (x *SandboxWorkloadTemplateSpec) GetWorkload() *SandboxWorkloadConfig { if x != nil { - return x.CurrentPolicyVersion + return x.Workload } - return 0 + return nil } -func (x *SandboxStatus) GetMainProcessInstanceId() string { +func (x *SandboxWorkloadTemplateSpec) GetDriverConfig() *structpb.Struct { if x != nil { - return x.MainProcessInstanceId + return x.DriverConfig } - return "" + return nil } -func (x *SandboxStatus) GetExitCode() int32 { - if x != nil && x.ExitCode != nil { - return *x.ExitCode +func (x *SandboxWorkloadTemplateSpec) GetDesiredServiceLevel() *SandboxServiceLevel { + if x != nil { + return x.DesiredServiceLevel } - return 0 + return nil } -// User-facing sandbox condition derived from driver-native conditions. -type SandboxCondition struct { +type SandboxWorkloadConfig struct { state protoimpl.MessageState `protogen:"open.v1"` - // Condition class, typically mirroring the underlying platform condition type. - Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` - // Condition status value such as `True`, `False`, or `Unknown`. - Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` - // Short machine-readable reason associated with the condition. - Reason string `protobuf:"bytes,3,opt,name=reason,proto3" json:"reason,omitempty"` - // Human-readable condition message. - Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` - // Timestamp reported by the underlying platform for the last transition. - LastTransitionTime string `protobuf:"bytes,5,opt,name=last_transition_time,json=lastTransitionTime,proto3" json:"last_transition_time,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Fully-qualified OCI image reference used to boot the sandbox. + Image string `protobuf:"bytes,1,opt,name=image,proto3" json:"image,omitempty"` + // Environment variables injected into the sandbox runtime. + Environment map[string]string `protobuf:"bytes,2,rep,name=environment,proto3" json:"environment,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Portable resource requirements for sandboxes created from this workload. + Resources *SandboxResources `protobuf:"bytes,3,opt,name=resources,proto3" json:"resources,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *SandboxCondition) Reset() { - *x = SandboxCondition{} - mi := &file_openshell_proto_msgTypes[18] +func (x *SandboxWorkloadConfig) Reset() { + *x = SandboxWorkloadConfig{} + mi := &file_openshell_proto_msgTypes[19] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *SandboxCondition) String() string { +func (x *SandboxWorkloadConfig) String() string { return protoimpl.X.MessageStringOf(x) } -func (*SandboxCondition) ProtoMessage() {} +func (*SandboxWorkloadConfig) ProtoMessage() {} -func (x *SandboxCondition) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[18] +func (x *SandboxWorkloadConfig) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[19] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1705,80 +1715,61 @@ func (x *SandboxCondition) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use SandboxCondition.ProtoReflect.Descriptor instead. -func (*SandboxCondition) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{18} -} - -func (x *SandboxCondition) GetType() string { - if x != nil { - return x.Type - } - return "" -} - -func (x *SandboxCondition) GetStatus() string { - if x != nil { - return x.Status - } - return "" +// Deprecated: Use SandboxWorkloadConfig.ProtoReflect.Descriptor instead. +func (*SandboxWorkloadConfig) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{19} } -func (x *SandboxCondition) GetReason() string { +func (x *SandboxWorkloadConfig) GetImage() string { if x != nil { - return x.Reason + return x.Image } return "" } -func (x *SandboxCondition) GetMessage() string { +func (x *SandboxWorkloadConfig) GetEnvironment() map[string]string { if x != nil { - return x.Message + return x.Environment } - return "" + return nil } -func (x *SandboxCondition) GetLastTransitionTime() string { +func (x *SandboxWorkloadConfig) GetResources() *SandboxResources { if x != nil { - return x.LastTransitionTime + return x.Resources } - return "" + return nil } -// Public platform event exposed on the sandbox watch stream. -type PlatformEvent struct { +type SandboxResources struct { state protoimpl.MessageState `protogen:"open.v1"` - // Event timestamp in milliseconds since epoch. - TimestampMs int64 `protobuf:"varint,1,opt,name=timestamp_ms,json=timestampMs,proto3" json:"timestamp_ms,omitempty"` - // Event source (e.g. "kubernetes", "docker", "process"). - Source string `protobuf:"bytes,2,opt,name=source,proto3" json:"source,omitempty"` - // Event type/severity (e.g. "Normal", "Warning"). - Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` - // Short reason code (e.g. "Started", "Pulled", "Failed"). - Reason string `protobuf:"bytes,4,opt,name=reason,proto3" json:"reason,omitempty"` - // Human-readable event message. - Message string `protobuf:"bytes,5,opt,name=message,proto3" json:"message,omitempty"` - // Optional metadata as key-value pairs. - Metadata map[string]string `protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Portable CPU quantity, for example "500m" or "2". + Cpu string `protobuf:"bytes,1,opt,name=cpu,proto3" json:"cpu,omitempty"` + // Portable memory quantity, for example "512Mi" or "2Gi". + Memory string `protobuf:"bytes,2,opt,name=memory,proto3" json:"memory,omitempty"` + // GPU requirements for the sandbox workload. Presence indicates a GPU + // request. When count is omitted, the request uses the selected driver's + // default GPU assignment behavior. + Gpu *GpuResourceRequirements `protobuf:"bytes,3,opt,name=gpu,proto3" json:"gpu,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *PlatformEvent) Reset() { - *x = PlatformEvent{} - mi := &file_openshell_proto_msgTypes[19] +func (x *SandboxResources) Reset() { + *x = SandboxResources{} + mi := &file_openshell_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *PlatformEvent) String() string { +func (x *SandboxResources) String() string { return protoimpl.X.MessageStringOf(x) } -func (*PlatformEvent) ProtoMessage() {} +func (*SandboxResources) ProtoMessage() {} -func (x *PlatformEvent) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[19] +func (x *SandboxResources) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1789,88 +1780,54 @@ func (x *PlatformEvent) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use PlatformEvent.ProtoReflect.Descriptor instead. -func (*PlatformEvent) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{19} -} - -func (x *PlatformEvent) GetTimestampMs() int64 { - if x != nil { - return x.TimestampMs - } - return 0 -} - -func (x *PlatformEvent) GetSource() string { - if x != nil { - return x.Source - } - return "" -} - -func (x *PlatformEvent) GetType() string { - if x != nil { - return x.Type - } - return "" +// Deprecated: Use SandboxResources.ProtoReflect.Descriptor instead. +func (*SandboxResources) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{20} } -func (x *PlatformEvent) GetReason() string { +func (x *SandboxResources) GetCpu() string { if x != nil { - return x.Reason + return x.Cpu } return "" } -func (x *PlatformEvent) GetMessage() string { +func (x *SandboxResources) GetMemory() string { if x != nil { - return x.Message + return x.Memory } return "" } -func (x *PlatformEvent) GetMetadata() map[string]string { +func (x *SandboxResources) GetGpu() *GpuResourceRequirements { if x != nil { - return x.Metadata + return x.Gpu } return nil } -// Create sandbox request. -type CreateSandboxRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - Spec *SandboxSpec `protobuf:"bytes,1,opt,name=spec,proto3" json:"spec,omitempty"` - // Optional user-supplied sandbox name. When empty the server generates one. - Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` - // Optional labels for the sandbox (key-value metadata). - Labels map[string]string `protobuf:"bytes,3,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - // Optional annotations for the sandbox (non-selector metadata). - Annotations map[string]string `protobuf:"bytes,4,rep,name=annotations,proto3" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` - // Workspace for the sandbox. Empty defaults to "default". - Workspace string `protobuf:"bytes,5,opt,name=workspace,proto3" json:"workspace,omitempty"` - // One-shot launch hint indicating that the creating client will attach to - // the canonical main process. The supervisor keeps the terminal transport - // alive until that attachment connects and closes naturally. - AwaitMainProcessAttachment bool `protobuf:"varint,6,opt,name=await_main_process_attachment,json=awaitMainProcessAttachment,proto3" json:"await_main_process_attachment,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache +type SandboxServiceLevel struct { + state protoimpl.MessageState `protogen:"open.v1"` + Startup *SandboxStartup `protobuf:"bytes,1,opt,name=startup,proto3" json:"startup,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *CreateSandboxRequest) Reset() { - *x = CreateSandboxRequest{} - mi := &file_openshell_proto_msgTypes[20] +func (x *SandboxServiceLevel) Reset() { + *x = SandboxServiceLevel{} + mi := &file_openshell_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *CreateSandboxRequest) String() string { +func (x *SandboxServiceLevel) String() string { return protoimpl.X.MessageStringOf(x) } -func (*CreateSandboxRequest) ProtoMessage() {} +func (*SandboxServiceLevel) ProtoMessage() {} -func (x *CreateSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[20] +func (x *SandboxServiceLevel) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1881,49 +1838,885 @@ func (x *CreateSandboxRequest) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use CreateSandboxRequest.ProtoReflect.Descriptor instead. -func (*CreateSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{20} +// Deprecated: Use SandboxServiceLevel.ProtoReflect.Descriptor instead. +func (*SandboxServiceLevel) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{21} } -func (x *CreateSandboxRequest) GetSpec() *SandboxSpec { +func (x *SandboxServiceLevel) GetStartup() *SandboxStartup { if x != nil { - return x.Spec + return x.Startup } return nil } -func (x *CreateSandboxRequest) GetName() string { - if x != nil { - return x.Name - } - return "" +type SandboxStartup struct { + state protoimpl.MessageState `protogen:"open.v1"` + ReadyWithin *durationpb.Duration `protobuf:"bytes,1,opt,name=ready_within,json=readyWithin,proto3" json:"ready_within,omitempty"` + MaxBurst uint32 `protobuf:"varint,2,opt,name=max_burst,json=maxBurst,proto3" json:"max_burst,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } -func (x *CreateSandboxRequest) GetLabels() map[string]string { - if x != nil { +func (x *SandboxStartup) Reset() { + *x = SandboxStartup{} + mi := &file_openshell_proto_msgTypes[22] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SandboxStartup) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SandboxStartup) ProtoMessage() {} + +func (x *SandboxStartup) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[22] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SandboxStartup.ProtoReflect.Descriptor instead. +func (*SandboxStartup) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{22} +} + +func (x *SandboxStartup) GetReadyWithin() *durationpb.Duration { + if x != nil { + return x.ReadyWithin + } + return nil +} + +func (x *SandboxStartup) GetMaxBurst() uint32 { + if x != nil { + return x.MaxBurst + } + return 0 +} + +type SandboxWorkloadTemplateProvenance struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + ResourceVersion string `protobuf:"bytes,2,opt,name=resource_version,json=resourceVersion,proto3" json:"resource_version,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SandboxWorkloadTemplateProvenance) Reset() { + *x = SandboxWorkloadTemplateProvenance{} + mi := &file_openshell_proto_msgTypes[23] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SandboxWorkloadTemplateProvenance) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SandboxWorkloadTemplateProvenance) ProtoMessage() {} + +func (x *SandboxWorkloadTemplateProvenance) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[23] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SandboxWorkloadTemplateProvenance.ProtoReflect.Descriptor instead. +func (*SandboxWorkloadTemplateProvenance) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{23} +} + +func (x *SandboxWorkloadTemplateProvenance) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *SandboxWorkloadTemplateProvenance) GetResourceVersion() string { + if x != nil { + return x.ResourceVersion + } + return "" +} + +// User-facing sandbox status derived by the gateway from compute-driver observations. +// +// Public status does not embed driver-only flags such as `deleting`. +type SandboxStatus struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Compute-platform sandbox object name. + SandboxName string `protobuf:"bytes,1,opt,name=sandbox_name,json=sandboxName,proto3" json:"sandbox_name,omitempty"` + // Name of the agent pod or equivalent runtime instance. + AgentPod string `protobuf:"bytes,2,opt,name=agent_pod,json=agentPod,proto3" json:"agent_pod,omitempty"` + // File descriptor or endpoint for reaching the agent service, when available. + AgentFd string `protobuf:"bytes,3,opt,name=agent_fd,json=agentFd,proto3" json:"agent_fd,omitempty"` + // File descriptor or endpoint for reaching the sandbox service, when available. + SandboxFd string `protobuf:"bytes,4,opt,name=sandbox_fd,json=sandboxFd,proto3" json:"sandbox_fd,omitempty"` + // Latest user-facing readiness and lifecycle conditions. + Conditions []*SandboxCondition `protobuf:"bytes,5,rep,name=conditions,proto3" json:"conditions,omitempty"` + // Gateway-derived lifecycle summary. + Phase SandboxPhase `protobuf:"varint,6,opt,name=phase,proto3,enum=openshell.v1.SandboxPhase" json:"phase,omitempty"` + // Currently active policy version (updated when sandbox reports loaded). + CurrentPolicyVersion uint32 `protobuf:"varint,7,opt,name=current_policy_version,json=currentPolicyVersion,proto3" json:"current_policy_version,omitempty"` + // Supervisor instance currently associated with the canonical main process. + // The gateway uses this to reject stale exit reports after a restart. + MainProcessInstanceId string `protobuf:"bytes,8,opt,name=main_process_instance_id,json=mainProcessInstanceId,proto3" json:"main_process_instance_id,omitempty"` + // Normalized main process result. Signal exits use 128 + signal number. + // Presence indicates that the canonical main process exited. Exit code 0 + // produces Completed; nonzero and signal-normalized exits produce Error. + ExitCode *int32 `protobuf:"varint,9,opt,name=exit_code,json=exitCode,proto3,oneof" json:"exit_code,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SandboxStatus) Reset() { + *x = SandboxStatus{} + mi := &file_openshell_proto_msgTypes[24] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SandboxStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SandboxStatus) ProtoMessage() {} + +func (x *SandboxStatus) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[24] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SandboxStatus.ProtoReflect.Descriptor instead. +func (*SandboxStatus) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{24} +} + +func (x *SandboxStatus) GetSandboxName() string { + if x != nil { + return x.SandboxName + } + return "" +} + +func (x *SandboxStatus) GetAgentPod() string { + if x != nil { + return x.AgentPod + } + return "" +} + +func (x *SandboxStatus) GetAgentFd() string { + if x != nil { + return x.AgentFd + } + return "" +} + +func (x *SandboxStatus) GetSandboxFd() string { + if x != nil { + return x.SandboxFd + } + return "" +} + +func (x *SandboxStatus) GetConditions() []*SandboxCondition { + if x != nil { + return x.Conditions + } + return nil +} + +func (x *SandboxStatus) GetPhase() SandboxPhase { + if x != nil { + return x.Phase + } + return SandboxPhase_SANDBOX_PHASE_UNSPECIFIED +} + +func (x *SandboxStatus) GetCurrentPolicyVersion() uint32 { + if x != nil { + return x.CurrentPolicyVersion + } + return 0 +} + +func (x *SandboxStatus) GetMainProcessInstanceId() string { + if x != nil { + return x.MainProcessInstanceId + } + return "" +} + +func (x *SandboxStatus) GetExitCode() int32 { + if x != nil && x.ExitCode != nil { + return *x.ExitCode + } + return 0 +} + +// User-facing sandbox condition derived from driver-native conditions. +type SandboxCondition struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Condition class, typically mirroring the underlying platform condition type. + Type string `protobuf:"bytes,1,opt,name=type,proto3" json:"type,omitempty"` + // Condition status value such as `True`, `False`, or `Unknown`. + Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` + // Short machine-readable reason associated with the condition. + Reason string `protobuf:"bytes,3,opt,name=reason,proto3" json:"reason,omitempty"` + // Human-readable condition message. + Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` + // Timestamp reported by the underlying platform for the last transition. + LastTransitionTime string `protobuf:"bytes,5,opt,name=last_transition_time,json=lastTransitionTime,proto3" json:"last_transition_time,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SandboxCondition) Reset() { + *x = SandboxCondition{} + mi := &file_openshell_proto_msgTypes[25] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SandboxCondition) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SandboxCondition) ProtoMessage() {} + +func (x *SandboxCondition) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[25] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SandboxCondition.ProtoReflect.Descriptor instead. +func (*SandboxCondition) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{25} +} + +func (x *SandboxCondition) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *SandboxCondition) GetStatus() string { + if x != nil { + return x.Status + } + return "" +} + +func (x *SandboxCondition) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *SandboxCondition) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +func (x *SandboxCondition) GetLastTransitionTime() string { + if x != nil { + return x.LastTransitionTime + } + return "" +} + +// Public platform event exposed on the sandbox watch stream. +type PlatformEvent struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Event timestamp in milliseconds since epoch. + TimestampMs int64 `protobuf:"varint,1,opt,name=timestamp_ms,json=timestampMs,proto3" json:"timestamp_ms,omitempty"` + // Event source (e.g. "kubernetes", "docker", "process"). + Source string `protobuf:"bytes,2,opt,name=source,proto3" json:"source,omitempty"` + // Event type/severity (e.g. "Normal", "Warning"). + Type string `protobuf:"bytes,3,opt,name=type,proto3" json:"type,omitempty"` + // Short reason code (e.g. "Started", "Pulled", "Failed"). + Reason string `protobuf:"bytes,4,opt,name=reason,proto3" json:"reason,omitempty"` + // Human-readable event message. + Message string `protobuf:"bytes,5,opt,name=message,proto3" json:"message,omitempty"` + // Optional metadata as key-value pairs. + Metadata map[string]string `protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *PlatformEvent) Reset() { + *x = PlatformEvent{} + mi := &file_openshell_proto_msgTypes[26] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *PlatformEvent) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*PlatformEvent) ProtoMessage() {} + +func (x *PlatformEvent) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[26] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use PlatformEvent.ProtoReflect.Descriptor instead. +func (*PlatformEvent) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{26} +} + +func (x *PlatformEvent) GetTimestampMs() int64 { + if x != nil { + return x.TimestampMs + } + return 0 +} + +func (x *PlatformEvent) GetSource() string { + if x != nil { + return x.Source + } + return "" +} + +func (x *PlatformEvent) GetType() string { + if x != nil { + return x.Type + } + return "" +} + +func (x *PlatformEvent) GetReason() string { + if x != nil { + return x.Reason + } + return "" +} + +func (x *PlatformEvent) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +func (x *PlatformEvent) GetMetadata() map[string]string { + if x != nil { + return x.Metadata + } + return nil +} + +// Create sandbox request. +type CreateSandboxRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Spec *SandboxSpec `protobuf:"bytes,1,opt,name=spec,proto3" json:"spec,omitempty"` + // Optional user-supplied sandbox name. When empty the server generates one. + Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` + // Optional labels for the sandbox (key-value metadata). + Labels map[string]string `protobuf:"bytes,3,rep,name=labels,proto3" json:"labels,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Optional annotations for the sandbox (non-selector metadata). + Annotations map[string]string `protobuf:"bytes,4,rep,name=annotations,proto3" json:"annotations,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + // Workspace for the sandbox. Empty defaults to "default". + Workspace string `protobuf:"bytes,5,opt,name=workspace,proto3" json:"workspace,omitempty"` + // One-shot launch hint indicating that the creating client will attach to + // the canonical main process. The supervisor keeps the terminal transport + // alive until that attachment connects and closes naturally. + AwaitMainProcessAttachment bool `protobuf:"varint,6,opt,name=await_main_process_attachment,json=awaitMainProcessAttachment,proto3" json:"await_main_process_attachment,omitempty"` + // Workspace-scoped SandboxWorkloadTemplate name to resolve at creation time. + WorkloadTemplateName string `protobuf:"bytes,7,opt,name=workload_template_name,json=workloadTemplateName,proto3" json:"workload_template_name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CreateSandboxRequest) Reset() { + *x = CreateSandboxRequest{} + mi := &file_openshell_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateSandboxRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateSandboxRequest) ProtoMessage() {} + +func (x *CreateSandboxRequest) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[27] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateSandboxRequest.ProtoReflect.Descriptor instead. +func (*CreateSandboxRequest) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{27} +} + +func (x *CreateSandboxRequest) GetSpec() *SandboxSpec { + if x != nil { + return x.Spec + } + return nil +} + +func (x *CreateSandboxRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *CreateSandboxRequest) GetLabels() map[string]string { + if x != nil { return x.Labels } return nil } -func (x *CreateSandboxRequest) GetAnnotations() map[string]string { +func (x *CreateSandboxRequest) GetAnnotations() map[string]string { + if x != nil { + return x.Annotations + } + return nil +} + +func (x *CreateSandboxRequest) GetWorkspace() string { + if x != nil { + return x.Workspace + } + return "" +} + +func (x *CreateSandboxRequest) GetAwaitMainProcessAttachment() bool { + if x != nil { + return x.AwaitMainProcessAttachment + } + return false +} + +func (x *CreateSandboxRequest) GetWorkloadTemplateName() string { + if x != nil { + return x.WorkloadTemplateName + } + return "" +} + +type CreateSandboxTemplateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Template *SandboxWorkloadTemplate `protobuf:"bytes,1,opt,name=template,proto3" json:"template,omitempty"` + // Workspace for the template. Empty defaults to "default". + Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CreateSandboxTemplateRequest) Reset() { + *x = CreateSandboxTemplateRequest{} + mi := &file_openshell_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateSandboxTemplateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateSandboxTemplateRequest) ProtoMessage() {} + +func (x *CreateSandboxTemplateRequest) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[28] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateSandboxTemplateRequest.ProtoReflect.Descriptor instead. +func (*CreateSandboxTemplateRequest) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{28} +} + +func (x *CreateSandboxTemplateRequest) GetTemplate() *SandboxWorkloadTemplate { + if x != nil { + return x.Template + } + return nil +} + +func (x *CreateSandboxTemplateRequest) GetWorkspace() string { + if x != nil { + return x.Workspace + } + return "" +} + +type GetSandboxTemplateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // Workspace scope. Empty defaults to "default". + Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetSandboxTemplateRequest) Reset() { + *x = GetSandboxTemplateRequest{} + mi := &file_openshell_proto_msgTypes[29] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetSandboxTemplateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetSandboxTemplateRequest) ProtoMessage() {} + +func (x *GetSandboxTemplateRequest) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[29] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetSandboxTemplateRequest.ProtoReflect.Descriptor instead. +func (*GetSandboxTemplateRequest) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{29} +} + +func (x *GetSandboxTemplateRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *GetSandboxTemplateRequest) GetWorkspace() string { + if x != nil { + return x.Workspace + } + return "" +} + +type ListSandboxTemplatesRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Limit uint32 `protobuf:"varint,1,opt,name=limit,proto3" json:"limit,omitempty"` + Offset uint32 `protobuf:"varint,2,opt,name=offset,proto3" json:"offset,omitempty"` + // Workspace scope. Empty defaults to "default". + Workspace string `protobuf:"bytes,3,opt,name=workspace,proto3" json:"workspace,omitempty"` + // List across all workspaces. Mutually exclusive with workspace. + AllWorkspaces bool `protobuf:"varint,4,opt,name=all_workspaces,json=allWorkspaces,proto3" json:"all_workspaces,omitempty"` + // Optional label selector in key=value comma-separated form. + LabelSelector string `protobuf:"bytes,5,opt,name=label_selector,json=labelSelector,proto3" json:"label_selector,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListSandboxTemplatesRequest) Reset() { + *x = ListSandboxTemplatesRequest{} + mi := &file_openshell_proto_msgTypes[30] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListSandboxTemplatesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListSandboxTemplatesRequest) ProtoMessage() {} + +func (x *ListSandboxTemplatesRequest) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[30] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListSandboxTemplatesRequest.ProtoReflect.Descriptor instead. +func (*ListSandboxTemplatesRequest) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{30} +} + +func (x *ListSandboxTemplatesRequest) GetLimit() uint32 { + if x != nil { + return x.Limit + } + return 0 +} + +func (x *ListSandboxTemplatesRequest) GetOffset() uint32 { + if x != nil { + return x.Offset + } + return 0 +} + +func (x *ListSandboxTemplatesRequest) GetWorkspace() string { + if x != nil { + return x.Workspace + } + return "" +} + +func (x *ListSandboxTemplatesRequest) GetAllWorkspaces() bool { + if x != nil { + return x.AllWorkspaces + } + return false +} + +func (x *ListSandboxTemplatesRequest) GetLabelSelector() string { + if x != nil { + return x.LabelSelector + } + return "" +} + +type DeleteSandboxTemplateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // Workspace scope. Empty defaults to "default". + Workspace string `protobuf:"bytes,2,opt,name=workspace,proto3" json:"workspace,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteSandboxTemplateRequest) Reset() { + *x = DeleteSandboxTemplateRequest{} + mi := &file_openshell_proto_msgTypes[31] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteSandboxTemplateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteSandboxTemplateRequest) ProtoMessage() {} + +func (x *DeleteSandboxTemplateRequest) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[31] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteSandboxTemplateRequest.ProtoReflect.Descriptor instead. +func (*DeleteSandboxTemplateRequest) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{31} +} + +func (x *DeleteSandboxTemplateRequest) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *DeleteSandboxTemplateRequest) GetWorkspace() string { + if x != nil { + return x.Workspace + } + return "" +} + +type SandboxTemplateResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Template *SandboxWorkloadTemplate `protobuf:"bytes,1,opt,name=template,proto3" json:"template,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *SandboxTemplateResponse) Reset() { + *x = SandboxTemplateResponse{} + mi := &file_openshell_proto_msgTypes[32] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *SandboxTemplateResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*SandboxTemplateResponse) ProtoMessage() {} + +func (x *SandboxTemplateResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[32] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use SandboxTemplateResponse.ProtoReflect.Descriptor instead. +func (*SandboxTemplateResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{32} +} + +func (x *SandboxTemplateResponse) GetTemplate() *SandboxWorkloadTemplate { + if x != nil { + return x.Template + } + return nil +} + +type ListSandboxTemplatesResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Templates []*SandboxWorkloadTemplate `protobuf:"bytes,1,rep,name=templates,proto3" json:"templates,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListSandboxTemplatesResponse) Reset() { + *x = ListSandboxTemplatesResponse{} + mi := &file_openshell_proto_msgTypes[33] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListSandboxTemplatesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListSandboxTemplatesResponse) ProtoMessage() {} + +func (x *ListSandboxTemplatesResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[33] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListSandboxTemplatesResponse.ProtoReflect.Descriptor instead. +func (*ListSandboxTemplatesResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{33} +} + +func (x *ListSandboxTemplatesResponse) GetTemplates() []*SandboxWorkloadTemplate { + if x != nil { + return x.Templates + } + return nil +} + +type DeleteSandboxTemplateResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + Deleted bool `protobuf:"varint,1,opt,name=deleted,proto3" json:"deleted,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteSandboxTemplateResponse) Reset() { + *x = DeleteSandboxTemplateResponse{} + mi := &file_openshell_proto_msgTypes[34] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteSandboxTemplateResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteSandboxTemplateResponse) ProtoMessage() {} + +func (x *DeleteSandboxTemplateResponse) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[34] if x != nil { - return x.Annotations + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms } - return nil + return mi.MessageOf(x) } -func (x *CreateSandboxRequest) GetWorkspace() string { - if x != nil { - return x.Workspace - } - return "" +// Deprecated: Use DeleteSandboxTemplateResponse.ProtoReflect.Descriptor instead. +func (*DeleteSandboxTemplateResponse) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{34} } -func (x *CreateSandboxRequest) GetAwaitMainProcessAttachment() bool { +func (x *DeleteSandboxTemplateResponse) GetDeleted() bool { if x != nil { - return x.AwaitMainProcessAttachment + return x.Deleted } return false } @@ -1941,7 +2734,7 @@ type GetSandboxRequest struct { func (x *GetSandboxRequest) Reset() { *x = GetSandboxRequest{} - mi := &file_openshell_proto_msgTypes[21] + mi := &file_openshell_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -1953,7 +2746,7 @@ func (x *GetSandboxRequest) String() string { func (*GetSandboxRequest) ProtoMessage() {} func (x *GetSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[21] + mi := &file_openshell_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -1966,7 +2759,7 @@ func (x *GetSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxRequest.ProtoReflect.Descriptor instead. func (*GetSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{21} + return file_openshell_proto_rawDescGZIP(), []int{35} } func (x *GetSandboxRequest) GetName() string { @@ -2000,7 +2793,7 @@ type ListSandboxesRequest struct { func (x *ListSandboxesRequest) Reset() { *x = ListSandboxesRequest{} - mi := &file_openshell_proto_msgTypes[22] + mi := &file_openshell_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2012,7 +2805,7 @@ func (x *ListSandboxesRequest) String() string { func (*ListSandboxesRequest) ProtoMessage() {} func (x *ListSandboxesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[22] + mi := &file_openshell_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2025,7 +2818,7 @@ func (x *ListSandboxesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxesRequest.ProtoReflect.Descriptor instead. func (*ListSandboxesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{22} + return file_openshell_proto_rawDescGZIP(), []int{36} } func (x *ListSandboxesRequest) GetLimit() uint32 { @@ -2076,7 +2869,7 @@ type ListSandboxProvidersRequest struct { func (x *ListSandboxProvidersRequest) Reset() { *x = ListSandboxProvidersRequest{} - mi := &file_openshell_proto_msgTypes[23] + mi := &file_openshell_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2088,7 +2881,7 @@ func (x *ListSandboxProvidersRequest) String() string { func (*ListSandboxProvidersRequest) ProtoMessage() {} func (x *ListSandboxProvidersRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[23] + mi := &file_openshell_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2101,7 +2894,7 @@ func (x *ListSandboxProvidersRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxProvidersRequest.ProtoReflect.Descriptor instead. func (*ListSandboxProvidersRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{23} + return file_openshell_proto_rawDescGZIP(), []int{37} } func (x *ListSandboxProvidersRequest) GetSandboxName() string { @@ -2138,7 +2931,7 @@ type AttachSandboxProviderRequest struct { func (x *AttachSandboxProviderRequest) Reset() { *x = AttachSandboxProviderRequest{} - mi := &file_openshell_proto_msgTypes[24] + mi := &file_openshell_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2150,7 +2943,7 @@ func (x *AttachSandboxProviderRequest) String() string { func (*AttachSandboxProviderRequest) ProtoMessage() {} func (x *AttachSandboxProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[24] + mi := &file_openshell_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2163,7 +2956,7 @@ func (x *AttachSandboxProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use AttachSandboxProviderRequest.ProtoReflect.Descriptor instead. func (*AttachSandboxProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{24} + return file_openshell_proto_rawDescGZIP(), []int{38} } func (x *AttachSandboxProviderRequest) GetSandboxName() string { @@ -2214,7 +3007,7 @@ type DetachSandboxProviderRequest struct { func (x *DetachSandboxProviderRequest) Reset() { *x = DetachSandboxProviderRequest{} - mi := &file_openshell_proto_msgTypes[25] + mi := &file_openshell_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2226,7 +3019,7 @@ func (x *DetachSandboxProviderRequest) String() string { func (*DetachSandboxProviderRequest) ProtoMessage() {} func (x *DetachSandboxProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[25] + mi := &file_openshell_proto_msgTypes[39] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2239,7 +3032,7 @@ func (x *DetachSandboxProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DetachSandboxProviderRequest.ProtoReflect.Descriptor instead. func (*DetachSandboxProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{25} + return file_openshell_proto_rawDescGZIP(), []int{39} } func (x *DetachSandboxProviderRequest) GetSandboxName() string { @@ -2283,7 +3076,7 @@ type DeleteSandboxRequest struct { func (x *DeleteSandboxRequest) Reset() { *x = DeleteSandboxRequest{} - mi := &file_openshell_proto_msgTypes[26] + mi := &file_openshell_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2295,7 +3088,7 @@ func (x *DeleteSandboxRequest) String() string { func (*DeleteSandboxRequest) ProtoMessage() {} func (x *DeleteSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[26] + mi := &file_openshell_proto_msgTypes[40] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2308,7 +3101,7 @@ func (x *DeleteSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteSandboxRequest.ProtoReflect.Descriptor instead. func (*DeleteSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{26} + return file_openshell_proto_rawDescGZIP(), []int{40} } func (x *DeleteSandboxRequest) GetName() string { @@ -2338,7 +3131,7 @@ type StopSandboxRequest struct { func (x *StopSandboxRequest) Reset() { *x = StopSandboxRequest{} - mi := &file_openshell_proto_msgTypes[27] + mi := &file_openshell_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2350,7 +3143,7 @@ func (x *StopSandboxRequest) String() string { func (*StopSandboxRequest) ProtoMessage() {} func (x *StopSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[27] + mi := &file_openshell_proto_msgTypes[41] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2363,7 +3156,7 @@ func (x *StopSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use StopSandboxRequest.ProtoReflect.Descriptor instead. func (*StopSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{27} + return file_openshell_proto_rawDescGZIP(), []int{41} } func (x *StopSandboxRequest) GetName() string { @@ -2393,7 +3186,7 @@ type StartSandboxRequest struct { func (x *StartSandboxRequest) Reset() { *x = StartSandboxRequest{} - mi := &file_openshell_proto_msgTypes[28] + mi := &file_openshell_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2405,7 +3198,7 @@ func (x *StartSandboxRequest) String() string { func (*StartSandboxRequest) ProtoMessage() {} func (x *StartSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[28] + mi := &file_openshell_proto_msgTypes[42] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2418,7 +3211,7 @@ func (x *StartSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use StartSandboxRequest.ProtoReflect.Descriptor instead. func (*StartSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{28} + return file_openshell_proto_rawDescGZIP(), []int{42} } func (x *StartSandboxRequest) GetName() string { @@ -2445,7 +3238,7 @@ type SandboxResponse struct { func (x *SandboxResponse) Reset() { *x = SandboxResponse{} - mi := &file_openshell_proto_msgTypes[29] + mi := &file_openshell_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2457,7 +3250,7 @@ func (x *SandboxResponse) String() string { func (*SandboxResponse) ProtoMessage() {} func (x *SandboxResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[29] + mi := &file_openshell_proto_msgTypes[43] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2470,7 +3263,7 @@ func (x *SandboxResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxResponse.ProtoReflect.Descriptor instead. func (*SandboxResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{29} + return file_openshell_proto_rawDescGZIP(), []int{43} } func (x *SandboxResponse) GetSandbox() *Sandbox { @@ -2490,7 +3283,7 @@ type ListSandboxesResponse struct { func (x *ListSandboxesResponse) Reset() { *x = ListSandboxesResponse{} - mi := &file_openshell_proto_msgTypes[30] + mi := &file_openshell_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2502,7 +3295,7 @@ func (x *ListSandboxesResponse) String() string { func (*ListSandboxesResponse) ProtoMessage() {} func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[30] + mi := &file_openshell_proto_msgTypes[44] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2515,7 +3308,7 @@ func (x *ListSandboxesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxesResponse.ProtoReflect.Descriptor instead. func (*ListSandboxesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{30} + return file_openshell_proto_rawDescGZIP(), []int{44} } func (x *ListSandboxesResponse) GetSandboxes() []*Sandbox { @@ -2535,7 +3328,7 @@ type ListSandboxProvidersResponse struct { func (x *ListSandboxProvidersResponse) Reset() { *x = ListSandboxProvidersResponse{} - mi := &file_openshell_proto_msgTypes[31] + mi := &file_openshell_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2547,7 +3340,7 @@ func (x *ListSandboxProvidersResponse) String() string { func (*ListSandboxProvidersResponse) ProtoMessage() {} func (x *ListSandboxProvidersResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[31] + mi := &file_openshell_proto_msgTypes[45] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2560,7 +3353,7 @@ func (x *ListSandboxProvidersResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxProvidersResponse.ProtoReflect.Descriptor instead. func (*ListSandboxProvidersResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{31} + return file_openshell_proto_rawDescGZIP(), []int{45} } func (x *ListSandboxProvidersResponse) GetProviders() []*datamodelv1.Provider { @@ -2582,7 +3375,7 @@ type AttachSandboxProviderResponse struct { func (x *AttachSandboxProviderResponse) Reset() { *x = AttachSandboxProviderResponse{} - mi := &file_openshell_proto_msgTypes[32] + mi := &file_openshell_proto_msgTypes[46] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2594,7 +3387,7 @@ func (x *AttachSandboxProviderResponse) String() string { func (*AttachSandboxProviderResponse) ProtoMessage() {} func (x *AttachSandboxProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[32] + mi := &file_openshell_proto_msgTypes[46] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2607,7 +3400,7 @@ func (x *AttachSandboxProviderResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use AttachSandboxProviderResponse.ProtoReflect.Descriptor instead. func (*AttachSandboxProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{32} + return file_openshell_proto_rawDescGZIP(), []int{46} } func (x *AttachSandboxProviderResponse) GetSandbox() *Sandbox { @@ -2636,7 +3429,7 @@ type DetachSandboxProviderResponse struct { func (x *DetachSandboxProviderResponse) Reset() { *x = DetachSandboxProviderResponse{} - mi := &file_openshell_proto_msgTypes[33] + mi := &file_openshell_proto_msgTypes[47] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2648,7 +3441,7 @@ func (x *DetachSandboxProviderResponse) String() string { func (*DetachSandboxProviderResponse) ProtoMessage() {} func (x *DetachSandboxProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[33] + mi := &file_openshell_proto_msgTypes[47] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2661,7 +3454,7 @@ func (x *DetachSandboxProviderResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DetachSandboxProviderResponse.ProtoReflect.Descriptor instead. func (*DetachSandboxProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{33} + return file_openshell_proto_rawDescGZIP(), []int{47} } func (x *DetachSandboxProviderResponse) GetSandbox() *Sandbox { @@ -2688,7 +3481,7 @@ type DeleteSandboxResponse struct { func (x *DeleteSandboxResponse) Reset() { *x = DeleteSandboxResponse{} - mi := &file_openshell_proto_msgTypes[34] + mi := &file_openshell_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2700,7 +3493,7 @@ func (x *DeleteSandboxResponse) String() string { func (*DeleteSandboxResponse) ProtoMessage() {} func (x *DeleteSandboxResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[34] + mi := &file_openshell_proto_msgTypes[48] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2713,7 +3506,7 @@ func (x *DeleteSandboxResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteSandboxResponse.ProtoReflect.Descriptor instead. func (*DeleteSandboxResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{34} + return file_openshell_proto_rawDescGZIP(), []int{48} } func (x *DeleteSandboxResponse) GetDeleted() bool { @@ -2734,7 +3527,7 @@ type CreateSshSessionRequest struct { func (x *CreateSshSessionRequest) Reset() { *x = CreateSshSessionRequest{} - mi := &file_openshell_proto_msgTypes[35] + mi := &file_openshell_proto_msgTypes[49] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2746,7 +3539,7 @@ func (x *CreateSshSessionRequest) String() string { func (*CreateSshSessionRequest) ProtoMessage() {} func (x *CreateSshSessionRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[35] + mi := &file_openshell_proto_msgTypes[49] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2759,7 +3552,7 @@ func (x *CreateSshSessionRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateSshSessionRequest.ProtoReflect.Descriptor instead. func (*CreateSshSessionRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{35} + return file_openshell_proto_rawDescGZIP(), []int{49} } func (x *CreateSshSessionRequest) GetSandboxId() string { @@ -2802,7 +3595,7 @@ type CreateSshSessionResponse struct { func (x *CreateSshSessionResponse) Reset() { *x = CreateSshSessionResponse{} - mi := &file_openshell_proto_msgTypes[36] + mi := &file_openshell_proto_msgTypes[50] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2814,7 +3607,7 @@ func (x *CreateSshSessionResponse) String() string { func (*CreateSshSessionResponse) ProtoMessage() {} func (x *CreateSshSessionResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[36] + mi := &file_openshell_proto_msgTypes[50] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2827,7 +3620,7 @@ func (x *CreateSshSessionResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateSshSessionResponse.ProtoReflect.Descriptor instead. func (*CreateSshSessionResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{36} + return file_openshell_proto_rawDescGZIP(), []int{50} } func (x *CreateSshSessionResponse) GetSandboxId() string { @@ -2898,7 +3691,7 @@ type ExposeServiceRequest struct { func (x *ExposeServiceRequest) Reset() { *x = ExposeServiceRequest{} - mi := &file_openshell_proto_msgTypes[37] + mi := &file_openshell_proto_msgTypes[51] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2910,7 +3703,7 @@ func (x *ExposeServiceRequest) String() string { func (*ExposeServiceRequest) ProtoMessage() {} func (x *ExposeServiceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[37] + mi := &file_openshell_proto_msgTypes[51] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2923,7 +3716,7 @@ func (x *ExposeServiceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ExposeServiceRequest.ProtoReflect.Descriptor instead. func (*ExposeServiceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{37} + return file_openshell_proto_rawDescGZIP(), []int{51} } func (x *ExposeServiceRequest) GetSandbox() string { @@ -2976,7 +3769,7 @@ type GetServiceRequest struct { func (x *GetServiceRequest) Reset() { *x = GetServiceRequest{} - mi := &file_openshell_proto_msgTypes[38] + mi := &file_openshell_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2988,7 +3781,7 @@ func (x *GetServiceRequest) String() string { func (*GetServiceRequest) ProtoMessage() {} func (x *GetServiceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[38] + mi := &file_openshell_proto_msgTypes[52] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3001,7 +3794,7 @@ func (x *GetServiceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetServiceRequest.ProtoReflect.Descriptor instead. func (*GetServiceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{38} + return file_openshell_proto_rawDescGZIP(), []int{52} } func (x *GetServiceRequest) GetSandbox() string { @@ -3044,7 +3837,7 @@ type ListServicesRequest struct { func (x *ListServicesRequest) Reset() { *x = ListServicesRequest{} - mi := &file_openshell_proto_msgTypes[39] + mi := &file_openshell_proto_msgTypes[53] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3056,7 +3849,7 @@ func (x *ListServicesRequest) String() string { func (*ListServicesRequest) ProtoMessage() {} func (x *ListServicesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[39] + mi := &file_openshell_proto_msgTypes[53] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3069,7 +3862,7 @@ func (x *ListServicesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListServicesRequest.ProtoReflect.Descriptor instead. func (*ListServicesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{39} + return file_openshell_proto_rawDescGZIP(), []int{53} } func (x *ListServicesRequest) GetSandbox() string { @@ -3117,7 +3910,7 @@ type ListServicesResponse struct { func (x *ListServicesResponse) Reset() { *x = ListServicesResponse{} - mi := &file_openshell_proto_msgTypes[40] + mi := &file_openshell_proto_msgTypes[54] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3129,7 +3922,7 @@ func (x *ListServicesResponse) String() string { func (*ListServicesResponse) ProtoMessage() {} func (x *ListServicesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[40] + mi := &file_openshell_proto_msgTypes[54] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3142,7 +3935,7 @@ func (x *ListServicesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListServicesResponse.ProtoReflect.Descriptor instead. func (*ListServicesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{40} + return file_openshell_proto_rawDescGZIP(), []int{54} } func (x *ListServicesResponse) GetServices() []*ServiceEndpointResponse { @@ -3167,7 +3960,7 @@ type DeleteServiceRequest struct { func (x *DeleteServiceRequest) Reset() { *x = DeleteServiceRequest{} - mi := &file_openshell_proto_msgTypes[41] + mi := &file_openshell_proto_msgTypes[55] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3179,7 +3972,7 @@ func (x *DeleteServiceRequest) String() string { func (*DeleteServiceRequest) ProtoMessage() {} func (x *DeleteServiceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[41] + mi := &file_openshell_proto_msgTypes[55] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3192,7 +3985,7 @@ func (x *DeleteServiceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteServiceRequest.ProtoReflect.Descriptor instead. func (*DeleteServiceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{41} + return file_openshell_proto_rawDescGZIP(), []int{55} } func (x *DeleteServiceRequest) GetSandbox() string { @@ -3227,7 +4020,7 @@ type DeleteServiceResponse struct { func (x *DeleteServiceResponse) Reset() { *x = DeleteServiceResponse{} - mi := &file_openshell_proto_msgTypes[42] + mi := &file_openshell_proto_msgTypes[56] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3239,7 +4032,7 @@ func (x *DeleteServiceResponse) String() string { func (*DeleteServiceResponse) ProtoMessage() {} func (x *DeleteServiceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[42] + mi := &file_openshell_proto_msgTypes[56] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3252,7 +4045,7 @@ func (x *DeleteServiceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteServiceResponse.ProtoReflect.Descriptor instead. func (*DeleteServiceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{42} + return file_openshell_proto_rawDescGZIP(), []int{56} } func (x *DeleteServiceResponse) GetDeleted() bool { @@ -3283,7 +4076,7 @@ type ServiceEndpoint struct { func (x *ServiceEndpoint) Reset() { *x = ServiceEndpoint{} - mi := &file_openshell_proto_msgTypes[43] + mi := &file_openshell_proto_msgTypes[57] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3295,7 +4088,7 @@ func (x *ServiceEndpoint) String() string { func (*ServiceEndpoint) ProtoMessage() {} func (x *ServiceEndpoint) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[43] + mi := &file_openshell_proto_msgTypes[57] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3308,7 +4101,7 @@ func (x *ServiceEndpoint) ProtoReflect() protoreflect.Message { // Deprecated: Use ServiceEndpoint.ProtoReflect.Descriptor instead. func (*ServiceEndpoint) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{43} + return file_openshell_proto_rawDescGZIP(), []int{57} } func (x *ServiceEndpoint) GetMetadata() *datamodelv1.ObjectMeta { @@ -3364,7 +4157,7 @@ type ServiceEndpointResponse struct { func (x *ServiceEndpointResponse) Reset() { *x = ServiceEndpointResponse{} - mi := &file_openshell_proto_msgTypes[44] + mi := &file_openshell_proto_msgTypes[58] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3376,7 +4169,7 @@ func (x *ServiceEndpointResponse) String() string { func (*ServiceEndpointResponse) ProtoMessage() {} func (x *ServiceEndpointResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[44] + mi := &file_openshell_proto_msgTypes[58] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3389,7 +4182,7 @@ func (x *ServiceEndpointResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ServiceEndpointResponse.ProtoReflect.Descriptor instead. func (*ServiceEndpointResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{44} + return file_openshell_proto_rawDescGZIP(), []int{58} } func (x *ServiceEndpointResponse) GetEndpoint() *ServiceEndpoint { @@ -3417,7 +4210,7 @@ type RevokeSshSessionRequest struct { func (x *RevokeSshSessionRequest) Reset() { *x = RevokeSshSessionRequest{} - mi := &file_openshell_proto_msgTypes[45] + mi := &file_openshell_proto_msgTypes[59] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3429,7 +4222,7 @@ func (x *RevokeSshSessionRequest) String() string { func (*RevokeSshSessionRequest) ProtoMessage() {} func (x *RevokeSshSessionRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[45] + mi := &file_openshell_proto_msgTypes[59] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3442,7 +4235,7 @@ func (x *RevokeSshSessionRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RevokeSshSessionRequest.ProtoReflect.Descriptor instead. func (*RevokeSshSessionRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{45} + return file_openshell_proto_rawDescGZIP(), []int{59} } func (x *RevokeSshSessionRequest) GetToken() string { @@ -3463,7 +4256,7 @@ type RevokeSshSessionResponse struct { func (x *RevokeSshSessionResponse) Reset() { *x = RevokeSshSessionResponse{} - mi := &file_openshell_proto_msgTypes[46] + mi := &file_openshell_proto_msgTypes[60] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3475,7 +4268,7 @@ func (x *RevokeSshSessionResponse) String() string { func (*RevokeSshSessionResponse) ProtoMessage() {} func (x *RevokeSshSessionResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[46] + mi := &file_openshell_proto_msgTypes[60] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3488,7 +4281,7 @@ func (x *RevokeSshSessionResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RevokeSshSessionResponse.ProtoReflect.Descriptor instead. func (*RevokeSshSessionResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{46} + return file_openshell_proto_rawDescGZIP(), []int{60} } func (x *RevokeSshSessionResponse) GetRevoked() bool { @@ -3531,7 +4324,7 @@ type ExecSandboxRequest struct { func (x *ExecSandboxRequest) Reset() { *x = ExecSandboxRequest{} - mi := &file_openshell_proto_msgTypes[47] + mi := &file_openshell_proto_msgTypes[61] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3543,7 +4336,7 @@ func (x *ExecSandboxRequest) String() string { func (*ExecSandboxRequest) ProtoMessage() {} func (x *ExecSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[47] + mi := &file_openshell_proto_msgTypes[61] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3556,7 +4349,7 @@ func (x *ExecSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxRequest.ProtoReflect.Descriptor instead. func (*ExecSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{47} + return file_openshell_proto_rawDescGZIP(), []int{61} } func (x *ExecSandboxRequest) GetSandboxId() string { @@ -3639,7 +4432,7 @@ type ExecSandboxStdout struct { func (x *ExecSandboxStdout) Reset() { *x = ExecSandboxStdout{} - mi := &file_openshell_proto_msgTypes[48] + mi := &file_openshell_proto_msgTypes[62] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3651,7 +4444,7 @@ func (x *ExecSandboxStdout) String() string { func (*ExecSandboxStdout) ProtoMessage() {} func (x *ExecSandboxStdout) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[48] + mi := &file_openshell_proto_msgTypes[62] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3664,7 +4457,7 @@ func (x *ExecSandboxStdout) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxStdout.ProtoReflect.Descriptor instead. func (*ExecSandboxStdout) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{48} + return file_openshell_proto_rawDescGZIP(), []int{62} } func (x *ExecSandboxStdout) GetData() []byte { @@ -3684,7 +4477,7 @@ type ExecSandboxStderr struct { func (x *ExecSandboxStderr) Reset() { *x = ExecSandboxStderr{} - mi := &file_openshell_proto_msgTypes[49] + mi := &file_openshell_proto_msgTypes[63] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3696,7 +4489,7 @@ func (x *ExecSandboxStderr) String() string { func (*ExecSandboxStderr) ProtoMessage() {} func (x *ExecSandboxStderr) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[49] + mi := &file_openshell_proto_msgTypes[63] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3709,7 +4502,7 @@ func (x *ExecSandboxStderr) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxStderr.ProtoReflect.Descriptor instead. func (*ExecSandboxStderr) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{49} + return file_openshell_proto_rawDescGZIP(), []int{63} } func (x *ExecSandboxStderr) GetData() []byte { @@ -3729,7 +4522,7 @@ type ExecSandboxExit struct { func (x *ExecSandboxExit) Reset() { *x = ExecSandboxExit{} - mi := &file_openshell_proto_msgTypes[50] + mi := &file_openshell_proto_msgTypes[64] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3741,7 +4534,7 @@ func (x *ExecSandboxExit) String() string { func (*ExecSandboxExit) ProtoMessage() {} func (x *ExecSandboxExit) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[50] + mi := &file_openshell_proto_msgTypes[64] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3754,7 +4547,7 @@ func (x *ExecSandboxExit) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxExit.ProtoReflect.Descriptor instead. func (*ExecSandboxExit) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{50} + return file_openshell_proto_rawDescGZIP(), []int{64} } func (x *ExecSandboxExit) GetExitCode() int32 { @@ -3779,7 +4572,7 @@ type ExecSandboxEvent struct { func (x *ExecSandboxEvent) Reset() { *x = ExecSandboxEvent{} - mi := &file_openshell_proto_msgTypes[51] + mi := &file_openshell_proto_msgTypes[65] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3791,7 +4584,7 @@ func (x *ExecSandboxEvent) String() string { func (*ExecSandboxEvent) ProtoMessage() {} func (x *ExecSandboxEvent) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[51] + mi := &file_openshell_proto_msgTypes[65] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3804,7 +4597,7 @@ func (x *ExecSandboxEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxEvent.ProtoReflect.Descriptor instead. func (*ExecSandboxEvent) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{51} + return file_openshell_proto_rawDescGZIP(), []int{65} } func (x *ExecSandboxEvent) GetPayload() isExecSandboxEvent_Payload { @@ -3886,7 +4679,7 @@ type TcpForwardInit struct { func (x *TcpForwardInit) Reset() { *x = TcpForwardInit{} - mi := &file_openshell_proto_msgTypes[52] + mi := &file_openshell_proto_msgTypes[66] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3898,7 +4691,7 @@ func (x *TcpForwardInit) String() string { func (*TcpForwardInit) ProtoMessage() {} func (x *TcpForwardInit) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[52] + mi := &file_openshell_proto_msgTypes[66] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3911,7 +4704,7 @@ func (x *TcpForwardInit) ProtoReflect() protoreflect.Message { // Deprecated: Use TcpForwardInit.ProtoReflect.Descriptor instead. func (*TcpForwardInit) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{52} + return file_openshell_proto_rawDescGZIP(), []int{66} } func (x *TcpForwardInit) GetSandboxId() string { @@ -3990,7 +4783,7 @@ type TcpForwardFrame struct { func (x *TcpForwardFrame) Reset() { *x = TcpForwardFrame{} - mi := &file_openshell_proto_msgTypes[53] + mi := &file_openshell_proto_msgTypes[67] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4002,7 +4795,7 @@ func (x *TcpForwardFrame) String() string { func (*TcpForwardFrame) ProtoMessage() {} func (x *TcpForwardFrame) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[53] + mi := &file_openshell_proto_msgTypes[67] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4015,7 +4808,7 @@ func (x *TcpForwardFrame) ProtoReflect() protoreflect.Message { // Deprecated: Use TcpForwardFrame.ProtoReflect.Descriptor instead. func (*TcpForwardFrame) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{53} + return file_openshell_proto_rawDescGZIP(), []int{67} } func (x *TcpForwardFrame) GetPayload() isTcpForwardFrame_Payload { @@ -4074,7 +4867,7 @@ type ExecSandboxInput struct { func (x *ExecSandboxInput) Reset() { *x = ExecSandboxInput{} - mi := &file_openshell_proto_msgTypes[54] + mi := &file_openshell_proto_msgTypes[68] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4086,7 +4879,7 @@ func (x *ExecSandboxInput) String() string { func (*ExecSandboxInput) ProtoMessage() {} func (x *ExecSandboxInput) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[54] + mi := &file_openshell_proto_msgTypes[68] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4099,7 +4892,7 @@ func (x *ExecSandboxInput) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxInput.ProtoReflect.Descriptor instead. func (*ExecSandboxInput) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{54} + return file_openshell_proto_rawDescGZIP(), []int{68} } func (x *ExecSandboxInput) GetPayload() isExecSandboxInput_Payload { @@ -4172,7 +4965,7 @@ type ExecSandboxWindowResize struct { func (x *ExecSandboxWindowResize) Reset() { *x = ExecSandboxWindowResize{} - mi := &file_openshell_proto_msgTypes[55] + mi := &file_openshell_proto_msgTypes[69] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4184,7 +4977,7 @@ func (x *ExecSandboxWindowResize) String() string { func (*ExecSandboxWindowResize) ProtoMessage() {} func (x *ExecSandboxWindowResize) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[55] + mi := &file_openshell_proto_msgTypes[69] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4197,7 +4990,7 @@ func (x *ExecSandboxWindowResize) ProtoReflect() protoreflect.Message { // Deprecated: Use ExecSandboxWindowResize.ProtoReflect.Descriptor instead. func (*ExecSandboxWindowResize) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{55} + return file_openshell_proto_rawDescGZIP(), []int{69} } func (x *ExecSandboxWindowResize) GetCols() uint32 { @@ -4234,7 +5027,7 @@ type SshSession struct { func (x *SshSession) Reset() { *x = SshSession{} - mi := &file_openshell_proto_msgTypes[56] + mi := &file_openshell_proto_msgTypes[70] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4246,7 +5039,7 @@ func (x *SshSession) String() string { func (*SshSession) ProtoMessage() {} func (x *SshSession) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[56] + mi := &file_openshell_proto_msgTypes[70] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4259,7 +5052,7 @@ func (x *SshSession) ProtoReflect() protoreflect.Message { // Deprecated: Use SshSession.ProtoReflect.Descriptor instead. func (*SshSession) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{56} + return file_openshell_proto_rawDescGZIP(), []int{70} } func (x *SshSession) GetMetadata() *datamodelv1.ObjectMeta { @@ -4328,7 +5121,7 @@ type WatchSandboxRequest struct { func (x *WatchSandboxRequest) Reset() { *x = WatchSandboxRequest{} - mi := &file_openshell_proto_msgTypes[57] + mi := &file_openshell_proto_msgTypes[71] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4340,7 +5133,7 @@ func (x *WatchSandboxRequest) String() string { func (*WatchSandboxRequest) ProtoMessage() {} func (x *WatchSandboxRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[57] + mi := &file_openshell_proto_msgTypes[71] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4353,7 +5146,7 @@ func (x *WatchSandboxRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use WatchSandboxRequest.ProtoReflect.Descriptor instead. func (*WatchSandboxRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{57} + return file_openshell_proto_rawDescGZIP(), []int{71} } func (x *WatchSandboxRequest) GetId() string { @@ -4443,7 +5236,7 @@ type SandboxStreamEvent struct { func (x *SandboxStreamEvent) Reset() { *x = SandboxStreamEvent{} - mi := &file_openshell_proto_msgTypes[58] + mi := &file_openshell_proto_msgTypes[72] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4455,7 +5248,7 @@ func (x *SandboxStreamEvent) String() string { func (*SandboxStreamEvent) ProtoMessage() {} func (x *SandboxStreamEvent) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[58] + mi := &file_openshell_proto_msgTypes[72] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4468,7 +5261,7 @@ func (x *SandboxStreamEvent) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxStreamEvent.ProtoReflect.Descriptor instead. func (*SandboxStreamEvent) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{58} + return file_openshell_proto_rawDescGZIP(), []int{72} } func (x *SandboxStreamEvent) GetPayload() isSandboxStreamEvent_Payload { @@ -4581,7 +5374,7 @@ type SandboxLogLine struct { func (x *SandboxLogLine) Reset() { *x = SandboxLogLine{} - mi := &file_openshell_proto_msgTypes[59] + mi := &file_openshell_proto_msgTypes[73] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4593,7 +5386,7 @@ func (x *SandboxLogLine) String() string { func (*SandboxLogLine) ProtoMessage() {} func (x *SandboxLogLine) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[59] + mi := &file_openshell_proto_msgTypes[73] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4606,7 +5399,7 @@ func (x *SandboxLogLine) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxLogLine.ProtoReflect.Descriptor instead. func (*SandboxLogLine) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{59} + return file_openshell_proto_rawDescGZIP(), []int{73} } func (x *SandboxLogLine) GetSandboxId() string { @@ -4667,7 +5460,7 @@ type SandboxStreamWarning struct { func (x *SandboxStreamWarning) Reset() { *x = SandboxStreamWarning{} - mi := &file_openshell_proto_msgTypes[60] + mi := &file_openshell_proto_msgTypes[74] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4679,7 +5472,7 @@ func (x *SandboxStreamWarning) String() string { func (*SandboxStreamWarning) ProtoMessage() {} func (x *SandboxStreamWarning) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[60] + mi := &file_openshell_proto_msgTypes[74] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4692,7 +5485,7 @@ func (x *SandboxStreamWarning) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxStreamWarning.ProtoReflect.Descriptor instead. func (*SandboxStreamWarning) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{60} + return file_openshell_proto_rawDescGZIP(), []int{74} } func (x *SandboxStreamWarning) GetMessage() string { @@ -4714,7 +5507,7 @@ type CreateProviderRequest struct { func (x *CreateProviderRequest) Reset() { *x = CreateProviderRequest{} - mi := &file_openshell_proto_msgTypes[61] + mi := &file_openshell_proto_msgTypes[75] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4726,7 +5519,7 @@ func (x *CreateProviderRequest) String() string { func (*CreateProviderRequest) ProtoMessage() {} func (x *CreateProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[61] + mi := &file_openshell_proto_msgTypes[75] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4739,7 +5532,7 @@ func (x *CreateProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateProviderRequest.ProtoReflect.Descriptor instead. func (*CreateProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{61} + return file_openshell_proto_rawDescGZIP(), []int{75} } func (x *CreateProviderRequest) GetProvider() *datamodelv1.Provider { @@ -4768,7 +5561,7 @@ type GetProviderRequest struct { func (x *GetProviderRequest) Reset() { *x = GetProviderRequest{} - mi := &file_openshell_proto_msgTypes[62] + mi := &file_openshell_proto_msgTypes[76] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4780,7 +5573,7 @@ func (x *GetProviderRequest) String() string { func (*GetProviderRequest) ProtoMessage() {} func (x *GetProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[62] + mi := &file_openshell_proto_msgTypes[76] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4793,7 +5586,7 @@ func (x *GetProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderRequest.ProtoReflect.Descriptor instead. func (*GetProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{62} + return file_openshell_proto_rawDescGZIP(), []int{76} } func (x *GetProviderRequest) GetName() string { @@ -4825,7 +5618,7 @@ type ListProvidersRequest struct { func (x *ListProvidersRequest) Reset() { *x = ListProvidersRequest{} - mi := &file_openshell_proto_msgTypes[63] + mi := &file_openshell_proto_msgTypes[77] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4837,7 +5630,7 @@ func (x *ListProvidersRequest) String() string { func (*ListProvidersRequest) ProtoMessage() {} func (x *ListProvidersRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[63] + mi := &file_openshell_proto_msgTypes[77] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4850,7 +5643,7 @@ func (x *ListProvidersRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProvidersRequest.ProtoReflect.Descriptor instead. func (*ListProvidersRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{63} + return file_openshell_proto_rawDescGZIP(), []int{77} } func (x *ListProvidersRequest) GetLimit() uint32 { @@ -4896,7 +5689,7 @@ type UpdateProviderRequest struct { func (x *UpdateProviderRequest) Reset() { *x = UpdateProviderRequest{} - mi := &file_openshell_proto_msgTypes[64] + mi := &file_openshell_proto_msgTypes[78] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4908,7 +5701,7 @@ func (x *UpdateProviderRequest) String() string { func (*UpdateProviderRequest) ProtoMessage() {} func (x *UpdateProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[64] + mi := &file_openshell_proto_msgTypes[78] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4921,7 +5714,7 @@ func (x *UpdateProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateProviderRequest.ProtoReflect.Descriptor instead. func (*UpdateProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{64} + return file_openshell_proto_rawDescGZIP(), []int{78} } func (x *UpdateProviderRequest) GetProvider() *datamodelv1.Provider { @@ -4957,7 +5750,7 @@ type DeleteProviderRequest struct { func (x *DeleteProviderRequest) Reset() { *x = DeleteProviderRequest{} - mi := &file_openshell_proto_msgTypes[65] + mi := &file_openshell_proto_msgTypes[79] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4969,7 +5762,7 @@ func (x *DeleteProviderRequest) String() string { func (*DeleteProviderRequest) ProtoMessage() {} func (x *DeleteProviderRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[65] + mi := &file_openshell_proto_msgTypes[79] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4982,7 +5775,7 @@ func (x *DeleteProviderRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderRequest.ProtoReflect.Descriptor instead. func (*DeleteProviderRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{65} + return file_openshell_proto_rawDescGZIP(), []int{79} } func (x *DeleteProviderRequest) GetName() string { @@ -5009,7 +5802,7 @@ type ProviderResponse struct { func (x *ProviderResponse) Reset() { *x = ProviderResponse{} - mi := &file_openshell_proto_msgTypes[66] + mi := &file_openshell_proto_msgTypes[80] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5021,7 +5814,7 @@ func (x *ProviderResponse) String() string { func (*ProviderResponse) ProtoMessage() {} func (x *ProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[66] + mi := &file_openshell_proto_msgTypes[80] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5034,7 +5827,7 @@ func (x *ProviderResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderResponse.ProtoReflect.Descriptor instead. func (*ProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{66} + return file_openshell_proto_rawDescGZIP(), []int{80} } func (x *ProviderResponse) GetProvider() *datamodelv1.Provider { @@ -5054,7 +5847,7 @@ type ListProvidersResponse struct { func (x *ListProvidersResponse) Reset() { *x = ListProvidersResponse{} - mi := &file_openshell_proto_msgTypes[67] + mi := &file_openshell_proto_msgTypes[81] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5066,7 +5859,7 @@ func (x *ListProvidersResponse) String() string { func (*ListProvidersResponse) ProtoMessage() {} func (x *ListProvidersResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[67] + mi := &file_openshell_proto_msgTypes[81] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5079,7 +5872,7 @@ func (x *ListProvidersResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProvidersResponse.ProtoReflect.Descriptor instead. func (*ListProvidersResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{67} + return file_openshell_proto_rawDescGZIP(), []int{81} } func (x *ListProvidersResponse) GetProviders() []*datamodelv1.Provider { @@ -5103,7 +5896,7 @@ type ListProviderProfilesRequest struct { func (x *ListProviderProfilesRequest) Reset() { *x = ListProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[68] + mi := &file_openshell_proto_msgTypes[82] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5115,7 +5908,7 @@ func (x *ListProviderProfilesRequest) String() string { func (*ListProviderProfilesRequest) ProtoMessage() {} func (x *ListProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[68] + mi := &file_openshell_proto_msgTypes[82] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5128,7 +5921,7 @@ func (x *ListProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*ListProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{68} + return file_openshell_proto_rawDescGZIP(), []int{82} } func (x *ListProviderProfilesRequest) GetLimit() uint32 { @@ -5166,7 +5959,7 @@ type GetProviderProfileRequest struct { func (x *GetProviderProfileRequest) Reset() { *x = GetProviderProfileRequest{} - mi := &file_openshell_proto_msgTypes[69] + mi := &file_openshell_proto_msgTypes[83] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5178,7 +5971,7 @@ func (x *GetProviderProfileRequest) String() string { func (*GetProviderProfileRequest) ProtoMessage() {} func (x *GetProviderProfileRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[69] + mi := &file_openshell_proto_msgTypes[83] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5191,7 +5984,7 @@ func (x *GetProviderProfileRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderProfileRequest.ProtoReflect.Descriptor instead. func (*GetProviderProfileRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{69} + return file_openshell_proto_rawDescGZIP(), []int{83} } func (x *GetProviderProfileRequest) GetId() string { @@ -5219,7 +6012,7 @@ type ProviderProfileImportItem struct { func (x *ProviderProfileImportItem) Reset() { *x = ProviderProfileImportItem{} - mi := &file_openshell_proto_msgTypes[70] + mi := &file_openshell_proto_msgTypes[84] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5231,7 +6024,7 @@ func (x *ProviderProfileImportItem) String() string { func (*ProviderProfileImportItem) ProtoMessage() {} func (x *ProviderProfileImportItem) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[70] + mi := &file_openshell_proto_msgTypes[84] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5244,7 +6037,7 @@ func (x *ProviderProfileImportItem) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileImportItem.ProtoReflect.Descriptor instead. func (*ProviderProfileImportItem) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{70} + return file_openshell_proto_rawDescGZIP(), []int{84} } func (x *ProviderProfileImportItem) GetProfile() *ProviderProfile { @@ -5275,7 +6068,7 @@ type ProviderProfileDiagnostic struct { func (x *ProviderProfileDiagnostic) Reset() { *x = ProviderProfileDiagnostic{} - mi := &file_openshell_proto_msgTypes[71] + mi := &file_openshell_proto_msgTypes[85] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5287,7 +6080,7 @@ func (x *ProviderProfileDiagnostic) String() string { func (*ProviderProfileDiagnostic) ProtoMessage() {} func (x *ProviderProfileDiagnostic) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[71] + mi := &file_openshell_proto_msgTypes[85] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5300,7 +6093,7 @@ func (x *ProviderProfileDiagnostic) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileDiagnostic.ProtoReflect.Descriptor instead. func (*ProviderProfileDiagnostic) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{71} + return file_openshell_proto_rawDescGZIP(), []int{85} } func (x *ProviderProfileDiagnostic) GetSource() string { @@ -5357,7 +6150,7 @@ type ProviderCredentialTokenGrantAudienceOverride struct { func (x *ProviderCredentialTokenGrantAudienceOverride) Reset() { *x = ProviderCredentialTokenGrantAudienceOverride{} - mi := &file_openshell_proto_msgTypes[72] + mi := &file_openshell_proto_msgTypes[86] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5369,7 +6162,7 @@ func (x *ProviderCredentialTokenGrantAudienceOverride) String() string { func (*ProviderCredentialTokenGrantAudienceOverride) ProtoMessage() {} func (x *ProviderCredentialTokenGrantAudienceOverride) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[72] + mi := &file_openshell_proto_msgTypes[86] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5382,7 +6175,7 @@ func (x *ProviderCredentialTokenGrantAudienceOverride) ProtoReflect() protorefle // Deprecated: Use ProviderCredentialTokenGrantAudienceOverride.ProtoReflect.Descriptor instead. func (*ProviderCredentialTokenGrantAudienceOverride) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{72} + return file_openshell_proto_rawDescGZIP(), []int{86} } func (x *ProviderCredentialTokenGrantAudienceOverride) GetHost() string { @@ -5436,7 +6229,7 @@ type ProviderCredentialTokenGrantSubjectToken struct { func (x *ProviderCredentialTokenGrantSubjectToken) Reset() { *x = ProviderCredentialTokenGrantSubjectToken{} - mi := &file_openshell_proto_msgTypes[73] + mi := &file_openshell_proto_msgTypes[87] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5448,7 +6241,7 @@ func (x *ProviderCredentialTokenGrantSubjectToken) String() string { func (*ProviderCredentialTokenGrantSubjectToken) ProtoMessage() {} func (x *ProviderCredentialTokenGrantSubjectToken) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[73] + mi := &file_openshell_proto_msgTypes[87] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5461,7 +6254,7 @@ func (x *ProviderCredentialTokenGrantSubjectToken) ProtoReflect() protoreflect.M // Deprecated: Use ProviderCredentialTokenGrantSubjectToken.ProtoReflect.Descriptor instead. func (*ProviderCredentialTokenGrantSubjectToken) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{73} + return file_openshell_proto_rawDescGZIP(), []int{87} } func (x *ProviderCredentialTokenGrantSubjectToken) GetSource() string { @@ -5518,7 +6311,7 @@ type ProviderCredentialTokenGrant struct { func (x *ProviderCredentialTokenGrant) Reset() { *x = ProviderCredentialTokenGrant{} - mi := &file_openshell_proto_msgTypes[74] + mi := &file_openshell_proto_msgTypes[88] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5530,7 +6323,7 @@ func (x *ProviderCredentialTokenGrant) String() string { func (*ProviderCredentialTokenGrant) ProtoMessage() {} func (x *ProviderCredentialTokenGrant) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[74] + mi := &file_openshell_proto_msgTypes[88] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5543,7 +6336,7 @@ func (x *ProviderCredentialTokenGrant) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialTokenGrant.ProtoReflect.Descriptor instead. func (*ProviderCredentialTokenGrant) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{74} + return file_openshell_proto_rawDescGZIP(), []int{88} } func (x *ProviderCredentialTokenGrant) GetTokenEndpoint() string { @@ -5635,7 +6428,7 @@ type ProviderProfileCredential struct { func (x *ProviderProfileCredential) Reset() { *x = ProviderProfileCredential{} - mi := &file_openshell_proto_msgTypes[75] + mi := &file_openshell_proto_msgTypes[89] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5647,7 +6440,7 @@ func (x *ProviderProfileCredential) String() string { func (*ProviderProfileCredential) ProtoMessage() {} func (x *ProviderProfileCredential) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[75] + mi := &file_openshell_proto_msgTypes[89] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5660,7 +6453,7 @@ func (x *ProviderProfileCredential) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileCredential.ProtoReflect.Descriptor instead. func (*ProviderProfileCredential) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{75} + return file_openshell_proto_rawDescGZIP(), []int{89} } func (x *ProviderProfileCredential) GetName() string { @@ -5745,7 +6538,7 @@ type ProviderCredentialRefreshMaterial struct { func (x *ProviderCredentialRefreshMaterial) Reset() { *x = ProviderCredentialRefreshMaterial{} - mi := &file_openshell_proto_msgTypes[76] + mi := &file_openshell_proto_msgTypes[90] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5757,7 +6550,7 @@ func (x *ProviderCredentialRefreshMaterial) String() string { func (*ProviderCredentialRefreshMaterial) ProtoMessage() {} func (x *ProviderCredentialRefreshMaterial) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[76] + mi := &file_openshell_proto_msgTypes[90] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5770,7 +6563,7 @@ func (x *ProviderCredentialRefreshMaterial) ProtoReflect() protoreflect.Message // Deprecated: Use ProviderCredentialRefreshMaterial.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefreshMaterial) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{76} + return file_openshell_proto_rawDescGZIP(), []int{90} } func (x *ProviderCredentialRefreshMaterial) GetName() string { @@ -5815,7 +6608,7 @@ type ProviderCredentialRefreshOutput struct { func (x *ProviderCredentialRefreshOutput) Reset() { *x = ProviderCredentialRefreshOutput{} - mi := &file_openshell_proto_msgTypes[77] + mi := &file_openshell_proto_msgTypes[91] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5827,7 +6620,7 @@ func (x *ProviderCredentialRefreshOutput) String() string { func (*ProviderCredentialRefreshOutput) ProtoMessage() {} func (x *ProviderCredentialRefreshOutput) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[77] + mi := &file_openshell_proto_msgTypes[91] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5840,7 +6633,7 @@ func (x *ProviderCredentialRefreshOutput) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialRefreshOutput.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefreshOutput) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{77} + return file_openshell_proto_rawDescGZIP(), []int{91} } func (x *ProviderCredentialRefreshOutput) GetOutput() string { @@ -5872,7 +6665,7 @@ type ProviderCredentialRefresh struct { func (x *ProviderCredentialRefresh) Reset() { *x = ProviderCredentialRefresh{} - mi := &file_openshell_proto_msgTypes[78] + mi := &file_openshell_proto_msgTypes[92] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5884,7 +6677,7 @@ func (x *ProviderCredentialRefresh) String() string { func (*ProviderCredentialRefresh) ProtoMessage() {} func (x *ProviderCredentialRefresh) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[78] + mi := &file_openshell_proto_msgTypes[92] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5897,7 +6690,7 @@ func (x *ProviderCredentialRefresh) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialRefresh.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefresh) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{78} + return file_openshell_proto_rawDescGZIP(), []int{92} } func (x *ProviderCredentialRefresh) GetStrategy() ProviderCredentialRefreshStrategy { @@ -5980,7 +6773,7 @@ type ProviderCredentialRefreshStatus struct { func (x *ProviderCredentialRefreshStatus) Reset() { *x = ProviderCredentialRefreshStatus{} - mi := &file_openshell_proto_msgTypes[79] + mi := &file_openshell_proto_msgTypes[93] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5992,7 +6785,7 @@ func (x *ProviderCredentialRefreshStatus) String() string { func (*ProviderCredentialRefreshStatus) ProtoMessage() {} func (x *ProviderCredentialRefreshStatus) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[79] + mi := &file_openshell_proto_msgTypes[93] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6005,7 +6798,7 @@ func (x *ProviderCredentialRefreshStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderCredentialRefreshStatus.ProtoReflect.Descriptor instead. func (*ProviderCredentialRefreshStatus) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{79} + return file_openshell_proto_rawDescGZIP(), []int{93} } func (x *ProviderCredentialRefreshStatus) GetProviderName() string { @@ -6110,7 +6903,7 @@ type ProviderProfileDiscovery struct { func (x *ProviderProfileDiscovery) Reset() { *x = ProviderProfileDiscovery{} - mi := &file_openshell_proto_msgTypes[80] + mi := &file_openshell_proto_msgTypes[94] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6122,7 +6915,7 @@ func (x *ProviderProfileDiscovery) String() string { func (*ProviderProfileDiscovery) ProtoMessage() {} func (x *ProviderProfileDiscovery) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[80] + mi := &file_openshell_proto_msgTypes[94] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6135,7 +6928,7 @@ func (x *ProviderProfileDiscovery) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileDiscovery.ProtoReflect.Descriptor instead. func (*ProviderProfileDiscovery) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{80} + return file_openshell_proto_rawDescGZIP(), []int{94} } func (x *ProviderProfileDiscovery) GetCredentials() []string { @@ -6199,7 +6992,7 @@ type StoredProviderCredentialRefreshState struct { func (x *StoredProviderCredentialRefreshState) Reset() { *x = StoredProviderCredentialRefreshState{} - mi := &file_openshell_proto_msgTypes[81] + mi := &file_openshell_proto_msgTypes[95] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6211,7 +7004,7 @@ func (x *StoredProviderCredentialRefreshState) String() string { func (*StoredProviderCredentialRefreshState) ProtoMessage() {} func (x *StoredProviderCredentialRefreshState) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[81] + mi := &file_openshell_proto_msgTypes[95] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6224,7 +7017,7 @@ func (x *StoredProviderCredentialRefreshState) ProtoReflect() protoreflect.Messa // Deprecated: Use StoredProviderCredentialRefreshState.ProtoReflect.Descriptor instead. func (*StoredProviderCredentialRefreshState) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{81} + return file_openshell_proto_rawDescGZIP(), []int{95} } func (x *StoredProviderCredentialRefreshState) GetMetadata() *datamodelv1.ObjectMeta { @@ -6407,7 +7200,7 @@ type StoredRefreshMaterialDeletion struct { func (x *StoredRefreshMaterialDeletion) Reset() { *x = StoredRefreshMaterialDeletion{} - mi := &file_openshell_proto_msgTypes[82] + mi := &file_openshell_proto_msgTypes[96] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6419,7 +7212,7 @@ func (x *StoredRefreshMaterialDeletion) String() string { func (*StoredRefreshMaterialDeletion) ProtoMessage() {} func (x *StoredRefreshMaterialDeletion) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[82] + mi := &file_openshell_proto_msgTypes[96] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6432,7 +7225,7 @@ func (x *StoredRefreshMaterialDeletion) ProtoReflect() protoreflect.Message { // Deprecated: Use StoredRefreshMaterialDeletion.ProtoReflect.Descriptor instead. func (*StoredRefreshMaterialDeletion) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{82} + return file_openshell_proto_rawDescGZIP(), []int{96} } func (x *StoredRefreshMaterialDeletion) GetMaterialKey() string { @@ -6461,7 +7254,7 @@ type GetProviderRefreshStatusRequest struct { func (x *GetProviderRefreshStatusRequest) Reset() { *x = GetProviderRefreshStatusRequest{} - mi := &file_openshell_proto_msgTypes[83] + mi := &file_openshell_proto_msgTypes[97] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6473,7 +7266,7 @@ func (x *GetProviderRefreshStatusRequest) String() string { func (*GetProviderRefreshStatusRequest) ProtoMessage() {} func (x *GetProviderRefreshStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[83] + mi := &file_openshell_proto_msgTypes[97] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6486,7 +7279,7 @@ func (x *GetProviderRefreshStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderRefreshStatusRequest.ProtoReflect.Descriptor instead. func (*GetProviderRefreshStatusRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{83} + return file_openshell_proto_rawDescGZIP(), []int{97} } func (x *GetProviderRefreshStatusRequest) GetProvider() string { @@ -6519,7 +7312,7 @@ type GetProviderRefreshStatusResponse struct { func (x *GetProviderRefreshStatusResponse) Reset() { *x = GetProviderRefreshStatusResponse{} - mi := &file_openshell_proto_msgTypes[84] + mi := &file_openshell_proto_msgTypes[98] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6531,7 +7324,7 @@ func (x *GetProviderRefreshStatusResponse) String() string { func (*GetProviderRefreshStatusResponse) ProtoMessage() {} func (x *GetProviderRefreshStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[84] + mi := &file_openshell_proto_msgTypes[98] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6544,7 +7337,7 @@ func (x *GetProviderRefreshStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetProviderRefreshStatusResponse.ProtoReflect.Descriptor instead. func (*GetProviderRefreshStatusResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{84} + return file_openshell_proto_rawDescGZIP(), []int{98} } func (x *GetProviderRefreshStatusResponse) GetCredentials() []*ProviderCredentialRefreshStatus { @@ -6573,7 +7366,7 @@ type ConfigureProviderRefreshRequest struct { func (x *ConfigureProviderRefreshRequest) Reset() { *x = ConfigureProviderRefreshRequest{} - mi := &file_openshell_proto_msgTypes[85] + mi := &file_openshell_proto_msgTypes[99] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6585,7 +7378,7 @@ func (x *ConfigureProviderRefreshRequest) String() string { func (*ConfigureProviderRefreshRequest) ProtoMessage() {} func (x *ConfigureProviderRefreshRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[85] + mi := &file_openshell_proto_msgTypes[99] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6598,7 +7391,7 @@ func (x *ConfigureProviderRefreshRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ConfigureProviderRefreshRequest.ProtoReflect.Descriptor instead. func (*ConfigureProviderRefreshRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{85} + return file_openshell_proto_rawDescGZIP(), []int{99} } func (x *ConfigureProviderRefreshRequest) GetProvider() string { @@ -6659,7 +7452,7 @@ type ConfigureProviderRefreshResponse struct { func (x *ConfigureProviderRefreshResponse) Reset() { *x = ConfigureProviderRefreshResponse{} - mi := &file_openshell_proto_msgTypes[86] + mi := &file_openshell_proto_msgTypes[100] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6671,7 +7464,7 @@ func (x *ConfigureProviderRefreshResponse) String() string { func (*ConfigureProviderRefreshResponse) ProtoMessage() {} func (x *ConfigureProviderRefreshResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[86] + mi := &file_openshell_proto_msgTypes[100] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6684,7 +7477,7 @@ func (x *ConfigureProviderRefreshResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ConfigureProviderRefreshResponse.ProtoReflect.Descriptor instead. func (*ConfigureProviderRefreshResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{86} + return file_openshell_proto_rawDescGZIP(), []int{100} } func (x *ConfigureProviderRefreshResponse) GetStatus() *ProviderCredentialRefreshStatus { @@ -6706,7 +7499,7 @@ type RotateProviderCredentialRequest struct { func (x *RotateProviderCredentialRequest) Reset() { *x = RotateProviderCredentialRequest{} - mi := &file_openshell_proto_msgTypes[87] + mi := &file_openshell_proto_msgTypes[101] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6718,7 +7511,7 @@ func (x *RotateProviderCredentialRequest) String() string { func (*RotateProviderCredentialRequest) ProtoMessage() {} func (x *RotateProviderCredentialRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[87] + mi := &file_openshell_proto_msgTypes[101] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6731,7 +7524,7 @@ func (x *RotateProviderCredentialRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RotateProviderCredentialRequest.ProtoReflect.Descriptor instead. func (*RotateProviderCredentialRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{87} + return file_openshell_proto_rawDescGZIP(), []int{101} } func (x *RotateProviderCredentialRequest) GetProvider() string { @@ -6764,7 +7557,7 @@ type RotateProviderCredentialResponse struct { func (x *RotateProviderCredentialResponse) Reset() { *x = RotateProviderCredentialResponse{} - mi := &file_openshell_proto_msgTypes[88] + mi := &file_openshell_proto_msgTypes[102] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6776,7 +7569,7 @@ func (x *RotateProviderCredentialResponse) String() string { func (*RotateProviderCredentialResponse) ProtoMessage() {} func (x *RotateProviderCredentialResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[88] + mi := &file_openshell_proto_msgTypes[102] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6789,7 +7582,7 @@ func (x *RotateProviderCredentialResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RotateProviderCredentialResponse.ProtoReflect.Descriptor instead. func (*RotateProviderCredentialResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{88} + return file_openshell_proto_rawDescGZIP(), []int{102} } func (x *RotateProviderCredentialResponse) GetStatus() *ProviderCredentialRefreshStatus { @@ -6811,7 +7604,7 @@ type DeleteProviderRefreshRequest struct { func (x *DeleteProviderRefreshRequest) Reset() { *x = DeleteProviderRefreshRequest{} - mi := &file_openshell_proto_msgTypes[89] + mi := &file_openshell_proto_msgTypes[103] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6823,7 +7616,7 @@ func (x *DeleteProviderRefreshRequest) String() string { func (*DeleteProviderRefreshRequest) ProtoMessage() {} func (x *DeleteProviderRefreshRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[89] + mi := &file_openshell_proto_msgTypes[103] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6836,7 +7629,7 @@ func (x *DeleteProviderRefreshRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderRefreshRequest.ProtoReflect.Descriptor instead. func (*DeleteProviderRefreshRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{89} + return file_openshell_proto_rawDescGZIP(), []int{103} } func (x *DeleteProviderRefreshRequest) GetProvider() string { @@ -6869,7 +7662,7 @@ type DeleteProviderRefreshResponse struct { func (x *DeleteProviderRefreshResponse) Reset() { *x = DeleteProviderRefreshResponse{} - mi := &file_openshell_proto_msgTypes[90] + mi := &file_openshell_proto_msgTypes[104] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6881,7 +7674,7 @@ func (x *DeleteProviderRefreshResponse) String() string { func (*DeleteProviderRefreshResponse) ProtoMessage() {} func (x *DeleteProviderRefreshResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[90] + mi := &file_openshell_proto_msgTypes[104] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6894,7 +7687,7 @@ func (x *DeleteProviderRefreshResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderRefreshResponse.ProtoReflect.Descriptor instead. func (*DeleteProviderRefreshResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{90} + return file_openshell_proto_rawDescGZIP(), []int{104} } func (x *DeleteProviderRefreshResponse) GetDeleted() bool { @@ -6934,7 +7727,7 @@ type ProviderProfile struct { func (x *ProviderProfile) Reset() { *x = ProviderProfile{} - mi := &file_openshell_proto_msgTypes[91] + mi := &file_openshell_proto_msgTypes[105] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6946,7 +7739,7 @@ func (x *ProviderProfile) String() string { func (*ProviderProfile) ProtoMessage() {} func (x *ProviderProfile) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[91] + mi := &file_openshell_proto_msgTypes[105] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6959,7 +7752,7 @@ func (x *ProviderProfile) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfile.ProtoReflect.Descriptor instead. func (*ProviderProfile) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{91} + return file_openshell_proto_rawDescGZIP(), []int{105} } func (x *ProviderProfile) GetId() string { @@ -7064,7 +7857,7 @@ type StoredProviderProfile struct { func (x *StoredProviderProfile) Reset() { *x = StoredProviderProfile{} - mi := &file_openshell_proto_msgTypes[92] + mi := &file_openshell_proto_msgTypes[106] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7076,7 +7869,7 @@ func (x *StoredProviderProfile) String() string { func (*StoredProviderProfile) ProtoMessage() {} func (x *StoredProviderProfile) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[92] + mi := &file_openshell_proto_msgTypes[106] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7089,7 +7882,7 @@ func (x *StoredProviderProfile) ProtoReflect() protoreflect.Message { // Deprecated: Use StoredProviderProfile.ProtoReflect.Descriptor instead. func (*StoredProviderProfile) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{92} + return file_openshell_proto_rawDescGZIP(), []int{106} } func (x *StoredProviderProfile) GetMetadata() *datamodelv1.ObjectMeta { @@ -7116,7 +7909,7 @@ type ProviderProfileResponse struct { func (x *ProviderProfileResponse) Reset() { *x = ProviderProfileResponse{} - mi := &file_openshell_proto_msgTypes[93] + mi := &file_openshell_proto_msgTypes[107] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7128,7 +7921,7 @@ func (x *ProviderProfileResponse) String() string { func (*ProviderProfileResponse) ProtoMessage() {} func (x *ProviderProfileResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[93] + mi := &file_openshell_proto_msgTypes[107] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7141,7 +7934,7 @@ func (x *ProviderProfileResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ProviderProfileResponse.ProtoReflect.Descriptor instead. func (*ProviderProfileResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{93} + return file_openshell_proto_rawDescGZIP(), []int{107} } func (x *ProviderProfileResponse) GetProfile() *ProviderProfile { @@ -7161,7 +7954,7 @@ type ListProviderProfilesResponse struct { func (x *ListProviderProfilesResponse) Reset() { *x = ListProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[94] + mi := &file_openshell_proto_msgTypes[108] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7173,7 +7966,7 @@ func (x *ListProviderProfilesResponse) String() string { func (*ListProviderProfilesResponse) ProtoMessage() {} func (x *ListProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[94] + mi := &file_openshell_proto_msgTypes[108] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7186,7 +7979,7 @@ func (x *ListProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*ListProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{94} + return file_openshell_proto_rawDescGZIP(), []int{108} } func (x *ListProviderProfilesResponse) GetProfiles() []*ProviderProfile { @@ -7209,7 +8002,7 @@ type ImportProviderProfilesRequest struct { func (x *ImportProviderProfilesRequest) Reset() { *x = ImportProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[95] + mi := &file_openshell_proto_msgTypes[109] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7221,7 +8014,7 @@ func (x *ImportProviderProfilesRequest) String() string { func (*ImportProviderProfilesRequest) ProtoMessage() {} func (x *ImportProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[95] + mi := &file_openshell_proto_msgTypes[109] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7234,7 +8027,7 @@ func (x *ImportProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*ImportProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{95} + return file_openshell_proto_rawDescGZIP(), []int{109} } func (x *ImportProviderProfilesRequest) GetProfiles() []*ProviderProfileImportItem { @@ -7263,7 +8056,7 @@ type ImportProviderProfilesResponse struct { func (x *ImportProviderProfilesResponse) Reset() { *x = ImportProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[96] + mi := &file_openshell_proto_msgTypes[110] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7275,7 +8068,7 @@ func (x *ImportProviderProfilesResponse) String() string { func (*ImportProviderProfilesResponse) ProtoMessage() {} func (x *ImportProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[96] + mi := &file_openshell_proto_msgTypes[110] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7288,7 +8081,7 @@ func (x *ImportProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ImportProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*ImportProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{96} + return file_openshell_proto_rawDescGZIP(), []int{110} } func (x *ImportProviderProfilesResponse) GetDiagnostics() []*ProviderProfileDiagnostic { @@ -7332,7 +8125,7 @@ type UpdateProviderProfilesRequest struct { func (x *UpdateProviderProfilesRequest) Reset() { *x = UpdateProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[97] + mi := &file_openshell_proto_msgTypes[111] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7344,7 +8137,7 @@ func (x *UpdateProviderProfilesRequest) String() string { func (*UpdateProviderProfilesRequest) ProtoMessage() {} func (x *UpdateProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[97] + mi := &file_openshell_proto_msgTypes[111] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7357,7 +8150,7 @@ func (x *UpdateProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*UpdateProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{97} + return file_openshell_proto_rawDescGZIP(), []int{111} } func (x *UpdateProviderProfilesRequest) GetProfile() *ProviderProfileImportItem { @@ -7400,7 +8193,7 @@ type UpdateProviderProfilesResponse struct { func (x *UpdateProviderProfilesResponse) Reset() { *x = UpdateProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[98] + mi := &file_openshell_proto_msgTypes[112] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7412,7 +8205,7 @@ func (x *UpdateProviderProfilesResponse) String() string { func (*UpdateProviderProfilesResponse) ProtoMessage() {} func (x *UpdateProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[98] + mi := &file_openshell_proto_msgTypes[112] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7425,7 +8218,7 @@ func (x *UpdateProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*UpdateProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{98} + return file_openshell_proto_rawDescGZIP(), []int{112} } func (x *UpdateProviderProfilesResponse) GetDiagnostics() []*ProviderProfileDiagnostic { @@ -7462,7 +8255,7 @@ type LintProviderProfilesRequest struct { func (x *LintProviderProfilesRequest) Reset() { *x = LintProviderProfilesRequest{} - mi := &file_openshell_proto_msgTypes[99] + mi := &file_openshell_proto_msgTypes[113] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7474,7 +8267,7 @@ func (x *LintProviderProfilesRequest) String() string { func (*LintProviderProfilesRequest) ProtoMessage() {} func (x *LintProviderProfilesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[99] + mi := &file_openshell_proto_msgTypes[113] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7487,7 +8280,7 @@ func (x *LintProviderProfilesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use LintProviderProfilesRequest.ProtoReflect.Descriptor instead. func (*LintProviderProfilesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{99} + return file_openshell_proto_rawDescGZIP(), []int{113} } func (x *LintProviderProfilesRequest) GetProfiles() []*ProviderProfileImportItem { @@ -7515,7 +8308,7 @@ type LintProviderProfilesResponse struct { func (x *LintProviderProfilesResponse) Reset() { *x = LintProviderProfilesResponse{} - mi := &file_openshell_proto_msgTypes[100] + mi := &file_openshell_proto_msgTypes[114] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7527,7 +8320,7 @@ func (x *LintProviderProfilesResponse) String() string { func (*LintProviderProfilesResponse) ProtoMessage() {} func (x *LintProviderProfilesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[100] + mi := &file_openshell_proto_msgTypes[114] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7540,7 +8333,7 @@ func (x *LintProviderProfilesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use LintProviderProfilesResponse.ProtoReflect.Descriptor instead. func (*LintProviderProfilesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{100} + return file_openshell_proto_rawDescGZIP(), []int{114} } func (x *LintProviderProfilesResponse) GetDiagnostics() []*ProviderProfileDiagnostic { @@ -7567,7 +8360,7 @@ type DeleteProviderResponse struct { func (x *DeleteProviderResponse) Reset() { *x = DeleteProviderResponse{} - mi := &file_openshell_proto_msgTypes[101] + mi := &file_openshell_proto_msgTypes[115] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7579,7 +8372,7 @@ func (x *DeleteProviderResponse) String() string { func (*DeleteProviderResponse) ProtoMessage() {} func (x *DeleteProviderResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[101] + mi := &file_openshell_proto_msgTypes[115] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7592,7 +8385,7 @@ func (x *DeleteProviderResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderResponse.ProtoReflect.Descriptor instead. func (*DeleteProviderResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{101} + return file_openshell_proto_rawDescGZIP(), []int{115} } func (x *DeleteProviderResponse) GetDeleted() bool { @@ -7615,7 +8408,7 @@ type DeleteProviderProfileRequest struct { func (x *DeleteProviderProfileRequest) Reset() { *x = DeleteProviderProfileRequest{} - mi := &file_openshell_proto_msgTypes[102] + mi := &file_openshell_proto_msgTypes[116] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7627,7 +8420,7 @@ func (x *DeleteProviderProfileRequest) String() string { func (*DeleteProviderProfileRequest) ProtoMessage() {} func (x *DeleteProviderProfileRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[102] + mi := &file_openshell_proto_msgTypes[116] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7640,7 +8433,7 @@ func (x *DeleteProviderProfileRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderProfileRequest.ProtoReflect.Descriptor instead. func (*DeleteProviderProfileRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{102} + return file_openshell_proto_rawDescGZIP(), []int{116} } func (x *DeleteProviderProfileRequest) GetId() string { @@ -7667,7 +8460,7 @@ type DeleteProviderProfileResponse struct { func (x *DeleteProviderProfileResponse) Reset() { *x = DeleteProviderProfileResponse{} - mi := &file_openshell_proto_msgTypes[103] + mi := &file_openshell_proto_msgTypes[117] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7679,7 +8472,7 @@ func (x *DeleteProviderProfileResponse) String() string { func (*DeleteProviderProfileResponse) ProtoMessage() {} func (x *DeleteProviderProfileResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[103] + mi := &file_openshell_proto_msgTypes[117] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7692,7 +8485,7 @@ func (x *DeleteProviderProfileResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteProviderProfileResponse.ProtoReflect.Descriptor instead. func (*DeleteProviderProfileResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{103} + return file_openshell_proto_rawDescGZIP(), []int{117} } func (x *DeleteProviderProfileResponse) GetDeleted() bool { @@ -7717,7 +8510,7 @@ type GetSandboxProviderEnvironmentRequest struct { func (x *GetSandboxProviderEnvironmentRequest) Reset() { *x = GetSandboxProviderEnvironmentRequest{} - mi := &file_openshell_proto_msgTypes[104] + mi := &file_openshell_proto_msgTypes[118] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7729,7 +8522,7 @@ func (x *GetSandboxProviderEnvironmentRequest) String() string { func (*GetSandboxProviderEnvironmentRequest) ProtoMessage() {} func (x *GetSandboxProviderEnvironmentRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[104] + mi := &file_openshell_proto_msgTypes[118] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7742,7 +8535,7 @@ func (x *GetSandboxProviderEnvironmentRequest) ProtoReflect() protoreflect.Messa // Deprecated: Use GetSandboxProviderEnvironmentRequest.ProtoReflect.Descriptor instead. func (*GetSandboxProviderEnvironmentRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{104} + return file_openshell_proto_rawDescGZIP(), []int{118} } func (x *GetSandboxProviderEnvironmentRequest) GetSandboxId() string { @@ -7771,7 +8564,7 @@ type StaticCredentialEndpointBinding struct { func (x *StaticCredentialEndpointBinding) Reset() { *x = StaticCredentialEndpointBinding{} - mi := &file_openshell_proto_msgTypes[105] + mi := &file_openshell_proto_msgTypes[119] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7783,7 +8576,7 @@ func (x *StaticCredentialEndpointBinding) String() string { func (*StaticCredentialEndpointBinding) ProtoMessage() {} func (x *StaticCredentialEndpointBinding) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[105] + mi := &file_openshell_proto_msgTypes[119] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7796,7 +8589,7 @@ func (x *StaticCredentialEndpointBinding) ProtoReflect() protoreflect.Message { // Deprecated: Use StaticCredentialEndpointBinding.ProtoReflect.Descriptor instead. func (*StaticCredentialEndpointBinding) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{105} + return file_openshell_proto_rawDescGZIP(), []int{119} } func (x *StaticCredentialEndpointBinding) GetHost() string { @@ -7840,7 +8633,7 @@ type StaticCredentialBinding struct { func (x *StaticCredentialBinding) Reset() { *x = StaticCredentialBinding{} - mi := &file_openshell_proto_msgTypes[106] + mi := &file_openshell_proto_msgTypes[120] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7852,7 +8645,7 @@ func (x *StaticCredentialBinding) String() string { func (*StaticCredentialBinding) ProtoMessage() {} func (x *StaticCredentialBinding) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[106] + mi := &file_openshell_proto_msgTypes[120] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7865,7 +8658,7 @@ func (x *StaticCredentialBinding) ProtoReflect() protoreflect.Message { // Deprecated: Use StaticCredentialBinding.ProtoReflect.Descriptor instead. func (*StaticCredentialBinding) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{106} + return file_openshell_proto_rawDescGZIP(), []int{120} } func (x *StaticCredentialBinding) GetEndpoints() []*StaticCredentialEndpointBinding { @@ -7916,7 +8709,7 @@ type GetSandboxProviderEnvironmentResponse struct { func (x *GetSandboxProviderEnvironmentResponse) Reset() { *x = GetSandboxProviderEnvironmentResponse{} - mi := &file_openshell_proto_msgTypes[107] + mi := &file_openshell_proto_msgTypes[121] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7928,7 +8721,7 @@ func (x *GetSandboxProviderEnvironmentResponse) String() string { func (*GetSandboxProviderEnvironmentResponse) ProtoMessage() {} func (x *GetSandboxProviderEnvironmentResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[107] + mi := &file_openshell_proto_msgTypes[121] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7941,7 +8734,7 @@ func (x *GetSandboxProviderEnvironmentResponse) ProtoReflect() protoreflect.Mess // Deprecated: Use GetSandboxProviderEnvironmentResponse.ProtoReflect.Descriptor instead. func (*GetSandboxProviderEnvironmentResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{107} + return file_openshell_proto_rawDescGZIP(), []int{121} } func (x *GetSandboxProviderEnvironmentResponse) GetEnvironment() map[string]string { @@ -8003,7 +8796,7 @@ type ExchangeProviderSubjectTokenRequest struct { func (x *ExchangeProviderSubjectTokenRequest) Reset() { *x = ExchangeProviderSubjectTokenRequest{} - mi := &file_openshell_proto_msgTypes[108] + mi := &file_openshell_proto_msgTypes[122] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8015,7 +8808,7 @@ func (x *ExchangeProviderSubjectTokenRequest) String() string { func (*ExchangeProviderSubjectTokenRequest) ProtoMessage() {} func (x *ExchangeProviderSubjectTokenRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[108] + mi := &file_openshell_proto_msgTypes[122] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8028,7 +8821,7 @@ func (x *ExchangeProviderSubjectTokenRequest) ProtoReflect() protoreflect.Messag // Deprecated: Use ExchangeProviderSubjectTokenRequest.ProtoReflect.Descriptor instead. func (*ExchangeProviderSubjectTokenRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{108} + return file_openshell_proto_rawDescGZIP(), []int{122} } func (x *ExchangeProviderSubjectTokenRequest) GetSandboxId() string { @@ -8070,7 +8863,7 @@ type ExchangeProviderSubjectTokenResponse struct { func (x *ExchangeProviderSubjectTokenResponse) Reset() { *x = ExchangeProviderSubjectTokenResponse{} - mi := &file_openshell_proto_msgTypes[109] + mi := &file_openshell_proto_msgTypes[123] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8082,7 +8875,7 @@ func (x *ExchangeProviderSubjectTokenResponse) String() string { func (*ExchangeProviderSubjectTokenResponse) ProtoMessage() {} func (x *ExchangeProviderSubjectTokenResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[109] + mi := &file_openshell_proto_msgTypes[123] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8095,7 +8888,7 @@ func (x *ExchangeProviderSubjectTokenResponse) ProtoReflect() protoreflect.Messa // Deprecated: Use ExchangeProviderSubjectTokenResponse.ProtoReflect.Descriptor instead. func (*ExchangeProviderSubjectTokenResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{109} + return file_openshell_proto_rawDescGZIP(), []int{123} } func (x *ExchangeProviderSubjectTokenResponse) GetAccessToken() string { @@ -8166,7 +8959,7 @@ type UpdateConfigRequest struct { func (x *UpdateConfigRequest) Reset() { *x = UpdateConfigRequest{} - mi := &file_openshell_proto_msgTypes[110] + mi := &file_openshell_proto_msgTypes[124] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8178,7 +8971,7 @@ func (x *UpdateConfigRequest) String() string { func (*UpdateConfigRequest) ProtoMessage() {} func (x *UpdateConfigRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[110] + mi := &file_openshell_proto_msgTypes[124] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8191,7 +8984,7 @@ func (x *UpdateConfigRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateConfigRequest.ProtoReflect.Descriptor instead. func (*UpdateConfigRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{110} + return file_openshell_proto_rawDescGZIP(), []int{124} } func (x *UpdateConfigRequest) GetName() string { @@ -8281,7 +9074,7 @@ type PolicyMergeOperation struct { func (x *PolicyMergeOperation) Reset() { *x = PolicyMergeOperation{} - mi := &file_openshell_proto_msgTypes[111] + mi := &file_openshell_proto_msgTypes[125] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8293,7 +9086,7 @@ func (x *PolicyMergeOperation) String() string { func (*PolicyMergeOperation) ProtoMessage() {} func (x *PolicyMergeOperation) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[111] + mi := &file_openshell_proto_msgTypes[125] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8306,7 +9099,7 @@ func (x *PolicyMergeOperation) ProtoReflect() protoreflect.Message { // Deprecated: Use PolicyMergeOperation.ProtoReflect.Descriptor instead. func (*PolicyMergeOperation) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{111} + return file_openshell_proto_rawDescGZIP(), []int{125} } func (x *PolicyMergeOperation) GetOperation() isPolicyMergeOperation_Operation { @@ -8420,7 +9213,7 @@ type AddNetworkRule struct { func (x *AddNetworkRule) Reset() { *x = AddNetworkRule{} - mi := &file_openshell_proto_msgTypes[112] + mi := &file_openshell_proto_msgTypes[126] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8432,7 +9225,7 @@ func (x *AddNetworkRule) String() string { func (*AddNetworkRule) ProtoMessage() {} func (x *AddNetworkRule) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[112] + mi := &file_openshell_proto_msgTypes[126] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8445,7 +9238,7 @@ func (x *AddNetworkRule) ProtoReflect() protoreflect.Message { // Deprecated: Use AddNetworkRule.ProtoReflect.Descriptor instead. func (*AddNetworkRule) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{112} + return file_openshell_proto_rawDescGZIP(), []int{126} } func (x *AddNetworkRule) GetRuleName() string { @@ -8473,7 +9266,7 @@ type RemoveNetworkEndpoint struct { func (x *RemoveNetworkEndpoint) Reset() { *x = RemoveNetworkEndpoint{} - mi := &file_openshell_proto_msgTypes[113] + mi := &file_openshell_proto_msgTypes[127] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8485,7 +9278,7 @@ func (x *RemoveNetworkEndpoint) String() string { func (*RemoveNetworkEndpoint) ProtoMessage() {} func (x *RemoveNetworkEndpoint) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[113] + mi := &file_openshell_proto_msgTypes[127] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8498,7 +9291,7 @@ func (x *RemoveNetworkEndpoint) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveNetworkEndpoint.ProtoReflect.Descriptor instead. func (*RemoveNetworkEndpoint) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{113} + return file_openshell_proto_rawDescGZIP(), []int{127} } func (x *RemoveNetworkEndpoint) GetRuleName() string { @@ -8531,7 +9324,7 @@ type RemoveNetworkRule struct { func (x *RemoveNetworkRule) Reset() { *x = RemoveNetworkRule{} - mi := &file_openshell_proto_msgTypes[114] + mi := &file_openshell_proto_msgTypes[128] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8543,7 +9336,7 @@ func (x *RemoveNetworkRule) String() string { func (*RemoveNetworkRule) ProtoMessage() {} func (x *RemoveNetworkRule) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[114] + mi := &file_openshell_proto_msgTypes[128] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8556,7 +9349,7 @@ func (x *RemoveNetworkRule) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveNetworkRule.ProtoReflect.Descriptor instead. func (*RemoveNetworkRule) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{114} + return file_openshell_proto_rawDescGZIP(), []int{128} } func (x *RemoveNetworkRule) GetRuleName() string { @@ -8577,7 +9370,7 @@ type AddDenyRules struct { func (x *AddDenyRules) Reset() { *x = AddDenyRules{} - mi := &file_openshell_proto_msgTypes[115] + mi := &file_openshell_proto_msgTypes[129] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8589,7 +9382,7 @@ func (x *AddDenyRules) String() string { func (*AddDenyRules) ProtoMessage() {} func (x *AddDenyRules) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[115] + mi := &file_openshell_proto_msgTypes[129] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8602,7 +9395,7 @@ func (x *AddDenyRules) ProtoReflect() protoreflect.Message { // Deprecated: Use AddDenyRules.ProtoReflect.Descriptor instead. func (*AddDenyRules) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{115} + return file_openshell_proto_rawDescGZIP(), []int{129} } func (x *AddDenyRules) GetHost() string { @@ -8637,7 +9430,7 @@ type AddAllowRules struct { func (x *AddAllowRules) Reset() { *x = AddAllowRules{} - mi := &file_openshell_proto_msgTypes[116] + mi := &file_openshell_proto_msgTypes[130] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8649,7 +9442,7 @@ func (x *AddAllowRules) String() string { func (*AddAllowRules) ProtoMessage() {} func (x *AddAllowRules) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[116] + mi := &file_openshell_proto_msgTypes[130] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8662,7 +9455,7 @@ func (x *AddAllowRules) ProtoReflect() protoreflect.Message { // Deprecated: Use AddAllowRules.ProtoReflect.Descriptor instead. func (*AddAllowRules) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{116} + return file_openshell_proto_rawDescGZIP(), []int{130} } func (x *AddAllowRules) GetHost() string { @@ -8696,7 +9489,7 @@ type RemoveNetworkBinary struct { func (x *RemoveNetworkBinary) Reset() { *x = RemoveNetworkBinary{} - mi := &file_openshell_proto_msgTypes[117] + mi := &file_openshell_proto_msgTypes[131] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8708,7 +9501,7 @@ func (x *RemoveNetworkBinary) String() string { func (*RemoveNetworkBinary) ProtoMessage() {} func (x *RemoveNetworkBinary) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[117] + mi := &file_openshell_proto_msgTypes[131] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8721,7 +9514,7 @@ func (x *RemoveNetworkBinary) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveNetworkBinary.ProtoReflect.Descriptor instead. func (*RemoveNetworkBinary) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{117} + return file_openshell_proto_rawDescGZIP(), []int{131} } func (x *RemoveNetworkBinary) GetRuleName() string { @@ -8757,7 +9550,7 @@ type UpdateConfigResponse struct { func (x *UpdateConfigResponse) Reset() { *x = UpdateConfigResponse{} - mi := &file_openshell_proto_msgTypes[118] + mi := &file_openshell_proto_msgTypes[132] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8769,7 +9562,7 @@ func (x *UpdateConfigResponse) String() string { func (*UpdateConfigResponse) ProtoMessage() {} func (x *UpdateConfigResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[118] + mi := &file_openshell_proto_msgTypes[132] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8782,7 +9575,7 @@ func (x *UpdateConfigResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateConfigResponse.ProtoReflect.Descriptor instead. func (*UpdateConfigResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{118} + return file_openshell_proto_rawDescGZIP(), []int{132} } func (x *UpdateConfigResponse) GetVersion() uint32 { @@ -8837,7 +9630,7 @@ type GetSandboxPolicyStatusRequest struct { func (x *GetSandboxPolicyStatusRequest) Reset() { *x = GetSandboxPolicyStatusRequest{} - mi := &file_openshell_proto_msgTypes[119] + mi := &file_openshell_proto_msgTypes[133] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8849,7 +9642,7 @@ func (x *GetSandboxPolicyStatusRequest) String() string { func (*GetSandboxPolicyStatusRequest) ProtoMessage() {} func (x *GetSandboxPolicyStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[119] + mi := &file_openshell_proto_msgTypes[133] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8862,7 +9655,7 @@ func (x *GetSandboxPolicyStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxPolicyStatusRequest.ProtoReflect.Descriptor instead. func (*GetSandboxPolicyStatusRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{119} + return file_openshell_proto_rawDescGZIP(), []int{133} } func (x *GetSandboxPolicyStatusRequest) GetName() string { @@ -8906,7 +9699,7 @@ type GetSandboxPolicyStatusResponse struct { func (x *GetSandboxPolicyStatusResponse) Reset() { *x = GetSandboxPolicyStatusResponse{} - mi := &file_openshell_proto_msgTypes[120] + mi := &file_openshell_proto_msgTypes[134] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8918,7 +9711,7 @@ func (x *GetSandboxPolicyStatusResponse) String() string { func (*GetSandboxPolicyStatusResponse) ProtoMessage() {} func (x *GetSandboxPolicyStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[120] + mi := &file_openshell_proto_msgTypes[134] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8931,7 +9724,7 @@ func (x *GetSandboxPolicyStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxPolicyStatusResponse.ProtoReflect.Descriptor instead. func (*GetSandboxPolicyStatusResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{120} + return file_openshell_proto_rawDescGZIP(), []int{134} } func (x *GetSandboxPolicyStatusResponse) GetRevision() *SandboxPolicyRevision { @@ -8965,7 +9758,7 @@ type ListSandboxPoliciesRequest struct { func (x *ListSandboxPoliciesRequest) Reset() { *x = ListSandboxPoliciesRequest{} - mi := &file_openshell_proto_msgTypes[121] + mi := &file_openshell_proto_msgTypes[135] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8977,7 +9770,7 @@ func (x *ListSandboxPoliciesRequest) String() string { func (*ListSandboxPoliciesRequest) ProtoMessage() {} func (x *ListSandboxPoliciesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[121] + mi := &file_openshell_proto_msgTypes[135] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8990,7 +9783,7 @@ func (x *ListSandboxPoliciesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxPoliciesRequest.ProtoReflect.Descriptor instead. func (*ListSandboxPoliciesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{121} + return file_openshell_proto_rawDescGZIP(), []int{135} } func (x *ListSandboxPoliciesRequest) GetName() string { @@ -9038,7 +9831,7 @@ type ListSandboxPoliciesResponse struct { func (x *ListSandboxPoliciesResponse) Reset() { *x = ListSandboxPoliciesResponse{} - mi := &file_openshell_proto_msgTypes[122] + mi := &file_openshell_proto_msgTypes[136] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9050,7 +9843,7 @@ func (x *ListSandboxPoliciesResponse) String() string { func (*ListSandboxPoliciesResponse) ProtoMessage() {} func (x *ListSandboxPoliciesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[122] + mi := &file_openshell_proto_msgTypes[136] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9063,7 +9856,7 @@ func (x *ListSandboxPoliciesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListSandboxPoliciesResponse.ProtoReflect.Descriptor instead. func (*ListSandboxPoliciesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{122} + return file_openshell_proto_rawDescGZIP(), []int{136} } func (x *ListSandboxPoliciesResponse) GetRevisions() []*SandboxPolicyRevision { @@ -9090,7 +9883,7 @@ type ReportPolicyStatusRequest struct { func (x *ReportPolicyStatusRequest) Reset() { *x = ReportPolicyStatusRequest{} - mi := &file_openshell_proto_msgTypes[123] + mi := &file_openshell_proto_msgTypes[137] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9102,7 +9895,7 @@ func (x *ReportPolicyStatusRequest) String() string { func (*ReportPolicyStatusRequest) ProtoMessage() {} func (x *ReportPolicyStatusRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[123] + mi := &file_openshell_proto_msgTypes[137] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9115,7 +9908,7 @@ func (x *ReportPolicyStatusRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportPolicyStatusRequest.ProtoReflect.Descriptor instead. func (*ReportPolicyStatusRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{123} + return file_openshell_proto_rawDescGZIP(), []int{137} } func (x *ReportPolicyStatusRequest) GetSandboxId() string { @@ -9155,7 +9948,7 @@ type ReportPolicyStatusResponse struct { func (x *ReportPolicyStatusResponse) Reset() { *x = ReportPolicyStatusResponse{} - mi := &file_openshell_proto_msgTypes[124] + mi := &file_openshell_proto_msgTypes[138] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9167,7 +9960,7 @@ func (x *ReportPolicyStatusResponse) String() string { func (*ReportPolicyStatusResponse) ProtoMessage() {} func (x *ReportPolicyStatusResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[124] + mi := &file_openshell_proto_msgTypes[138] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9180,7 +9973,7 @@ func (x *ReportPolicyStatusResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportPolicyStatusResponse.ProtoReflect.Descriptor instead. func (*ReportPolicyStatusResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{124} + return file_openshell_proto_rawDescGZIP(), []int{138} } // A versioned policy revision with metadata. @@ -9208,7 +10001,7 @@ type SandboxPolicyRevision struct { func (x *SandboxPolicyRevision) Reset() { *x = SandboxPolicyRevision{} - mi := &file_openshell_proto_msgTypes[125] + mi := &file_openshell_proto_msgTypes[139] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9220,7 +10013,7 @@ func (x *SandboxPolicyRevision) String() string { func (*SandboxPolicyRevision) ProtoMessage() {} func (x *SandboxPolicyRevision) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[125] + mi := &file_openshell_proto_msgTypes[139] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9233,7 +10026,7 @@ func (x *SandboxPolicyRevision) ProtoReflect() protoreflect.Message { // Deprecated: Use SandboxPolicyRevision.ProtoReflect.Descriptor instead. func (*SandboxPolicyRevision) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{125} + return file_openshell_proto_rawDescGZIP(), []int{139} } func (x *SandboxPolicyRevision) GetVersion() uint32 { @@ -9313,7 +10106,7 @@ type GetSandboxLogsRequest struct { func (x *GetSandboxLogsRequest) Reset() { *x = GetSandboxLogsRequest{} - mi := &file_openshell_proto_msgTypes[126] + mi := &file_openshell_proto_msgTypes[140] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9325,7 +10118,7 @@ func (x *GetSandboxLogsRequest) String() string { func (*GetSandboxLogsRequest) ProtoMessage() {} func (x *GetSandboxLogsRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[126] + mi := &file_openshell_proto_msgTypes[140] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9338,7 +10131,7 @@ func (x *GetSandboxLogsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxLogsRequest.ProtoReflect.Descriptor instead. func (*GetSandboxLogsRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{126} + return file_openshell_proto_rawDescGZIP(), []int{140} } func (x *GetSandboxLogsRequest) GetSandboxId() string { @@ -9396,7 +10189,7 @@ type PushSandboxLogsRequest struct { func (x *PushSandboxLogsRequest) Reset() { *x = PushSandboxLogsRequest{} - mi := &file_openshell_proto_msgTypes[127] + mi := &file_openshell_proto_msgTypes[141] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9408,7 +10201,7 @@ func (x *PushSandboxLogsRequest) String() string { func (*PushSandboxLogsRequest) ProtoMessage() {} func (x *PushSandboxLogsRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[127] + mi := &file_openshell_proto_msgTypes[141] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9421,7 +10214,7 @@ func (x *PushSandboxLogsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use PushSandboxLogsRequest.ProtoReflect.Descriptor instead. func (*PushSandboxLogsRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{127} + return file_openshell_proto_rawDescGZIP(), []int{141} } func (x *PushSandboxLogsRequest) GetSandboxId() string { @@ -9447,7 +10240,7 @@ type PushSandboxLogsResponse struct { func (x *PushSandboxLogsResponse) Reset() { *x = PushSandboxLogsResponse{} - mi := &file_openshell_proto_msgTypes[128] + mi := &file_openshell_proto_msgTypes[142] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9459,7 +10252,7 @@ func (x *PushSandboxLogsResponse) String() string { func (*PushSandboxLogsResponse) ProtoMessage() {} func (x *PushSandboxLogsResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[128] + mi := &file_openshell_proto_msgTypes[142] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9472,7 +10265,7 @@ func (x *PushSandboxLogsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use PushSandboxLogsResponse.ProtoReflect.Descriptor instead. func (*PushSandboxLogsResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{128} + return file_openshell_proto_rawDescGZIP(), []int{142} } // Get sandbox logs response. @@ -9488,7 +10281,7 @@ type GetSandboxLogsResponse struct { func (x *GetSandboxLogsResponse) Reset() { *x = GetSandboxLogsResponse{} - mi := &file_openshell_proto_msgTypes[129] + mi := &file_openshell_proto_msgTypes[143] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9500,7 +10293,7 @@ func (x *GetSandboxLogsResponse) String() string { func (*GetSandboxLogsResponse) ProtoMessage() {} func (x *GetSandboxLogsResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[129] + mi := &file_openshell_proto_msgTypes[143] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9513,7 +10306,7 @@ func (x *GetSandboxLogsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetSandboxLogsResponse.ProtoReflect.Descriptor instead. func (*GetSandboxLogsResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{129} + return file_openshell_proto_rawDescGZIP(), []int{143} } func (x *GetSandboxLogsResponse) GetLogs() []*SandboxLogLine { @@ -9546,7 +10339,7 @@ type SupervisorMessage struct { func (x *SupervisorMessage) Reset() { *x = SupervisorMessage{} - mi := &file_openshell_proto_msgTypes[130] + mi := &file_openshell_proto_msgTypes[144] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9558,7 +10351,7 @@ func (x *SupervisorMessage) String() string { func (*SupervisorMessage) ProtoMessage() {} func (x *SupervisorMessage) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[130] + mi := &file_openshell_proto_msgTypes[144] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9571,7 +10364,7 @@ func (x *SupervisorMessage) ProtoReflect() protoreflect.Message { // Deprecated: Use SupervisorMessage.ProtoReflect.Descriptor instead. func (*SupervisorMessage) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{130} + return file_openshell_proto_rawDescGZIP(), []int{144} } func (x *SupervisorMessage) GetPayload() isSupervisorMessage_Payload { @@ -9662,7 +10455,7 @@ type GatewayMessage struct { func (x *GatewayMessage) Reset() { *x = GatewayMessage{} - mi := &file_openshell_proto_msgTypes[131] + mi := &file_openshell_proto_msgTypes[145] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9674,7 +10467,7 @@ func (x *GatewayMessage) String() string { func (*GatewayMessage) ProtoMessage() {} func (x *GatewayMessage) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[131] + mi := &file_openshell_proto_msgTypes[145] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9687,7 +10480,7 @@ func (x *GatewayMessage) ProtoReflect() protoreflect.Message { // Deprecated: Use GatewayMessage.ProtoReflect.Descriptor instead. func (*GatewayMessage) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{131} + return file_openshell_proto_rawDescGZIP(), []int{145} } func (x *GatewayMessage) GetPayload() isGatewayMessage_Payload { @@ -9789,7 +10582,7 @@ type SupervisorHello struct { func (x *SupervisorHello) Reset() { *x = SupervisorHello{} - mi := &file_openshell_proto_msgTypes[132] + mi := &file_openshell_proto_msgTypes[146] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9801,7 +10594,7 @@ func (x *SupervisorHello) String() string { func (*SupervisorHello) ProtoMessage() {} func (x *SupervisorHello) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[132] + mi := &file_openshell_proto_msgTypes[146] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9814,7 +10607,7 @@ func (x *SupervisorHello) ProtoReflect() protoreflect.Message { // Deprecated: Use SupervisorHello.ProtoReflect.Descriptor instead. func (*SupervisorHello) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{132} + return file_openshell_proto_rawDescGZIP(), []int{146} } func (x *SupervisorHello) GetSandboxId() string { @@ -9844,7 +10637,7 @@ type SessionAccepted struct { func (x *SessionAccepted) Reset() { *x = SessionAccepted{} - mi := &file_openshell_proto_msgTypes[133] + mi := &file_openshell_proto_msgTypes[147] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9856,7 +10649,7 @@ func (x *SessionAccepted) String() string { func (*SessionAccepted) ProtoMessage() {} func (x *SessionAccepted) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[133] + mi := &file_openshell_proto_msgTypes[147] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9869,7 +10662,7 @@ func (x *SessionAccepted) ProtoReflect() protoreflect.Message { // Deprecated: Use SessionAccepted.ProtoReflect.Descriptor instead. func (*SessionAccepted) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{133} + return file_openshell_proto_rawDescGZIP(), []int{147} } func (x *SessionAccepted) GetSessionId() string { @@ -9897,7 +10690,7 @@ type SessionRejected struct { func (x *SessionRejected) Reset() { *x = SessionRejected{} - mi := &file_openshell_proto_msgTypes[134] + mi := &file_openshell_proto_msgTypes[148] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9909,7 +10702,7 @@ func (x *SessionRejected) String() string { func (*SessionRejected) ProtoMessage() {} func (x *SessionRejected) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[134] + mi := &file_openshell_proto_msgTypes[148] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9922,7 +10715,7 @@ func (x *SessionRejected) ProtoReflect() protoreflect.Message { // Deprecated: Use SessionRejected.ProtoReflect.Descriptor instead. func (*SessionRejected) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{134} + return file_openshell_proto_rawDescGZIP(), []int{148} } func (x *SessionRejected) GetReason() string { @@ -9941,7 +10734,7 @@ type SupervisorHeartbeat struct { func (x *SupervisorHeartbeat) Reset() { *x = SupervisorHeartbeat{} - mi := &file_openshell_proto_msgTypes[135] + mi := &file_openshell_proto_msgTypes[149] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9953,7 +10746,7 @@ func (x *SupervisorHeartbeat) String() string { func (*SupervisorHeartbeat) ProtoMessage() {} func (x *SupervisorHeartbeat) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[135] + mi := &file_openshell_proto_msgTypes[149] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9966,7 +10759,7 @@ func (x *SupervisorHeartbeat) ProtoReflect() protoreflect.Message { // Deprecated: Use SupervisorHeartbeat.ProtoReflect.Descriptor instead. func (*SupervisorHeartbeat) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{135} + return file_openshell_proto_rawDescGZIP(), []int{149} } // Gateway heartbeat. @@ -9978,7 +10771,7 @@ type GatewayHeartbeat struct { func (x *GatewayHeartbeat) Reset() { *x = GatewayHeartbeat{} - mi := &file_openshell_proto_msgTypes[136] + mi := &file_openshell_proto_msgTypes[150] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9990,7 +10783,7 @@ func (x *GatewayHeartbeat) String() string { func (*GatewayHeartbeat) ProtoMessage() {} func (x *GatewayHeartbeat) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[136] + mi := &file_openshell_proto_msgTypes[150] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10003,7 +10796,7 @@ func (x *GatewayHeartbeat) ProtoReflect() protoreflect.Message { // Deprecated: Use GatewayHeartbeat.ProtoReflect.Descriptor instead. func (*GatewayHeartbeat) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{136} + return file_openshell_proto_rawDescGZIP(), []int{150} } // Terminal result reported before the supervisor shuts down. A successful RPC @@ -10020,7 +10813,7 @@ type ReportMainProcessExitRequest struct { func (x *ReportMainProcessExitRequest) Reset() { *x = ReportMainProcessExitRequest{} - mi := &file_openshell_proto_msgTypes[137] + mi := &file_openshell_proto_msgTypes[151] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10032,7 +10825,7 @@ func (x *ReportMainProcessExitRequest) String() string { func (*ReportMainProcessExitRequest) ProtoMessage() {} func (x *ReportMainProcessExitRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[137] + mi := &file_openshell_proto_msgTypes[151] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10045,7 +10838,7 @@ func (x *ReportMainProcessExitRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportMainProcessExitRequest.ProtoReflect.Descriptor instead. func (*ReportMainProcessExitRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{137} + return file_openshell_proto_rawDescGZIP(), []int{151} } func (x *ReportMainProcessExitRequest) GetSandboxId() string { @@ -10077,7 +10870,7 @@ type ReportMainProcessExitResponse struct { func (x *ReportMainProcessExitResponse) Reset() { *x = ReportMainProcessExitResponse{} - mi := &file_openshell_proto_msgTypes[138] + mi := &file_openshell_proto_msgTypes[152] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10089,7 +10882,7 @@ func (x *ReportMainProcessExitResponse) String() string { func (*ReportMainProcessExitResponse) ProtoMessage() {} func (x *ReportMainProcessExitResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[138] + mi := &file_openshell_proto_msgTypes[152] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10102,7 +10895,7 @@ func (x *ReportMainProcessExitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportMainProcessExitResponse.ProtoReflect.Descriptor instead. func (*ReportMainProcessExitResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{138} + return file_openshell_proto_rawDescGZIP(), []int{152} } // Terminal-delivery completion reported after all expected foreground SSH @@ -10117,7 +10910,7 @@ type FinalizeMainProcessExitRequest struct { func (x *FinalizeMainProcessExitRequest) Reset() { *x = FinalizeMainProcessExitRequest{} - mi := &file_openshell_proto_msgTypes[139] + mi := &file_openshell_proto_msgTypes[153] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10129,7 +10922,7 @@ func (x *FinalizeMainProcessExitRequest) String() string { func (*FinalizeMainProcessExitRequest) ProtoMessage() {} func (x *FinalizeMainProcessExitRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[139] + mi := &file_openshell_proto_msgTypes[153] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10142,7 +10935,7 @@ func (x *FinalizeMainProcessExitRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use FinalizeMainProcessExitRequest.ProtoReflect.Descriptor instead. func (*FinalizeMainProcessExitRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{139} + return file_openshell_proto_rawDescGZIP(), []int{153} } func (x *FinalizeMainProcessExitRequest) GetSandboxId() string { @@ -10167,7 +10960,7 @@ type FinalizeMainProcessExitResponse struct { func (x *FinalizeMainProcessExitResponse) Reset() { *x = FinalizeMainProcessExitResponse{} - mi := &file_openshell_proto_msgTypes[140] + mi := &file_openshell_proto_msgTypes[154] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10179,7 +10972,7 @@ func (x *FinalizeMainProcessExitResponse) String() string { func (*FinalizeMainProcessExitResponse) ProtoMessage() {} func (x *FinalizeMainProcessExitResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[140] + mi := &file_openshell_proto_msgTypes[154] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10192,7 +10985,7 @@ func (x *FinalizeMainProcessExitResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use FinalizeMainProcessExitResponse.ProtoReflect.Descriptor instead. func (*FinalizeMainProcessExitResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{140} + return file_openshell_proto_rawDescGZIP(), []int{154} } // Gateway requests the supervisor to open a relay channel. @@ -10221,7 +11014,7 @@ type RelayOpen struct { func (x *RelayOpen) Reset() { *x = RelayOpen{} - mi := &file_openshell_proto_msgTypes[141] + mi := &file_openshell_proto_msgTypes[155] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10233,7 +11026,7 @@ func (x *RelayOpen) String() string { func (*RelayOpen) ProtoMessage() {} func (x *RelayOpen) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[141] + mi := &file_openshell_proto_msgTypes[155] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10246,7 +11039,7 @@ func (x *RelayOpen) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayOpen.ProtoReflect.Descriptor instead. func (*RelayOpen) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{141} + return file_openshell_proto_rawDescGZIP(), []int{155} } func (x *RelayOpen) GetChannelId() string { @@ -10313,7 +11106,7 @@ type SshRelayTarget struct { func (x *SshRelayTarget) Reset() { *x = SshRelayTarget{} - mi := &file_openshell_proto_msgTypes[142] + mi := &file_openshell_proto_msgTypes[156] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10325,7 +11118,7 @@ func (x *SshRelayTarget) String() string { func (*SshRelayTarget) ProtoMessage() {} func (x *SshRelayTarget) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[142] + mi := &file_openshell_proto_msgTypes[156] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10338,7 +11131,7 @@ func (x *SshRelayTarget) ProtoReflect() protoreflect.Message { // Deprecated: Use SshRelayTarget.ProtoReflect.Descriptor instead. func (*SshRelayTarget) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{142} + return file_openshell_proto_rawDescGZIP(), []int{156} } // TCP target dialed by the supervisor from inside the sandbox. @@ -10354,7 +11147,7 @@ type TcpRelayTarget struct { func (x *TcpRelayTarget) Reset() { *x = TcpRelayTarget{} - mi := &file_openshell_proto_msgTypes[143] + mi := &file_openshell_proto_msgTypes[157] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10366,7 +11159,7 @@ func (x *TcpRelayTarget) String() string { func (*TcpRelayTarget) ProtoMessage() {} func (x *TcpRelayTarget) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[143] + mi := &file_openshell_proto_msgTypes[157] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10379,7 +11172,7 @@ func (x *TcpRelayTarget) ProtoReflect() protoreflect.Message { // Deprecated: Use TcpRelayTarget.ProtoReflect.Descriptor instead. func (*TcpRelayTarget) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{143} + return file_openshell_proto_rawDescGZIP(), []int{157} } func (x *TcpRelayTarget) GetHost() string { @@ -10407,7 +11200,7 @@ type RelayInit struct { func (x *RelayInit) Reset() { *x = RelayInit{} - mi := &file_openshell_proto_msgTypes[144] + mi := &file_openshell_proto_msgTypes[158] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10419,7 +11212,7 @@ func (x *RelayInit) String() string { func (*RelayInit) ProtoMessage() {} func (x *RelayInit) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[144] + mi := &file_openshell_proto_msgTypes[158] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10432,7 +11225,7 @@ func (x *RelayInit) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayInit.ProtoReflect.Descriptor instead. func (*RelayInit) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{144} + return file_openshell_proto_rawDescGZIP(), []int{158} } func (x *RelayInit) GetChannelId() string { @@ -10459,7 +11252,7 @@ type RelayFrame struct { func (x *RelayFrame) Reset() { *x = RelayFrame{} - mi := &file_openshell_proto_msgTypes[145] + mi := &file_openshell_proto_msgTypes[159] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10471,7 +11264,7 @@ func (x *RelayFrame) String() string { func (*RelayFrame) ProtoMessage() {} func (x *RelayFrame) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[145] + mi := &file_openshell_proto_msgTypes[159] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10484,7 +11277,7 @@ func (x *RelayFrame) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayFrame.ProtoReflect.Descriptor instead. func (*RelayFrame) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{145} + return file_openshell_proto_rawDescGZIP(), []int{159} } func (x *RelayFrame) GetPayload() isRelayFrame_Payload { @@ -10543,7 +11336,7 @@ type RelayOpenResult struct { func (x *RelayOpenResult) Reset() { *x = RelayOpenResult{} - mi := &file_openshell_proto_msgTypes[146] + mi := &file_openshell_proto_msgTypes[160] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10555,7 +11348,7 @@ func (x *RelayOpenResult) String() string { func (*RelayOpenResult) ProtoMessage() {} func (x *RelayOpenResult) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[146] + mi := &file_openshell_proto_msgTypes[160] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10568,7 +11361,7 @@ func (x *RelayOpenResult) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayOpenResult.ProtoReflect.Descriptor instead. func (*RelayOpenResult) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{146} + return file_openshell_proto_rawDescGZIP(), []int{160} } func (x *RelayOpenResult) GetChannelId() string { @@ -10605,7 +11398,7 @@ type RelayClose struct { func (x *RelayClose) Reset() { *x = RelayClose{} - mi := &file_openshell_proto_msgTypes[147] + mi := &file_openshell_proto_msgTypes[161] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10617,7 +11410,7 @@ func (x *RelayClose) String() string { func (*RelayClose) ProtoMessage() {} func (x *RelayClose) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[147] + mi := &file_openshell_proto_msgTypes[161] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10630,7 +11423,7 @@ func (x *RelayClose) ProtoReflect() protoreflect.Message { // Deprecated: Use RelayClose.ProtoReflect.Descriptor instead. func (*RelayClose) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{147} + return file_openshell_proto_rawDescGZIP(), []int{161} } func (x *RelayClose) GetChannelId() string { @@ -10664,7 +11457,7 @@ type L7RequestSample struct { func (x *L7RequestSample) Reset() { *x = L7RequestSample{} - mi := &file_openshell_proto_msgTypes[148] + mi := &file_openshell_proto_msgTypes[162] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10676,7 +11469,7 @@ func (x *L7RequestSample) String() string { func (*L7RequestSample) ProtoMessage() {} func (x *L7RequestSample) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[148] + mi := &file_openshell_proto_msgTypes[162] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10689,7 +11482,7 @@ func (x *L7RequestSample) ProtoReflect() protoreflect.Message { // Deprecated: Use L7RequestSample.ProtoReflect.Descriptor instead. func (*L7RequestSample) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{148} + return file_openshell_proto_rawDescGZIP(), []int{162} } func (x *L7RequestSample) GetMethod() string { @@ -10763,7 +11556,7 @@ type DenialSummary struct { func (x *DenialSummary) Reset() { *x = DenialSummary{} - mi := &file_openshell_proto_msgTypes[149] + mi := &file_openshell_proto_msgTypes[163] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10775,7 +11568,7 @@ func (x *DenialSummary) String() string { func (*DenialSummary) ProtoMessage() {} func (x *DenialSummary) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[149] + mi := &file_openshell_proto_msgTypes[163] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10788,7 +11581,7 @@ func (x *DenialSummary) ProtoReflect() protoreflect.Message { // Deprecated: Use DenialSummary.ProtoReflect.Descriptor instead. func (*DenialSummary) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{149} + return file_openshell_proto_rawDescGZIP(), []int{163} } func (x *DenialSummary) GetSandboxId() string { @@ -10923,7 +11716,7 @@ type DenialGroupCount struct { func (x *DenialGroupCount) Reset() { *x = DenialGroupCount{} - mi := &file_openshell_proto_msgTypes[150] + mi := &file_openshell_proto_msgTypes[164] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10935,7 +11728,7 @@ func (x *DenialGroupCount) String() string { func (*DenialGroupCount) ProtoMessage() {} func (x *DenialGroupCount) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[150] + mi := &file_openshell_proto_msgTypes[164] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -10948,7 +11741,7 @@ func (x *DenialGroupCount) ProtoReflect() protoreflect.Message { // Deprecated: Use DenialGroupCount.ProtoReflect.Descriptor instead. func (*DenialGroupCount) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{150} + return file_openshell_proto_rawDescGZIP(), []int{164} } func (x *DenialGroupCount) GetDenyGroup() string { @@ -10981,7 +11774,7 @@ type NetworkActivitySummary struct { func (x *NetworkActivitySummary) Reset() { *x = NetworkActivitySummary{} - mi := &file_openshell_proto_msgTypes[151] + mi := &file_openshell_proto_msgTypes[165] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -10993,7 +11786,7 @@ func (x *NetworkActivitySummary) String() string { func (*NetworkActivitySummary) ProtoMessage() {} func (x *NetworkActivitySummary) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[151] + mi := &file_openshell_proto_msgTypes[165] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11006,7 +11799,7 @@ func (x *NetworkActivitySummary) ProtoReflect() protoreflect.Message { // Deprecated: Use NetworkActivitySummary.ProtoReflect.Descriptor instead. func (*NetworkActivitySummary) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{151} + return file_openshell_proto_rawDescGZIP(), []int{165} } func (x *NetworkActivitySummary) GetNetworkActivityCount() uint32 { @@ -11094,7 +11887,7 @@ type PolicyChunk struct { func (x *PolicyChunk) Reset() { *x = PolicyChunk{} - mi := &file_openshell_proto_msgTypes[152] + mi := &file_openshell_proto_msgTypes[166] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11106,7 +11899,7 @@ func (x *PolicyChunk) String() string { func (*PolicyChunk) ProtoMessage() {} func (x *PolicyChunk) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[152] + mi := &file_openshell_proto_msgTypes[166] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11119,7 +11912,7 @@ func (x *PolicyChunk) ProtoReflect() protoreflect.Message { // Deprecated: Use PolicyChunk.ProtoReflect.Descriptor instead. func (*PolicyChunk) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{152} + return file_openshell_proto_rawDescGZIP(), []int{166} } func (x *PolicyChunk) GetId() string { @@ -11307,7 +12100,7 @@ type DraftPolicyUpdate struct { func (x *DraftPolicyUpdate) Reset() { *x = DraftPolicyUpdate{} - mi := &file_openshell_proto_msgTypes[153] + mi := &file_openshell_proto_msgTypes[167] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11319,7 +12112,7 @@ func (x *DraftPolicyUpdate) String() string { func (*DraftPolicyUpdate) ProtoMessage() {} func (x *DraftPolicyUpdate) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[153] + mi := &file_openshell_proto_msgTypes[167] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11332,7 +12125,7 @@ func (x *DraftPolicyUpdate) ProtoReflect() protoreflect.Message { // Deprecated: Use DraftPolicyUpdate.ProtoReflect.Descriptor instead. func (*DraftPolicyUpdate) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{153} + return file_openshell_proto_rawDescGZIP(), []int{167} } func (x *DraftPolicyUpdate) GetDraftVersion() uint64 { @@ -11390,7 +12183,7 @@ type SubmitPolicyAnalysisRequest struct { func (x *SubmitPolicyAnalysisRequest) Reset() { *x = SubmitPolicyAnalysisRequest{} - mi := &file_openshell_proto_msgTypes[154] + mi := &file_openshell_proto_msgTypes[168] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11402,7 +12195,7 @@ func (x *SubmitPolicyAnalysisRequest) String() string { func (*SubmitPolicyAnalysisRequest) ProtoMessage() {} func (x *SubmitPolicyAnalysisRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[154] + mi := &file_openshell_proto_msgTypes[168] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11415,7 +12208,7 @@ func (x *SubmitPolicyAnalysisRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SubmitPolicyAnalysisRequest.ProtoReflect.Descriptor instead. func (*SubmitPolicyAnalysisRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{154} + return file_openshell_proto_rawDescGZIP(), []int{168} } func (x *SubmitPolicyAnalysisRequest) GetSummaries() []*DenialSummary { @@ -11478,7 +12271,7 @@ type SubmitPolicyAnalysisResponse struct { func (x *SubmitPolicyAnalysisResponse) Reset() { *x = SubmitPolicyAnalysisResponse{} - mi := &file_openshell_proto_msgTypes[155] + mi := &file_openshell_proto_msgTypes[169] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11490,7 +12283,7 @@ func (x *SubmitPolicyAnalysisResponse) String() string { func (*SubmitPolicyAnalysisResponse) ProtoMessage() {} func (x *SubmitPolicyAnalysisResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[155] + mi := &file_openshell_proto_msgTypes[169] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11503,7 +12296,7 @@ func (x *SubmitPolicyAnalysisResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SubmitPolicyAnalysisResponse.ProtoReflect.Descriptor instead. func (*SubmitPolicyAnalysisResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{155} + return file_openshell_proto_rawDescGZIP(), []int{169} } func (x *SubmitPolicyAnalysisResponse) GetAcceptedChunks() uint32 { @@ -11549,7 +12342,7 @@ type GetDraftPolicyRequest struct { func (x *GetDraftPolicyRequest) Reset() { *x = GetDraftPolicyRequest{} - mi := &file_openshell_proto_msgTypes[156] + mi := &file_openshell_proto_msgTypes[170] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11561,7 +12354,7 @@ func (x *GetDraftPolicyRequest) String() string { func (*GetDraftPolicyRequest) ProtoMessage() {} func (x *GetDraftPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[156] + mi := &file_openshell_proto_msgTypes[170] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11574,7 +12367,7 @@ func (x *GetDraftPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftPolicyRequest.ProtoReflect.Descriptor instead. func (*GetDraftPolicyRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{156} + return file_openshell_proto_rawDescGZIP(), []int{170} } func (x *GetDraftPolicyRequest) GetName() string { @@ -11614,7 +12407,7 @@ type GetDraftPolicyResponse struct { func (x *GetDraftPolicyResponse) Reset() { *x = GetDraftPolicyResponse{} - mi := &file_openshell_proto_msgTypes[157] + mi := &file_openshell_proto_msgTypes[171] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11626,7 +12419,7 @@ func (x *GetDraftPolicyResponse) String() string { func (*GetDraftPolicyResponse) ProtoMessage() {} func (x *GetDraftPolicyResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[157] + mi := &file_openshell_proto_msgTypes[171] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11639,7 +12432,7 @@ func (x *GetDraftPolicyResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftPolicyResponse.ProtoReflect.Descriptor instead. func (*GetDraftPolicyResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{157} + return file_openshell_proto_rawDescGZIP(), []int{171} } func (x *GetDraftPolicyResponse) GetChunks() []*PolicyChunk { @@ -11688,7 +12481,7 @@ type ApproveDraftChunkRequest struct { func (x *ApproveDraftChunkRequest) Reset() { *x = ApproveDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[158] + mi := &file_openshell_proto_msgTypes[172] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11700,7 +12493,7 @@ func (x *ApproveDraftChunkRequest) String() string { func (*ApproveDraftChunkRequest) ProtoMessage() {} func (x *ApproveDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[158] + mi := &file_openshell_proto_msgTypes[172] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11713,7 +12506,7 @@ func (x *ApproveDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveDraftChunkRequest.ProtoReflect.Descriptor instead. func (*ApproveDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{158} + return file_openshell_proto_rawDescGZIP(), []int{172} } func (x *ApproveDraftChunkRequest) GetName() string { @@ -11756,7 +12549,7 @@ type ApproveDraftChunkResponse struct { func (x *ApproveDraftChunkResponse) Reset() { *x = ApproveDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[159] + mi := &file_openshell_proto_msgTypes[173] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11768,7 +12561,7 @@ func (x *ApproveDraftChunkResponse) String() string { func (*ApproveDraftChunkResponse) ProtoMessage() {} func (x *ApproveDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[159] + mi := &file_openshell_proto_msgTypes[173] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11781,7 +12574,7 @@ func (x *ApproveDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveDraftChunkResponse.ProtoReflect.Descriptor instead. func (*ApproveDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{159} + return file_openshell_proto_rawDescGZIP(), []int{173} } func (x *ApproveDraftChunkResponse) GetPolicyVersion() uint32 { @@ -11815,7 +12608,7 @@ type RejectDraftChunkRequest struct { func (x *RejectDraftChunkRequest) Reset() { *x = RejectDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[160] + mi := &file_openshell_proto_msgTypes[174] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11827,7 +12620,7 @@ func (x *RejectDraftChunkRequest) String() string { func (*RejectDraftChunkRequest) ProtoMessage() {} func (x *RejectDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[160] + mi := &file_openshell_proto_msgTypes[174] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11840,7 +12633,7 @@ func (x *RejectDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RejectDraftChunkRequest.ProtoReflect.Descriptor instead. func (*RejectDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{160} + return file_openshell_proto_rawDescGZIP(), []int{174} } func (x *RejectDraftChunkRequest) GetName() string { @@ -11879,7 +12672,7 @@ type RejectDraftChunkResponse struct { func (x *RejectDraftChunkResponse) Reset() { *x = RejectDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[161] + mi := &file_openshell_proto_msgTypes[175] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11891,7 +12684,7 @@ func (x *RejectDraftChunkResponse) String() string { func (*RejectDraftChunkResponse) ProtoMessage() {} func (x *RejectDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[161] + mi := &file_openshell_proto_msgTypes[175] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11904,7 +12697,7 @@ func (x *RejectDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RejectDraftChunkResponse.ProtoReflect.Descriptor instead. func (*RejectDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{161} + return file_openshell_proto_rawDescGZIP(), []int{175} } // Approve all pending chunks. @@ -11918,7 +12711,7 @@ type DraftChunkApproval struct { func (x *DraftChunkApproval) Reset() { *x = DraftChunkApproval{} - mi := &file_openshell_proto_msgTypes[162] + mi := &file_openshell_proto_msgTypes[176] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11930,7 +12723,7 @@ func (x *DraftChunkApproval) String() string { func (*DraftChunkApproval) ProtoMessage() {} func (x *DraftChunkApproval) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[162] + mi := &file_openshell_proto_msgTypes[176] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -11943,7 +12736,7 @@ func (x *DraftChunkApproval) ProtoReflect() protoreflect.Message { // Deprecated: Use DraftChunkApproval.ProtoReflect.Descriptor instead. func (*DraftChunkApproval) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{162} + return file_openshell_proto_rawDescGZIP(), []int{176} } func (x *DraftChunkApproval) GetChunkId() string { @@ -11977,7 +12770,7 @@ type ApproveAllDraftChunksRequest struct { func (x *ApproveAllDraftChunksRequest) Reset() { *x = ApproveAllDraftChunksRequest{} - mi := &file_openshell_proto_msgTypes[163] + mi := &file_openshell_proto_msgTypes[177] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -11989,7 +12782,7 @@ func (x *ApproveAllDraftChunksRequest) String() string { func (*ApproveAllDraftChunksRequest) ProtoMessage() {} func (x *ApproveAllDraftChunksRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[163] + mi := &file_openshell_proto_msgTypes[177] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12002,7 +12795,7 @@ func (x *ApproveAllDraftChunksRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveAllDraftChunksRequest.ProtoReflect.Descriptor instead. func (*ApproveAllDraftChunksRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{163} + return file_openshell_proto_rawDescGZIP(), []int{177} } func (x *ApproveAllDraftChunksRequest) GetName() string { @@ -12050,7 +12843,7 @@ type ApproveAllDraftChunksResponse struct { func (x *ApproveAllDraftChunksResponse) Reset() { *x = ApproveAllDraftChunksResponse{} - mi := &file_openshell_proto_msgTypes[164] + mi := &file_openshell_proto_msgTypes[178] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12062,7 +12855,7 @@ func (x *ApproveAllDraftChunksResponse) String() string { func (*ApproveAllDraftChunksResponse) ProtoMessage() {} func (x *ApproveAllDraftChunksResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[164] + mi := &file_openshell_proto_msgTypes[178] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12075,7 +12868,7 @@ func (x *ApproveAllDraftChunksResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ApproveAllDraftChunksResponse.ProtoReflect.Descriptor instead. func (*ApproveAllDraftChunksResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{164} + return file_openshell_proto_rawDescGZIP(), []int{178} } func (x *ApproveAllDraftChunksResponse) GetPolicyVersion() uint32 { @@ -12123,7 +12916,7 @@ type EditDraftChunkRequest struct { func (x *EditDraftChunkRequest) Reset() { *x = EditDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[165] + mi := &file_openshell_proto_msgTypes[179] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12135,7 +12928,7 @@ func (x *EditDraftChunkRequest) String() string { func (*EditDraftChunkRequest) ProtoMessage() {} func (x *EditDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[165] + mi := &file_openshell_proto_msgTypes[179] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12148,7 +12941,7 @@ func (x *EditDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use EditDraftChunkRequest.ProtoReflect.Descriptor instead. func (*EditDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{165} + return file_openshell_proto_rawDescGZIP(), []int{179} } func (x *EditDraftChunkRequest) GetName() string { @@ -12187,7 +12980,7 @@ type EditDraftChunkResponse struct { func (x *EditDraftChunkResponse) Reset() { *x = EditDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[166] + mi := &file_openshell_proto_msgTypes[180] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12199,7 +12992,7 @@ func (x *EditDraftChunkResponse) String() string { func (*EditDraftChunkResponse) ProtoMessage() {} func (x *EditDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[166] + mi := &file_openshell_proto_msgTypes[180] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12212,7 +13005,7 @@ func (x *EditDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use EditDraftChunkResponse.ProtoReflect.Descriptor instead. func (*EditDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{166} + return file_openshell_proto_rawDescGZIP(), []int{180} } // Reverse an approval (remove merged rule from active policy). @@ -12230,7 +13023,7 @@ type UndoDraftChunkRequest struct { func (x *UndoDraftChunkRequest) Reset() { *x = UndoDraftChunkRequest{} - mi := &file_openshell_proto_msgTypes[167] + mi := &file_openshell_proto_msgTypes[181] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12242,7 +13035,7 @@ func (x *UndoDraftChunkRequest) String() string { func (*UndoDraftChunkRequest) ProtoMessage() {} func (x *UndoDraftChunkRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[167] + mi := &file_openshell_proto_msgTypes[181] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12255,7 +13048,7 @@ func (x *UndoDraftChunkRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UndoDraftChunkRequest.ProtoReflect.Descriptor instead. func (*UndoDraftChunkRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{167} + return file_openshell_proto_rawDescGZIP(), []int{181} } func (x *UndoDraftChunkRequest) GetName() string { @@ -12291,7 +13084,7 @@ type UndoDraftChunkResponse struct { func (x *UndoDraftChunkResponse) Reset() { *x = UndoDraftChunkResponse{} - mi := &file_openshell_proto_msgTypes[168] + mi := &file_openshell_proto_msgTypes[182] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12303,7 +13096,7 @@ func (x *UndoDraftChunkResponse) String() string { func (*UndoDraftChunkResponse) ProtoMessage() {} func (x *UndoDraftChunkResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[168] + mi := &file_openshell_proto_msgTypes[182] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12316,7 +13109,7 @@ func (x *UndoDraftChunkResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use UndoDraftChunkResponse.ProtoReflect.Descriptor instead. func (*UndoDraftChunkResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{168} + return file_openshell_proto_rawDescGZIP(), []int{182} } func (x *UndoDraftChunkResponse) GetPolicyVersion() uint32 { @@ -12346,7 +13139,7 @@ type ClearDraftChunksRequest struct { func (x *ClearDraftChunksRequest) Reset() { *x = ClearDraftChunksRequest{} - mi := &file_openshell_proto_msgTypes[169] + mi := &file_openshell_proto_msgTypes[183] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12358,7 +13151,7 @@ func (x *ClearDraftChunksRequest) String() string { func (*ClearDraftChunksRequest) ProtoMessage() {} func (x *ClearDraftChunksRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[169] + mi := &file_openshell_proto_msgTypes[183] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12371,7 +13164,7 @@ func (x *ClearDraftChunksRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ClearDraftChunksRequest.ProtoReflect.Descriptor instead. func (*ClearDraftChunksRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{169} + return file_openshell_proto_rawDescGZIP(), []int{183} } func (x *ClearDraftChunksRequest) GetName() string { @@ -12398,7 +13191,7 @@ type ClearDraftChunksResponse struct { func (x *ClearDraftChunksResponse) Reset() { *x = ClearDraftChunksResponse{} - mi := &file_openshell_proto_msgTypes[170] + mi := &file_openshell_proto_msgTypes[184] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12410,7 +13203,7 @@ func (x *ClearDraftChunksResponse) String() string { func (*ClearDraftChunksResponse) ProtoMessage() {} func (x *ClearDraftChunksResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[170] + mi := &file_openshell_proto_msgTypes[184] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12423,7 +13216,7 @@ func (x *ClearDraftChunksResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ClearDraftChunksResponse.ProtoReflect.Descriptor instead. func (*ClearDraftChunksResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{170} + return file_openshell_proto_rawDescGZIP(), []int{184} } func (x *ClearDraftChunksResponse) GetChunksCleared() uint32 { @@ -12446,7 +13239,7 @@ type GetDraftHistoryRequest struct { func (x *GetDraftHistoryRequest) Reset() { *x = GetDraftHistoryRequest{} - mi := &file_openshell_proto_msgTypes[171] + mi := &file_openshell_proto_msgTypes[185] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12458,7 +13251,7 @@ func (x *GetDraftHistoryRequest) String() string { func (*GetDraftHistoryRequest) ProtoMessage() {} func (x *GetDraftHistoryRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[171] + mi := &file_openshell_proto_msgTypes[185] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12471,7 +13264,7 @@ func (x *GetDraftHistoryRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftHistoryRequest.ProtoReflect.Descriptor instead. func (*GetDraftHistoryRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{171} + return file_openshell_proto_rawDescGZIP(), []int{185} } func (x *GetDraftHistoryRequest) GetName() string { @@ -12505,7 +13298,7 @@ type DraftHistoryEntry struct { func (x *DraftHistoryEntry) Reset() { *x = DraftHistoryEntry{} - mi := &file_openshell_proto_msgTypes[172] + mi := &file_openshell_proto_msgTypes[186] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12517,7 +13310,7 @@ func (x *DraftHistoryEntry) String() string { func (*DraftHistoryEntry) ProtoMessage() {} func (x *DraftHistoryEntry) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[172] + mi := &file_openshell_proto_msgTypes[186] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12530,7 +13323,7 @@ func (x *DraftHistoryEntry) ProtoReflect() protoreflect.Message { // Deprecated: Use DraftHistoryEntry.ProtoReflect.Descriptor instead. func (*DraftHistoryEntry) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{172} + return file_openshell_proto_rawDescGZIP(), []int{186} } func (x *DraftHistoryEntry) GetTimestampMs() int64 { @@ -12571,7 +13364,7 @@ type GetDraftHistoryResponse struct { func (x *GetDraftHistoryResponse) Reset() { *x = GetDraftHistoryResponse{} - mi := &file_openshell_proto_msgTypes[173] + mi := &file_openshell_proto_msgTypes[187] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12583,7 +13376,7 @@ func (x *GetDraftHistoryResponse) String() string { func (*GetDraftHistoryResponse) ProtoMessage() {} func (x *GetDraftHistoryResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[173] + mi := &file_openshell_proto_msgTypes[187] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12596,7 +13389,7 @@ func (x *GetDraftHistoryResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetDraftHistoryResponse.ProtoReflect.Descriptor instead. func (*GetDraftHistoryResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{173} + return file_openshell_proto_rawDescGZIP(), []int{187} } func (x *GetDraftHistoryResponse) GetEntries() []*DraftHistoryEntry { @@ -12625,7 +13418,7 @@ type PolicyRevisionPayload struct { func (x *PolicyRevisionPayload) Reset() { *x = PolicyRevisionPayload{} - mi := &file_openshell_proto_msgTypes[174] + mi := &file_openshell_proto_msgTypes[188] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12637,7 +13430,7 @@ func (x *PolicyRevisionPayload) String() string { func (*PolicyRevisionPayload) ProtoMessage() {} func (x *PolicyRevisionPayload) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[174] + mi := &file_openshell_proto_msgTypes[188] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12650,7 +13443,7 @@ func (x *PolicyRevisionPayload) ProtoReflect() protoreflect.Message { // Deprecated: Use PolicyRevisionPayload.ProtoReflect.Descriptor instead. func (*PolicyRevisionPayload) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{174} + return file_openshell_proto_rawDescGZIP(), []int{188} } func (x *PolicyRevisionPayload) GetPolicy() *sandboxv1.SandboxPolicy { @@ -12729,7 +13522,7 @@ type DraftChunkPayload struct { func (x *DraftChunkPayload) Reset() { *x = DraftChunkPayload{} - mi := &file_openshell_proto_msgTypes[175] + mi := &file_openshell_proto_msgTypes[189] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12741,7 +13534,7 @@ func (x *DraftChunkPayload) String() string { func (*DraftChunkPayload) ProtoMessage() {} func (x *DraftChunkPayload) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[175] + mi := &file_openshell_proto_msgTypes[189] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12754,7 +13547,7 @@ func (x *DraftChunkPayload) ProtoReflect() protoreflect.Message { // Deprecated: Use DraftChunkPayload.ProtoReflect.Descriptor instead. func (*DraftChunkPayload) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{175} + return file_openshell_proto_rawDescGZIP(), []int{189} } func (x *DraftChunkPayload) GetRuleName() string { @@ -12902,7 +13695,7 @@ type StoredPolicyRevision struct { func (x *StoredPolicyRevision) Reset() { *x = StoredPolicyRevision{} - mi := &file_openshell_proto_msgTypes[176] + mi := &file_openshell_proto_msgTypes[190] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -12914,7 +13707,7 @@ func (x *StoredPolicyRevision) String() string { func (*StoredPolicyRevision) ProtoMessage() {} func (x *StoredPolicyRevision) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[176] + mi := &file_openshell_proto_msgTypes[190] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -12927,7 +13720,7 @@ func (x *StoredPolicyRevision) ProtoReflect() protoreflect.Message { // Deprecated: Use StoredPolicyRevision.ProtoReflect.Descriptor instead. func (*StoredPolicyRevision) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{176} + return file_openshell_proto_rawDescGZIP(), []int{190} } func (x *StoredPolicyRevision) GetId() string { @@ -13036,7 +13829,7 @@ type StoredDraftChunk struct { func (x *StoredDraftChunk) Reset() { *x = StoredDraftChunk{} - mi := &file_openshell_proto_msgTypes[177] + mi := &file_openshell_proto_msgTypes[191] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13048,7 +13841,7 @@ func (x *StoredDraftChunk) String() string { func (*StoredDraftChunk) ProtoMessage() {} func (x *StoredDraftChunk) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[177] + mi := &file_openshell_proto_msgTypes[191] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13061,7 +13854,7 @@ func (x *StoredDraftChunk) ProtoReflect() protoreflect.Message { // Deprecated: Use StoredDraftChunk.ProtoReflect.Descriptor instead. func (*StoredDraftChunk) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{177} + return file_openshell_proto_rawDescGZIP(), []int{191} } func (x *StoredDraftChunk) GetId() string { @@ -13252,7 +14045,7 @@ type CreateWorkspaceRequest struct { func (x *CreateWorkspaceRequest) Reset() { *x = CreateWorkspaceRequest{} - mi := &file_openshell_proto_msgTypes[178] + mi := &file_openshell_proto_msgTypes[192] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13264,7 +14057,7 @@ func (x *CreateWorkspaceRequest) String() string { func (*CreateWorkspaceRequest) ProtoMessage() {} func (x *CreateWorkspaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[178] + mi := &file_openshell_proto_msgTypes[192] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13277,7 +14070,7 @@ func (x *CreateWorkspaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateWorkspaceRequest.ProtoReflect.Descriptor instead. func (*CreateWorkspaceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{178} + return file_openshell_proto_rawDescGZIP(), []int{192} } func (x *CreateWorkspaceRequest) GetName() string { @@ -13304,7 +14097,7 @@ type CreateWorkspaceResponse struct { func (x *CreateWorkspaceResponse) Reset() { *x = CreateWorkspaceResponse{} - mi := &file_openshell_proto_msgTypes[179] + mi := &file_openshell_proto_msgTypes[193] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13316,7 +14109,7 @@ func (x *CreateWorkspaceResponse) String() string { func (*CreateWorkspaceResponse) ProtoMessage() {} func (x *CreateWorkspaceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[179] + mi := &file_openshell_proto_msgTypes[193] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13329,7 +14122,7 @@ func (x *CreateWorkspaceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateWorkspaceResponse.ProtoReflect.Descriptor instead. func (*CreateWorkspaceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{179} + return file_openshell_proto_rawDescGZIP(), []int{193} } func (x *CreateWorkspaceResponse) GetWorkspace() *datamodelv1.Workspace { @@ -13350,7 +14143,7 @@ type GetWorkspaceRequest struct { func (x *GetWorkspaceRequest) Reset() { *x = GetWorkspaceRequest{} - mi := &file_openshell_proto_msgTypes[180] + mi := &file_openshell_proto_msgTypes[194] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13362,7 +14155,7 @@ func (x *GetWorkspaceRequest) String() string { func (*GetWorkspaceRequest) ProtoMessage() {} func (x *GetWorkspaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[180] + mi := &file_openshell_proto_msgTypes[194] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13375,7 +14168,7 @@ func (x *GetWorkspaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetWorkspaceRequest.ProtoReflect.Descriptor instead. func (*GetWorkspaceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{180} + return file_openshell_proto_rawDescGZIP(), []int{194} } func (x *GetWorkspaceRequest) GetName() string { @@ -13395,7 +14188,7 @@ type GetWorkspaceResponse struct { func (x *GetWorkspaceResponse) Reset() { *x = GetWorkspaceResponse{} - mi := &file_openshell_proto_msgTypes[181] + mi := &file_openshell_proto_msgTypes[195] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13407,7 +14200,7 @@ func (x *GetWorkspaceResponse) String() string { func (*GetWorkspaceResponse) ProtoMessage() {} func (x *GetWorkspaceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[181] + mi := &file_openshell_proto_msgTypes[195] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13420,7 +14213,7 @@ func (x *GetWorkspaceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use GetWorkspaceResponse.ProtoReflect.Descriptor instead. func (*GetWorkspaceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{181} + return file_openshell_proto_rawDescGZIP(), []int{195} } func (x *GetWorkspaceResponse) GetWorkspace() *datamodelv1.Workspace { @@ -13443,7 +14236,7 @@ type ListWorkspacesRequest struct { func (x *ListWorkspacesRequest) Reset() { *x = ListWorkspacesRequest{} - mi := &file_openshell_proto_msgTypes[182] + mi := &file_openshell_proto_msgTypes[196] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13455,7 +14248,7 @@ func (x *ListWorkspacesRequest) String() string { func (*ListWorkspacesRequest) ProtoMessage() {} func (x *ListWorkspacesRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[182] + mi := &file_openshell_proto_msgTypes[196] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13468,7 +14261,7 @@ func (x *ListWorkspacesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspacesRequest.ProtoReflect.Descriptor instead. func (*ListWorkspacesRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{182} + return file_openshell_proto_rawDescGZIP(), []int{196} } func (x *ListWorkspacesRequest) GetLimit() uint32 { @@ -13502,7 +14295,7 @@ type ListWorkspacesResponse struct { func (x *ListWorkspacesResponse) Reset() { *x = ListWorkspacesResponse{} - mi := &file_openshell_proto_msgTypes[183] + mi := &file_openshell_proto_msgTypes[197] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13514,7 +14307,7 @@ func (x *ListWorkspacesResponse) String() string { func (*ListWorkspacesResponse) ProtoMessage() {} func (x *ListWorkspacesResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[183] + mi := &file_openshell_proto_msgTypes[197] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13527,7 +14320,7 @@ func (x *ListWorkspacesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspacesResponse.ProtoReflect.Descriptor instead. func (*ListWorkspacesResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{183} + return file_openshell_proto_rawDescGZIP(), []int{197} } func (x *ListWorkspacesResponse) GetWorkspaces() []*datamodelv1.Workspace { @@ -13548,7 +14341,7 @@ type DeleteWorkspaceRequest struct { func (x *DeleteWorkspaceRequest) Reset() { *x = DeleteWorkspaceRequest{} - mi := &file_openshell_proto_msgTypes[184] + mi := &file_openshell_proto_msgTypes[198] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13560,7 +14353,7 @@ func (x *DeleteWorkspaceRequest) String() string { func (*DeleteWorkspaceRequest) ProtoMessage() {} func (x *DeleteWorkspaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[184] + mi := &file_openshell_proto_msgTypes[198] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13573,7 +14366,7 @@ func (x *DeleteWorkspaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteWorkspaceRequest.ProtoReflect.Descriptor instead. func (*DeleteWorkspaceRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{184} + return file_openshell_proto_rawDescGZIP(), []int{198} } func (x *DeleteWorkspaceRequest) GetName() string { @@ -13593,7 +14386,7 @@ type DeleteWorkspaceResponse struct { func (x *DeleteWorkspaceResponse) Reset() { *x = DeleteWorkspaceResponse{} - mi := &file_openshell_proto_msgTypes[185] + mi := &file_openshell_proto_msgTypes[199] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13605,7 +14398,7 @@ func (x *DeleteWorkspaceResponse) String() string { func (*DeleteWorkspaceResponse) ProtoMessage() {} func (x *DeleteWorkspaceResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[185] + mi := &file_openshell_proto_msgTypes[199] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13618,7 +14411,7 @@ func (x *DeleteWorkspaceResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteWorkspaceResponse.ProtoReflect.Descriptor instead. func (*DeleteWorkspaceResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{185} + return file_openshell_proto_rawDescGZIP(), []int{199} } func (x *DeleteWorkspaceResponse) GetDeleted() bool { @@ -13642,7 +14435,7 @@ type WorkspaceMember struct { func (x *WorkspaceMember) Reset() { *x = WorkspaceMember{} - mi := &file_openshell_proto_msgTypes[186] + mi := &file_openshell_proto_msgTypes[200] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13654,7 +14447,7 @@ func (x *WorkspaceMember) String() string { func (*WorkspaceMember) ProtoMessage() {} func (x *WorkspaceMember) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[186] + mi := &file_openshell_proto_msgTypes[200] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13667,7 +14460,7 @@ func (x *WorkspaceMember) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkspaceMember.ProtoReflect.Descriptor instead. func (*WorkspaceMember) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{186} + return file_openshell_proto_rawDescGZIP(), []int{200} } func (x *WorkspaceMember) GetMetadata() *datamodelv1.ObjectMeta { @@ -13706,7 +14499,7 @@ type AddWorkspaceMemberRequest struct { func (x *AddWorkspaceMemberRequest) Reset() { *x = AddWorkspaceMemberRequest{} - mi := &file_openshell_proto_msgTypes[187] + mi := &file_openshell_proto_msgTypes[201] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13718,7 +14511,7 @@ func (x *AddWorkspaceMemberRequest) String() string { func (*AddWorkspaceMemberRequest) ProtoMessage() {} func (x *AddWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[187] + mi := &file_openshell_proto_msgTypes[201] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13731,7 +14524,7 @@ func (x *AddWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use AddWorkspaceMemberRequest.ProtoReflect.Descriptor instead. func (*AddWorkspaceMemberRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{187} + return file_openshell_proto_rawDescGZIP(), []int{201} } func (x *AddWorkspaceMemberRequest) GetWorkspace() string { @@ -13765,7 +14558,7 @@ type AddWorkspaceMemberResponse struct { func (x *AddWorkspaceMemberResponse) Reset() { *x = AddWorkspaceMemberResponse{} - mi := &file_openshell_proto_msgTypes[188] + mi := &file_openshell_proto_msgTypes[202] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13777,7 +14570,7 @@ func (x *AddWorkspaceMemberResponse) String() string { func (*AddWorkspaceMemberResponse) ProtoMessage() {} func (x *AddWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[188] + mi := &file_openshell_proto_msgTypes[202] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13790,7 +14583,7 @@ func (x *AddWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use AddWorkspaceMemberResponse.ProtoReflect.Descriptor instead. func (*AddWorkspaceMemberResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{188} + return file_openshell_proto_rawDescGZIP(), []int{202} } func (x *AddWorkspaceMemberResponse) GetMember() *WorkspaceMember { @@ -13813,7 +14606,7 @@ type RemoveWorkspaceMemberRequest struct { func (x *RemoveWorkspaceMemberRequest) Reset() { *x = RemoveWorkspaceMemberRequest{} - mi := &file_openshell_proto_msgTypes[189] + mi := &file_openshell_proto_msgTypes[203] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13825,7 +14618,7 @@ func (x *RemoveWorkspaceMemberRequest) String() string { func (*RemoveWorkspaceMemberRequest) ProtoMessage() {} func (x *RemoveWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[189] + mi := &file_openshell_proto_msgTypes[203] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13838,7 +14631,7 @@ func (x *RemoveWorkspaceMemberRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveWorkspaceMemberRequest.ProtoReflect.Descriptor instead. func (*RemoveWorkspaceMemberRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{189} + return file_openshell_proto_rawDescGZIP(), []int{203} } func (x *RemoveWorkspaceMemberRequest) GetWorkspace() string { @@ -13865,7 +14658,7 @@ type RemoveWorkspaceMemberResponse struct { func (x *RemoveWorkspaceMemberResponse) Reset() { *x = RemoveWorkspaceMemberResponse{} - mi := &file_openshell_proto_msgTypes[190] + mi := &file_openshell_proto_msgTypes[204] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13877,7 +14670,7 @@ func (x *RemoveWorkspaceMemberResponse) String() string { func (*RemoveWorkspaceMemberResponse) ProtoMessage() {} func (x *RemoveWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[190] + mi := &file_openshell_proto_msgTypes[204] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13890,7 +14683,7 @@ func (x *RemoveWorkspaceMemberResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RemoveWorkspaceMemberResponse.ProtoReflect.Descriptor instead. func (*RemoveWorkspaceMemberResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{190} + return file_openshell_proto_rawDescGZIP(), []int{204} } func (x *RemoveWorkspaceMemberResponse) GetRemoved() bool { @@ -13913,7 +14706,7 @@ type ListWorkspaceMembersRequest struct { func (x *ListWorkspaceMembersRequest) Reset() { *x = ListWorkspaceMembersRequest{} - mi := &file_openshell_proto_msgTypes[191] + mi := &file_openshell_proto_msgTypes[205] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13925,7 +14718,7 @@ func (x *ListWorkspaceMembersRequest) String() string { func (*ListWorkspaceMembersRequest) ProtoMessage() {} func (x *ListWorkspaceMembersRequest) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[191] + mi := &file_openshell_proto_msgTypes[205] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13938,7 +14731,7 @@ func (x *ListWorkspaceMembersRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspaceMembersRequest.ProtoReflect.Descriptor instead. func (*ListWorkspaceMembersRequest) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{191} + return file_openshell_proto_rawDescGZIP(), []int{205} } func (x *ListWorkspaceMembersRequest) GetWorkspace() string { @@ -13972,7 +14765,7 @@ type ListWorkspaceMembersResponse struct { func (x *ListWorkspaceMembersResponse) Reset() { *x = ListWorkspaceMembersResponse{} - mi := &file_openshell_proto_msgTypes[192] + mi := &file_openshell_proto_msgTypes[206] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -13984,7 +14777,7 @@ func (x *ListWorkspaceMembersResponse) String() string { func (*ListWorkspaceMembersResponse) ProtoMessage() {} func (x *ListWorkspaceMembersResponse) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[192] + mi := &file_openshell_proto_msgTypes[206] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -13997,7 +14790,7 @@ func (x *ListWorkspaceMembersResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkspaceMembersResponse.ProtoReflect.Descriptor instead. func (*ListWorkspaceMembersResponse) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{192} + return file_openshell_proto_rawDescGZIP(), []int{206} } func (x *ListWorkspaceMembersResponse) GetMembers() []*WorkspaceMember { @@ -14025,7 +14818,7 @@ type ExtensionServiceCredential struct { func (x *ExtensionServiceCredential) Reset() { *x = ExtensionServiceCredential{} - mi := &file_openshell_proto_msgTypes[193] + mi := &file_openshell_proto_msgTypes[207] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -14037,7 +14830,7 @@ func (x *ExtensionServiceCredential) String() string { func (*ExtensionServiceCredential) ProtoMessage() {} func (x *ExtensionServiceCredential) ProtoReflect() protoreflect.Message { - mi := &file_openshell_proto_msgTypes[193] + mi := &file_openshell_proto_msgTypes[207] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -14050,7 +14843,7 @@ func (x *ExtensionServiceCredential) ProtoReflect() protoreflect.Message { // Deprecated: Use ExtensionServiceCredential.ProtoReflect.Descriptor instead. func (*ExtensionServiceCredential) Descriptor() ([]byte, []int) { - return file_openshell_proto_rawDescGZIP(), []int{193} + return file_openshell_proto_rawDescGZIP(), []int{207} } func (x *ExtensionServiceCredential) GetServiceName() string { @@ -14078,7 +14871,7 @@ var File_openshell_proto protoreflect.FileDescriptor const file_openshell_proto_rawDesc = "" + "\n" + - "\x0fopenshell.proto\x12\fopenshell.v1\x1a\x0fdatamodel.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\roptions.proto\x1a\rsandbox.proto\"\x1a\n" + + "\x0fopenshell.proto\x12\fopenshell.v1\x1a\x0fdatamodel.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\roptions.proto\x1a\rsandbox.proto\"\x1a\n" + "\x18IssueSandboxTokenRequest\"[\n" + "\x19IssueSandboxTokenResponse\x12\x1a\n" + "\x05token\x18\x01 \x01(\tB\x04\x88\xb5\x18\x01R\x05token\x12\"\n" + @@ -14111,11 +14904,12 @@ const file_openshell_proto_rawDesc = "" + "\x19ComputeDriverCapabilities\x12\x1f\n" + "\vdriver_name\x18\x01 \x01(\tR\n" + "driverName\x12%\n" + - "\x0edriver_version\x18\x02 \x01(\tR\rdriverVersion\"\xd8\x01\n" + + "\x0edriver_version\x18\x02 \x01(\tR\rdriverVersion\"\xce\x02\n" + "\aSandbox\x12>\n" + "\bmetadata\x18\x01 \x01(\v2\".openshell.datamodel.v1.ObjectMetaR\bmetadata\x12-\n" + "\x04spec\x18\x02 \x01(\v2\x19.openshell.v1.SandboxSpecR\x04spec\x123\n" + - "\x06status\x18\x03 \x01(\v2\x1b.openshell.v1.SandboxStatusR\x06statusJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\x05phaseR\x16current_policy_version\"\x83\x04\n" + + "\x06status\x18\x03 \x01(\v2\x1b.openshell.v1.SandboxStatusR\x06status\x12t\n" + + "\x1ecreated_from_workload_template\x18\x14 \x01(\v2/.openshell.v1.SandboxWorkloadTemplateProvenanceR\x1bcreatedFromWorkloadTemplateJ\x04\b\x04\x10\x05J\x04\b\x05\x10\x06R\x05phaseR\x16current_policy_version\"\x83\x04\n" + "\vSandboxSpec\x12\x1b\n" + "\tlog_level\x18\x01 \x01(\tR\blogLevel\x12L\n" + "\venvironment\x18\x05 \x03(\v2*.openshell.v1.SandboxSpec.EnvironmentEntryR\venvironment\x129\n" + @@ -14156,7 +14950,33 @@ const file_openshell_proto_rawDesc = "" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\x12\n" + "\x10_user_namespacesJ\x04\b\t\x10\n" + - "R\x16volume_claim_templates\"\x9a\x03\n" + + "R\x16volume_claim_templates\"\x98\x01\n" + + "\x17SandboxWorkloadTemplate\x12>\n" + + "\bmetadata\x18\x01 \x01(\v2\".openshell.datamodel.v1.ObjectMetaR\bmetadata\x12=\n" + + "\x04spec\x18\x02 \x01(\v2).openshell.v1.SandboxWorkloadTemplateSpecR\x04spec\"\xf3\x01\n" + + "\x1bSandboxWorkloadTemplateSpec\x12?\n" + + "\bworkload\x18\x01 \x01(\v2#.openshell.v1.SandboxWorkloadConfigR\bworkload\x12<\n" + + "\rdriver_config\x18\x02 \x01(\v2\x17.google.protobuf.StructR\fdriverConfig\x12U\n" + + "\x15desired_service_level\x18\x03 \x01(\v2!.openshell.v1.SandboxServiceLevelR\x13desiredServiceLevel\"\x83\x02\n" + + "\x15SandboxWorkloadConfig\x12\x14\n" + + "\x05image\x18\x01 \x01(\tR\x05image\x12V\n" + + "\venvironment\x18\x02 \x03(\v24.openshell.v1.SandboxWorkloadConfig.EnvironmentEntryR\venvironment\x12<\n" + + "\tresources\x18\x03 \x01(\v2\x1e.openshell.v1.SandboxResourcesR\tresources\x1a>\n" + + "\x10EnvironmentEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"u\n" + + "\x10SandboxResources\x12\x10\n" + + "\x03cpu\x18\x01 \x01(\tR\x03cpu\x12\x16\n" + + "\x06memory\x18\x02 \x01(\tR\x06memory\x127\n" + + "\x03gpu\x18\x03 \x01(\v2%.openshell.v1.GpuResourceRequirementsR\x03gpu\"M\n" + + "\x13SandboxServiceLevel\x126\n" + + "\astartup\x18\x01 \x01(\v2\x1c.openshell.v1.SandboxStartupR\astartup\"k\n" + + "\x0eSandboxStartup\x12<\n" + + "\fready_within\x18\x01 \x01(\v2\x19.google.protobuf.DurationR\vreadyWithin\x12\x1b\n" + + "\tmax_burst\x18\x02 \x01(\rR\bmaxBurst\"b\n" + + "!SandboxWorkloadTemplateProvenance\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12)\n" + + "\x10resource_version\x18\x02 \x01(\tR\x0fresourceVersion\"\x9a\x03\n" + "\rSandboxStatus\x12!\n" + "\fsandbox_name\x18\x01 \x01(\tR\vsandboxName\x12\x1b\n" + "\tagent_pod\x18\x02 \x01(\tR\bagentPod\x12\x19\n" + @@ -14187,20 +15007,42 @@ const file_openshell_proto_rawDesc = "" + "\bmetadata\x18\x06 \x03(\v2).openshell.v1.PlatformEvent.MetadataEntryR\bmetadata\x1a;\n" + "\rMetadataEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xd4\x03\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x8a\x04\n" + "\x14CreateSandboxRequest\x12-\n" + "\x04spec\x18\x01 \x01(\v2\x19.openshell.v1.SandboxSpecR\x04spec\x12\x12\n" + "\x04name\x18\x02 \x01(\tR\x04name\x12F\n" + "\x06labels\x18\x03 \x03(\v2..openshell.v1.CreateSandboxRequest.LabelsEntryR\x06labels\x12U\n" + "\vannotations\x18\x04 \x03(\v23.openshell.v1.CreateSandboxRequest.AnnotationsEntryR\vannotations\x12\x1c\n" + "\tworkspace\x18\x05 \x01(\tR\tworkspace\x12A\n" + - "\x1dawait_main_process_attachment\x18\x06 \x01(\bR\x1aawaitMainProcessAttachment\x1a9\n" + + "\x1dawait_main_process_attachment\x18\x06 \x01(\bR\x1aawaitMainProcessAttachment\x124\n" + + "\x16workload_template_name\x18\a \x01(\tR\x14workloadTemplateName\x1a9\n" + "\vLabelsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\x1a>\n" + "\x10AnnotationsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + - "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"E\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x7f\n" + + "\x1cCreateSandboxTemplateRequest\x12A\n" + + "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\x12\x1c\n" + + "\tworkspace\x18\x02 \x01(\tR\tworkspace\"M\n" + + "\x19GetSandboxTemplateRequest\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + + "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\xb7\x01\n" + + "\x1bListSandboxTemplatesRequest\x12\x14\n" + + "\x05limit\x18\x01 \x01(\rR\x05limit\x12\x16\n" + + "\x06offset\x18\x02 \x01(\rR\x06offset\x12\x1c\n" + + "\tworkspace\x18\x03 \x01(\tR\tworkspace\x12%\n" + + "\x0eall_workspaces\x18\x04 \x01(\bR\rallWorkspaces\x12%\n" + + "\x0elabel_selector\x18\x05 \x01(\tR\rlabelSelector\"P\n" + + "\x1cDeleteSandboxTemplateRequest\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + + "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\\\n" + + "\x17SandboxTemplateResponse\x12A\n" + + "\btemplate\x18\x01 \x01(\v2%.openshell.v1.SandboxWorkloadTemplateR\btemplate\"c\n" + + "\x1cListSandboxTemplatesResponse\x12C\n" + + "\ttemplates\x18\x01 \x03(\v2%.openshell.v1.SandboxWorkloadTemplateR\ttemplates\"9\n" + + "\x1dDeleteSandboxTemplateResponse\x12\x18\n" + + "\adeleted\x18\x01 \x01(\bR\adeleted\"E\n" + "\x11GetSandboxRequest\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12\x1c\n" + "\tworkspace\x18\x02 \x01(\tR\tworkspace\"\xb0\x01\n" + @@ -15211,7 +16053,7 @@ const file_openshell_proto_rawDesc = "" + "1PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_RETRY\x10\x01\x12;\n" + "7PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_REAUTHORIZE\x10\x02\x12A\n" + "=PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_FIX_CONFIGURATION\x10\x03\x12;\n" + - "7PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE\x10\x042\xb4G\n" + + "7PROVIDER_CREDENTIAL_REFRESH_RECOVERY_ACTION_INVESTIGATE\x10\x042\xf7K\n" + "\tOpenShell\x12Z\n" + "\x06Health\x12\x1b.openshell.v1.HealthRequest\x1a\x1c.openshell.v1.HealthResponse\"\x15\x82\xb5\x18\x11\n" + "\x0funauthenticated\x12i\n" + @@ -15225,7 +16067,15 @@ const file_openshell_proto_rawDesc = "" + "GetSandbox\x12\x1f.openshell.v1.GetSandboxRequest\x1a\x1d.openshell.v1.SandboxResponse\" \x82\xb5\x18\x1c\n" + "\x06bearer\x12\x04user\"\fsandbox:read\x12z\n" + "\rListSandboxes\x12\".openshell.v1.ListSandboxesRequest\x1a#.openshell.v1.ListSandboxesResponse\" \x82\xb5\x18\x1c\n" + + "\x06bearer\x12\x04user\"\fsandbox:read\x12\x8e\x01\n" + + "\x15CreateSandboxTemplate\x12*.openshell.v1.CreateSandboxTemplateRequest\x1a%.openshell.v1.SandboxTemplateResponse\"\"\x82\xb5\x18\x1e\n" + + "\x06bearer\x12\x05admin\"\rsandbox:write\x12\x86\x01\n" + + "\x12GetSandboxTemplate\x12'.openshell.v1.GetSandboxTemplateRequest\x1a%.openshell.v1.SandboxTemplateResponse\" \x82\xb5\x18\x1c\n" + "\x06bearer\x12\x04user\"\fsandbox:read\x12\x8f\x01\n" + + "\x14ListSandboxTemplates\x12).openshell.v1.ListSandboxTemplatesRequest\x1a*.openshell.v1.ListSandboxTemplatesResponse\" \x82\xb5\x18\x1c\n" + + "\x06bearer\x12\x04user\"\fsandbox:read\x12\x94\x01\n" + + "\x15DeleteSandboxTemplate\x12*.openshell.v1.DeleteSandboxTemplateRequest\x1a+.openshell.v1.DeleteSandboxTemplateResponse\"\"\x82\xb5\x18\x1e\n" + + "\x06bearer\x12\x05admin\"\rsandbox:write\x12\x8f\x01\n" + "\x14ListSandboxProviders\x12).openshell.v1.ListSandboxProvidersRequest\x1a*.openshell.v1.ListSandboxProvidersResponse\" \x82\xb5\x18\x1c\n" + "\x06bearer\x12\x04user\"\fsandbox:read\x12\x93\x01\n" + "\x15AttachSandboxProvider\x12*.openshell.v1.AttachSandboxProviderRequest\x1a+.openshell.v1.AttachSandboxProviderResponse\"!\x82\xb5\x18\x1d\n" + @@ -15368,7 +16218,7 @@ func file_openshell_proto_rawDescGZIP() []byte { } var file_openshell_proto_enumTypes = make([]protoimpl.EnumInfo, 8) -var file_openshell_proto_msgTypes = make([]protoimpl.MessageInfo, 219) +var file_openshell_proto_msgTypes = make([]protoimpl.MessageInfo, 234) var file_openshell_proto_goTypes = []any{ (SandboxPhase)(0), // 0: openshell.v1.SandboxPhase (ProviderCredentialTokenGrantType)(0), // 1: openshell.v1.ProviderCredentialTokenGrantType @@ -15395,535 +16245,573 @@ var file_openshell_proto_goTypes = []any{ (*ResourceRequirements)(nil), // 22: openshell.v1.ResourceRequirements (*GpuResourceRequirements)(nil), // 23: openshell.v1.GpuResourceRequirements (*SandboxTemplate)(nil), // 24: openshell.v1.SandboxTemplate - (*SandboxStatus)(nil), // 25: openshell.v1.SandboxStatus - (*SandboxCondition)(nil), // 26: openshell.v1.SandboxCondition - (*PlatformEvent)(nil), // 27: openshell.v1.PlatformEvent - (*CreateSandboxRequest)(nil), // 28: openshell.v1.CreateSandboxRequest - (*GetSandboxRequest)(nil), // 29: openshell.v1.GetSandboxRequest - (*ListSandboxesRequest)(nil), // 30: openshell.v1.ListSandboxesRequest - (*ListSandboxProvidersRequest)(nil), // 31: openshell.v1.ListSandboxProvidersRequest - (*AttachSandboxProviderRequest)(nil), // 32: openshell.v1.AttachSandboxProviderRequest - (*DetachSandboxProviderRequest)(nil), // 33: openshell.v1.DetachSandboxProviderRequest - (*DeleteSandboxRequest)(nil), // 34: openshell.v1.DeleteSandboxRequest - (*StopSandboxRequest)(nil), // 35: openshell.v1.StopSandboxRequest - (*StartSandboxRequest)(nil), // 36: openshell.v1.StartSandboxRequest - (*SandboxResponse)(nil), // 37: openshell.v1.SandboxResponse - (*ListSandboxesResponse)(nil), // 38: openshell.v1.ListSandboxesResponse - (*ListSandboxProvidersResponse)(nil), // 39: openshell.v1.ListSandboxProvidersResponse - (*AttachSandboxProviderResponse)(nil), // 40: openshell.v1.AttachSandboxProviderResponse - (*DetachSandboxProviderResponse)(nil), // 41: openshell.v1.DetachSandboxProviderResponse - (*DeleteSandboxResponse)(nil), // 42: openshell.v1.DeleteSandboxResponse - (*CreateSshSessionRequest)(nil), // 43: openshell.v1.CreateSshSessionRequest - (*CreateSshSessionResponse)(nil), // 44: openshell.v1.CreateSshSessionResponse - (*ExposeServiceRequest)(nil), // 45: openshell.v1.ExposeServiceRequest - (*GetServiceRequest)(nil), // 46: openshell.v1.GetServiceRequest - (*ListServicesRequest)(nil), // 47: openshell.v1.ListServicesRequest - (*ListServicesResponse)(nil), // 48: openshell.v1.ListServicesResponse - (*DeleteServiceRequest)(nil), // 49: openshell.v1.DeleteServiceRequest - (*DeleteServiceResponse)(nil), // 50: openshell.v1.DeleteServiceResponse - (*ServiceEndpoint)(nil), // 51: openshell.v1.ServiceEndpoint - (*ServiceEndpointResponse)(nil), // 52: openshell.v1.ServiceEndpointResponse - (*RevokeSshSessionRequest)(nil), // 53: openshell.v1.RevokeSshSessionRequest - (*RevokeSshSessionResponse)(nil), // 54: openshell.v1.RevokeSshSessionResponse - (*ExecSandboxRequest)(nil), // 55: openshell.v1.ExecSandboxRequest - (*ExecSandboxStdout)(nil), // 56: openshell.v1.ExecSandboxStdout - (*ExecSandboxStderr)(nil), // 57: openshell.v1.ExecSandboxStderr - (*ExecSandboxExit)(nil), // 58: openshell.v1.ExecSandboxExit - (*ExecSandboxEvent)(nil), // 59: openshell.v1.ExecSandboxEvent - (*TcpForwardInit)(nil), // 60: openshell.v1.TcpForwardInit - (*TcpForwardFrame)(nil), // 61: openshell.v1.TcpForwardFrame - (*ExecSandboxInput)(nil), // 62: openshell.v1.ExecSandboxInput - (*ExecSandboxWindowResize)(nil), // 63: openshell.v1.ExecSandboxWindowResize - (*SshSession)(nil), // 64: openshell.v1.SshSession - (*WatchSandboxRequest)(nil), // 65: openshell.v1.WatchSandboxRequest - (*SandboxStreamEvent)(nil), // 66: openshell.v1.SandboxStreamEvent - (*SandboxLogLine)(nil), // 67: openshell.v1.SandboxLogLine - (*SandboxStreamWarning)(nil), // 68: openshell.v1.SandboxStreamWarning - (*CreateProviderRequest)(nil), // 69: openshell.v1.CreateProviderRequest - (*GetProviderRequest)(nil), // 70: openshell.v1.GetProviderRequest - (*ListProvidersRequest)(nil), // 71: openshell.v1.ListProvidersRequest - (*UpdateProviderRequest)(nil), // 72: openshell.v1.UpdateProviderRequest - (*DeleteProviderRequest)(nil), // 73: openshell.v1.DeleteProviderRequest - (*ProviderResponse)(nil), // 74: openshell.v1.ProviderResponse - (*ListProvidersResponse)(nil), // 75: openshell.v1.ListProvidersResponse - (*ListProviderProfilesRequest)(nil), // 76: openshell.v1.ListProviderProfilesRequest - (*GetProviderProfileRequest)(nil), // 77: openshell.v1.GetProviderProfileRequest - (*ProviderProfileImportItem)(nil), // 78: openshell.v1.ProviderProfileImportItem - (*ProviderProfileDiagnostic)(nil), // 79: openshell.v1.ProviderProfileDiagnostic - (*ProviderCredentialTokenGrantAudienceOverride)(nil), // 80: openshell.v1.ProviderCredentialTokenGrantAudienceOverride - (*ProviderCredentialTokenGrantSubjectToken)(nil), // 81: openshell.v1.ProviderCredentialTokenGrantSubjectToken - (*ProviderCredentialTokenGrant)(nil), // 82: openshell.v1.ProviderCredentialTokenGrant - (*ProviderProfileCredential)(nil), // 83: openshell.v1.ProviderProfileCredential - (*ProviderCredentialRefreshMaterial)(nil), // 84: openshell.v1.ProviderCredentialRefreshMaterial - (*ProviderCredentialRefreshOutput)(nil), // 85: openshell.v1.ProviderCredentialRefreshOutput - (*ProviderCredentialRefresh)(nil), // 86: openshell.v1.ProviderCredentialRefresh - (*ProviderCredentialRefreshStatus)(nil), // 87: openshell.v1.ProviderCredentialRefreshStatus - (*ProviderProfileDiscovery)(nil), // 88: openshell.v1.ProviderProfileDiscovery - (*StoredProviderCredentialRefreshState)(nil), // 89: openshell.v1.StoredProviderCredentialRefreshState - (*StoredRefreshMaterialDeletion)(nil), // 90: openshell.v1.StoredRefreshMaterialDeletion - (*GetProviderRefreshStatusRequest)(nil), // 91: openshell.v1.GetProviderRefreshStatusRequest - (*GetProviderRefreshStatusResponse)(nil), // 92: openshell.v1.GetProviderRefreshStatusResponse - (*ConfigureProviderRefreshRequest)(nil), // 93: openshell.v1.ConfigureProviderRefreshRequest - (*ConfigureProviderRefreshResponse)(nil), // 94: openshell.v1.ConfigureProviderRefreshResponse - (*RotateProviderCredentialRequest)(nil), // 95: openshell.v1.RotateProviderCredentialRequest - (*RotateProviderCredentialResponse)(nil), // 96: openshell.v1.RotateProviderCredentialResponse - (*DeleteProviderRefreshRequest)(nil), // 97: openshell.v1.DeleteProviderRefreshRequest - (*DeleteProviderRefreshResponse)(nil), // 98: openshell.v1.DeleteProviderRefreshResponse - (*ProviderProfile)(nil), // 99: openshell.v1.ProviderProfile - (*StoredProviderProfile)(nil), // 100: openshell.v1.StoredProviderProfile - (*ProviderProfileResponse)(nil), // 101: openshell.v1.ProviderProfileResponse - (*ListProviderProfilesResponse)(nil), // 102: openshell.v1.ListProviderProfilesResponse - (*ImportProviderProfilesRequest)(nil), // 103: openshell.v1.ImportProviderProfilesRequest - (*ImportProviderProfilesResponse)(nil), // 104: openshell.v1.ImportProviderProfilesResponse - (*UpdateProviderProfilesRequest)(nil), // 105: openshell.v1.UpdateProviderProfilesRequest - (*UpdateProviderProfilesResponse)(nil), // 106: openshell.v1.UpdateProviderProfilesResponse - (*LintProviderProfilesRequest)(nil), // 107: openshell.v1.LintProviderProfilesRequest - (*LintProviderProfilesResponse)(nil), // 108: openshell.v1.LintProviderProfilesResponse - (*DeleteProviderResponse)(nil), // 109: openshell.v1.DeleteProviderResponse - (*DeleteProviderProfileRequest)(nil), // 110: openshell.v1.DeleteProviderProfileRequest - (*DeleteProviderProfileResponse)(nil), // 111: openshell.v1.DeleteProviderProfileResponse - (*GetSandboxProviderEnvironmentRequest)(nil), // 112: openshell.v1.GetSandboxProviderEnvironmentRequest - (*StaticCredentialEndpointBinding)(nil), // 113: openshell.v1.StaticCredentialEndpointBinding - (*StaticCredentialBinding)(nil), // 114: openshell.v1.StaticCredentialBinding - (*GetSandboxProviderEnvironmentResponse)(nil), // 115: openshell.v1.GetSandboxProviderEnvironmentResponse - (*ExchangeProviderSubjectTokenRequest)(nil), // 116: openshell.v1.ExchangeProviderSubjectTokenRequest - (*ExchangeProviderSubjectTokenResponse)(nil), // 117: openshell.v1.ExchangeProviderSubjectTokenResponse - (*UpdateConfigRequest)(nil), // 118: openshell.v1.UpdateConfigRequest - (*PolicyMergeOperation)(nil), // 119: openshell.v1.PolicyMergeOperation - (*AddNetworkRule)(nil), // 120: openshell.v1.AddNetworkRule - (*RemoveNetworkEndpoint)(nil), // 121: openshell.v1.RemoveNetworkEndpoint - (*RemoveNetworkRule)(nil), // 122: openshell.v1.RemoveNetworkRule - (*AddDenyRules)(nil), // 123: openshell.v1.AddDenyRules - (*AddAllowRules)(nil), // 124: openshell.v1.AddAllowRules - (*RemoveNetworkBinary)(nil), // 125: openshell.v1.RemoveNetworkBinary - (*UpdateConfigResponse)(nil), // 126: openshell.v1.UpdateConfigResponse - (*GetSandboxPolicyStatusRequest)(nil), // 127: openshell.v1.GetSandboxPolicyStatusRequest - (*GetSandboxPolicyStatusResponse)(nil), // 128: openshell.v1.GetSandboxPolicyStatusResponse - (*ListSandboxPoliciesRequest)(nil), // 129: openshell.v1.ListSandboxPoliciesRequest - (*ListSandboxPoliciesResponse)(nil), // 130: openshell.v1.ListSandboxPoliciesResponse - (*ReportPolicyStatusRequest)(nil), // 131: openshell.v1.ReportPolicyStatusRequest - (*ReportPolicyStatusResponse)(nil), // 132: openshell.v1.ReportPolicyStatusResponse - (*SandboxPolicyRevision)(nil), // 133: openshell.v1.SandboxPolicyRevision - (*GetSandboxLogsRequest)(nil), // 134: openshell.v1.GetSandboxLogsRequest - (*PushSandboxLogsRequest)(nil), // 135: openshell.v1.PushSandboxLogsRequest - (*PushSandboxLogsResponse)(nil), // 136: openshell.v1.PushSandboxLogsResponse - (*GetSandboxLogsResponse)(nil), // 137: openshell.v1.GetSandboxLogsResponse - (*SupervisorMessage)(nil), // 138: openshell.v1.SupervisorMessage - (*GatewayMessage)(nil), // 139: openshell.v1.GatewayMessage - (*SupervisorHello)(nil), // 140: openshell.v1.SupervisorHello - (*SessionAccepted)(nil), // 141: openshell.v1.SessionAccepted - (*SessionRejected)(nil), // 142: openshell.v1.SessionRejected - (*SupervisorHeartbeat)(nil), // 143: openshell.v1.SupervisorHeartbeat - (*GatewayHeartbeat)(nil), // 144: openshell.v1.GatewayHeartbeat - (*ReportMainProcessExitRequest)(nil), // 145: openshell.v1.ReportMainProcessExitRequest - (*ReportMainProcessExitResponse)(nil), // 146: openshell.v1.ReportMainProcessExitResponse - (*FinalizeMainProcessExitRequest)(nil), // 147: openshell.v1.FinalizeMainProcessExitRequest - (*FinalizeMainProcessExitResponse)(nil), // 148: openshell.v1.FinalizeMainProcessExitResponse - (*RelayOpen)(nil), // 149: openshell.v1.RelayOpen - (*SshRelayTarget)(nil), // 150: openshell.v1.SshRelayTarget - (*TcpRelayTarget)(nil), // 151: openshell.v1.TcpRelayTarget - (*RelayInit)(nil), // 152: openshell.v1.RelayInit - (*RelayFrame)(nil), // 153: openshell.v1.RelayFrame - (*RelayOpenResult)(nil), // 154: openshell.v1.RelayOpenResult - (*RelayClose)(nil), // 155: openshell.v1.RelayClose - (*L7RequestSample)(nil), // 156: openshell.v1.L7RequestSample - (*DenialSummary)(nil), // 157: openshell.v1.DenialSummary - (*DenialGroupCount)(nil), // 158: openshell.v1.DenialGroupCount - (*NetworkActivitySummary)(nil), // 159: openshell.v1.NetworkActivitySummary - (*PolicyChunk)(nil), // 160: openshell.v1.PolicyChunk - (*DraftPolicyUpdate)(nil), // 161: openshell.v1.DraftPolicyUpdate - (*SubmitPolicyAnalysisRequest)(nil), // 162: openshell.v1.SubmitPolicyAnalysisRequest - (*SubmitPolicyAnalysisResponse)(nil), // 163: openshell.v1.SubmitPolicyAnalysisResponse - (*GetDraftPolicyRequest)(nil), // 164: openshell.v1.GetDraftPolicyRequest - (*GetDraftPolicyResponse)(nil), // 165: openshell.v1.GetDraftPolicyResponse - (*ApproveDraftChunkRequest)(nil), // 166: openshell.v1.ApproveDraftChunkRequest - (*ApproveDraftChunkResponse)(nil), // 167: openshell.v1.ApproveDraftChunkResponse - (*RejectDraftChunkRequest)(nil), // 168: openshell.v1.RejectDraftChunkRequest - (*RejectDraftChunkResponse)(nil), // 169: openshell.v1.RejectDraftChunkResponse - (*DraftChunkApproval)(nil), // 170: openshell.v1.DraftChunkApproval - (*ApproveAllDraftChunksRequest)(nil), // 171: openshell.v1.ApproveAllDraftChunksRequest - (*ApproveAllDraftChunksResponse)(nil), // 172: openshell.v1.ApproveAllDraftChunksResponse - (*EditDraftChunkRequest)(nil), // 173: openshell.v1.EditDraftChunkRequest - (*EditDraftChunkResponse)(nil), // 174: openshell.v1.EditDraftChunkResponse - (*UndoDraftChunkRequest)(nil), // 175: openshell.v1.UndoDraftChunkRequest - (*UndoDraftChunkResponse)(nil), // 176: openshell.v1.UndoDraftChunkResponse - (*ClearDraftChunksRequest)(nil), // 177: openshell.v1.ClearDraftChunksRequest - (*ClearDraftChunksResponse)(nil), // 178: openshell.v1.ClearDraftChunksResponse - (*GetDraftHistoryRequest)(nil), // 179: openshell.v1.GetDraftHistoryRequest - (*DraftHistoryEntry)(nil), // 180: openshell.v1.DraftHistoryEntry - (*GetDraftHistoryResponse)(nil), // 181: openshell.v1.GetDraftHistoryResponse - (*PolicyRevisionPayload)(nil), // 182: openshell.v1.PolicyRevisionPayload - (*DraftChunkPayload)(nil), // 183: openshell.v1.DraftChunkPayload - (*StoredPolicyRevision)(nil), // 184: openshell.v1.StoredPolicyRevision - (*StoredDraftChunk)(nil), // 185: openshell.v1.StoredDraftChunk - (*CreateWorkspaceRequest)(nil), // 186: openshell.v1.CreateWorkspaceRequest - (*CreateWorkspaceResponse)(nil), // 187: openshell.v1.CreateWorkspaceResponse - (*GetWorkspaceRequest)(nil), // 188: openshell.v1.GetWorkspaceRequest - (*GetWorkspaceResponse)(nil), // 189: openshell.v1.GetWorkspaceResponse - (*ListWorkspacesRequest)(nil), // 190: openshell.v1.ListWorkspacesRequest - (*ListWorkspacesResponse)(nil), // 191: openshell.v1.ListWorkspacesResponse - (*DeleteWorkspaceRequest)(nil), // 192: openshell.v1.DeleteWorkspaceRequest - (*DeleteWorkspaceResponse)(nil), // 193: openshell.v1.DeleteWorkspaceResponse - (*WorkspaceMember)(nil), // 194: openshell.v1.WorkspaceMember - (*AddWorkspaceMemberRequest)(nil), // 195: openshell.v1.AddWorkspaceMemberRequest - (*AddWorkspaceMemberResponse)(nil), // 196: openshell.v1.AddWorkspaceMemberResponse - (*RemoveWorkspaceMemberRequest)(nil), // 197: openshell.v1.RemoveWorkspaceMemberRequest - (*RemoveWorkspaceMemberResponse)(nil), // 198: openshell.v1.RemoveWorkspaceMemberResponse - (*ListWorkspaceMembersRequest)(nil), // 199: openshell.v1.ListWorkspaceMembersRequest - (*ListWorkspaceMembersResponse)(nil), // 200: openshell.v1.ListWorkspaceMembersResponse - (*ExtensionServiceCredential)(nil), // 201: openshell.v1.ExtensionServiceCredential - nil, // 202: openshell.v1.SandboxSpec.EnvironmentEntry - nil, // 203: openshell.v1.SandboxTemplate.LabelsEntry - nil, // 204: openshell.v1.SandboxTemplate.AnnotationsEntry - nil, // 205: openshell.v1.SandboxTemplate.EnvironmentEntry - nil, // 206: openshell.v1.PlatformEvent.MetadataEntry - nil, // 207: openshell.v1.CreateSandboxRequest.LabelsEntry - nil, // 208: openshell.v1.CreateSandboxRequest.AnnotationsEntry - nil, // 209: openshell.v1.ExecSandboxRequest.EnvironmentEntry - nil, // 210: openshell.v1.SandboxLogLine.FieldsEntry - nil, // 211: openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry - nil, // 212: openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry - nil, // 213: openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry - nil, // 214: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry - nil, // 215: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - nil, // 216: openshell.v1.ProviderProfile.AnnotationsEntry - nil, // 217: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - nil, // 218: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry - nil, // 219: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - nil, // 220: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - nil, // 221: openshell.v1.UpdateConfigRequest.AnnotationsEntry - nil, // 222: openshell.v1.UpdateConfigResponse.AnnotationsEntry - nil, // 223: openshell.v1.SandboxPolicyRevision.ProvenanceEntry - nil, // 224: openshell.v1.PolicyRevisionPayload.ProvenanceEntry - nil, // 225: openshell.v1.StoredPolicyRevision.ProvenanceEntry - nil, // 226: openshell.v1.CreateWorkspaceRequest.LabelsEntry - (*datamodelv1.ObjectMeta)(nil), // 227: openshell.datamodel.v1.ObjectMeta - (*sandboxv1.SandboxPolicy)(nil), // 228: openshell.sandbox.v1.SandboxPolicy - (*structpb.Struct)(nil), // 229: google.protobuf.Struct - (*datamodelv1.Provider)(nil), // 230: openshell.datamodel.v1.Provider - (*datamodelv1.CredentialHandle)(nil), // 231: openshell.datamodel.v1.CredentialHandle - (*sandboxv1.NetworkEndpoint)(nil), // 232: openshell.sandbox.v1.NetworkEndpoint - (*sandboxv1.NetworkBinary)(nil), // 233: openshell.sandbox.v1.NetworkBinary - (*sandboxv1.SettingValue)(nil), // 234: openshell.sandbox.v1.SettingValue - (*sandboxv1.NetworkPolicyRule)(nil), // 235: openshell.sandbox.v1.NetworkPolicyRule - (*sandboxv1.L7DenyRule)(nil), // 236: openshell.sandbox.v1.L7DenyRule - (*sandboxv1.L7Rule)(nil), // 237: openshell.sandbox.v1.L7Rule - (*datamodelv1.Workspace)(nil), // 238: openshell.datamodel.v1.Workspace - (*sandboxv1.GetSandboxConfigRequest)(nil), // 239: openshell.sandbox.v1.GetSandboxConfigRequest - (*sandboxv1.GetGatewayConfigRequest)(nil), // 240: openshell.sandbox.v1.GetGatewayConfigRequest - (*sandboxv1.GetSandboxConfigResponse)(nil), // 241: openshell.sandbox.v1.GetSandboxConfigResponse - (*sandboxv1.GetGatewayConfigResponse)(nil), // 242: openshell.sandbox.v1.GetGatewayConfigResponse + (*SandboxWorkloadTemplate)(nil), // 25: openshell.v1.SandboxWorkloadTemplate + (*SandboxWorkloadTemplateSpec)(nil), // 26: openshell.v1.SandboxWorkloadTemplateSpec + (*SandboxWorkloadConfig)(nil), // 27: openshell.v1.SandboxWorkloadConfig + (*SandboxResources)(nil), // 28: openshell.v1.SandboxResources + (*SandboxServiceLevel)(nil), // 29: openshell.v1.SandboxServiceLevel + (*SandboxStartup)(nil), // 30: openshell.v1.SandboxStartup + (*SandboxWorkloadTemplateProvenance)(nil), // 31: openshell.v1.SandboxWorkloadTemplateProvenance + (*SandboxStatus)(nil), // 32: openshell.v1.SandboxStatus + (*SandboxCondition)(nil), // 33: openshell.v1.SandboxCondition + (*PlatformEvent)(nil), // 34: openshell.v1.PlatformEvent + (*CreateSandboxRequest)(nil), // 35: openshell.v1.CreateSandboxRequest + (*CreateSandboxTemplateRequest)(nil), // 36: openshell.v1.CreateSandboxTemplateRequest + (*GetSandboxTemplateRequest)(nil), // 37: openshell.v1.GetSandboxTemplateRequest + (*ListSandboxTemplatesRequest)(nil), // 38: openshell.v1.ListSandboxTemplatesRequest + (*DeleteSandboxTemplateRequest)(nil), // 39: openshell.v1.DeleteSandboxTemplateRequest + (*SandboxTemplateResponse)(nil), // 40: openshell.v1.SandboxTemplateResponse + (*ListSandboxTemplatesResponse)(nil), // 41: openshell.v1.ListSandboxTemplatesResponse + (*DeleteSandboxTemplateResponse)(nil), // 42: openshell.v1.DeleteSandboxTemplateResponse + (*GetSandboxRequest)(nil), // 43: openshell.v1.GetSandboxRequest + (*ListSandboxesRequest)(nil), // 44: openshell.v1.ListSandboxesRequest + (*ListSandboxProvidersRequest)(nil), // 45: openshell.v1.ListSandboxProvidersRequest + (*AttachSandboxProviderRequest)(nil), // 46: openshell.v1.AttachSandboxProviderRequest + (*DetachSandboxProviderRequest)(nil), // 47: openshell.v1.DetachSandboxProviderRequest + (*DeleteSandboxRequest)(nil), // 48: openshell.v1.DeleteSandboxRequest + (*StopSandboxRequest)(nil), // 49: openshell.v1.StopSandboxRequest + (*StartSandboxRequest)(nil), // 50: openshell.v1.StartSandboxRequest + (*SandboxResponse)(nil), // 51: openshell.v1.SandboxResponse + (*ListSandboxesResponse)(nil), // 52: openshell.v1.ListSandboxesResponse + (*ListSandboxProvidersResponse)(nil), // 53: openshell.v1.ListSandboxProvidersResponse + (*AttachSandboxProviderResponse)(nil), // 54: openshell.v1.AttachSandboxProviderResponse + (*DetachSandboxProviderResponse)(nil), // 55: openshell.v1.DetachSandboxProviderResponse + (*DeleteSandboxResponse)(nil), // 56: openshell.v1.DeleteSandboxResponse + (*CreateSshSessionRequest)(nil), // 57: openshell.v1.CreateSshSessionRequest + (*CreateSshSessionResponse)(nil), // 58: openshell.v1.CreateSshSessionResponse + (*ExposeServiceRequest)(nil), // 59: openshell.v1.ExposeServiceRequest + (*GetServiceRequest)(nil), // 60: openshell.v1.GetServiceRequest + (*ListServicesRequest)(nil), // 61: openshell.v1.ListServicesRequest + (*ListServicesResponse)(nil), // 62: openshell.v1.ListServicesResponse + (*DeleteServiceRequest)(nil), // 63: openshell.v1.DeleteServiceRequest + (*DeleteServiceResponse)(nil), // 64: openshell.v1.DeleteServiceResponse + (*ServiceEndpoint)(nil), // 65: openshell.v1.ServiceEndpoint + (*ServiceEndpointResponse)(nil), // 66: openshell.v1.ServiceEndpointResponse + (*RevokeSshSessionRequest)(nil), // 67: openshell.v1.RevokeSshSessionRequest + (*RevokeSshSessionResponse)(nil), // 68: openshell.v1.RevokeSshSessionResponse + (*ExecSandboxRequest)(nil), // 69: openshell.v1.ExecSandboxRequest + (*ExecSandboxStdout)(nil), // 70: openshell.v1.ExecSandboxStdout + (*ExecSandboxStderr)(nil), // 71: openshell.v1.ExecSandboxStderr + (*ExecSandboxExit)(nil), // 72: openshell.v1.ExecSandboxExit + (*ExecSandboxEvent)(nil), // 73: openshell.v1.ExecSandboxEvent + (*TcpForwardInit)(nil), // 74: openshell.v1.TcpForwardInit + (*TcpForwardFrame)(nil), // 75: openshell.v1.TcpForwardFrame + (*ExecSandboxInput)(nil), // 76: openshell.v1.ExecSandboxInput + (*ExecSandboxWindowResize)(nil), // 77: openshell.v1.ExecSandboxWindowResize + (*SshSession)(nil), // 78: openshell.v1.SshSession + (*WatchSandboxRequest)(nil), // 79: openshell.v1.WatchSandboxRequest + (*SandboxStreamEvent)(nil), // 80: openshell.v1.SandboxStreamEvent + (*SandboxLogLine)(nil), // 81: openshell.v1.SandboxLogLine + (*SandboxStreamWarning)(nil), // 82: openshell.v1.SandboxStreamWarning + (*CreateProviderRequest)(nil), // 83: openshell.v1.CreateProviderRequest + (*GetProviderRequest)(nil), // 84: openshell.v1.GetProviderRequest + (*ListProvidersRequest)(nil), // 85: openshell.v1.ListProvidersRequest + (*UpdateProviderRequest)(nil), // 86: openshell.v1.UpdateProviderRequest + (*DeleteProviderRequest)(nil), // 87: openshell.v1.DeleteProviderRequest + (*ProviderResponse)(nil), // 88: openshell.v1.ProviderResponse + (*ListProvidersResponse)(nil), // 89: openshell.v1.ListProvidersResponse + (*ListProviderProfilesRequest)(nil), // 90: openshell.v1.ListProviderProfilesRequest + (*GetProviderProfileRequest)(nil), // 91: openshell.v1.GetProviderProfileRequest + (*ProviderProfileImportItem)(nil), // 92: openshell.v1.ProviderProfileImportItem + (*ProviderProfileDiagnostic)(nil), // 93: openshell.v1.ProviderProfileDiagnostic + (*ProviderCredentialTokenGrantAudienceOverride)(nil), // 94: openshell.v1.ProviderCredentialTokenGrantAudienceOverride + (*ProviderCredentialTokenGrantSubjectToken)(nil), // 95: openshell.v1.ProviderCredentialTokenGrantSubjectToken + (*ProviderCredentialTokenGrant)(nil), // 96: openshell.v1.ProviderCredentialTokenGrant + (*ProviderProfileCredential)(nil), // 97: openshell.v1.ProviderProfileCredential + (*ProviderCredentialRefreshMaterial)(nil), // 98: openshell.v1.ProviderCredentialRefreshMaterial + (*ProviderCredentialRefreshOutput)(nil), // 99: openshell.v1.ProviderCredentialRefreshOutput + (*ProviderCredentialRefresh)(nil), // 100: openshell.v1.ProviderCredentialRefresh + (*ProviderCredentialRefreshStatus)(nil), // 101: openshell.v1.ProviderCredentialRefreshStatus + (*ProviderProfileDiscovery)(nil), // 102: openshell.v1.ProviderProfileDiscovery + (*StoredProviderCredentialRefreshState)(nil), // 103: openshell.v1.StoredProviderCredentialRefreshState + (*StoredRefreshMaterialDeletion)(nil), // 104: openshell.v1.StoredRefreshMaterialDeletion + (*GetProviderRefreshStatusRequest)(nil), // 105: openshell.v1.GetProviderRefreshStatusRequest + (*GetProviderRefreshStatusResponse)(nil), // 106: openshell.v1.GetProviderRefreshStatusResponse + (*ConfigureProviderRefreshRequest)(nil), // 107: openshell.v1.ConfigureProviderRefreshRequest + (*ConfigureProviderRefreshResponse)(nil), // 108: openshell.v1.ConfigureProviderRefreshResponse + (*RotateProviderCredentialRequest)(nil), // 109: openshell.v1.RotateProviderCredentialRequest + (*RotateProviderCredentialResponse)(nil), // 110: openshell.v1.RotateProviderCredentialResponse + (*DeleteProviderRefreshRequest)(nil), // 111: openshell.v1.DeleteProviderRefreshRequest + (*DeleteProviderRefreshResponse)(nil), // 112: openshell.v1.DeleteProviderRefreshResponse + (*ProviderProfile)(nil), // 113: openshell.v1.ProviderProfile + (*StoredProviderProfile)(nil), // 114: openshell.v1.StoredProviderProfile + (*ProviderProfileResponse)(nil), // 115: openshell.v1.ProviderProfileResponse + (*ListProviderProfilesResponse)(nil), // 116: openshell.v1.ListProviderProfilesResponse + (*ImportProviderProfilesRequest)(nil), // 117: openshell.v1.ImportProviderProfilesRequest + (*ImportProviderProfilesResponse)(nil), // 118: openshell.v1.ImportProviderProfilesResponse + (*UpdateProviderProfilesRequest)(nil), // 119: openshell.v1.UpdateProviderProfilesRequest + (*UpdateProviderProfilesResponse)(nil), // 120: openshell.v1.UpdateProviderProfilesResponse + (*LintProviderProfilesRequest)(nil), // 121: openshell.v1.LintProviderProfilesRequest + (*LintProviderProfilesResponse)(nil), // 122: openshell.v1.LintProviderProfilesResponse + (*DeleteProviderResponse)(nil), // 123: openshell.v1.DeleteProviderResponse + (*DeleteProviderProfileRequest)(nil), // 124: openshell.v1.DeleteProviderProfileRequest + (*DeleteProviderProfileResponse)(nil), // 125: openshell.v1.DeleteProviderProfileResponse + (*GetSandboxProviderEnvironmentRequest)(nil), // 126: openshell.v1.GetSandboxProviderEnvironmentRequest + (*StaticCredentialEndpointBinding)(nil), // 127: openshell.v1.StaticCredentialEndpointBinding + (*StaticCredentialBinding)(nil), // 128: openshell.v1.StaticCredentialBinding + (*GetSandboxProviderEnvironmentResponse)(nil), // 129: openshell.v1.GetSandboxProviderEnvironmentResponse + (*ExchangeProviderSubjectTokenRequest)(nil), // 130: openshell.v1.ExchangeProviderSubjectTokenRequest + (*ExchangeProviderSubjectTokenResponse)(nil), // 131: openshell.v1.ExchangeProviderSubjectTokenResponse + (*UpdateConfigRequest)(nil), // 132: openshell.v1.UpdateConfigRequest + (*PolicyMergeOperation)(nil), // 133: openshell.v1.PolicyMergeOperation + (*AddNetworkRule)(nil), // 134: openshell.v1.AddNetworkRule + (*RemoveNetworkEndpoint)(nil), // 135: openshell.v1.RemoveNetworkEndpoint + (*RemoveNetworkRule)(nil), // 136: openshell.v1.RemoveNetworkRule + (*AddDenyRules)(nil), // 137: openshell.v1.AddDenyRules + (*AddAllowRules)(nil), // 138: openshell.v1.AddAllowRules + (*RemoveNetworkBinary)(nil), // 139: openshell.v1.RemoveNetworkBinary + (*UpdateConfigResponse)(nil), // 140: openshell.v1.UpdateConfigResponse + (*GetSandboxPolicyStatusRequest)(nil), // 141: openshell.v1.GetSandboxPolicyStatusRequest + (*GetSandboxPolicyStatusResponse)(nil), // 142: openshell.v1.GetSandboxPolicyStatusResponse + (*ListSandboxPoliciesRequest)(nil), // 143: openshell.v1.ListSandboxPoliciesRequest + (*ListSandboxPoliciesResponse)(nil), // 144: openshell.v1.ListSandboxPoliciesResponse + (*ReportPolicyStatusRequest)(nil), // 145: openshell.v1.ReportPolicyStatusRequest + (*ReportPolicyStatusResponse)(nil), // 146: openshell.v1.ReportPolicyStatusResponse + (*SandboxPolicyRevision)(nil), // 147: openshell.v1.SandboxPolicyRevision + (*GetSandboxLogsRequest)(nil), // 148: openshell.v1.GetSandboxLogsRequest + (*PushSandboxLogsRequest)(nil), // 149: openshell.v1.PushSandboxLogsRequest + (*PushSandboxLogsResponse)(nil), // 150: openshell.v1.PushSandboxLogsResponse + (*GetSandboxLogsResponse)(nil), // 151: openshell.v1.GetSandboxLogsResponse + (*SupervisorMessage)(nil), // 152: openshell.v1.SupervisorMessage + (*GatewayMessage)(nil), // 153: openshell.v1.GatewayMessage + (*SupervisorHello)(nil), // 154: openshell.v1.SupervisorHello + (*SessionAccepted)(nil), // 155: openshell.v1.SessionAccepted + (*SessionRejected)(nil), // 156: openshell.v1.SessionRejected + (*SupervisorHeartbeat)(nil), // 157: openshell.v1.SupervisorHeartbeat + (*GatewayHeartbeat)(nil), // 158: openshell.v1.GatewayHeartbeat + (*ReportMainProcessExitRequest)(nil), // 159: openshell.v1.ReportMainProcessExitRequest + (*ReportMainProcessExitResponse)(nil), // 160: openshell.v1.ReportMainProcessExitResponse + (*FinalizeMainProcessExitRequest)(nil), // 161: openshell.v1.FinalizeMainProcessExitRequest + (*FinalizeMainProcessExitResponse)(nil), // 162: openshell.v1.FinalizeMainProcessExitResponse + (*RelayOpen)(nil), // 163: openshell.v1.RelayOpen + (*SshRelayTarget)(nil), // 164: openshell.v1.SshRelayTarget + (*TcpRelayTarget)(nil), // 165: openshell.v1.TcpRelayTarget + (*RelayInit)(nil), // 166: openshell.v1.RelayInit + (*RelayFrame)(nil), // 167: openshell.v1.RelayFrame + (*RelayOpenResult)(nil), // 168: openshell.v1.RelayOpenResult + (*RelayClose)(nil), // 169: openshell.v1.RelayClose + (*L7RequestSample)(nil), // 170: openshell.v1.L7RequestSample + (*DenialSummary)(nil), // 171: openshell.v1.DenialSummary + (*DenialGroupCount)(nil), // 172: openshell.v1.DenialGroupCount + (*NetworkActivitySummary)(nil), // 173: openshell.v1.NetworkActivitySummary + (*PolicyChunk)(nil), // 174: openshell.v1.PolicyChunk + (*DraftPolicyUpdate)(nil), // 175: openshell.v1.DraftPolicyUpdate + (*SubmitPolicyAnalysisRequest)(nil), // 176: openshell.v1.SubmitPolicyAnalysisRequest + (*SubmitPolicyAnalysisResponse)(nil), // 177: openshell.v1.SubmitPolicyAnalysisResponse + (*GetDraftPolicyRequest)(nil), // 178: openshell.v1.GetDraftPolicyRequest + (*GetDraftPolicyResponse)(nil), // 179: openshell.v1.GetDraftPolicyResponse + (*ApproveDraftChunkRequest)(nil), // 180: openshell.v1.ApproveDraftChunkRequest + (*ApproveDraftChunkResponse)(nil), // 181: openshell.v1.ApproveDraftChunkResponse + (*RejectDraftChunkRequest)(nil), // 182: openshell.v1.RejectDraftChunkRequest + (*RejectDraftChunkResponse)(nil), // 183: openshell.v1.RejectDraftChunkResponse + (*DraftChunkApproval)(nil), // 184: openshell.v1.DraftChunkApproval + (*ApproveAllDraftChunksRequest)(nil), // 185: openshell.v1.ApproveAllDraftChunksRequest + (*ApproveAllDraftChunksResponse)(nil), // 186: openshell.v1.ApproveAllDraftChunksResponse + (*EditDraftChunkRequest)(nil), // 187: openshell.v1.EditDraftChunkRequest + (*EditDraftChunkResponse)(nil), // 188: openshell.v1.EditDraftChunkResponse + (*UndoDraftChunkRequest)(nil), // 189: openshell.v1.UndoDraftChunkRequest + (*UndoDraftChunkResponse)(nil), // 190: openshell.v1.UndoDraftChunkResponse + (*ClearDraftChunksRequest)(nil), // 191: openshell.v1.ClearDraftChunksRequest + (*ClearDraftChunksResponse)(nil), // 192: openshell.v1.ClearDraftChunksResponse + (*GetDraftHistoryRequest)(nil), // 193: openshell.v1.GetDraftHistoryRequest + (*DraftHistoryEntry)(nil), // 194: openshell.v1.DraftHistoryEntry + (*GetDraftHistoryResponse)(nil), // 195: openshell.v1.GetDraftHistoryResponse + (*PolicyRevisionPayload)(nil), // 196: openshell.v1.PolicyRevisionPayload + (*DraftChunkPayload)(nil), // 197: openshell.v1.DraftChunkPayload + (*StoredPolicyRevision)(nil), // 198: openshell.v1.StoredPolicyRevision + (*StoredDraftChunk)(nil), // 199: openshell.v1.StoredDraftChunk + (*CreateWorkspaceRequest)(nil), // 200: openshell.v1.CreateWorkspaceRequest + (*CreateWorkspaceResponse)(nil), // 201: openshell.v1.CreateWorkspaceResponse + (*GetWorkspaceRequest)(nil), // 202: openshell.v1.GetWorkspaceRequest + (*GetWorkspaceResponse)(nil), // 203: openshell.v1.GetWorkspaceResponse + (*ListWorkspacesRequest)(nil), // 204: openshell.v1.ListWorkspacesRequest + (*ListWorkspacesResponse)(nil), // 205: openshell.v1.ListWorkspacesResponse + (*DeleteWorkspaceRequest)(nil), // 206: openshell.v1.DeleteWorkspaceRequest + (*DeleteWorkspaceResponse)(nil), // 207: openshell.v1.DeleteWorkspaceResponse + (*WorkspaceMember)(nil), // 208: openshell.v1.WorkspaceMember + (*AddWorkspaceMemberRequest)(nil), // 209: openshell.v1.AddWorkspaceMemberRequest + (*AddWorkspaceMemberResponse)(nil), // 210: openshell.v1.AddWorkspaceMemberResponse + (*RemoveWorkspaceMemberRequest)(nil), // 211: openshell.v1.RemoveWorkspaceMemberRequest + (*RemoveWorkspaceMemberResponse)(nil), // 212: openshell.v1.RemoveWorkspaceMemberResponse + (*ListWorkspaceMembersRequest)(nil), // 213: openshell.v1.ListWorkspaceMembersRequest + (*ListWorkspaceMembersResponse)(nil), // 214: openshell.v1.ListWorkspaceMembersResponse + (*ExtensionServiceCredential)(nil), // 215: openshell.v1.ExtensionServiceCredential + nil, // 216: openshell.v1.SandboxSpec.EnvironmentEntry + nil, // 217: openshell.v1.SandboxTemplate.LabelsEntry + nil, // 218: openshell.v1.SandboxTemplate.AnnotationsEntry + nil, // 219: openshell.v1.SandboxTemplate.EnvironmentEntry + nil, // 220: openshell.v1.SandboxWorkloadConfig.EnvironmentEntry + nil, // 221: openshell.v1.PlatformEvent.MetadataEntry + nil, // 222: openshell.v1.CreateSandboxRequest.LabelsEntry + nil, // 223: openshell.v1.CreateSandboxRequest.AnnotationsEntry + nil, // 224: openshell.v1.ExecSandboxRequest.EnvironmentEntry + nil, // 225: openshell.v1.SandboxLogLine.FieldsEntry + nil, // 226: openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry + nil, // 227: openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry + nil, // 228: openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry + nil, // 229: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry + nil, // 230: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + nil, // 231: openshell.v1.ProviderProfile.AnnotationsEntry + nil, // 232: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + nil, // 233: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry + nil, // 234: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + nil, // 235: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + nil, // 236: openshell.v1.UpdateConfigRequest.AnnotationsEntry + nil, // 237: openshell.v1.UpdateConfigResponse.AnnotationsEntry + nil, // 238: openshell.v1.SandboxPolicyRevision.ProvenanceEntry + nil, // 239: openshell.v1.PolicyRevisionPayload.ProvenanceEntry + nil, // 240: openshell.v1.StoredPolicyRevision.ProvenanceEntry + nil, // 241: openshell.v1.CreateWorkspaceRequest.LabelsEntry + (*datamodelv1.ObjectMeta)(nil), // 242: openshell.datamodel.v1.ObjectMeta + (*sandboxv1.SandboxPolicy)(nil), // 243: openshell.sandbox.v1.SandboxPolicy + (*structpb.Struct)(nil), // 244: google.protobuf.Struct + (*durationpb.Duration)(nil), // 245: google.protobuf.Duration + (*datamodelv1.Provider)(nil), // 246: openshell.datamodel.v1.Provider + (*datamodelv1.CredentialHandle)(nil), // 247: openshell.datamodel.v1.CredentialHandle + (*sandboxv1.NetworkEndpoint)(nil), // 248: openshell.sandbox.v1.NetworkEndpoint + (*sandboxv1.NetworkBinary)(nil), // 249: openshell.sandbox.v1.NetworkBinary + (*sandboxv1.SettingValue)(nil), // 250: openshell.sandbox.v1.SettingValue + (*sandboxv1.NetworkPolicyRule)(nil), // 251: openshell.sandbox.v1.NetworkPolicyRule + (*sandboxv1.L7DenyRule)(nil), // 252: openshell.sandbox.v1.L7DenyRule + (*sandboxv1.L7Rule)(nil), // 253: openshell.sandbox.v1.L7Rule + (*datamodelv1.Workspace)(nil), // 254: openshell.datamodel.v1.Workspace + (*sandboxv1.GetSandboxConfigRequest)(nil), // 255: openshell.sandbox.v1.GetSandboxConfigRequest + (*sandboxv1.GetGatewayConfigRequest)(nil), // 256: openshell.sandbox.v1.GetGatewayConfigRequest + (*sandboxv1.GetSandboxConfigResponse)(nil), // 257: openshell.sandbox.v1.GetSandboxConfigResponse + (*sandboxv1.GetGatewayConfigResponse)(nil), // 258: openshell.sandbox.v1.GetGatewayConfigResponse } var file_openshell_proto_depIdxs = []int32{ - 201, // 0: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential + 215, // 0: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential 5, // 1: openshell.v1.HealthResponse.status:type_name -> openshell.v1.ServiceStatus 5, // 2: openshell.v1.GetGatewayInfoResponse.status:type_name -> openshell.v1.ServiceStatus 18, // 3: openshell.v1.GetGatewayInfoResponse.compute_drivers:type_name -> openshell.v1.ComputeDriverInfo 19, // 4: openshell.v1.ComputeDriverInfo.capabilities:type_name -> openshell.v1.ComputeDriverCapabilities - 227, // 5: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 242, // 5: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta 21, // 6: openshell.v1.Sandbox.spec:type_name -> openshell.v1.SandboxSpec - 25, // 7: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus - 202, // 8: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry - 24, // 9: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate - 228, // 10: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 22, // 11: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements - 23, // 12: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements - 203, // 13: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry - 204, // 14: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry - 205, // 15: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry - 229, // 16: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct - 229, // 17: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct - 26, // 18: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition - 0, // 19: openshell.v1.SandboxStatus.phase:type_name -> openshell.v1.SandboxPhase - 206, // 20: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry - 21, // 21: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec - 207, // 22: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry - 208, // 23: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry - 20, // 24: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox - 20, // 25: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox - 230, // 26: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 20, // 27: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 20, // 28: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 52, // 29: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse - 227, // 30: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 51, // 31: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint - 209, // 32: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry - 56, // 33: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout - 57, // 34: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr - 58, // 35: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit - 150, // 36: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget - 151, // 37: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget - 60, // 38: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit - 55, // 39: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest - 63, // 40: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize - 227, // 41: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 20, // 42: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox - 67, // 43: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine - 27, // 44: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent - 68, // 45: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning - 161, // 46: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate - 210, // 47: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry - 230, // 48: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 230, // 49: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 211, // 50: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry - 230, // 51: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider - 230, // 52: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 99, // 53: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile - 80, // 54: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride - 1, // 55: openshell.v1.ProviderCredentialTokenGrant.grant_type:type_name -> openshell.v1.ProviderCredentialTokenGrantType - 81, // 56: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken - 86, // 57: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh - 82, // 58: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant - 2, // 59: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 84, // 60: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial - 85, // 61: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput - 2, // 62: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 7, // 63: openshell.v1.ProviderCredentialRefreshStatus.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction - 227, // 64: openshell.v1.StoredProviderCredentialRefreshState.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 2, // 65: openshell.v1.StoredProviderCredentialRefreshState.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 212, // 66: openshell.v1.StoredProviderCredentialRefreshState.material:type_name -> openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry - 213, // 67: openshell.v1.StoredProviderCredentialRefreshState.additional_output_keys:type_name -> openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry - 214, // 68: openshell.v1.StoredProviderCredentialRefreshState.secret_material_handles:type_name -> openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry - 90, // 69: openshell.v1.StoredProviderCredentialRefreshState.pending_secret_deletions:type_name -> openshell.v1.StoredRefreshMaterialDeletion - 7, // 70: openshell.v1.StoredProviderCredentialRefreshState.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction - 231, // 71: openshell.v1.StoredRefreshMaterialDeletion.handle:type_name -> openshell.datamodel.v1.CredentialHandle - 87, // 72: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 2, // 73: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 215, // 74: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - 87, // 75: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 87, // 76: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 3, // 77: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory - 83, // 78: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential - 232, // 79: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint - 233, // 80: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary - 88, // 81: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery - 216, // 82: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry - 227, // 83: openshell.v1.StoredProviderProfile.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 99, // 84: openshell.v1.StoredProviderProfile.profile:type_name -> openshell.v1.ProviderProfile - 99, // 85: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile - 99, // 86: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 78, // 87: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 79, // 88: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 99, // 89: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 78, // 90: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem - 79, // 91: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 99, // 92: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile - 78, // 93: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 79, // 94: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 113, // 95: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding - 217, // 96: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - 218, // 97: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry - 219, // 98: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - 220, // 99: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - 228, // 100: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 234, // 101: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue - 119, // 102: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation - 221, // 103: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry - 120, // 104: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule - 121, // 105: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint - 122, // 106: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule - 123, // 107: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules - 124, // 108: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules - 125, // 109: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary - 235, // 110: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 236, // 111: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule - 237, // 112: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule - 222, // 113: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry - 133, // 114: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision - 133, // 115: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision - 4, // 116: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus - 4, // 117: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus - 228, // 118: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 223, // 119: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry - 67, // 120: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine - 67, // 121: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine - 140, // 122: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello - 143, // 123: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat - 154, // 124: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult - 155, // 125: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose - 141, // 126: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted - 142, // 127: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected - 144, // 128: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat - 149, // 129: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen - 155, // 130: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose - 150, // 131: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget - 151, // 132: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget - 152, // 133: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit - 156, // 134: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample - 158, // 135: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount - 235, // 136: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 228, // 137: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 228, // 138: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 157, // 139: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary - 160, // 140: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk - 159, // 141: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary - 160, // 142: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk - 170, // 143: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval - 235, // 144: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 180, // 145: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry - 228, // 146: openshell.v1.PolicyRevisionPayload.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 224, // 147: openshell.v1.PolicyRevisionPayload.provenance:type_name -> openshell.v1.PolicyRevisionPayload.ProvenanceEntry - 235, // 148: openshell.v1.DraftChunkPayload.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 228, // 149: openshell.v1.DraftChunkPayload.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 228, // 150: openshell.v1.DraftChunkPayload.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 225, // 151: openshell.v1.StoredPolicyRevision.provenance:type_name -> openshell.v1.StoredPolicyRevision.ProvenanceEntry - 228, // 152: openshell.v1.StoredDraftChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 228, // 153: openshell.v1.StoredDraftChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 226, // 154: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry - 238, // 155: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 238, // 156: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 238, // 157: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace - 227, // 158: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 6, // 159: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole - 6, // 160: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole - 194, // 161: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember - 194, // 162: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember - 231, // 163: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry.value:type_name -> openshell.datamodel.v1.CredentialHandle - 83, // 164: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential - 114, // 165: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding - 12, // 166: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest - 14, // 167: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest - 16, // 168: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest - 28, // 169: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest - 29, // 170: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest - 30, // 171: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest - 31, // 172: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest - 32, // 173: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest - 33, // 174: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest - 34, // 175: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest - 35, // 176: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest - 36, // 177: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest - 43, // 178: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest - 45, // 179: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest - 46, // 180: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest - 47, // 181: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest - 49, // 182: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest - 53, // 183: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest - 55, // 184: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest - 61, // 185: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame - 62, // 186: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput - 69, // 187: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest - 70, // 188: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest - 71, // 189: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest - 76, // 190: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest - 77, // 191: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest - 103, // 192: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest - 105, // 193: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest - 107, // 194: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest - 72, // 195: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest - 91, // 196: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest - 93, // 197: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest - 95, // 198: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest - 97, // 199: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest - 73, // 200: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest - 110, // 201: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest - 239, // 202: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest - 240, // 203: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest - 118, // 204: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest - 127, // 205: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest - 129, // 206: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest - 131, // 207: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest - 112, // 208: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest - 116, // 209: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest - 134, // 210: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest - 135, // 211: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest - 138, // 212: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage - 145, // 213: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest - 147, // 214: openshell.v1.OpenShell.FinalizeMainProcessExit:input_type -> openshell.v1.FinalizeMainProcessExitRequest - 153, // 215: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame - 65, // 216: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest - 162, // 217: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest - 164, // 218: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest - 166, // 219: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest - 168, // 220: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest - 171, // 221: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest - 173, // 222: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest - 175, // 223: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest - 177, // 224: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest - 179, // 225: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest - 8, // 226: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest - 10, // 227: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest - 186, // 228: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest - 188, // 229: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest - 190, // 230: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest - 192, // 231: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest - 195, // 232: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest - 197, // 233: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest - 199, // 234: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest - 13, // 235: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse - 15, // 236: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse - 17, // 237: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse - 37, // 238: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse - 37, // 239: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse - 38, // 240: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse - 39, // 241: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse - 40, // 242: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse - 41, // 243: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse - 42, // 244: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse - 37, // 245: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse - 37, // 246: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse - 44, // 247: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse - 52, // 248: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse - 52, // 249: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse - 48, // 250: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse - 50, // 251: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse - 54, // 252: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse - 59, // 253: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent - 61, // 254: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame - 59, // 255: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent - 74, // 256: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse - 74, // 257: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse - 75, // 258: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse - 102, // 259: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse - 101, // 260: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse - 104, // 261: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse - 106, // 262: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse - 108, // 263: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse - 74, // 264: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse - 92, // 265: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse - 94, // 266: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse - 96, // 267: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse - 98, // 268: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse - 109, // 269: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse - 111, // 270: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse - 241, // 271: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse - 242, // 272: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse - 126, // 273: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse - 128, // 274: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse - 130, // 275: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse - 132, // 276: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse - 115, // 277: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse - 117, // 278: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse - 137, // 279: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse - 136, // 280: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse - 139, // 281: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage - 146, // 282: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse - 148, // 283: openshell.v1.OpenShell.FinalizeMainProcessExit:output_type -> openshell.v1.FinalizeMainProcessExitResponse - 153, // 284: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame - 66, // 285: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent - 163, // 286: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse - 165, // 287: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse - 167, // 288: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse - 169, // 289: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse - 172, // 290: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse - 174, // 291: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse - 176, // 292: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse - 178, // 293: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse - 181, // 294: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse - 9, // 295: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse - 11, // 296: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse - 187, // 297: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse - 189, // 298: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse - 191, // 299: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse - 193, // 300: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse - 196, // 301: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse - 198, // 302: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse - 200, // 303: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse - 235, // [235:304] is the sub-list for method output_type - 166, // [166:235] is the sub-list for method input_type - 166, // [166:166] is the sub-list for extension type_name - 166, // [166:166] is the sub-list for extension extendee - 0, // [0:166] is the sub-list for field type_name + 32, // 7: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus + 31, // 8: openshell.v1.Sandbox.created_from_workload_template:type_name -> openshell.v1.SandboxWorkloadTemplateProvenance + 216, // 9: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry + 24, // 10: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate + 243, // 11: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 22, // 12: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements + 23, // 13: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements + 217, // 14: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry + 218, // 15: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry + 219, // 16: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry + 244, // 17: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct + 244, // 18: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct + 242, // 19: openshell.v1.SandboxWorkloadTemplate.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 26, // 20: openshell.v1.SandboxWorkloadTemplate.spec:type_name -> openshell.v1.SandboxWorkloadTemplateSpec + 27, // 21: openshell.v1.SandboxWorkloadTemplateSpec.workload:type_name -> openshell.v1.SandboxWorkloadConfig + 244, // 22: openshell.v1.SandboxWorkloadTemplateSpec.driver_config:type_name -> google.protobuf.Struct + 29, // 23: openshell.v1.SandboxWorkloadTemplateSpec.desired_service_level:type_name -> openshell.v1.SandboxServiceLevel + 220, // 24: openshell.v1.SandboxWorkloadConfig.environment:type_name -> openshell.v1.SandboxWorkloadConfig.EnvironmentEntry + 28, // 25: openshell.v1.SandboxWorkloadConfig.resources:type_name -> openshell.v1.SandboxResources + 23, // 26: openshell.v1.SandboxResources.gpu:type_name -> openshell.v1.GpuResourceRequirements + 30, // 27: openshell.v1.SandboxServiceLevel.startup:type_name -> openshell.v1.SandboxStartup + 245, // 28: openshell.v1.SandboxStartup.ready_within:type_name -> google.protobuf.Duration + 33, // 29: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition + 0, // 30: openshell.v1.SandboxStatus.phase:type_name -> openshell.v1.SandboxPhase + 221, // 31: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry + 21, // 32: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec + 222, // 33: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry + 223, // 34: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry + 25, // 35: openshell.v1.CreateSandboxTemplateRequest.template:type_name -> openshell.v1.SandboxWorkloadTemplate + 25, // 36: openshell.v1.SandboxTemplateResponse.template:type_name -> openshell.v1.SandboxWorkloadTemplate + 25, // 37: openshell.v1.ListSandboxTemplatesResponse.templates:type_name -> openshell.v1.SandboxWorkloadTemplate + 20, // 38: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox + 20, // 39: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox + 246, // 40: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 20, // 41: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 20, // 42: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 66, // 43: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse + 242, // 44: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 65, // 45: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint + 224, // 46: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry + 70, // 47: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout + 71, // 48: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr + 72, // 49: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit + 164, // 50: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget + 165, // 51: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget + 74, // 52: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit + 69, // 53: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest + 77, // 54: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize + 242, // 55: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 20, // 56: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox + 81, // 57: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine + 34, // 58: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent + 82, // 59: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning + 175, // 60: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate + 225, // 61: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry + 246, // 62: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 246, // 63: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 226, // 64: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry + 246, // 65: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider + 246, // 66: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 113, // 67: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile + 94, // 68: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride + 1, // 69: openshell.v1.ProviderCredentialTokenGrant.grant_type:type_name -> openshell.v1.ProviderCredentialTokenGrantType + 95, // 70: openshell.v1.ProviderCredentialTokenGrant.subject_token:type_name -> openshell.v1.ProviderCredentialTokenGrantSubjectToken + 100, // 71: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh + 96, // 72: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant + 2, // 73: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 98, // 74: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial + 99, // 75: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput + 2, // 76: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 7, // 77: openshell.v1.ProviderCredentialRefreshStatus.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction + 242, // 78: openshell.v1.StoredProviderCredentialRefreshState.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 2, // 79: openshell.v1.StoredProviderCredentialRefreshState.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 227, // 80: openshell.v1.StoredProviderCredentialRefreshState.material:type_name -> openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry + 228, // 81: openshell.v1.StoredProviderCredentialRefreshState.additional_output_keys:type_name -> openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry + 229, // 82: openshell.v1.StoredProviderCredentialRefreshState.secret_material_handles:type_name -> openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry + 104, // 83: openshell.v1.StoredProviderCredentialRefreshState.pending_secret_deletions:type_name -> openshell.v1.StoredRefreshMaterialDeletion + 7, // 84: openshell.v1.StoredProviderCredentialRefreshState.recovery_action:type_name -> openshell.v1.ProviderCredentialRefreshRecoveryAction + 247, // 85: openshell.v1.StoredRefreshMaterialDeletion.handle:type_name -> openshell.datamodel.v1.CredentialHandle + 101, // 86: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 2, // 87: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 230, // 88: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + 101, // 89: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 101, // 90: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 3, // 91: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory + 97, // 92: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential + 248, // 93: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint + 249, // 94: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary + 102, // 95: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery + 231, // 96: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry + 242, // 97: openshell.v1.StoredProviderProfile.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 113, // 98: openshell.v1.StoredProviderProfile.profile:type_name -> openshell.v1.ProviderProfile + 113, // 99: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile + 113, // 100: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 92, // 101: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 93, // 102: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 113, // 103: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 92, // 104: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem + 93, // 105: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 113, // 106: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile + 92, // 107: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 93, // 108: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 127, // 109: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding + 232, // 110: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + 233, // 111: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry + 234, // 112: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + 235, // 113: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + 243, // 114: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 250, // 115: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue + 133, // 116: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation + 236, // 117: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry + 134, // 118: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule + 135, // 119: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint + 136, // 120: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule + 137, // 121: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules + 138, // 122: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules + 139, // 123: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary + 251, // 124: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 252, // 125: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule + 253, // 126: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule + 237, // 127: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry + 147, // 128: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision + 147, // 129: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision + 4, // 130: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus + 4, // 131: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus + 243, // 132: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 238, // 133: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry + 81, // 134: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine + 81, // 135: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine + 154, // 136: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello + 157, // 137: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat + 168, // 138: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult + 169, // 139: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose + 155, // 140: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted + 156, // 141: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected + 158, // 142: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat + 163, // 143: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen + 169, // 144: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose + 164, // 145: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget + 165, // 146: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget + 166, // 147: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit + 170, // 148: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample + 172, // 149: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount + 251, // 150: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 243, // 151: openshell.v1.PolicyChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 243, // 152: openshell.v1.PolicyChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 171, // 153: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary + 174, // 154: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk + 173, // 155: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary + 174, // 156: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk + 184, // 157: openshell.v1.ApproveAllDraftChunksRequest.approvals:type_name -> openshell.v1.DraftChunkApproval + 251, // 158: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 194, // 159: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry + 243, // 160: openshell.v1.PolicyRevisionPayload.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 239, // 161: openshell.v1.PolicyRevisionPayload.provenance:type_name -> openshell.v1.PolicyRevisionPayload.ProvenanceEntry + 251, // 162: openshell.v1.DraftChunkPayload.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 243, // 163: openshell.v1.DraftChunkPayload.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 243, // 164: openshell.v1.DraftChunkPayload.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 240, // 165: openshell.v1.StoredPolicyRevision.provenance:type_name -> openshell.v1.StoredPolicyRevision.ProvenanceEntry + 243, // 166: openshell.v1.StoredDraftChunk.current_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 243, // 167: openshell.v1.StoredDraftChunk.candidate_effective_policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 241, // 168: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry + 254, // 169: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 254, // 170: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 254, // 171: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace + 242, // 172: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 6, // 173: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole + 6, // 174: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole + 208, // 175: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember + 208, // 176: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember + 247, // 177: openshell.v1.StoredProviderCredentialRefreshState.SecretMaterialHandlesEntry.value:type_name -> openshell.datamodel.v1.CredentialHandle + 97, // 178: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential + 128, // 179: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding + 12, // 180: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest + 14, // 181: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest + 16, // 182: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest + 35, // 183: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest + 43, // 184: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest + 44, // 185: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest + 36, // 186: openshell.v1.OpenShell.CreateSandboxTemplate:input_type -> openshell.v1.CreateSandboxTemplateRequest + 37, // 187: openshell.v1.OpenShell.GetSandboxTemplate:input_type -> openshell.v1.GetSandboxTemplateRequest + 38, // 188: openshell.v1.OpenShell.ListSandboxTemplates:input_type -> openshell.v1.ListSandboxTemplatesRequest + 39, // 189: openshell.v1.OpenShell.DeleteSandboxTemplate:input_type -> openshell.v1.DeleteSandboxTemplateRequest + 45, // 190: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest + 46, // 191: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest + 47, // 192: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest + 48, // 193: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest + 49, // 194: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest + 50, // 195: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest + 57, // 196: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest + 59, // 197: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest + 60, // 198: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest + 61, // 199: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest + 63, // 200: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest + 67, // 201: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest + 69, // 202: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest + 75, // 203: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame + 76, // 204: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput + 83, // 205: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest + 84, // 206: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest + 85, // 207: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest + 90, // 208: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest + 91, // 209: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest + 117, // 210: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest + 119, // 211: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest + 121, // 212: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest + 86, // 213: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest + 105, // 214: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest + 107, // 215: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest + 109, // 216: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest + 111, // 217: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest + 87, // 218: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest + 124, // 219: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest + 255, // 220: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest + 256, // 221: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest + 132, // 222: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest + 141, // 223: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest + 143, // 224: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest + 145, // 225: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest + 126, // 226: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest + 130, // 227: openshell.v1.OpenShell.ExchangeProviderSubjectToken:input_type -> openshell.v1.ExchangeProviderSubjectTokenRequest + 148, // 228: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest + 149, // 229: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest + 152, // 230: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage + 159, // 231: openshell.v1.OpenShell.ReportMainProcessExit:input_type -> openshell.v1.ReportMainProcessExitRequest + 161, // 232: openshell.v1.OpenShell.FinalizeMainProcessExit:input_type -> openshell.v1.FinalizeMainProcessExitRequest + 167, // 233: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame + 79, // 234: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest + 176, // 235: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest + 178, // 236: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest + 180, // 237: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest + 182, // 238: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest + 185, // 239: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest + 187, // 240: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest + 189, // 241: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest + 191, // 242: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest + 193, // 243: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest + 8, // 244: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest + 10, // 245: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest + 200, // 246: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest + 202, // 247: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest + 204, // 248: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest + 206, // 249: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest + 209, // 250: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest + 211, // 251: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest + 213, // 252: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest + 13, // 253: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse + 15, // 254: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse + 17, // 255: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse + 51, // 256: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse + 51, // 257: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse + 52, // 258: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse + 40, // 259: openshell.v1.OpenShell.CreateSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse + 40, // 260: openshell.v1.OpenShell.GetSandboxTemplate:output_type -> openshell.v1.SandboxTemplateResponse + 41, // 261: openshell.v1.OpenShell.ListSandboxTemplates:output_type -> openshell.v1.ListSandboxTemplatesResponse + 42, // 262: openshell.v1.OpenShell.DeleteSandboxTemplate:output_type -> openshell.v1.DeleteSandboxTemplateResponse + 53, // 263: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse + 54, // 264: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse + 55, // 265: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse + 56, // 266: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse + 51, // 267: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse + 51, // 268: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse + 58, // 269: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse + 66, // 270: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse + 66, // 271: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse + 62, // 272: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse + 64, // 273: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse + 68, // 274: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse + 73, // 275: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent + 75, // 276: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame + 73, // 277: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent + 88, // 278: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse + 88, // 279: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse + 89, // 280: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse + 116, // 281: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse + 115, // 282: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse + 118, // 283: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse + 120, // 284: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse + 122, // 285: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse + 88, // 286: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse + 106, // 287: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse + 108, // 288: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse + 110, // 289: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse + 112, // 290: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse + 123, // 291: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse + 125, // 292: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse + 257, // 293: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse + 258, // 294: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse + 140, // 295: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse + 142, // 296: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse + 144, // 297: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse + 146, // 298: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse + 129, // 299: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse + 131, // 300: openshell.v1.OpenShell.ExchangeProviderSubjectToken:output_type -> openshell.v1.ExchangeProviderSubjectTokenResponse + 151, // 301: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse + 150, // 302: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse + 153, // 303: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage + 160, // 304: openshell.v1.OpenShell.ReportMainProcessExit:output_type -> openshell.v1.ReportMainProcessExitResponse + 162, // 305: openshell.v1.OpenShell.FinalizeMainProcessExit:output_type -> openshell.v1.FinalizeMainProcessExitResponse + 167, // 306: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame + 80, // 307: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent + 177, // 308: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse + 179, // 309: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse + 181, // 310: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse + 183, // 311: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse + 186, // 312: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse + 188, // 313: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse + 190, // 314: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse + 192, // 315: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse + 195, // 316: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse + 9, // 317: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse + 11, // 318: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse + 201, // 319: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse + 203, // 320: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse + 205, // 321: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse + 207, // 322: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse + 210, // 323: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse + 212, // 324: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse + 214, // 325: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse + 253, // [253:326] is the sub-list for method output_type + 180, // [180:253] is the sub-list for method input_type + 180, // [180:180] is the sub-list for extension type_name + 180, // [180:180] is the sub-list for extension extendee + 0, // [0:180] is the sub-list for field type_name } func init() { file_openshell_proto_init() } @@ -15933,34 +16821,34 @@ func file_openshell_proto_init() { } file_openshell_proto_msgTypes[15].OneofWrappers = []any{} file_openshell_proto_msgTypes[16].OneofWrappers = []any{} - file_openshell_proto_msgTypes[17].OneofWrappers = []any{} - file_openshell_proto_msgTypes[51].OneofWrappers = []any{ + file_openshell_proto_msgTypes[24].OneofWrappers = []any{} + file_openshell_proto_msgTypes[65].OneofWrappers = []any{ (*ExecSandboxEvent_Stdout)(nil), (*ExecSandboxEvent_Stderr)(nil), (*ExecSandboxEvent_Exit)(nil), } - file_openshell_proto_msgTypes[52].OneofWrappers = []any{ + file_openshell_proto_msgTypes[66].OneofWrappers = []any{ (*TcpForwardInit_Ssh)(nil), (*TcpForwardInit_Tcp)(nil), } - file_openshell_proto_msgTypes[53].OneofWrappers = []any{ + file_openshell_proto_msgTypes[67].OneofWrappers = []any{ (*TcpForwardFrame_Init)(nil), (*TcpForwardFrame_Data)(nil), } - file_openshell_proto_msgTypes[54].OneofWrappers = []any{ + file_openshell_proto_msgTypes[68].OneofWrappers = []any{ (*ExecSandboxInput_Start)(nil), (*ExecSandboxInput_Stdin)(nil), (*ExecSandboxInput_Resize)(nil), } - file_openshell_proto_msgTypes[58].OneofWrappers = []any{ + file_openshell_proto_msgTypes[72].OneofWrappers = []any{ (*SandboxStreamEvent_Sandbox)(nil), (*SandboxStreamEvent_Log)(nil), (*SandboxStreamEvent_Event)(nil), (*SandboxStreamEvent_Warning)(nil), (*SandboxStreamEvent_DraftPolicyUpdate)(nil), } - file_openshell_proto_msgTypes[85].OneofWrappers = []any{} - file_openshell_proto_msgTypes[111].OneofWrappers = []any{ + file_openshell_proto_msgTypes[99].OneofWrappers = []any{} + file_openshell_proto_msgTypes[125].OneofWrappers = []any{ (*PolicyMergeOperation_AddRule)(nil), (*PolicyMergeOperation_RemoveEndpoint)(nil), (*PolicyMergeOperation_RemoveRule)(nil), @@ -15968,36 +16856,36 @@ func file_openshell_proto_init() { (*PolicyMergeOperation_AddAllowRules)(nil), (*PolicyMergeOperation_RemoveBinary)(nil), } - file_openshell_proto_msgTypes[130].OneofWrappers = []any{ + file_openshell_proto_msgTypes[144].OneofWrappers = []any{ (*SupervisorMessage_Hello)(nil), (*SupervisorMessage_Heartbeat)(nil), (*SupervisorMessage_RelayOpenResult)(nil), (*SupervisorMessage_RelayClose)(nil), } - file_openshell_proto_msgTypes[131].OneofWrappers = []any{ + file_openshell_proto_msgTypes[145].OneofWrappers = []any{ (*GatewayMessage_SessionAccepted)(nil), (*GatewayMessage_SessionRejected)(nil), (*GatewayMessage_Heartbeat)(nil), (*GatewayMessage_RelayOpen)(nil), (*GatewayMessage_RelayClose)(nil), } - file_openshell_proto_msgTypes[141].OneofWrappers = []any{ + file_openshell_proto_msgTypes[155].OneofWrappers = []any{ (*RelayOpen_Ssh)(nil), (*RelayOpen_Tcp)(nil), } - file_openshell_proto_msgTypes[145].OneofWrappers = []any{ + file_openshell_proto_msgTypes[159].OneofWrappers = []any{ (*RelayFrame_Init)(nil), (*RelayFrame_Data)(nil), } - file_openshell_proto_msgTypes[176].OneofWrappers = []any{} - file_openshell_proto_msgTypes[177].OneofWrappers = []any{} + file_openshell_proto_msgTypes[190].OneofWrappers = []any{} + file_openshell_proto_msgTypes[191].OneofWrappers = []any{} type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_openshell_proto_rawDesc), len(file_openshell_proto_rawDesc)), NumEnums: 8, - NumMessages: 219, + NumMessages: 234, NumExtensions: 0, NumServices: 1, }, diff --git a/sdk/go/proto/openshellv1/openshell_grpc.pb.go b/sdk/go/proto/openshellv1/openshell_grpc.pb.go index 9220f22999..61bc081437 100644 --- a/sdk/go/proto/openshellv1/openshell_grpc.pb.go +++ b/sdk/go/proto/openshellv1/openshell_grpc.pb.go @@ -29,6 +29,10 @@ const ( OpenShell_CreateSandbox_FullMethodName = "/openshell.v1.OpenShell/CreateSandbox" OpenShell_GetSandbox_FullMethodName = "/openshell.v1.OpenShell/GetSandbox" OpenShell_ListSandboxes_FullMethodName = "/openshell.v1.OpenShell/ListSandboxes" + OpenShell_CreateSandboxTemplate_FullMethodName = "/openshell.v1.OpenShell/CreateSandboxTemplate" + OpenShell_GetSandboxTemplate_FullMethodName = "/openshell.v1.OpenShell/GetSandboxTemplate" + OpenShell_ListSandboxTemplates_FullMethodName = "/openshell.v1.OpenShell/ListSandboxTemplates" + OpenShell_DeleteSandboxTemplate_FullMethodName = "/openshell.v1.OpenShell/DeleteSandboxTemplate" OpenShell_ListSandboxProviders_FullMethodName = "/openshell.v1.OpenShell/ListSandboxProviders" OpenShell_AttachSandboxProvider_FullMethodName = "/openshell.v1.OpenShell/AttachSandboxProvider" OpenShell_DetachSandboxProvider_FullMethodName = "/openshell.v1.OpenShell/DetachSandboxProvider" @@ -119,6 +123,14 @@ type OpenShellClient interface { GetSandbox(ctx context.Context, in *GetSandboxRequest, opts ...grpc.CallOption) (*SandboxResponse, error) // List sandboxes. ListSandboxes(ctx context.Context, in *ListSandboxesRequest, opts ...grpc.CallOption) (*ListSandboxesResponse, error) + // Create a reusable sandbox workload template. + CreateSandboxTemplate(ctx context.Context, in *CreateSandboxTemplateRequest, opts ...grpc.CallOption) (*SandboxTemplateResponse, error) + // Fetch a reusable sandbox workload template by name. + GetSandboxTemplate(ctx context.Context, in *GetSandboxTemplateRequest, opts ...grpc.CallOption) (*SandboxTemplateResponse, error) + // List reusable sandbox workload templates. + ListSandboxTemplates(ctx context.Context, in *ListSandboxTemplatesRequest, opts ...grpc.CallOption) (*ListSandboxTemplatesResponse, error) + // Delete a reusable sandbox workload template by name. + DeleteSandboxTemplate(ctx context.Context, in *DeleteSandboxTemplateRequest, opts ...grpc.CallOption) (*DeleteSandboxTemplateResponse, error) // List provider records attached to a sandbox. ListSandboxProviders(ctx context.Context, in *ListSandboxProvidersRequest, opts ...grpc.CallOption) (*ListSandboxProvidersResponse, error) // Attach a provider record to an existing sandbox. @@ -354,6 +366,46 @@ func (c *openShellClient) ListSandboxes(ctx context.Context, in *ListSandboxesRe return out, nil } +func (c *openShellClient) CreateSandboxTemplate(ctx context.Context, in *CreateSandboxTemplateRequest, opts ...grpc.CallOption) (*SandboxTemplateResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SandboxTemplateResponse) + err := c.cc.Invoke(ctx, OpenShell_CreateSandboxTemplate_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *openShellClient) GetSandboxTemplate(ctx context.Context, in *GetSandboxTemplateRequest, opts ...grpc.CallOption) (*SandboxTemplateResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(SandboxTemplateResponse) + err := c.cc.Invoke(ctx, OpenShell_GetSandboxTemplate_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *openShellClient) ListSandboxTemplates(ctx context.Context, in *ListSandboxTemplatesRequest, opts ...grpc.CallOption) (*ListSandboxTemplatesResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListSandboxTemplatesResponse) + err := c.cc.Invoke(ctx, OpenShell_ListSandboxTemplates_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *openShellClient) DeleteSandboxTemplate(ctx context.Context, in *DeleteSandboxTemplateRequest, opts ...grpc.CallOption) (*DeleteSandboxTemplateResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(DeleteSandboxTemplateResponse) + err := c.cc.Invoke(ctx, OpenShell_DeleteSandboxTemplate_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *openShellClient) ListSandboxProviders(ctx context.Context, in *ListSandboxProvidersRequest, opts ...grpc.CallOption) (*ListSandboxProvidersResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ListSandboxProvidersResponse) @@ -1042,6 +1094,14 @@ type OpenShellServer interface { GetSandbox(context.Context, *GetSandboxRequest) (*SandboxResponse, error) // List sandboxes. ListSandboxes(context.Context, *ListSandboxesRequest) (*ListSandboxesResponse, error) + // Create a reusable sandbox workload template. + CreateSandboxTemplate(context.Context, *CreateSandboxTemplateRequest) (*SandboxTemplateResponse, error) + // Fetch a reusable sandbox workload template by name. + GetSandboxTemplate(context.Context, *GetSandboxTemplateRequest) (*SandboxTemplateResponse, error) + // List reusable sandbox workload templates. + ListSandboxTemplates(context.Context, *ListSandboxTemplatesRequest) (*ListSandboxTemplatesResponse, error) + // Delete a reusable sandbox workload template by name. + DeleteSandboxTemplate(context.Context, *DeleteSandboxTemplateRequest) (*DeleteSandboxTemplateResponse, error) // List provider records attached to a sandbox. ListSandboxProviders(context.Context, *ListSandboxProvidersRequest) (*ListSandboxProvidersResponse, error) // Attach a provider record to an existing sandbox. @@ -1235,6 +1295,18 @@ func (UnimplementedOpenShellServer) GetSandbox(context.Context, *GetSandboxReque func (UnimplementedOpenShellServer) ListSandboxes(context.Context, *ListSandboxesRequest) (*ListSandboxesResponse, error) { return nil, status.Error(codes.Unimplemented, "method ListSandboxes not implemented") } +func (UnimplementedOpenShellServer) CreateSandboxTemplate(context.Context, *CreateSandboxTemplateRequest) (*SandboxTemplateResponse, error) { + return nil, status.Error(codes.Unimplemented, "method CreateSandboxTemplate not implemented") +} +func (UnimplementedOpenShellServer) GetSandboxTemplate(context.Context, *GetSandboxTemplateRequest) (*SandboxTemplateResponse, error) { + return nil, status.Error(codes.Unimplemented, "method GetSandboxTemplate not implemented") +} +func (UnimplementedOpenShellServer) ListSandboxTemplates(context.Context, *ListSandboxTemplatesRequest) (*ListSandboxTemplatesResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListSandboxTemplates not implemented") +} +func (UnimplementedOpenShellServer) DeleteSandboxTemplate(context.Context, *DeleteSandboxTemplateRequest) (*DeleteSandboxTemplateResponse, error) { + return nil, status.Error(codes.Unimplemented, "method DeleteSandboxTemplate not implemented") +} func (UnimplementedOpenShellServer) ListSandboxProviders(context.Context, *ListSandboxProvidersRequest) (*ListSandboxProvidersResponse, error) { return nil, status.Error(codes.Unimplemented, "method ListSandboxProviders not implemented") } @@ -1553,6 +1625,78 @@ func _OpenShell_ListSandboxes_Handler(srv interface{}, ctx context.Context, dec return interceptor(ctx, in, info, handler) } +func _OpenShell_CreateSandboxTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateSandboxTemplateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OpenShellServer).CreateSandboxTemplate(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OpenShell_CreateSandboxTemplate_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OpenShellServer).CreateSandboxTemplate(ctx, req.(*CreateSandboxTemplateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _OpenShell_GetSandboxTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetSandboxTemplateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OpenShellServer).GetSandboxTemplate(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OpenShell_GetSandboxTemplate_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OpenShellServer).GetSandboxTemplate(ctx, req.(*GetSandboxTemplateRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _OpenShell_ListSandboxTemplates_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListSandboxTemplatesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OpenShellServer).ListSandboxTemplates(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OpenShell_ListSandboxTemplates_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OpenShellServer).ListSandboxTemplates(ctx, req.(*ListSandboxTemplatesRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _OpenShell_DeleteSandboxTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DeleteSandboxTemplateRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(OpenShellServer).DeleteSandboxTemplate(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: OpenShell_DeleteSandboxTemplate_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(OpenShellServer).DeleteSandboxTemplate(ctx, req.(*DeleteSandboxTemplateRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _OpenShell_ListSandboxProviders_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListSandboxProvidersRequest) if err := dec(in); err != nil { @@ -2649,6 +2793,22 @@ var OpenShell_ServiceDesc = grpc.ServiceDesc{ MethodName: "ListSandboxes", Handler: _OpenShell_ListSandboxes_Handler, }, + { + MethodName: "CreateSandboxTemplate", + Handler: _OpenShell_CreateSandboxTemplate_Handler, + }, + { + MethodName: "GetSandboxTemplate", + Handler: _OpenShell_GetSandboxTemplate_Handler, + }, + { + MethodName: "ListSandboxTemplates", + Handler: _OpenShell_ListSandboxTemplates_Handler, + }, + { + MethodName: "DeleteSandboxTemplate", + Handler: _OpenShell_DeleteSandboxTemplate_Handler, + }, { MethodName: "ListSandboxProviders", Handler: _OpenShell_ListSandboxProviders_Handler, diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index b0e7ed696c..322b1a092c 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -152,11 +152,54 @@ await client.sandbox.setSetting(name, 'feature.enabled', { value: { case: 'boolV Sandbox-scoped `setPolicy` may only change `networkPolicies`; static fields (`filesystem`, `landlock`, `process`) must match the create-time policy. Sandbox-scoped setting deletes are rejected by the gateway, so only upsert (`setSetting`) is exposed here. +## Sandbox templates + +Sandbox workload templates are reusable, workspace-scoped runtime shapes. They +own image, environment, resource, and driver-specific settings; sandbox creation +from a template can still attach labels, providers, and create-time policy. + +```ts +import { OpenShellClient, type SandboxWorkloadTemplate } from '@nvidia/openshell-sdk' + +const client = await OpenShellClient.connect({ gateway, oidcToken }) + +const template: SandboxWorkloadTemplate = await client.sandboxTemplates.create( + { + metadata: { name: 'python', labels: { team: 'runtime' } }, + spec: { + workload: { + image: 'ghcr.io/nvidia/openshell-community/sandboxes/python:latest', + environment: { FEATURE_FLAG: 'on' }, + resources: { cpu: '1', memory: '512Mi' }, + }, + driverConfig: { kubernetes: { pod: { runtime_class_name: 'kata-containers' } } }, + }, + }, + { workspace: 'default' }, +) + +const sandbox = await client.sandbox.createFromTemplate({ + templateName: template.metadata!.name, + workspace: 'default', + providers: ['github'], + policy: { version: 1, networkPolicies: {} }, +}) + +await client.sandboxTemplates.get('python', { workspace: 'default' }) +await client.sandboxTemplates.list({ workspace: 'default', limit: 100 }) +await client.sandboxTemplates.delete('python', { workspace: 'default' }) +``` + +Use `allWorkspaces: true` on `list()` for a platform-admin view. The SDK clears +the workspace field in that request because the gateway treats `workspace` and +`allWorkspaces` as mutually exclusive. + ## Surface and roadmap The SDK's goal is agent parity: anything the OpenShell gateway can do should be reachable from typed code, not only the CLI. The API is organized as scoped sub-clients over one shared connection, mirroring the CLI's verbs. - `client.sandbox` (`SandboxClient`) is available today: sandbox lifecycle, exec, forward, SSH, sandbox-scoped providers, config, and policy. +- `client.sandboxTemplates` (`SandboxTemplateClient`) is available today: reusable sandbox workload template CRUD. - `client.gateway` (`GatewayClient`) is planned: gateway-scoped config and settings, health, and cluster status. - `client.providers` (`ProviderClient`) is planned: gateway-scoped provider CRUD and profiles. diff --git a/sdk/typescript/src/client.test.ts b/sdk/typescript/src/client.test.ts index 29a7438c69..5b12a48e23 100644 --- a/sdk/typescript/src/client.test.ts +++ b/sdk/typescript/src/client.test.ts @@ -17,6 +17,7 @@ import { POLICY_SOURCE_NAMES, Pushable, SandboxClient, + SandboxTemplateClient, SCOPE_NAMES, STATUS_NAMES, } from './client.js'; @@ -30,15 +31,25 @@ function client(impl: Partial>): SandboxClient { return new SandboxClient(transport); } +function templateClient(impl: Partial>): SandboxTemplateClient { + const transport: Transport = createRouterTransport((router) => { + router.service(OpenShell, impl); + }); + return new SandboxTemplateClient(transport); +} + function readySandbox( name: string, id: string, resourceVersion = 7n, + createdFromWorkloadTemplate?: { name: string; resourceVersion: string }, + workspace = 'default', ): MessageInitShape { return { sandbox: { - metadata: { id, name, labels: { team: 'aire' }, resourceVersion }, + metadata: { id, name, workspace, labels: { team: 'aire' }, resourceVersion }, status: { phase: SandboxPhase.READY }, + createdFromWorkloadTemplate, }, }; } @@ -261,6 +272,207 @@ describe('create', () => { expect(created.spec?.providers).toEqual(['claude']); }); + it('createFromTemplate sends the workload template name with governance fields only', async () => { + let created: { + workloadTemplateName?: string; + name?: string; + workspace?: string; + labels?: Record; + spec?: { + policy?: { version?: number }; + providers?: string[]; + command?: string[]; + tty?: boolean; + template?: { image?: string }; + }; + } = {}; + const sandbox = client({ + createSandbox: (req) => { + created = req; + return readySandbox('job-1', 'sb-id', 7n, undefined, req.workspace || 'default'); + }, + }); + const ref = await sandbox.createFromTemplate({ + name: 'job-1', + workspace: 'staging', + templateName: 'gpu-kata', + labels: { team: 'runtime' }, + providers: ['github'], + command: ['/opt/worker', '--serve'], + tty: true, + policy: { version: 1, networkPolicies: {} }, + }); + + expect(created.workloadTemplateName).toBe('gpu-kata'); + expect(created.name).toBe('job-1'); + expect(created.workspace).toBe('staging'); + expect(created.labels).toEqual({ team: 'runtime' }); + expect(created.spec?.providers).toEqual(['github']); + expect(created.spec?.command).toEqual(['/opt/worker', '--serve']); + expect(created.spec?.tty).toBe(true); + expect(created.spec?.policy?.version).toBe(1); + expect(created.spec?.template).toBeUndefined(); + expect(ref.workspace).toBe('staging'); + }); + + it('propagates workspace through sandbox lifecycle calls', async () => { + const observed: { + create?: { workspace?: string }; + get?: { workspace?: string }; + list?: { workspace?: string; allWorkspaces?: boolean }; + delete?: { workspace?: string }; + attach?: { workspace?: string }; + detach?: { workspace?: string }; + listProviders?: { workspace?: string }; + updatePolicy?: { workspace?: string }; + updateSetting?: { workspace?: string }; + configGets: string[]; + execGet?: string; + interactiveGet?: string; + sshGet?: string; + forwardGet?: string; + } = { configGets: [] }; + const sandbox = client({ + createSandbox: (req) => { + observed.create = req; + return readySandbox(req.name || 'sb', 'sb-created', 7n, undefined, req.workspace || 'default'); + }, + getSandbox: (req) => { + if (req.name === 'exec') observed.execGet = req.workspace; + else if (req.name === 'interactive') observed.interactiveGet = req.workspace; + else if (req.name === 'ssh') observed.sshGet = req.workspace; + else if (req.name === 'forward') observed.forwardGet = req.workspace; + else if (req.name === 'config') observed.configGets.push(req.workspace); + else observed.get = req; + return readySandbox(req.name, `${req.name}-id`, 7n, undefined, req.workspace || 'default'); + }, + listSandboxes: (req) => { + observed.list = req; + return { + sandboxes: [ + { + metadata: { + id: 'listed-id', + name: 'listed', + workspace: req.workspace || 'default', + labels: { team: 'aire' }, + resourceVersion: 7n, + }, + status: { phase: SandboxPhase.READY }, + }, + ], + }; + }, + deleteSandbox: (req) => { + observed.delete = req; + return { deleted: true }; + }, + attachSandboxProvider: (req) => { + observed.attach = req; + return { + sandbox: readySandbox(req.sandboxName, 'attach-id', 7n, undefined, req.workspace || 'default').sandbox, + attached: true, + }; + }, + detachSandboxProvider: (req) => { + observed.detach = req; + return { + sandbox: readySandbox(req.sandboxName, 'detach-id', 7n, undefined, req.workspace || 'default').sandbox, + detached: true, + }; + }, + listSandboxProviders: (req) => { + observed.listProviders = req; + return { providers: [] }; + }, + updateConfig: (req) => { + if (req.settingKey) observed.updateSetting = req; + else observed.updatePolicy = req; + return { version: 5, policyHash: 'hash', settingsRevision: 10n, deleted: false }; + }, + getSandboxConfig: () => ({ + policy: { version: 1, networkPolicies: {} }, + version: 5, + policyHash: 'hash', + settings: {}, + configRevision: 1n, + policySource: PolicySource.SANDBOX, + globalPolicyVersion: 0, + providerEnvRevision: 0n, + }), + // eslint-disable-next-line require-yield + execSandbox: async function* () { + yield { payload: { case: 'exit', value: { exitCode: 0 } } }; + }, + // eslint-disable-next-line require-yield + execSandboxInteractive: async function* () { + yield { payload: { case: 'exit', value: { exitCode: 0 } } }; + }, + createSshSession: (req) => ({ + sandboxId: req.sandboxId, + token: 'tok', + gatewayHost: 'gw', + gatewayPort: 443, + gatewayScheme: 'https', + hostKeyFingerprint: '', + expiresAtMs: 0n, + }), + revokeSshSession: () => ({ revoked: true }), + }); + + const created = await sandbox.create({ name: 'direct', workspace: 'staging', image: 'img' }); + const got = await sandbox.get('lookup', { workspace: 'staging' }); + const listed = await sandbox.list({ workspace: 'staging', limit: 10 }); + const deleted = await sandbox.delete('lookup', { workspace: 'staging' }); + await expect(sandbox.waitReady('lookup', 1, { workspace: 'staging' })).resolves.toMatchObject({ + workspace: 'staging', + }); + await expect(sandbox.exec('exec', ['true'], { workspace: 'staging' })).resolves.toMatchObject({ exitCode: 0 }); + const interactive = await sandbox.execInteractive('interactive', ['true'], { workspace: 'staging' }); + for await (const _event of interactive.output) { + // drain + } + await sandbox.createSshSession('ssh', { workspace: 'staging' }); + const attached = await sandbox.attachProvider('lookup', 'github', { workspace: 'staging' }); + const detached = await sandbox.detachProvider('lookup', 'github', { workspace: 'staging' }); + await sandbox.listProviders('lookup', { workspace: 'staging' }); + await sandbox.getConfig('config', { workspace: 'staging' }); + await sandbox.setPolicy('lookup', { version: 1, networkPolicies: {} }, { workspace: 'staging' }); + await sandbox.setSetting( + 'lookup', + 'feature.enabled', + { value: { case: 'boolValue', value: true } }, + { workspace: 'staging' }, + ); + + expect(created.workspace).toBe('staging'); + expect(got.workspace).toBe('staging'); + expect(listed[0]?.workspace).toBe('staging'); + expect(deleted).toBe(true); + expect(attached.sandbox.workspace).toBe('staging'); + expect(detached.sandbox.workspace).toBe('staging'); + expect(observed.create?.workspace).toBe('staging'); + expect(observed.get?.workspace).toBe('staging'); + expect(observed.list).toMatchObject({ workspace: 'staging', allWorkspaces: false }); + expect(observed.delete?.workspace).toBe('staging'); + expect(observed.execGet).toBe('staging'); + expect(observed.interactiveGet).toBe('staging'); + expect(observed.sshGet).toBe('staging'); + expect(observed.attach?.workspace).toBe('staging'); + expect(observed.detach?.workspace).toBe('staging'); + expect(observed.listProviders?.workspace).toBe('staging'); + expect(observed.configGets).toContain('staging'); + expect(observed.updatePolicy?.workspace).toBe('staging'); + expect(observed.updateSetting?.workspace).toBe('staging'); + }); + + it('createFromTemplate rejects an empty template name locally', async () => { + const sandbox = client({}); + await expect(sandbox.createFromTemplate({ templateName: ' ' })).rejects.toMatchObject({ + code: 'invalid_config', + }); + }); + it('rejects gateway sandboxes missing required metadata', async () => { const sandbox = client({ getSandbox: () => ({ sandbox: { status: { phase: SandboxPhase.READY } } }), @@ -288,6 +500,158 @@ describe('create', () => { exitCode: 9, }); }); + + it('maps workload template provenance onto SandboxRef', async () => { + const sandbox = client({ + getSandbox: () => + readySandbox('from-template', 'sb-id', 7n, { + name: 'gpu-kata', + resourceVersion: '42', + }), + }); + + const ref = await sandbox.get('from-template'); + + expect(ref.createdFromWorkloadTemplate).toEqual({ + name: 'gpu-kata', + resourceVersion: '42', + }); + }); +}); + +describe('sandbox templates', () => { + it('create sends the template resource and workspace', async () => { + let observed: { + workspace?: string; + template?: { + metadata?: { name?: string; labels?: Record }; + spec?: { + workload?: { + image?: string; + environment?: Record; + resources?: { cpu?: string; memory?: string; gpu?: { count?: number } }; + }; + driverConfig?: Record; + }; + }; + } = {}; + const templates = templateClient({ + createSandboxTemplate: (req) => { + observed = req; + return { + template: { + metadata: { + id: 'template-python', + name: req.template?.metadata?.name ?? '', + labels: req.template?.metadata?.labels ?? {}, + workspace: req.workspace, + resourceVersion: 1n, + }, + spec: req.template?.spec, + }, + }; + }, + }); + + const created = await templates.create( + { + metadata: { name: 'python', labels: { team: 'runtime' } }, + spec: { + workload: { + image: 'ghcr.io/nvidia/openshell-community/sandboxes/python:latest', + environment: { FEATURE_FLAG: 'on' }, + resources: { cpu: '1', memory: '512Mi', gpu: { count: 1 } }, + }, + driverConfig: { kubernetes: { runtime_class_name: 'kata-containers' } }, + }, + }, + { workspace: 'default' }, + ); + + expect(observed.workspace).toBe('default'); + expect(observed.template?.metadata?.name).toBe('python'); + expect(observed.template?.metadata?.labels).toEqual({ team: 'runtime' }); + expect(observed.template?.spec?.workload?.environment).toEqual({ FEATURE_FLAG: 'on' }); + expect(observed.template?.spec?.workload?.resources?.gpu?.count).toBe(1); + expect(created.metadata?.workspace).toBe('default'); + expect(created.metadata?.resourceVersion).toBe(1n); + }); + + it('get list and delete forward workspace and pagination', async () => { + const observed: { + get?: { name?: string; workspace?: string }; + list?: { limit?: number; offset?: number; workspace?: string; allWorkspaces?: boolean }; + delete?: { name?: string; workspace?: string }; + } = {}; + const templates = templateClient({ + getSandboxTemplate: (req) => { + observed.get = req; + return { + template: { + metadata: { id: 'template-gpu-kata', name: req.name, workspace: req.workspace }, + spec: { workload: { image: 'img:v1' } }, + }, + }; + }, + listSandboxTemplates: (req) => { + observed.list = req; + return { + templates: [ + { + metadata: { id: 'template-python', name: 'python', workspace: req.workspace || 'default' }, + spec: { workload: { image: 'img:v1' } }, + }, + ], + }; + }, + deleteSandboxTemplate: (req) => { + observed.delete = req; + return { deleted: true }; + }, + }); + + const got = await templates.get('gpu-kata', { workspace: 'staging' }); + const listed = await templates.list({ workspace: 'staging', limit: 10, offset: 2, labelSelector: 'team=runtime' }); + const deleted = await templates.delete('gpu-kata', { workspace: 'staging' }); + + expect(got.metadata?.name).toBe('gpu-kata'); + expect(listed).toHaveLength(1); + expect(deleted).toBe(true); + expect(observed.get).toMatchObject({ name: 'gpu-kata', workspace: 'staging' }); + expect(observed.list).toMatchObject({ + limit: 10, + offset: 2, + workspace: 'staging', + allWorkspaces: false, + labelSelector: 'team=runtime', + }); + expect(observed.delete).toMatchObject({ name: 'gpu-kata', workspace: 'staging' }); + }); + + it('list clears workspace when allWorkspaces is set', async () => { + let observed: { workspace?: string; allWorkspaces?: boolean } = {}; + const templates = templateClient({ + listSandboxTemplates: (req) => { + observed = req; + return { templates: [] }; + }, + }); + + await templates.list({ workspace: 'staging', allWorkspaces: true }); + + expect(observed.workspace).toBe(''); + expect(observed.allWorkspaces).toBe(true); + }); + + it('rejects empty names and missing template responses locally', async () => { + const templates = templateClient({ + getSandboxTemplate: () => ({}), + }); + + await expect(templates.get(' ')).rejects.toMatchObject({ code: 'invalid_config' }); + await expect(templates.delete(' ')).rejects.toMatchObject({ code: 'invalid_config' }); + await expect(templates.get('missing-response')).rejects.toMatchObject({ code: 'invalid_config' }); + }); }); describe('waits', () => { diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.ts index d2bf520800..25b6f952f8 100644 --- a/sdk/typescript/src/client.ts +++ b/sdk/typescript/src/client.ts @@ -17,12 +17,13 @@ import type { MessageInitShape } from '@bufbuild/protobuf'; import { type CallOptions, type Client, createClient, type Transport } from '@connectrpc/connect'; import { errorCode, fromConnect, SdkError } from './errors.js'; import type { Provider } from './gen/datamodel_pb.js'; -import type { Sandbox, UpdateConfigResponse } from './gen/openshell_pb.js'; +import type { Sandbox, SandboxWorkloadTemplate, UpdateConfigResponse } from './gen/openshell_pb.js'; import { type ExecSandboxInputSchema, OpenShell, SandboxPhase, type SandboxSpecSchema, + type SandboxWorkloadTemplateSchema, ServiceStatus, type TcpForwardFrameSchema, } from './gen/openshell_pb.js'; @@ -31,9 +32,16 @@ import { PolicySource, type SandboxPolicySchema, SettingScope, type SettingValue import { validateSshResponse } from './ssh-validate.js'; import { buildTransport, type ConnectOptions } from './transport.js'; -// The policy and setting value shapes are the generated protobuf messages; -// re-export them rather than re-curating a parallel surface. Callers round-trip -// `getConfig().policy` back into `setPolicy`, and build `SettingValue`s inline. +// Generated protobuf message shapes that callers need to populate or round-trip +// directly. Re-export these rather than re-curating parallel surfaces. +export type { + SandboxResources, + SandboxServiceLevel, + SandboxStartup, + SandboxWorkloadConfig, + SandboxWorkloadTemplate, + SandboxWorkloadTemplateSpec, +} from './gen/openshell_pb.js'; export type { SandboxPolicy, SettingValue } from './gen/sandbox_pb.js'; export type { ConnectOptions }; export { errorCode }; @@ -78,6 +86,8 @@ export interface Health { export interface SandboxSpec { name?: string; + /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + workspace?: string; image?: string; labels?: Record; environment?: Record; @@ -103,24 +113,74 @@ export interface SandboxSpec { rawSpec?: MessageInitShape; } +export interface SandboxFromTemplateSpec { + name?: string; + /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + workspace?: string; + templateName: string; + labels?: Record; + providers?: string[]; + /** Exact canonical command. Empty selects the gateway scratch shell. */ + command?: string[]; + /** Allocate a retained pseudo-terminal for the canonical command. */ + tty?: boolean; + /** + * Create-time sandbox policy (the safety boundary). The named workload + * template supplies runtime workload fields. + */ + policy?: MessageInitShape; +} + export interface SandboxRef { id: string; name: string; + workspace: string; phase: SandboxPhaseName; labels: Record; /** u64 rendered as a string — JS numbers can't hold it safely. */ resourceVersion: string; mainProcessInstanceId?: string; exitCode?: number; + createdFromWorkloadTemplate?: SandboxWorkloadTemplateProvenance; +} + +export interface SandboxWorkloadTemplateProvenance { + name: string; + resourceVersion: string; } export interface ListOptions { limit?: number; offset?: number; labelSelector?: string; + /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + workspace?: string; + /** List across all workspaces. Requires platform admin permission. */ + allWorkspaces?: boolean; +} + +export interface SandboxWorkspaceOptions { + /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + workspace?: string; +} + +export type SandboxCallOptions = CallOptions & SandboxWorkspaceOptions; + +export interface SandboxTemplateWorkspaceOptions { + /** Workspace scope. Omit or use an empty string for the gateway default workspace. */ + workspace?: string; +} + +export interface SandboxTemplateListOptions extends SandboxTemplateWorkspaceOptions { + limit?: number; + offset?: number; + /** Optional label selector in key=value comma-separated form. */ + labelSelector?: string; + /** List templates across all workspaces. Requires platform admin permission. */ + allWorkspaces?: boolean; } -export interface ExecOptions { +export interface ExecOptions extends SandboxWorkspaceOptions { workdir?: string; environment?: Record; timeoutSecs?: number; @@ -158,7 +218,7 @@ export interface ExecExitEvent { /** An exec stream item: a stdout/stderr chunk or the terminal exit event. */ export type ExecStreamEvent = ExecStreamChunk | ExecExitEvent; -export interface ExecInteractiveOptions { +export interface ExecInteractiveOptions extends SandboxWorkspaceOptions { workdir?: string; environment?: Record; timeoutSecs?: number; @@ -190,12 +250,12 @@ export interface ExecInteractiveSession { } /** Cancellation for the poll-based wait helpers. */ -export interface WaitOptions { +export interface WaitOptions extends SandboxWorkspaceOptions { /** Abort the wait (and the in-flight poll RPC) early. */ signal?: AbortSignal; } -export interface ForwardOptions { +export interface ForwardOptions extends SandboxWorkspaceOptions { /** Loopback TCP port inside the sandbox to dial. */ targetPort: number; /** Target host inside the sandbox (loopback only). Default 127.0.0.1. */ @@ -248,7 +308,7 @@ export interface ProviderChange { changed: boolean; } -export interface ProviderChangeOptions { +export interface ProviderChangeOptions extends SandboxWorkspaceOptions { /** Pin the sandbox resource version for optimistic concurrency (u64 as string). */ expectedResourceVersion?: string; } @@ -274,7 +334,7 @@ export interface SandboxConfig { providerEnvRevision: string; } -export interface SetPolicyOptions { +export interface SetPolicyOptions extends SandboxWorkspaceOptions { /** Pin the sandbox resource version for optimistic concurrency (u64 as string). */ expectedResourceVersion?: string; /** Poll getConfig until the applied policy hash is observed. */ @@ -346,14 +406,26 @@ function sandboxRef(sandbox: Sandbox | undefined): SandboxRef { return { id: meta.id, name: meta.name, + workspace: meta.workspace, phase: phaseName(sandbox.status?.phase ?? SandboxPhase.UNSPECIFIED), labels: meta?.labels ?? {}, resourceVersion: (meta?.resourceVersion ?? 0n).toString(), mainProcessInstanceId: sandbox.status?.mainProcessInstanceId || undefined, exitCode: sandbox.status?.exitCode, + createdFromWorkloadTemplate: sandbox.createdFromWorkloadTemplate + ? { + name: sandbox.createdFromWorkloadTemplate.name, + resourceVersion: sandbox.createdFromWorkloadTemplate.resourceVersion, + } + : undefined, }; } +function sandboxTemplate(template: SandboxWorkloadTemplate | undefined): SandboxWorkloadTemplate { + if (!template) throw new SdkError('invalid_config', 'sandbox template missing from gateway response'); + return template; +} + function providerRef(provider: Provider): ProviderRef { const meta = provider.metadata; return { @@ -419,6 +491,16 @@ function versionPin(value: string | undefined): bigint { const FORWARD_CHUNK = 64 * 1024; +function workspaceOption(options?: SandboxWorkspaceOptions | null): string { + return options?.workspace ?? ''; +} + +function requestCallOptions(options?: SandboxCallOptions | null): CallOptions | undefined { + if (!options) return undefined; + const { workspace: _workspace, ...callOptions } = options; + return callOptions; +} + // Build CallOptions that bound one poll RPC by the remaining wall-clock budget // and honor caller cancellation, so a stalled RPC cannot outlive the deadline. function deadlineOptions(remainingMs: number, signal?: AbortSignal): CallOptions { @@ -536,6 +618,85 @@ export class Pushable implements AsyncIterable { } } +// ---- sandbox template client ---------------------------------------------- + +// Reusable sandbox workload template lifecycle. Templates intentionally return +// generated proto messages because the resource owns portable workload fields +// plus driver-specific config that should not be lossy in the curated layer. +export class SandboxTemplateClient { + private readonly grpc: Client; + + readonly raw: Client; + readonly transport: Transport; + + constructor(transport: Transport, grpc = createClient(OpenShell, transport)) { + this.transport = transport; + this.grpc = grpc; + this.raw = this.grpc; + } + + static async connect(options: ConnectOptions): Promise { + return new SandboxTemplateClient(buildTransport(options)); + } + + async create( + template: MessageInitShape, + options?: SandboxTemplateWorkspaceOptions | null, + ): Promise { + try { + const resp = await this.grpc.createSandboxTemplate({ + template, + workspace: options?.workspace ?? '', + }); + return sandboxTemplate(resp.template); + } catch (e) { + throw e instanceof SdkError ? e : fromConnect(e); + } + } + + async get(name: string, options?: SandboxTemplateWorkspaceOptions | null): Promise { + if (name.trim() === '') throw new SdkError('invalid_config', 'template name is required'); + try { + const resp = await this.grpc.getSandboxTemplate({ + name, + workspace: options?.workspace ?? '', + }); + return sandboxTemplate(resp.template); + } catch (e) { + throw e instanceof SdkError ? e : fromConnect(e); + } + } + + async list(options?: SandboxTemplateListOptions | null): Promise { + try { + const allWorkspaces = options?.allWorkspaces ?? false; + const resp = await this.grpc.listSandboxTemplates({ + limit: options?.limit ?? 0, + offset: options?.offset ?? 0, + workspace: allWorkspaces ? '' : (options?.workspace ?? ''), + allWorkspaces, + labelSelector: options?.labelSelector ?? '', + }); + return resp.templates; + } catch (e) { + throw fromConnect(e); + } + } + + async delete(name: string, options?: SandboxTemplateWorkspaceOptions | null): Promise { + if (name.trim() === '') throw new SdkError('invalid_config', 'template name is required'); + try { + const resp = await this.grpc.deleteSandboxTemplate({ + name, + workspace: options?.workspace ?? '', + }); + return resp.deleted; + } catch (e) { + throw fromConnect(e); + } + } +} + // ---- sandbox client -------------------------------------------------------- // Sandbox lifecycle + exec. Usable standalone via `SandboxClient.connect()`, @@ -590,6 +751,7 @@ export class SandboxClient { const resp = await this.grpc.createSandbox({ name: spec.name ?? '', labels: spec.labels ?? {}, + workspace: spec.workspace ?? '', spec: specInit, }); return sandboxRef(resp.sandbox); @@ -598,9 +760,33 @@ export class SandboxClient { } } - async get(name: string, callOptions?: CallOptions): Promise { + async createFromTemplate(spec: SandboxFromTemplateSpec): Promise { + if (spec.templateName.trim() === '') throw new SdkError('invalid_config', 'templateName is required'); try { - const resp = await this.grpc.getSandbox({ name }, callOptions); + const resp = await this.grpc.createSandbox({ + name: spec.name ?? '', + labels: spec.labels ?? {}, + workspace: spec.workspace ?? '', + spec: { + providers: spec.providers ?? [], + command: spec.command ?? [], + tty: spec.tty ?? false, + policy: spec.policy, + }, + workloadTemplateName: spec.templateName, + }); + return sandboxRef(resp.sandbox); + } catch (e) { + throw fromConnect(e); + } + } + + async get(name: string, options?: SandboxCallOptions | null): Promise { + try { + const resp = await this.grpc.getSandbox( + { name, workspace: workspaceOption(options) }, + requestCallOptions(options), + ); return sandboxRef(resp.sandbox); } catch (e) { throw fromConnect(e); @@ -609,10 +795,13 @@ export class SandboxClient { async list(options?: ListOptions | null): Promise { try { + const allWorkspaces = options?.allWorkspaces ?? false; const resp = await this.grpc.listSandboxes({ limit: options?.limit ?? 0, offset: options?.offset ?? 0, labelSelector: options?.labelSelector ?? '', + workspace: allWorkspaces ? '' : (options?.workspace ?? ''), + allWorkspaces, }); return resp.sandboxes.map((s) => sandboxRef(s)); } catch (e) { @@ -620,9 +809,9 @@ export class SandboxClient { } } - async delete(name: string): Promise { + async delete(name: string, options?: SandboxWorkspaceOptions | null): Promise { try { - const resp = await this.grpc.deleteSandbox({ name }); + const resp = await this.grpc.deleteSandbox({ name, workspace: workspaceOption(options) }); return resp.deleted; } catch (e) { throw fromConnect(e); @@ -641,7 +830,10 @@ export class SandboxClient { if (Date.now() >= deadline) throw new SdkError('connect', `timed out waiting for sandbox '${name}'`); let ref: SandboxRef; try { - ref = await this.get(name, deadlineOptions(deadline - Date.now(), signal)); + ref = await this.get(name, { + ...deadlineOptions(deadline - Date.now(), signal), + workspace: options?.workspace, + }); } catch (e) { throw mapWaitError(e, name, deadline, signal); } @@ -664,7 +856,7 @@ export class SandboxClient { if (signal?.aborted) throw new SdkError('connect', `wait for sandbox '${name}' aborted`); if (Date.now() >= deadline) throw new SdkError('connect', `timed out waiting for sandbox '${name}' to delete`); try { - await this.get(name, deadlineOptions(deadline - Date.now(), signal)); + await this.get(name, { ...deadlineOptions(deadline - Date.now(), signal), workspace: options?.workspace }); } catch (e) { if (e instanceof SdkError && e.code === 'not_found') return; throw mapWaitError(e, name, deadline, signal); @@ -687,7 +879,10 @@ export class SandboxClient { ): AsyncGenerator { try { // Resolve the sandbox id first, exactly like the gateway client. - const sandbox = await this.get(name, options?.signal ? { signal: options.signal } : undefined); + const sandbox = await this.get(name, { + workspace: options?.workspace, + ...(options?.signal ? { signal: options.signal } : {}), + }); const stream = this.grpc.execSandbox( { sandboxId: sandbox.id, @@ -761,7 +956,9 @@ export class SandboxClient { ): Promise { let sandboxId: string; try { - sandboxId = (await this.get(name, options?.signal ? { signal: options.signal } : undefined)).id; + sandboxId = ( + await this.get(name, { workspace: options?.workspace, ...(options?.signal ? { signal: options.signal } : {}) }) + ).id; } catch (e) { throw e instanceof SdkError ? e : fromConnect(e); } @@ -880,7 +1077,7 @@ export class SandboxClient { let sandboxId: string; try { - const ref = await this.get(name, opts.signal ? { signal: opts.signal } : undefined); + const ref = await this.get(name, { workspace: opts.workspace, ...(opts.signal ? { signal: opts.signal } : {}) }); if (ref.phase !== 'ready') { throw new SdkError('connect', `sandbox '${name}' is not ready (phase: ${ref.phase})`); } @@ -1061,9 +1258,9 @@ export class SandboxClient { // Mint a short-lived SSH session token for the sandbox — the input side of // ssh-config / ProxyCommand and forwardTcp authorization. - async createSshSession(name: string): Promise { + async createSshSession(name: string, options?: SandboxWorkspaceOptions | null): Promise { try { - const sandbox = await this.get(name); + const sandbox = await this.get(name, options); const resp = await this.grpc.createSshSession({ sandboxId: sandbox.id }); // Reject any response outside the proto trust-boundary contract before // handing these values to the caller (they feed OpenSSH ProxyCommand). @@ -1101,6 +1298,7 @@ export class SandboxClient { sandboxName: name, providerName: provider, expectedResourceVersion: versionPin(options?.expectedResourceVersion), + workspace: workspaceOption(options), }); return { sandbox: sandboxRef(resp.sandbox), changed: resp.attached }; } catch (e) { @@ -1118,6 +1316,7 @@ export class SandboxClient { sandboxName: name, providerName: provider, expectedResourceVersion: versionPin(options?.expectedResourceVersion), + workspace: workspaceOption(options), }); return { sandbox: sandboxRef(resp.sandbox), changed: resp.detached }; } catch (e) { @@ -1125,19 +1324,19 @@ export class SandboxClient { } } - async listProviders(name: string): Promise { + async listProviders(name: string, options?: SandboxWorkspaceOptions | null): Promise { try { - const resp = await this.grpc.listSandboxProviders({ sandboxName: name }); + const resp = await this.grpc.listSandboxProviders({ sandboxName: name, workspace: workspaceOption(options) }); return resp.providers.map((p) => providerRef(p)); } catch (e) { throw fromConnect(e); } } - async getConfig(name: string, callOptions?: CallOptions): Promise { + async getConfig(name: string, options?: SandboxCallOptions | null): Promise { try { - const sandbox = await this.get(name, callOptions); - const resp = await this.grpc.getSandboxConfig({ sandboxId: sandbox.id }, callOptions); + const sandbox = await this.get(name, options); + const resp = await this.grpc.getSandboxConfig({ sandboxId: sandbox.id }, requestCallOptions(options)); return sandboxConfig(resp); } catch (e) { throw e instanceof SdkError ? e : fromConnect(e); @@ -1159,9 +1358,11 @@ export class SandboxClient { policy, global: false, expectedResourceVersion: versionPin(options?.expectedResourceVersion), + workspace: workspaceOption(options), }); const result = updateConfigResult(resp); - if (options?.wait) await this.waitForPolicyHash(name, result.policyHash, options.waitTimeoutSecs); + if (options?.wait) + await this.waitForPolicyHash(name, result.policyHash, options.waitTimeoutSecs, options.workspace); return result; } catch (e) { throw e instanceof SdkError ? e : fromConnect(e); @@ -1174,6 +1375,7 @@ export class SandboxClient { name: string, key: string, value: MessageInitShape, + options?: SandboxWorkspaceOptions | null, ): Promise { try { const resp = await this.grpc.updateConfig({ @@ -1181,6 +1383,7 @@ export class SandboxClient { settingKey: key, settingValue: value, global: false, + workspace: workspaceOption(options), }); return updateConfigResult(resp); } catch (e) { @@ -1191,13 +1394,18 @@ export class SandboxClient { // Poll getConfig until the applied policy hash is observed. Each poll RPC is // bounded by the remaining deadline (deadlineOptions), so a stalled getConfig // cannot make the returned promise outlive timeoutSecs. - private async waitForPolicyHash(name: string, policyHash: string, timeoutSecs = 60): Promise { + private async waitForPolicyHash( + name: string, + policyHash: string, + timeoutSecs = 60, + workspace?: string, + ): Promise { const deadline = Date.now() + timeoutSecs * 1000; let delay = 100; for (;;) { let config: SandboxConfig; try { - config = await this.getConfig(name, deadlineOptions(deadline - Date.now())); + config = await this.getConfig(name, { ...deadlineOptions(deadline - Date.now()), workspace }); } catch (e) { if (Date.now() >= deadline) { throw new SdkError('connect', `timed out waiting for policy '${policyHash}' on sandbox '${name}'`); @@ -1219,6 +1427,8 @@ export class SandboxClient { export class OpenShellClient { /** Sandbox lifecycle + exec: create/get/list/delete, waitReady/waitDeleted, exec. */ readonly sandbox: SandboxClient; + /** Reusable sandbox workload template lifecycle. */ + readonly sandboxTemplates: SandboxTemplateClient; /** * Advanced escape hatch: a generated client for every gateway RPC, including @@ -1238,6 +1448,7 @@ export class OpenShellClient { this.grpc = createClient(OpenShell, transport); this.raw = this.grpc; this.sandbox = new SandboxClient(transport, this.grpc); + this.sandboxTemplates = new SandboxTemplateClient(transport, this.grpc); } /** diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 61cdce3871..31571865be 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -23,10 +23,20 @@ export type { ProviderChangeOptions, ProviderRef, SandboxConfig, + SandboxFromTemplateSpec, SandboxPhaseName, SandboxPolicy, SandboxRef, + SandboxResources, + SandboxServiceLevel, SandboxSpec, + SandboxStartup, + SandboxTemplateListOptions, + SandboxTemplateWorkspaceOptions, + SandboxWorkloadConfig, + SandboxWorkloadTemplate, + SandboxWorkloadTemplateProvenance, + SandboxWorkloadTemplateSpec, SetPolicyOptions, SettingScopeName, SettingValue, @@ -34,7 +44,7 @@ export type { UpdateConfigResult, WaitOptions, } from './client.js'; -export { errorCode, OpenShellClient, SandboxClient } from './client.js'; +export { errorCode, OpenShellClient, SandboxClient, SandboxTemplateClient } from './client.js'; export type { SdkErrorCode } from './errors.js'; export { SdkError } from './errors.js'; export type { ClientCredentialsOptions, OidcTokenProvider } from './oidc.js'; diff --git a/tasks/ci.toml b/tasks/ci.toml index 4c0b5f8ea7..cc4158448f 100644 --- a/tasks/ci.toml +++ b/tasks/ci.toml @@ -31,7 +31,7 @@ hide = true description = "Build release Rust binaries consumed by the hand-staged snap" run = [ "cargo build --release -p openshell-cli", - "cargo build --release -p openshell-server --features bundled-z3", + "cargo build --release -p openshell-gateway --features bundled-z3", "cargo build --release -p openshell-sandbox", ] diff --git a/tasks/gateway.toml b/tasks/gateway.toml index fb88849348..bbf309c459 100644 --- a/tasks/gateway.toml +++ b/tasks/gateway.toml @@ -5,7 +5,7 @@ ["build:gateway"] description = "Build the standalone openshell-gateway binary" -run = "cargo build -p openshell-server --bin openshell-gateway" +run = "cargo build -p openshell-gateway --bin openshell-gateway" hide = true ["gateway"] diff --git a/tasks/helm.toml b/tasks/helm.toml index f7db8f9c57..525e9c2e51 100644 --- a/tasks/helm.toml +++ b/tasks/helm.toml @@ -4,27 +4,36 @@ # Helm chart tasks ["helm:docs"] -description = "Generate the openshell Helm chart README from Chart.yaml, values.yaml, and README.md.gotmpl" -run = "helm-docs --chart-search-root deploy/helm/openshell" +description = "Generate the OpenShell gateway and workspace Helm chart READMEs" +run = """ + helm-docs --chart-search-root deploy/helm/openshell + helm-docs --chart-search-root deploy/helm/openshell-workspace +""" ["helm:docs:check"] description = "Verify the openshell Helm chart README is generated and up to date" run = """ set -e - tmp="$(mktemp)" - trap 'rm -f "$tmp"' EXIT + gateway_tmp="$(mktemp)" + workspace_tmp="$(mktemp)" + trap 'rm -f "$gateway_tmp" "$workspace_tmp"' EXIT - helm-docs --chart-search-root deploy/helm/openshell --dry-run > "$tmp" - if ! diff -u deploy/helm/openshell/README.md "$tmp"; then + helm-docs --chart-search-root deploy/helm/openshell --dry-run > "$gateway_tmp" + if ! diff -u deploy/helm/openshell/README.md "$gateway_tmp"; then echo "Helm chart README is out of sync. Run: mise run helm:docs" >&2 exit 1 fi + helm-docs --chart-search-root deploy/helm/openshell-workspace --dry-run > "$workspace_tmp" + if ! diff -u deploy/helm/openshell-workspace/README.md "$workspace_tmp"; then + echo "Workspace Helm chart README is out of sync. Run: mise run helm:docs" >&2 + exit 1 + fi """ run_windows = "echo Skipping helm:docs:check: Helm validation is not part of the native Windows lane." hide = true ["helm:lint"] -description = "Lint the openshell Helm chart (defaults + all CI configuration variants)" +description = "Lint the OpenShell gateway and workspace Helm charts" run = """ set -e helm dependency build deploy/helm/openshell @@ -37,12 +46,14 @@ run = """ echo "values files: deploy/helm/openshell/values.yaml, $f" helm lint deploy/helm/openshell -f "$f" --set agentSandbox.preflight.enabled=false done + echo "--- helm lint: workspace defaults ---" + helm lint deploy/helm/openshell-workspace echo "All variants passed." """ run_windows = "echo Skipping helm:lint: Helm validation is not part of the native Windows lane." ["helm:test"] -description = "Run Helm chart unit tests" +description = "Run gateway and workspace Helm chart unit tests" run = """ set -e if ! helm plugin list | grep -q unittest; then @@ -50,6 +61,8 @@ run = """ fi helm dependency build deploy/helm/openshell helm unittest deploy/helm/openshell + helm unittest deploy/helm/openshell-workspace + deploy/helm/test-split-ownership.sh """ run_windows = "echo Skipping helm:test: Helm validation is not part of the native Windows lane." diff --git a/tasks/rust.toml b/tasks/rust.toml index 854c2ac939..03b7ebb7ce 100644 --- a/tasks/rust.toml +++ b/tasks/rust.toml @@ -51,15 +51,21 @@ description = "Verify telemetry emission code is compiled out with --no-default- run = [ # Positive control: the default (telemetry-on) gateway must contain the # markers, so the absent checks below can never become silently vacuous. - "cargo build -p openshell-server --bin openshell-gateway", + "cargo build -p openshell-gateway --bin openshell-gateway", "tasks/scripts/verify-telemetry-compiled-out.sh present target/debug/openshell-gateway", - # Guard: telemetry-free builds must contain no telemetry markers. - "cargo build -p openshell-server --bin openshell-gateway --no-default-features", + # Guard: telemetry-free builds must contain no telemetry markers. Built + # through the `defaults-without-telemetry` alias, which is how the docs tell + # operators to produce these artifacts. + "cargo build -p openshell-gateway --bin openshell-gateway --no-default-features --features defaults-without-telemetry", "tasks/scripts/verify-telemetry-compiled-out.sh absent target/debug/openshell-gateway", - "cargo build -p openshell-sandbox --bin openshell-sandbox --no-default-features --features bundled-ca-roots", + "cargo build -p openshell-sandbox --bin openshell-sandbox --no-default-features --features defaults-without-telemetry", "tasks/scripts/verify-telemetry-compiled-out.sh absent target/debug/openshell-sandbox", ] +["rust:verify:defaults-without-telemetry"] +description = "Verify the defaults-without-telemetry feature alias matches default minus telemetry and cannot be used additively" +run = "tasks/scripts/verify-defaults-without-telemetry.sh" + ["rust:verify:system-ca-roots"] description = "Verify system CA roots build mode compiles and excludes bundled Mozilla root crates" run = [ diff --git a/tasks/scripts/gateway-docker.sh b/tasks/scripts/gateway-docker.sh index b38bfb7942..6826829fd8 100644 --- a/tasks/scripts/gateway-docker.sh +++ b/tasks/scripts/gateway-docker.sh @@ -161,7 +161,7 @@ fi echo "Building openshell-gateway..." cargo build ${CARGO_BUILD_JOBS_ARG[@]+"${CARGO_BUILD_JOBS_ARG[@]}"} \ - -p openshell-server --bin openshell-gateway + -p openshell-gateway --bin openshell-gateway TLS_DIR="${STATE_DIR}/tls" echo "Generating local gateway credentials..." diff --git a/tasks/scripts/gateway-vm.sh b/tasks/scripts/gateway-vm.sh index 2e8aecc5d0..3818dca364 100755 --- a/tasks/scripts/gateway-vm.sh +++ b/tasks/scripts/gateway-vm.sh @@ -311,7 +311,7 @@ fi echo "==> Building openshell-gateway and openshell-driver-vm" cargo build ${CARGO_BUILD_JOBS_ARG[@]+"${CARGO_BUILD_JOBS_ARG[@]}"} \ - -p openshell-server -p openshell-driver-vm + -p openshell-gateway -p openshell-driver-vm if [ "$(uname -s)" = "Darwin" ]; then echo "==> Codesigning openshell-driver-vm (Hypervisor entitlement)" diff --git a/tasks/scripts/package-deb-install.sh b/tasks/scripts/package-deb-install.sh index b6e4730674..e20d409bbd 100755 --- a/tasks/scripts/package-deb-install.sh +++ b/tasks/scripts/package-deb-install.sh @@ -56,7 +56,7 @@ remove_existing_gateway_registration() { echo "==> Building release binaries" cargo build --release \ -p openshell-cli \ - -p openshell-server \ + -p openshell-gateway \ -p openshell-driver-vm echo "==> Building Debian package" diff --git a/tasks/scripts/stage-prebuilt-binaries.sh b/tasks/scripts/stage-prebuilt-binaries.sh index 757a21298b..fe4913439a 100755 --- a/tasks/scripts/stage-prebuilt-binaries.sh +++ b/tasks/scripts/stage-prebuilt-binaries.sh @@ -124,7 +124,7 @@ components_for_target() { resolve_component() { case "$1" in gateway) - crate=openshell-server + crate=openshell-gateway binary=openshell-gateway target_libc=gnu ;; diff --git a/tasks/scripts/verify-defaults-without-telemetry.sh b/tasks/scripts/verify-defaults-without-telemetry.sh new file mode 100755 index 0000000000..1fd7e67dff --- /dev/null +++ b/tasks/scripts/verify-defaults-without-telemetry.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Verify the `defaults-without-telemetry` alias still means "every default +# feature except telemetry", and that it cannot be used additively. +# +# Cargo cannot subtract a single default feature, so telemetry-free builds use +# `--no-default-features --features defaults-without-telemetry`. Two failure +# modes follow from that, and this guard covers both: +# +# 1. Drift. The alias enumerates the keep-list by hand, so it silently rots +# the moment a crate gains a new default feature. Telemetry-free builds +# would then quietly lose an unrelated default. +# 2. Additive misuse. `--features defaults-without-telemetry` without +# `--no-default-features` would otherwise compile a telemetry-on binary +# that reads as telemetry-free. Each crate root carries a `compile_error!` +# for that combination; this asserts the error is actually wired up. + +set -euo pipefail + +# Crates that define the alias. Each must forward `telemetry` and define +# `defaults-without-telemetry`. +CRATES=( + openshell-gateway + openshell-sandbox + openshell-driver-vm +) + +if ! command -v jq >/dev/null 2>&1; then + echo "error: 'jq' is required to inspect cargo metadata" >&2 + exit 2 +fi + +metadata=$(cargo metadata --no-deps --format-version 1) + +failed=0 +for crate in "${CRATES[@]}"; do + features=$(jq -c --arg crate "$crate" \ + '.packages[] | select(.name == $crate) | .features' <<<"$metadata") + + if [[ -z $features || $features == "null" ]]; then + echo "FAIL: crate '$crate' not found in workspace metadata" >&2 + failed=1 + continue + fi + + if ! jq -e 'has("defaults-without-telemetry")' <<<"$features" >/dev/null; then + echo "FAIL: $crate defines no 'defaults-without-telemetry' feature" >&2 + failed=1 + continue + fi + + expected=$(jq -r '(.default // []) - ["telemetry"] | sort | join(",")' <<<"$features") + actual=$(jq -r '(."defaults-without-telemetry" // []) | sort | join(",")' <<<"$features") + + if [[ $expected != "$actual" ]]; then + echo "FAIL: $crate 'defaults-without-telemetry' is out of sync with 'default'" >&2 + echo " default minus telemetry: [${expected}]" >&2 + echo " defaults-without-telemetry: [${actual}]" >&2 + echo " Update 'defaults-without-telemetry' in crates/$crate/Cargo.toml to match." >&2 + failed=1 + continue + fi + + echo "OK: $crate 'defaults-without-telemetry' == default minus telemetry [${expected}]" +done + +# Additive misuse must be a hard error. Match on the `compile_error!` text +# rather than a nonzero exit code: openshell-driver-vm does not build on every +# host, and a check that failed for an unrelated reason would make this guard +# silently vacuous. +for crate in "${CRATES[@]}"; do + output=$(cargo check -p "$crate" --features defaults-without-telemetry 2>&1 || true) + + if grep -qF "features \`telemetry\` and \`defaults-without-telemetry\` are mutually exclusive" <<<"$output"; then + echo "OK: $crate rejects 'telemetry' + 'defaults-without-telemetry'" + continue + fi + + echo "FAIL: $crate did not reject 'telemetry' + 'defaults-without-telemetry'" >&2 + echo " Expected the mutual-exclusion compile_error! in crates/$crate/src/lib.rs." >&2 + echo " Got:" >&2 + sed 's/^/ /' <<<"$output" | tail -20 >&2 + failed=1 +done + +exit "$failed" diff --git a/tasks/scripts/vm/smoke-orphan-cleanup.sh b/tasks/scripts/vm/smoke-orphan-cleanup.sh index 6da48919d1..7d0b05334d 100755 --- a/tasks/scripts/vm/smoke-orphan-cleanup.sh +++ b/tasks/scripts/vm/smoke-orphan-cleanup.sh @@ -37,7 +37,7 @@ trap cleanup_stray EXIT build_binaries() { echo "==> Ensuring binaries are built" if [ ! -x "$ROOT/target/debug/openshell-gateway" ] || [ ! -x "$ROOT/target/debug/openshell-driver-vm" ]; then - cargo build -p openshell-server -p openshell-driver-vm >&2 + cargo build -p openshell-gateway -p openshell-driver-vm >&2 fi if [ "$(uname -s)" = "Darwin" ]; then codesign \ diff --git a/tasks/scripts/windows-msvc.ps1 b/tasks/scripts/windows-msvc.ps1 index cf1b4c8686..0a0410f4ca 100644 --- a/tasks/scripts/windows-msvc.ps1 +++ b/tasks/scripts/windows-msvc.ps1 @@ -583,7 +583,7 @@ function Assert-GatewayExcludesUnsupportedDriverCrates([string] $RustTarget) { $logName = "build-$RustTarget-driver-tree.log" Invoke-VsCargo ` -RustTarget $RustTarget ` - -CargoArgs "cargo tree -p openshell-server --target $RustTarget --prefix none" ` + -CargoArgs "cargo tree -p openshell-gateway --target $RustTarget --prefix none" ` -LogName $logName $logPath = Join-Path $LogDir $logName @@ -643,7 +643,7 @@ function Invoke-UnsupportedContractTests([string] $RustTarget) { foreach ($test in $tests) { Invoke-VsCargo ` -RustTarget $RustTarget ` - -CargoArgs "cargo test -p openshell-server --target $RustTarget $test $Z3ServerFeatures" ` + -CargoArgs "cargo test -p openshell-gateway --target $RustTarget $test $Z3ServerFeatures" ` -LogName "test-$RustTarget-unsupported-$test.log" } }