diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index d5340f9569..0817e8e882 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -295,14 +295,6 @@ jobs: strategy: matrix: include: - - package: openshell-driver-docker - binary: openshell-driver-docker - triple: x86_64-unknown-linux-gnu - runner: ubuntu-24.04 - - package: openshell-driver-podman - binary: openshell-driver-podman - triple: x86_64-unknown-linux-gnu - runner: ubuntu-24.04 - package: openshell-driver-kubernetes binary: openshell-driver-kubernetes triple: x86_64-unknown-linux-gnu @@ -541,6 +533,7 @@ jobs: checkout-ref: ${{ needs.pr_metadata.outputs.sha }} prebuilt-conformance: true image-tag: ${{ needs.pr_metadata.outputs.sha }} + external-driver-binary: openshell-driver-docker runner: ubuntu-24.04-arm podman-e2e: @@ -555,6 +548,7 @@ jobs: checkout-ref: ${{ needs.pr_metadata.outputs.sha }} prebuilt-conformance: true image-tag: ${{ needs.pr_metadata.outputs.sha }} + external-driver-binary: openshell-driver-podman suite-matrix: >- [{"suite":"ci","runner":"ubuntu-26.04","podman_major":"5","podman_package_version":"5.7.0+ds2-3build1","conmon_package_version":"2.1.13+ds1-2","cmd":"mise run --no-deps --skip-deps e2e:podman:ci"}] @@ -570,6 +564,7 @@ jobs: checkout-ref: ${{ needs.pr_metadata.outputs.sha }} prebuilt-conformance: true image-tag: ${{ needs.pr_metadata.outputs.sha }} + external-driver-binary: openshell-driver-podman suite-matrix: >- [{"suite":"additional-ca","runner":"ubuntu-26.04","podman_major":"5","podman_package_version":"5.7.0+ds2-3build1","conmon_package_version":"2.1.13+ds1-2","cmd":"OPENSHELL_E2E_PODMAN_TEST=additional_ca mise run --no-deps --skip-deps e2e:podman"}] diff --git a/.github/workflows/build-binaries-linux.yml b/.github/workflows/build-binaries-linux.yml index bfe2048b94..9b41355382 100644 --- a/.github/workflows/build-binaries-linux.yml +++ b/.github/workflows/build-binaries-linux.yml @@ -128,6 +128,38 @@ jobs: timeout-minutes: 60 steps: *build_steps + podman-driver: + name: openshell-driver-podman (${{ matrix.triple }}) + env: + PACKAGE: openshell-driver-podman + BINARY: openshell-driver-podman + strategy: + matrix: + include: + - triple: x86_64-unknown-linux-gnu + runner: ubuntu-24.04 + - triple: aarch64-unknown-linux-gnu + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + steps: *build_steps + + docker-driver: + name: openshell-driver-docker (${{ matrix.triple }}) + env: + PACKAGE: openshell-driver-docker + BINARY: openshell-driver-docker + strategy: + matrix: + include: + - triple: x86_64-unknown-linux-gnu + runner: ubuntu-24.04 + - triple: aarch64-unknown-linux-gnu + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + steps: *build_steps + vm-init: name: openshell-vm-init (${{ matrix.triple }}) env: diff --git a/.github/workflows/build-binaries-macos.yml b/.github/workflows/build-binaries-macos.yml index 01933c3b01..574b6d181a 100644 --- a/.github/workflows/build-binaries-macos.yml +++ b/.github/workflows/build-binaries-macos.yml @@ -45,6 +45,12 @@ jobs: - package: openshell-gateway binary: openshell-gateway triple: aarch64-apple-darwin + - package: openshell-driver-podman + binary: openshell-driver-podman + triple: aarch64-apple-darwin + - package: openshell-driver-docker + binary: openshell-driver-docker + triple: aarch64-apple-darwin - package: openshell-supervisor binary: openshell-supervisor triple: aarch64-apple-darwin diff --git a/.github/workflows/build-rpm.yml b/.github/workflows/build-rpm.yml index 5050372df0..2262fc75ef 100644 --- a/.github/workflows/build-rpm.yml +++ b/.github/workflows/build-rpm.yml @@ -90,10 +90,22 @@ jobs: name: openshell-prover-${{ inputs.prover-target }} path: package-binaries/ + - name: Download Podman driver artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-driver-podman-${{ inputs.gateway-target }} + path: package-binaries/ + + - name: Download Docker driver artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-driver-docker-${{ inputs.gateway-target }} + path: package-binaries/ + - name: Configure package inputs run: | set -euo pipefail - chmod +x package-binaries/openshell{,-gateway,-prover} + chmod +x package-binaries/openshell{,-gateway,-prover,-driver-podman,-driver-docker} ls -lah package-binaries - name: Mark workspace safe for git diff --git a/.github/workflows/deb-package.yml b/.github/workflows/deb-package.yml index c3ebabedb6..a4f5cd4650 100644 --- a/.github/workflows/deb-package.yml +++ b/.github/workflows/deb-package.yml @@ -63,10 +63,22 @@ jobs: name: openshell-driver-vm-${{ matrix.gnu_target }} path: package-binaries/ + - name: Download Podman driver artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-driver-podman-${{ matrix.gnu_target }} + path: package-binaries/ + + - name: Download Docker driver artifact + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-driver-docker-${{ matrix.gnu_target }} + path: package-binaries/ + - name: Configure package inputs run: | set -euo pipefail - chmod +x package-binaries/openshell{,-gateway,-prover,-driver-vm} + chmod +x package-binaries/openshell{,-gateway,-prover,-driver-vm,-driver-podman,-driver-docker} ls -lah package-binaries - name: Build Debian package @@ -76,6 +88,8 @@ jobs: OPENSHELL_GATEWAY_BINARY="${PWD}/package-binaries/openshell-gateway" \ OPENSHELL_PROVER_BINARY="${PWD}/package-binaries/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="${PWD}/package-binaries/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="${PWD}/package-binaries/openshell-driver-podman" \ + OPENSHELL_DRIVER_DOCKER_BINARY="${PWD}/package-binaries/openshell-driver-docker" \ OPENSHELL_DEB_VERSION="${INPUTS_DEB_VERSION}" \ OPENSHELL_DEB_ARCH="${{ matrix.deb_arch }}" \ OPENSHELL_OUTPUT_DIR=artifacts \ diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index a53bc53ee6..a8fedd03e1 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -25,6 +25,10 @@ on: required: false type: boolean default: false + external-driver-binary: + required: false + type: string + default: "" suite-matrix: required: false type: string @@ -74,6 +78,11 @@ jobs: with: artifact-name: ${{ inputs.gateway-artifact }} + - if: inputs.external-driver-binary != '' + uses: ./.github/actions/setup-e2e-driver + with: + binary: ${{ inputs.external-driver-binary }} + - uses: ./.github/actions/load-e2e-images with: images: sandbox supervisor diff --git a/.github/workflows/package-release-binaries.yml b/.github/workflows/package-release-binaries.yml index 429e98db19..bd24b0ba01 100644 --- a/.github/workflows/package-release-binaries.yml +++ b/.github/workflows/package-release-binaries.yml @@ -63,6 +63,24 @@ jobs: - artifact: openshell-driver-vm-aarch64-apple-darwin binary: openshell-driver-vm package: driver-vm-macos + - artifact: openshell-driver-podman-x86_64-unknown-linux-gnu + binary: openshell-driver-podman + package: driver-podman-linux-amd64 + - artifact: openshell-driver-docker-x86_64-unknown-linux-gnu + binary: openshell-driver-docker + package: driver-docker-linux-amd64 + - artifact: openshell-driver-podman-aarch64-unknown-linux-gnu + binary: openshell-driver-podman + package: driver-podman-linux-arm64 + - artifact: openshell-driver-docker-aarch64-unknown-linux-gnu + binary: openshell-driver-docker + package: driver-docker-linux-arm64 + - artifact: openshell-driver-podman-aarch64-apple-darwin + binary: openshell-driver-podman + package: driver-podman-macos + - artifact: openshell-driver-docker-aarch64-apple-darwin + binary: openshell-driver-docker + package: driver-docker-macos - artifact: openshell-prover-x86_64-unknown-linux-musl binary: openshell-prover package: prover-binary-linux-amd64 diff --git a/.github/workflows/release-dev.yml b/.github/workflows/release-dev.yml index 352b40993e..422c4652f8 100644 --- a/.github/workflows/release-dev.yml +++ b/.github/workflows/release-dev.yml @@ -198,6 +198,7 @@ jobs: with: image-tag: ${{ github.sha }} checkout-ref: ${{ github.sha }} + external-driver-binary: openshell-driver-docker runner: ubuntu-24.04-arm vm-e2e: @@ -358,6 +359,20 @@ jobs: path: release/ merge-multiple: true + - name: Download Podman driver artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: driver-podman-* + path: release/ + merge-multiple: true + + - name: Download Docker driver artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: driver-docker-* + path: release/ + merge-multiple: true + - name: Download prover binary artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -428,6 +443,12 @@ jobs: openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-apple-darwin.tar.gz \ + openshell-driver-podman-x86_64-unknown-linux-gnu.tar.gz \ + openshell-driver-docker-x86_64-unknown-linux-gnu.tar.gz \ + openshell-driver-podman-aarch64-unknown-linux-gnu.tar.gz \ + openshell-driver-docker-aarch64-unknown-linux-gnu.tar.gz \ + openshell-driver-podman-aarch64-apple-darwin.tar.gz \ + openshell-driver-docker-aarch64-apple-darwin.tar.gz \ *.deb \ openshell-*.rpm > openshell-checksums-sha256.txt cat openshell-checksums-sha256.txt @@ -454,13 +475,19 @@ jobs: --output release/openshell.rb cat release/openshell.rb - - name: Attest VM driver artifacts + - name: Attest driver artifacts uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 with: subject-path: | release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-x86_64-unknown-linux-gnu.tar.gz + release/openshell-driver-docker-x86_64-unknown-linux-gnu.tar.gz + release/openshell-driver-podman-aarch64-unknown-linux-gnu.tar.gz + release/openshell-driver-docker-aarch64-unknown-linux-gnu.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz + release/openshell-driver-docker-aarch64-apple-darwin.tar.gz - name: Prune managed assets from dev release uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9 @@ -554,6 +581,12 @@ jobs: release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-x86_64-unknown-linux-gnu.tar.gz + release/openshell-driver-docker-x86_64-unknown-linux-gnu.tar.gz + release/openshell-driver-podman-aarch64-unknown-linux-gnu.tar.gz + release/openshell-driver-docker-aarch64-unknown-linux-gnu.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz + release/openshell-driver-docker-aarch64-apple-darwin.tar.gz release/openshell-prover-x86_64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-apple-darwin.tar.gz diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 0e10728ae4..3869ad8c59 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -95,6 +95,20 @@ jobs: path: release/ merge-multiple: true + - name: Download Podman driver artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: driver-podman-* + path: release/ + merge-multiple: true + + - name: Download Docker driver artifacts + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: driver-docker-* + path: release/ + merge-multiple: true + - name: Download prover binary artifacts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -140,6 +154,12 @@ jobs: openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz \ openshell-driver-vm-aarch64-apple-darwin.tar.gz \ + openshell-driver-podman-x86_64-unknown-linux-gnu.tar.gz \ + openshell-driver-docker-x86_64-unknown-linux-gnu.tar.gz \ + openshell-driver-podman-aarch64-unknown-linux-gnu.tar.gz \ + openshell-driver-docker-aarch64-unknown-linux-gnu.tar.gz \ + openshell-driver-podman-aarch64-apple-darwin.tar.gz \ + openshell-driver-docker-aarch64-apple-darwin.tar.gz \ openshell_*.deb \ openshell-*.rpm > openshell-checksums-sha256.txt cat openshell-checksums-sha256.txt @@ -422,6 +442,12 @@ jobs: release/openshell-driver-vm-x86_64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-unknown-linux-gnu.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-x86_64-unknown-linux-gnu.tar.gz + release/openshell-driver-docker-x86_64-unknown-linux-gnu.tar.gz + release/openshell-driver-podman-aarch64-unknown-linux-gnu.tar.gz + release/openshell-driver-docker-aarch64-unknown-linux-gnu.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz + release/openshell-driver-docker-aarch64-apple-darwin.tar.gz release/openshell-prover-x86_64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-unknown-linux-musl.tar.gz release/openshell-prover-aarch64-apple-darwin.tar.gz @@ -485,6 +511,8 @@ jobs: release/openshell-aarch64-apple-darwin.tar.gz release/openshell-gateway-aarch64-apple-darwin.tar.gz release/openshell-driver-vm-aarch64-apple-darwin.tar.gz + release/openshell-driver-podman-aarch64-apple-darwin.tar.gz + release/openshell-driver-docker-aarch64-apple-darwin.tar.gz release/openshell-prover-aarch64-apple-darwin.tar.gz release/openshell.rb release/openshell-checksums-sha256.txt diff --git a/.github/workflows/snap-package.yml b/.github/workflows/snap-package.yml index 81f321864d..6597b28df1 100644 --- a/.github/workflows/snap-package.yml +++ b/.github/workflows/snap-package.yml @@ -55,6 +55,12 @@ jobs: name: openshell-gateway-${{ matrix.rust_arch }}-unknown-linux-gnu path: prebuilt/gateway + - name: Download prebuilt Docker driver binary + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: openshell-driver-docker-${{ matrix.rust_arch }}-unknown-linux-gnu + path: prebuilt/docker-driver + - name: Download prebuilt sandbox binary uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: @@ -67,6 +73,7 @@ jobs: chmod +x prebuilt/cli/openshell chmod +x prebuilt/prover/openshell-prover chmod +x prebuilt/gateway/openshell-gateway + chmod +x prebuilt/docker-driver/openshell-driver-docker chmod +x prebuilt/sandbox/openshell-sandbox ls -laR prebuilt/ @@ -78,6 +85,7 @@ jobs: cp prebuilt/cli/openshell snap/prebuilt/openshell cp prebuilt/prover/openshell-prover snap/prebuilt/openshell-prover cp prebuilt/gateway/openshell-gateway snap/prebuilt/openshell-gateway + cp prebuilt/docker-driver/openshell-driver-docker snap/prebuilt/openshell-driver-docker cp prebuilt/sandbox/openshell-sandbox snap/prebuilt/openshell-sandbox cp tasks/scripts/snap-gateway-wrapper.sh snap/prebuilt/openshell-gateway-wrapper diff --git a/AGENTS.md b/AGENTS.md index 1fb29f3a98..4e4d3fe180 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -52,12 +52,14 @@ Do not rely on this file for a full inventory. The detailed public and contribut | `crates/openshell-spiffe/` | SPIFFE identity types | Dependency-light SPIFFE ID mapping, claim parsing, and the sandbox identity provider interface | | `crates/openshell-spire/` | SPIRE adapter | Gateway-owned SPIFFE Broker API client that issues and verifies stable sandbox JWT-SVIDs | | `crates/openshell-tui/` | Terminal UI | Ratatui-based dashboard for monitoring | +| `crates/openshell-driver-launch/` | Driver launch protocol | `DriverLaunch` `GetLaunchInfo`/`Configure` service and the `Deferred` wrapper for launched compute drivers | +| `crates/openshell-driver-sdk/` | Launched-driver SDK | Stdin table reader, start-up exit codes, staged network-trust loader, telemetry and admission conversion, and gateway context | | `crates/openshell-driver-kubernetes-secrets/` | Kubernetes Secrets credential driver | In-process `CredentialDriver` backend for OpenShell-managed K8s Secret storage | | `crates/openshell-driver-vault/` | Vault credential driver | In-process `CredentialDriver` backend for Vault-compatible KV storage | | `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-podman/` | Podman compute driver | In-process `ComputeDriver` backend for local Podman sandbox containers | +| `crates/openshell-driver-docker/` | Docker compute driver | Gateway-launched `ComputeDriver` subprocess for local Docker sandbox containers | +| `crates/openshell-driver-podman/` | Podman compute driver | Gateway-launched `ComputeDriver` subprocess for local Podman sandbox containers | | `crates/openshell-driver-vm/` | VM compute driver | Standalone libkrun-backed `ComputeDriver` subprocess (embeds its own rootfs + runtime) | | [`crates/openshell-driver-mxc/`](https://github.com/ai-openshell/openshell/tree/windows/crates/openshell-driver-mxc) (`windows` branch) | Microsoft MXC compute driver | Native Windows ProcessContainer backend; see the Windows branch for the maintained implementation | | [`crates/openshell-mxc-boundary/`](https://github.com/ai-openshell/openshell/tree/windows/crates/openshell-mxc-boundary) (`windows` branch) | Windows sandbox boundary | Dedicated Windows workload boundary paired with the host supervisor | diff --git a/Cargo.lock b/Cargo.lock index f76c9c406f..5b3cbcadec 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4948,9 +4948,11 @@ dependencies = [ "clap", "futures", "http 1.4.0", + "hyper-util", "libc", "miette", "openshell-core", + "openshell-driver-sdk", "openshell-isolation-interface", "openshell-otel", "openshell-otel-test-support", @@ -4970,6 +4972,7 @@ dependencies = [ "tokio-stream", "toml", "tonic", + "tower", "tower-http 0.6.8", "tracing", "tracing-opentelemetry", @@ -5043,6 +5046,21 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "openshell-driver-launch" +version = "0.0.0" +dependencies = [ + "http 1.4.0", + "prost", + "protoc-bin-vendored", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", + "tonic-prost-build", + "tower", +] + [[package]] name = "openshell-driver-mxc" version = "0.0.0" @@ -5081,6 +5099,7 @@ dependencies = [ "nix 0.29.0", "openshell-core", "openshell-crypto", + "openshell-driver-sdk", "openshell-isolation-interface", "openshell-otel", "openshell-otel-test-support", @@ -5099,7 +5118,9 @@ dependencies = [ "thiserror 2.0.20", "tokio", "tokio-stream", + "toml", "tonic", + "tower", "tower-http 0.6.8", "tracing", "tracing-opentelemetry", @@ -5108,6 +5129,23 @@ dependencies = [ "uuid", ] +[[package]] +name = "openshell-driver-sdk" +version = "0.0.0" +dependencies = [ + "http 1.4.0", + "libc", + "nix 0.29.0", + "openshell-core", + "openshell-crypto", + "openshell-driver-launch", + "openshell-otel", + "serde", + "serde_json", + "tempfile", + "tonic", +] + [[package]] name = "openshell-driver-vault" version = "0.0.0" @@ -5144,6 +5182,7 @@ dependencies = [ "flate2", "futures", "http 1.4.0", + "hyper-util", "libc", "libloading", "miette", @@ -5151,7 +5190,9 @@ dependencies = [ "oci-client", "openshell-core", "openshell-crypto", + "openshell-driver-launch", "openshell-driver-podman", + "openshell-driver-sdk", "openshell-isolation-interface", "openshell-otel", "openshell-otel-test-support", @@ -5173,7 +5214,9 @@ dependencies = [ "tempfile", "tokio", "tokio-stream", + "toml", "tonic", + "tower", "tower-http 0.6.8", "tracing", "tracing-opentelemetry", @@ -5210,19 +5253,19 @@ dependencies = [ "nix 0.29.0", "openshell-core", "openshell-crypto", - "openshell-driver-docker", "openshell-driver-kubernetes", + "openshell-driver-launch", "openshell-driver-mxc", - "openshell-driver-podman", + "openshell-driver-sdk", "openshell-otel", - "openshell-policy", + "openshell-otel-test-support", "openshell-server", "rcgen", "rustix 1.1.6", - "serde", "serde_json", "tempfile", "tokio", + "tokio-stream", "toml", "tonic", "tower", diff --git a/crates/openshell-driver-docker/Cargo.toml b/crates/openshell-driver-docker/Cargo.toml index e4ba6f40c0..de2b341de4 100644 --- a/crates/openshell-driver-docker/Cargo.toml +++ b/crates/openshell-driver-docker/Cargo.toml @@ -18,6 +18,7 @@ path = "src/main.rs" openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction", "otel", "clap"] } openshell-isolation-interface = { path = "../openshell-isolation-interface" } openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } +openshell-driver-sdk = { path = "../openshell-driver-sdk" } openshell-otel = { path = "../openshell-otel" } opentelemetry = { workspace = true } @@ -48,6 +49,8 @@ tar = "0.4" tempfile = "3" [dev-dependencies] +hyper-util = { workspace = true } +tower = { workspace = true } openshell-otel-test-support = { path = "../openshell-otel-test-support" } opentelemetry = { workspace = true } opentelemetry_sdk = { workspace = true, features = ["testing"] } diff --git a/crates/openshell-driver-docker/README.md b/crates/openshell-driver-docker/README.md index 268dca4f4b..670b01f866 100644 --- a/crates/openshell-driver-docker/README.md +++ b/crates/openshell-driver-docker/README.md @@ -317,3 +317,16 @@ The supervisor owns these security-critical variables: Template and sandbox environment is encoded in the protected bootstrap and exposed only to workload children. Workload input cannot override security-critical supervisor variables. + +## Launched mode + +```text +openshell-driver-docker serve --bind-socket --expected-peer-pid --log-level < table.toml +openshell-driver-docker preflight < table.toml +``` + +The gateway passes the `[openshell.drivers.docker]` table on stdin and gateway metadata in a `Configure` call (`proto/driver_launch.proto`). `settings_from_table` in `src/launch.rs` is the only place the table is parsed and validated. + +`serve` resolves the Docker socket from `socket_path`, then `DOCKER_HOST` and the usual locations, and pings it before it binds. It exits 69 when Docker is not reachable and 78 when the table is invalid. Until `Configure` succeeds, both gRPC services (`ComputeDriver` and `ComputeDriverConfigurationUpdates`) return `UNAVAILABLE` and the driver creates no volumes, networks or containers. `preflight` validates the table without contacting Docker. + +The gateway supplies the CA, the admission policy, its listener address, trusted runtime images from its environment, destination trust, and OTLP settings through `Configure`, so the table rejects `guest_tls_ca`, `allow_driver_config` and `resource_admission`. `grpc_endpoint` remains an optional override, and an `https://` endpoint needs the gateway CA. diff --git a/crates/openshell-driver-docker/src/launch.rs b/crates/openshell-driver-docker/src/launch.rs new file mode 100644 index 0000000000..b7bdcf0a45 --- /dev/null +++ b/crates/openshell-driver-docker/src/launch.rs @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! What a gateway-launched Docker driver needs before it serves: the one place +//! the operator's table is parsed, and the backend check. + +use bollard::Docker; + +use crate::{DockerComputeConfig, detect_socket}; + +/// Settings the gateway supplies through `Configure`, or owns itself, so the +/// table cannot set them. The standalone driver still takes some as flags, so +/// the struct keeps the fields. +const GATEWAY_SUPPLIED_KEYS: &[&str] = &[ + "allow_driver_config", + "resource_admission", + "guest_tls_ca", + "guest_tls_cert", + "guest_tls_key", +]; + +/// Parse and validate the operator's `[openshell.drivers.docker]` table. +/// +/// This is the only place the table is parsed. It has no side effects: it +/// needs neither the gateway context nor Docker. An empty table selects the +/// defaults. +pub fn settings_from_table(table: &str) -> Result { + let keys: toml::Table = + toml::from_str(table).map_err(|error| format!("invalid docker driver table: {error}"))?; + if let Some(key) = GATEWAY_SUPPLIED_KEYS + .iter() + .find(|key| keys.contains_key(**key)) + { + return Err(format!( + "invalid docker driver table: `{key}` is supplied by the gateway and cannot be set here" + )); + } + let config: DockerComputeConfig = + toml::from_str(table).map_err(|error| format!("invalid docker driver table: {error}"))?; + if !config.grpc_endpoint.trim().is_empty() { + openshell_driver_sdk::validate_grpc_endpoint(&config.grpc_endpoint)?; + } + config.validate_table().map_err(|error| error.to_string())?; + Ok(config) +} + +/// Check that Docker is reachable with `config`: resolve the socket (the +/// configured one, else the first responsive one) and ping it. Creates +/// nothing. +pub async fn check_backend(config: &DockerComputeConfig) -> Result<(), String> { + let socket = config + .socket_path + .clone() + .or_else(detect_socket) + .ok_or_else(|| { + "no responsive Docker API socket found; set DOCKER_HOST or configure socket_path" + .to_string() + })?; + let socket = socket.to_str().ok_or_else(|| { + format!( + "Docker socket path is not valid UTF-8: {}", + socket.display() + ) + })?; + let docker = Docker::connect_with_socket(socket, 30, bollard::API_DEFAULT_VERSION) + .map_err(|error| format!("failed to create Docker client: {error}"))?; + docker + .ping() + .await + .map(|_| ()) + .map_err(|error| format!("Docker is not reachable at {socket}: {error}")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_empty_table_selects_the_defaults() { + let config = settings_from_table("").unwrap(); + assert!(!config.allow_driver_config); + assert_eq!(config.sandbox_label, "default"); + } + + #[test] + fn existing_operator_keys_are_accepted() { + let config = settings_from_table( + "sandbox_label = \"mine\"\nimage_pull_policy = \"always\"\npersist_workspace = true\nsocket_path = \"/var/run/docker.sock\"\ngrpc_endpoint = \"http://127.0.0.1:8080\"", + ) + .unwrap(); + assert_eq!(config.sandbox_label, "mine"); + assert!(config.persist_workspace); + } + + #[test] + fn gateway_supplied_keys_are_rejected() { + for key in [ + "allow_driver_config = true", + "resource_admission = {}", + "guest_tls_ca = \"/ca.pem\"", + "guest_tls_cert = \"/cert.pem\"", + ] { + let error = settings_from_table(key).unwrap_err(); + assert!(error.contains("supplied by the gateway"), "{key}: {error}"); + } + } + + #[test] + fn unknown_keys_and_bad_endpoints_are_rejected() { + assert!(settings_from_table("no_such_key = 1").is_err()); + assert!(settings_from_table("grpc_endpoint = \"ftp://gw:1\"").is_err()); + } + + #[tokio::test] + async fn an_unreachable_socket_is_reported_not_created() { + let config = settings_from_table("socket_path = \"/nonexistent/docker.sock\"").unwrap(); + let error = check_backend(&config).await.unwrap_err(); + assert!(error.contains("/nonexistent/docker.sock"), "{error}"); + } +} diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index a012b69aaf..b7898463c7 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -7,6 +7,7 @@ mod image_update; mod isolation; +pub mod launch; pub mod otel_tracing; mod workspace; @@ -290,6 +291,18 @@ pub struct DockerComputeConfig { impl DockerComputeConfig { /// Validate startup configuration without connecting to Docker. pub fn validate_configuration(&self, gateway_bind_address: SocketAddr) -> CoreResult<()> { + self.validate_table()?; + if gateway_bind_address.port() == 0 { + return Err(Error::config( + "docker compute driver requires a fixed non-zero gateway bind port", + )); + } + Ok(()) + } + + /// The checks that need neither the gateway nor Docker: everything about + /// the operator's table. + pub fn validate_table(&self) -> CoreResult<()> { self.resource_admission.validate().map_err(Error::config)?; if let Some(socket_path) = self.socket_path.as_deref() && socket_path.to_str().is_none() @@ -309,11 +322,6 @@ impl DockerComputeConfig { openshell_core::driver_utils::validate_provider_spiffe_unix_socket(socket) .map_err(Error::config)?; } - if gateway_bind_address.port() == 0 { - return Err(Error::config( - "docker compute driver requires a fixed non-zero gateway bind port", - )); - } Ok(()) } } diff --git a/crates/openshell-driver-docker/src/main.rs b/crates/openshell-driver-docker/src/main.rs index 55ae263582..3f94fd0855 100644 --- a/crates/openshell-driver-docker/src/main.rs +++ b/crates/openshell-driver-docker/src/main.rs @@ -13,6 +13,8 @@ use openshell_core::sandbox_env::SupervisorOtlpArgs; use openshell_driver_docker::{ComputeDriverService, DockerComputeConfig, DockerComputeDriver}; use tracing::info; +mod serve; + #[derive(Debug, Parser)] #[command(name = "openshell-driver-docker", version = VERSION)] struct Args { @@ -55,6 +57,9 @@ struct Args { #[tokio::main] async fn main() -> Result<()> { + if let Some(code) = serve::dispatch().await { + std::process::exit(code); + } let args = Args::parse(); let _tracing = openshell_otel::install_driver_tracing( openshell_driver_docker::otel_tracing::TRACING, diff --git a/crates/openshell-driver-docker/src/serve.rs b/crates/openshell-driver-docker/src/serve.rs new file mode 100644 index 0000000000..6d6d979a6f --- /dev/null +++ b/crates/openshell-driver-docker/src/serve.rs @@ -0,0 +1,310 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The launched-driver commands: `serve` and `preflight`. +//! +//! The gateway starts `serve` with bootstrap arguments only and the operator's +//! `[openshell.drivers.docker]` table on stdin, then delivers gateway-owned +//! metadata with the `Configure` RPC. Until `Configure` succeeds the driver +//! creates no Docker volumes, networks or containers, and both of its gRPC +//! services answer `UNAVAILABLE`. + +use std::path::PathBuf; + +use clap::Parser; +use openshell_core::VERSION; +use openshell_core::proto::compute::v1::compute_driver_configuration_updates_server::ComputeDriverConfigurationUpdatesServer; +use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; +use openshell_driver_docker::launch::{check_backend, settings_from_table}; +use openshell_driver_docker::{ComputeDriverService, DockerComputeConfig, DockerComputeDriver}; +use openshell_driver_sdk::launch::{ConfigureRequest, Deferred, Launch, LaunchInfo}; +use openshell_driver_sdk::{GatewayContext, StartResult}; +use tonic::Status; +use tracing::info; + +/// Bootstrap arguments the gateway passes to `serve`. They are frozen for +/// protocol version 1. +#[derive(Parser, Debug)] +#[command(name = "openshell-driver-docker serve")] +struct ServeArgs { + #[arg(long)] + bind_socket: PathBuf, + + #[arg(long)] + expected_peer_pid: u32, + + #[arg(long, default_value = "info")] + log_level: String, +} + +/// Run `serve` or `preflight` when that is the first argument and return the +/// process exit code. Any other invocation returns `None` and takes the +/// standalone path. +pub async fn dispatch() -> Option { + let args: Vec = std::env::args().collect(); + match args.get(1)?.as_str() { + "serve" => { + let parsed = ServeArgs::parse_from( + std::iter::once("openshell-driver-docker serve".to_string()) + .chain(args.into_iter().skip(2)), + ); + Some(serve(parsed).await) + } + "preflight" => Some(preflight()), + _ => None, + } +} + +fn read_settings() -> Result { + let table = openshell_driver_sdk::read_stdin_table() + .map_err(|error| StartResult::invalid_config(format!("read driver table: {error}")))?; + settings_from_table(&table).map_err(StartResult::invalid_config) +} + +fn preflight() -> i32 { + match read_settings() { + Ok(_) => 0, + Err(result) => result.report(), + } +} + +async fn serve(args: ServeArgs) -> i32 { + let tracing = openshell_otel::install_deferred_driver_tracing( + openshell_driver_docker::otel_tracing::TRACING, + &args.log_level, + openshell_core::color::stdout_ansi(), + ); + match run(args, tracing).await { + Ok(()) => 0, + Err(result) => result.report(), + } +} + +async fn run( + args: ServeArgs, + tracing: openshell_otel::DeferredDriverTracing, +) -> Result<(), StartResult> { + let settings = read_settings()?; + check_backend(&settings) + .await + .map_err(StartResult::unavailable)?; + + let listener = openshell_core::external_driver_socket::bind_private(&args.bind_socket) + .map_err(StartResult::error)?; + let _cleanup = + openshell_core::external_driver_socket::SocketCleanup::new(args.bind_socket.clone()); + #[cfg(unix)] + openshell_driver_sdk::watch_parent(args.expected_peer_pid); + + let log_level = args.log_level.clone(); + let launch = Launch::new( + LaunchInfo { + driver_name: "docker".to_string(), + driver_version: VERSION.to_string(), + features: Vec::new(), + }, + move |request| { + let settings = settings.clone(); + let tracing = tracing.clone(); + let log_level = log_level.clone(); + async move { apply_configure(settings, &log_level, &tracing, request).await } + }, + ); + // One configured service backs both gRPC services. + let compute = Deferred::new(launch.configured(), |service: &ComputeDriverService| { + ComputeDriverServer::new(service.clone()) + }); + let configuration_updates = + Deferred::new(launch.configured(), |service: &ComputeDriverService| { + ComputeDriverConfigurationUpdatesServer::new(service.clone()) + }); + + info!(socket = %args.bind_socket.display(), "Starting Docker compute driver"); + tonic::transport::Server::builder() + .layer(openshell_otel::compute_driver_rpc_layer()) + .add_service(launch.into_server()) + .add_service(compute) + .add_service(configuration_updates) + .serve_with_incoming_shutdown( + openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener), + crate::shutdown_signal(), + ) + .await + .map_err(|error| StartResult::error(format!("serve: {error}"))) +} + +/// Build the driver from the operator's settings and the gateway's metadata. +async fn apply_configure( + settings: DockerComputeConfig, + log_level: &str, + tracing: &openshell_otel::DeferredDriverTracing, + request: ConfigureRequest, +) -> Result { + let gateway = GatewayContext::try_from(&request.gateway.clone().unwrap_or_default())?; + if let Some(export) = openshell_driver_sdk::deferred_export_config( + request.telemetry.as_ref(), + gateway.gateway_name.as_deref(), + VERSION, + )? && let Err(error) = tracing.enable_export(export) + { + tracing::error!(%error, "OTLP exporting could not be started"); + } + let supervisor_otlp = openshell_driver_sdk::supervisor_otlp(request.telemetry.as_ref())?; + let network_trust = openshell_driver_sdk::load_network_trust(request.network_trust.as_ref())?; + let admission = openshell_driver_sdk::admission_from_json(&request.admission_json)?; + let (config, bind_address) = driver_config( + settings, + &gateway, + request.image_overrides.as_ref(), + supervisor_otlp, + &admission, + )?; + let driver = DockerComputeDriver::new(bind_address, log_level, &config, network_trust) + .await + .map_err(|error| Status::internal(error.to_string()))?; + Ok(ComputeDriverService::new(driver)) +} + +/// The driver configuration for `settings` and the gateway's metadata, and +/// the gateway's listener. The gateway supplies the CA and the admission +/// policy, which the table cannot set. Image overrides win over the table, as +/// the environment did when the gateway built the configuration itself. +fn driver_config( + mut settings: DockerComputeConfig, + gateway: &GatewayContext, + images: Option<&openshell_driver_sdk::launch::ImageOverrides>, + supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, + admission: &openshell_core::resource_admission::DriverAdmissionConfig, +) -> Result<(DockerComputeConfig, std::net::SocketAddr), Status> { + let bind_address = gateway + .bind_address + .ok_or_else(|| Status::invalid_argument("the gateway did not send its bind address"))?; + settings.guest_tls_ca.clone_from(&gateway.tls_ca_path); + if openshell_driver_sdk::endpoint_uses_tls(&settings.grpc_endpoint) + && settings.guest_tls_ca.is_none() + { + return Err(Status::invalid_argument( + "grpc_endpoint uses https:// but the gateway supplied no CA path", + )); + } + settings.allow_driver_config = admission.allow_driver_config; + settings.resource_admission = admission.resource_admission.clone(); + if let Some(images) = images { + if let Some(image) = &images.sandbox_runtime_image { + settings.sandbox_runtime_image = Some(image.clone()); + } + if let Some(image) = &images.supervisor_image { + settings.supervisor_image = Some(image.clone()); + } + } + settings.supervisor_otlp = supervisor_otlp; + settings + .supervisor_gateway_name + .clone_from(&gateway.gateway_name); + Ok((settings, bind_address)) +} + +#[cfg(test)] +mod tests { + use openshell_core::resource_admission::DriverAdmissionConfig; + use openshell_driver_sdk::launch::ImageOverrides; + + use super::*; + + fn gateway(bind: Option<&str>, ca: Option<&str>) -> GatewayContext { + GatewayContext { + gateway_port: Some(8080), + tls_ca_path: ca.map(PathBuf::from), + gateway_name: Some("gw".to_string()), + bind_address: bind.map(|address| address.parse().unwrap()), + } + } + + fn build( + settings: DockerComputeConfig, + gateway: &GatewayContext, + images: Option<&ImageOverrides>, + admission: &DriverAdmissionConfig, + ) -> Result<(DockerComputeConfig, std::net::SocketAddr), Status> { + driver_config( + settings, + gateway, + images, + openshell_core::sandbox_env::SupervisorOtlp::default(), + admission, + ) + } + + #[test] + fn the_gateway_supplies_the_listener_name_ca_and_admission() { + let admission = DriverAdmissionConfig { + allow_driver_config: true, + ..DriverAdmissionConfig::default() + }; + let (config, bind) = build( + DockerComputeConfig::default(), + &gateway(Some("127.0.0.1:8080"), Some("/ca.pem")), + None, + &admission, + ) + .unwrap(); + assert_eq!(bind, "127.0.0.1:8080".parse().unwrap()); + assert_eq!(config.guest_tls_ca, Some("/ca.pem".into())); + assert_eq!(config.supervisor_gateway_name.as_deref(), Some("gw")); + assert!(config.allow_driver_config); + } + + #[test] + fn the_bind_address_is_required() { + let status = build( + DockerComputeConfig::default(), + &gateway(None, None), + None, + &DriverAdmissionConfig::default(), + ) + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } + + #[test] + fn an_https_endpoint_needs_the_gateway_ca() { + let table = settings_from_table("grpc_endpoint = \"https://host.test:9\"").unwrap(); + let admission = DriverAdmissionConfig::default(); + let status = build( + table.clone(), + &gateway(Some("127.0.0.1:8080"), None), + None, + &admission, + ) + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + build( + table, + &gateway(Some("127.0.0.1:8080"), Some("/ca.pem")), + None, + &admission, + ) + .unwrap(); + } + + #[test] + fn image_overrides_win_over_the_table_as_the_environment_did() { + let table = settings_from_table( + "sandbox_runtime_image = \"table-runtime\"\nsupervisor_image = \"table-supervisor\"", + ) + .unwrap(); + let overrides = ImageOverrides { + sandbox_runtime_image: Some("env-runtime".to_string()), + supervisor_image: None, + }; + let (config, _) = build( + table, + &gateway(Some("127.0.0.1:8080"), None), + Some(&overrides), + &DriverAdmissionConfig::default(), + ) + .unwrap(); + assert_eq!(config.sandbox_runtime_image.as_deref(), Some("env-runtime")); + assert_eq!(config.supervisor_image.as_deref(), Some("table-supervisor")); + } +} diff --git a/crates/openshell-driver-docker/tests/serve_configure.rs b/crates/openshell-driver-docker/tests/serve_configure.rs new file mode 100644 index 0000000000..59eec337e0 --- /dev/null +++ b/crates/openshell-driver-docker/tests/serve_configure.rs @@ -0,0 +1,277 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Runs the real `openshell-driver-docker` binary through `serve` and +//! `preflight` against a fake Docker API socket. + +#![cfg(unix)] + +use std::io::{Read as _, Write as _}; +use std::os::unix::net::UnixListener; +use std::path::Path; +use std::process::{Child, Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +use hyper_util::rt::TokioIo; +use openshell_core::proto::compute::v1::GetCapabilitiesRequest; +use openshell_core::proto::compute::v1::UpdateSandboxConfigurationRequest; +use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; +use openshell_core::proto::compute::v1::compute_driver_configuration_updates_client::ComputeDriverConfigurationUpdatesClient; +use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; +use openshell_driver_sdk::launch::{ConfigureRequest, GetLaunchInfoRequest, PROTOCOL_VERSION}; +use tonic::Code; +use tonic::transport::{Channel, Endpoint}; + +const BIN: &str = env!("CARGO_BIN_EXE_openshell-driver-docker"); + +fn command(args: &[&str], table: &str, dir: &Path) -> Command { + // The table is a file, as the gateway provides it, so it always ends. + let stdin = dir.join("table.toml"); + std::fs::write(&stdin, table).unwrap(); + let mut command = Command::new(BIN); + command + .args(args) + .env_remove("DOCKER_HOST") + .stdin(std::fs::File::open(stdin).unwrap()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + command +} + +fn run(args: &[&str], table: &str) -> Output { + let dir = tempfile::tempdir().unwrap(); + command(args, table, dir.path()).output().unwrap() +} + +/// A Docker API that answers every request with `200 OK`. +fn fake_docker(path: &Path) { + let listener = UnixListener::bind(path).unwrap(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut buffer = [0_u8; 4096]; + let _ = stream.read(&mut buffer); + let _ = stream + .write_all(b"HTTP/1.1 200 OK\r\nApi-Version: 1.45\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK"); + } + }); +} + +struct Serving { + child: Child, + channel: Channel, + _dir: tempfile::TempDir, +} + +impl Drop for Serving { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +async fn connect(path: &Path) -> Option { + let path = path.to_path_buf(); + Endpoint::try_from("http://localhost") + .unwrap() + .connect_with_connector(tower::service_fn(move |_| { + let path = path.clone(); + async move { + Ok::<_, std::io::Error>(TokioIo::new(tokio::net::UnixStream::connect(path).await?)) + } + })) + .await + .ok() +} + +async fn serve() -> Serving { + let dir = tempfile::tempdir().unwrap(); + let docker = dir.path().join("docker.sock"); + fake_docker(&docker); + let socket = dir.path().join("driver.sock"); + let table = format!("socket_path = \"{}\"\n", docker.display()); + let mut child = command( + &[ + "serve", + "--bind-socket", + socket.to_str().unwrap(), + "--expected-peer-pid", + &std::process::id().to_string(), + ], + &table, + dir.path(), + ) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_mins(1); + loop { + if let Some(status) = child.try_wait().unwrap() { + panic!("driver exited early: {status}"); + } + if let Some(channel) = connect(&socket).await { + return Serving { + child, + channel, + _dir: dir, + }; + } + assert!( + Instant::now() < deadline, + "driver never accepted a connection" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +fn configure(version: u32) -> ConfigureRequest { + ConfigureRequest { + protocol_version: version, + gateway: Some(openshell_driver_sdk::launch::GatewayContext { + gateway_port: 8080, + bind_address: "127.0.0.1:8080".to_string(), + ..Default::default() + }), + ..Default::default() + } +} + +#[tokio::test] +async fn launch_info_answers_and_compute_calls_wait_for_configure() { + let serving = serve().await; + + let info = DriverLaunchClient::new(serving.channel.clone()) + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap() + .into_inner(); + assert_eq!(info.driver_name, "docker"); + assert_eq!(info.protocol_versions, [PROTOCOL_VERSION]); + + let status = ComputeDriverClient::new(serving.channel.clone()) + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); + + // The configuration-updates service is gated the same way. + let status = ComputeDriverConfigurationUpdatesClient::new(serving.channel.clone()) + .update_sandbox_configuration(UpdateSandboxConfigurationRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[tokio::test] +async fn a_failed_configure_leaves_the_driver_running_for_a_retry() { + let mut serving = serve().await; + let mut client = DriverLaunchClient::new(serving.channel.clone()); + + let unsupported = client + .configure(configure(PROTOCOL_VERSION + 1)) + .await + .unwrap_err(); + assert_eq!(unsupported.code(), Code::FailedPrecondition); + + // The fake Docker cannot describe itself, so construction fails here. + let failed = client + .configure(configure(PROTOCOL_VERSION)) + .await + .unwrap_err(); + assert_ne!(failed.code(), Code::Ok); + assert!(serving.child.try_wait().unwrap().is_none()); + + let retried = client + .configure(configure(PROTOCOL_VERSION)) + .await + .unwrap_err(); + assert_ne!(retried.code(), Code::FailedPrecondition, "{retried}"); + let still_unavailable = ComputeDriverClient::new(serving.channel.clone()) + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(still_unavailable.code(), Code::Unavailable); +} + +fn report_of(output: &Output) -> openshell_driver_sdk::StartReport { + let stdout = String::from_utf8_lossy(&output.stdout); + openshell_driver_sdk::StartReport::from_output(&stdout) + .unwrap_or_else(|| panic!("no report line in: {stdout}")) +} + +const SERVE_ARGS: [&str; 5] = [ + "serve", + "--bind-socket", + "/nonexistent/driver.sock", + "--expected-peer-pid", + "1", +]; + +#[test] +fn an_invalid_table_exits_with_the_config_code_and_one_json_line() { + let output = run(&SERVE_ARGS, "no_such_key = 1"); + assert_eq!(output.status.code(), Some(78)); + let report = report_of(&output); + assert_eq!(report.kind, openshell_driver_sdk::StartKind::InvalidConfig); + assert!(report.reason.contains("no_such_key"), "{}", report.reason); +} + +#[test] +fn an_unreachable_socket_exits_as_unavailable() { + let output = run(&SERVE_ARGS, "socket_path = \"/nonexistent/docker.sock\""); + assert_eq!(output.status.code(), Some(69)); + assert_eq!( + report_of(&output).kind, + openshell_driver_sdk::StartKind::Unavailable + ); +} + +#[test] +fn preflight_accepts_a_valid_table_without_contacting_docker() { + let table = "socket_path = \"/nonexistent/docker.sock\"\nsandbox_label = \"example\"\n"; + let output = run(&["preflight"], table); + assert_eq!(output.status.code(), Some(0), "{:?}", output.stdout); + assert_eq!(run(&["preflight"], "").status.code(), Some(0)); +} + +#[test] +fn preflight_rejects_an_unknown_key() { + let output = run(&["preflight"], "no_such_key = 1"); + assert_eq!(output.status.code(), Some(78)); + assert_eq!( + report_of(&output).kind, + openshell_driver_sdk::StartKind::InvalidConfig + ); +} + +#[test] +fn docker_host_finds_the_socket_when_the_table_sets_none() { + let dir = tempfile::tempdir().unwrap(); + let docker = dir.path().join("docker.sock"); + fake_docker(&docker); + let socket = dir.path().join("driver.sock"); + let mut child = command( + &[ + "serve", + "--bind-socket", + socket.to_str().unwrap(), + "--expected-peer-pid", + &std::process::id().to_string(), + ], + "", + dir.path(), + ) + .env("DOCKER_HOST", format!("unix://{}", docker.display())) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + while !socket.exists() { + assert!( + child.try_wait().unwrap().is_none(), + "the driver should have found the socket from DOCKER_HOST" + ); + assert!(Instant::now() < deadline, "driver never bound its socket"); + std::thread::sleep(Duration::from_millis(50)); + } + let _ = child.kill(); + let _ = child.wait(); +} diff --git a/crates/openshell-driver-launch/Cargo.toml b/crates/openshell-driver-launch/Cargo.toml new file mode 100644 index 0000000000..b92b11e304 --- /dev/null +++ b/crates/openshell-driver-launch/Cargo.toml @@ -0,0 +1,29 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-driver-launch" +description = "Launch and Configure protocol shared by the gateway and launched compute drivers" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +http = { workspace = true } +prost = { workspace = true } +tokio = { workspace = true } +tonic = { workspace = true } +tonic-prost = { workspace = true } +tower = { workspace = true } + +[build-dependencies] +protoc-bin-vendored = { workspace = true } +tonic-prost-build = { workspace = true } + +[dev-dependencies] +tokio-stream = { workspace = true, features = ["net"] } + +[lints] +workspace = true diff --git a/crates/openshell-driver-launch/build.rs b/crates/openshell-driver-launch/build.rs new file mode 100644 index 0000000000..ab7f2d00b5 --- /dev/null +++ b/crates/openshell-driver-launch/build.rs @@ -0,0 +1,25 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::path::PathBuf; + +fn main() -> Result<(), Box> { + println!("cargo:rerun-if-env-changed=PROTOC"); + let proto_root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR")?).join("../../proto"); + println!( + "cargo:rerun-if-changed={}", + proto_root.join("driver_launch.proto").display() + ); + + let mut config = tonic_prost_build::Config::new(); + // A caller-supplied PROTOC is used as-is; otherwise use the vendored one. + if std::env::var_os("PROTOC").is_none() { + config.protoc_executable(protoc_bin_vendored::protoc_bin_path()?); + } + tonic_prost_build::configure().compile_with_config( + config, + &[proto_root.join("driver_launch.proto")], + &[proto_root], + )?; + Ok(()) +} diff --git a/crates/openshell-driver-launch/src/lib.rs b/crates/openshell-driver-launch/src/lib.rs new file mode 100644 index 0000000000..efdd67ff04 --- /dev/null +++ b/crates/openshell-driver-launch/src/lib.rs @@ -0,0 +1,249 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Launch and `Configure` protocol for gateway-launched compute drivers. +//! +//! A launched driver serves [`Launch`] next to its own services. The driver's +//! services are wrapped in [`Deferred`], which answers `UNAVAILABLE` until +//! `Configure` has succeeded once. + +use std::convert::Infallible; +use std::future::Future; +use std::pin::Pin; +use std::sync::{Arc, OnceLock}; +use std::task::{Context, Poll}; + +use tonic::{Request, Response, Status}; + +#[allow( + clippy::all, + clippy::pedantic, + clippy::nursery, + missing_docs, + unused_qualifications +)] +pub mod proto { + tonic::include_proto!("openshell.driver.launch.v1"); +} + +pub use proto::driver_launch_server::{DriverLaunch, DriverLaunchServer}; +pub use proto::{ + CollectorTls, ConfigureRequest, ConfigureResponse, GatewayContext, GetLaunchInfoRequest, + GetLaunchInfoResponse, ImageOverrides, NetworkTrust, OtlpExport, Telemetry, +}; + +/// The launch protocol version this crate implements. +pub const PROTOCOL_VERSION: u32 = 1; + +/// Largest `ConfigureRequest` a driver accepts. +pub const MAX_CONFIGURE_REQUEST_BYTES: usize = 1024 * 1024; + +/// Encode `request` for the wire. +#[must_use] +pub fn encode_configure_request(request: &ConfigureRequest) -> Vec { + prost::Message::encode_to_vec(request) +} + +/// Decode a `ConfigureRequest`, rejecting bytes over the size limit. +pub fn decode_configure_request(bytes: &[u8]) -> Result { + if bytes.len() > MAX_CONFIGURE_REQUEST_BYTES { + return Err(Status::out_of_range("ConfigureRequest is too large")); + } + prost::Message::decode(bytes) + .map_err(|error| Status::invalid_argument(format!("invalid ConfigureRequest: {error}"))) +} + +/// State a driver builds from a successful `Configure`. +/// +/// Cloning shares the same cell. +pub struct Configured(Arc>); + +impl Clone for Configured { + fn clone(&self) -> Self { + Self(Arc::clone(&self.0)) + } +} + +impl Default for Configured { + fn default() -> Self { + Self(Arc::new(OnceLock::new())) + } +} + +impl Configured { + /// The state, once `Configure` has succeeded. + #[must_use] + pub fn get(&self) -> Option<&S> { + self.0.get() + } +} + +/// What a driver reports from `GetLaunchInfo`. +#[derive(Debug, Clone)] +pub struct LaunchInfo { + pub driver_name: String, + pub driver_version: String, + pub features: Vec, +} + +type ConfigureFuture = Pin> + Send>>; +type ConfigureFn = Box ConfigureFuture + Send + Sync>; + +/// Server for [`DriverLaunch`]. +/// +/// `configure` runs after the request passes the protocol checks. It either +/// returns the driver's configured state or a status. `INVALID_ARGUMENT` and +/// `FAILED_PRECONDITION` leave the driver running for a retry. Calls are +/// serialized, and once one has succeeded later calls fail with +/// `FAILED_PRECONDITION`. +pub struct Launch { + info: LaunchInfo, + configured: Configured, + configure: ConfigureFn, + gate: tokio::sync::Mutex<()>, +} + +impl Launch { + pub fn new(info: LaunchInfo, configure: F) -> Self + where + F: Fn(ConfigureRequest) -> Fut + Send + Sync + 'static, + Fut: Future> + Send + 'static, + { + Self { + info, + configured: Configured::default(), + configure: Box::new(move |request| Box::pin(configure(request))), + gate: tokio::sync::Mutex::new(()), + } + } + + /// A handle to the state `Configure` produces, for [`Deferred`]. + #[must_use] + pub fn configured(&self) -> Configured { + self.configured.clone() + } + + /// The gRPC service, limited to [`MAX_CONFIGURE_REQUEST_BYTES`]. + #[must_use] + pub fn into_server(self) -> DriverLaunchServer { + DriverLaunchServer::new(self).max_decoding_message_size(MAX_CONFIGURE_REQUEST_BYTES) + } +} + +#[tonic::async_trait] +impl DriverLaunch for Launch { + async fn get_launch_info( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(GetLaunchInfoResponse { + driver_name: self.info.driver_name.clone(), + driver_version: self.info.driver_version.clone(), + protocol_versions: vec![PROTOCOL_VERSION], + features: self.info.features.clone(), + })) + } + + async fn configure( + &self, + request: Request, + ) -> Result, Status> { + let request = request.into_inner(); + let _serialized = self.gate.lock().await; + if self.configured.get().is_some() { + return Err(Status::failed_precondition("driver is already configured")); + } + if request.protocol_version != PROTOCOL_VERSION { + return Err(Status::failed_precondition(format!( + "unsupported protocol version {}; this driver supports {PROTOCOL_VERSION}", + request.protocol_version + ))); + } + if let Some(feature) = request + .required_features + .iter() + .find(|feature| !self.info.features.contains(feature)) + { + return Err(Status::failed_precondition(format!( + "unsupported required feature {feature:?}" + ))); + } + let state = (self.configure)(request).await?; + // The gate makes this the only writer. + let _ = self.configured.0.set(state); + Ok(Response::new(ConfigureResponse {})) + } +} + +type BoxFuture = Pin + Send>>; + +/// Wraps a driver service so it answers `UNAVAILABLE` until `Configure` +/// succeeds, then delegates to the service built from the configured state. +pub struct Deferred { + configured: Configured, + build: Arc Svc + Send + Sync>, + service: Arc>, +} + +impl Deferred { + pub fn new( + configured: Configured, + build: impl Fn(&S) -> Svc + Send + Sync + 'static, + ) -> Self { + Self { + configured, + build: Arc::new(build), + service: Arc::new(OnceLock::new()), + } + } +} + +impl Clone for Deferred { + fn clone(&self) -> Self { + Self { + configured: self.configured.clone(), + build: Arc::clone(&self.build), + service: Arc::clone(&self.service), + } + } +} + +impl tonic::server::NamedService for Deferred { + const NAME: &'static str = Svc::NAME; +} + +impl tower::Service> for Deferred +where + Svc: tower::Service< + http::Request, + Response = http::Response, + Error = Infallible, + > + Clone + + Send + + Sync + + 'static, + Svc::Future: Send + 'static, + S: Send + Sync + 'static, +{ + type Response = http::Response; + type Error = Infallible; + type Future = BoxFuture>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, request: http::Request) -> Self::Future { + let Some(state) = self.configured.get() else { + return Box::pin(std::future::ready(Ok(Status::unavailable( + "driver is not configured yet", + ) + .into_http()))); + }; + let mut service = self.service.get_or_init(|| (self.build)(state)).clone(); + Box::pin(async move { tower::Service::call(&mut service, request).await }) + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-driver-launch/src/tests.rs b/crates/openshell-driver-launch/src/tests.rs new file mode 100644 index 0000000000..face99a072 --- /dev/null +++ b/crates/openshell-driver-launch/src/tests.rs @@ -0,0 +1,200 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; + +use tonic::Code; + +use super::proto::driver_launch_client::DriverLaunchClient; +use super::*; + +fn info() -> LaunchInfo { + LaunchInfo { + driver_name: "test".to_string(), + driver_version: "1.2.3".to_string(), + features: vec!["known".to_string()], + } +} + +fn request(version: u32, features: &[&str]) -> ConfigureRequest { + ConfigureRequest { + protocol_version: version, + required_features: features.iter().map(ToString::to_string).collect(), + ..ConfigureRequest::default() + } +} + +async fn serve(service: S) -> String +where + S: tower::Service< + http::Request, + Response = http::Response, + Error = Infallible, + > + tonic::server::NamedService + + Clone + + Send + + Sync + + 'static, + S::Future: Send + 'static, +{ + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let endpoint = format!("http://{}", listener.local_addr().unwrap()); + tokio::spawn( + tonic::transport::Server::builder() + .add_service(service) + .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener)), + ); + endpoint +} + +#[tokio::test] +async fn launch_info_answers_and_configure_succeeds_once() { + let calls = Arc::new(AtomicU32::new(0)); + let counted = Arc::clone(&calls); + let launch = Launch::new(info(), move |_| { + let counted = Arc::clone(&counted); + async move { Ok(counted.fetch_add(1, Ordering::SeqCst) + 1) } + }); + let configured = launch.configured(); + let mut client = DriverLaunchClient::connect(serve(launch.into_server()).await) + .await + .unwrap(); + + let launch_info = client + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap() + .into_inner(); + assert_eq!(launch_info.driver_name, "test"); + assert_eq!(launch_info.protocol_versions, [PROTOCOL_VERSION]); + assert!(configured.get().is_none()); + + client + .configure(request(PROTOCOL_VERSION, &["known"])) + .await + .unwrap(); + assert_eq!(configured.get(), Some(&1)); + let again = client + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap_err(); + assert_eq!(again.code(), Code::FailedPrecondition); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +#[tokio::test] +async fn unsupported_requests_are_rejected_and_can_be_retried() { + let launch = Launch::new(info(), |_| async { Ok(()) }); + let configured = launch.configured(); + let mut client = DriverLaunchClient::connect(serve(launch.into_server()).await) + .await + .unwrap(); + + for bad in [ + request(PROTOCOL_VERSION + 1, &[]), + request(PROTOCOL_VERSION, &["unknown"]), + ] { + let status = client.configure(bad).await.unwrap_err(); + assert_eq!(status.code(), Code::FailedPrecondition); + assert!(configured.get().is_none()); + } + client + .configure(request(PROTOCOL_VERSION, &["known"])) + .await + .unwrap(); + assert!(configured.get().is_some()); +} + +#[tokio::test] +async fn a_failed_configure_can_be_retried() { + let attempts = Arc::new(AtomicU32::new(0)); + let counted = Arc::clone(&attempts); + let launch = Launch::new(info(), move |_| { + let attempt = counted.fetch_add(1, Ordering::SeqCst); + async move { + if attempt == 0 { + Err(Status::invalid_argument("bad input")) + } else { + Ok(()) + } + } + }); + let mut client = DriverLaunchClient::connect(serve(launch.into_server()).await) + .await + .unwrap(); + + let status = client + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::InvalidArgument); + client + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap(); +} + +#[tokio::test] +async fn oversized_configure_requests_are_rejected() { + let launch = Launch::new(info(), |_| async { Ok(()) }); + let mut client = DriverLaunchClient::connect(serve(launch.into_server()).await) + .await + .unwrap(); + let mut oversized = request(PROTOCOL_VERSION, &[]); + oversized.telemetry = Some(Telemetry { + trace_headers: "x".repeat(MAX_CONFIGURE_REQUEST_BYTES), + ..Telemetry::default() + }); + + let status = client.configure(oversized).await.unwrap_err(); + assert_ne!(status.code(), Code::Ok); + assert!(decode_configure_request(&vec![0; MAX_CONFIGURE_REQUEST_BYTES + 1]).is_err()); +} + +#[tokio::test] +async fn deferred_services_wait_for_configure() { + let launch = Launch::new(info(), |_| async { Ok("configured".to_string()) }); + let configured = launch.configured(); + let mut launch_client = DriverLaunchClient::connect(serve(launch.into_server()).await) + .await + .unwrap(); + // The deferred service is a second `DriverLaunch` server, so its answers + // show which state built it. + let deferred = Deferred::new(configured, |state: &String| { + DriverLaunchServer::new(Launch::new( + LaunchInfo { + driver_name: state.clone(), + ..info() + }, + |_| async { Ok(()) }, + )) + }); + let mut deferred_client = DriverLaunchClient::connect(serve(deferred).await) + .await + .unwrap(); + + let before = deferred_client + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap_err(); + assert_eq!(before.code(), Code::Unavailable); + + launch_client + .configure(request(PROTOCOL_VERSION, &[])) + .await + .unwrap(); + let after = deferred_client + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap() + .into_inner(); + assert_eq!(after.driver_name, "configured"); +} + +#[test] +fn configure_requests_round_trip() { + let original = request(PROTOCOL_VERSION, &["known"]); + let decoded = decode_configure_request(&encode_configure_request(&original)).unwrap(); + assert_eq!(decoded, original); +} diff --git a/crates/openshell-driver-podman/Cargo.toml b/crates/openshell-driver-podman/Cargo.toml index 3fb3c51b5d..db5d0765c2 100644 --- a/crates/openshell-driver-podman/Cargo.toml +++ b/crates/openshell-driver-podman/Cargo.toml @@ -16,6 +16,7 @@ path = "src/main.rs" [dependencies] openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction", "otel", "clap"] } +openshell-driver-sdk = { path = "../openshell-driver-sdk" } openshell-otel = { path = "../openshell-otel" } openshell-isolation-interface = { path = "../openshell-isolation-interface" } openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } @@ -47,8 +48,11 @@ thiserror = { workspace = true } miette = { workspace = true } sha2 = { workspace = true } url = { workspace = true } +toml = { workspace = true } [dev-dependencies] +hyper-util = { workspace = true } +tower = { workspace = true } openshell-crypto = { workspace = true } openshell-otel-test-support = { path = "../openshell-otel-test-support" } opentelemetry_sdk = { workspace = true, features = ["testing"] } diff --git a/crates/openshell-driver-podman/README.md b/crates/openshell-driver-podman/README.md index 87a617069e..75088f8f21 100644 --- a/crates/openshell-driver-podman/README.md +++ b/crates/openshell-driver-podman/README.md @@ -1,6 +1,6 @@ # openshell-driver-podman -The Podman compute driver runs inside the gateway and uses the native libpod +The Podman compute driver runs as a subprocess of the gateway and uses the native libpod REST API over a Unix socket. Each sandbox has two independent containers: - `openshell-sandbox` owns the agent process in the workload container. @@ -164,3 +164,16 @@ When `[openshell.gateway.otlp.agent]` is enabled, the driver sets `OPENSHELL_OTLP_AGENT_PROTOCOL` for a non-gRPC collector, which starts the agent trace relay. On Podman Machine it rewrites a loopback agent endpoint to the desktop host, as it does for the supervisor's trace endpoint. + +## Launched mode + +```text +openshell-driver-podman serve --bind-socket --expected-peer-pid --log-level < table.toml +openshell-driver-podman preflight < table.toml +``` + +The gateway passes the `[openshell.drivers.podman]` table on stdin and gateway metadata in a `Configure` call (`proto/driver_launch.proto`). `settings_from_table` in `src/config.rs` is the only place the table is parsed and validated. + +`serve` resolves the Podman socket from `OPENSHELL_PODMAN_SOCKET`, `socket_path`, or discovery, and pings it before it binds. It exits 69 when Podman is not reachable and 78 when the table is invalid. Until `Configure` succeeds, `ComputeDriver` calls return `UNAVAILABLE` and the driver creates no networks, volumes, or secrets. `preflight` validates the table without contacting Podman. + +The gateway port and name, trusted runtime images, and OTLP settings come from `Configure`. Trusted runtime images from the gateway's environment take precedence over the table, as they did when the driver ran in process. The gateway supplies `gateway_port` and the CA, so the table rejects `gateway_port`, `guest_tls_ca` and the admission keys (`allow_driver_config`, `resource_admission`), which the gateway delivers in `Configure`. `grpc_endpoint` remains an optional override, and an `https://` endpoint needs the gateway CA. diff --git a/crates/openshell-driver-podman/src/config.rs b/crates/openshell-driver-podman/src/config.rs index 7653e3443f..185958652f 100644 --- a/crates/openshell-driver-podman/src/config.rs +++ b/crates/openshell-driver-podman/src/config.rs @@ -265,6 +265,43 @@ pub fn parse_id_map_entry( Ok((container_id, host_id, size)) } +/// Parse and validate the operator's `[openshell.drivers.podman]` table. +/// +/// This is the only place the table is parsed. It has no side effects: it +/// needs neither the gateway context nor Podman. An empty table selects the +/// defaults. +pub fn settings_from_table(table: &str) -> Result { + // The gateway supplies these through `Configure`. The standalone driver + // still takes them as flags, so the struct keeps the fields. + let keys: toml::Table = + toml::from_str(table).map_err(|error| format!("invalid podman driver table: {error}"))?; + if let Some(key) = GATEWAY_SUPPLIED_KEYS + .iter() + .find(|key| keys.contains_key(**key)) + { + return Err(format!( + "invalid podman driver table: `{key}` is supplied by the gateway and cannot be set here" + )); + } + let mut config: PodmanComputeConfig = + toml::from_str(table).map_err(|error| format!("invalid podman driver table: {error}"))?; + if !config.grpc_endpoint.trim().is_empty() { + openshell_driver_sdk::validate_grpc_endpoint(&config.grpc_endpoint)?; + } + config + .validate_configuration() + .map_err(|error| error.to_string())?; + Ok(config) +} + +/// Settings the gateway supplies through `Configure` instead of the table. +const GATEWAY_SUPPLIED_KEYS: &[&str] = &[ + "gateway_port", + "guest_tls_ca", + "allow_driver_config", + "resource_admission", +]; + impl PodmanComputeConfig { /// Validate and normalize startup configuration without connecting to Podman. pub fn validate_configuration(&mut self) -> Result<(), crate::client::PodmanApiError> { @@ -639,6 +676,35 @@ impl std::fmt::Debug for PodmanComputeConfig { } } +#[cfg(test)] +mod table_tests { + use super::*; + + #[test] + fn gateway_supplied_keys_are_rejected() { + for key in [ + "gateway_port = 8080", + "guest_tls_ca = \"/ca.pem\"", + "allow_driver_config = true", + "resource_admission = {}", + ] { + let error = settings_from_table(key).unwrap_err(); + assert!(error.contains("supplied by the gateway"), "{error}"); + } + } + + #[test] + fn grpc_endpoint_is_checked_for_syntax_and_scheme() { + settings_from_table("grpc_endpoint = \"https://gw.test:8443\"").unwrap(); + for bad in ["ftp://gw.test:1", "gw.test:8080"] { + assert!( + settings_from_table(&format!("grpc_endpoint = \"{bad}\"")).is_err(), + "accepted: {bad}" + ); + } + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/openshell-driver-podman/src/driver.rs b/crates/openshell-driver-podman/src/driver.rs index 284ef2c913..5c2c259c2b 100644 --- a/crates/openshell-driver-podman/src/driver.rs +++ b/crates/openshell-driver-podman/src/driver.rs @@ -445,6 +445,13 @@ pub fn is_available() -> bool { detect_socket().is_some() } +/// Check that Podman is reachable with `config`: resolve the socket, honouring +/// `socket_path` and `OPENSHELL_PODMAN_SOCKET`, and ping it. Creates nothing. +pub async fn check_backend(config: &PodmanComputeConfig) -> Result<(), PodmanApiError> { + let socket_path = resolve_socket_path(config.socket_path.clone(), detect_socket)?; + PodmanClient::new(socket_path).ping().await +} + /// Resolve the socket to connect to: explicit configuration wins, otherwise /// fall back to `detect`. Returns an error if neither resolves. /// diff --git a/crates/openshell-driver-podman/src/main.rs b/crates/openshell-driver-podman/src/main.rs index 625eabd1fe..84079c856f 100644 --- a/crates/openshell-driver-podman/src/main.rs +++ b/crates/openshell-driver-podman/src/main.rs @@ -9,6 +9,8 @@ use std::num::{NonZeroI64, NonZeroU64}; use std::path::PathBuf; use tracing::info; +mod serve; + use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; use openshell_core::sandbox_env::SupervisorOtlpArgs; use openshell_core::{AppArmorProfile, ImagePullPolicy, VERSION}; @@ -213,6 +215,9 @@ struct Args { #[tokio::main] async fn main() -> Result<()> { + if let Some(code) = serve::dispatch().await { + std::process::exit(code); + } let args = Args::parse(); let _tracing = openshell_otel::install_driver_tracing( openshell_driver_podman::otel_tracing::TRACING, diff --git a/crates/openshell-driver-podman/src/serve.rs b/crates/openshell-driver-podman/src/serve.rs new file mode 100644 index 0000000000..1f46886d24 --- /dev/null +++ b/crates/openshell-driver-podman/src/serve.rs @@ -0,0 +1,266 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The launched-driver commands: `serve` and `preflight`. +//! +//! The gateway starts `serve` with bootstrap arguments only and the operator's +//! `[openshell.drivers.podman]` table on stdin, then delivers gateway-owned +//! metadata with the `Configure` RPC. Until `Configure` succeeds the driver +//! creates no Podman networks, volumes or secrets. + +use std::path::PathBuf; + +use clap::Parser; +use openshell_core::VERSION; +use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; +use openshell_driver_podman::config::settings_from_table; +use openshell_driver_podman::driver::check_backend; +use openshell_driver_podman::{ComputeDriverService, PodmanComputeConfig, PodmanComputeDriver}; +use openshell_driver_sdk::launch::{ConfigureRequest, Deferred, Launch, LaunchInfo}; +use openshell_driver_sdk::{GatewayContext, StartResult}; +use tonic::Status; +use tracing::info; + +/// Bootstrap arguments the gateway passes to `serve`. They are frozen for +/// protocol version 1. +#[derive(Parser, Debug)] +#[command(name = "openshell-driver-podman serve")] +struct ServeArgs { + #[arg(long)] + bind_socket: PathBuf, + + #[arg(long)] + expected_peer_pid: u32, + + #[arg(long, default_value = "info")] + log_level: String, +} + +/// Run `serve` or `preflight` when that is the first argument and return the +/// process exit code. Any other invocation returns `None` and takes the +/// standalone path. +pub async fn dispatch() -> Option { + let args: Vec = std::env::args().collect(); + match args.get(1)?.as_str() { + "serve" => { + let parsed = ServeArgs::parse_from( + std::iter::once("openshell-driver-podman serve".to_string()) + .chain(args.into_iter().skip(2)), + ); + Some(serve(parsed).await) + } + "preflight" => Some(preflight()), + _ => None, + } +} + +fn read_settings() -> Result { + let table = openshell_driver_sdk::read_stdin_table() + .map_err(|error| StartResult::invalid_config(format!("read driver table: {error}")))?; + let mut config = settings_from_table(&table).map_err(StartResult::invalid_config)?; + // The environment variable wins over the table, as it always has. + if let Ok(path) = std::env::var("OPENSHELL_PODMAN_SOCKET") { + config.socket_path = Some(path.into()); + } + Ok(config) +} + +fn preflight() -> i32 { + match read_settings() { + Ok(_) => 0, + Err(result) => result.report(), + } +} + +async fn serve(args: ServeArgs) -> i32 { + let tracing = openshell_otel::install_deferred_driver_tracing( + openshell_driver_podman::otel_tracing::TRACING, + &args.log_level, + openshell_core::color::stdout_ansi(), + ); + match run(args, tracing).await { + Ok(()) => 0, + Err(result) => result.report(), + } +} + +async fn run( + args: ServeArgs, + tracing: openshell_otel::DeferredDriverTracing, +) -> Result<(), StartResult> { + let settings = read_settings()?; + check_backend(&settings) + .await + .map_err(|error| StartResult::unavailable(error.to_string()))?; + + let listener = openshell_core::external_driver_socket::bind_private(&args.bind_socket) + .map_err(StartResult::error)?; + let _cleanup = + openshell_core::external_driver_socket::SocketCleanup::new(args.bind_socket.clone()); + #[cfg(unix)] + openshell_driver_sdk::watch_parent(args.expected_peer_pid); + + let launch = Launch::new( + LaunchInfo { + driver_name: "podman".to_string(), + driver_version: VERSION.to_string(), + features: Vec::new(), + }, + move |request| { + let settings = settings.clone(); + let tracing = tracing.clone(); + async move { apply_configure(settings, &tracing, request).await } + }, + ); + let deferred = Deferred::new(launch.configured(), |service: &ComputeDriverService| { + ComputeDriverServer::new(service.clone()) + }); + + info!(socket = %args.bind_socket.display(), "Starting Podman compute driver"); + tonic::transport::Server::builder() + .layer(openshell_otel::compute_driver_rpc_layer()) + .add_service(launch.into_server()) + .add_service(deferred) + .serve_with_incoming_shutdown( + openshell_core::external_driver_socket::SameUidUnixIncoming::new(listener), + crate::shutdown_signal(), + ) + .await + .map_err(|error| StartResult::error(format!("serve: {error}"))) +} + +/// Build the driver from the operator's settings and the gateway's metadata. +async fn apply_configure( + settings: PodmanComputeConfig, + tracing: &openshell_otel::DeferredDriverTracing, + request: ConfigureRequest, +) -> Result { + let gateway = GatewayContext::try_from(&request.gateway.clone().unwrap_or_default())?; + if let Some(export) = openshell_driver_sdk::deferred_export_config( + request.telemetry.as_ref(), + gateway.gateway_name.as_deref(), + VERSION, + )? && let Err(error) = tracing.enable_export(export) + { + tracing::error!(%error, "OTLP exporting could not be started"); + } + let supervisor_otlp = openshell_driver_sdk::supervisor_otlp(request.telemetry.as_ref())?; + let network_trust = openshell_driver_sdk::load_network_trust(request.network_trust.as_ref())?; + let admission = openshell_driver_sdk::admission_from_json(&request.admission_json)?; + let mut config = driver_config( + settings, + &gateway, + request.image_overrides.as_ref(), + supervisor_otlp, + )?; + config.allow_driver_config = admission.allow_driver_config; + config.resource_admission = admission.resource_admission; + let driver = PodmanComputeDriver::new(config, network_trust) + .await + .map_err(|error| Status::internal(error.to_string()))?; + Ok(ComputeDriverService::new(driver)) +} + +/// The driver configuration for `settings` and the gateway's metadata. The +/// gateway supplies the port and the CA, which the table cannot set. The +/// image overrides win, as the environment did when the gateway built the +/// configuration itself. +fn driver_config( + mut settings: PodmanComputeConfig, + gateway: &GatewayContext, + images: Option<&openshell_driver_sdk::launch::ImageOverrides>, + supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, +) -> Result { + if let Some(port) = gateway.gateway_port { + settings.gateway_port = port; + } + settings.guest_tls_ca.clone_from(&gateway.tls_ca_path); + if openshell_driver_sdk::endpoint_uses_tls(&settings.grpc_endpoint) + && settings.guest_tls_ca.is_none() + { + return Err(Status::invalid_argument( + "grpc_endpoint uses https:// but the gateway supplied no CA path", + )); + } + if let Some(images) = images { + if let Some(image) = &images.sandbox_runtime_image { + settings.sandbox_runtime_image.clone_from(image); + } + if let Some(image) = &images.supervisor_image { + settings.supervisor_image.clone_from(image); + } + } + settings.supervisor_otlp = supervisor_otlp; + settings + .supervisor_gateway_name + .clone_from(&gateway.gateway_name); + Ok(settings) +} + +#[cfg(test)] +mod tests { + use openshell_driver_sdk::launch::ImageOverrides; + + use super::*; + + fn gateway(port: Option, ca: Option<&str>) -> GatewayContext { + GatewayContext { + gateway_port: port, + tls_ca_path: ca.map(PathBuf::from), + gateway_name: Some("gw".to_string()), + bind_address: None, + } + } + + fn build( + settings: PodmanComputeConfig, + gateway: &GatewayContext, + images: Option<&ImageOverrides>, + ) -> Result { + driver_config( + settings, + gateway, + images, + openshell_core::sandbox_env::SupervisorOtlp::default(), + ) + } + + #[test] + fn the_gateway_supplies_the_port_name_and_ca() { + let built = build( + PodmanComputeConfig::default(), + &gateway(Some(9000), Some("/gateway-ca.pem")), + None, + ) + .unwrap(); + assert_eq!(built.gateway_port, 9000); + assert_eq!(built.supervisor_gateway_name.as_deref(), Some("gw")); + assert_eq!(built.guest_tls_ca, Some("/gateway-ca.pem".into())); + + let plain = build(PodmanComputeConfig::default(), &gateway(None, None), None).unwrap(); + assert!(plain.guest_tls_ca.is_none()); + } + + #[test] + fn an_https_endpoint_needs_the_gateway_ca() { + let table = settings_from_table("grpc_endpoint = \"https://host.test:9\"").unwrap(); + let status = build(table.clone(), &gateway(Some(1), None), None).unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + build(table, &gateway(Some(1), Some("/ca.pem")), None).unwrap(); + } + + #[test] + fn image_overrides_win_over_the_table_as_the_environment_did() { + let table = settings_from_table( + "sandbox_runtime_image = \"table-runtime\"\nsupervisor_image = \"table-supervisor\"", + ) + .unwrap(); + let overrides = ImageOverrides { + sandbox_runtime_image: Some("env-runtime".to_string()), + supervisor_image: None, + }; + let built = build(table, &gateway(None, None), Some(&overrides)).unwrap(); + assert_eq!(built.sandbox_runtime_image, "env-runtime"); + assert_eq!(built.supervisor_image, "table-supervisor"); + } +} diff --git a/crates/openshell-driver-podman/tests/serve_configure.rs b/crates/openshell-driver-podman/tests/serve_configure.rs new file mode 100644 index 0000000000..74ee26ad36 --- /dev/null +++ b/crates/openshell-driver-podman/tests/serve_configure.rs @@ -0,0 +1,263 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Runs the real `openshell-driver-podman` binary through `serve` and +//! `preflight` against a fake Podman API socket. + +#![cfg(unix)] + +use std::io::{Read as _, Write as _}; +use std::os::unix::net::UnixListener; +use std::path::Path; +use std::process::{Child, Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +use hyper_util::rt::TokioIo; +use openshell_core::proto::compute::v1::GetCapabilitiesRequest; +use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; +use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; +use openshell_driver_sdk::launch::{ConfigureRequest, GetLaunchInfoRequest, PROTOCOL_VERSION}; +use tonic::Code; +use tonic::transport::{Channel, Endpoint}; + +const BIN: &str = env!("CARGO_BIN_EXE_openshell-driver-podman"); + +fn command(args: &[&str], table: &str, dir: &Path) -> Command { + // The table is a file, as the gateway provides it, so it always ends. + let stdin = dir.join("table.toml"); + std::fs::write(&stdin, table).unwrap(); + let mut command = Command::new(BIN); + command + .args(args) + .env_remove("OPENSHELL_PODMAN_SOCKET") + .stdin(std::fs::File::open(stdin).unwrap()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + command +} + +fn run(args: &[&str], table: &str) -> Output { + let dir = tempfile::tempdir().unwrap(); + command(args, table, dir.path()).output().unwrap() +} + +/// A Podman API that answers every request with `200 OK`. +fn fake_podman(path: &Path) { + let listener = UnixListener::bind(path).unwrap(); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut buffer = [0_u8; 4096]; + let _ = stream.read(&mut buffer); + let _ = stream + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK"); + } + }); +} + +struct Serving { + child: Child, + channel: Channel, + _dir: tempfile::TempDir, +} + +impl Drop for Serving { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +async fn connect(path: &Path) -> Option { + let path = path.to_path_buf(); + Endpoint::try_from("http://localhost") + .unwrap() + .connect_with_connector(tower::service_fn(move |_| { + let path = path.clone(); + async move { + Ok::<_, std::io::Error>(TokioIo::new(tokio::net::UnixStream::connect(path).await?)) + } + })) + .await + .ok() +} + +async fn serve() -> Serving { + let dir = tempfile::tempdir().unwrap(); + let podman = dir.path().join("podman.sock"); + fake_podman(&podman); + let socket = dir.path().join("driver.sock"); + let table = format!("socket_path = \"{}\"\n", podman.display()); + let mut child = command( + &[ + "serve", + "--bind-socket", + socket.to_str().unwrap(), + "--expected-peer-pid", + &std::process::id().to_string(), + ], + &table, + dir.path(), + ) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_mins(1); + loop { + if let Some(status) = child.try_wait().unwrap() { + panic!("driver exited early: {status}"); + } + if let Some(channel) = connect(&socket).await { + return Serving { + child, + channel, + _dir: dir, + }; + } + assert!( + Instant::now() < deadline, + "driver never accepted a connection" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +fn configure(version: u32) -> ConfigureRequest { + ConfigureRequest { + protocol_version: version, + ..Default::default() + } +} + +#[tokio::test] +async fn launch_info_answers_and_compute_calls_wait_for_configure() { + let serving = serve().await; + + let info = DriverLaunchClient::new(serving.channel.clone()) + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap() + .into_inner(); + assert_eq!(info.driver_name, "podman"); + assert_eq!(info.protocol_versions, [PROTOCOL_VERSION]); + + let status = ComputeDriverClient::new(serving.channel.clone()) + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[tokio::test] +async fn a_failed_configure_leaves_the_driver_running_for_a_retry() { + let mut serving = serve().await; + let mut client = DriverLaunchClient::new(serving.channel.clone()); + + let unsupported = client + .configure(configure(PROTOCOL_VERSION + 1)) + .await + .unwrap_err(); + assert_eq!(unsupported.code(), Code::FailedPrecondition); + + // The fake Podman cannot describe itself, so construction fails here. + let failed = client + .configure(configure(PROTOCOL_VERSION)) + .await + .unwrap_err(); + assert_ne!(failed.code(), Code::Ok); + assert!(serving.child.try_wait().unwrap().is_none()); + + let retried = client + .configure(configure(PROTOCOL_VERSION)) + .await + .unwrap_err(); + assert_ne!(retried.code(), Code::FailedPrecondition, "{retried}"); + let still_unavailable = ComputeDriverClient::new(serving.channel.clone()) + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(still_unavailable.code(), Code::Unavailable); +} + +fn report_of(output: &Output) -> openshell_driver_sdk::StartReport { + let stdout = String::from_utf8_lossy(&output.stdout); + openshell_driver_sdk::StartReport::from_output(&stdout) + .unwrap_or_else(|| panic!("no report line in: {stdout}")) +} + +const SERVE_ARGS: [&str; 5] = [ + "serve", + "--bind-socket", + "/nonexistent/driver.sock", + "--expected-peer-pid", + "1", +]; + +#[test] +fn an_invalid_table_exits_with_the_config_code_and_one_json_line() { + let output = run(&SERVE_ARGS, "no_such_key = 1"); + assert_eq!(output.status.code(), Some(78)); + let report = report_of(&output); + assert_eq!(report.kind, openshell_driver_sdk::StartKind::InvalidConfig); + assert!(report.reason.contains("no_such_key"), "{}", report.reason); +} + +#[test] +fn an_unreachable_socket_exits_as_unavailable() { + let output = run(&SERVE_ARGS, "socket_path = \"/nonexistent/podman.sock\""); + assert_eq!(output.status.code(), Some(69)); + assert_eq!( + report_of(&output).kind, + openshell_driver_sdk::StartKind::Unavailable + ); +} + +#[test] +fn preflight_accepts_a_valid_table_without_contacting_podman() { + let table = "socket_path = \"/nonexistent/podman.sock\"\nnetwork_name = \"example\"\n"; + let output = run(&["preflight"], table); + assert_eq!(output.status.code(), Some(0), "{:?}", output.stdout); + assert_eq!(run(&["preflight"], "").status.code(), Some(0)); +} + +#[test] +fn preflight_rejects_an_unknown_key() { + let output = run(&["preflight"], "no_such_key = 1"); + assert_eq!(output.status.code(), Some(78)); + assert_eq!( + report_of(&output).kind, + openshell_driver_sdk::StartKind::InvalidConfig + ); +} + +#[test] +fn the_podman_socket_variable_is_honoured_before_the_table() { + let dir = tempfile::tempdir().unwrap(); + let podman = dir.path().join("podman.sock"); + fake_podman(&podman); + let socket = dir.path().join("driver.sock"); + let mut child = command( + &[ + "serve", + "--bind-socket", + socket.to_str().unwrap(), + "--expected-peer-pid", + &std::process::id().to_string(), + ], + "socket_path = \"/nonexistent/podman.sock\"", + dir.path(), + ) + .env("OPENSHELL_PODMAN_SOCKET", &podman) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(30); + while !socket.exists() { + assert!( + child.try_wait().unwrap().is_none(), + "the driver should have found the socket from the environment" + ); + assert!(Instant::now() < deadline, "driver never bound its socket"); + std::thread::sleep(Duration::from_millis(50)); + } + let _ = child.kill(); + let _ = child.wait(); +} diff --git a/crates/openshell-driver-sdk/Cargo.toml b/crates/openshell-driver-sdk/Cargo.toml new file mode 100644 index 0000000000..23706f09f4 --- /dev/null +++ b/crates/openshell-driver-sdk/Cargo.toml @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-driver-sdk" +description = "Shared building blocks for gateway-launched compute drivers" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +http = { workspace = true } +libc = "0.2" +openshell-core = { path = "../openshell-core", default-features = false, features = ["otel"] } +openshell-crypto = { workspace = true } +openshell-driver-launch = { path = "../openshell-driver-launch" } +openshell-otel = { path = "../openshell-otel" } +serde = { workspace = true } +serde_json = { workspace = true } +tonic = { workspace = true } + +[target.'cfg(unix)'.dependencies] +nix = { workspace = true } + +[dev-dependencies] +tempfile = "3" + +[lints] +workspace = true diff --git a/crates/openshell-driver-sdk/src/admission.rs b/crates/openshell-driver-sdk/src/admission.rs new file mode 100644 index 0000000000..1a3a77f358 --- /dev/null +++ b/crates/openshell-driver-sdk/src/admission.rs @@ -0,0 +1,47 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use openshell_core::resource_admission::DriverAdmissionConfig; +use tonic::Status; + +/// The admission policy the gateway sent in `Configure`. +/// +/// Empty means the defaults. The gateway validates the policy before it sends +/// it; the driver checks it again so a malformed message cannot weaken +/// admission. +pub fn admission_from_json(json: &str) -> Result { + if json.trim().is_empty() { + return Ok(DriverAdmissionConfig::default()); + } + let policy: DriverAdmissionConfig = serde_json::from_str(json) + .map_err(|error| Status::invalid_argument(format!("invalid admission policy: {error}")))?; + policy.validate().map_err(Status::invalid_argument)?; + Ok(policy) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_means_the_secure_defaults() { + let policy = admission_from_json("").unwrap(); + assert!(!policy.allow_driver_config); + } + + #[test] + fn a_policy_round_trips() { + let sent = DriverAdmissionConfig { + allow_driver_config: true, + ..DriverAdmissionConfig::default() + }; + let json = serde_json::to_string(&sent).unwrap(); + assert!(admission_from_json(&json).unwrap().allow_driver_config); + } + + #[test] + fn malformed_json_is_invalid() { + let status = admission_from_json("{not json").unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } +} diff --git a/crates/openshell-driver-sdk/src/endpoint.rs b/crates/openshell-driver-sdk/src/endpoint.rs new file mode 100644 index 0000000000..d3747dafc1 --- /dev/null +++ b/crates/openshell-driver-sdk/src/endpoint.rs @@ -0,0 +1,61 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/// Check the syntax and scheme of an operator-set `grpc_endpoint`: an +/// `http://` or `https://` URL with a host. This needs no gateway context, so +/// `preflight` can run it. +pub fn validate_grpc_endpoint(endpoint: &str) -> Result<(), String> { + let uri: http::Uri = endpoint + .parse() + .map_err(|error| format!("grpc_endpoint {endpoint:?} is not a valid URL: {error}"))?; + match uri.scheme_str() { + Some("http" | "https") => {} + _ => { + return Err(format!( + "grpc_endpoint {endpoint:?} must use the http:// or https:// scheme" + )); + } + } + if uri.host().is_none_or(str::is_empty) { + return Err(format!("grpc_endpoint {endpoint:?} has no host")); + } + Ok(()) +} + +/// Whether sandboxes dial `endpoint` over TLS, which needs the gateway CA. +#[must_use] +pub fn endpoint_uses_tls(endpoint: &str) -> bool { + endpoint + .get(..8) + .is_some_and(|prefix| prefix.eq_ignore_ascii_case("https://")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn http_and_https_urls_with_a_host_are_accepted() { + for endpoint in [ + "http://127.0.0.1:8080", + "https://gateway.internal:8443", + "https://[::1]:8443", + ] { + validate_grpc_endpoint(endpoint).unwrap(); + } + } + + #[test] + fn other_schemes_and_malformed_urls_are_rejected() { + for endpoint in ["ftp://host:1", "host:8080", "http://", "not a url", "/path"] { + assert!(validate_grpc_endpoint(endpoint).is_err(), "{endpoint}"); + } + } + + #[test] + fn only_https_needs_the_gateway_ca() { + assert!(endpoint_uses_tls("https://gateway:1")); + assert!(endpoint_uses_tls("HTTPS://gateway:1")); + assert!(!endpoint_uses_tls("http://gateway:1")); + } +} diff --git a/crates/openshell-driver-sdk/src/gateway.rs b/crates/openshell-driver-sdk/src/gateway.rs new file mode 100644 index 0000000000..f277611f00 --- /dev/null +++ b/crates/openshell-driver-sdk/src/gateway.rs @@ -0,0 +1,99 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::net::SocketAddr; +use std::path::PathBuf; + +use openshell_driver_launch::proto; +use tonic::Status; + +/// Gateway-owned values a driver needs. A launched driver receives them in +/// `Configure`; a standalone driver builds them from its flags. Unset values +/// fall back to what the operator's driver table says. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GatewayContext { + pub gateway_port: Option, + pub tls_ca_path: Option, + pub gateway_name: Option, + /// The gateway's listener, which a driver may use to choose how sandboxes + /// reach it. + pub bind_address: Option, +} + +impl TryFrom<&proto::GatewayContext> for GatewayContext { + type Error = Status; + + fn try_from(context: &proto::GatewayContext) -> Result { + let gateway_port = match context.gateway_port { + 0 => None, + port => Some(u16::try_from(port).map_err(|_| { + Status::invalid_argument(format!("gateway_port {port} is out of range")) + })?), + }; + let non_empty = |value: &str| (!value.is_empty()).then(|| value.to_string()); + let bind_address = non_empty(&context.bind_address) + .map(|address| { + address.parse().map_err(|error| { + Status::invalid_argument(format!("bind_address {address:?}: {error}")) + }) + }) + .transpose()?; + Ok(Self { + gateway_port, + tls_ca_path: non_empty(&context.tls_ca_path).map(PathBuf::from), + gateway_name: non_empty(&context.gateway_name), + bind_address, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_values_are_unset() { + assert_eq!( + GatewayContext::try_from(&proto::GatewayContext::default()).unwrap(), + GatewayContext::default() + ); + } + + #[test] + fn values_are_carried_over() { + let context = GatewayContext::try_from(&proto::GatewayContext { + gateway_port: 8080, + tls_ca_path: "/etc/ca.pem".to_string(), + gateway_name: "gw".to_string(), + bind_address: "127.0.0.1:8080".to_string(), + }) + .unwrap(); + assert_eq!(context.gateway_port, Some(8080)); + assert_eq!(context.tls_ca_path, Some(PathBuf::from("/etc/ca.pem"))); + assert_eq!(context.gateway_name.as_deref(), Some("gw")); + assert_eq!( + context.bind_address, + Some("127.0.0.1:8080".parse().unwrap()) + ); + } + + #[test] + fn a_malformed_bind_address_is_invalid() { + let status = GatewayContext::try_from(&proto::GatewayContext { + bind_address: "not-an-address".to_string(), + ..Default::default() + }) + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } + + #[test] + fn an_out_of_range_port_is_invalid() { + let status = GatewayContext::try_from(&proto::GatewayContext { + gateway_port: 70_000, + ..Default::default() + }) + .unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } +} diff --git a/crates/openshell-driver-sdk/src/guard.rs b/crates/openshell-driver-sdk/src/guard.rs new file mode 100644 index 0000000000..5969075883 --- /dev/null +++ b/crates/openshell-driver-sdk/src/guard.rs @@ -0,0 +1,30 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::time::Duration; + +use nix::errno::Errno; +use nix::sys::signal::kill; +use nix::unistd::Pid; + +/// How often the guard checks that the parent still exists. +const POLL_INTERVAL: Duration = Duration::from_secs(1); + +/// Exit this process when `parent_pid` no longer exists, so a driver does +/// not outlive the gateway that launched it. Works on every Unix, unlike +/// `PR_SET_PDEATHSIG`. +pub fn watch_parent(parent_pid: u32) { + let Ok(parent_pid) = i32::try_from(parent_pid) else { + return; + }; + let pid = Pid::from_raw(parent_pid); + std::thread::spawn(move || { + loop { + std::thread::sleep(POLL_INTERVAL); + if kill(pid, None) == Err(Errno::ESRCH) { + eprintln!("parent process {parent_pid} exited; stopping"); + std::process::exit(1); + } + } + }); +} diff --git a/crates/openshell-driver-sdk/src/lib.rs b/crates/openshell-driver-sdk/src/lib.rs new file mode 100644 index 0000000000..207da5c992 --- /dev/null +++ b/crates/openshell-driver-sdk/src/lib.rs @@ -0,0 +1,28 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Shared building blocks for gateway-launched compute drivers. +//! +//! A launched driver reads its operator table from stdin, reports start-up +//! failures with a stable exit code and one JSON line on stdout, and receives +//! gateway metadata through [`launch`]'s `Configure` RPC. + +mod admission; +mod endpoint; +mod gateway; +mod guard; +mod start; +mod table; +mod telemetry; +mod trust; + +pub use admission::admission_from_json; +pub use endpoint::{endpoint_uses_tls, validate_grpc_endpoint}; +pub use gateway::GatewayContext; +#[cfg(unix)] +pub use guard::watch_parent; +pub use openshell_driver_launch as launch; +pub use start::{EXIT_CONFIG, EXIT_UNAVAILABLE, StartKind, StartReport, StartResult}; +pub use table::{MAX_TABLE_BYTES, read_stdin_table, read_table}; +pub use telemetry::{deferred_export_config, supervisor_otlp}; +pub use trust::load_network_trust; diff --git a/crates/openshell-driver-sdk/src/start.rs b/crates/openshell-driver-sdk/src/start.rs new file mode 100644 index 0000000000..ff38e64cf5 --- /dev/null +++ b/crates/openshell-driver-sdk/src/start.rs @@ -0,0 +1,143 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use serde::{Deserialize, Serialize}; + +/// `EX_UNAVAILABLE`: the backend is not reachable with these settings. +pub const EXIT_UNAVAILABLE: i32 = 69; +/// `EX_CONFIG`: the driver table is invalid. +pub const EXIT_CONFIG: i32 = 78; + +/// Why a driver stopped before it began serving. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum StartKind { + Unavailable, + InvalidConfig, + Error, +} + +impl StartKind { + /// The process exit code for this result. + #[must_use] + pub const fn exit_code(self) -> i32 { + match self { + Self::Unavailable => EXIT_UNAVAILABLE, + Self::InvalidConfig => EXIT_CONFIG, + Self::Error => 1, + } + } + + /// The result for a driver's exit code. Any code other than the two + /// defined ones is an internal failure. + #[must_use] + pub const fn from_exit_code(code: i32) -> Self { + match code { + EXIT_UNAVAILABLE => Self::Unavailable, + EXIT_CONFIG => Self::InvalidConfig, + _ => Self::Error, + } + } +} + +/// The one JSON line a driver writes to stdout before exiting. Stderr stays +/// for tracing, panics and native library output. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StartReport { + #[serde(rename = "result")] + pub kind: StartKind, + pub reason: String, +} + +impl StartReport { + /// The report in the last line of `stdout` that parses as one. + #[must_use] + pub fn from_output(stdout: &str) -> Option { + stdout + .lines() + .rev() + .find_map(|line| serde_json::from_str(line.trim()).ok()) + } +} + +/// A start-up failure, reported once and mapped to an exit code. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct StartResult { + pub kind: StartKind, + pub reason: String, +} + +impl StartResult { + pub fn unavailable(reason: impl Into) -> Self { + Self::new(StartKind::Unavailable, reason) + } + + pub fn invalid_config(reason: impl Into) -> Self { + Self::new(StartKind::InvalidConfig, reason) + } + + pub fn error(reason: impl Into) -> Self { + Self::new(StartKind::Error, reason) + } + + fn new(kind: StartKind, reason: impl Into) -> Self { + Self { + kind, + reason: reason.into(), + } + } + + /// The JSON line, without a trailing newline. + #[must_use] + pub fn json_line(&self) -> String { + serde_json::to_string(&StartReport { + kind: self.kind, + reason: self.reason.clone(), + }) + .expect("a report of strings serializes") + } + + /// Write the JSON line to stdout and return the exit code. + #[must_use] + pub fn report(&self) -> i32 { + println!("{}", self.json_line()); + self.kind.exit_code() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn kinds_map_to_the_documented_exit_codes() { + assert_eq!(StartKind::Unavailable.exit_code(), 69); + assert_eq!(StartKind::InvalidConfig.exit_code(), 78); + assert_eq!(StartKind::Error.exit_code(), 1); + for kind in [ + StartKind::Unavailable, + StartKind::InvalidConfig, + StartKind::Error, + ] { + assert_eq!(StartKind::from_exit_code(kind.exit_code()), kind); + } + assert_eq!(StartKind::from_exit_code(2), StartKind::Error); + } + + #[test] + fn the_report_line_has_the_documented_shape() { + let line = StartResult::invalid_config("unknown key `x`").json_line(); + assert_eq!( + line, + r#"{"result":"invalid_config","reason":"unknown key `x`"}"# + ); + assert_eq!( + StartReport::from_output(&format!("log noise\n{line}\n")), + Some(StartReport { + kind: StartKind::InvalidConfig, + reason: "unknown key `x`".to_string() + }) + ); + assert_eq!(StartReport::from_output("no report here\n"), None); + } +} diff --git a/crates/openshell-driver-sdk/src/table.rs b/crates/openshell-driver-sdk/src/table.rs new file mode 100644 index 0000000000..c9450d3858 --- /dev/null +++ b/crates/openshell-driver-sdk/src/table.rs @@ -0,0 +1,55 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::io::Read; + +/// Largest driver table a driver reads. +pub const MAX_TABLE_BYTES: u64 = 1024 * 1024; + +/// Read the driver table from `reader`. An empty table means the operator +/// wrote none, and the driver uses its defaults. +pub fn read_table(reader: impl Read) -> std::io::Result { + let mut table = String::new(); + let read = reader + .take(MAX_TABLE_BYTES + 1) + .read_to_string(&mut table)?; + if read as u64 > MAX_TABLE_BYTES { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + "driver table is too large", + )); + } + Ok(table) +} + +/// Read the driver table from stdin. +pub fn read_stdin_table() -> std::io::Result { + read_table(std::io::stdin().lock()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn empty_input_is_an_empty_table() { + assert_eq!(read_table(&b""[..]).unwrap(), ""); + } + + #[test] + fn the_table_is_read_unparsed() { + let text = "key = \"value\"\n# a comment\n"; + assert_eq!(read_table(text.as_bytes()).unwrap(), text); + } + + #[test] + fn an_oversized_table_is_rejected() { + let big = vec![b'#'; usize::try_from(MAX_TABLE_BYTES).unwrap() + 1]; + assert!(read_table(&big[..]).is_err()); + } + + #[test] + fn invalid_utf8_is_rejected() { + assert!(read_table(&[0xff, 0xfe][..]).is_err()); + } +} diff --git a/crates/openshell-driver-sdk/src/telemetry.rs b/crates/openshell-driver-sdk/src/telemetry.rs new file mode 100644 index 0000000000..dc98b33df2 --- /dev/null +++ b/crates/openshell-driver-sdk/src/telemetry.rs @@ -0,0 +1,142 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::path::Path; + +use openshell_core::sandbox_env::{OtlpExport, OtlpProtocol, SupervisorOtlp}; +use openshell_driver_launch::proto; +use openshell_otel::DeferredExportConfig; +use tonic::Status; + +fn export(export: Option<&proto::OtlpExport>) -> Result, Status> { + let Some(export) = export.filter(|export| !export.endpoint.is_empty()) else { + return Ok(None); + }; + let protocol = if export.protocol.is_empty() { + OtlpProtocol::default() + } else { + export.protocol.parse().map_err(Status::invalid_argument)? + }; + Ok(Some(OtlpExport { + endpoint: export.endpoint.clone(), + protocol, + })) +} + +/// The OTLP exports supervisors receive. +pub fn supervisor_otlp(telemetry: Option<&proto::Telemetry>) -> Result { + let Some(telemetry) = telemetry else { + return Ok(SupervisorOtlp::default()); + }; + Ok(SupervisorOtlp { + traces: export(telemetry.traces.as_ref())?, + ocsf: export(telemetry.ocsf.as_ref())?, + agent: export(telemetry.agent.as_ref())?, + }) +} + +/// The settings for the driver's own trace exporter, or `None` when the +/// gateway configured no trace endpoint. +pub fn deferred_export_config<'a>( + telemetry: Option<&'a proto::Telemetry>, + gateway_name: Option<&'a str>, + service_version: &'static str, +) -> Result>, Status> { + let Some(telemetry) = telemetry else { + return Ok(None); + }; + let Some(traces) = export(telemetry.traces.as_ref())? else { + return Ok(None); + }; + let tls = telemetry.collector.as_ref(); + let path = |value: Option<&'a String>| { + value + .filter(|value| !value.is_empty()) + .map(|value| Path::new(value.as_str())) + }; + Ok(Some(DeferredExportConfig { + endpoint: telemetry + .traces + .as_ref() + .map_or("", |traces| traces.endpoint.as_str()), + protocol: traces.protocol.into(), + ca_file: path(tls.map(|tls| &tls.ca_file)), + cert_file: path(tls.map(|tls| &tls.cert_file)), + key_file: path(tls.map(|tls| &tls.key_file)), + gateway_name, + service_version, + headers: telemetry.trace_headers.as_str(), + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn telemetry() -> proto::Telemetry { + proto::Telemetry { + traces: Some(proto::OtlpExport { + endpoint: "http://traces:4317".to_string(), + protocol: "http/protobuf".to_string(), + }), + ocsf: Some(proto::OtlpExport { + endpoint: "http://ocsf:4317".to_string(), + protocol: String::new(), + }), + agent: None, + collector: Some(proto::CollectorTls { + ca_file: "/etc/ca.pem".to_string(), + ..Default::default() + }), + trace_headers: "authorization=secret".to_string(), + } + } + + #[test] + fn supervisors_receive_each_lane_with_its_protocol() { + let otlp = supervisor_otlp(Some(&telemetry())).unwrap(); + assert_eq!( + otlp.traces, + Some(OtlpExport { + endpoint: "http://traces:4317".to_string(), + protocol: OtlpProtocol::HttpProtobuf + }) + ); + assert_eq!(otlp.ocsf.unwrap().protocol, OtlpProtocol::Grpc); + assert!(otlp.agent.is_none()); + assert_eq!(supervisor_otlp(None).unwrap(), SupervisorOtlp::default()); + } + + #[test] + fn an_unknown_protocol_is_invalid() { + let mut telemetry = telemetry(); + telemetry.traces.as_mut().unwrap().protocol = "carrier-pigeon".to_string(); + let status = supervisor_otlp(Some(&telemetry)).unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } + + #[test] + fn the_driver_exporter_takes_the_trace_lane_tls_and_headers() { + let telemetry = telemetry(); + let config = deferred_export_config(Some(&telemetry), Some("gw"), "1.0") + .unwrap() + .unwrap(); + assert_eq!(config.endpoint, "http://traces:4317"); + assert_eq!(config.ca_file, Some(Path::new("/etc/ca.pem"))); + assert_eq!(config.cert_file, None); + assert_eq!(config.gateway_name, Some("gw")); + assert_eq!(config.headers, "authorization=secret"); + } + + #[test] + fn no_trace_endpoint_means_no_exporter() { + let mut telemetry = telemetry(); + telemetry.traces = None; + assert!( + deferred_export_config(Some(&telemetry), None, "1.0") + .unwrap() + .is_none() + ); + assert!(deferred_export_config(None, None, "1.0").unwrap().is_none()); + } +} diff --git a/crates/openshell-driver-sdk/src/trust.rs b/crates/openshell-driver-sdk/src/trust.rs new file mode 100644 index 0000000000..ef3d5131d3 --- /dev/null +++ b/crates/openshell-driver-sdk/src/trust.rs @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::io::Read as _; +use std::path::PathBuf; + +use openshell_core::network_trust::{ + MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES, NetworkSupervisorTrustBundle, +}; +use openshell_driver_launch::proto; +use tonic::Status; + +const CERTIFICATE_BEGIN: &str = "-----BEGIN CERTIFICATE-----"; + +/// Load the gateway-staged destination trust bundle that `Configure` +/// described, or `None` when the gateway sent none. +/// +/// The artifact is read once, without following symlinks and within a size +/// limit. Its digest and certificate count must match the message, and its +/// file permissions must be the ones the gateway sets. The returned bundle +/// keeps the path so a driver can call +/// [`NetworkSupervisorTrustBundle::verify_artifact`] before each sandbox +/// create, start or supervisor replacement. +pub fn load_network_trust( + trust: Option<&proto::NetworkTrust>, +) -> Result, Status> { + let Some(trust) = trust.filter(|trust| !trust.artifact_path.is_empty()) else { + return Ok(None); + }; + let path = PathBuf::from(&trust.artifact_path); + let invalid = |message: String| Status::invalid_argument(message); + let hex = trust + .digest + .strip_prefix("sha256:") + .filter(|hex| { + hex.len() == 64 + && hex + .bytes() + .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) + }) + .ok_or_else(|| invalid("network trust digest must be sha256: and lowercase hex".into()))?; + + let pem = read_artifact(&path)?; + let actual = openshell_crypto::sha256(&pem) + .map_err(|error| Status::internal(format!("hash network trust bundle: {error}")))?; + if hex_lower(&actual) != hex { + return Err(Status::failed_precondition(format!( + "network trust artifact '{}' does not match digest {}", + path.display(), + trust.digest + ))); + } + let count = std::str::from_utf8(&pem) + .map_err(|_| invalid("network trust bundle is not PEM text".into()))? + .matches(CERTIFICATE_BEGIN) + .count(); + if count == 0 || u32::try_from(count) != Ok(trust.certificate_count) { + return Err(invalid(format!( + "network trust bundle has {count} certificates but the gateway reported {}", + trust.certificate_count + ))); + } + let bundle = NetworkSupervisorTrustBundle::new(pem, count, trust.digest.clone(), path); + bundle + .verify_artifact() + .map_err(|error| Status::failed_precondition(error.to_string()))?; + Ok(Some(bundle)) +} + +fn hex_lower(bytes: &[u8]) -> String { + use std::fmt::Write as _; + + bytes.iter().fold(String::new(), |mut out, byte| { + let _ = write!(out, "{byte:02x}"); + out + }) +} + +fn read_artifact(path: &std::path::Path) -> Result, Status> { + let unreadable = |error: std::io::Error| { + Status::failed_precondition(format!( + "read network trust artifact '{}': {error}", + path.display() + )) + }; + let mut options = std::fs::OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt as _; + options.custom_flags(libc::O_CLOEXEC | libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = options.open(path).map_err(unreadable)?; + if !file.metadata().map_err(unreadable)?.is_file() { + return Err(Status::failed_precondition(format!( + "network trust artifact '{}' is not a regular file", + path.display() + ))); + } + let mut pem = Vec::new(); + file.take(MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES as u64 + 1) + .read_to_end(&mut pem) + .map_err(unreadable)?; + if pem.len() > MAX_NETWORK_SUPERVISOR_TRUST_BUNDLE_BYTES { + return Err(Status::failed_precondition(format!( + "network trust artifact '{}' is too large", + path.display() + ))); + } + Ok(pem) +} + +#[cfg(all(test, unix))] +mod tests { + use std::os::unix::fs::PermissionsExt as _; + + use super::*; + + const PEM: &[u8] = b"-----BEGIN CERTIFICATE-----\nAAAA\n-----END CERTIFICATE-----\n"; + + fn stage(mode: u32, contents: &[u8]) -> (tempfile::TempDir, proto::NetworkTrust) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("additional-ca.crt"); + std::fs::write(&path, contents).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap(); + let digest = hex_lower(&openshell_crypto::sha256(contents).unwrap()); + let trust = proto::NetworkTrust { + artifact_path: path.display().to_string(), + digest: format!("sha256:{digest}"), + certificate_count: 1, + }; + (dir, trust) + } + + #[test] + fn no_trust_means_no_bundle() { + assert!(load_network_trust(None).unwrap().is_none()); + assert!( + load_network_trust(Some(&proto::NetworkTrust::default())) + .unwrap() + .is_none() + ); + } + + #[test] + fn a_staged_artifact_loads_and_verifies() { + let (_dir, trust) = stage(0o444, PEM); + let bundle = load_network_trust(Some(&trust)).unwrap().unwrap(); + assert_eq!(bundle.certificate_count(), 1); + assert_eq!(bundle.digest(), trust.digest); + bundle.verify_artifact().unwrap(); + } + + #[test] + fn a_digest_mismatch_is_rejected() { + let (_dir, mut trust) = stage(0o444, PEM); + trust.digest = format!("sha256:{}", "0".repeat(64)); + let status = load_network_trust(Some(&trust)).unwrap_err(); + assert_eq!(status.code(), tonic::Code::FailedPrecondition); + } + + #[test] + fn a_wrong_certificate_count_is_rejected() { + let (_dir, mut trust) = stage(0o444, PEM); + trust.certificate_count = 2; + let status = load_network_trust(Some(&trust)).unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } + + #[test] + fn a_writable_artifact_is_rejected() { + let (_dir, trust) = stage(0o666, PEM); + assert!(load_network_trust(Some(&trust)).is_err()); + } + + #[test] + fn a_symlink_is_not_followed() { + let (dir, trust) = stage(0o444, PEM); + let link = dir.path().join("link.crt"); + std::os::unix::fs::symlink(&trust.artifact_path, &link).unwrap(); + let trust = proto::NetworkTrust { + artifact_path: link.display().to_string(), + ..trust + }; + assert!(load_network_trust(Some(&trust)).is_err()); + } + + #[test] + fn a_malformed_digest_is_rejected() { + let (_dir, mut trust) = stage(0o444, PEM); + trust.digest = "sha256:XYZ".to_string(); + assert_eq!( + load_network_trust(Some(&trust)).unwrap_err().code(), + tonic::Code::InvalidArgument + ); + } +} diff --git a/crates/openshell-driver-vm/Cargo.toml b/crates/openshell-driver-vm/Cargo.toml index 57921d4b9a..b203b506d0 100644 --- a/crates/openshell-driver-vm/Cargo.toml +++ b/crates/openshell-driver-vm/Cargo.toml @@ -27,6 +27,8 @@ path = "src/bin/openshell-vm-init.rs" openshell-core = { path = "../openshell-core", default-features = false, features = ["clap"] } openshell-isolation-interface = { path = "../openshell-isolation-interface" } openshell-sandbox-backend = { path = "../openshell-sandbox-backend" } +openshell-driver-launch = { path = "../openshell-driver-launch", optional = true } +openshell-driver-sdk = { path = "../openshell-driver-sdk", optional = true } openshell-otel = { path = "../openshell-otel", optional = true } openshell-policy = { path = "../openshell-policy", optional = true } openshell-driver-podman = { path = "../openshell-driver-podman", optional = true } @@ -61,6 +63,7 @@ libloading = { version = "0.8", optional = true } tar = { version = "0.4", optional = true } flate2 = { version = "1", optional = true } sha2 = { version = "0.10", optional = true } +toml = { workspace = true, optional = true } zstd = { version = "0.14", optional = true } [features] @@ -79,7 +82,10 @@ compute-driver = [ "dep:miette", "dep:nix", "dep:oci-client", + "dep:openshell-driver-launch", + "dep:openshell-driver-sdk", "dep:openshell-otel", + "dep:toml", "openshell-core/otel", "dep:openshell-policy", "dep:openshell-driver-podman", @@ -116,6 +122,8 @@ telemetry = ["openshell-core/telemetry"] defaults-without-telemetry = ["compute-driver"] [dev-dependencies] +hyper-util = { workspace = true } +tower = { workspace = true } openshell-otel-test-support = { path = "../openshell-otel-test-support" } temp-env = "0.3" tempfile = "3" diff --git a/crates/openshell-driver-vm/README.md b/crates/openshell-driver-vm/README.md index cb9433d08e..9bfa3cff50 100644 --- a/crates/openshell-driver-vm/README.md +++ b/crates/openshell-driver-vm/README.md @@ -2,7 +2,7 @@ > Status: Experimental. The VM compute driver is under active development. -Standalone libkrun-backed [`ComputeDriver`](../../proto/compute_driver.proto) for OpenShell. The gateway spawns this binary as a subprocess and talks to it over the `openshell.compute.v1.ComputeDriver` Unix-socket surface. `openshell-supervisor` runs as a native host process, while `openshell-sandbox` runs as capability-free PID 1 inside each microVM and applies guest-local isolation over virtio-vsock. +Standalone libkrun-backed [`ComputeDriver`](../../proto/compute_driver.proto) for OpenShell. The gateway spawns this binary as `serve`, passes the `[openshell.drivers.vm]` table on stdin and gateway metadata in a `Configure` call (`proto/driver_launch.proto`), and talks to it over the `openshell.compute.v1.ComputeDriver` Unix-socket surface. `openshell-supervisor` runs as a native host process, while `openshell-sandbox` runs as capability-free PID 1 inside each microVM and applies guest-local isolation over virtio-vsock. New VM generations initiate the control connection to host CID 2 over vsock. Libkrun forwards that guest connection to the supervisor's protected Unix @@ -20,13 +20,13 @@ Caller driver config is disabled by default, including upload workflows encoded in driver JSON. GPU devices and their trusted VFIO plumbing are temporarily exempt from approval labels; existing GPU selection validation still applies. Private rootfs staging does not authorize arbitrary host paths. -The gateway passes its common policy to its managed VM subprocess. +The gateway's table, which holds the common policy, reaches the managed VM subprocess unparsed on stdin. See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission). ```mermaid flowchart LR subgraph host["Host"] - gateway["openshell-gateway
(vm::spawn)"] + gateway["openshell-gateway
(launcher)"] driver["openshell-driver-vm
libkrun"] supervisor["openshell-supervisor
host policy supervisor"] gateway <-->|"gRPC over UDS
compute-driver.sock"| driver @@ -341,3 +341,12 @@ so driver choice remains automatic unless the user explicitly overrides it. - 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. + +## Launched mode + +```text +openshell-driver-vm serve --bind-socket --expected-peer-pid --log-level < table.toml +openshell-driver-vm preflight < table.toml +``` + +`settings_from_table` in `src/settings.rs` is the only place the table is parsed and validated. `serve` exits 78 on an invalid table. A setting the table leaves unset still falls back to the driver's environment variable (for example `OPENSHELL_VM_UPSTREAM_PROXY`), as it did when the gateway passed flags. The table rejects `guest_tls_ca`, `gateway_port` and the admission keys, which the gateway supplies in `Configure`. The driver binds its socket and answers `GetLaunchInfo` at once, but `ComputeDriver` calls return `UNAVAILABLE` and no VM state is created until `Configure` succeeds. `preflight` validates the table and exits. diff --git a/crates/openshell-driver-vm/src/lib.rs b/crates/openshell-driver-vm/src/lib.rs index 66041ea034..bc88fa5d80 100644 --- a/crates/openshell-driver-vm/src/lib.rs +++ b/crates/openshell-driver-vm/src/lib.rs @@ -36,6 +36,8 @@ pub mod procguard; mod rootfs; #[cfg(feature = "compute-driver")] mod runtime; +#[cfg(feature = "compute-driver")] +pub mod settings; #[cfg(feature = "compute-driver")] pub use driver::{VmDriver, VmDriverConfig}; diff --git a/crates/openshell-driver-vm/src/listener.rs b/crates/openshell-driver-vm/src/listener.rs new file mode 100644 index 0000000000..04283b7482 --- /dev/null +++ b/crates/openshell-driver-vm/src/listener.rs @@ -0,0 +1,271 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The driver's private Unix-socket listener: socket directory and socket +//! preparation, peer authorization by uid and expected gateway PID, and the +//! shutdown signal. + +use futures::Stream; +use std::io; +use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; +use std::path::Path; +use std::pin::Pin; +use std::task::{Context, Poll}; +use tokio::net::{UnixListener, UnixStream}; +use tracing::info; + +pub async fn shutdown_signal() { + let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("install SIGTERM handler"); + tokio::select! { + result = tokio::signal::ctrl_c() => { + if let Err(error) = result { + tracing::warn!(%error, "failed to listen for Ctrl-C"); + } + } + _ = terminate.recv() => {} + } + info!("Shutdown signal received; stopping vm compute driver"); +} + +pub fn prepare_compute_driver_socket(socket_path: &Path) -> Result<(), String> { + let Some(parent) = socket_path.parent() else { + return Err(format!( + "vm compute driver socket path '{}' has no parent directory", + socket_path.display() + )); + }; + let expected_uid = current_euid(); + prepare_private_socket_dir(parent, expected_uid)?; + remove_stale_socket(socket_path, expected_uid) +} + +pub fn current_euid() -> u32 { + rustix::process::geteuid().as_raw() +} + +pub fn prepare_private_socket_dir(socket_dir: &Path, expected_uid: u32) -> Result<(), String> { + std::fs::create_dir_all(socket_dir) + .map_err(|err| format!("create socket dir {}: {err}", socket_dir.display()))?; + let metadata = std::fs::symlink_metadata(socket_dir) + .map_err(|err| format!("stat socket dir {}: {err}", socket_dir.display()))?; + let file_type = metadata.file_type(); + if file_type.is_symlink() { + return Err(format!( + "socket dir {} is a symlink; refusing to use it", + socket_dir.display() + )); + } + if !file_type.is_dir() { + return Err(format!( + "socket dir {} is not a directory", + socket_dir.display() + )); + } + if metadata.uid() != expected_uid { + return Err(format!( + "socket dir {} is owned by uid {} but current euid is {}", + socket_dir.display(), + metadata.uid(), + expected_uid + )); + } + std::fs::set_permissions(socket_dir, std::fs::Permissions::from_mode(0o700)) + .map_err(|err| format!("chmod socket dir {}: {err}", socket_dir.display())) +} + +pub fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> Result<(), String> { + let metadata = match std::fs::symlink_metadata(socket_path) { + Ok(metadata) => metadata, + Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), + Err(err) => return Err(format!("stat socket {}: {err}", socket_path.display())), + }; + let file_type = metadata.file_type(); + if file_type.is_symlink() { + return Err(format!( + "socket {} is a symlink; refusing to remove it", + socket_path.display() + )); + } + if metadata.uid() != expected_uid { + return Err(format!( + "socket {} is owned by uid {} but current euid is {}", + socket_path.display(), + metadata.uid(), + expected_uid + )); + } + if !file_type.is_socket() { + return Err(format!( + "socket path {} exists but is not a Unix socket", + socket_path.display() + )); + } + std::fs::remove_file(socket_path) + .map_err(|err| format!("remove stale socket {}: {err}", socket_path.display())) +} + +pub fn restrict_socket_permissions(socket_path: &Path) -> Result<(), String> { + std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600)) + .map_err(|err| format!("chmod socket {}: {err}", socket_path.display())) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PeerCredentials { + uid: u32, + pid: Option, +} + +pub fn peer_credentials(stream: &UnixStream) -> Result { + let credentials = stream + .peer_cred() + .map_err(|err| format!("read peer credentials: {err}"))?; + Ok(PeerCredentials { + uid: credentials.uid(), + pid: credentials.pid(), + }) +} + +pub fn authorize_peer_credentials( + peer: PeerCredentials, + driver_uid: u32, + gateway_pid: Option, +) -> Result<(), String> { + if peer.uid != driver_uid { + return Err(format!( + "peer uid {} does not match current euid {}", + peer.uid, driver_uid + )); + } + let Some(gateway_pid) = gateway_pid else { + return Ok(()); + }; + let Some(peer_process_id) = peer.pid.and_then(|pid| u32::try_from(pid).ok()) else { + return Err(format!( + "peer pid is unavailable; expected gateway pid {gateway_pid}" + )); + }; + if peer_process_id != gateway_pid { + return Err(format!( + "peer pid {peer_process_id} does not match expected gateway pid {gateway_pid}" + )); + } + Ok(()) +} + +pub struct AuthenticatedUnixIncoming { + listener: UnixListener, + expected_uid: u32, + expected_peer_pid: Option, +} + +impl AuthenticatedUnixIncoming { + pub fn new(listener: UnixListener, expected_peer_pid: Option) -> Self { + Self { + listener, + expected_uid: current_euid(), + expected_peer_pid, + } + } +} + +impl Stream for AuthenticatedUnixIncoming { + type Item = io::Result; + + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + loop { + match this.listener.poll_accept(cx) { + Poll::Ready(Ok((stream, _addr))) => { + let authorized = peer_credentials(&stream).and_then(|peer| { + authorize_peer_credentials(peer, this.expected_uid, this.expected_peer_pid) + }); + match authorized { + Ok(()) => return Poll::Ready(Some(Ok(stream))), + Err(err) => { + tracing::warn!( + error = %err, + "rejected vm compute driver UDS client" + ); + } + } + } + Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err))), + Poll::Pending => return Poll::Pending, + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn peer_authorization_accepts_matching_uid_and_pid() { + authorize_peer_credentials( + PeerCredentials { + uid: 1000, + pid: Some(42), + }, + 1000, + Some(42), + ) + .unwrap(); + } + + #[test] + fn peer_authorization_rejects_wrong_pid() { + let err = authorize_peer_credentials( + PeerCredentials { + uid: 1000, + pid: Some(7), + }, + 1000, + Some(42), + ) + .expect_err("wrong pid should be rejected"); + assert!(err.contains("does not match expected gateway pid")); + } + + #[test] + fn peer_authorization_rejects_wrong_uid() { + let err = authorize_peer_credentials( + PeerCredentials { + uid: 1001, + pid: Some(42), + }, + 1000, + Some(42), + ) + .expect_err("wrong uid should be rejected"); + assert!(err.contains("does not match current euid")); + } + + #[test] + fn peer_authorization_rejects_missing_pid_when_expected() { + let err = authorize_peer_credentials( + PeerCredentials { + uid: 1000, + pid: None, + }, + 1000, + Some(42), + ) + .expect_err("missing pid should be rejected"); + assert!(err.contains("peer pid is unavailable")); + } + + #[test] + fn peer_authorization_accepts_matching_uid_without_expected_pid() { + authorize_peer_credentials( + PeerCredentials { + uid: 1000, + pid: None, + }, + 1000, + None, + ) + .unwrap(); + } +} diff --git a/crates/openshell-driver-vm/src/main.rs b/crates/openshell-driver-vm/src/main.rs index fac8ee7c7a..1360276daf 100644 --- a/crates/openshell-driver-vm/src/main.rs +++ b/crates/openshell-driver-vm/src/main.rs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 use clap::Parser; -use futures::Stream; use miette::{IntoDiagnostic, Result}; use openshell_core::VERSION; use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; @@ -12,15 +11,18 @@ use openshell_driver_vm::{VM_RUNTIME_DIR_ENV, configured_runtime_dir}; use openshell_driver_vm::{ VmBackend, VmDriver, VmDriverConfig, VmLaunchConfig, VmMount, VsockPortMap, procguard, run_vm, }; -use std::io; use std::net::SocketAddr; -use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt}; -use std::path::{Path, PathBuf}; -use std::pin::Pin; -use std::task::{Context, Poll}; -use tokio::net::{UnixListener, UnixStream}; +use std::path::PathBuf; +use tokio::net::UnixListener; use tracing::info; +mod listener; +mod serve; +use listener::{ + AuthenticatedUnixIncoming, prepare_compute_driver_socket, restrict_socket_permissions, + shutdown_signal, +}; + #[derive(Parser, Debug)] #[command(name = "openshell-driver-vm")] #[command(version = VERSION)] @@ -290,6 +292,9 @@ struct Args { #[tokio::main] async fn main() -> Result<()> { + if let Some(code) = serve::dispatch().await { + std::process::exit(code); + } let args = Args::parse(); if let Some(request) = args.internal_prepare_image { openshell_driver_vm::driver::run_image_preparation_worker(&request) @@ -426,20 +431,6 @@ async fn main() -> Result<()> { result } -async fn shutdown_signal() { - let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) - .expect("install SIGTERM handler"); - tokio::select! { - result = tokio::signal::ctrl_c() => { - if let Err(error) = result { - tracing::warn!(%error, "failed to listen for Ctrl-C"); - } - } - _ = terminate.recv() => {} - } - info!("Shutdown signal received; stopping vm compute driver"); -} - #[derive(Debug, Clone, PartialEq, Eq)] enum ComputeDriverListenMode { Unix { @@ -477,178 +468,6 @@ fn compute_driver_listen_mode(args: &Args) -> std::result::Result std::result::Result<(), String> { - let Some(parent) = socket_path.parent() else { - return Err(format!( - "vm compute driver socket path '{}' has no parent directory", - socket_path.display() - )); - }; - let expected_uid = current_euid(); - prepare_private_socket_dir(parent, expected_uid)?; - remove_stale_socket(socket_path, expected_uid) -} - -fn current_euid() -> u32 { - rustix::process::geteuid().as_raw() -} - -fn prepare_private_socket_dir( - socket_dir: &Path, - expected_uid: u32, -) -> std::result::Result<(), String> { - std::fs::create_dir_all(socket_dir) - .map_err(|err| format!("create socket dir {}: {err}", socket_dir.display()))?; - let metadata = std::fs::symlink_metadata(socket_dir) - .map_err(|err| format!("stat socket dir {}: {err}", socket_dir.display()))?; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(format!( - "socket dir {} is a symlink; refusing to use it", - socket_dir.display() - )); - } - if !file_type.is_dir() { - return Err(format!( - "socket dir {} is not a directory", - socket_dir.display() - )); - } - if metadata.uid() != expected_uid { - return Err(format!( - "socket dir {} is owned by uid {} but current euid is {}", - socket_dir.display(), - metadata.uid(), - expected_uid - )); - } - std::fs::set_permissions(socket_dir, std::fs::Permissions::from_mode(0o700)) - .map_err(|err| format!("chmod socket dir {}: {err}", socket_dir.display())) -} - -fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> std::result::Result<(), String> { - let metadata = match std::fs::symlink_metadata(socket_path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == io::ErrorKind::NotFound => return Ok(()), - Err(err) => return Err(format!("stat socket {}: {err}", socket_path.display())), - }; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(format!( - "socket {} is a symlink; refusing to remove it", - socket_path.display() - )); - } - if metadata.uid() != expected_uid { - return Err(format!( - "socket {} is owned by uid {} but current euid is {}", - socket_path.display(), - metadata.uid(), - expected_uid - )); - } - if !file_type.is_socket() { - return Err(format!( - "socket path {} exists but is not a Unix socket", - socket_path.display() - )); - } - std::fs::remove_file(socket_path) - .map_err(|err| format!("remove stale socket {}: {err}", socket_path.display())) -} - -fn restrict_socket_permissions(socket_path: &Path) -> std::result::Result<(), String> { - std::fs::set_permissions(socket_path, std::fs::Permissions::from_mode(0o600)) - .map_err(|err| format!("chmod socket {}: {err}", socket_path.display())) -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -struct PeerCredentials { - uid: u32, - pid: Option, -} - -fn peer_credentials(stream: &UnixStream) -> std::result::Result { - let credentials = stream - .peer_cred() - .map_err(|err| format!("read peer credentials: {err}"))?; - Ok(PeerCredentials { - uid: credentials.uid(), - pid: credentials.pid(), - }) -} - -fn authorize_peer_credentials( - peer: PeerCredentials, - driver_uid: u32, - gateway_pid: Option, -) -> std::result::Result<(), String> { - if peer.uid != driver_uid { - return Err(format!( - "peer uid {} does not match current euid {}", - peer.uid, driver_uid - )); - } - let Some(gateway_pid) = gateway_pid else { - return Ok(()); - }; - let Some(peer_process_id) = peer.pid.and_then(|pid| u32::try_from(pid).ok()) else { - return Err(format!( - "peer pid is unavailable; expected gateway pid {gateway_pid}" - )); - }; - if peer_process_id != gateway_pid { - return Err(format!( - "peer pid {peer_process_id} does not match expected gateway pid {gateway_pid}" - )); - } - Ok(()) -} - -struct AuthenticatedUnixIncoming { - listener: UnixListener, - expected_uid: u32, - expected_peer_pid: Option, -} - -impl AuthenticatedUnixIncoming { - fn new(listener: UnixListener, expected_peer_pid: Option) -> Self { - Self { - listener, - expected_uid: current_euid(), - expected_peer_pid, - } - } -} - -impl Stream for AuthenticatedUnixIncoming { - type Item = io::Result; - - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - let this = self.get_mut(); - loop { - match this.listener.poll_accept(cx) { - Poll::Ready(Ok((stream, _addr))) => { - let authorized = peer_credentials(&stream).and_then(|peer| { - authorize_peer_credentials(peer, this.expected_uid, this.expected_peer_pid) - }); - match authorized { - Ok(()) => return Poll::Ready(Some(Ok(stream))), - Err(err) => { - tracing::warn!( - error = %err, - "rejected vm compute driver UDS client" - ); - } - } - } - Poll::Ready(Err(err)) => return Poll::Ready(Some(Err(err))), - Poll::Pending => return Poll::Pending, - } - } - } -} - fn build_vm_launch_config(args: &Args) -> std::result::Result { let root_disk = args .vm_root_disk @@ -800,10 +619,7 @@ fn maybe_reexec_internal_vm_with_runtime_env() -> Result<()> { #[cfg(test)] mod tests { - use super::{ - Args, ComputeDriverListenMode, PeerCredentials, authorize_peer_credentials, - compute_driver_listen_mode, parse_vm_mount_arg, - }; + use super::{Args, ComputeDriverListenMode, compute_driver_listen_mode, parse_vm_mount_arg}; use clap::Parser; use std::path::PathBuf; @@ -916,74 +732,6 @@ mod tests { ); } - #[test] - fn peer_authorization_accepts_matching_uid_and_pid() { - authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: Some(42), - }, - 1000, - Some(42), - ) - .unwrap(); - } - - #[test] - fn peer_authorization_rejects_wrong_pid() { - let err = authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: Some(7), - }, - 1000, - Some(42), - ) - .expect_err("wrong pid should be rejected"); - assert!(err.contains("does not match expected gateway pid")); - } - - #[test] - fn peer_authorization_rejects_wrong_uid() { - let err = authorize_peer_credentials( - PeerCredentials { - uid: 1001, - pid: Some(42), - }, - 1000, - Some(42), - ) - .expect_err("wrong uid should be rejected"); - assert!(err.contains("does not match current euid")); - } - - #[test] - fn peer_authorization_rejects_missing_pid_when_expected() { - let err = authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: None, - }, - 1000, - Some(42), - ) - .expect_err("missing pid should be rejected"); - assert!(err.contains("peer pid is unavailable")); - } - - #[test] - fn peer_authorization_accepts_matching_uid_without_expected_pid() { - authorize_peer_credentials( - PeerCredentials { - uid: 1000, - pid: None, - }, - 1000, - None, - ) - .unwrap(); - } - #[test] fn listen_mode_rejects_default_tcp() { let args = Args::parse_from(["openshell-driver-vm"]); diff --git a/crates/openshell-driver-vm/src/serve.rs b/crates/openshell-driver-vm/src/serve.rs new file mode 100644 index 0000000000..8a8df45633 --- /dev/null +++ b/crates/openshell-driver-vm/src/serve.rs @@ -0,0 +1,371 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The launched-driver commands: `serve` and `preflight`. +//! +//! The gateway starts `serve` with only bootstrap arguments and the operator's +//! `[openshell.drivers.vm]` table on stdin, then delivers gateway-owned +//! metadata with the `Configure` RPC. No VM state is created before +//! `Configure` succeeds. + +use std::path::PathBuf; + +use clap::Parser; +use openshell_core::VERSION; +use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; +use openshell_driver_sdk::launch::{ConfigureRequest, Deferred, Launch, LaunchInfo}; +use openshell_driver_sdk::{GatewayContext, StartResult}; +use openshell_driver_vm::settings::{VmSettings, settings_with_environment}; +use openshell_driver_vm::{VmDriver, VmDriverConfig, procguard}; +use tokio::net::UnixListener; +use tonic::Status; +use tracing::info; + +/// Bootstrap arguments the gateway passes to `serve`. They are frozen for +/// protocol version 1. +#[derive(Parser, Debug)] +#[command(name = "openshell-driver-vm serve")] +struct ServeArgs { + #[arg(long)] + bind_socket: PathBuf, + + #[arg(long)] + expected_peer_pid: u32, + + #[arg(long, default_value = "info")] + log_level: String, + + #[arg(long, env = "OPENSHELL_VM_GPU")] + gpu: bool, + + #[arg(long, env = "OPENSHELL_VM_GPU_MEM_MIB", default_value_t = 8192)] + gpu_mem_mib: u32, + + #[arg(long, env = "OPENSHELL_VM_GPU_VCPUS", default_value_t = 4)] + gpu_vcpus: u8, +} + +/// Run `serve` or `preflight` when that is the first argument, and return the +/// process exit code. Any other invocation returns `None` and takes the +/// standalone path. +pub async fn dispatch() -> Option { + let args: Vec = std::env::args().collect(); + match args.get(1)?.as_str() { + "serve" => { + let parsed = ServeArgs::parse_from( + std::iter::once("openshell-driver-vm serve".to_string()) + .chain(args.into_iter().skip(2)), + ); + Some(serve(parsed).await) + } + "preflight" => Some(preflight()), + _ => None, + } +} + +fn read_settings() -> Result { + let table = openshell_driver_sdk::read_stdin_table() + .map_err(|error| StartResult::invalid_config(format!("read driver table: {error}")))?; + settings_with_environment(&table, &|name| std::env::var(name).ok()) + .map_err(|error| StartResult::invalid_config(error.to_string())) +} + +fn preflight() -> i32 { + match read_settings() { + Ok(_) => 0, + Err(result) => result.report(), + } +} + +async fn serve(args: ServeArgs) -> i32 { + let tracing = openshell_otel::install_deferred_driver_tracing( + openshell_driver_vm::otel_tracing::TRACING, + &args.log_level, + openshell_core::color::stdout_ansi(), + ); + match run(args, tracing).await { + Ok(()) => 0, + Err(result) => result.report(), + } +} + +async fn run( + args: ServeArgs, + tracing: openshell_otel::DeferredDriverTracing, +) -> Result<(), StartResult> { + let settings = read_settings()?; + // The VM driver has no backend to reach before construction, which + // `Configure` triggers: libkrun and image preparation are used per sandbox. + + crate::listener::prepare_compute_driver_socket(&args.bind_socket) + .map_err(StartResult::error)?; + let listener = UnixListener::bind(&args.bind_socket) + .map_err(|error| StartResult::error(format!("bind socket: {error}")))?; + crate::listener::restrict_socket_permissions(&args.bind_socket).map_err(StartResult::error)?; + + // Arm procguard so the driver dies with the gateway instead of orphaning + // its per-sandbox VM launchers. + if let Err(error) = procguard::die_with_parent() { + tracing::warn!(%error, "procguard arm failed; gateway crashes may orphan this driver"); + } + + let log_level = args.log_level.clone(); + let launch = Launch::new( + LaunchInfo { + driver_name: "vm".to_string(), + driver_version: VERSION.to_string(), + features: Vec::new(), + }, + move |request| { + let settings = settings.clone(); + let log_level = log_level.clone(); + let tracing = tracing.clone(); + let gpu = (args.gpu, args.gpu_mem_mib, args.gpu_vcpus); + async move { apply_configure(settings, &log_level, gpu, &tracing, request).await } + }, + ); + let configured = launch.configured(); + let deferred = Deferred::new(configured.clone(), |driver: &VmDriver| { + ComputeDriverServer::new(driver.clone()) + }); + + info!(socket = %args.bind_socket.display(), "Starting vm compute driver"); + let result = tonic::transport::Server::builder() + .layer(openshell_otel::compute_driver_rpc_layer()) + .add_service(launch.into_server()) + .add_service(deferred) + .serve_with_incoming_shutdown( + crate::listener::AuthenticatedUnixIncoming::new(listener, Some(args.expected_peer_pid)), + crate::listener::shutdown_signal(), + ) + .await; + let _ = std::fs::remove_file(&args.bind_socket); + if let Some(driver) = configured.get() { + driver.remove_socket_root(); + } + result.map_err(|error| StartResult::error(format!("serve: {error}"))) +} + +/// Build the driver from the operator's settings and the gateway's metadata. +async fn apply_configure( + settings: VmSettings, + log_level: &str, + gpu: (bool, u32, u8), + tracing: &openshell_otel::DeferredDriverTracing, + request: ConfigureRequest, +) -> Result { + let gateway = GatewayContext::try_from(&request.gateway.clone().unwrap_or_default())?; + if let Some(export) = openshell_driver_sdk::deferred_export_config( + request.telemetry.as_ref(), + gateway.gateway_name.as_deref(), + VERSION, + )? && let Err(error) = tracing.enable_export(export) + { + tracing::error!(%error, "OTLP exporting could not be started"); + } + let supervisor_otlp = openshell_driver_sdk::supervisor_otlp(request.telemetry.as_ref())?; + let admission = openshell_driver_sdk::admission_from_json(&request.admission_json)?; + let config = driver_config( + settings, + &gateway, + request.network_trust.as_ref(), + supervisor_otlp, + admission, + log_level, + gpu, + )?; + VmDriver::new(config).await.map_err(Status::internal) +} + +/// The driver configuration for `settings` and the gateway's metadata. An +/// explicit `grpc_endpoint` wins over the gateway context. The gateway +/// supplies the admission policy. +fn driver_config( + settings: VmSettings, + gateway: &GatewayContext, + network_trust: Option<&openshell_driver_sdk::launch::NetworkTrust>, + supervisor_otlp: openshell_core::sandbox_env::SupervisorOtlp, + admission: openshell_core::resource_admission::DriverAdmissionConfig, + log_level: &str, + (gpu_enabled, gpu_mem_mib, gpu_vcpus): (bool, u32, u8), +) -> Result { + let tls_enabled = gateway.tls_ca_path.is_some(); + let grpc_endpoint = if settings.grpc_endpoint.trim().is_empty() { + let port = gateway.gateway_port.ok_or_else(|| { + Status::invalid_argument( + "grpc_endpoint is required when using the vm compute driver and the gateway sent no port", + ) + })?; + let scheme = if tls_enabled { "https" } else { "http" }; + format!("{scheme}://127.0.0.1:{port}") + } else { + settings.grpc_endpoint + }; + let trust = network_trust.filter(|trust| !trust.artifact_path.is_empty()); + if openshell_driver_sdk::endpoint_uses_tls(&grpc_endpoint) && !tls_enabled { + return Err(Status::invalid_argument( + "grpc_endpoint uses https:// but the gateway supplied no CA path", + )); + } + Ok(VmDriverConfig { + allow_driver_config: admission.allow_driver_config, + resource_admission: admission.resource_admission, + grpc_endpoint, + supervisor_otlp, + supervisor_gateway_name: gateway.gateway_name.clone(), + state_dir: settings.state_dir, + launcher_bin: None, + default_image: settings.default_image, + bootstrap_image: settings.bootstrap_image, + log_level: log_level.to_string(), + krun_log_level: settings.krun_log_level, + vcpus: settings.vcpus, + mem_mib: settings.mem_mib, + overlay_disk_mib: settings.overlay_disk_mib, + guest_tls_ca: gateway.tls_ca_path.clone(), + guest_tls_cert: None, + guest_tls_key: None, + additional_ca_bundle: trust.map(|trust| PathBuf::from(&trust.artifact_path)), + additional_ca_digest: trust.map(|trust| trust.digest.clone()), + additional_ca_certificate_count: trust + .map(|trust| usize::try_from(trust.certificate_count)) + .transpose() + .map_err(|_| Status::invalid_argument("certificate_count is out of range"))?, + additional_ca_snapshot: None, + upstream_proxy: settings.upstream_proxy, + proxy_ca_bundle: settings.proxy_ca_bundle, + ipv6_egress: settings.ipv6_egress, + provider_spiffe_workload_api_tcp_endpoint: settings + .provider_spiffe_workload_api_tcp_endpoint, + provider_spiffe_allow_guest_tcp: settings.provider_spiffe_allow_guest_tcp, + gpu_enabled, + gpu_mem_mib, + gpu_vcpus, + sandbox_uid: settings.sandbox_uid, + sandbox_gid: settings.sandbox_gid, + rootfs_tar_staging_dir: settings.rootfs_tar_staging_dir, + rootfs_tar_max_bytes: settings.rootfs_tar_max_bytes, + enable_bind_mounts: settings.enable_bind_mounts, + }) +} + +#[cfg(test)] +mod tests { + use openshell_driver_sdk::launch::NetworkTrust; + use openshell_driver_vm::settings::settings_from_table; + + use super::*; + + fn config( + table: &str, + gateway: &GatewayContext, + trust: Option<&NetworkTrust>, + ) -> Result { + driver_config( + settings_from_table(table).unwrap(), + gateway, + trust, + openshell_core::sandbox_env::SupervisorOtlp::default(), + openshell_core::resource_admission::DriverAdmissionConfig::default(), + "info", + (false, 8192, 4), + ) + } + + #[test] + fn the_endpoint_defaults_to_the_gateway_loopback_address() { + let plain = GatewayContext { + gateway_port: Some(8080), + ..Default::default() + }; + assert_eq!( + config("", &plain, None).unwrap().grpc_endpoint, + "http://127.0.0.1:8080" + ); + let tls = GatewayContext { + gateway_port: Some(8080), + tls_ca_path: Some("/ca.pem".into()), + ..Default::default() + }; + let built = config("", &tls, None).unwrap(); + assert_eq!(built.grpc_endpoint, "https://127.0.0.1:8080"); + assert_eq!(built.guest_tls_ca, Some("/ca.pem".into())); + } + + #[test] + fn an_explicit_endpoint_wins_but_the_ca_comes_from_the_gateway() { + let gateway = GatewayContext { + gateway_port: Some(8080), + tls_ca_path: Some("/gateway-ca.pem".into()), + gateway_name: Some("gw".to_string()), + bind_address: None, + }; + let built = config("grpc_endpoint = \"https://host.test:9\"", &gateway, None).unwrap(); + assert_eq!(built.grpc_endpoint, "https://host.test:9"); + assert_eq!(built.guest_tls_ca, Some("/gateway-ca.pem".into())); + assert_eq!(built.supervisor_gateway_name.as_deref(), Some("gw")); + } + + #[test] + fn the_admission_policy_comes_from_configure() { + let gateway = GatewayContext { + gateway_port: Some(1), + ..Default::default() + }; + let policy = openshell_core::resource_admission::DriverAdmissionConfig { + allow_driver_config: true, + ..Default::default() + }; + let built = driver_config( + settings_from_table("").unwrap(), + &gateway, + None, + openshell_core::sandbox_env::SupervisorOtlp::default(), + policy, + "info", + (false, 8192, 4), + ) + .unwrap(); + assert!(built.allow_driver_config); + assert!(!config("", &gateway, None).unwrap().allow_driver_config); + } + + #[test] + fn an_https_endpoint_needs_the_gateway_ca() { + let gateway = GatewayContext { + gateway_port: Some(8080), + ..Default::default() + }; + let status = config("grpc_endpoint = \"https://host.test:9\"", &gateway, None).unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } + + #[test] + fn a_missing_endpoint_and_port_is_invalid() { + let status = config("", &GatewayContext::default(), None).unwrap_err(); + assert_eq!(status.code(), tonic::Code::InvalidArgument); + } + + #[test] + fn network_trust_reaches_the_driver_config() { + let gateway = GatewayContext { + gateway_port: Some(1), + ..Default::default() + }; + let trust = NetworkTrust { + artifact_path: "/var/lib/ca.crt".to_string(), + digest: "sha256:abc".to_string(), + certificate_count: 2, + }; + let built = config("", &gateway, Some(&trust)).unwrap(); + assert_eq!(built.additional_ca_bundle, Some("/var/lib/ca.crt".into())); + assert_eq!(built.additional_ca_digest.as_deref(), Some("sha256:abc")); + assert_eq!(built.additional_ca_certificate_count, Some(2)); + assert!( + config("", &gateway, None) + .unwrap() + .additional_ca_bundle + .is_none() + ); + } +} diff --git a/crates/openshell-driver-vm/src/settings.rs b/crates/openshell-driver-vm/src/settings.rs new file mode 100644 index 0000000000..57122f3ded --- /dev/null +++ b/crates/openshell-driver-vm/src/settings.rs @@ -0,0 +1,494 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The operator's `[openshell.drivers.vm]` table. +//! +//! [`settings_from_table`] is the only place the table is parsed and +//! validated. `serve` and `preflight` both call it, so they agree on whether a +//! table is valid. It has no side effects and needs neither the gateway +//! context nor the backend. + +use std::path::PathBuf; + +use openshell_core::UpstreamProxyConfig; + +/// Why a driver table was rejected. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConfigError(pub String); + +impl std::fmt::Display for ConfigError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl std::error::Error for ConfigError {} + +/// Operator-written settings for the VM driver. +/// +/// `driver_dir` is gateway-owned: the gateway reads and removes it before it +/// forwards the table, so it is not accepted here. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(default, deny_unknown_fields)] +#[allow(clippy::struct_excessive_bools)] +pub struct VmSettings { + /// Working directory for VM driver sandbox state. + pub state_dir: PathBuf, + /// Default sandbox image the driver should use when a request omits one. + pub default_image: String, + /// Optional override of the gateway gRPC endpoint the sandbox guest + /// connects back to, for custom network or NAT setups. Unset, it defaults + /// from the gateway context. The gateway supplies the gateway port and CA. + pub grpc_endpoint: String, + /// Bootstrap image used to boot and prepare VM sandbox target images. + pub bootstrap_image: String, + /// libkrun log level used by the VM driver helper. + pub krun_log_level: u32, + /// Default vCPU count for VM sandboxes. + pub vcpus: u8, + /// Default memory allocation for VM sandboxes, in MiB. + pub mem_mib: u32, + /// Writable overlay disk size for each VM sandbox, in MiB. + pub overlay_disk_mib: u64, + /// Optional UID override for the VM guest sandbox account. + pub sandbox_uid: Option, + /// Optional GID override for the VM guest sandbox account. + pub sandbox_gid: Option, + /// Directory shared with the gateway for request-scoped rootfs tar staging. + pub rootfs_tar_staging_dir: Option, + /// Maximum accepted rootfs tar size, in bytes, before and after decompression. + pub rootfs_tar_max_bytes: Option, + /// Corporate forward-proxy settings. Flattening preserves the shared + /// local-driver TOML field names. + #[serde(flatten)] + pub upstream_proxy: UpstreamProxyConfig, + /// PEM CA bundle trusted for the corporate proxy and for server + /// certificates re-signed by a TLS-intercepting proxy. + pub proxy_ca_bundle: Option, + /// Policy DNS IPv6 egress mode and NAT64 prefixes for the host-side + /// supervisors. + #[serde(flatten)] + pub ipv6_egress: openshell_core::SupervisorIpv6EgressConfig, + /// Explicit guest-reachable SPIFFE Workload API TCP listener. VM guests + /// cannot receive a host UNIX socket, so this requires acknowledgement. + pub provider_spiffe_workload_api_tcp_endpoint: Option, + pub provider_spiffe_allow_guest_tcp: bool, + /// Allow bind-mounting host directories into VM sandboxes. + pub enable_bind_mounts: bool, +} + +impl VmSettings { + /// Default working directory for VM driver state. + #[must_use] + pub fn default_state_dir() -> PathBuf { + openshell_core::paths::openshell_state_dir().map_or_else( + |_| PathBuf::from("target/openshell-vm-driver"), + |dir| dir.join("vm-driver"), + ) + } + + /// Checks that need neither the gateway context nor the backend. + fn validate(&self) -> Result<(), ConfigError> { + self.ipv6_egress.validate().map_err(ConfigError)?; + if !self.grpc_endpoint.trim().is_empty() { + openshell_driver_sdk::validate_grpc_endpoint(&self.grpc_endpoint) + .map_err(ConfigError)?; + } + if self.bootstrap_image.trim().is_empty() && self.default_image.trim().is_empty() { + return Err(ConfigError( + "bootstrap_image or default_image is required when using the vm compute driver; sandbox images cannot be used as VM bootstrap images".to_string(), + )); + } + let range = openshell_policy::MIN_SANDBOX_UID..=openshell_policy::MAX_SANDBOX_UID; + for (field, value) in [ + ("sandbox_uid", self.sandbox_uid), + ("sandbox_gid", self.sandbox_gid), + ] { + if let Some(value) = value + && !range.contains(&value) + { + return Err(ConfigError(format!( + "{field} {value} is outside the allowed range [{}, {}]", + openshell_policy::MIN_SANDBOX_UID, + openshell_policy::MAX_SANDBOX_UID + ))); + } + } + if self + .rootfs_tar_staging_dir + .as_ref() + .is_some_and(|path| path.as_os_str().is_empty()) + { + return Err(ConfigError( + "rootfs_tar_staging_dir must not be empty when set".to_string(), + )); + } + if self.rootfs_tar_max_bytes == Some(0) { + return Err(ConfigError( + "rootfs_tar_max_bytes must be greater than zero when set".to_string(), + )); + } + self.upstream_proxy.validate().map_err(ConfigError)?; + if let Some(path) = self.proxy_ca_bundle.as_ref() { + if path.as_os_str().is_empty() { + return Err(ConfigError( + "proxy_ca_bundle must not be empty when set".to_string(), + )); + } + if self.upstream_proxy.https_proxy.is_none() { + return Err(ConfigError( + "proxy_ca_bundle is set but no https_proxy is configured".to_string(), + )); + } + } + if let Some(endpoint) = self.provider_spiffe_workload_api_tcp_endpoint.as_deref() { + openshell_core::driver_utils::validate_guest_spiffe_tcp_endpoint( + endpoint, + self.provider_spiffe_allow_guest_tcp, + ) + .map_err(ConfigError)?; + } else if self.provider_spiffe_allow_guest_tcp { + return Err(ConfigError( + "provider_spiffe_allow_guest_tcp is set but no provider_spiffe_workload_api_tcp_endpoint is configured".to_string(), + )); + } + Ok(()) + } +} + +impl Default for VmSettings { + fn default() -> Self { + Self { + state_dir: Self::default_state_dir(), + default_image: openshell_core::image::default_sandbox_image(), + grpc_endpoint: String::new(), + bootstrap_image: String::new(), + krun_log_level: 1, + vcpus: 2, + mem_mib: 2048, + overlay_disk_mib: 4096, + sandbox_uid: None, + sandbox_gid: None, + rootfs_tar_staging_dir: None, + rootfs_tar_max_bytes: None, + upstream_proxy: UpstreamProxyConfig::default(), + proxy_ca_bundle: None, + ipv6_egress: openshell_core::SupervisorIpv6EgressConfig::default(), + provider_spiffe_workload_api_tcp_endpoint: None, + provider_spiffe_allow_guest_tcp: false, + enable_bind_mounts: false, + } + } +} + +/// Parse and validate the driver table. An empty table is valid and selects +/// the defaults. +pub fn settings_from_table(table: &str) -> Result { + settings_with_environment(table, &|_| None) +} + +/// [`settings_from_table`] with the standalone driver's environment fallbacks. +/// +/// The gateway used to pass only the settings an operator wrote, so a setting +/// left out of the table fell back to the driver's own environment variable. +/// Existing installs rely on that, so a setting the table leaves unset still +/// reads its variable. The table wins when both are set. +pub fn settings_with_environment( + table: &str, + env: &dyn Fn(&str) -> Option, +) -> Result { + let mut settings: VmSettings = toml::from_str(table) + .map_err(|error| ConfigError(format!("invalid vm driver table: {error}")))?; + settings.apply_environment(env)?; + if settings.state_dir.as_os_str().is_empty() { + settings.state_dir = VmSettings::default_state_dir(); + } + settings.validate()?; + Ok(settings) +} + +impl VmSettings { + /// Fill settings the table left unset from their environment variables. + fn apply_environment( + &mut self, + env: &dyn Fn(&str) -> Option, + ) -> Result<(), ConfigError> { + fn parse(name: &str, value: &str) -> Result + where + T::Err: std::fmt::Display, + { + value + .trim() + .parse() + .map_err(|error| ConfigError(format!("invalid {name}={value:?}: {error}"))) + } + let get = |name: &str| env(name).filter(|value| !value.trim().is_empty()); + + if self.bootstrap_image.trim().is_empty() + && let Some(value) = get("OPENSHELL_VM_BOOTSTRAP_IMAGE") + { + self.bootstrap_image = value; + } + if self.sandbox_uid.is_none() + && let Some(value) = get("OPENSHELL_VM_SANDBOX_UID") + { + self.sandbox_uid = Some(parse("OPENSHELL_VM_SANDBOX_UID", &value)?); + } + if self.sandbox_gid.is_none() + && let Some(value) = get("OPENSHELL_VM_SANDBOX_GID") + { + self.sandbox_gid = Some(parse("OPENSHELL_VM_SANDBOX_GID", &value)?); + } + if self.rootfs_tar_staging_dir.is_none() + && let Some(value) = get("OPENSHELL_VM_ROOTFS_TAR_STAGING_DIR") + { + self.rootfs_tar_staging_dir = Some(value.into()); + } + if self.rootfs_tar_max_bytes.is_none() + && let Some(value) = get("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES") + { + self.rootfs_tar_max_bytes = Some(parse("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES", &value)?); + } + + let proxy = &mut self.upstream_proxy; + if proxy.https_proxy.is_none() { + proxy.https_proxy = get("OPENSHELL_VM_UPSTREAM_PROXY"); + } + if proxy.no_proxy.is_none() { + proxy.no_proxy = get("OPENSHELL_VM_UPSTREAM_NO_PROXY"); + } + if proxy.proxy_auth_file.is_none() { + proxy.proxy_auth_file = get("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_FILE").map(Into::into); + } + if proxy.proxy_auth_allow_insecure.is_none() + && let Some(value) = get("OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE") + { + proxy.proxy_auth_allow_insecure = Some(parse( + "OPENSHELL_VM_UPSTREAM_PROXY_AUTH_ALLOW_INSECURE", + &value, + )?); + } + if proxy.proxy_connect_by_hostname.is_none() + && let Some(value) = get("OPENSHELL_VM_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME") + { + proxy.proxy_connect_by_hostname = Some(parse( + "OPENSHELL_VM_UPSTREAM_PROXY_CONNECT_BY_HOSTNAME", + &value, + )?); + } + if self.proxy_ca_bundle.is_none() { + self.proxy_ca_bundle = get("OPENSHELL_VM_UPSTREAM_PROXY_CA_BUNDLE").map(Into::into); + } + + if self.provider_spiffe_workload_api_tcp_endpoint.is_none() { + self.provider_spiffe_workload_api_tcp_endpoint = + get("OPENSHELL_PROVIDER_SPIFFE_WORKLOAD_API_TCP_ENDPOINT"); + } + if !self.provider_spiffe_allow_guest_tcp + && let Some(value) = get("OPENSHELL_PROVIDER_SPIFFE_ALLOW_GUEST_TCP") + { + self.provider_spiffe_allow_guest_tcp = + parse("OPENSHELL_PROVIDER_SPIFFE_ALLOW_GUEST_TCP", &value)?; + } + if !self.enable_bind_mounts + && let Some(value) = get("OPENSHELL_VM_ENABLE_BIND_MOUNTS") + { + self.enable_bind_mounts = parse("OPENSHELL_VM_ENABLE_BIND_MOUNTS", &value)?; + } + + if self.ipv6_egress.policy_dns_ipv6_egress.is_none() + && let Some(value) = get("OPENSHELL_VM_POLICY_DNS_IPV6_EGRESS") + { + self.ipv6_egress.policy_dns_ipv6_egress = + Some(value.trim().parse().map_err(|error| { + ConfigError(format!("OPENSHELL_VM_POLICY_DNS_IPV6_EGRESS: {error}")) + })?); + } + if self.ipv6_egress.nat64_prefixes.is_empty() + && let Some(value) = get("OPENSHELL_VM_NAT64_PREFIXES") + { + self.ipv6_egress.nat64_prefixes = value + .split(',') + .map(|prefix| prefix.trim().to_string()) + .filter(|prefix| !prefix.is_empty()) + .collect(); + } + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn an_empty_table_selects_the_defaults() { + let settings = settings_from_table("").unwrap(); + assert_eq!(settings.vcpus, 2); + assert_eq!(settings.mem_mib, 2048); + assert!(settings.grpc_endpoint.is_empty()); + } + + #[test] + fn existing_operator_keys_are_accepted() { + let settings = settings_from_table( + r#" + state_dir = "/var/lib/openshell/vm" + default_image = "example.test/sandbox:1" + bootstrap_image = "example.test/bootstrap:1" + grpc_endpoint = "https://gateway.test:8080" + krun_log_level = 3 + vcpus = 4 + mem_mib = 4096 + overlay_disk_mib = 8192 + sandbox_uid = 10001 + sandbox_gid = 10001 + https_proxy = "http://proxy.test:3128" + proxy_ca_bundle = "/etc/openshell/proxy-ca.pem" + enable_bind_mounts = true + "#, + ) + .unwrap(); + assert_eq!(settings.vcpus, 4); + assert_eq!(settings.sandbox_uid, Some(10001)); + assert_eq!( + settings.upstream_proxy.https_proxy.as_deref(), + Some("http://proxy.test:3128") + ); + } + + #[test] + fn ipv6_egress_settings_are_accepted_and_validated() { + let settings = settings_from_table( + "policy_dns_ipv6_egress = \"disabled\"\nnat64_prefixes = [\"2001:db8:64::/96\"]", + ) + .unwrap(); + assert_eq!(settings.ipv6_egress.nat64_prefixes, ["2001:db8:64::/96"]); + assert!(settings_from_table("nat64_prefixes = [\"not-a-prefix\"]").is_err()); + } + + fn env<'a>(pairs: &'a [(&'a str, &'a str)]) -> impl Fn(&str) -> Option + 'a { + move |name| { + pairs + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| (*value).to_string()) + } + } + + #[test] + fn unset_settings_fall_back_to_the_environment() { + let settings = settings_with_environment( + "bootstrap_image = \"\"", + &env(&[ + ("OPENSHELL_VM_UPSTREAM_PROXY", "http://proxy.test:3128"), + ("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES", "1048576"), + ("OPENSHELL_VM_ENABLE_BIND_MOUNTS", "true"), + ("OPENSHELL_VM_BOOTSTRAP_IMAGE", "example.test/bootstrap:1"), + ( + "OPENSHELL_VM_NAT64_PREFIXES", + "2001:db8:64::/96, 64:ff9b::/96", + ), + ]), + ) + .unwrap(); + assert_eq!( + settings.upstream_proxy.https_proxy.as_deref(), + Some("http://proxy.test:3128") + ); + assert_eq!(settings.rootfs_tar_max_bytes, Some(1_048_576)); + assert!(settings.enable_bind_mounts); + assert_eq!(settings.bootstrap_image, "example.test/bootstrap:1"); + assert_eq!( + settings.ipv6_egress.nat64_prefixes, + ["2001:db8:64::/96", "64:ff9b::/96"] + ); + } + + #[test] + fn the_table_wins_over_the_environment() { + let settings = settings_with_environment( + "https_proxy = \"http://table.test:1\"", + &env(&[("OPENSHELL_VM_UPSTREAM_PROXY", "http://env.test:2")]), + ) + .unwrap(); + assert_eq!( + settings.upstream_proxy.https_proxy.as_deref(), + Some("http://table.test:1") + ); + } + + #[test] + fn a_malformed_environment_value_is_invalid_config() { + let error = + settings_with_environment("", &env(&[("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES", "lots")])) + .unwrap_err(); + assert!( + error.0.contains("OPENSHELL_VM_ROOTFS_TAR_MAX_BYTES"), + "{error}" + ); + } + + #[test] + fn unknown_keys_are_rejected() { + let error = settings_from_table("vcpu = 4").unwrap_err(); + assert!(error.0.contains("vcpu"), "{error}"); + } + + #[test] + fn gateway_supplied_values_are_not_driver_keys() { + for key in [ + "guest_tls_ca = \"/ca.pem\"", + "gateway_port = 8080", + "allow_driver_config = true", + "resource_admission = {}", + ] { + assert!(settings_from_table(key).is_err(), "accepted: {key}"); + } + } + + #[test] + fn grpc_endpoint_is_checked_for_syntax_and_scheme() { + settings_from_table("grpc_endpoint = \"https://gw.test:8443\"").unwrap(); + for bad in ["ftp://gw.test:1", "gw.test:8080", "http://"] { + assert!( + settings_from_table(&format!("grpc_endpoint = \"{bad}\"")).is_err(), + "accepted: {bad}" + ); + } + } + + #[test] + fn the_gateway_owned_driver_dir_is_not_a_driver_key() { + assert!(settings_from_table(r#"driver_dir = "/opt/drivers""#).is_err()); + } + + #[test] + fn invalid_values_are_rejected() { + for table in [ + "sandbox_uid = 0", + "rootfs_tar_max_bytes = 0", + "rootfs_tar_staging_dir = \"\"", + "proxy_ca_bundle = \"/ca.pem\"", + "provider_spiffe_allow_guest_tcp = true", + "default_image = \"\"\nbootstrap_image = \"\"", + ] { + assert!(settings_from_table(table).is_err(), "accepted: {table}"); + } + } + + #[test] + fn a_proxy_exclusion_without_a_proxy_names_the_keys() { + let error = settings_from_table("no_proxy = \"10.0.0.0/8\"").unwrap_err(); + assert!(error.0.contains("no_proxy"), "{error}"); + assert!(error.0.contains("https_proxy"), "{error}"); + } + + #[test] + fn an_empty_state_dir_selects_the_default() { + assert_eq!( + settings_from_table("state_dir = \"\"").unwrap().state_dir, + VmSettings::default_state_dir() + ); + } +} diff --git a/crates/openshell-driver-vm/tests/serve_configure.rs b/crates/openshell-driver-vm/tests/serve_configure.rs new file mode 100644 index 0000000000..ffe27b1537 --- /dev/null +++ b/crates/openshell-driver-vm/tests/serve_configure.rs @@ -0,0 +1,226 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Runs the real `openshell-driver-vm` binary through `serve` and `preflight`. + +#![cfg(unix)] + +use std::io::Write as _; +use std::path::Path; +use std::process::{Child, Command, Output, Stdio}; +use std::time::{Duration, Instant}; + +use hyper_util::rt::TokioIo; +use openshell_core::proto::compute::v1::GetCapabilitiesRequest; +use openshell_core::proto::compute::v1::compute_driver_client::ComputeDriverClient; +use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; +use openshell_driver_sdk::launch::{ConfigureRequest, GetLaunchInfoRequest, PROTOCOL_VERSION}; +use tonic::Code; +use tonic::transport::{Channel, Endpoint}; + +const BIN: &str = env!("CARGO_BIN_EXE_openshell-driver-vm"); + +fn driver(args: &[&str], table: &str) -> Command { + let mut command = Command::new(BIN); + command + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()); + let _ = table; + command +} + +fn run_with_table(args: &[&str], table: &str) -> Output { + let mut child = driver(args, table).spawn().unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(table.as_bytes()) + .unwrap(); + child.wait_with_output().unwrap() +} + +struct Serving { + child: Child, + channel: Channel, + _dir: tempfile::TempDir, +} + +impl Drop for Serving { + fn drop(&mut self) { + let _ = self.child.kill(); + let _ = self.child.wait(); + } +} + +async fn connect(path: &Path) -> Option { + let path = path.to_path_buf(); + Endpoint::try_from("http://localhost") + .unwrap() + .connect_with_connector(tower::service_fn(move |_| { + let path = path.clone(); + async move { + Ok::<_, std::io::Error>(TokioIo::new(tokio::net::UnixStream::connect(path).await?)) + } + })) + .await + .ok() +} + +async fn serve(table: &str) -> Serving { + let dir = tempfile::tempdir().unwrap(); + let socket = dir.path().join("run").join("driver.sock"); + let table = table.replace("@STATE@", &dir.path().join("state").display().to_string()); + let pid = std::process::id().to_string(); + let mut child = driver( + &[ + "serve", + "--bind-socket", + socket.to_str().unwrap(), + "--expected-peer-pid", + &pid, + ], + &table, + ) + .spawn() + .unwrap(); + child + .stdin + .take() + .unwrap() + .write_all(table.as_bytes()) + .unwrap(); + let deadline = Instant::now() + Duration::from_mins(1); + loop { + if let Some(status) = child.try_wait().unwrap() { + panic!("driver exited early: {status}"); + } + if let Some(channel) = connect(&socket).await { + return Serving { + child, + channel, + _dir: dir, + }; + } + assert!( + Instant::now() < deadline, + "driver never accepted a connection" + ); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +const TABLE: &str = "state_dir = \"@STATE@\"\ndefault_image = \"example.test/sandbox:1\"\n"; + +fn configure(version: u32, port: u32) -> ConfigureRequest { + ConfigureRequest { + protocol_version: version, + gateway: Some(openshell_driver_sdk::launch::GatewayContext { + gateway_port: port, + ..Default::default() + }), + ..Default::default() + } +} + +#[tokio::test] +async fn launch_info_answers_and_compute_calls_wait_for_configure() { + let serving = serve(TABLE).await; + + let info = DriverLaunchClient::new(serving.channel.clone()) + .get_launch_info(GetLaunchInfoRequest {}) + .await + .unwrap() + .into_inner(); + assert_eq!(info.driver_name, "vm"); + assert_eq!(info.protocol_versions, [PROTOCOL_VERSION]); + + let status = ComputeDriverClient::new(serving.channel.clone()) + .get_capabilities(GetCapabilitiesRequest::default()) + .await + .unwrap_err(); + assert_eq!(status.code(), Code::Unavailable); +} + +#[tokio::test] +async fn a_failed_configure_leaves_the_driver_running_for_a_retry() { + let mut serving = serve(TABLE).await; + let mut client = DriverLaunchClient::new(serving.channel.clone()); + + let unsupported = client + .configure(configure(PROTOCOL_VERSION + 1, 8080)) + .await + .unwrap_err(); + assert_eq!(unsupported.code(), Code::FailedPrecondition); + + // No gateway port and no `grpc_endpoint` in the table. + let incomplete = client + .configure(configure(PROTOCOL_VERSION, 0)) + .await + .unwrap_err(); + assert_eq!(incomplete.code(), Code::InvalidArgument); + assert!(serving.child.try_wait().unwrap().is_none()); + + client + .configure(configure(PROTOCOL_VERSION, 8080)) + .await + .unwrap(); + // The driver now answers; it rejects this bare request only because the + // extension handshake metadata is missing. + let answered = ComputeDriverClient::new(serving.channel.clone()) + .get_capabilities(GetCapabilitiesRequest::default()) + .await; + assert_ne!( + answered.err().map(|status| status.code()), + Some(Code::Unavailable) + ); + let again = client + .configure(configure(PROTOCOL_VERSION, 8080)) + .await + .unwrap_err(); + assert_eq!(again.code(), Code::FailedPrecondition); +} + +#[test] +fn an_invalid_table_exits_with_the_config_code_and_one_json_line() { + let output = run_with_table( + &[ + "serve", + "--bind-socket", + "/nonexistent/driver.sock", + "--expected-peer-pid", + "1", + ], + "vcpu = 4", + ); + assert_eq!(output.status.code(), Some(78)); + let stdout = String::from_utf8_lossy(&output.stdout); + let report = openshell_driver_sdk::StartReport::from_output(&stdout) + .unwrap_or_else(|| panic!("no report line in: {stdout}")); + assert_eq!(report.kind, openshell_driver_sdk::StartKind::InvalidConfig); + assert!(report.reason.contains("vcpu"), "{}", report.reason); +} + +#[test] +fn preflight_accepts_a_valid_table_and_creates_no_state() { + let dir = tempfile::tempdir().unwrap(); + let state = dir.path().join("state"); + let table = format!("state_dir = \"{}\"\nvcpus = 4\n", state.display()); + + let output = run_with_table(&["preflight"], &table); + assert_eq!(output.status.code(), Some(0), "{:?}", output.stdout); + assert!(!state.exists(), "preflight must not create state"); + assert_eq!(run_with_table(&["preflight"], "").status.code(), Some(0)); +} + +#[test] +fn preflight_rejects_an_unknown_key() { + let output = run_with_table(&["preflight"], "vcpu = 4"); + assert_eq!(output.status.code(), Some(78)); + assert!( + openshell_driver_sdk::StartReport::from_output(&String::from_utf8_lossy(&output.stdout)) + .is_some() + ); +} diff --git a/crates/openshell-gateway/Cargo.toml b/crates/openshell-gateway/Cargo.toml index 0141e39978..f948d4dafc 100644 --- a/crates/openshell-gateway/Cargo.toml +++ b/crates/openshell-gateway/Cargo.toml @@ -24,13 +24,12 @@ 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 } -openshell-policy = { path = "../openshell-policy", optional = true } +openshell-driver-launch = { path = "../openshell-driver-launch", optional = true } +openshell-driver-sdk = { path = "../openshell-driver-sdk", optional = true } hyper-util = { workspace = true, optional = true } -nix = { workspace = true, optional = true } -serde = { workspace = true, optional = true } +toml = { workspace = true, optional = true } +tempfile = { version = "3", optional = true } rustix = { workspace = true, optional = true } tonic = { workspace = true, optional = true } tower = { workspace = true, optional = true } @@ -51,19 +50,22 @@ in-tree-compute-drivers = [ "compute-driver-mxc", ] compute-driver-mxc = ["dep:openshell-driver-mxc"] -compute-driver-docker = ["dep:openshell-driver-docker", "dep:openshell-otel"] +compute-driver-docker = ["driver-launcher"] compute-driver-kubernetes = ["dep:openshell-driver-kubernetes", "dep:openshell-otel"] -compute-driver-podman = ["dep:openshell-driver-podman", "dep:openshell-otel"] -compute-driver-vm = [ - "dep:openshell-policy", +compute-driver-podman = ["driver-launcher"] +compute-driver-vm = ["driver-launcher"] +## Launch a compute driver as a subprocess with `serve` and `Configure`. +driver-launcher = [ + "dep:openshell-driver-launch", + "dep:openshell-driver-sdk", "dep:openshell-otel", "dep:hyper-util", - "dep:nix", - "dep:serde", "dep:rustix", "dep:tonic", "dep:tower", "dep:tracing", + "dep:toml", + "dep:tempfile", ] telemetry = ["openshell-core/telemetry", "openshell-server/telemetry"] ## Convenience alias: every default feature except `telemetry`. Build a @@ -82,6 +84,9 @@ workspace = true [dev-dependencies] openshell-crypto = { workspace = true, default-features = false, features = ["aws-lc"] } +nix = { workspace = true } rcgen = { workspace = true } tempfile = "3" +openshell-otel-test-support = { path = "../openshell-otel-test-support" } toml = { workspace = true } +tokio-stream = { workspace = true, features = ["net"] } diff --git a/crates/openshell-gateway/src/docker.rs b/crates/openshell-gateway/src/docker.rs new file mode 100644 index 0000000000..43a023f6c6 --- /dev/null +++ b/crates/openshell-gateway/src/docker.rs @@ -0,0 +1,29 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The Docker compute driver, launched as a subprocess. +//! +//! The `openshell-driver-docker` subprocess owns its +//! `[openshell.drivers.docker]` table. The gateway reads only the keys it +//! owns and forwards the rest as TOML text on stdin; see +//! [`crate::local_driver`]. + +use openshell_server::{DriverDetection, DriverDetectionContext}; + +use crate::local_driver::LocalDriver; + +pub const DOCKER: LocalDriver = LocalDriver { + name: "docker", + drop_legacy_keys: |_| {}, + // The in-process driver did not retry an unreachable daemon. + retry_unavailable: None, +}; + +/// Detect Docker by starting its driver with the operator's table, so a +/// configured `socket_path` is honoured. +pub fn detect(context: &DriverDetectionContext<'_>) -> DriverDetection { + DOCKER.detect(context, &LocalDriver::socket_dir()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-gateway/src/docker/tests.rs b/crates/openshell-gateway/src/docker/tests.rs new file mode 100644 index 0000000000..edca3c64d1 --- /dev/null +++ b/crates/openshell-gateway/src/docker/tests.rs @@ -0,0 +1,178 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::io::Write as _; +use std::os::unix::fs::OpenOptionsExt as _; + +use std::path::{Path, PathBuf}; + +use super::*; + +fn table(text: &str) -> toml::map::Map { + toml::from_str(text).unwrap() +} + +/// Write an executable script by writing and closing a temporary file, then +/// renaming it into place, so it is never executed while open for writing. +fn driver(dir: &Path, body: &str) { + let temporary = dir.join("driver.tmp"); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o755) + .open(&temporary) + .unwrap(); + file.write_all(format!("#!/bin/sh\n{body}\n").as_bytes()) + .unwrap(); + file.sync_all().unwrap(); + drop(file); + std::fs::rename(temporary, dir.join("openshell-driver-docker")).unwrap(); +} + +fn detect_with(body: &str, extra: &str) -> DriverDetection { + let dir = tempfile::tempdir().unwrap(); + driver(dir.path(), body); + let table = table(extra); + DOCKER.detect( + &DriverDetectionContext { + table: &table, + driver_dir: Some(dir.path()), + gateway_log_level: "info", + }, + &dir.path().join("run"), + ) +} + +#[test] +fn gateway_owned_keys_are_removed_and_the_rest_is_forwarded() { + let plan = DOCKER.plan( + table( + "driver_dir = \"/opt/drivers\"\nsocket_path = \"/run/docker.sock\"\nsandbox_label = \"n\"", + ), + None, + ) + .unwrap(); + + assert_eq!(plan.driver_dir, Some(PathBuf::from("/opt/drivers"))); + let forwarded = table(&plan.table); + assert!(!forwarded.contains_key("driver_dir")); + assert_eq!(forwarded["socket_path"].as_str(), Some("/run/docker.sock")); + assert_eq!(forwarded["sandbox_label"].as_str(), Some("n")); + assert!(DOCKER.plan(table("driver_dir = 3"), None).is_err()); +} + +#[test] +fn detection_runs_the_driver_with_the_operators_table() { + // The fake exits "unavailable" and says which table it received. + let body = "grep -q 'socket_path = \"/var/run/docker.sock\"' || { \ + printf '{\"result\":\"unavailable\",\"reason\":\"wrong table\"}\\n'; exit 69; }\n\ + printf '{\"result\":\"unavailable\",\"reason\":\"right table\"}\\n'; exit 69"; + assert!(matches!( + detect_with(body, "socket_path = \"/var/run/docker.sock\""), + DriverDetection::Unavailable(reason) if reason == "right table" + )); + assert!(matches!( + detect_with(body, ""), + DriverDetection::Unavailable(reason) if reason == "wrong table" + )); +} + +#[test] +fn detection_reports_an_invalid_table_so_the_next_candidate_can_be_tried() { + let body = "printf '{\"result\":\"invalid_config\",\"reason\":\"unknown key\"}\\n'\nexit 78"; + assert!(matches!( + detect_with(body, ""), + DriverDetection::InvalidConfig(reason) if reason == "unknown key" + )); +} + +#[test] +fn detection_keeps_the_driver_it_started_and_stops_it_if_unused() { + // The fake binds the socket named on its command line, as `serve` does. + if !Path::new("/usr/bin/python3").exists() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + let pid_file = dir.path().join("pid"); + driver( + &bin, + &format!( + "echo $$ > '{}'\nexec /usr/bin/python3 -c \"import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); s.listen(); import time; time.sleep(30)\" \"$3\"", + pid_file.display() + ), + ); + let table = table(""); + let context = DriverDetectionContext { + table: &table, + driver_dir: Some(&bin), + gateway_log_level: "info", + }; + + let result = DOCKER.detect(&context, &dir.path().join("run")); + + let DriverDetection::Available(Some(detected)) = result else { + panic!("a driver that binds its socket is available and kept"); + }; + let pid = std::fs::read_to_string(&pid_file).unwrap(); + let alive = || { + std::process::Command::new("kill") + .args(["-0", pid.trim()]) + .stderr(std::process::Stdio::null()) + .status() + .unwrap() + .success() + }; + assert!( + alive(), + "the detected driver keeps running until it is built" + ); + + // Dropping it without building stops it. + drop(detected); + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!alive(), "an unused detected driver must be stopped"); +} + +#[test] +fn a_missing_driver_binary_is_unavailable() { + let dir = tempfile::tempdir().unwrap(); + let table = table(""); + let result = DOCKER.detect( + &DriverDetectionContext { + table: &table, + driver_dir: Some(dir.path()), + gateway_log_level: "info", + }, + &dir.path().join("run"), + ); + assert!(matches!(result, DriverDetection::Unavailable(reason) if reason.contains("not found"))); +} + +#[test] +fn the_admission_policy_is_not_forwarded_in_the_driver_table() { + let plan = DOCKER.plan( + table("allow_driver_config = true\n[resource_admission]\nenabled = false\nrequired_labels = {}\n"), + None, + ) + .unwrap(); + assert!( + !plan.table.contains("allow_driver_config"), + "{}", + plan.table + ); + assert!(!plan.table.contains("resource_admission"), "{}", plan.table); +} + +#[test] +fn a_launch_error_stops_detection_instead_of_looking_like_an_absent_backend() { + let dir = tempfile::tempdir().unwrap(); + // Exit status 1 is an internal failure, whatever the driver claims. + let result = detect_with( + "printf '{\"result\":\"unavailable\",\"reason\":\"claims absent\"}\\n'\nexit 1", + "", + ); + drop(dir); + assert!(matches!(result, DriverDetection::Failed(reason) if reason.contains("claims absent"))); +} diff --git a/crates/openshell-gateway/src/launcher.rs b/crates/openshell-gateway/src/launcher.rs new file mode 100644 index 0000000000..e798d830e2 --- /dev/null +++ b/crates/openshell-gateway/src/launcher.rs @@ -0,0 +1,749 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Launch a compute driver as a subprocess. +//! +//! The gateway starts ` serve` with bootstrap arguments only and the +//! operator's driver table on stdin. When the driver accepts a connection, the +//! gateway reads `GetLaunchInfo` and sends gateway-owned metadata in +//! `Configure`. The table itself is never parsed here beyond removing the +//! gateway-owned keys the caller already took out. + +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use hyper_util::rt::TokioIo; +use openshell_core::{Error, Result}; +use openshell_driver_sdk::launch::proto::driver_launch_client::DriverLaunchClient; +use openshell_driver_sdk::launch::{ConfigureRequest, GetLaunchInfoRequest, PROTOCOL_VERSION}; +use openshell_driver_sdk::{StartKind, StartReport}; +use openshell_server::{DriverProcessState, ManagedDriverProcess}; +use tokio::net::UnixStream; +use tonic::transport::{Channel, Endpoint}; +use tower::service_fn; + +const SOCKET_NAME: &str = "driver.sock"; +/// How long a driver has to accept a connection after it starts. +const START_TIMEOUT: Duration = Duration::from_secs(30); +const CONFIGURE_TIMEOUT: Duration = Duration::from_mins(2); +const PREFLIGHT_TIMEOUT: Duration = Duration::from_secs(20); +const POLL_INTERVAL: Duration = Duration::from_millis(50); +const EXIT_WATCH_INTERVAL: Duration = Duration::from_secs(1); + +pub fn default_driver_search_dirs(home: Option) -> Vec { + let mut dirs = Vec::new(); + if let Some(home) = home { + dirs.push(home.join(".local").join("libexec").join("openshell")); + } + for dir in [ + "/usr/libexec/openshell", + "/usr/local/libexec/openshell", + "/usr/local/libexec", + ] { + push_unique_path(&mut dirs, PathBuf::from(dir)); + } + dirs +} + +pub fn driver_search_dirs(driver_dir: Option<&Path>) -> Vec { + driver_dir.map_or_else( + || { + let mut dirs = Vec::new(); + if let Ok(current_exe) = std::env::current_exe() + && let Some(prefix) = current_exe.parent().and_then(Path::parent) + { + push_unique_path(&mut dirs, prefix.join("libexec")); + push_unique_path(&mut dirs, prefix.join("libexec").join("openshell")); + } + for dir in default_driver_search_dirs(std::env::var_os("HOME").map(PathBuf::from)) { + push_unique_path(&mut dirs, dir); + } + dirs + }, + |dir| vec![dir.to_path_buf()], + ) +} + +fn push_unique_path(paths: &mut Vec, path: PathBuf) { + if !paths.iter().any(|existing| existing == &path) { + paths.push(path); + } +} + +/// Search `dirs` for `bin_name`, then next to the gateway executable, and +/// require the result to be trusted. +pub fn resolve_binary(bin_name: &str, dirs: &[PathBuf], hint: &str) -> Result { + let mut searched = Vec::new(); + let sibling = std::env::current_exe() + .ok() + .and_then(|exe| exe.parent().map(|parent| parent.join(bin_name))); + for candidate in dirs.iter().map(|dir| dir.join(bin_name)).chain(sibling) { + if candidate.is_file() { + check_binary_trust(&candidate)?; + return Ok(candidate); + } + if !searched.contains(&candidate) { + searched.push(candidate); + } + } + let searched = searched + .iter() + .map(|path| format!("'{}'", path.display())) + .collect::>() + .join(", "); + Err(Error::config(format!( + "compute driver binary {bin_name} not found (searched {searched}); {hint}" + ))) +} + +/// Require a driver binary the gateway can run with the authority it has: owned +/// by root or by the gateway's user, and not writable by group or others. +pub fn check_binary_trust(path: &Path) -> Result<()> { + let resolved = std::fs::canonicalize(path).map_err(|error| { + Error::config(format!( + "resolve driver binary '{}': {error}", + path.display() + )) + })?; + let metadata = std::fs::metadata(&resolved).map_err(|error| { + Error::config(format!( + "stat driver binary '{}': {error}", + resolved.display() + )) + })?; + let euid = rustix::process::geteuid().as_raw(); + if metadata.uid() != 0 && metadata.uid() != euid { + return Err(Error::config(format!( + "driver binary '{}' is owned by uid {}; it must be owned by root or the gateway user (uid {euid})", + resolved.display(), + metadata.uid() + ))); + } + if metadata.permissions().mode() & 0o022 != 0 { + return Err(Error::config(format!( + "driver binary '{}' is writable by group or others; refusing to run it", + resolved.display() + ))); + } + Ok(()) +} + +/// Create a private directory for one launch's socket under `base` and return +/// the socket path in it. +/// +/// Every launch gets its own directory, so a launch only configures and +/// cleans up its own child: a second startup under the same account cannot +/// remove a running driver's socket. The directory is removed with the +/// driver's handle. +pub fn prepare_socket(base: &Path) -> Result { + let euid = rustix::process::geteuid().as_raw(); + std::fs::create_dir_all(base).map_err(|error| { + Error::execution(format!( + "failed to create compute driver socket dir '{}': {error}", + base.display() + )) + })?; + let metadata = std::fs::symlink_metadata(base).map_err(|error| { + Error::execution(format!( + "failed to stat socket dir '{}': {error}", + base.display() + )) + })?; + if metadata.file_type().is_symlink() || !metadata.file_type().is_dir() { + return Err(Error::execution(format!( + "compute driver socket dir '{}' is not a plain directory", + base.display() + ))); + } + if metadata.uid() != euid { + return Err(Error::execution(format!( + "compute driver socket dir '{}' is owned by uid {} but the gateway runs as {euid}", + base.display(), + metadata.uid() + ))); + } + std::fs::set_permissions(base, std::fs::Permissions::from_mode(0o700)).map_err(|error| { + Error::execution(format!( + "failed to restrict socket dir '{}': {error}", + base.display() + )) + })?; + let launch_dir = tempfile::Builder::new() + .prefix("") + .tempdir_in(base) + .map_err(|error| { + Error::execution(format!( + "failed to create a launch directory in '{}': {error}", + base.display() + )) + })? + .keep(); + std::fs::set_permissions(&launch_dir, std::fs::Permissions::from_mode(0o700)).map_err( + |error| { + Error::execution(format!( + "failed to restrict launch directory '{}': {error}", + launch_dir.display() + )) + }, + )?; + Ok(launch_dir.join(SOCKET_NAME)) +} + +/// The driver table as a driver's stdin. +/// +/// This is an unlinked, private temporary file, not a pipe. A pipe's end of +/// file waits for every copy of its write end to close, and on macOS a child +/// spawned by another thread can briefly inherit one. A file ends where the +/// table ends. +fn table_stdin(table: &str) -> std::io::Result { + use std::io::{Seek as _, SeekFrom, Write as _}; + + let mut file = tempfile::tempfile()?; + file.write_all(table.as_bytes())?; + file.seek(SeekFrom::Start(0))?; + Ok(Stdio::from(file)) +} + +/// The stdout of a driver, forwarded line by line, with its start report kept. +/// Stderr is the driver's own: it passes straight through to the gateway's. +#[derive(Clone, Default)] +struct StderrCapture { + report: Arc>>, +} + +impl StderrCapture { + /// Forward `stdout` until the driver closes it, keeping the start report. + fn spawn(&self, stdout: std::process::ChildStdout) -> std::thread::JoinHandle<()> { + use std::io::BufRead as _; + + let report = Arc::clone(&self.report); + std::thread::spawn(move || { + for line in std::io::BufReader::new(stdout) + .lines() + .map_while(std::result::Result::ok) + { + if let Ok(parsed) = serde_json::from_str::(line.trim()) { + *report + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(parsed); + } else { + println!("{line}"); + } + } + }) + } + + fn take(&self) -> Option { + self.report + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + } +} + +/// How a driver that exited before serving is described. +fn exit_outcome( + name: &str, + code: Option, + status: std::process::ExitStatus, + report: Option, +) -> Result { + // The exit status decides the result; the report only explains it. A + // crash or a signal is never an absent backend. + let kind = code.map_or(StartKind::Error, StartKind::from_exit_code); + let reason = report.map_or_else(|| status.to_string(), |report| report.reason); + match kind { + StartKind::Unavailable => Ok(StartOutcome::Unavailable(reason)), + StartKind::InvalidConfig => Ok(StartOutcome::InvalidConfig(reason)), + StartKind::Error => Err(Error::execution(format!( + "compute driver '{name}' failed to start: {reason}" + ))), + } +} + +/// A driver process that has started and accepts connections but is not yet +/// configured. Dropping it stops the process. +pub struct Started { + name: String, + child: Option, + socket: PathBuf, + /// `finish` handed the process and its launch directory to a managed + /// process. + handed_off: bool, +} + +impl Drop for Started { + fn drop(&mut self) { + if self.handed_off { + return; + } + if let Some(mut child) = self.child.take() { + let _ = child.kill(); + let _ = child.wait(); + } + // The launch directory belongs to this launch. + let _ = std::fs::remove_file(&self.socket); + if let Some(dir) = self.socket.parent() { + let _ = std::fs::remove_dir(dir); + } + } +} + +/// How starting a driver ended. +pub enum StartOutcome { + /// The driver is running and accepts connections. + Started(Started), + /// The driver's backend is not reachable with these settings. + Unavailable(String), + /// The driver rejected its table. + InvalidConfig(String), +} + +/// How a launch ended before the driver was serving. +pub enum LaunchOutcome { + /// The driver is running and configured. + Launched(Launched), + /// The driver's backend is not reachable with these settings. + Unavailable(String), + /// The driver rejected its table. + InvalidConfig(String), +} + +/// A running, configured driver. +pub struct Launched { + pub channel: Channel, + pub process: Arc, +} + +/// What to launch. +#[derive(Clone, Copy)] +pub struct LaunchRequest<'a> { + /// The driver name `GetLaunchInfo` must report, such as `vm`. + pub name: &'a str, + pub binary: &'a Path, + /// The driver table as TOML text. + pub table: &'a str, + /// A directory the gateway owns, made private (`0700`) for the socket. + pub socket_dir: &'a Path, + pub log_level: &'a str, +} + +/// Start ` serve` with `request.table` on stdin and wait until it +/// accepts a connection or exits. Blocking: callers in async code use +/// `spawn_blocking`. +/// +/// Detection and launch share this. The driver checks its table and backend +/// before it binds, so a driver that accepts a connection is available, and +/// the same process goes on to be configured. +pub fn start(request: &LaunchRequest<'_>) -> Result { + let name = request.name; + let socket = prepare_socket(request.socket_dir)?; + let stdin = table_stdin(request.table) + .map_err(|error| Error::execution(format!("failed to stage the driver table: {error}")))?; + let mut child = std::process::Command::new(request.binary) + .arg("serve") + .arg("--bind-socket") + .arg(&socket) + .arg("--expected-peer-pid") + .arg(std::process::id().to_string()) + .arg("--log-level") + .arg(request.log_level) + .stdin(stdin) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .map_err(|error| { + Error::execution(format!( + "failed to launch compute driver '{}': {error}", + request.binary.display() + )) + })?; + let capture = StderrCapture::default(); + let stdout_task = capture.spawn(child.stdout.take().expect("stdout is piped")); + let mut started = Started { + name: name.to_string(), + child: Some(child), + socket, + handed_off: false, + }; + + let deadline = Instant::now() + START_TIMEOUT; + loop { + let child = started + .child + .as_mut() + .expect("the child is held until it exits"); + if let Some(status) = child.try_wait().map_err(|error| { + Error::execution(format!("failed to poll compute driver '{name}': {error}")) + })? { + started.child = None; + // The driver's end of stdout is closed; let the reader finish. + let wait_until = Instant::now() + Duration::from_secs(1); + while !stdout_task.is_finished() && Instant::now() < wait_until { + std::thread::sleep(Duration::from_millis(10)); + } + return exit_outcome(name, status.code(), status, capture.take()); + } + if std::os::unix::net::UnixStream::connect(&started.socket).is_ok() { + return Ok(StartOutcome::Started(started)); + } + if Instant::now() >= deadline { + return Err(Error::execution(format!( + "timed out waiting for compute driver '{name}' to accept connections on '{}'", + started.socket.display() + ))); + } + std::thread::sleep(POLL_INTERVAL); + } +} + +/// Configure a driver that `start` returned and begin watching its process. +pub async fn finish( + mut started: Started, + configure: ConfigureRequest, + on_unexpected_exit: Arc, +) -> Result { + let channel = connect(&started.socket) + .await + .map_err(|error| Error::execution(format!("failed to connect to driver: {error}")))?; + handshake(&channel, &started.name, configure).await?; + let child = started + .child + .take() + .expect("a started driver holds its process"); + started.handed_off = true; + let process = Arc::new(ManagedDriverProcess::from_std( + child, + started.socket.clone(), + )); + watch_process(started.name.clone(), &process, on_unexpected_exit); + Ok(Launched { channel, process }) +} + +/// Start a driver and configure it. +pub async fn launch( + request: LaunchRequest<'_>, + configure: ConfigureRequest, + on_unexpected_exit: Arc, +) -> Result { + let owned = ( + request.name.to_string(), + request.binary.to_path_buf(), + request.table.to_string(), + request.socket_dir.to_path_buf(), + request.log_level.to_string(), + ); + let outcome = tokio::task::spawn_blocking(move || { + start(&LaunchRequest { + name: &owned.0, + binary: &owned.1, + table: &owned.2, + socket_dir: &owned.3, + log_level: &owned.4, + }) + }) + .await + .map_err(|error| Error::execution(format!("driver start task failed: {error}")))??; + match outcome { + StartOutcome::Started(started) => Ok(LaunchOutcome::Launched( + finish(started, configure, on_unexpected_exit).await?, + )), + StartOutcome::Unavailable(reason) => Ok(LaunchOutcome::Unavailable(reason)), + StartOutcome::InvalidConfig(reason) => Ok(LaunchOutcome::InvalidConfig(reason)), + } +} + +/// How often to start a driver whose backend is unreachable. +#[derive(Clone, Copy)] +pub struct UnavailableRetry { + pub attempts: u32, + pub delay: Duration, +} + +/// [`launch`], starting the driver again while its backend is unreachable. +/// +/// Only an "unavailable" result is retried. An invalid table or a crash is +/// final. +pub async fn launch_tolerating_unavailable( + request: LaunchRequest<'_>, + configure: ConfigureRequest, + on_unexpected_exit: Arc, + retry: UnavailableRetry, +) -> Result { + let attempts = retry.attempts.max(1); + let mut attempt = 1; + loop { + let outcome = launch(request, configure.clone(), Arc::clone(&on_unexpected_exit)).await?; + match outcome { + LaunchOutcome::Unavailable(reason) if attempt < attempts => { + tracing::warn!( + driver = request.name, + attempt, + attempts, + %reason, + "compute driver backend is not reachable yet; retrying" + ); + tokio::time::sleep(retry.delay).await; + attempt += 1; + } + outcome => return Ok(outcome), + } + } +} + +/// Check the driver's identity and protocol, then configure it. +pub async fn handshake(channel: &Channel, name: &str, configure: ConfigureRequest) -> Result<()> { + let mut client = DriverLaunchClient::new(channel.clone()); + let info = client + .get_launch_info(GetLaunchInfoRequest {}) + .await + .map_err(|status| Error::execution(format!("GetLaunchInfo failed: {status}")))? + .into_inner(); + if info.driver_name != name { + return Err(Error::execution(format!( + "expected compute driver '{name}' but the process reports '{}'", + info.driver_name + ))); + } + if !info.protocol_versions.contains(&PROTOCOL_VERSION) { + return Err(Error::execution(format!( + "compute driver '{name}' {} supports launch protocol versions {:?}, not {PROTOCOL_VERSION}; upgrade the gateway and driver together", + info.driver_version, info.protocol_versions + ))); + } + let mut request = tonic::Request::new(ConfigureRequest { + protocol_version: PROTOCOL_VERSION, + ..configure + }); + request.set_timeout(CONFIGURE_TIMEOUT); + client.configure(request).await.map_err(|status| { + Error::execution(format!("configuring compute driver '{name}': {status}")) + })?; + Ok(()) +} + +/// Report a managed driver's unexpected exit once. A stop the gateway asked +/// for, which releases the process, is not reported. +fn watch_process( + name: String, + process: &Arc, + on_unexpected_exit: Arc, +) { + let process = Arc::downgrade(process); + tokio::spawn(async move { + loop { + tokio::time::sleep(EXIT_WATCH_INTERVAL).await; + let Some(process) = process.upgrade() else { + return; + }; + match process.poll_exit() { + DriverProcessState::Running => {} + DriverProcessState::Released => return, + DriverProcessState::Exited(how) => { + on_unexpected_exit(format!("compute driver '{name}' {how}")); + return; + } + } + } + }); +} + +/// The default response to a driver that exited unexpectedly: log it and exit +/// nonzero, which leaves the sandboxes running. +pub fn exit_gateway_on_driver_exit() -> Arc { + Arc::new(|message| { + tracing::error!("{message}; the gateway cannot serve without it and is exiting"); + std::process::exit(1); + }) +} + +async fn connect(socket: &Path) -> std::result::Result { + let socket = socket.to_path_buf(); + Endpoint::from_static("http://[::]:50051") + .connect_with_connector(service_fn(move |_: tonic::transport::Uri| { + let socket = socket.clone(); + async move { UnixStream::connect(socket).await.map(TokioIo::new) } + })) + .await +} + +/// A driver's answer to `preflight`. +#[derive(Debug, PartialEq, Eq)] +pub enum PreflightFailure { + /// The driver rejected the table. + InvalidConfig(String), + /// The check itself failed. + Error(String), +} + +/// Run ` preflight` with the table on stdin. The driver contacts no +/// backend and creates no state. +pub fn preflight(binary: &Path, table: &str) -> std::result::Result<(), PreflightFailure> { + use std::io::Read as _; + + let mut child = std::process::Command::new(binary) + .arg("preflight") + .stdin(table_stdin(table).map_err(|error| { + PreflightFailure::Error(format!("failed to stage the driver table: {error}")) + })?) + .stdout(Stdio::piped()) + .stderr(Stdio::inherit()) + .spawn() + .map_err(|error| { + PreflightFailure::Error(format!("failed to run '{}': {error}", binary.display())) + })?; + let mut stdout = child.stdout.take().expect("stdout is piped"); + let reader = std::thread::spawn(move || { + let mut text = String::new(); + let _ = stdout.read_to_string(&mut text); + text + }); + + let deadline = Instant::now() + PREFLIGHT_TIMEOUT; + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if Instant::now() < deadline => std::thread::sleep(Duration::from_millis(10)), + Ok(None) => { + let _ = child.kill(); + let _ = child.wait(); + return Err(PreflightFailure::Error(format!( + "'{}' preflight timed out", + binary.display() + ))); + } + Err(error) => return Err(PreflightFailure::Error(error.to_string())), + } + }; + let stdout = reader.join().unwrap_or_default(); + if status.success() { + return Ok(()); + } + let report = StartReport::from_output(&stdout); + let reason = report + .as_ref() + .map_or_else(|| status.to_string(), |report| report.reason.clone()); + // The exit status decides the result; the report only explains it. + match status.code().map(StartKind::from_exit_code) { + Some(StartKind::InvalidConfig) => Err(PreflightFailure::InvalidConfig(reason)), + _ => Err(PreflightFailure::Error(reason)), + } +} + +/// Gateway-owned values a driver receives in `Configure`. +pub struct ConfigureInputs<'a> { + /// The gateway's listener. Its port is the gateway port. + pub gateway_bind_address: std::net::SocketAddr, + /// The gateway CA guests trust; unset when the gateway serves plaintext. + pub guest_tls_ca: Option<&'a Path>, + pub gateway_name: &'a str, + pub network_trust: Option<&'a openshell_core::NetworkSupervisorTrustBundle>, + pub otlp: Option<&'a openshell_server::config_file::OtlpConfig>, + /// The operator's admission policy, which the gateway owns. + pub admission: Option<&'a openshell_core::resource_admission::DriverAdmissionConfig>, + pub sandbox_runtime_image: Option, + pub supervisor_image: Option, +} + +impl<'a> ConfigureInputs<'a> { + /// The inputs with image overrides read from the gateway's environment. + #[must_use] + pub fn from_environment( + gateway_bind_address: std::net::SocketAddr, + guest_tls_ca: Option<&'a Path>, + gateway_name: &'a str, + network_trust: Option<&'a openshell_core::NetworkSupervisorTrustBundle>, + otlp: Option<&'a openshell_server::config_file::OtlpConfig>, + admission: Option<&'a openshell_core::resource_admission::DriverAdmissionConfig>, + ) -> Self { + Self { + gateway_bind_address, + guest_tls_ca, + gateway_name, + network_trust, + otlp, + admission, + sandbox_runtime_image: std::env::var(openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV) + .ok(), + supervisor_image: std::env::var(openshell_core::config::SUPERVISOR_IMAGE_ENV).ok(), + } + } + + /// The `Configure` request for these inputs. The protocol version is + /// filled in when the request is sent. + #[must_use] + pub fn request(&self) -> ConfigureRequest { + use openshell_driver_sdk::launch as proto; + + let export = |export: Option<&openshell_core::sandbox_env::OtlpExport>| { + export.map(|export| proto::OtlpExport { + endpoint: export.endpoint.clone(), + protocol: export.protocol.as_str().to_string(), + }) + }; + let supervisor = self + .otlp + .map(openshell_server::config_file::OtlpConfig::supervisor_otlp) + .unwrap_or_default(); + let collector = self + .otlp + .and_then(|otlp| otlp.traces.as_ref()) + .map(|traces| &traces.collector); + let path = |path: Option<&Path>| { + path.map(|path| path.display().to_string()) + .unwrap_or_default() + }; + let telemetry = (!supervisor.is_empty()).then(|| proto::Telemetry { + traces: export(supervisor.traces.as_ref()), + ocsf: export(supervisor.ocsf.as_ref()), + agent: export(supervisor.agent.as_ref()), + collector: collector.map(|collector| proto::CollectorTls { + ca_file: path(collector.ca_file()), + cert_file: path(collector.cert_file()), + key_file: path(collector.key_file()), + }), + // Secret: it travels only here, over the private socket. + trace_headers: openshell_server::gateway_trace_headers(self.otlp) + .map(|headers| headers.expose_secret().to_string()) + .unwrap_or_default(), + }); + ConfigureRequest { + protocol_version: PROTOCOL_VERSION, + required_features: Vec::new(), + gateway: Some(proto::GatewayContext { + gateway_port: u32::from(self.gateway_bind_address.port()), + bind_address: self.gateway_bind_address.to_string(), + tls_ca_path: path(self.guest_tls_ca), + gateway_name: self.gateway_name.to_string(), + }), + network_trust: self.network_trust.map(|bundle| proto::NetworkTrust { + artifact_path: bundle.artifact_path().display().to_string(), + digest: bundle.digest().to_string(), + certificate_count: u32::try_from(bundle.certificate_count()).unwrap_or(u32::MAX), + }), + image_overrides: Some(proto::ImageOverrides { + sandbox_runtime_image: self.sandbox_runtime_image.clone(), + supervisor_image: self.supervisor_image.clone(), + }), + telemetry, + admission_json: self + .admission + .and_then(|policy| serde_json::to_string(policy).ok()) + .unwrap_or_default(), + } + } +} + +/// Remove the admission keys from a driver table. The gateway owns the +/// policy: it reads and validates it, and sends it in `Configure`. +pub fn strip_gateway_owned_keys(table: &mut toml::map::Map) { + for key in ["allow_driver_config", "resource_admission"] { + table.remove(key); + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-gateway/src/launcher/tests.rs b/crates/openshell-gateway/src/launcher/tests.rs new file mode 100644 index 0000000000..a46c5461af --- /dev/null +++ b/crates/openshell-gateway/src/launcher/tests.rs @@ -0,0 +1,521 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::io::Write as _; +use std::os::unix::fs::OpenOptionsExt as _; +use std::sync::atomic::{AtomicBool, Ordering}; + +use openshell_driver_sdk::launch::{Launch, LaunchInfo}; + +use openshell_server::config_file::OtlpConfig; + +use super::*; + +/// Write an executable script by writing and closing a temporary file, then +/// renaming it into place, so it is never executed while open for writing. +fn script(dir: &Path, name: &str, body: &str) -> PathBuf { + let temporary = dir.join(format!("{name}.tmp")); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o755) + .open(&temporary) + .unwrap(); + file.write_all(format!("#!/bin/sh\n{body}\n").as_bytes()) + .unwrap(); + file.sync_all().unwrap(); + drop(file); + let path = dir.join(name); + std::fs::rename(&temporary, &path).unwrap(); + path +} + +async fn run(binary: &Path, table: &str, dir: &Path) -> Result { + launch( + LaunchRequest { + name: "fake", + binary, + table, + socket_dir: &dir.join("run"), + log_level: "info", + }, + ConfigureRequest::default(), + Arc::new(|_| {}), + ) + .await +} + +#[tokio::test] +async fn the_table_arrives_on_stdin_and_bootstrap_arguments_on_argv() { + let dir = tempfile::tempdir().unwrap(); + let record = dir.path().join("record"); + let binary = script( + dir.path(), + "driver", + &format!( + "printf '%s\\n' \"$@\" > '{0}.argv'\ncat > '{0}.stdin'\nprintf '{{\"result\":\"invalid_config\",\"reason\":\"nope\"}}\\n'\nexit 78", + record.display() + ), + ); + let table = "vcpus = 4\n# comment\n"; + + let outcome = run(&binary, table, dir.path()).await.unwrap(); + + assert!(matches!(outcome, LaunchOutcome::InvalidConfig(reason) if reason == "nope")); + assert_eq!( + std::fs::read_to_string(dir.path().join("record.stdin")).unwrap(), + table + ); + let argv = std::fs::read_to_string(dir.path().join("record.argv")).unwrap(); + let argv: Vec<_> = argv.lines().collect(); + assert_eq!(argv[0], "serve"); + assert_eq!(argv[1], "--bind-socket"); + assert!(argv[2].contains("/run/"), "{}", argv[2]); + assert!(argv[2].ends_with("/driver.sock"), "{}", argv[2]); + assert_eq!(argv[3], "--expected-peer-pid"); + assert_eq!(argv[4], std::process::id().to_string()); + assert_eq!(&argv[5..], ["--log-level", "info"]); + assert_eq!(argv.len(), 7, "no other flags: {argv:?}"); +} + +#[tokio::test] +async fn exit_codes_map_to_the_documented_results() { + let dir = tempfile::tempdir().unwrap(); + let report = |kind: &str| format!("printf '{{\"result\":\"{kind}\",\"reason\":\"why\"}}\\n'\n"); + let cases = [ + ("unavailable", report("unavailable") + "exit 69"), + ("unavailable-bare", "exit 69".to_string()), + ("invalid", report("invalid_config") + "exit 78"), + ("invalid-bare", "exit 78".to_string()), + ]; + for (name, body) in cases { + let binary = script(dir.path(), name, &body); + let outcome = run(&binary, "", &dir.path().join(format!("{name}-dir"))) + .await + .unwrap(); + match (name, outcome) { + ("unavailable", LaunchOutcome::Unavailable(reason)) + | ("invalid", LaunchOutcome::InvalidConfig(reason)) => assert_eq!(reason, "why"), + ("unavailable-bare", LaunchOutcome::Unavailable(_)) + | ("invalid-bare", LaunchOutcome::InvalidConfig(_)) => {} + _ => panic!("{name} mapped to the wrong result"), + } + } + + let binary = script(dir.path(), "crash", "exit 1"); + let error = run(&binary, "", &dir.path().join("crash-dir")) + .await + .err() + .expect("an internal failure is an error"); + assert!(error.to_string().contains("failed to start"), "{error}"); +} + +#[test] +fn a_binary_writable_by_others_is_not_trusted() { + let dir = tempfile::tempdir().unwrap(); + let good = script(dir.path(), "good", "exit 0"); + check_binary_trust(&good).unwrap(); + + for mode in [0o775, 0o757] { + let loose = script(dir.path(), &format!("loose-{mode:o}"), "exit 0"); + std::fs::set_permissions(&loose, std::fs::Permissions::from_mode(mode)).unwrap(); + let error = check_binary_trust(&loose).unwrap_err().to_string(); + assert!(error.contains("writable"), "{error}"); + } +} + +#[test] +fn binaries_are_found_in_the_configured_directories() { + let dir = tempfile::tempdir().unwrap(); + script(dir.path(), "openshell-driver-fake", "exit 0"); + + let found = resolve_binary( + "openshell-driver-fake", + &[dir.path().join("missing"), dir.path().to_path_buf()], + "install it", + ) + .unwrap(); + assert_eq!(found, dir.path().join("openshell-driver-fake")); + + let error = resolve_binary( + "openshell-driver-absent", + &[dir.path().to_path_buf()], + "install it", + ) + .unwrap_err() + .to_string(); + assert!( + error.contains("not found") && error.contains("install it"), + "{error}" + ); +} + +#[test] +fn every_launch_gets_its_own_private_socket_directory() { + let dir = tempfile::tempdir().unwrap(); + let base = dir.path().join("run"); + std::fs::create_dir(&base).unwrap(); + std::fs::set_permissions(&base, std::fs::Permissions::from_mode(0o755)).unwrap(); + + let first = prepare_socket(&base).unwrap(); + let second = prepare_socket(&base).unwrap(); + + assert_ne!( + first.parent(), + second.parent(), + "launches must not share a directory" + ); + assert_eq!(first.file_name().unwrap(), SOCKET_NAME); + for launch_dir in [first.parent().unwrap(), second.parent().unwrap()] { + assert!(launch_dir.starts_with(&base)); + assert_eq!( + std::fs::metadata(launch_dir).unwrap().permissions().mode() & 0o777, + 0o700 + ); + } + assert_eq!( + std::fs::metadata(&base).unwrap().permissions().mode() & 0o777, + 0o700 + ); + + // Another launch's socket is never touched. + std::fs::write(&first, b"first").unwrap(); + prepare_socket(&base).unwrap(); + assert_eq!(std::fs::read(&first).unwrap(), b"first"); +} + +#[tokio::test] +async fn a_launch_that_fails_removes_its_directory() { + let dir = tempfile::tempdir().unwrap(); + let binary = script(dir.path(), "driver", "exit 78"); + let base = dir.path().join("base"); + + run(&binary, "", &base).await.unwrap(); + + let leftovers = std::fs::read_dir(base.join("run")).map_or(0, Iterator::count); + assert_eq!( + leftovers, 0, + "the failed launch's directory must be removed" + ); +} + +#[tokio::test] +async fn the_exit_status_decides_the_result_not_the_report() { + let dir = tempfile::tempdir().unwrap(); + // A report that claims "unavailable" cannot turn a crash into an absent + // backend, which would silently fall through to another driver. + let lies = script( + dir.path(), + "lies", + "printf '{\"result\":\"unavailable\",\"reason\":\"nope\"}\\n'\nexit 1", + ); + let error = run(&lies, "", &dir.path().join("lies-dir")) + .await + .err() + .expect("an exit status of 1 is an internal failure"); + assert!(error.to_string().contains("nope"), "{error}"); + + let killed = script(dir.path(), "killed", "kill -9 $$"); + assert!( + run(&killed, "", &dir.path().join("killed-dir")) + .await + .is_err() + ); +} + +#[tokio::test] +async fn an_unexpected_exit_is_reported_and_a_released_process_is_not() { + let dir = tempfile::tempdir().unwrap(); + let spawn = |script: &str| { + tokio::process::Command::new("sh") + .arg("-c") + .arg(script) + .kill_on_drop(true) + .spawn() + .unwrap() + }; + + let reported = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&reported); + let exits = Arc::new(ManagedDriverProcess::new( + spawn("exit 7"), + dir.path().join("a"), + )); + watch_process( + "fake".into(), + &exits, + Arc::new(move |message| { + assert!(message.contains("fake"), "{message}"); + flag.store(true, Ordering::SeqCst); + }), + ); + let deadline = Instant::now() + Duration::from_secs(10); + while !reported.load(Ordering::SeqCst) { + assert!(Instant::now() < deadline, "the exit was never reported"); + tokio::time::sleep(Duration::from_millis(50)).await; + } + + let spurious = Arc::new(AtomicBool::new(false)); + let flag = Arc::clone(&spurious); + let released = Arc::new(ManagedDriverProcess::new( + spawn("sleep 30"), + dir.path().join("b"), + )); + watch_process( + "fake".into(), + &released, + Arc::new(move |_| flag.store(true, Ordering::SeqCst)), + ); + drop(released); + tokio::time::sleep(EXIT_WATCH_INTERVAL * 2 + Duration::from_millis(200)).await; + assert!(!spurious.load(Ordering::SeqCst)); +} + +async fn serve_launch( + socket: &Path, + name: &str, + seen: Arc>>, +) -> Channel { + let launch = Launch::new( + LaunchInfo { + driver_name: name.to_string(), + driver_version: "1.0".to_string(), + features: Vec::new(), + }, + move |request| { + let seen = Arc::clone(&seen); + async move { + *seen.lock().unwrap() = Some(request); + Ok(()) + } + }, + ); + let listener = tokio::net::UnixListener::bind(socket).unwrap(); + tokio::spawn( + tonic::transport::Server::builder() + .add_service(launch.into_server()) + .serve_with_incoming(tokio_stream::wrappers::UnixListenerStream::new(listener)), + ); + connect(socket).await.unwrap() +} + +#[tokio::test] +async fn the_handshake_configures_the_driver_it_expects() { + let dir = tempfile::tempdir().unwrap(); + let seen = Arc::new(Mutex::new(None)); + let channel = serve_launch(&dir.path().join("a.sock"), "fake", Arc::clone(&seen)).await; + let configure = ConfigureRequest { + gateway: Some(openshell_driver_sdk::launch::GatewayContext { + gateway_port: 8080, + ..Default::default() + }), + ..Default::default() + }; + + handshake(&channel, "fake", configure).await.unwrap(); + + let received = seen.lock().unwrap().take().expect("configured"); + assert_eq!(received.protocol_version, PROTOCOL_VERSION); + assert_eq!(received.gateway.unwrap().gateway_port, 8080); + + let seen = Arc::new(Mutex::new(None)); + let channel = serve_launch(&dir.path().join("b.sock"), "other", Arc::clone(&seen)).await; + let error = handshake(&channel, "fake", ConfigureRequest::default()) + .await + .unwrap_err() + .to_string(); + assert!(error.contains("'other'"), "{error}"); + assert!( + seen.lock().unwrap().is_none(), + "a mismatched driver is not configured" + ); +} + +#[test] +fn preflight_maps_its_exit_codes() { + let dir = tempfile::tempdir().unwrap(); + let stdin = dir.path().join("stdin"); + let accepts = script( + dir.path(), + "accepts", + &format!("cat > '{}'", stdin.display()), + ); + preflight(&accepts, "vcpus = 4\n").unwrap(); + assert_eq!(std::fs::read_to_string(stdin).unwrap(), "vcpus = 4\n"); + + let rejects = script( + dir.path(), + "rejects", + "printf '{\"result\":\"invalid_config\",\"reason\":\"unknown key\"}\\n'\nexit 78", + ); + assert_eq!( + preflight(&rejects, ""), + Err(PreflightFailure::InvalidConfig("unknown key".to_string())) + ); + + let breaks = script(dir.path(), "breaks", "exit 3"); + assert!(matches!( + preflight(&breaks, ""), + Err(PreflightFailure::Error(_)) + )); +} + +#[test] +fn configure_carries_the_gateway_metadata_the_argv_used_to() { + let ca_dir = tempfile::tempdir().unwrap(); + let ca = ca_dir.path().join("collector-ca.pem"); + let pki = openshell_otel_test_support::TestPki::generate(); + std::fs::write(&ca, &pki.ca_pem).unwrap(); + let otlp: OtlpConfig = toml::from_str(&format!( + r#" + [traces] + endpoint = "https://traces.test:4317" + protocol = "http/protobuf" + ca_file = "{}" + [ocsf] + enabled = true + endpoint = "https://ocsf.test:4317" + "#, + ca.display() + )) + .unwrap(); + let bundle = openshell_core::NetworkSupervisorTrustBundle::new( + b"pem".to_vec(), + 2, + "sha256:abc", + PathBuf::from("/var/lib/openshell/network/additional-ca.crt"), + ); + let admission = openshell_core::resource_admission::DriverAdmissionConfig { + allow_driver_config: true, + ..Default::default() + }; + let inputs = ConfigureInputs { + gateway_bind_address: "127.0.0.1:8080".parse().unwrap(), + guest_tls_ca: Some(Path::new("/etc/openshell/ca.pem")), + gateway_name: "gw", + network_trust: Some(&bundle), + otlp: Some(&otlp), + admission: Some(&admission), + sandbox_runtime_image: Some("runtime:1".to_string()), + supervisor_image: None, + }; + + let request = inputs.request(); + + assert_eq!(request.protocol_version, PROTOCOL_VERSION); + let gateway = request.gateway.unwrap(); + assert_eq!(gateway.gateway_port, 8080); + assert_eq!(gateway.bind_address, "127.0.0.1:8080"); + assert_eq!(gateway.tls_ca_path, "/etc/openshell/ca.pem"); + assert_eq!(gateway.gateway_name, "gw"); + let trust = request.network_trust.unwrap(); + assert_eq!( + trust.artifact_path, + "/var/lib/openshell/network/additional-ca.crt" + ); + assert_eq!(trust.digest, "sha256:abc"); + assert_eq!(trust.certificate_count, 2); + let images = request.image_overrides.unwrap(); + assert_eq!(images.sandbox_runtime_image.as_deref(), Some("runtime:1")); + assert_eq!(images.supervisor_image, None); + let telemetry = request.telemetry.unwrap(); + let traces = telemetry.traces.unwrap(); + assert_eq!(traces.endpoint, "https://traces.test:4317"); + assert_eq!(traces.protocol, "http/protobuf"); + assert_eq!(telemetry.ocsf.unwrap().endpoint, "https://ocsf.test:4317"); + assert!(telemetry.agent.is_none()); + let sent: openshell_core::resource_admission::DriverAdmissionConfig = + serde_json::from_str(&request.admission_json).unwrap(); + assert!(sent.allow_driver_config); + assert_eq!( + telemetry.collector.unwrap().ca_file, + ca.display().to_string() + ); +} + +#[test] +fn configure_omits_what_the_gateway_does_not_have() { + let inputs = ConfigureInputs { + gateway_bind_address: "127.0.0.1:8080".parse().unwrap(), + guest_tls_ca: None, + gateway_name: "gw", + network_trust: None, + otlp: None, + admission: None, + sandbox_runtime_image: None, + supervisor_image: None, + }; + + let request = inputs.request(); + + assert_eq!(request.gateway.unwrap().tls_ca_path, ""); + assert!(request.network_trust.is_none()); + assert!(request.telemetry.is_none()); + assert!(request.admission_json.is_empty()); +} + +#[tokio::test] +async fn an_unreachable_backend_is_retried_a_bounded_number_of_times() { + let dir = tempfile::tempdir().unwrap(); + let counter = dir.path().join("starts"); + let binary = script( + dir.path(), + "driver", + &format!("echo x >> '{}'\nexit 69", counter.display()), + ); + + let outcome = launch_tolerating_unavailable( + LaunchRequest { + name: "fake", + binary: &binary, + table: "", + socket_dir: &dir.path().join("run"), + log_level: "info", + }, + ConfigureRequest::default(), + Arc::new(|_| {}), + UnavailableRetry { + attempts: 3, + delay: Duration::from_millis(5), + }, + ) + .await + .unwrap(); + + assert!(matches!(outcome, LaunchOutcome::Unavailable(_))); + assert_eq!(std::fs::read_to_string(counter).unwrap().lines().count(), 3); +} + +#[tokio::test] +async fn an_invalid_table_or_a_crash_is_not_retried() { + let dir = tempfile::tempdir().unwrap(); + for (name, code) in [("invalid", 78), ("crash", 1)] { + let counter = dir.path().join(format!("{name}-starts")); + let binary = script( + dir.path(), + name, + &format!("echo x >> '{}'\nexit {code}", counter.display()), + ); + let _ = launch_tolerating_unavailable( + LaunchRequest { + name: "fake", + binary: &binary, + table: "", + socket_dir: &dir.path().join(format!("{name}-run")), + log_level: "info", + }, + ConfigureRequest::default(), + Arc::new(|_| {}), + UnavailableRetry { + attempts: 3, + delay: Duration::from_millis(5), + }, + ) + .await; + assert_eq!( + std::fs::read_to_string(counter).unwrap().lines().count(), + 1, + "{name} must not be retried" + ); + } +} diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs index 2e75ec61f6..6676230e2f 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -16,6 +16,17 @@ compile_error!( build a telemetry-free gateway with `--no-default-features --features defaults-without-telemetry`" ); +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-docker"))] +mod docker; +#[cfg(all(not(target_os = "windows"), feature = "driver-launcher"))] +mod launcher; +#[cfg(all( + not(target_os = "windows"), + any(feature = "compute-driver-docker", feature = "compute-driver-podman") +))] +mod local_driver; +#[cfg(all(not(target_os = "windows"), feature = "compute-driver-podman"))] +mod podman; #[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] mod vm; @@ -194,28 +205,20 @@ fn install_in_tree_compute_drivers(registry: &mut ComputeDriverRegistry) { .with_in_process_tracing(openshell_driver_kubernetes::otel_tracing::TRACING) }), #[cfg(feature = "compute-driver-podman")] - ComputeDriverRegistration::new( - "podman", - 200, - Some(openshell_driver_podman::driver::is_available), - PodmanFactory, - ) - .map(|registration| { + ComputeDriverRegistration::new("podman", 200, None, PodmanFactory).map(|registration| { registration .with_telemetry_category(TelemetryComputeDriver::anonymous_category("podman")) - .with_in_process_tracing(openshell_driver_podman::otel_tracing::TRACING) + // Detection starts the driver with the operator's table, so a + // configured socket_path is honoured. + .with_table_detection(podman::detect) }), #[cfg(feature = "compute-driver-docker")] - ComputeDriverRegistration::new( - "docker", - 300, - Some(openshell_driver_docker::is_available), - DockerFactory, - ) - .map(|registration| { + ComputeDriverRegistration::new("docker", 300, None, DockerFactory).map(|registration| { registration .with_telemetry_category(TelemetryComputeDriver::anonymous_category("docker")) - .with_in_process_tracing(openshell_driver_docker::otel_tracing::TRACING) + // Detection starts the driver with the operator's table, so a + // configured socket_path is honoured. + .with_table_detection(docker::detect) }), #[cfg(feature = "compute-driver-vm")] ComputeDriverRegistration::new("vm", u16::MAX, None, VmFactory).map(|registration| { @@ -392,76 +395,54 @@ impl openshell_server::ComputeDriverFactory for DockerFactory { &self, context: openshell_server::ComputeDriverConfigContext<'_>, ) -> openshell_core::Result<()> { - let config = docker_config(context)?; - config.validate_configuration(context.gateway_bind_address()) + // The gateway owns the admission policy and its own listener, so it + // validates them here; the driver checks the rest of its table. + self.admission_policy(context)?; + if context.gateway_bind_address().port() == 0 { + return Err(openshell_core::Error::config( + "docker compute driver requires a fixed non-zero gateway bind port", + )); + } + docker::DOCKER.validate(&docker_launch_plan(context)?) } async fn build( &self, context: openshell_server::ComputeDriverBuildContext<'_>, ) -> openshell_core::Result { - self.build_with_configuration_updates(context) - .await - .map(|(instance, _)| instance) - } - - async fn build_with_configuration_updates( - &self, - context: openshell_server::ComputeDriverBuildContext<'_>, - ) -> openshell_core::Result<( - openshell_server::ComputeDriverInstance, - Option, - )> { - let mut config = docker_config(context.config_context())?; - config.supervisor_otlp = context - .otlp_config() - .map(OtlpConfig::supervisor_otlp) - .unwrap_or_default(); - config.supervisor_gateway_name = Some(context.gateway_name().to_string()); + let plan = docker_launch_plan(context.config_context())?; require_guest_tls_for_local_driver(&context, "docker")?; - apply_guest_tls(&mut config.guest_tls_ca, context.guest_tls_ca()); - let driver = openshell_driver_docker::DockerComputeDriver::new( + let admission = self.admission_policy(context.config_context())?; + let inputs = launcher::ConfigureInputs::from_environment( context.gateway_bind_address(), - context.gateway_log_level(), - &config, - context.network_trust_bundle().cloned(), - ) - .await - .map_err(|error| openshell_core::Error::execution(error.to_string()))?; - let driver = std::sync::Arc::new( - openshell_driver_docker::ComputeDriverService::new_in_process(driver), + context.guest_tls_ca(), + context.gateway_name(), + context.network_trust_bundle(), + context.otlp_config(), + Some(&admission), ); - let updates: Option = - if config.persist_workspace { - Some(driver.clone()) - } else { - None - }; - Ok(( - openshell_server::ComputeDriverInstance::InProcess(driver), - updates, + // Auto-detection already started the driver; configure that process. + let detected = context.take_detected_driver::(); + let endpoint = docker::DOCKER + .spawn( + &plan, + detected, + &local_driver::LocalDriver::socket_dir(), + context.gateway_log_level(), + &inputs, + ) + .await?; + Ok(openshell_server::ComputeDriverInstance::ManagedRemote( + endpoint, )) } } #[cfg(all(not(target_os = "windows"), feature = "compute-driver-docker"))] -fn docker_config( +fn docker_launch_plan( context: openshell_server::ComputeDriverConfigContext<'_>, -) -> openshell_core::Result { - let mut config: openshell_driver_docker::DockerComputeConfig = context.driver_config()?; - config.sandbox_runtime_image = prefer_environment( - config.sandbox_runtime_image, - std::env::var(openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV) - .ok() - .map(Some), - ); - config.supervisor_image = prefer_environment( - config.supervisor_image, - std::env::var(openshell_core::config::SUPERVISOR_IMAGE_ENV) - .ok() - .map(Some), - ); - Ok(config) +) -> openshell_core::Result { + docker::DOCKER.plan(context.driver_table()?, context.driver_dir()) } #[cfg(all(not(target_os = "windows"), feature = "compute-driver-podman"))] @@ -483,54 +464,47 @@ impl openshell_server::ComputeDriverFactory for PodmanFactory { &self, context: openshell_server::ComputeDriverConfigContext<'_>, ) -> openshell_core::Result<()> { - podman_config(context)? - .validate_configuration() - .map_err(|error| openshell_core::Error::config(error.to_string())) + self.admission_policy(context)?; + podman::PODMAN.validate(&podman_launch_plan(context)?) } async fn build( &self, context: openshell_server::ComputeDriverBuildContext<'_>, ) -> openshell_core::Result { - let mut config = podman_config(context.config_context())?; - config.supervisor_otlp = context - .otlp_config() - .map(OtlpConfig::supervisor_otlp) - .unwrap_or_default(); - config.supervisor_gateway_name = Some(context.gateway_name().to_string()); + let plan = podman_launch_plan(context.config_context())?; require_guest_tls_for_local_driver(&context, "podman")?; - apply_guest_tls(&mut config.guest_tls_ca, context.guest_tls_ca()); - let driver = openshell_driver_podman::PodmanComputeDriver::new( - config, - context.network_trust_bundle().cloned(), - ) - .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), + let admission = self.admission_policy(context.config_context())?; + // Auto-detection already started the driver; configure that process. + let detected = context.take_detected_driver::(); + let inputs = launcher::ConfigureInputs::from_environment( + context.gateway_bind_address(), + context.guest_tls_ca(), + context.gateway_name(), + context.network_trust_bundle(), + context.otlp_config(), + Some(&admission), + ); + let endpoint = podman::PODMAN + .spawn( + &plan, + detected, + &local_driver::LocalDriver::socket_dir(), + context.gateway_log_level(), + &inputs, + ) + .await?; + Ok(openshell_server::ComputeDriverInstance::ManagedRemote( + endpoint, )) } } #[cfg(all(not(target_os = "windows"), feature = "compute-driver-podman"))] -fn podman_config( +fn podman_launch_plan( context: openshell_server::ComputeDriverConfigContext<'_>, -) -> openshell_core::Result { - let mut config: openshell_driver_podman::PodmanComputeConfig = context.driver_config()?; - config.gateway_port = context.gateway_port(); - config.sandbox_runtime_image = prefer_environment( - config.sandbox_runtime_image, - std::env::var(openshell_core::config::SANDBOX_RUNTIME_IMAGE_ENV).ok(), - ); - config.supervisor_image = prefer_environment( - config.supervisor_image, - std::env::var(openshell_core::config::SUPERVISOR_IMAGE_ENV).ok(), - ); - if let Ok(path) = std::env::var("OPENSHELL_PODMAN_SOCKET") { - config.socket_path = Some(path.into()); - } - Ok(config) +) -> openshell_core::Result { + podman::PODMAN.plan(context.driver_table()?, context.driver_dir()) } #[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] @@ -561,43 +535,27 @@ impl openshell_server::ComputeDriverFactory for VmFactory { &self, context: openshell_server::ComputeDriverConfigContext<'_>, ) -> openshell_core::Result<()> { - let mut config = vm_config(context)?; - if config.grpc_endpoint.trim().is_empty() { - let scheme = if context.gateway_tls_enabled() { - "https" - } else { - "http" - }; - config.grpc_endpoint = format!("{scheme}://127.0.0.1:{}", context.gateway_port()); - } - config.validate_configuration() + // The gateway owns the admission policy, so it validates it here. + self.admission_policy(context)?; + vm::validate(&vm_launch_plan(context)?) } async fn build( &self, context: openshell_server::ComputeDriverBuildContext<'_>, ) -> openshell_core::Result { - let mut config = vm_config(context.config_context())?; + let plan = vm_launch_plan(context.config_context())?; require_guest_tls_for_local_driver(&context, "vm")?; - if config.grpc_endpoint.trim().is_empty() - && (!context.gateway_tls_enabled() || context.guest_tls_ca().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, context.guest_tls_ca()); - let endpoint = vm::spawn( - context.gateway_log_level(), + let admission = self.admission_policy(context.config_context())?; + let inputs = launcher::ConfigureInputs::from_environment( + context.gateway_bind_address(), + context.guest_tls_ca(), context.gateway_name(), - &config, - context.otlp_config(), context.network_trust_bundle(), - ) - .await?; + context.otlp_config(), + Some(&admission), + ); + let endpoint = vm::spawn(&plan, context.gateway_log_level(), &inputs).await?; Ok(openshell_server::ComputeDriverInstance::ManagedRemote( endpoint, )) @@ -605,14 +563,10 @@ impl openshell_server::ComputeDriverFactory for VmFactory { } #[cfg(all(not(target_os = "windows"), feature = "compute-driver-vm"))] -fn vm_config( +fn vm_launch_plan( context: openshell_server::ComputeDriverConfigContext<'_>, -) -> 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(); - } - Ok(config) +) -> openshell_core::Result { + vm::VmLaunchPlan::from_table(context.driver_table()?, context.driver_dir()) } #[cfg(all( @@ -655,22 +609,6 @@ fn validate_local_driver_guest_tls( Ok(()) } -#[cfg(all( - not(target_os = "windows"), - any( - feature = "compute-driver-docker", - feature = "compute-driver-podman", - feature = "compute-driver-vm" - ) -))] -fn apply_guest_tls(ca: &mut Option, default_ca: Option<&std::path::Path>) { - if ca.is_none() - && let Some(default_ca) = default_ca - { - *ca = Some(default_ca.to_owned()); - } -} - #[cfg(all( test, not(target_os = "windows"), @@ -681,8 +619,7 @@ fn apply_guest_tls(ca: &mut Option, default_ca: Option<&std: ) ))] mod local_driver_tests { - use super::{apply_guest_tls, validate_local_driver_guest_tls}; - use std::path::{Path, PathBuf}; + use super::validate_local_driver_guest_tls; #[test] #[cfg(feature = "in-tree-compute-drivers")] @@ -709,13 +646,6 @@ mod local_driver_tests { validate_local_driver_guest_tls(false, false, "docker") .expect("plaintext gateways do not require guest TLS"); } - - #[test] - fn package_managed_gateway_ca_is_injected_when_driver_path_is_absent() { - let mut ca = None; - apply_guest_tls(&mut ca, Some(Path::new("/managed/ca.pem"))); - assert_eq!(ca, Some(PathBuf::from("/managed/ca.pem"))); - } } #[cfg(all(test, target_os = "windows"))] diff --git a/crates/openshell-gateway/src/local_driver.rs b/crates/openshell-gateway/src/local_driver.rs new file mode 100644 index 0000000000..1a84df9adf --- /dev/null +++ b/crates/openshell-gateway/src/local_driver.rs @@ -0,0 +1,205 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! What the gateway does the same way for each local driver it launches and +//! detects: split gateway-owned keys from the table, find the binary, check +//! the table with the driver's `preflight`, detect it by starting it, and +//! launch and configure it. +//! +//! The gateway knows only the driver's name and the keys it owns or has +//! deprecated. It never parses the rest of the table. + +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use openshell_core::{Error, Result}; +use openshell_server::{ + AcquiredRemoteDriverEndpoint, DetectedDriver, DriverDetection, DriverDetectionContext, +}; + +use crate::launcher::{ + self, ConfigureInputs, LaunchOutcome, LaunchRequest, PreflightFailure, StartOutcome, Started, + UnavailableRetry, +}; + +/// One launched driver, such as `podman`. +#[derive(Clone, Copy)] +pub struct LocalDriver { + /// The driver's name, which names its table and binary. + pub name: &'static str, + /// Removes keys earlier releases accepted that the driver's strict table no + /// longer does. The gateway warns about each, so the driver can reject them. + pub drop_legacy_keys: fn(&mut toml::map::Map), + /// Start a named driver again this often while its backend is unreachable. + /// Drivers that never retried leave it unset. + pub retry_unavailable: Option, +} + +/// The gateway's view of a driver's table: where its binary is, and the table +/// to forward, without gateway-owned keys. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LaunchPlan { + pub driver_dir: Option, + pub table: String, +} + +impl LocalDriver { + fn binary_name(self) -> String { + format!("openshell-driver-{}", self.name) + } + + /// Split gateway-owned keys from the table the driver will parse. + /// + /// `gateway_driver_dir` is `driver_dir` from `[openshell.gateway]`. A + /// `driver_dir` in the driver table is deprecated: it is removed with a + /// warning and used only when the gateway section sets none. The admission + /// policy is removed too: the gateway owns it and sends it in `Configure`. + pub fn plan( + self, + mut table: toml::map::Map, + gateway_driver_dir: Option<&Path>, + ) -> Result { + let name = self.name; + let legacy_driver_dir = table + .remove("driver_dir") + .map(|value| { + tracing::warn!( + "[openshell.drivers.{name}].driver_dir is deprecated; set driver_dir in [openshell.gateway]" + ); + value.as_str().map(PathBuf::from).ok_or_else(|| { + Error::config(format!("[openshell.drivers.{name}].driver_dir must be a string")) + }) + }) + .transpose()?; + let driver_dir = gateway_driver_dir + .map(Path::to_path_buf) + .or(legacy_driver_dir); + launcher::strip_gateway_owned_keys(&mut table); + (self.drop_legacy_keys)(&mut table); + let table = toml::to_string(&table) + .map_err(|error| Error::config(format!("invalid {name} driver table: {error}")))?; + Ok(LaunchPlan { driver_dir, table }) + } + + fn binary(self, plan: &LaunchPlan) -> Result { + let binary = self.binary_name(); + launcher::resolve_binary( + &binary, + &launcher::driver_search_dirs(plan.driver_dir.as_deref()), + "set driver_dir in [openshell.gateway], install it in a conventional libexec path such as ~/.local/libexec/openshell, /usr/libexec/openshell, or /usr/local/libexec{,/openshell}, or place it next to the gateway binary", + ) + } + + /// Validate the table with the driver's own `preflight`, which contacts no + /// backend and creates no state. + pub fn validate(self, plan: &LaunchPlan) -> Result<()> { + let name = self.name; + launcher::preflight(&self.binary(plan)?, &plan.table).map_err(|failure| match failure { + PreflightFailure::InvalidConfig(reason) | PreflightFailure::Error(reason) => { + Error::config(format!( + "invalid [openshell.drivers.{name}] table: {reason}" + )) + } + }) + } + + /// Decide whether the driver can serve with the operator's table by + /// starting it, which makes it check the table and its backend before it + /// binds. The running driver is kept: if it is selected, this same process + /// is configured. + pub fn detect( + self, + context: &DriverDetectionContext<'_>, + socket_dir: &Path, + ) -> DriverDetection { + let plan = match self.plan(context.table.clone(), context.driver_dir) { + Ok(plan) => plan, + Err(error) => return DriverDetection::InvalidConfig(error.to_string()), + }; + let binary = match self.binary(&plan) { + Ok(binary) => binary, + Err(error) => return DriverDetection::Unavailable(error.to_string()), + }; + match launcher::start(&LaunchRequest { + name: self.name, + binary: &binary, + table: &plan.table, + socket_dir, + log_level: context.gateway_log_level, + }) { + Ok(StartOutcome::Started(started)) => { + DriverDetection::Available(Some(DetectedDriver::new(started))) + } + Ok(StartOutcome::Unavailable(reason)) => DriverDetection::Unavailable(reason), + Ok(StartOutcome::InvalidConfig(reason)) => DriverDetection::InvalidConfig(reason), + // A crash, a timeout, or a launch error is not an absent backend. + Err(error) => DriverDetection::Failed(error.to_string()), + } + } + + /// Launch the driver, configure it, and return a gRPC channel connected to + /// it with a handle that stops it when dropped. `detected` is the driver + /// that auto-detection already started, which is configured instead of + /// starting another. + pub async fn spawn( + self, + plan: &LaunchPlan, + detected: Option, + socket_dir: &Path, + gateway_log_level: &str, + inputs: &ConfigureInputs<'_>, + ) -> Result { + let name = self.name; + let configure = inputs.request(); + let on_exit = launcher::exit_gateway_on_driver_exit(); + let launched = if let Some(started) = detected { + launcher::finish(started, configure, on_exit).await? + } else { + let binary = self.binary(plan)?; + let request = LaunchRequest { + name, + binary: &binary, + table: &plan.table, + socket_dir, + log_level: gateway_log_level, + }; + let outcome = match self.retry_unavailable { + Some(retry) => { + launcher::launch_tolerating_unavailable(request, configure, on_exit, retry) + .await? + } + None => launcher::launch(request, configure, on_exit).await?, + }; + match outcome { + LaunchOutcome::Launched(launched) => launched, + LaunchOutcome::InvalidConfig(reason) => { + return Err(Error::config(format!( + "invalid [openshell.drivers.{name}] table: {reason}" + ))); + } + LaunchOutcome::Unavailable(reason) => { + return Err(Error::execution(format!( + "the {name} compute driver is unavailable: {reason}" + ))); + } + } + }; + Ok(AcquiredRemoteDriverEndpoint::managed( + name, + launched.channel, + launched.process, + )) + } + + /// The private directory for a launched driver's sockets. + #[must_use] + pub fn socket_dir() -> PathBuf { + openshell_core::paths::openshell_state_dir().map_or_else( + |_| PathBuf::from("target/openshell/run"), + |dir| dir.join("run"), + ) + } +} + +/// How long to wait between starts while a named driver's backend is down. +pub const BACKEND_RETRY_DELAY: Duration = Duration::from_secs(2); diff --git a/crates/openshell-gateway/src/podman.rs b/crates/openshell-gateway/src/podman.rs new file mode 100644 index 0000000000..e70d8e7d57 --- /dev/null +++ b/crates/openshell-gateway/src/podman.rs @@ -0,0 +1,48 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The Podman compute driver, launched as a subprocess. +//! +//! The `openshell-driver-podman` subprocess owns its +//! `[openshell.drivers.podman]` table. The gateway reads only the keys it +//! owns and forwards the rest as TOML text on stdin; see +//! [`crate::local_driver`]. + +use openshell_server::{DriverDetection, DriverDetectionContext}; + +use crate::launcher::UnavailableRetry; +use crate::local_driver::{BACKEND_RETRY_DELAY, LocalDriver}; + +/// How many times a named Podman is started while its socket is unreachable. +/// This keeps the bounded tolerance the in-process driver had, such as +/// `podman.socket` restarting during a package upgrade. +const START_ATTEMPTS: u32 = 6; + +pub const PODMAN: LocalDriver = LocalDriver { + name: "podman", + drop_legacy_keys: drop_legacy_gateway_port, + retry_unavailable: Some(UnavailableRetry { + attempts: START_ATTEMPTS, + delay: BACKEND_RETRY_DELAY, + }), +}; + +/// `main` accepted `gateway_port` and overwrote it with the gateway's +/// listening port. The driver now rejects the key, so the gateway drops it, +/// warning once, and never treats it as an override. +fn drop_legacy_gateway_port(table: &mut toml::map::Map) { + if table.remove("gateway_port").is_some() { + tracing::warn!( + "[openshell.drivers.podman].gateway_port is ignored: the gateway supplies its listening port; remove it" + ); + } +} + +/// Detect Podman by starting its driver with the operator's table, so a +/// configured `socket_path` is honoured. +pub fn detect(context: &DriverDetectionContext<'_>) -> DriverDetection { + PODMAN.detect(context, &LocalDriver::socket_dir()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-gateway/src/podman/tests.rs b/crates/openshell-gateway/src/podman/tests.rs new file mode 100644 index 0000000000..0d3adb289e --- /dev/null +++ b/crates/openshell-gateway/src/podman/tests.rs @@ -0,0 +1,190 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::io::Write as _; +use std::os::unix::fs::OpenOptionsExt as _; + +use std::path::{Path, PathBuf}; + +use super::*; + +fn table(text: &str) -> toml::map::Map { + toml::from_str(text).unwrap() +} + +/// Write an executable script by writing and closing a temporary file, then +/// renaming it into place, so it is never executed while open for writing. +fn driver(dir: &Path, body: &str) { + let temporary = dir.join("driver.tmp"); + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o755) + .open(&temporary) + .unwrap(); + file.write_all(format!("#!/bin/sh\n{body}\n").as_bytes()) + .unwrap(); + file.sync_all().unwrap(); + drop(file); + std::fs::rename(temporary, dir.join("openshell-driver-podman")).unwrap(); +} + +fn detect_with(body: &str, extra: &str) -> DriverDetection { + let dir = tempfile::tempdir().unwrap(); + driver(dir.path(), body); + let table = table(extra); + PODMAN.detect( + &DriverDetectionContext { + table: &table, + driver_dir: Some(dir.path()), + gateway_log_level: "info", + }, + &dir.path().join("run"), + ) +} + +#[test] +fn gateway_owned_keys_are_removed_and_the_rest_is_forwarded() { + let plan = PODMAN.plan( + table( + "driver_dir = \"/opt/drivers\"\nsocket_path = \"/run/podman.sock\"\nnetwork_name = \"n\"", + ), + None, + ) + .unwrap(); + + assert_eq!(plan.driver_dir, Some(PathBuf::from("/opt/drivers"))); + let forwarded = table(&plan.table); + assert!(!forwarded.contains_key("driver_dir")); + assert_eq!(forwarded["socket_path"].as_str(), Some("/run/podman.sock")); + assert_eq!(forwarded["network_name"].as_str(), Some("n")); + assert!(PODMAN.plan(table("driver_dir = 3"), None).is_err()); +} + +#[test] +fn detection_runs_the_driver_with_the_operators_table() { + // The fake exits "unavailable" and says which table it received. + let body = "grep -q 'socket_path = \"/run/user/1/podman.sock\"' || { \ + printf '{\"result\":\"unavailable\",\"reason\":\"wrong table\"}\\n'; exit 69; }\n\ + printf '{\"result\":\"unavailable\",\"reason\":\"right table\"}\\n'; exit 69"; + assert!(matches!( + detect_with(body, "socket_path = \"/run/user/1/podman.sock\""), + DriverDetection::Unavailable(reason) if reason == "right table" + )); + assert!(matches!( + detect_with(body, ""), + DriverDetection::Unavailable(reason) if reason == "wrong table" + )); +} + +#[test] +fn detection_reports_an_invalid_table_so_the_next_candidate_can_be_tried() { + let body = "printf '{\"result\":\"invalid_config\",\"reason\":\"unknown key\"}\\n'\nexit 78"; + assert!(matches!( + detect_with(body, ""), + DriverDetection::InvalidConfig(reason) if reason == "unknown key" + )); +} + +#[test] +fn detection_keeps_the_driver_it_started_and_stops_it_if_unused() { + // The fake binds the socket named on its command line, as `serve` does. + if !Path::new("/usr/bin/python3").exists() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let bin = dir.path().join("bin"); + std::fs::create_dir(&bin).unwrap(); + let pid_file = dir.path().join("pid"); + driver( + &bin, + &format!( + "echo $$ > '{}'\nexec /usr/bin/python3 -c \"import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); s.listen(); import time; time.sleep(30)\" \"$3\"", + pid_file.display() + ), + ); + let table = table(""); + let context = DriverDetectionContext { + table: &table, + driver_dir: Some(&bin), + gateway_log_level: "info", + }; + + let result = PODMAN.detect(&context, &dir.path().join("run")); + + let DriverDetection::Available(Some(detected)) = result else { + panic!("a driver that binds its socket is available and kept"); + }; + let pid = std::fs::read_to_string(&pid_file).unwrap(); + let alive = || { + std::process::Command::new("kill") + .args(["-0", pid.trim()]) + .stderr(std::process::Stdio::null()) + .status() + .unwrap() + .success() + }; + assert!( + alive(), + "the detected driver keeps running until it is built" + ); + + // Dropping it without building stops it. + drop(detected); + std::thread::sleep(std::time::Duration::from_millis(200)); + assert!(!alive(), "an unused detected driver must be stopped"); +} + +#[test] +fn a_missing_driver_binary_is_unavailable() { + let dir = tempfile::tempdir().unwrap(); + let table = table(""); + let result = PODMAN.detect( + &DriverDetectionContext { + table: &table, + driver_dir: Some(dir.path()), + gateway_log_level: "info", + }, + &dir.path().join("run"), + ); + assert!(matches!(result, DriverDetection::Unavailable(reason) if reason.contains("not found"))); +} + +#[test] +fn the_admission_policy_is_not_forwarded_in_the_driver_table() { + let plan = PODMAN.plan( + table("allow_driver_config = true\n[resource_admission]\nenabled = false\nrequired_labels = {}\n"), + None, + ) + .unwrap(); + assert!( + !plan.table.contains("allow_driver_config"), + "{}", + plan.table + ); + assert!(!plan.table.contains("resource_admission"), "{}", plan.table); +} + +#[test] +fn a_legacy_gateway_port_is_dropped_so_the_driver_can_stay_strict() { + let plan = PODMAN + .plan( + table("gateway_port = 8080\nsocket_path = \"/run/podman.sock\""), + None, + ) + .unwrap(); + assert!(!plan.table.contains("gateway_port"), "{}", plan.table); + assert!(plan.table.contains("socket_path")); +} + +#[test] +fn a_launch_error_stops_detection_instead_of_looking_like_an_absent_backend() { + let dir = tempfile::tempdir().unwrap(); + // Exit status 1 is an internal failure, whatever the driver claims. + let result = detect_with( + "printf '{\"result\":\"unavailable\",\"reason\":\"claims absent\"}\\n'\nexit 1", + "", + ); + drop(dir); + assert!(matches!(result, DriverDetection::Failed(reason) if reason.contains("claims absent"))); +} diff --git a/crates/openshell-gateway/src/vm.rs b/crates/openshell-gateway/src/vm.rs index ff7d458719..45828bda18 100644 --- a/crates/openshell-gateway/src/vm.rs +++ b/crates/openshell-gateway/src/vm.rs @@ -1,140 +1,79 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! VM compute driver plumbing. +//! VM compute driver launch. //! -//! This module owns everything needed to hand the gateway a `Channel` speaking -//! the `openshell.compute.v1.ComputeDriver` RPC surface against an -//! `openshell-driver-vm` subprocess over a Unix domain socket: -//! -//! - [`VmComputeConfig`]: gateway-local configuration (state dir, driver binary, -//! VM shape, guest TLS material). -//! - [`spawn`]: spawn the driver subprocess, wait for its UDS to be ready, -//! and return a live gRPC channel plus a [`ManagedDriverProcess`] handle -//! that will reap the subprocess and clean up the socket on drop. -//! - Helpers to resolve the driver binary, compute the socket path, and -//! validate guest TLS material when the gateway runs an `https://` control -//! plane. -//! -//! The VM-driver fields deliberately live here rather than in -//! [`openshell_core::Config`] so the shared core stays free of driver-specific -//! plumbing. -//! -//! 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. +//! The `openshell-driver-vm` subprocess owns its `[openshell.drivers.vm]` +//! table. This module reads only the two gateway-owned keys, `driver_dir` and +//! `state_dir`, forwards the rest as TOML text on stdin, and launches the +//! driver through [`crate::launcher`]. -#[cfg(unix)] -use hyper_util::rt::TokioIo; -#[cfg(unix)] -use openshell_core::proto::compute::v1::{ - GetCapabilitiesRequest, compute_driver_client::ComputeDriverClient, -}; -use openshell_core::sandbox_env::{self, OtlpExport, OtlpProtocol}; -use openshell_core::{Error, NetworkSupervisorTrustBundle, Result, UpstreamProxyConfig}; -#[cfg(unix)] -use openshell_otel::TraceContextInterceptor; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; +use std::path::{Path, PathBuf}; + +use openshell_core::{Error, Result}; 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)] -use std::path::Path; -use std::path::PathBuf; -#[cfg(unix)] -use std::{io::ErrorKind, process::Stdio, sync::Arc, time::Duration}; -#[cfg(unix)] -use tokio::net::UnixStream; -#[cfg(unix)] -use tokio::process::Command; -use tonic::transport::Channel; -#[cfg(unix)] -use tonic::transport::Endpoint; -#[cfg(unix)] -use tower::service_fn; + +use crate::launcher::{self, ConfigureInputs, LaunchOutcome, LaunchRequest, PreflightFailure}; const DRIVER_BIN_NAME: &str = "openshell-driver-vm"; const COMPUTE_DRIVER_SOCKET_RUN_DIR: &str = "run"; -const COMPUTE_DRIVER_SOCKET_NAME: &str = "compute-driver.sock"; +const DRIVER_BIN_HINT: &str = "set driver_dir in [openshell.gateway], install it in a conventional libexec path such as ~/.local/libexec/openshell, /usr/libexec/openshell, or /usr/local/libexec{,/openshell}, or place it next to the gateway binary"; -/// Configuration for launching and talking to the VM compute driver. -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] -#[serde(default, deny_unknown_fields)] -pub struct VmComputeConfig { - pub allow_driver_config: bool, - pub resource_admission: openshell_core::resource_admission::ResourceAdmissionConfig, - /// Working directory for VM driver sandbox state. - pub state_dir: PathBuf, - - /// Directory to search for compute-driver binaries before the gateway - /// falls back to its conventional install paths and sibling binary. +/// The gateway's view of the `[openshell.drivers.vm]` table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VmLaunchPlan { + /// Where to look for the driver binary before the conventional locations. pub driver_dir: Option, + /// The driver's state directory, under which the gateway keeps the + /// private socket directory. + pub state_dir: PathBuf, + /// The table to forward, without gateway-owned keys. + pub table: String, +} + +impl VmLaunchPlan { + /// Split gateway-owned keys from the table the driver will parse. + /// + /// `gateway_driver_dir` is `driver_dir` from `[openshell.gateway]`. A + /// `driver_dir` in the driver table is deprecated: it is removed with a + /// warning and used only when the gateway section sets none. + pub fn from_table( + mut table: toml::map::Map, + gateway_driver_dir: Option<&Path>, + ) -> Result { + let path_key = |table: &toml::map::Map, key: &str| { + table + .get(key) + .map(|value| { + value.as_str().map(PathBuf::from).ok_or_else(|| { + Error::config(format!("[openshell.drivers.vm].{key} must be a string")) + }) + }) + .transpose() + }; + let legacy_driver_dir = path_key(&table, "driver_dir")?; + if table.remove("driver_dir").is_some() { + tracing::warn!( + "[openshell.drivers.vm].driver_dir is deprecated; set driver_dir in [openshell.gateway]" + ); + } + let driver_dir = gateway_driver_dir + .map(Path::to_path_buf) + .or(legacy_driver_dir); + let state_dir = path_key(&table, "state_dir")? + .filter(|dir| !dir.as_os_str().is_empty()) + .unwrap_or_else(Self::default_state_dir); + launcher::strip_gateway_owned_keys(&mut table); + let table = toml::to_string(&table) + .map_err(|error| Error::config(format!("invalid vm driver table: {error}")))?; + Ok(Self { + driver_dir, + state_dir, + table, + }) + } - /// Default sandbox image the driver should use when a request omits one. - pub default_image: String, - - /// Gateway gRPC endpoint the sandbox guest connects back to. - pub grpc_endpoint: String, - - /// Bootstrap image used to boot and prepare VM sandbox target images. - pub bootstrap_image: String, - - /// libkrun log level used by the VM driver helper. - pub krun_log_level: u32, - - /// Default vCPU count for VM sandboxes. - pub vcpus: u8, - - /// Default memory allocation for VM sandboxes, in MiB. - pub mem_mib: u32, - - /// Writable overlay disk size for each VM sandbox, in MiB. - pub overlay_disk_mib: u64, - - /// Optional UID override for the VM guest sandbox account. - pub sandbox_uid: Option, - - /// Optional GID override for the VM guest sandbox account. - pub sandbox_gid: Option, - - /// Directory shared with the gateway for request-scoped rootfs tar staging. - pub rootfs_tar_staging_dir: Option, - - /// Maximum accepted rootfs tar size, in bytes, before and after decompression. - pub rootfs_tar_max_bytes: Option, - - /// Host-side CA certificate used to authenticate the gateway. - pub guest_tls_ca: Option, - - /// Corporate forward-proxy settings passed to the VM driver. Flattening - /// preserves the shared local-driver TOML field names. - #[serde(flatten)] - pub upstream_proxy: UpstreamProxyConfig, - - /// Policy DNS IPv6 egress mode and NAT64 prefixes passed to the VM - /// driver for its host-side supervisors. - #[serde(flatten)] - pub ipv6_egress: openshell_core::SupervisorIpv6EgressConfig, - - /// Path on the gateway host to a PEM CA bundle trusted for the corporate - /// proxy and for server certificates re-signed by a TLS-intercepting proxy. - pub proxy_ca_bundle: Option, - - /// Explicit guest-reachable SPIFFE Workload API TCP listener. VM guests - /// cannot receive a host UNIX socket, so this requires acknowledgement. - pub provider_spiffe_workload_api_tcp_endpoint: Option, - #[serde(default)] - pub provider_spiffe_allow_guest_tcp: bool, - - /// Allow bind-mounting host directories into VM sandboxes. - #[serde(default)] - pub enable_bind_mounts: bool, -} - -impl VmComputeConfig { /// Default working directory for VM driver state. #[must_use] pub fn default_state_dir() -> PathBuf { @@ -144,245 +83,35 @@ impl VmComputeConfig { ) } - /// Default libkrun log level. - #[must_use] - pub const fn default_krun_log_level() -> u32 { - 1 - } - - /// Default vCPU count. - #[must_use] - pub const fn default_vcpus() -> u8 { - 2 - } - - /// Default memory allocation, in MiB. - #[must_use] - pub const fn default_mem_mib() -> u32 { - 2048 - } - - /// Default writable overlay disk size, in MiB. - #[must_use] - pub const fn default_overlay_disk_mib() -> u64 { - 4096 - } - - /// Validate startup configuration without resolving binaries, creating - /// state directories, spawning a process, or connecting a socket. - pub fn validate_configuration(&self) -> Result<()> { - self.resource_admission.validate().map_err(Error::config)?; - if self.grpc_endpoint.trim().is_empty() { - return Err(Error::config( - "grpc_endpoint is required when using the vm compute driver", - )); - } - if self.bootstrap_image.trim().is_empty() && self.default_image.trim().is_empty() { - return Err(Error::config( - "bootstrap_image or default_image is required when using the vm compute driver; sandbox images cannot be used as VM bootstrap images", - )); - } - validate_vm_sandbox_identity(self)?; - if self - .rootfs_tar_staging_dir - .as_ref() - .is_some_and(|path| path.as_os_str().is_empty()) - { - return Err(Error::config( - "rootfs_tar_staging_dir must not be empty when set", - )); - } - if self.rootfs_tar_max_bytes == Some(0) { - return Err(Error::config( - "rootfs_tar_max_bytes must be greater than zero when set", - )); - } - self.validate_proxy_config()?; - if let Some(endpoint) = self.provider_spiffe_workload_api_tcp_endpoint.as_deref() { - openshell_core::driver_utils::validate_guest_spiffe_tcp_endpoint( - endpoint, - self.provider_spiffe_allow_guest_tcp, - ) - .map_err(Error::config)?; - } else if self.provider_spiffe_allow_guest_tcp { - return Err(Error::config( - "provider_spiffe_allow_guest_tcp is set but no provider_spiffe_workload_api_tcp_endpoint is configured", - )); - } - Ok(()) + fn socket_dir(&self) -> PathBuf { + self.state_dir.join(COMPUTE_DRIVER_SOCKET_RUN_DIR) } - - fn validate_proxy_config(&self) -> Result<()> { - self.upstream_proxy.validate().map_err(Error::config)?; - self.ipv6_egress.validate().map_err(Error::config)?; - if let Some(path) = self.proxy_ca_bundle.as_ref() { - if path.as_os_str().is_empty() { - return Err(Error::config("proxy_ca_bundle must not be empty when set")); - } - if self.upstream_proxy.https_proxy.is_none() { - return Err(Error::config( - "proxy_ca_bundle is set but no https_proxy is configured", - )); - } - } - Ok(()) - } - - #[must_use] - fn default_driver_search_dirs(home: Option) -> Vec { - let mut dirs = Vec::new(); - if let Some(home) = home { - dirs.push(home.join(".local").join("libexec").join("openshell")); - } - push_unique_path(&mut dirs, PathBuf::from("/usr/libexec/openshell")); - push_unique_path(&mut dirs, PathBuf::from("/usr/local/libexec/openshell")); - push_unique_path(&mut dirs, PathBuf::from("/usr/local/libexec")); - dirs - } -} - -impl Default for VmComputeConfig { - fn default() -> Self { - Self { - state_dir: Self::default_state_dir(), - allow_driver_config: false, - resource_admission: - openshell_core::resource_admission::ResourceAdmissionConfig::default(), - driver_dir: None, - default_image: openshell_core::image::default_sandbox_image(), - grpc_endpoint: String::new(), - bootstrap_image: String::new(), - krun_log_level: Self::default_krun_log_level(), - vcpus: Self::default_vcpus(), - mem_mib: Self::default_mem_mib(), - overlay_disk_mib: Self::default_overlay_disk_mib(), - sandbox_uid: None, - sandbox_gid: None, - rootfs_tar_staging_dir: None, - rootfs_tar_max_bytes: None, - guest_tls_ca: None, - upstream_proxy: UpstreamProxyConfig::default(), - ipv6_egress: openshell_core::SupervisorIpv6EgressConfig::default(), - proxy_ca_bundle: None, - provider_spiffe_workload_api_tcp_endpoint: None, - provider_spiffe_allow_guest_tcp: false, - enable_bind_mounts: false, - } - } -} - -#[cfg(unix)] -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct VmGuestTlsPaths { - pub ca: PathBuf, } -/// Resolve the `openshell-driver-vm` binary path. +/// Resolve the trusted `openshell-driver-vm` binary. /// -/// Resolution order: -/// 1. `{driver_dir}/openshell-driver-vm`, where `driver_dir` comes from -/// `[openshell.drivers.vm].driver_dir`. -/// 2. Conventional install directories: -/// `~/.local/libexec/openshell`, `/usr/libexec/openshell`, -/// `/usr/local/libexec/openshell`, `/usr/local/libexec`. -/// 3. Sibling of the gateway's own executable (last-resort fallback so -/// local development builds still work out of the box). -pub fn resolve_compute_driver_bin(vm_config: &VmComputeConfig) -> Result { - let mut searched: Vec = Vec::new(); - - // 1. Configured driver directory, or the conventional install locations - // when no explicit override is configured. - for dir in resolve_driver_search_dirs(vm_config) { - let candidate = dir.join(DRIVER_BIN_NAME); - if candidate.is_file() { - return Ok(candidate); - } - push_unique_path(&mut searched, candidate); - } - - // 2. Sibling-of-gateway fallback. - let current_exe = std::env::current_exe() - .map_err(|e| Error::config(format!("failed to resolve current executable: {e}")))?; - let Some(parent) = current_exe.parent() else { - return Err(Error::config(format!( - "current executable '{}' has no parent directory", - current_exe.display() - ))); - }; - let sibling = parent.join(DRIVER_BIN_NAME); - if sibling.is_file() { - return Ok(sibling); - } - push_unique_path(&mut searched, sibling); - - let searched_display = searched - .iter() - .map(|p| format!("'{}'", p.display())) - .collect::>() - .join(", "); - Err(Error::config(format!( - "vm compute driver binary not found (searched {searched_display}); install it under [openshell.drivers.vm].driver_dir, a conventional libexec path such as ~/.local/libexec/openshell, /usr/libexec/openshell, or /usr/local/libexec{{,/openshell}}, or place it next to the gateway binary" - ))) -} - -fn resolve_driver_search_dirs(vm_config: &VmComputeConfig) -> Vec { - vm_config.driver_dir.clone().map_or_else( - || { - let mut dirs = Vec::new(); - if let Ok(current_exe) = std::env::current_exe() - && let Some(prefix) = current_exe.parent().and_then(Path::parent) - { - push_unique_path(&mut dirs, prefix.join("libexec")); - push_unique_path(&mut dirs, prefix.join("libexec").join("openshell")); - } - for dir in VmComputeConfig::default_driver_search_dirs( - std::env::var_os("HOME").map(PathBuf::from), - ) { - push_unique_path(&mut dirs, dir); - } - dirs - }, - |dir| vec![dir], +/// Resolution order: `driver_dir` from `[openshell.drivers.vm]`, or when it +/// is unset the conventional install directories, then the directory of the +/// gateway's own executable so development builds work out of the box. +pub fn resolve_compute_driver_bin(driver_dir: Option<&Path>) -> Result { + launcher::resolve_binary( + DRIVER_BIN_NAME, + &launcher::driver_search_dirs(driver_dir), + DRIVER_BIN_HINT, ) } -fn push_unique_path(paths: &mut Vec, path: PathBuf) { - if !paths.iter().any(|existing| existing == &path) { - paths.push(path); - } -} - -/// Path of the Unix domain socket the driver will listen on. -pub fn compute_driver_socket_path(vm_config: &VmComputeConfig) -> PathBuf { - vm_config - .state_dir - .join(COMPUTE_DRIVER_SOCKET_RUN_DIR) - .join(COMPUTE_DRIVER_SOCKET_NAME) -} - -#[cfg(unix)] -fn prepare_compute_driver_socket_path( - vm_config: &VmComputeConfig, - socket_path: &Path, -) -> Result<()> { - let expected_uid = current_euid(); - prepare_vm_state_dir(&vm_config.state_dir, expected_uid)?; - let parent = socket_path.parent().ok_or_else(|| { - Error::execution(format!( - "vm compute driver socket path '{}' has no parent directory", - socket_path.display() - )) - })?; - prepare_private_socket_dir(parent, expected_uid)?; - remove_stale_socket(socket_path, expected_uid) -} - -#[cfg(unix)] -fn current_euid() -> u32 { - rustix::process::geteuid().as_raw() +/// Validate the table with the driver's own `preflight`, which contacts no +/// backend and creates no state. +pub fn validate(plan: &VmLaunchPlan) -> Result<()> { + let binary = resolve_compute_driver_bin(plan.driver_dir.as_deref())?; + launcher::preflight(&binary, &plan.table).map_err(|failure| match failure { + PreflightFailure::InvalidConfig(reason) | PreflightFailure::Error(reason) => { + Error::config(format!("invalid [openshell.drivers.vm] table: {reason}")) + } + }) } -#[cfg(unix)] fn prepare_vm_state_dir(state_dir: &Path, expected_uid: u32) -> Result<()> { std::fs::create_dir_all(state_dir).map_err(|err| { Error::execution(format!( @@ -391,8 +120,7 @@ fn prepare_vm_state_dir(state_dir: &Path, expected_uid: u32) -> Result<()> { )) })?; let metadata = checked_directory_metadata(state_dir, expected_uid, "vm driver state dir")?; - let mode = metadata.permissions().mode() & 0o777; - if mode != 0o700 { + if metadata.permissions().mode() & 0o777 != 0o700 { std::fs::set_permissions(state_dir, std::fs::Permissions::from_mode(0o700)).map_err( |err| { Error::execution(format!( @@ -405,24 +133,6 @@ fn prepare_vm_state_dir(state_dir: &Path, expected_uid: u32) -> Result<()> { Ok(()) } -#[cfg(unix)] -fn prepare_private_socket_dir(socket_dir: &Path, expected_uid: u32) -> Result<()> { - std::fs::create_dir_all(socket_dir).map_err(|err| { - Error::execution(format!( - "failed to create vm compute driver socket dir '{}': {err}", - socket_dir.display() - )) - })?; - let _ = checked_directory_metadata(socket_dir, expected_uid, "vm compute driver socket dir")?; - std::fs::set_permissions(socket_dir, std::fs::Permissions::from_mode(0o700)).map_err(|err| { - Error::execution(format!( - "failed to restrict vm compute driver socket dir '{}': {err}", - socket_dir.display() - )) - }) -} - -#[cfg(unix)] fn checked_directory_metadata( path: &Path, expected_uid: u32, @@ -458,1182 +168,47 @@ fn checked_directory_metadata( Ok(metadata) } -#[cfg(unix)] -fn remove_stale_socket(socket_path: &Path, expected_uid: u32) -> Result<()> { - let metadata = match std::fs::symlink_metadata(socket_path) { - Ok(metadata) => metadata, - Err(err) if err.kind() == ErrorKind::NotFound => return Ok(()), - Err(err) => { - return Err(Error::execution(format!( - "failed to stat vm compute driver socket '{}': {err}", - socket_path.display() - ))); - } - }; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - return Err(Error::execution(format!( - "vm compute driver socket '{}' is a symlink; refusing to remove it", - socket_path.display() - ))); - } - if metadata.uid() != expected_uid { - return Err(Error::execution(format!( - "vm compute driver socket '{}' is owned by uid {} but current euid is {}", - socket_path.display(), - metadata.uid(), - expected_uid - ))); - } - if !file_type.is_socket() { - return Err(Error::execution(format!( - "vm compute driver socket path '{}' exists but is not a Unix socket", - socket_path.display() - ))); - } - std::fs::remove_file(socket_path).map_err(|err| { - Error::execution(format!( - "failed to remove stale vm compute driver socket '{}': {err}", - socket_path.display() - )) - }) -} - -#[cfg(unix)] -pub fn compute_driver_guest_tls_paths( - vm_config: &VmComputeConfig, -) -> Result> { - if !vm_config.grpc_endpoint.starts_with("https://") { - return Ok(None); - } - - if vm_config.guest_tls_ca.is_none() { - return Err(Error::config( - "vm compute driver requires guest_tls_ca when grpc_endpoint uses https://", - )); - } - - let Some(ca) = vm_config.guest_tls_ca.clone() else { - return Err(Error::config( - "guest_tls_ca is required when VM guest TLS materials are configured", - )); - }; - for path in [&ca] { - if !path.is_file() { - return Err(Error::config(format!( - "vm guest TLS material '{}' does not exist or is not a file", - path.display() - ))); - } - } - - Ok(Some(VmGuestTlsPaths { ca })) -} - -/// Launch the VM compute-driver subprocess, wait for its UDS to come up, -/// and return a gRPC `Channel` connected to it plus a process handle that -/// kills the subprocess and removes the socket on drop. -#[cfg(unix)] +/// Launch the VM compute driver, configure it, and return a gRPC channel +/// connected to it with a handle that stops it when dropped. +#[tracing::instrument( + name = "driver.launch", + skip_all, + fields(otel.name = "driver.launch", otel.status_code = tracing::field::Empty, driver.name = "vm") +)] pub async fn spawn( + plan: &VmLaunchPlan, gateway_log_level: &str, - gateway_name: &str, - vm_config: &VmComputeConfig, - otlp_config: Option<&OtlpConfig>, - additional_ca_bundle: Option<&NetworkSupervisorTrustBundle>, + inputs: &ConfigureInputs<'_>, ) -> Result { - vm_config.validate_configuration()?; - let driver_bin = resolve_compute_driver_bin(vm_config)?; - let socket_path = compute_driver_socket_path(vm_config); - let guest_tls_paths = compute_driver_guest_tls_paths(vm_config)?; - prepare_compute_driver_socket_path(vm_config, &socket_path)?; - - let mut command = Command::new(&driver_bin); - command.kill_on_drop(true); - command.stdin(Stdio::null()); - command.stdout(Stdio::inherit()); - command.stderr(Stdio::inherit()); - command.arg("--bind-socket").arg(&socket_path); - command.arg("--admission-config-json").arg( - serde_json::to_string(&openshell_core::resource_admission::DriverAdmissionConfig { - allow_driver_config: vm_config.allow_driver_config, - resource_admission: vm_config.resource_admission.clone(), - }) - .map_err(|error| Error::config(error.to_string()))?, - ); - command - .arg("--expected-peer-pid") - .arg(std::process::id().to_string()); - command.arg("--log-level").arg(gateway_log_level); - append_otlp_args(&mut command, otlp_config, gateway_name); - command.arg("--grpc-endpoint").arg(&vm_config.grpc_endpoint); - command.arg("--state-dir").arg(&vm_config.state_dir); - if !vm_config.default_image.trim().is_empty() { - command.arg("--default-image").arg(&vm_config.default_image); - } - if !vm_config.bootstrap_image.trim().is_empty() { - command - .arg("--bootstrap-image") - .arg(&vm_config.bootstrap_image); - } - command - .arg("--krun-log-level") - .arg(vm_config.krun_log_level.to_string()); - command.arg("--vcpus").arg(vm_config.vcpus.to_string()); - command.arg("--mem-mib").arg(vm_config.mem_mib.to_string()); - command - .arg("--overlay-disk-mib") - .arg(vm_config.overlay_disk_mib.to_string()); - append_vm_identity_args(&mut command, vm_config); - append_vm_rootfs_tar_args(&mut command, vm_config); - if let Some(tls) = guest_tls_paths { - command.arg("--guest-tls-ca").arg(tls.ca); - } - append_vm_proxy_and_spiffe_args(&mut command, vm_config); - append_vm_network_trust_args(&mut command, additional_ca_bundle); - if vm_config.enable_bind_mounts { - command.arg("--enable-bind-mounts"); - } - - let mut child = command.spawn().map_err(|e| { - Error::execution(format!( - "failed to launch vm compute driver '{}': {e}", - driver_bin.display() - )) - })?; - let channel = wait_for_compute_driver(&socket_path, &mut child).await?; - let process = Arc::new(ManagedDriverProcess::new(child, socket_path)); - Ok(AcquiredRemoteDriverEndpoint::managed( - "vm", channel, process, - )) -} - -fn validate_vm_sandbox_identity(config: &VmComputeConfig) -> Result<()> { - let range = openshell_policy::MIN_SANDBOX_UID..=openshell_policy::MAX_SANDBOX_UID; - for (field, value) in [ - ("sandbox_uid", config.sandbox_uid), - ("sandbox_gid", config.sandbox_gid), - ] { - if let Some(value) = value - && !range.contains(&value) - { - return Err(Error::config(format!( - "{field} {value} is outside the allowed range [{}, {}]", - openshell_policy::MIN_SANDBOX_UID, - openshell_policy::MAX_SANDBOX_UID - ))); - } - } - Ok(()) -} - -#[cfg(unix)] -fn append_vm_identity_args(command: &mut Command, config: &VmComputeConfig) { - if let Some(uid) = config.sandbox_uid { - command.arg("--sandbox-uid").arg(uid.to_string()); - } - if let Some(gid) = config.sandbox_gid { - command.arg("--sandbox-gid").arg(gid.to_string()); - } -} - -#[cfg(unix)] -fn append_vm_rootfs_tar_args(command: &mut Command, config: &VmComputeConfig) { - if let Some(path) = config.rootfs_tar_staging_dir.as_ref() { - command.arg("--rootfs-tar-staging-dir").arg(path); - } - if let Some(max_bytes) = config.rootfs_tar_max_bytes { - command - .arg("--rootfs-tar-max-bytes") - .arg(max_bytes.to_string()); - } -} - -#[cfg(unix)] -fn append_vm_network_trust_args( - command: &mut Command, - bundle: Option<&NetworkSupervisorTrustBundle>, -) { - if let Some(bundle) = bundle { - // Only stable, non-secret artifact metadata crosses the process - // boundary. The child reads and verifies the bounded artifact once, - // then retains its own immutable snapshot for sandbox launches. - command - .arg("--additional-ca-bundle") - .arg(bundle.artifact_path()); - command.arg("--additional-ca-digest").arg(bundle.digest()); - command - .arg("--additional-ca-certificate-count") - .arg(bundle.certificate_count().to_string()); - } -} - -#[cfg(unix)] -fn append_vm_proxy_and_spiffe_args(command: &mut Command, config: &VmComputeConfig) { - let proxy = &config.upstream_proxy; - if let Some(url) = proxy.https_proxy.as_ref() { - command.arg("--upstream-proxy").arg(url); - } - if let Some(no_proxy) = proxy.no_proxy.as_ref() { - command.arg("--upstream-no-proxy").arg(no_proxy); - } - if let Some(auth_file) = proxy.proxy_auth_file.as_ref() { - command.arg("--upstream-proxy-auth-file").arg(auth_file); - } - if proxy.proxy_auth_allow_insecure == Some(true) { - command.arg("--upstream-proxy-auth-allow-insecure"); - } - if proxy.proxy_connect_by_hostname == Some(true) { - command.arg("--upstream-proxy-connect-by-hostname"); - } - if let Some(path) = config.proxy_ca_bundle.as_ref() { - command.arg("--upstream-proxy-ca-bundle").arg(path); - } - // The VM driver accepts the supervisor's flag names and forwards them. - command.args(config.ipv6_egress.supervisor_args()); - if let Some(endpoint) = config.provider_spiffe_workload_api_tcp_endpoint.as_ref() { - command - .arg("--provider-spiffe-workload-api-tcp-endpoint") - .arg(endpoint); - command.arg("--provider-spiffe-allow-guest-tcp"); - } -} - -fn append_otlp_export_args( - command: &mut Command, - export: Option<&OtlpExport>, - endpoint_flag: &str, - protocol_flag: &str, -) { - if let Some(export) = export { - command - .arg(format!("--{endpoint_flag}")) - .arg(&export.endpoint); - if export.protocol != OtlpProtocol::Grpc { - command - .arg(format!("--{protocol_flag}")) - .arg(export.protocol.as_str()); - } - } -} - -fn append_otlp_args(command: &mut Command, otlp_config: Option<&OtlpConfig>, gateway_name: &str) { - let otlp = otlp_config - .map(OtlpConfig::supervisor_otlp) - .unwrap_or_default(); - append_otlp_export_args( - command, - otlp.traces.as_ref(), - sandbox_env::OTLP_ENDPOINT_FLAG, - sandbox_env::OTLP_PROTOCOL_FLAG, - ); - append_otlp_export_args( - command, - otlp.ocsf.as_ref(), - sandbox_env::OTLP_OCSF_ENDPOINT_FLAG, - sandbox_env::OTLP_OCSF_PROTOCOL_FLAG, - ); - append_otlp_export_args( - command, - otlp.agent.as_ref(), - sandbox_env::OTLP_AGENT_ENDPOINT_FLAG, - sandbox_env::OTLP_AGENT_PROTOCOL_FLAG, - ); - if let Some(traces) = otlp_config.and_then(|otlp| otlp.traces.as_ref()) { - let collector = &traces.collector; - for (flag, path) in [ - (sandbox_env::OTLP_CA_FILE_FLAG, collector.ca_file()), - (sandbox_env::OTLP_CERT_FILE_FLAG, collector.cert_file()), - (sandbox_env::OTLP_KEY_FILE_FLAG, collector.key_file()), - ] { - if let Some(path) = path { - command.arg(format!("--{flag}")).arg(path); - } - } - } - // The driver's own trace exporter reads this like any OTLP SDK; keeping - // it out of the arguments keeps the headers out of process listings. - if let Some(headers) = openshell_server::gateway_trace_headers(otlp_config) { - command.env("OTEL_EXPORTER_OTLP_TRACES_HEADERS", headers.expose_secret()); - } - // The driver names its own spans with the gateway name, and supervisors - // name their spans, OCSF records, and relayed traces with it. - if !otlp.is_empty() { - command.arg("--gateway-name").arg(gateway_name); - } -} - -#[cfg(not(unix))] -pub async fn spawn( - _gateway_log_level: &str, - _gateway_name: &str, - _vm_config: &VmComputeConfig, - _otlp_config: Option<&OtlpConfig>, - _additional_ca_bundle: Option<&NetworkSupervisorTrustBundle>, -) -> Result { - Err(Error::config( - "the vm compute driver requires unix domain socket support", - )) -} - -#[cfg(unix)] -#[tracing::instrument( - name = "driver.wait_for_ready", - skip_all, - fields( - otel.name = "driver.wait_for_ready", - otel.status_code = tracing::field::Empty, - driver.name = "vm", + let binary = resolve_compute_driver_bin(plan.driver_dir.as_deref())?; + prepare_vm_state_dir(&plan.state_dir, rustix::process::geteuid().as_raw())?; + let configure = inputs.request(); + let outcome = launcher::launch( + LaunchRequest { + name: "vm", + binary: &binary, + table: &plan.table, + socket_dir: &plan.socket_dir(), + log_level: gateway_log_level, + }, + configure, + launcher::exit_gateway_on_driver_exit(), ) -)] -async fn wait_for_compute_driver( - socket_path: &Path, - child: &mut tokio::process::Child, -) -> Result { - let mut last_error: Option = None; - for _ in 0..100 { - let try_wait_result = child.try_wait().map_err(|e| { - Error::execution(format!("failed to poll vm compute driver process: {e}")) - })?; - if let Some(status) = try_wait_result { - return Err(Error::execution(format!( - "vm compute driver exited before becoming ready with status {status}" - ))); - } - - match connect_compute_driver(socket_path).await { - Ok(channel) => { - let mut client = - ComputeDriverClient::with_interceptor(channel.clone(), TraceContextInterceptor); - match client - .get_capabilities(tonic::Request::new(GetCapabilitiesRequest { - gateway: Some(openshell_core::extension_protocol::gateway_metadata( - openshell_core::extension_protocol::ExtensionFamily::Compute, - )), - })) - .await - { - Ok(_) => return Ok(channel), - Err(status) => last_error = Some(status.to_string()), - } - } - Err(err) => last_error = Some(err.to_string()), - } - - tokio::time::sleep(Duration::from_millis(100)).await; - } - - Err(Error::execution(format!( - "timed out waiting for vm compute driver socket '{}': {}", - socket_path.display(), - last_error.unwrap_or_else(|| "unknown error".to_string()) - ))) -} - -#[cfg(unix)] -async fn connect_compute_driver(socket_path: &Path) -> Result { - let socket_path = socket_path.to_path_buf(); - let display_path = socket_path.clone(); - Endpoint::from_static("http://[::]:50051") - .connect_with_connector(service_fn(move |_: tonic::transport::Uri| { - let socket_path = socket_path.clone(); - async move { UnixStream::connect(socket_path).await.map(TokioIo::new) } - })) - .await - .map_err(|e| { - Error::execution(format!( - "failed to connect to vm compute driver socket '{}': {e}", - display_path.display() - )) - }) -} - -#[cfg(all(test, unix))] -mod tests { - use super::{ - VmComputeConfig, append_otlp_args, append_vm_identity_args, append_vm_network_trust_args, - append_vm_proxy_and_spiffe_args, append_vm_rootfs_tar_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, - validate_vm_sandbox_identity, - }; - use openshell_core::sandbox_env::OtlpProtocol; - use openshell_core::{NetworkSupervisorTrustBundle, UpstreamProxyConfig}; - use openshell_server::config_file::{ - AgentOtlpConfig, OcsfOtlpConfig, OtlpCollectorConfig, OtlpConfig, OtlpTracesConfig, - }; - use std::os::unix::fs::PermissionsExt; - use std::os::unix::net::UnixListener as StdUnixListener; - use std::path::PathBuf; - use tempfile::tempdir; - - #[test] - fn vm_uses_nvidia_ubuntu_default_image() { - assert_eq!( - VmComputeConfig::default().default_image, - openshell_core::image::DEFAULT_SANDBOX_BASE_IMAGE - ); - } - - #[test] - fn vm_gateway_requires_a_trusted_bootstrap_image_source() { - let config = VmComputeConfig { - grpc_endpoint: "http://127.0.0.1:50051".to_string(), - default_image: String::new(), - bootstrap_image: String::new(), - ..Default::default() - }; - let error = config - .validate_configuration() - .expect_err("the gateway must reject an empty bootstrap configuration"); - assert!(error.to_string().contains("sandbox images cannot be used")); - - VmComputeConfig { - default_image: "openshell/sandbox:default".to_string(), - ..config.clone() - } - .validate_configuration() - .expect("the operator-controlled default image is a valid fallback"); - - VmComputeConfig { - bootstrap_image: "openshell/sandbox-bootstrap:latest".to_string(), - ..config - } - .validate_configuration() - .expect("an explicit bootstrap image is valid"); - } - - #[test] - fn vm_driver_receives_trace_headers_in_its_environment_only() { - crate::test_environment::Environment::new() - .remove("OTEL_EXPORTER_OTLP_HEADERS") - .remove("OTEL_EXPORTER_OTLP_TRACES_HEADERS") - .run(|| { - let otlp: OtlpConfig = toml::from_str( - "endpoint = 'http://collector.internal:4318'\n\ - headers = { authorization = 'Bearer secret-token' }\n", - ) - .unwrap(); - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args(&mut command, Some(&otlp), "production-us-west"); - - let env = command - .as_std() - .get_envs() - .find(|(name, _)| *name == "OTEL_EXPORTER_OTLP_TRACES_HEADERS") - .and_then(|(_, value)| value) - .map(|value| value.to_string_lossy().into_owned()); - assert_eq!(env.as_deref(), Some("authorization=Bearer%20secret-token")); - assert!( - command - .as_std() - .get_args() - .all(|arg| !arg.to_string_lossy().contains("secret-token")) - ); - }); - } - - #[test] - fn vm_driver_receives_the_trace_collectors_tls_file_paths() { - let dir = tempdir().unwrap(); - let certified = rcgen::generate_simple_self_signed(vec!["collector".into()]).unwrap(); - let [ca, cert, key] = ["ca.pem", "client.pem", "client-key.pem"].map(|name| { - let path = dir.path().join(name); - let pem = if name == "client-key.pem" { - certified.signing_key.serialize_pem() - } else { - certified.cert.pem() - }; - std::fs::write(&path, pem).unwrap(); - path - }); - let collector = OtlpCollectorConfig::new("https://collector:4317", OtlpProtocol::Grpc) - .with_tls_files(Some(ca.clone()), Some(cert.clone()), Some(key.clone())) - .unwrap(); - assert!(collector.tls().client_identity().is_some()); - let otlp = OtlpConfig { - metrics: None, - service_name: None, - traces: Some(OtlpTracesConfig { collector }), - ocsf: None, - agent: None, - }; - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args(&mut command, Some(&otlp), "production-us-west"); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - for (flag, path) in [ - ("--otlp-ca-file", ca), - ("--otlp-cert-file", cert), - ("--otlp-key-file", key), - ] { - let pair = [flag.to_string(), path.display().to_string()]; - assert!( - args.windows(2).any(|window| window == pair), - "{pair:?} in {args:?}" - ); - } - } - - #[test] - fn vm_driver_command_includes_gateway_otlp_configuration() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: Some("custom-gateway".to_string()), - traces: Some(OtlpTracesConfig { - collector: OtlpCollectorConfig::new( - "http://collector.internal:4317", - OtlpProtocol::Grpc, - ), - }), - ocsf: None, - agent: None, - }), - "production-us-west", - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--otlp-endpoint", - "http://collector.internal:4317", - "--gateway-name", - "production-us-west" - ] - ); - - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: None, - traces: Some(OtlpTracesConfig { - collector: OtlpCollectorConfig::new( - "http://collector.internal:4318", - OtlpProtocol::HttpProtobuf, - ), - }), - ocsf: None, - agent: None, - }), - "production-us-west", - ); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args[..4], - [ - "--otlp-endpoint", - "http://collector.internal:4318", - "--otlp-protocol", - "http/protobuf", - ] - ); - } - - #[test] - fn vm_driver_command_includes_gateway_ocsf_export() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: None, - traces: None, - ocsf: Some(OcsfOtlpConfig { - collector: OtlpCollectorConfig::new( - "http://siem.internal:4318", - OtlpProtocol::HttpProtobuf, - ), - schema_version: Some("2.0".into()), - }), - agent: None, - }), - "production-us-west", - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--otlp-ocsf-endpoint", - "http://siem.internal:4318", - "--otlp-ocsf-protocol", - "http/protobuf", - "--gateway-name", - "production-us-west" - ] - ); - } - - #[test] - fn vm_driver_command_includes_the_agent_trace_relay() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_otlp_args( - &mut command, - Some(&OtlpConfig { - metrics: None, - service_name: None, - traces: None, - ocsf: None, - agent: Some(AgentOtlpConfig { - collector: OtlpCollectorConfig::new( - "http://agents.internal:4318", - OtlpProtocol::HttpProtobuf, - ), - }), - }), - "production-us-west", - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--otlp-agent-endpoint", - "http://agents.internal:4318", - "--otlp-agent-protocol", - "http/protobuf", - "--gateway-name", - "production-us-west" - ] - ); - } - - #[test] - fn vm_driver_command_forwards_ipv6_egress_settings() { - let config: VmComputeConfig = toml::from_str( - r#" -policy_dns_ipv6_egress = "disabled" -nat64_prefixes = ["2001:db8:64::/96"] -"#, - ) - .expect("VM driver config parses"); - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_proxy_and_spiffe_args(&mut command, &config); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--policy-dns-ipv6-egress", - "disabled", - "--nat64-prefix", - "2001:db8:64::/96" - ] - ); - } - - #[test] - fn vm_driver_command_forwards_corporate_proxy_settings() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_proxy_and_spiffe_args( - &mut command, - &VmComputeConfig { - upstream_proxy: UpstreamProxyConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - no_proxy: Some("10.0.0.0/8".to_string()), - proxy_auth_file: Some(PathBuf::from("/etc/openshell/secrets/proxy-auth")), - proxy_auth_allow_insecure: Some(true), - proxy_connect_by_hostname: Some(true), - }, - proxy_ca_bundle: Some(PathBuf::from("/etc/openshell/tls/proxy-ca.pem")), - provider_spiffe_workload_api_tcp_endpoint: Some("tcp:192.0.2.10:8081".to_string()), - provider_spiffe_allow_guest_tcp: true, - ..VmComputeConfig::default() - }, - ); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--upstream-proxy", - "http://proxy.corp.com:8080", - "--upstream-no-proxy", - "10.0.0.0/8", - "--upstream-proxy-auth-file", - "/etc/openshell/secrets/proxy-auth", - "--upstream-proxy-auth-allow-insecure", - "--upstream-proxy-connect-by-hostname", - "--upstream-proxy-ca-bundle", - "/etc/openshell/tls/proxy-ca.pem", - "--provider-spiffe-workload-api-tcp-endpoint", - "tcp:192.0.2.10:8081", - "--provider-spiffe-allow-guest-tcp", - ] - ); - } - - #[test] - fn vm_driver_command_omits_unset_corporate_proxy_settings() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_proxy_and_spiffe_args(&mut command, &VmComputeConfig::default()); - assert_eq!(command.as_std().get_args().count(), 0); - } - - #[test] - fn vm_driver_command_forwards_only_network_trust_artifact_metadata() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - let pem = - b"-----BEGIN CERTIFICATE-----\nprivate-fixture-bytes\n-----END CERTIFICATE-----\n"; - let bundle = NetworkSupervisorTrustBundle::new( - pem.to_vec(), - 2, - "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - PathBuf::from("/var/lib/openshell/network/additional-ca.crt"), - ); - append_vm_network_trust_args(&mut command, Some(&bundle)); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--additional-ca-bundle", - "/var/lib/openshell/network/additional-ca.crt", - "--additional-ca-digest", - "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", - "--additional-ca-certificate-count", - "2", - ] - ); - assert!(!args.iter().any(|arg| arg == "OPENSHELL_TLS_CA")); - assert!( - !args.iter().any(|arg| arg.contains("private-fixture-bytes")), - "CA material must not cross the process boundary in argv: {args:?}" - ); - - let mut unset = tokio::process::Command::new("openshell-driver-vm"); - append_vm_network_trust_args(&mut unset, None); - assert_eq!(unset.as_std().get_args().count(), 0); - } - - #[test] - fn invalid_corporate_proxy_config_is_rejected_before_the_driver_starts() { - let err = UpstreamProxyConfig { - https_proxy: Some("socks5://proxy.corp.com:1080".to_string()), - ..Default::default() - } - .validate() - .expect_err("only http:// and https:// proxies are supported"); - assert!(err.contains("https_proxy"), "{err}"); - - VmComputeConfig { - proxy_ca_bundle: Some(PathBuf::from("/etc/openshell/tls/proxy-ca.pem")), - ..Default::default() - } - .validate_proxy_config() - .expect_err("a CA bundle without a proxy URL must fail closed"); - - VmComputeConfig { - upstream_proxy: UpstreamProxyConfig { - https_proxy: Some("http://proxy.corp.com:8080".to_string()), - ..Default::default() - }, - ..Default::default() - } - .validate_proxy_config() - .expect("a lone proxy URL is a complete configuration"); - } - - #[test] - fn vm_driver_command_includes_configured_sandbox_identity() { - let mut command = tokio::process::Command::new("openshell-driver-vm"); - let config = VmComputeConfig { - sandbox_uid: Some(2000), - sandbox_gid: Some(3000), - ..Default::default() - }; - - validate_vm_sandbox_identity(&config).expect("valid identity"); - append_vm_identity_args(&mut command, &config); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!(args, ["--sandbox-uid", "2000", "--sandbox-gid", "3000"]); - } - - #[test] - fn vm_gateway_toml_forwards_rootfs_tar_settings() { - let config: VmComputeConfig = toml::from_str( - r#" - grpc_endpoint = "http://127.0.0.1:50051" - rootfs_tar_staging_dir = "/var/lib/openshell/rootfs-tar-staging" - rootfs_tar_max_bytes = 1073741824 - "#, - ) - .expect("schema-v2 VM rootfs tar settings must deserialize"); - config - .validate_configuration() - .expect("rootfs tar settings must pass static validation"); - - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_rootfs_tar_args(&mut command, &config); - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - - assert_eq!( - args, - [ - "--rootfs-tar-staging-dir", - "/var/lib/openshell/rootfs-tar-staging", - "--rootfs-tar-max-bytes", - "1073741824", - ] - ); - } - - #[test] - fn vm_gateway_rejects_zero_rootfs_tar_limit() { - let config = VmComputeConfig { - grpc_endpoint: "http://127.0.0.1:50051".to_string(), - rootfs_tar_max_bytes: Some(0), - ..Default::default() - }; - - let error = config - .validate_configuration() - .expect_err("a zero rootfs tar limit must fail before driver startup"); - assert!(error.to_string().contains("rootfs_tar_max_bytes")); - } - - #[test] - fn vm_driver_command_forwards_proxy_and_spiffe_configuration_without_credentials() { - let config = VmComputeConfig { - upstream_proxy: UpstreamProxyConfig { - https_proxy: Some("https://proxy.internal:8443".to_string()), - no_proxy: Some("localhost,.svc".to_string()), - proxy_auth_file: Some(PathBuf::from("/gateway/secrets/proxy-auth")), - proxy_auth_allow_insecure: Some(true), - proxy_connect_by_hostname: Some(true), - }, - provider_spiffe_workload_api_tcp_endpoint: Some("tcp:192.0.2.10:8081".to_string()), - provider_spiffe_allow_guest_tcp: true, - ..Default::default() - }; - let mut command = tokio::process::Command::new("openshell-driver-vm"); - append_vm_proxy_and_spiffe_args(&mut command, &config); - - let args = command - .as_std() - .get_args() - .map(|arg| arg.to_string_lossy().into_owned()) - .collect::>(); - assert_eq!( - args, - [ - "--upstream-proxy", - "https://proxy.internal:8443", - "--upstream-no-proxy", - "localhost,.svc", - "--upstream-proxy-auth-file", - "/gateway/secrets/proxy-auth", - "--upstream-proxy-auth-allow-insecure", - "--upstream-proxy-connect-by-hostname", - "--provider-spiffe-workload-api-tcp-endpoint", - "tcp:192.0.2.10:8081", - "--provider-spiffe-allow-guest-tcp", - ] - ); - assert!(!args.iter().any(|arg| arg.contains("user:password"))); - } - - #[test] - fn vm_gateway_config_rejects_root_identity() { - let config = VmComputeConfig { - sandbox_uid: Some(0), - ..Default::default() - }; - let error = validate_vm_sandbox_identity(&config).expect_err("root UID must fail"); - assert!(error.to_string().contains("sandbox_uid 0")); - } - - #[test] - fn resolve_driver_bin_uses_driver_dir_when_binary_present() { - let dir = tempdir().unwrap(); - let bin = dir.path().join("openshell-driver-vm"); - std::fs::write(&bin, "#!/bin/sh\n").unwrap(); - std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755)).unwrap(); - - let vm_config = VmComputeConfig { - driver_dir: Some(dir.path().to_path_buf()), - ..Default::default() - }; - assert_eq!(resolve_compute_driver_bin(&vm_config).unwrap(), bin); - } - - #[test] - fn resolve_driver_bin_error_mentions_driver_dir_hint() { - let dir = tempdir().unwrap(); // empty — no driver binary present - - let vm_config = VmComputeConfig { - driver_dir: Some(dir.path().to_path_buf()), - ..Default::default() - }; - let err = resolve_compute_driver_bin(&vm_config) - .unwrap_err() - .to_string(); - assert!(err.contains("[openshell.drivers.vm].driver_dir")); - assert!(err.contains("openshell-driver-vm")); - } - - #[test] - fn resolve_driver_search_dirs_include_libexec_fallbacks() { - let dirs = resolve_driver_search_dirs(&VmComputeConfig { - driver_dir: None, - ..Default::default() - }); - - assert!(dirs.contains(&PathBuf::from("/usr/libexec/openshell"))); - assert!(dirs.contains(&PathBuf::from("/usr/local/libexec/openshell"))); - assert!(dirs.contains(&PathBuf::from("/usr/local/libexec"))); - } - - #[test] - fn vm_compute_driver_tls_requires_explicit_guest_bundle() { - let vm_config = VmComputeConfig { - grpc_endpoint: "https://gateway.internal:8443".to_string(), - ..Default::default() - }; - - let err = compute_driver_guest_tls_paths(&vm_config) - .expect_err("https vm endpoints should require an explicit gateway CA"); - assert!(err.to_string().contains("guest_tls_ca")); - } - - #[test] - fn vm_compute_driver_tls_uses_only_gateway_ca() { - let dir = tempdir().unwrap(); - let guest_ca = dir.path().join("guest-ca.crt"); - std::fs::write(&guest_ca, guest_ca.display().to_string()).unwrap(); - - let vm_config = VmComputeConfig { - grpc_endpoint: "https://gateway.internal:8443".to_string(), - guest_tls_ca: Some(guest_ca.clone()), - ..Default::default() - }; - - let guest_paths = compute_driver_guest_tls_paths(&vm_config) - .unwrap() - .expect("https vm endpoints should pass an explicit gateway CA"); - assert_eq!(guest_paths.ca, guest_ca); - } - - #[test] - fn compute_driver_socket_path_uses_private_run_dir() { - let state_dir = PathBuf::from("/tmp/openshell-vm-state"); - let vm_config = VmComputeConfig { - state_dir: state_dir.clone(), - ..Default::default() - }; - - assert_eq!( - compute_driver_socket_path(&vm_config), - state_dir.join("run").join("compute-driver.sock") - ); - } - - #[test] - fn prepare_compute_driver_socket_path_creates_private_run_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - let mode = std::fs::metadata(vm_config.state_dir.join("run")) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o700); - } - - #[test] - fn prepare_compute_driver_socket_path_restricts_existing_run_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let run_dir = vm_config.state_dir.join("run"); - std::fs::create_dir_all(&run_dir).unwrap(); - std::fs::set_permissions(&run_dir, std::fs::Permissions::from_mode(0o777)).unwrap(); - let socket_path = compute_driver_socket_path(&vm_config); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - let mode = std::fs::metadata(run_dir).unwrap().permissions().mode() & 0o777; - assert_eq!(mode, 0o700); - } - - #[test] - fn prepare_compute_driver_socket_path_restricts_existing_state_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - std::fs::create_dir_all(&vm_config.state_dir).unwrap(); - std::fs::set_permissions(&vm_config.state_dir, std::fs::Permissions::from_mode(0o777)) - .unwrap(); - let socket_path = compute_driver_socket_path(&vm_config); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - let mode = std::fs::metadata(vm_config.state_dir) - .unwrap() - .permissions() - .mode() - & 0o777; - assert_eq!(mode, 0o700); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_symlinked_state_dir() { - let dir = tempdir().unwrap(); - let target = dir.path().join("target"); - let state_link = dir.path().join("state-link"); - std::fs::create_dir_all(&target).unwrap(); - std::os::unix::fs::symlink(&target, &state_link).unwrap(); - let vm_config = VmComputeConfig { - state_dir: state_link, - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("symlinked state dir should be rejected") - .to_string(); - assert!(err.contains("is a symlink")); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_symlinked_run_dir() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let target = dir.path().join("run-target"); - std::fs::create_dir_all(&vm_config.state_dir).unwrap(); - std::fs::create_dir_all(&target).unwrap(); - std::os::unix::fs::symlink(&target, vm_config.state_dir.join("run")).unwrap(); - let socket_path = compute_driver_socket_path(&vm_config); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("symlinked run dir should be rejected") - .to_string(); - assert!(err.contains("is a symlink")); - } - - #[test] - fn prepare_vm_state_dir_rejects_wrong_owner() { - let dir = tempdir().unwrap(); - let state_dir = dir.path().join("state"); - std::fs::create_dir_all(&state_dir).unwrap(); - let wrong_uid = if current_euid() == u32::MAX { - u32::MAX - 1 - } else { - current_euid() + 1 - }; - - let err = prepare_vm_state_dir(&state_dir, wrong_uid) - .expect_err("wrong owner should be rejected") - .to_string(); - assert!(err.contains("is owned by uid")); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_symlinked_socket() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); - std::os::unix::fs::symlink("/tmp/not-a-socket", &socket_path).unwrap(); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("symlinked socket should be rejected") - .to_string(); - assert!(err.contains("is a symlink")); - } - - #[test] - fn prepare_compute_driver_socket_path_rejects_non_socket_stale_path() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); - std::fs::write(&socket_path, "not a socket").unwrap(); - - let err = prepare_compute_driver_socket_path(&vm_config, &socket_path) - .expect_err("regular file should be rejected") - .to_string(); - assert!(err.contains("is not a Unix socket")); - } - - #[test] - fn prepare_compute_driver_socket_path_removes_same_owner_stale_socket() { - let dir = tempdir().unwrap(); - let vm_config = VmComputeConfig { - state_dir: dir.path().join("state"), - ..Default::default() - }; - let socket_path = compute_driver_socket_path(&vm_config); - std::fs::create_dir_all(socket_path.parent().unwrap()).unwrap(); - let listener = StdUnixListener::bind(&socket_path).unwrap(); - - prepare_compute_driver_socket_path(&vm_config, &socket_path).unwrap(); - - drop(listener); - assert!(!socket_path.exists()); - } -} + .await?; + match outcome { + LaunchOutcome::Launched(launched) => Ok(AcquiredRemoteDriverEndpoint::managed( + "vm", + launched.channel, + launched.process, + )), + LaunchOutcome::InvalidConfig(reason) => Err(Error::config(format!( + "invalid [openshell.drivers.vm] table: {reason}" + ))), + LaunchOutcome::Unavailable(reason) => Err(Error::execution(format!( + "the vm compute driver is unavailable: {reason}" + ))), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/openshell-gateway/src/vm/tests.rs b/crates/openshell-gateway/src/vm/tests.rs new file mode 100644 index 0000000000..45554db430 --- /dev/null +++ b/crates/openshell-gateway/src/vm/tests.rs @@ -0,0 +1,163 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::os::unix::fs::PermissionsExt as _; + +use tempfile::tempdir; + +use super::*; + +fn table(text: &str) -> toml::map::Map { + toml::from_str(text).unwrap() +} + +#[test] +fn gateway_owned_keys_are_removed_and_the_rest_is_forwarded() { + let plan = VmLaunchPlan::from_table( + table( + "driver_dir = \"/opt/drivers\"\nstate_dir = \"/var/lib/vm\"\nvcpus = 4\nunknown_to_the_gateway = true", + ), + None, + ) + .unwrap(); + + assert_eq!(plan.driver_dir, Some(PathBuf::from("/opt/drivers"))); + assert_eq!(plan.state_dir, PathBuf::from("/var/lib/vm")); + let forwarded: toml::map::Map = toml::from_str(&plan.table).unwrap(); + assert!(!forwarded.contains_key("driver_dir")); + assert_eq!(forwarded["state_dir"].as_str(), Some("/var/lib/vm")); + assert_eq!(forwarded["vcpus"].as_integer(), Some(4)); + assert_eq!(forwarded["unknown_to_the_gateway"].as_bool(), Some(true)); +} + +#[test] +fn an_empty_table_selects_the_default_state_dir() { + let plan = VmLaunchPlan::from_table(table(""), None).unwrap(); + assert_eq!(plan.state_dir, VmLaunchPlan::default_state_dir()); + assert_eq!(plan.driver_dir, None); + assert!(plan.table.trim().is_empty()); + + let empty = VmLaunchPlan::from_table(table("state_dir = \"\""), None).unwrap(); + assert_eq!(empty.state_dir, VmLaunchPlan::default_state_dir()); +} + +#[test] +fn a_non_string_gateway_key_is_rejected() { + assert!(VmLaunchPlan::from_table(table("driver_dir = 3"), None).is_err()); +} + +#[test] +fn socket_dir_is_the_private_run_dir_under_the_state_dir() { + let plan = + VmLaunchPlan::from_table(table("state_dir = \"/tmp/openshell-vm-state\""), None).unwrap(); + assert_eq!( + plan.socket_dir(), + PathBuf::from("/tmp/openshell-vm-state/run") + ); +} + +#[test] +fn resolve_driver_bin_uses_driver_dir_when_binary_present() { + let dir = tempdir().unwrap(); + let driver = dir.path().join(DRIVER_BIN_NAME); + std::fs::write(&driver, b"#!/bin/sh\n").unwrap(); + std::fs::set_permissions(&driver, std::fs::Permissions::from_mode(0o755)).unwrap(); + + assert_eq!( + resolve_compute_driver_bin(Some(dir.path())).unwrap(), + driver + ); +} + +#[test] +fn resolve_driver_bin_error_mentions_driver_dir_hint() { + let dir = tempdir().unwrap(); + let error = resolve_compute_driver_bin(Some(dir.path())) + .unwrap_err() + .to_string(); + assert!(error.contains("driver_dir"), "{error}"); + assert!(error.contains("openshell-driver-vm"), "{error}"); +} + +#[test] +fn resolve_driver_search_dirs_include_libexec_fallbacks() { + let dirs = launcher::default_driver_search_dirs(Some(PathBuf::from("/home/openshell"))); + assert_eq!( + dirs.first(), + Some(&PathBuf::from("/home/openshell/.local/libexec/openshell")) + ); + assert!(dirs.contains(&PathBuf::from("/usr/libexec/openshell"))); + assert!(dirs.contains(&PathBuf::from("/usr/local/libexec/openshell"))); + assert!(dirs.contains(&PathBuf::from("/usr/local/libexec"))); +} + +#[test] +fn prepare_vm_state_dir_creates_and_restricts_the_directory() { + let dir = tempdir().unwrap(); + let state = dir.path().join("state"); + let uid = rustix::process::geteuid().as_raw(); + + prepare_vm_state_dir(&state, uid).unwrap(); + assert_eq!( + std::fs::metadata(&state).unwrap().permissions().mode() & 0o777, + 0o700 + ); + + std::fs::set_permissions(&state, std::fs::Permissions::from_mode(0o755)).unwrap(); + prepare_vm_state_dir(&state, uid).unwrap(); + assert_eq!( + std::fs::metadata(&state).unwrap().permissions().mode() & 0o777, + 0o700 + ); +} + +#[test] +fn prepare_vm_state_dir_rejects_symlinks_and_the_wrong_owner() { + let dir = tempdir().unwrap(); + let real = dir.path().join("real"); + std::fs::create_dir(&real).unwrap(); + let link = dir.path().join("link"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let uid = rustix::process::geteuid().as_raw(); + + let error = prepare_vm_state_dir(&link, uid).unwrap_err().to_string(); + assert!(error.contains("symlink"), "{error}"); + + let error = prepare_vm_state_dir(&real, uid + 1) + .unwrap_err() + .to_string(); + assert!(error.contains("is owned by uid"), "{error}"); +} + +#[test] +fn driver_dir_comes_from_the_gateway_section_and_the_legacy_key_is_stripped() { + let from_gateway = VmLaunchPlan::from_table( + table("driver_dir = \"/legacy\"\nvcpus = 2"), + Some(Path::new("/gateway")), + ) + .unwrap(); + assert_eq!(from_gateway.driver_dir, Some(PathBuf::from("/gateway"))); + assert!(!from_gateway.table.contains("driver_dir")); + + let legacy_only = VmLaunchPlan::from_table(table("driver_dir = \"/legacy\""), None).unwrap(); + assert_eq!(legacy_only.driver_dir, Some(PathBuf::from("/legacy"))); + assert!(!legacy_only.table.contains("driver_dir")); + + let gateway_only = VmLaunchPlan::from_table(table(""), Some(Path::new("/gateway"))).unwrap(); + assert_eq!(gateway_only.driver_dir, Some(PathBuf::from("/gateway"))); +} + +#[test] +fn the_admission_policy_is_not_forwarded_in_the_driver_table() { + let plan = VmLaunchPlan::from_table( + table("allow_driver_config = true\n[resource_admission]\nenabled = false\nrequired_labels = {}\n"), + None, + ) + .unwrap(); + assert!( + !plan.table.contains("allow_driver_config"), + "{}", + plan.table + ); + assert!(!plan.table.contains("resource_admission"), "{}", plan.table); +} diff --git a/crates/openshell-gateway/tests/config_preflight.rs b/crates/openshell-gateway/tests/config_preflight.rs index 9b14a584bb..05c3f08697 100644 --- a/crates/openshell-gateway/tests/config_preflight.rs +++ b/crates/openshell-gateway/tests/config_preflight.rs @@ -27,6 +27,16 @@ impl Fixture { config, }; fixture.write_config(Some("vm")); + // The driver's own `preflight` validates its table; it contacts no + // backend and creates no state. The fixture records how it was run. + let invocations = fixture.root.path().join("driver-invocations"); + fixture.tool( + "openshell-driver-vm", + &format!( + "echo \"$1\" >> '{}'\nwhile read -r _; do :; done\ntest \"$1\" = preflight", + invocations.display() + ), + ); for name in ["mke2fs", "debugfs", "e2fsck"] { fixture.tool(name, &format!( "test \"$1\" = -V || exit 64\ntest \"$#\" = 1 || exit 65\nread ignored && exit 66\ntest \"$PREFLIGHT_TEST_ENV\" = inherited || exit 67\necho '{name} 1.47.4' >&2" @@ -41,15 +51,22 @@ impl Fixture { // TOML serialization preserves quotes and escapes in the fixture path. let state_dir = toml::Value::try_from(self.root.path().join("vm-state")) .expect("serialize VM state directory"); + let driver_dir = toml::Value::try_from(&self.tools).expect("serialize driver directory"); fs::write(&self.config, format!( - "[openshell]\nversion = 2\n[openshell.gateway]\ndisable_tls = true\n{selector}[openshell.drivers.vm]\nbootstrap_image = 'unreachable.invalid/vm:must-not-pull'\nstate_dir = {state_dir}\n" + "[openshell]\nversion = 2\n[openshell.gateway]\ndisable_tls = true\ndriver_dir = {driver_dir}\n{selector}[openshell.drivers.vm]\nbootstrap_image = 'unreachable.invalid/vm:must-not-pull'\nstate_dir = {state_dir}\n" )).expect("gateway configuration"); } fn tool(&self, name: &str, body: &str) { + // Write and close a temporary file, then rename it into place. A + // script another test's fork could still hold open for writing fails + // to execute with ETXTBSY. let path = self.tools.join(name); - fs::write(&path, format!("#!/bin/sh\n{body}\n")).expect("tool fixture"); - fs::set_permissions(path, fs::Permissions::from_mode(0o755)).expect("executable fixture"); + let temporary = self.tools.join(format!("{name}.tmp")); + fs::write(&temporary, format!("#!/bin/sh\n{body}\n")).expect("tool fixture"); + fs::set_permissions(&temporary, fs::Permissions::from_mode(0o755)) + .expect("executable fixture"); + fs::rename(temporary, path).expect("install fixture"); } fn command(&self, replay: &[&str]) -> tokio::process::Command { @@ -130,8 +147,10 @@ async fn local_vm_reports_tools_without_starting_driver_or_creating_state() { "{report}" ); } - // PATH contains only the filesystem fixtures, never a VM driver binary. - assert!(!fixture.tools.join("openshell-driver-vm").exists()); + // The gateway ran the driver only to check its table, never to serve. + let invocations = fs::read_to_string(fixture.root.path().join("driver-invocations")) + .expect("the driver checked its table"); + assert_eq!(invocations.trim(), "preflight"); } #[tokio::test] @@ -217,7 +236,9 @@ async fn signals_stop_probe_wrapper_and_descendants_before_cli_exit() { .expect("preflight process"); let pid = Pid::from_raw(i32::try_from(child.id().expect("gateway PID")).expect("valid PID")); - tokio::time::timeout(Duration::from_secs(5), async { + // Startup runs the driver's own `preflight` before the host tools, + // which takes a moment longer when several gateways start at once. + tokio::time::timeout(Duration::from_secs(15), async { while !ready.exists() { tokio::time::sleep(Duration::from_millis(10)).await; } @@ -270,6 +291,11 @@ async fn vm_table_without_selection_does_not_probe_tools() { async fn unrelated_driver_does_not_require_vm_tools() { let fixture = Fixture::new(); fixture.tool("mke2fs", "exit 42"); + // Docker validates its own table through its `preflight` command. + fixture.tool( + "openshell-driver-docker", + "while read -r _; do :; done\ntest \"$1\" = preflight", + ); let output = fixture.run(&["--compute-driver", "docker"]).await; assert!(output.status.success(), "{}", combined(&output)); assert!(!combined(&output).contains("VM host tool")); diff --git a/crates/openshell-gateway/tests/proxy_config_preflight.rs b/crates/openshell-gateway/tests/proxy_config_preflight.rs deleted file mode 100644 index d3d1917399..0000000000 --- a/crates/openshell-gateway/tests/proxy_config_preflight.rs +++ /dev/null @@ -1,136 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! An incoherent driver proxy table is fatal, rather than leaving every dial -//! direct while looking configured. A bypass list without a proxy URL means -//! the operator believed proxying was in effect. - -// Only Docker, Podman and the VM driver have a proxy table. -#![cfg(all( - unix, - any( - feature = "compute-driver-docker", - feature = "compute-driver-podman", - feature = "compute-driver-vm" - ) -))] - -use std::fs; -use std::path::PathBuf; -use std::process::Output; -use std::time::Duration; - -/// Drivers with an upstream proxy table, compiled into this gateway. -const DRIVERS: &[&str] = &[ - #[cfg(feature = "compute-driver-docker")] - "docker", - #[cfg(feature = "compute-driver-podman")] - "podman", - #[cfg(feature = "compute-driver-vm")] - "vm", -]; - -struct Fixture { - root: tempfile::TempDir, - config: PathBuf, -} - -impl Fixture { - /// A gateway config that selects `driver` and sets only `no_proxy` in its - /// table. - fn incoherent(driver: &str) -> Self { - let root = tempfile::tempdir().expect("fixture root"); - let config = root.path().join("gateway.toml"); - fs::write( - &config, - format!( - "[openshell] -version = 2 -[openshell.gateway] -disable_tls = true -bind_address = \"127.0.0.1:0\" -compute_driver = {driver:?} -[openshell.gateway.auth] -allow_unauthenticated_users = true -[openshell.drivers.{driver}] -no_proxy = \"10.0.0.0/8\" -" - ), - ) - .expect("gateway configuration"); - Self { root, config } - } - - async fn run(&self, args: &[&str]) -> Output { - let mut command = tokio::process::Command::new(env!("CARGO_BIN_EXE_openshell-gateway")); - command - .env_clear() - .env("HOME", self.root.path()) - .env("PATH", "/usr/bin:/bin") - .env("NO_COLOR", "1") - .env("XDG_CONFIG_HOME", self.root.path().join("config-home")) - .env("XDG_STATE_HOME", self.root.path().join("state-home")) - .args(args) - .kill_on_drop(true); - tokio::time::timeout(Duration::from_secs(30), command.output()) - .await - .expect("the gateway must exit instead of starting") - .expect("run openshell-gateway") - } - - fn config_path(&self) -> &str { - self.config.to_str().expect("UTF-8 config path") - } -} - -fn combined(output: &Output) -> String { - format!( - "{}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ) -} - -#[tokio::test] -async fn preflight_rejects_no_proxy_without_proxy() { - for driver in DRIVERS { - let fixture = Fixture::incoherent(driver); - let original = fs::read(&fixture.config).expect("original config"); - let output = fixture - .run(&["config", "preflight", "--path", fixture.config_path()]) - .await; - let report = combined(&output); - assert!( - !output.status.success(), - "preflight accepted an incoherent [openshell.drivers.{driver}] proxy table:\n{report}" - ); - assert!( - report.contains("category=malformed"), - "preflight did not classify the {driver} config as malformed:\n{report}" - ); - assert_eq!( - fs::read(&fixture.config).expect("config after preflight"), - original, - "preflight changed the {driver} config" - ); - } -} - -#[tokio::test] -async fn startup_rejects_no_proxy_without_proxy_and_names_the_keys() { - for driver in DRIVERS { - let fixture = Fixture::incoherent(driver); - let output = fixture.run(&["--config", fixture.config_path()]).await; - let report = combined(&output); - assert!( - !output.status.success(), - "the gateway started with an incoherent [openshell.drivers.{driver}] proxy table:\n{report}" - ); - // Matched on the key names, not the wording, so error wrapping can - // change. - assert!( - report.contains("no_proxy") && report.contains("https_proxy"), - "the {driver} startup error does not name the offending keys:\n{report}" - ); - } -} diff --git a/crates/openshell-otel/src/driver.rs b/crates/openshell-otel/src/driver.rs index 68be206834..740c9f6d22 100644 --- a/crates/openshell-otel/src/driver.rs +++ b/crates/openshell-otel/src/driver.rs @@ -5,6 +5,7 @@ use std::future::Future; use std::pin::Pin; +use std::sync::{Arc, Mutex, OnceLock}; use futures::Stream; use tracing::Instrument as _; @@ -267,6 +268,238 @@ pub fn install_driver_tracing( DriverTracingHandle { provider } } +type ExportLayer = tracing_opentelemetry::OpenTelemetryLayer< + tracing_subscriber::Registry, + opentelemetry_sdk::trace::Tracer, +>; + +/// Collector settings supplied after a launched driver is already logging. +#[derive(Debug, Clone, Copy)] +pub struct DeferredExportConfig<'a> { + pub endpoint: &'a str, + pub protocol: crate::Protocol, + /// PEM files for an `https://` collector; see [`crate::OtlpTls::from_files`]. + pub ca_file: Option<&'a std::path::Path>, + pub cert_file: Option<&'a std::path::Path>, + pub key_file: Option<&'a std::path::Path>, + pub gateway_name: Option<&'a str>, + pub service_version: &'static str, + /// Collector request headers in `OTEL_EXPORTER_OTLP_HEADERS` format. + pub headers: &'a str, +} + +/// A tracing layer whose OpenTelemetry export is installed once, later. +/// +/// Unlike `reload::Layer`, it forwards `downcast_raw` to the installed layer. +/// `OpenTelemetrySpanExt::set_parent` finds the OpenTelemetry layer through +/// that downcast, so a reloadable slot would silently drop the gateway's +/// parent trace context. +struct DeferredLayer { + slot: Arc>, +} + +impl tracing_subscriber::Layer for DeferredLayer { + fn on_new_span( + &self, + attrs: &tracing::span::Attributes<'_>, + id: &tracing::span::Id, + ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>, + ) { + if let Some(layer) = self.slot.get() { + layer.on_new_span(attrs, id, ctx); + } + } + + fn on_record( + &self, + id: &tracing::span::Id, + values: &tracing::span::Record<'_>, + ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>, + ) { + if let Some(layer) = self.slot.get() { + layer.on_record(id, values, ctx); + } + } + + fn on_follows_from( + &self, + id: &tracing::span::Id, + follows: &tracing::span::Id, + ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>, + ) { + if let Some(layer) = self.slot.get() { + layer.on_follows_from(id, follows, ctx); + } + } + + fn on_event( + &self, + event: &tracing::Event<'_>, + ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>, + ) { + if let Some(layer) = self.slot.get() { + layer.on_event(event, ctx); + } + } + + fn on_enter( + &self, + id: &tracing::span::Id, + ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>, + ) { + if let Some(layer) = self.slot.get() { + layer.on_enter(id, ctx); + } + } + + fn on_exit( + &self, + id: &tracing::span::Id, + ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>, + ) { + if let Some(layer) = self.slot.get() { + layer.on_exit(id, ctx); + } + } + + fn on_close( + &self, + id: tracing::span::Id, + ctx: tracing_subscriber::layer::Context<'_, tracing_subscriber::Registry>, + ) { + if let Some(layer) = self.slot.get() { + layer.on_close(id, ctx); + } + } + + // `downcast_raw` is an unsafe trait method; this implementation only + // returns pointers the installed layer itself returns, or to `self`. + #[allow(unsafe_code)] + unsafe fn downcast_raw(&self, id: std::any::TypeId) -> Option<*const ()> { + if id == std::any::TypeId::of::() { + return Some(std::ptr::from_ref(self).cast()); + } + // SAFETY: the slot is set at most once, and the layer stays at the + // same address in the `Arc` for as long as this layer exists. + self.slot + .get() + .and_then(|layer| unsafe { layer.downcast_raw(id) }) + } +} + +/// Handle to a launched driver's tracing, whose OTLP export starts later. +/// +/// Cloning shares the same exporter slot. The provider shuts down when the +/// last clone drops. +#[derive(Clone)] +pub struct DeferredDriverTracing { + inner: Arc, +} + +struct DeferredInner { + descriptor: ComputeDriverTracing, + slot: Arc>, + provider: Mutex>, +} + +impl Drop for DeferredInner { + fn drop(&mut self) { + let provider = self + .provider + .get_mut() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if let Some(provider) = provider + && let Err(error) = provider.shutdown() + { + tracing::warn!(%error, "OTLP tracer provider shutdown failed"); + } + } +} + +impl DeferredDriverTracing { + /// Start exporting spans created from now on. Spans created earlier are + /// not exported. Later calls are no-ops that return `Ok`, so a retried + /// configuration never installs a second exporter. + pub fn enable_export(&self, config: DeferredExportConfig<'_>) -> Result<(), SetupError> { + use opentelemetry::trace::TracerProvider as _; + + let mut provider_slot = self + .inner + .provider + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + if provider_slot.is_some() { + return Ok(()); + } + let transport = crate::CollectorTransport { + protocol: config.protocol, + headers: crate::parse_otlp_headers(config.headers), + tls: crate::OtlpTls::from_files(config.ca_file, config.cert_file, config.key_file)?, + }; + let descriptor = self.inner.descriptor; + let (provider, error) = descriptor.provider_for( + Some(config.endpoint), + &transport, + config.service_version, + config.gateway_name, + Some(descriptor.compute_driver()), + ); + if let Some(error) = error { + return Err(error); + } + let Some(provider) = provider else { + return Ok(()); + }; + let layer = + tracing_opentelemetry::layer().with_tracer(provider.tracer(descriptor.service_name())); + if self.inner.slot.set(layer).is_err() { + let _ = provider.shutdown(); + return Ok(()); + } + tracing::info!(endpoint = config.endpoint, "OTLP exporting enabled"); + *provider_slot = Some(provider); + Ok(()) + } +} + +/// Install logging for a launched driver with an empty OTLP slot to fill +/// later with [`DeferredDriverTracing::enable_export`]. +/// +/// Logs go to stderr: a launched driver's stdout carries its start-up result. +#[must_use] +pub fn install_deferred_driver_tracing( + descriptor: ComputeDriverTracing, + log_level: &str, + ansi: bool, +) -> DeferredDriverTracing { + let slot = Arc::new(OnceLock::new()); + // The span filter stays on the deferred layer's wrapper, so it is + // registered before the OpenTelemetry layer exists. + tracing_subscriber::registry() + .with( + DeferredLayer { + slot: Arc::clone(&slot), + } + .with_filter(tracing_subscriber::filter::filter_fn(|metadata| { + metadata.is_span() && !metadata.target().starts_with("opentelemetry") + })), + ) + .with(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(log_level))) + .with( + tracing_subscriber::fmt::layer() + .with_ansi(ansi) + .with_writer(std::io::stderr), + ) + .init(); + DeferredDriverTracing { + inner: Arc::new(DeferredInner { + descriptor, + slot, + provider: Mutex::new(None), + }), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/openshell-otel/src/lib.rs b/crates/openshell-otel/src/lib.rs index b8c2f4d79b..17a898e155 100644 --- a/crates/openshell-otel/src/lib.rs +++ b/crates/openshell-otel/src/lib.rs @@ -54,8 +54,9 @@ pub use correlation::current_ocsf_trace_correlation; #[cfg(feature = "export")] pub use driver::{ - BoxGrpcStream, ComputeDriverTracing, DriverTracingConfig, DriverTracingHandle, - IN_PROCESS_COMPUTE_DRIVER_TARGET, InProcessRpcTracer, install_driver_tracing, + BoxGrpcStream, ComputeDriverTracing, DeferredDriverTracing, DeferredExportConfig, + DriverTracingConfig, DriverTracingHandle, IN_PROCESS_COMPUTE_DRIVER_TARGET, InProcessRpcTracer, + install_deferred_driver_tracing, install_driver_tracing, }; #[cfg(feature = "export")] pub use grpc::{ diff --git a/crates/openshell-otel/tests/deferred_driver_tracing.rs b/crates/openshell-otel/tests/deferred_driver_tracing.rs new file mode 100644 index 0000000000..6051e67d8e --- /dev/null +++ b/crates/openshell-otel/tests/deferred_driver_tracing.rs @@ -0,0 +1,63 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The only test in its binary, since it installs process-wide tracing. + +use openshell_otel::{DeferredExportConfig, Protocol, compute_driver_tracing}; +use openshell_otel_test_support::OtlpTestServer; + +const TRACE_ID: [u8; 16] = [ + 0x0a, 0xf7, 0x65, 0x19, 0x16, 0xcd, 0x43, 0xdd, 0x84, 0x48, 0xeb, 0x21, 0x1c, 0x80, 0x31, 0x9c, +]; +const PARENT_SPAN_ID: [u8; 8] = [0xb7, 0xad, 0x6b, 0x71, 0x69, 0x20, 0x33, 0x31]; +const TRACEPARENT: &str = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; + +#[tokio::test(flavor = "multi_thread")] +async fn export_starts_after_install_once_and_keeps_the_parent_trace() { + const TRACING: openshell_otel::ComputeDriverTracing = compute_driver_tracing!(); + let collector = OtlpTestServer::start().await; + let tracing = openshell_otel::install_deferred_driver_tracing(TRACING, "info", false); + + drop(tracing::info_span!("before-enable", otel.name = "before-enable").entered()); + + let config = DeferredExportConfig { + endpoint: collector.endpoint(), + protocol: Protocol::Grpc, + ca_file: None, + cert_file: None, + key_file: None, + gateway_name: Some("test-gateway"), + service_version: "1.2.3", + headers: "", + }; + tracing.enable_export(config).expect("export enables"); + tracing + .enable_export(config) + .expect("second call is a no-op"); + + // A span for a gateway request: its parent is the gateway's span. + let span = tracing::info_span!("after-enable", otel.name = "after-enable"); + openshell_otel::set_parent_from_trace_context(&span, Some(TRACEPARENT), None); + drop(span.entered()); + + // Dropping the last handle shuts the provider down, flushing its spans. + let shutdown = tokio::task::spawn_blocking(move || drop(tracing)); + collector.wait_for_export().await; + shutdown.await.unwrap(); + let received = collector.shutdown().await; + + let names: Vec<_> = received + .spans + .iter() + .map(|span| span.name.as_str()) + .collect(); + assert_eq!(names, ["after-enable"], "unexpected spans: {names:?}"); + assert_eq!(received.gateway_names, ["test-gateway"]); + assert_eq!(received.compute_drivers, ["openshell-otel"]); + let exported = &received.spans[0]; + assert_eq!(exported.trace_id, TRACE_ID, "the gateway's trace id"); + assert_eq!( + exported.parent_span_id, PARENT_SPAN_ID, + "the gateway's span" + ); +} diff --git a/crates/openshell-server/src/cli.rs b/crates/openshell-server/src/cli.rs index 6ccd9fa72b..f54fb74f68 100644 --- a/crates/openshell-server/src/cli.rs +++ b/crates/openshell-server/src/cli.rs @@ -473,7 +473,11 @@ fn prepare_server_config_with_drivers( let legacy_compute_driver_env_seen = resolve_legacy_driver_selector_env(args)?; normalize_compute_driver_socket_args(args)?; let compute_driver = compute_drivers - .select(args.compute_driver.as_deref()) + .select_with_file( + args.compute_driver.as_deref(), + file.as_ref(), + &args.log_level, + ) .map_err(|error| miette::miette!("{error}"))?; if let Some(file) = file.as_mut() { config_file::normalize_legacy_podman_ca_bundle(file, compute_driver.name()) diff --git a/crates/openshell-server/src/compute/driver_config.rs b/crates/openshell-server/src/compute/driver_config.rs index 418ae5b108..f79239ff11 100644 --- a/crates/openshell-server/src/compute/driver_config.rs +++ b/crates/openshell-server/src/compute/driver_config.rs @@ -141,6 +141,30 @@ where driver_config_from_file(context.file, driver_name) } +/// The selected driver's merged table as TOML text, for a driver that parses +/// its own configuration. The gateway checks no field of it beyond the +/// gateway-owned guest TLS paths. +pub fn driver_table_from_context( + context: DriverStartupContext<'_>, + driver_name: &str, +) -> Result> { + let Some(file) = context.file else { + return Ok(toml::map::Map::new()); + }; + let merged = config_file::driver_table( + driver_name, + &file.openshell.gateway, + file.openshell.drivers.get(driver_name), + ); + reject_driver_owned_guest_tls_fields(&merged)?; + match merged { + toml::Value::Table(table) => Ok(table), + _ => Err(Error::config(format!( + "invalid [openshell.drivers.{driver_name}] table" + ))), + } +} + fn driver_config_from_file( file: Option<&config_file::ConfigFile>, driver_name: &str, diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index da516927a6..5f537fe588 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -560,18 +560,86 @@ const ORPHAN_GRACE_PERIOD: Duration = Duration::from_mins(5); // Re-export the shared error type under the name used by this module. pub use openshell_core::ComputeDriverError as ComputeError; +/// What a managed driver process is doing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DriverProcessState { + /// The process is running. + Running, + /// The process ended without the gateway asking it to; the text says how. + Exited(String), + /// The gateway stopped or released the process. + Released, +} + +/// A driver process, started with tokio or with `std`. +#[derive(Debug)] +enum DriverChild { + Tokio(tokio::process::Child), + Std(std::process::Child), +} + +impl DriverChild { + fn id(&self) -> Option { + match self { + Self::Tokio(child) => child.id(), + Self::Std(child) => Some(child.id()), + } + } + + fn try_wait(&mut self) -> std::io::Result> { + match self { + Self::Tokio(child) => child.try_wait(), + Self::Std(child) => child.try_wait(), + } + } +} + #[derive(Debug)] pub struct ManagedDriverProcess { - child: std::sync::Mutex>, + child: std::sync::Mutex>, socket_path: PathBuf, + /// The socket's directory belongs to this process and goes with it. + owns_socket_dir: bool, } impl ManagedDriverProcess { #[cfg(unix)] pub fn new(child: tokio::process::Child, socket_path: PathBuf) -> Self { Self { - child: std::sync::Mutex::new(Some(child)), + child: std::sync::Mutex::new(Some(DriverChild::Tokio(child))), socket_path, + owns_socket_dir: false, + } + } + + /// Manage a driver started with `std::process`, such as one that + /// auto-detection started and kept. The process is stopped when this + /// handle drops, and the directory holding `socket_path` is removed with + /// it, so it must be a directory made for this process alone. + #[cfg(unix)] + pub fn from_std(child: std::process::Child, socket_path: PathBuf) -> Self { + Self { + child: std::sync::Mutex::new(Some(DriverChild::Std(child))), + socket_path, + owns_socket_dir: true, + } + } + + /// Check whether the process is still running without waiting for it. + /// An exit the gateway caused through shutdown reports + /// [`DriverProcessState::Released`], not [`DriverProcessState::Exited`]. + pub fn poll_exit(&self) -> DriverProcessState { + let mut child = self + .child + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(process) = child.as_mut() else { + return DriverProcessState::Released; + }; + match process.try_wait() { + Ok(None) => DriverProcessState::Running, + Ok(Some(status)) => DriverProcessState::Exited(format!("exited with {status}")), + Err(error) => DriverProcessState::Exited(format!("could not be polled: {error}")), } } @@ -586,7 +654,7 @@ impl ManagedDriverProcess { .lock() .map_err(|_| "managed compute-driver process lock poisoned".to_string())? .take(); - let Some(mut child) = child else { + let Some(child) = child else { return Ok(()); }; @@ -597,33 +665,140 @@ impl ManagedDriverProcess { return Err(format!("failed to terminate managed compute driver: {err}")); } - match tokio::time::timeout(Duration::from_secs(5), child.wait()).await { - Ok(Ok(_)) => Ok(()), - Ok(Err(err)) => Err(format!("failed to wait for managed compute driver: {err}")), - Err(_) => { - child - .kill() - .await - .map_err(|err| format!("failed to kill managed compute driver: {err}"))?; - child - .wait() - .await - .map(|_| ()) - .map_err(|err| format!("failed to reap managed compute driver: {err}")) + match child { + DriverChild::Tokio(mut child) => { + match tokio::time::timeout(Duration::from_secs(5), child.wait()).await { + Ok(Ok(_)) => Ok(()), + Ok(Err(err)) => { + Err(format!("failed to wait for managed compute driver: {err}")) + } + Err(_) => { + child.kill().await.map_err(|err| { + format!("failed to kill managed compute driver: {err}") + })?; + child + .wait() + .await + .map(|_| ()) + .map_err(|err| format!("failed to reap managed compute driver: {err}")) + } + } } + DriverChild::Std(mut child) => tokio::task::spawn_blocking(move || { + let deadline = Instant::now() + Duration::from_secs(5); + loop { + match child.try_wait() { + Ok(Some(_)) => return Ok(()), + Ok(None) if Instant::now() < deadline => { + std::thread::sleep(Duration::from_millis(20)); + } + Ok(None) => { + child.kill().map_err(|err| { + format!("failed to kill managed compute driver: {err}") + })?; + return child.wait().map(|_| ()).map_err(|err| { + format!("failed to reap managed compute driver: {err}") + }); + } + Err(err) => { + return Err(format!( + "failed to wait for managed compute driver: {err}" + )); + } + } + } + }) + .await + .map_err(|err| format!("failed to wait for managed compute driver: {err}"))?, } } } impl Drop for ManagedDriverProcess { fn drop(&mut self) { - if let Ok(mut child) = self.child.lock() { - let _ = child.take(); + if let Ok(mut child) = self.child.lock() + && let Some(DriverChild::Std(mut process)) = child.take() + { + // Unlike a tokio child, a std child is not killed on drop. + let _ = process.kill(); + let _ = process.wait(); } let _ = std::fs::remove_file(&self.socket_path); + if self.owns_socket_dir + && let Some(dir) = self.socket_path.parent() + { + let _ = std::fs::remove_dir(dir); + } } } +#[cfg(all(test, unix))] +#[tokio::test] +async fn managed_driver_reports_unexpected_exit_but_not_shutdown() { + let dir = tempfile::tempdir().unwrap(); + let spawn = |script: &str| { + tokio::process::Command::new("sh") + .arg("-c") + .arg(script) + .kill_on_drop(true) + .spawn() + .unwrap() + }; + + let exits = ManagedDriverProcess::new(spawn("exit 3"), dir.path().join("a.sock")); + let mut state = exits.poll_exit(); + for _ in 0..100 { + if state != DriverProcessState::Running { + break; + } + tokio::time::sleep(Duration::from_millis(20)).await; + state = exits.poll_exit(); + } + assert!(matches!(&state, DriverProcessState::Exited(text) if text.contains('3'))); + + let stopped = ManagedDriverProcess::new(spawn("sleep 60"), dir.path().join("b.sock")); + assert_eq!(stopped.poll_exit(), DriverProcessState::Running); + stopped.shutdown().await.unwrap(); + assert_eq!(stopped.poll_exit(), DriverProcessState::Released); +} + +#[cfg(all(test, unix))] +#[tokio::test] +async fn a_std_driver_is_stopped_on_shutdown_and_when_dropped() { + let dir = tempfile::tempdir().unwrap(); + let spawn = || { + std::process::Command::new("sleep") + .arg("60") + .spawn() + .unwrap() + }; + + let stopped = ManagedDriverProcess::from_std(spawn(), dir.path().join("a.sock")); + assert_eq!(stopped.poll_exit(), DriverProcessState::Running); + stopped.shutdown().await.unwrap(); + assert_eq!(stopped.poll_exit(), DriverProcessState::Released); + + let child = spawn(); + let pid = child.id(); + let launch_dir = dir.path().join("launch-b"); + std::fs::create_dir(&launch_dir).unwrap(); + drop(ManagedDriverProcess::from_std( + child, + launch_dir.join("driver.sock"), + )); + assert!( + !launch_dir.exists(), + "the launch directory goes with the handle" + ); + let alive = std::process::Command::new("kill") + .args(["-0", &pid.to_string()]) + .stderr(std::process::Stdio::null()) + .status() + .unwrap() + .success(); + assert!(!alive, "dropping the handle must stop the process"); +} + #[cfg(all(test, unix))] #[tokio::test] async fn managed_driver_shutdown_sends_sigterm_before_forcing_exit() { diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index b43f22231e..337ccba05b 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -214,6 +214,13 @@ pub struct GatewayFileSection { #[serde(default)] pub guest_tls_ca: Option, + // ── Launched compute drivers ───────────────────────────────────────── + /// Directory searched first for launched compute-driver binaries such as + /// `openshell-driver-vm`. The gateway owns it; a `driver_dir` in a + /// `[openshell.drivers.]` table is deprecated. + #[serde(default)] + pub driver_dir: Option, + // ── TLS toggle ─────────────────────────────────────────────────────── /// When `true`, the gateway listens on plaintext HTTP and ignores any /// `[openshell.gateway.tls]` table. Mirrors `--disable-tls`. diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 799c46e397..c0798b7c1e 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -1800,8 +1800,8 @@ async fn terminate_signal() { } pub use compute::{ - AcquiredRemoteDriverEndpoint, DriverWatchStream, ManagedDriverProcess, SharedComputeDriver, - SharedComputeDriverAppEndpoints, SharedComputeDriverConfigurationUpdates, + AcquiredRemoteDriverEndpoint, DriverProcessState, DriverWatchStream, ManagedDriverProcess, + SharedComputeDriver, SharedComputeDriverAppEndpoints, SharedComputeDriverConfigurationUpdates, }; /// Driver instance returned by a compiled compute-driver factory. @@ -1896,12 +1896,65 @@ pub trait ComputeDriverFactory: Send + Sync { } } +/// A driver process that detection started and found available. +/// +/// The same process serves once it is built, so detection never starts a +/// driver it then has to stop. Dropping it without building stops it. +pub struct DetectedDriver(Box); + +impl DetectedDriver { + /// Hand a started driver to the build step that will configure it. + pub fn new(driver: T) -> Self { + Self(Box::new(driver)) + } +} + +/// What a table-aware detection probe found. +pub enum DriverDetection { + /// The driver can serve with this table. It may carry the running driver + /// process, which the factory's build step takes with + /// [`ComputeDriverBuildContext::take_detected_driver`]. + Available(Option), + /// The driver's backend is not reachable with this table. + Unavailable(String), + /// The driver rejected this table. + InvalidConfig(String), + /// Starting the driver failed for another reason, such as a crash or a + /// timeout. Unlike an unreachable backend, this stops startup instead of + /// falling through to another driver. + Failed(String), +} + +/// What a table-aware detection probe receives. +pub struct DriverDetectionContext<'a> { + /// The driver's merged `[openshell.drivers.]` table. + pub table: &'a toml::map::Map, + /// `driver_dir` from `[openshell.gateway]`. + pub driver_dir: Option<&'a Path>, + pub gateway_log_level: &'a str, +} + +/// A table-aware detection probe. +pub type DriverDetectFn = fn(&DriverDetectionContext<'_>) -> DriverDetection; + +/// The driver a registration's detection started, shared by its clones. +type DetectedSlot = Arc>>; + +#[derive(Clone, Copy)] +enum DetectionProbe { + /// A cheap probe of the environment. + Environment(fn() -> bool), + /// A probe that needs the operator's table and may start the driver. + Table(DriverDetectFn), +} + /// One named compiled-driver registration. #[derive(Clone)] pub struct ComputeDriverRegistration { name: String, detection_priority: u16, - detect: Option bool>, + detect: Option, + detected: DetectedSlot, factory: Arc, telemetry_category: TelemetryComputeDriver, in_process_tracing: Option, @@ -1931,13 +1984,23 @@ impl ComputeDriverRegistration { Ok(Self { name, detection_priority, - detect, + detect: detect.map(DetectionProbe::Environment), + detected: DetectedSlot::default(), factory: Arc::new(factory), telemetry_category: TelemetryComputeDriver::custom(), in_process_tracing: None, }) } + /// Detect this driver with its own table instead of an environment + /// probe. The probe's result decides whether the driver is auto-selected; + /// an invalid table is logged and the next candidate is tried. + #[must_use] + pub fn with_table_detection(mut self, probe: DriverDetectFn) -> Self { + self.detect = Some(DetectionProbe::Table(probe)); + self + } + /// Assign a bounded telemetry category chosen by the binary composition /// boundary. Runtime driver names are never used as telemetry values. #[must_use] @@ -1974,6 +2037,10 @@ pub struct ComputeDriverRegistry { #[derive(Clone, Debug)] struct ComputeDriverDetection { available: Vec, + /// Why each candidate that was probed and not selected was passed over. + skipped: Vec<(String, String)>, + /// A candidate whose start failed outright, as `(driver, reason)`. + failure: Option<(String, String)>, } impl ComputeDriverDetection { @@ -2053,7 +2120,11 @@ impl ComputeDriverRegistry { .and_then(ComputeDriverRegistration::in_process_tracing) } - fn detect(&self) -> ComputeDriverDetection { + fn detect( + &self, + file: Option<&config_file::ConfigFile>, + gateway_log_level: &str, + ) -> ComputeDriverDetection { let mut candidates = self .drivers .values() @@ -2064,23 +2135,141 @@ impl ComputeDriverRegistry { .cmp(&right.detection_priority) .then_with(|| left.name.cmp(&right.name)) }); - let available = candidates - .into_iter() - .filter(|registration| registration.detect.is_some_and(|detect| detect())) - .map(|registration| registration.name.clone()) - .collect(); - ComputeDriverDetection { available } + let mut available = Vec::new(); + let mut skipped = Vec::new(); + let mut failure = None; + for registration in candidates { + match registration.detect { + Some(DetectionProbe::Environment(detect)) => { + if detect() { + available.push(registration.name.clone()); + } else { + skipped.push((registration.name.clone(), "not detected".to_string())); + } + } + Some(DetectionProbe::Table(probe)) => { + // A probe may start the driver, so run it only while no + // earlier candidate has been found. + if !available.is_empty() { + continue; + } + // Normalize legacy keys in a copy for this candidate alone, so + // the driver sees the same table it would after selection + // and no other candidate's trust configuration changes. + let mut candidate = file.cloned(); + if let Some(candidate) = candidate.as_mut() + && let Err(error) = config_file::normalize_legacy_podman_ca_bundle( + candidate, + ®istration.name, + ) + { + warn!( + driver = %registration.name, + %error, + "ignoring compute driver whose configuration is invalid" + ); + skipped.push(( + registration.name.clone(), + format!("invalid configuration: {error}"), + )); + continue; + } + let file = candidate.as_ref(); + let table = file + .map(|file| { + config_file::driver_table( + ®istration.name, + &file.openshell.gateway, + file.openshell.drivers.get(®istration.name), + ) + }) + .and_then(|value| match value { + toml::Value::Table(table) => Some(table), + _ => None, + }) + .unwrap_or_default(); + let context = DriverDetectionContext { + table: &table, + driver_dir: file + .and_then(|file| file.openshell.gateway.driver_dir.as_deref()), + gateway_log_level, + }; + match probe(&context) { + DriverDetection::Available(driver) => { + // Replacing an earlier detection stops that driver. + *registration + .detected + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = driver; + available.push(registration.name.clone()); + } + DriverDetection::Unavailable(reason) => { + debug!(driver = %registration.name, %reason, "compute driver is unavailable"); + skipped.push((registration.name.clone(), reason)); + } + DriverDetection::Failed(reason) => { + failure = Some((registration.name.clone(), reason)); + break; + } + DriverDetection::InvalidConfig(reason) => { + warn!( + driver = %registration.name, + %reason, + "ignoring compute driver whose configuration is invalid" + ); + skipped.push(( + registration.name.clone(), + format!("invalid configuration: {reason}"), + )); + } + } + } + None => {} + } + } + ComputeDriverDetection { + available, + skipped, + failure, + } } pub(crate) fn select(&self, configured_driver: Option<&str>) -> Result { + self.select_with_file(configured_driver, None, "info") + } + + /// Select the configured driver, or auto-detect one using the tables in + /// `file`. + pub(crate) fn select_with_file( + &self, + configured_driver: Option<&str>, + file: Option<&config_file::ConfigFile>, + gateway_log_level: &str, + ) -> Result { match configured_driver { None => { - let detection = self.detect(); + let detection = self.detect(file, gateway_log_level); + if let Some((name, reason)) = &detection.failure { + return Err(Error::execution(format!( + "compute driver '{name}' failed while auto-detection started it: {reason}" + ))); + } if detection.selected().is_none() { - return Err(Error::config( + let reasons = detection + .skipped + .iter() + .map(|(name, reason)| format!("{name}: {reason}")) + .collect::>() + .join("; "); + let detail = if reasons.is_empty() { + String::new() + } else { + format!(" ({reasons})") + }; + return Err(Error::config(format!( "no compute driver configured and auto-detection found no suitable installed \ - driver; set --compute-driver or OPENSHELL_COMPUTE_DRIVER=", - )); + driver{detail}; set --compute-driver or OPENSHELL_COMPUTE_DRIVER=" + ))); } Ok(ComputeDriverSelection::AutoDetected(detection)) } @@ -2146,6 +2335,21 @@ impl ComputeDriverConfigContext<'_> { self.driver_startup.gateway_tls_enabled } + /// `driver_dir` from `[openshell.gateway]`: where launched compute-driver + /// binaries are searched for first. + #[must_use] + pub fn driver_dir(&self) -> Option<&Path> { + self.driver_startup + .file + .and_then(|file| file.openshell.gateway.driver_dir.as_deref()) + } + + /// The selected driver's merged TOML table, undecoded. A launched driver + /// parses and validates it itself. + pub fn driver_table(&self) -> Result> { + compute::driver_config::driver_table_from_context(self.driver_startup, self.driver_name) + } + /// Deserialize the selected driver's merged TOML table. pub fn driver_config(&self) -> Result where @@ -2166,9 +2370,29 @@ pub struct ComputeDriverBuildContext<'a> { /// Pool size limits from `[openshell.gateway.supervisor_pool]`, defaults /// filled in. supervisor_pool_limits: openshell_supervisor_control::PoolLimits, + /// The driver this driver's detection started, if it did. + detected: DetectedSlot, } impl ComputeDriverBuildContext<'_> { + /// Take the driver process that auto-detection started and kept running + /// for this driver, if its type is `T`. Detection happens once, so a + /// second call returns `None`. + pub fn take_detected_driver(&self) -> Option { + let mut slot = self + .detected + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let detected = slot.take()?; + match detected.0.downcast::() { + Ok(driver) => Some(*driver), + Err(other) => { + *slot = Some(DetectedDriver(other)); + None + } + } + } + /// Register an optional in-process application endpoint resolver during build. /// Existing factories need not provide this extension. pub fn register_app_endpoints(&self, resolver: SharedComputeDriverAppEndpoints) -> Result<()> { @@ -2352,6 +2576,7 @@ async fn build_compute_runtime( supervisor_recovery_timeout_secs: supervisor_pool .and_then(|pool| pool.recovery_timeout_secs), supervisor_pool_limits, + detected: registration.detected.clone(), }; let (instance, image_updates) = registration .factory @@ -3043,6 +3268,7 @@ mod tests { }, shutdown_rx: shutdown_rx.clone(), shared_supervision: &shared, + detected: crate::DetectedSlot::default(), app_endpoint_resolver: &std::sync::OnceLock::new(), supervisor_recovery_timeout_secs: configured, supervisor_pool_limits: limits, @@ -3911,6 +4137,132 @@ mod tests { assert_eq!(registration.name, "detected"); } + mod table_detection { + use super::*; + use crate::{DriverDetectFn, DriverDetection, DriverDetectionContext}; + use std::sync::atomic::{AtomicUsize, Ordering}; + + static LATER_PROBES: AtomicUsize = AtomicUsize::new(0); + + fn invalid(_: &DriverDetectionContext<'_>) -> DriverDetection { + DriverDetection::InvalidConfig("unknown key".to_string()) + } + + fn unavailable(_: &DriverDetectionContext<'_>) -> DriverDetection { + DriverDetection::Unavailable("no socket".to_string()) + } + + fn available(_: &DriverDetectionContext<'_>) -> DriverDetection { + DriverDetection::Available(None) + } + + fn failed(_: &DriverDetectionContext<'_>) -> DriverDetection { + DriverDetection::Failed("crashed".to_string()) + } + + fn rejects_the_legacy_ca_alias(context: &DriverDetectionContext<'_>) -> DriverDetection { + if context.table.contains_key("additional_ca_bundle") { + DriverDetection::InvalidConfig("unknown key additional_ca_bundle".to_string()) + } else { + DriverDetection::Available(None) + } + } + + fn counted(_: &DriverDetectionContext<'_>) -> DriverDetection { + LATER_PROBES.fetch_add(1, Ordering::SeqCst); + DriverDetection::Available(None) + } + + fn registry( + candidates: &[(&str, u16, DriverDetectFn)], + ) -> super::super::ComputeDriverRegistry { + let mut registry = super::super::ComputeDriverRegistry::new(); + for (name, priority, probe) in candidates { + registry + .install( + super::super::ComputeDriverRegistration::new( + *name, + *priority, + None, + TestComputeDriverFactory, + ) + .unwrap() + .with_table_detection(*probe), + ) + .unwrap(); + } + registry + } + + #[test] + fn an_invalid_table_or_unavailable_backend_falls_through_to_the_next_candidate() { + let registry = registry(&[ + ("broken", 100, invalid), + ("absent", 150, unavailable), + ("working", 200, available), + ]); + let selection = registry.select(None).unwrap(); + assert_eq!(selection.name(), "working"); + } + + #[test] + fn candidates_after_the_first_available_one_are_not_started() { + LATER_PROBES.store(0, Ordering::SeqCst); + let registry = registry(&[("first", 100, available), ("later", 200, counted)]); + assert_eq!(registry.select(None).unwrap().name(), "first"); + assert_eq!(LATER_PROBES.load(Ordering::SeqCst), 0); + } + + #[test] + fn the_error_lists_every_candidates_reason() { + let registry = registry(&[("broken", 100, invalid), ("absent", 200, unavailable)]); + let error = registry.select(None).unwrap_err().to_string(); + assert!( + error.contains("broken: invalid configuration: unknown key"), + "{error}" + ); + assert!(error.contains("absent: no socket"), "{error}"); + } + + #[test] + fn a_crash_stops_startup_instead_of_falling_through() { + let registry = registry(&[("crashy", 100, failed), ("working", 200, available)]); + let error = registry.select(None).unwrap_err().to_string(); + assert!( + error.contains("crashy") && error.contains("crashed"), + "{error}" + ); + } + + #[test] + fn a_legacy_key_is_normalized_in_a_copy_before_the_driver_sees_the_table() { + let file: crate::config_file::ConfigFile = toml::from_str( + "[openshell]\nversion = 2\n[openshell.drivers.podman]\nadditional_ca_bundle = \"/etc/ca.pem\"\n", + ) + .unwrap(); + let registry = registry(&[("podman", 100, rejects_the_legacy_ca_alias)]); + + let selection = registry + .select_with_file(None, Some(&file), "info") + .expect("the alias is moved out of the table the driver receives"); + + assert_eq!(selection.name(), "podman"); + // The caller's configuration is untouched. + assert!( + file.openshell.drivers["podman"] + .as_table() + .unwrap() + .contains_key("additional_ca_bundle") + ); + } + + #[test] + fn a_named_driver_is_never_probed() { + let registry = registry(&[("broken", 100, invalid)]); + assert_eq!(registry.select(Some("broken")).unwrap().name(), "broken"); + } + } + #[test] fn registry_detection_reports_available_drivers_in_priority_order() { DETECTION_PROBE_ORDER.lock().unwrap().clear(); @@ -3949,7 +4301,7 @@ mod tests { ) .unwrap(); - let detection = registry.detect(); + let detection = registry.detect(None, "info"); assert_eq!(detection.selected(), Some("second")); assert_eq!( detection diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index f20bbbd3cb..c916f7020c 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -638,6 +638,7 @@ mod tests { let mut isolation_methods = BTreeSet::new(); let mut sandbox_protocol_methods = BTreeSet::new(); let mut supervisor_host_methods = BTreeSet::new(); + let mut driver_launch_methods = BTreeSet::new(); for file in &public.file { let package = file.package.as_deref().unwrap_or_default(); for service in &file.service { @@ -669,6 +670,16 @@ mod tests { method.name.as_deref().expect("supervisor host method name") })); } + // Private gateway-to-driver launch protocol: served by launched + // compute drivers, never part of the public SDK surface. + if package == "openshell.driver.launch.v1" { + assert_eq!(service_name, "DriverLaunch"); + driver_launch_methods.extend( + service.method.iter().map(|method| { + method.name.as_deref().expect("driver launch method name") + }), + ); + } if !matches!( (package, service_name), ( @@ -709,6 +720,10 @@ mod tests { BTreeSet::from(["Exchange", "Mediate"]) ); assert_eq!(supervisor_host_methods, BTreeSet::from(["Attach"])); + assert_eq!( + driver_launch_methods, + BTreeSet::from(["Configure", "GetLaunchInfo"]) + ); for signature in PROVIDER_READINESS_RPC_SIGNATURES { assert!( methods.iter().any(|method| method == signature), @@ -729,7 +744,7 @@ mod tests { } assert_eq!( compiled_method_count, - 121 + PROVIDER_READINESS_RPC_SIGNATURES.len() + 123 + PROVIDER_READINESS_RPC_SIGNATURES.len() + PEER_OWNER_RPC_SIGNATURES.len() + PEER_CONFIG_RPC_SIGNATURES.len() + isolation_methods.len() diff --git a/docs/extensibility/drivers.mdx b/docs/extensibility/drivers.mdx index 366be0af30..5dc88b76d5 100644 --- a/docs/extensibility/drivers.mdx +++ b/docs/extensibility/drivers.mdx @@ -31,6 +31,9 @@ to each driver crate: | Kubernetes | [`openshell-driver-kubernetes`](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-driver-kubernetes/README.md) | | Windows MXC | [`openshell-driver-mxc`](https://github.com/ai-openshell/openshell/blob/main/crates/openshell-driver-mxc/README.md) | +The gateway launches the VM, Podman, and Docker drivers itself. Refer to +[Launched drivers](/how-it-works/gateways/configuration#launched-drivers) for how the gateway starts them, delivers configuration, and detects them. + ### Using an External Compute Driver External compute drivers must implement [`compute_driver.proto`](https://github.com/ai-openshell/openshell/blob/main/proto/compute_driver.proto). diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index e4608bcbeb..19834d4ae1 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -1555,6 +1555,24 @@ policy_dns_ipv6_egress = "auto" nat64_prefixes = ["2001:db8:64::/96"] ``` +### Launched drivers + +The gateway launches the VM, Podman, and Docker drivers as subprocesses. Each driver reads and validates its own `[openshell.drivers.]` table, so the keys in the table stay the same. + +The gateway starts `openshell-driver- serve` and passes the table as text on the driver's standard input. After the driver accepts a connection, the gateway sends gateway-owned values over the private socket: the gateway port and listener, gateway name, guest CA path, trusted runtime images from the environment, destination trust, OTLP settings, and the admission policy. The command line carries only the socket path, the gateway's process ID, and the log level. Trace headers and other secrets never appear in arguments or the environment. + +A driver exits with status 69 when its backend is not reachable and 78 when its table is invalid. It writes one JSON line describing the reason to standard output first. Standard error stays for logs. The exit status decides what the gateway does; the line explains why, and a crash is never treated as an absent backend. + +The gateway owns the admission policy (`allow_driver_config` and `resource_admission`). It validates the keys, removes them from the forwarded table, and sends the policy in `Configure`. The drivers' tables reject `gateway_port`, `guest_tls_ca` and these keys. The gateway drops a legacy `gateway_port` from the Podman table with a warning, because earlier releases accepted and overwrote it. `grpc_endpoint` remains an optional override: `preflight` checks its syntax and scheme, and an `https://` endpoint needs the gateway CA. + +Set `driver_dir` in `[openshell.gateway]`. A `driver_dir` in a driver table is deprecated: the gateway removes it with a warning and uses it only when `[openshell.gateway]` sets none. The gateway looks for the driver binary in `driver_dir`, then in `~/.local/libexec/openshell`, `/usr/libexec/openshell`, `/usr/local/libexec/openshell`, and `/usr/local/libexec`, then next to the gateway binary. The binary must be owned by root or the gateway user and must not be writable by group or others. + +When no driver is selected, the gateway tries Kubernetes, then Podman, then Docker. For Podman and Docker it starts the driver with the operator's table, so a configured `socket_path` is honored. The first driver that binds its socket is kept and configured, so detection never starts a driver it then stops. For Docker it does the same with the Docker table. A table that is invalid, or a socket that is not reachable, moves detection to the next candidate and logs the reason. A driver that crashes or times out stops startup. If a driver is selected by name, any such failure stops startup, except that Podman is started again a few times while its socket is unreachable, as the in-process driver retried. + +Each launch gets its own private socket directory, which goes away with the driver. If a launched driver exits while the gateway is running, the gateway logs an error and exits with a nonzero status. Running sandboxes continue. + +`openshell-gateway config preflight` runs `openshell-driver- preflight` with the table. The driver checks the table and contacts no backend. + ### Kubernetes The gateway runs as a Pod and creates paired workload and supervisor Pods in another namespace. The gateway CA is projected from a Kubernetes Secret into supervisor Pods; user client certificate and key entries in that Secret are not exposed to either Pod. @@ -1975,15 +1993,15 @@ network_name = "openshell" # Rootless socket path. For root Podman use /run/podman/podman.sock. # Omit to auto-detect: the driver probes for a responsive Podman socket, then # asks the podman CLI where its socket is, and fails to start if neither finds -# one. Set this to pin a specific Podman machine instead. +# one. Set this to pin a specific Podman machine instead; gateway driver +# detection honors it too. socket_path = "/run/user/1000/podman/podman.sock" default_image = "nvcr.io/nvidia/base/ubuntu:24.04" image_pull_policy = "if_not_present" # always | if_not_present | never | newer # Optional override. When omitted, Linux uses gateway loopback and Podman -# Machine uses host.containers.internal. +# Machine uses host.containers.internal. An https:// endpoint needs the +# gateway CA from [openshell.gateway]. The gateway supplies the port. grpc_endpoint = "https://127.0.0.1:17670" -# The gateway overwrites gateway_port from bind_address at runtime. -gateway_port = 17670 # Trusted supervisor-side destination returned for host.openshell.internal. # Omit for the platform default: 127.0.0.1 on native Linux and # 192.168.127.254 on macOS Podman Machine. @@ -2127,6 +2145,8 @@ log_level = "info" compute_driver = "vm" # Gateway-owned CA injected into the selected local driver. guest_tls_ca = "/var/lib/openshell/guest-tls/ca.pem" +# Where the gateway looks for the openshell-driver-vm subprocess binary. +driver_dir = "/usr/local/libexec/openshell" # Sandbox launch signing is separate from listener and guest TLS. [openshell.gateway.gateway_jwt] @@ -2137,8 +2157,6 @@ gateway_id = "openshell" [openshell.drivers.vm] state_dir = "/var/lib/openshell/vm" -# Where the gateway looks for the openshell-driver-vm subprocess binary. -driver_dir = "/usr/local/libexec/openshell" default_image = "nvcr.io/nvidia/base/ubuntu:24.04" # Optional override. When omitted, the gateway derives # https://host.openshell.internal: for the VM driver. @@ -2310,7 +2328,7 @@ env PATH=/opt/company/e2fsprogs/sbin:/opt/company/e2fsprogs/bin:/usr/bin:/bin /u Replace the executable and configuration paths with your installation's paths, and run this command as the service account. Preflight and VM image operations search inherited `PATH` entries, then the existing e2fsprogs `sbin` and `bin` directories under `/opt/homebrew/opt/e2fsprogs` and `/usr/local/opt/e2fsprogs`. They prefer `mke2fs` and try `mkfs.ext4` only when `mke2fs` is absent. A selected file that cannot run is an error; fix that installation or the service's `PATH` before rerunning the command. -The command reports each selected executable path and version. Each tool receives only `-V`, with a five-second deadline and an 8 KiB output limit per stream. Missing, non-executable, outdated, or failing tools return a nonzero exit status with corrective guidance and the selected tool's error. The checks create no gateway state or images and do not start a driver or VM. Version checks confirm the installation; they do not test image creation or filesystem recovery. +The command reports each selected executable path and version. Each tool receives only `-V`, with a five-second deadline and an 8 KiB output limit per stream. Missing, non-executable, outdated, or failing tools return a nonzero exit status with corrective guidance and the selected tool's error. The checks create no gateway state or images and start no VM. The gateway runs the driver's `preflight` command, which only validates the table. Version checks confirm the installation; they do not test image creation or filesystem recovery. Other drivers do not require these VM tools. A VM configuration table alone does not select the VM driver. When a remote driver socket is configured, preflight reports that host tool checks were not performed; run the check on that host in the driver service's environment with a local VM configuration. diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index 8f62245c9c..c3d86e1a9b 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -534,6 +534,10 @@ ensure_sandbox_image_available() { } e2e_build_gateway_binaries "${ROOT}" TARGET_DIR GATEWAY_BIN CLI_BIN +# The gateway launches the Docker driver as a subprocess. Build it, or use the +# prebuilt one, and point the gateway at its directory. +e2e_build_external_driver \ + "${ROOT}" openshell-driver-docker openshell-driver-docker DRIVER_BIN export OPENSHELL_BIN="${CLI_BIN}" SUPERVISOR_IMAGE="$(resolve_docker_supervisor_image)" @@ -629,6 +633,7 @@ GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" { printf '[openshell]\nversion = 2\n\n' printf '[openshell.gateway]\nlog_level = "info"\n' + printf 'driver_dir = %s\n' "$(toml_string "$(dirname "${DRIVER_BIN}")")" if [ "${IMAGE_UPDATES_MODE}" = "1" ]; then printf 'enable_sandbox_updates = true\n' fi diff --git a/e2e/with-podman-gateway.sh b/e2e/with-podman-gateway.sh index 96b2091380..3041c40118 100755 --- a/e2e/with-podman-gateway.sh +++ b/e2e/with-podman-gateway.sh @@ -500,10 +500,10 @@ fi e2e_build_gateway_binaries "${ROOT}" TARGET_DIR GATEWAY_BIN CLI_BIN export OPENSHELL_BIN="${CLI_BIN}" -if [ "${OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER:-0}" = "1" ]; then - e2e_build_external_driver \ - "${ROOT}" openshell-driver-podman openshell-driver-podman DRIVER_BIN -fi +# A standalone lane starts the driver itself. Otherwise the gateway launches +# it, so build it (or use the prebuilt one) and point the gateway at it. +e2e_build_external_driver \ + "${ROOT}" openshell-driver-podman openshell-driver-podman DRIVER_BIN SUPERVISOR_IMAGE="$(resolve_podman_supervisor_image)" ensure_podman_supervisor_image "${SUPERVISOR_IMAGE}" @@ -601,6 +601,21 @@ if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then ' "${GATEWAY_CONFIG}" >"${CONFIG_WITH_ADDITIONAL_CA}" mv "${CONFIG_WITH_ADDITIONAL_CA}" "${GATEWAY_CONFIG}" fi +if [ "${OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER:-0}" != "1" ]; then + # The gateway launches the Podman driver from this directory. + CONFIG_WITH_DRIVER_DIR="${GATEWAY_CONFIG}.driver-dir" + awk -v driver_dir="$(e2e_podman_toml_string "$(dirname "${DRIVER_BIN}")")" ' + !inserted && $0 == "[openshell.gateway]" { + print + print "driver_dir = " driver_dir + inserted = 1 + next + } + { print } + END { if (!inserted) exit 42 } + ' "${GATEWAY_CONFIG}" >"${CONFIG_WITH_DRIVER_DIR}" + mv "${CONFIG_WITH_DRIVER_DIR}" "${GATEWAY_CONFIG}" +fi EXTERNAL_DRIVER_GRPC_ENDPOINT="https://127.0.0.1:${HOST_PORT}" EXTERNAL_DRIVER_HEALTH_CHECK_INTERVAL_SECS=10 EXTERNAL_DRIVER_ENABLE_BIND_MOUNTS=true diff --git a/install.sh b/install.sh index abbb624698..2704887cef 100755 --- a/install.sh +++ b/install.sh @@ -22,6 +22,8 @@ HOMEBREW_FORMULA_NAME="openshell" HOMEBREW_CLI_ASSET="openshell-aarch64-apple-darwin.tar.gz" HOMEBREW_GATEWAY_ASSET="openshell-gateway-aarch64-apple-darwin.tar.gz" HOMEBREW_DRIVER_VM_ASSET="openshell-driver-vm-aarch64-apple-darwin.tar.gz" +HOMEBREW_DRIVER_PODMAN_ASSET="openshell-driver-podman-aarch64-apple-darwin.tar.gz" +HOMEBREW_DRIVER_DOCKER_ASSET="openshell-driver-docker-aarch64-apple-darwin.tar.gz" HOMEBREW_PROVER_ASSET="openshell-prover-aarch64-apple-darwin.tar.gz" BREAKING_RELEASE_VERSION="0.0.37" LINUX_PACKAGE_GLIBC_MIN_VERSION="2.28" @@ -912,7 +914,7 @@ patch_prerelease_homebrew_formula_urls() { _formula_file="$1" [ -n "$RELEASE_ASSET_DIR" ] || return 0 - for _asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_PROVER_ASSET"; do + for _asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_DRIVER_PODMAN_ASSET" "$HOMEBREW_DRIVER_DOCKER_ASSET" "$HOMEBREW_PROVER_ASSET"; do if [ ! -f "${RELEASE_ASSET_DIR}/${_asset}" ]; then error "prerelease artifact is missing the required macOS asset: ${_asset}" fi @@ -925,6 +927,8 @@ patch_prerelease_homebrew_formula_urls() { -e "s#${_release_asset_url}/${HOMEBREW_CLI_ASSET}#${_local_asset_url}/${HOMEBREW_CLI_ASSET}#g" \ -e "s#${_release_asset_url}/${HOMEBREW_GATEWAY_ASSET}#${_local_asset_url}/${HOMEBREW_GATEWAY_ASSET}#g" \ -e "s#${_release_asset_url}/${HOMEBREW_DRIVER_VM_ASSET}#${_local_asset_url}/${HOMEBREW_DRIVER_VM_ASSET}#g" \ + -e "s#${_release_asset_url}/${HOMEBREW_DRIVER_PODMAN_ASSET}#${_local_asset_url}/${HOMEBREW_DRIVER_PODMAN_ASSET}#g" \ + -e "s#${_release_asset_url}/${HOMEBREW_DRIVER_DOCKER_ASSET}#${_local_asset_url}/${HOMEBREW_DRIVER_DOCKER_ASSET}#g" \ -e "s#${_release_asset_url}/${HOMEBREW_PROVER_ASSET}#${_local_asset_url}/${HOMEBREW_PROVER_ASSET}#g" \ "$_formula_file" >"$_patched_file" mv "$_patched_file" "$_formula_file" diff --git a/openshell.spec b/openshell.spec index 59b9db5d8e..a226b5eb83 100644 --- a/openshell.spec +++ b/openshell.spec @@ -114,6 +114,8 @@ grep -q 'version = "%{openshell_cargo_version}"' Cargo.toml || (echo "ERROR: Car test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell" test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-gateway" test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-prover" +test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-driver-podman" +test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-driver-docker" # Generate vendored crate manifest and license metadata. # cargo-vendor.txt is consumed by an RPM generator (from cargo-rpm-macros) @@ -136,6 +138,12 @@ install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-prover" %{buildroo # --- Gateway binary --- install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-gateway" %{buildroot}%{_bindir}/%{name}-gateway +# --- Podman compute driver, launched by the gateway --- +install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-driver-podman" %{buildroot}%{_libexecdir}/%{name}/%{name}-driver-podman + +# --- Docker compute driver, launched by the gateway --- +install -Dpm 0755 "${OPENSHELL_PREBUILT_BINARIES_DIR}/%{name}-driver-docker" %{buildroot}%{_libexecdir}/%{name}/%{name}-driver-docker + # --- Default gateway TOML config template --- # Shipped as a read-only reference in %{_datadir}. The systemd unit seeds a # user-level copy at ~/.config/openshell/gateway.toml on first start. @@ -315,6 +323,8 @@ grep -q 'gateway.toml.default.v1' %{buildroot}%{_userunitdir}/%{name}-gateway.se %doc %{_docdir}/%{name}-gateway/CONFIGURATION.md %doc %{_docdir}/%{name}-gateway/TROUBLESHOOTING.md %{_bindir}/%{name}-gateway +%{_libexecdir}/%{name}/%{name}-driver-podman +%{_libexecdir}/%{name}/%{name}-driver-docker %{_userunitdir}/%{name}-gateway.service %{_libexecdir}/%{name}-gateway-migrate-config %{_datadir}/%{name}-gateway/gateway.toml.default diff --git a/proto/driver_launch.proto b/proto/driver_launch.proto new file mode 100644 index 0000000000..077a4e475f --- /dev/null +++ b/proto/driver_launch.proto @@ -0,0 +1,96 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +syntax = "proto3"; + +package openshell.driver.launch.v1; + +// Private gateway-to-driver launch protocol. +// +// The gateway starts a compute driver with only bootstrap arguments and the +// operator's driver table on stdin. Once the driver is serving on its private +// socket, the gateway calls GetLaunchInfo and then Configure to deliver +// gateway-owned metadata. Until Configure succeeds, every other service the +// driver serves returns UNAVAILABLE. +service DriverLaunch { + // Identify the driver and the protocol versions and features it supports. + // Answers before Configure. + rpc GetLaunchInfo(GetLaunchInfoRequest) returns (GetLaunchInfoResponse); + + // Deliver gateway-owned metadata. Succeeds at most once. A call that fails + // with INVALID_ARGUMENT or FAILED_PRECONDITION leaves the driver running and + // the gateway may retry. A request is at most 1 MiB. + rpc Configure(ConfigureRequest) returns (ConfigureResponse); +} + +message GetLaunchInfoRequest {} + +message GetLaunchInfoResponse { + string driver_name = 1; + string driver_version = 2; + repeated uint32 protocol_versions = 3; + repeated string features = 4; +} + +message ConfigureRequest { + uint32 protocol_version = 1; + // Features the gateway requires. The driver rejects any it does not know + // with FAILED_PRECONDITION. + repeated string required_features = 2; + GatewayContext gateway = 3; + // Unset means there is no trust bundle. + NetworkTrust network_trust = 4; + ImageOverrides image_overrides = 5; + Telemetry telemetry = 6; + // The operator's admission policy as JSON: `allow_driver_config` and + // `resource_admission`. The gateway owns and validates it. The driver + // applies it until `ComputeDriver` reports resolved resource labels to the + // gateway. Empty means the defaults. + string admission_json = 7; +} + +message ConfigureResponse {} + +message GatewayContext { + uint32 gateway_port = 1; + string tls_ca_path = 2; + string gateway_name = 3; + // The gateway's listener, `ip:port`. Drivers that choose how sandboxes reach + // the gateway from its bind address, such as Docker, use it. + string bind_address = 4; +} + +message NetworkTrust { + string artifact_path = 1; + string digest = 2; + uint32 certificate_count = 3; +} + +// From OPENSHELL_SANDBOX_RUNTIME_IMAGE and OPENSHELL_SUPERVISOR_IMAGE. +message ImageOverrides { + optional string sandbox_runtime_image = 1; + optional string supervisor_image = 2; +} + +message Telemetry { + // The driver's own exporter and the supervisors. + OtlpExport traces = 1; + // Supervisors. + OtlpExport ocsf = 2; + // Supervisors. + OtlpExport agent = 3; + CollectorTls collector = 4; + // Secret, in OTEL_EXPORTER_OTLP_TRACES_HEADERS format. + string trace_headers = 5; +} + +message OtlpExport { + string endpoint = 1; + string protocol = 2; +} + +message CollectorTls { + string ca_file = 1; + string cert_file = 2; + string key_file = 3; +} diff --git a/snapcraft.yaml b/snapcraft.yaml index ca5d7cc2e0..633e27450f 100644 --- a/snapcraft.yaml +++ b/snapcraft.yaml @@ -190,7 +190,7 @@ parts: set -euo pipefail MISSING=() - for bin in openshell openshell-prover openshell-gateway openshell-sandbox openshell-gateway-wrapper; do + for bin in openshell openshell-prover openshell-gateway openshell-driver-docker openshell-sandbox openshell-gateway-wrapper; do if [ ! -f "$CRAFT_PART_SRC/$bin" ]; then MISSING+=("$bin") fi @@ -212,6 +212,10 @@ parts: "$CRAFT_PART_INSTALL/bin/openshell-prover" install -D -m 0755 "$CRAFT_PART_SRC/openshell-gateway" \ "$CRAFT_PART_INSTALL/bin/openshell-gateway" + # The gateway launches the Docker driver as a subprocess. It finds it + # in $SNAP/libexec/openshell, next to the gateway's prefix. + install -D -m 0755 "$CRAFT_PART_SRC/openshell-driver-docker" \ + "$CRAFT_PART_INSTALL/libexec/openshell/openshell-driver-docker" install -D -m 0755 "$CRAFT_PART_SRC/openshell-sandbox" \ "$CRAFT_PART_INSTALL/bin/openshell-sandbox" install -D -m 0755 "$CRAFT_PART_SRC/openshell-gateway-wrapper" \ diff --git a/tasks/scripts/gateway-docker.sh b/tasks/scripts/gateway-docker.sh index 5a951eb28d..e507cc0ba5 100644 --- a/tasks/scripts/gateway-docker.sh +++ b/tasks/scripts/gateway-docker.sh @@ -140,9 +140,10 @@ if [[ -n "${CARGO_BUILD_JOBS:-}" ]]; then CARGO_BUILD_JOBS_ARG=(-j "${CARGO_BUILD_JOBS}") fi -echo "Building openshell-gateway..." +echo "Building openshell-gateway and openshell-driver-docker..." cargo build ${CARGO_BUILD_JOBS_ARG[@]+"${CARGO_BUILD_JOBS_ARG[@]}"} \ - -p openshell-gateway --bin openshell-gateway + -p openshell-gateway --bin openshell-gateway \ + -p openshell-driver-docker --bin openshell-driver-docker TLS_DIR="${STATE_DIR}/tls" echo "Generating local gateway credentials..." @@ -161,6 +162,7 @@ version = 2 [openshell.gateway] name = "${GATEWAY_NAME}" compute_driver = "docker" +driver_dir = "${ROOT}/target/debug" disable_tls = true [openshell.gateway.auth] diff --git a/tasks/scripts/gateway-podman.sh b/tasks/scripts/gateway-podman.sh index bb837e464a..8a5ea15211 100644 --- a/tasks/scripts/gateway-podman.sh +++ b/tasks/scripts/gateway-podman.sh @@ -161,9 +161,11 @@ ensure_podman_runtime_image \ "sandbox runtime" export OPENSHELL_SUPERVISOR_IMAGE="${SUPERVISOR_IMAGE}" -echo "Building openshell-gateway..." +echo "Building openshell-gateway and openshell-driver-podman..." require_mise mise run build:gateway +# The gateway launches the Podman driver as a subprocess. +cargo build -p openshell-driver-podman if [[ ! -x "${GATEWAY_BIN}" ]]; then echo "ERROR: expected gateway binary at ${GATEWAY_BIN}" >&2 @@ -190,6 +192,7 @@ version = 2 [openshell.gateway] name = "${GATEWAY_NAME}" compute_driver = "podman" +driver_dir = "${ROOT}/target/debug" disable_tls = true [openshell.gateway.auth] diff --git a/tasks/scripts/gateway-vm.sh b/tasks/scripts/gateway-vm.sh index 8a35cc41e6..e30d0e7e4e 100755 --- a/tasks/scripts/gateway-vm.sh +++ b/tasks/scripts/gateway-vm.sh @@ -333,6 +333,7 @@ version = 2 [openshell.gateway] name = "${GATEWAY_NAME}" compute_driver = "vm" +driver_dir = "${DRIVER_DIR}" disable_tls = ${DISABLE_TLS} [openshell.gateway.auth] @@ -348,7 +349,6 @@ gateway_id = "${GATEWAY_NAME}" default_image = "${SANDBOX_IMAGE}" bootstrap_image = "${VM_BOOTSTRAP_IMAGE}" grpc_endpoint = "${GRPC_ENDPOINT}" -driver_dir = "${DRIVER_DIR}" state_dir = "${VM_DRIVER_STATE_DIR}" EOF diff --git a/tasks/scripts/package-deb-install.sh b/tasks/scripts/package-deb-install.sh index bd95a13e49..e2e34ad5cf 100755 --- a/tasks/scripts/package-deb-install.sh +++ b/tasks/scripts/package-deb-install.sh @@ -58,13 +58,17 @@ cargo build --release \ -p openshell-cli \ -p openshell-gateway \ -p openshell-prover-cli \ - -p openshell-driver-vm + -p openshell-driver-vm \ + -p openshell-driver-podman \ + -p openshell-driver-docker echo "==> Building Debian package" OPENSHELL_CLI_BINARY="${repo_root}/target/release/openshell" \ OPENSHELL_GATEWAY_BINARY="${repo_root}/target/release/openshell-gateway" \ OPENSHELL_PROVER_BINARY="${repo_root}/target/release/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="${repo_root}/target/release/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="${repo_root}/target/release/openshell-driver-podman" \ + OPENSHELL_DRIVER_DOCKER_BINARY="${repo_root}/target/release/openshell-driver-docker" \ OPENSHELL_DEB_VERSION="$VERSION" \ OPENSHELL_DEB_ARCH="$ARCH" \ OPENSHELL_OUTPUT_DIR="$OUTPUT_DIR" \ diff --git a/tasks/scripts/package-deb.sh b/tasks/scripts/package-deb.sh index c2492dd242..912c9bfcf4 100755 --- a/tasks/scripts/package-deb.sh +++ b/tasks/scripts/package-deb.sh @@ -23,6 +23,8 @@ Required environment: OPENSHELL_GATEWAY_BINARY Path to openshell-gateway OPENSHELL_PROVER_BINARY Path to openshell-prover OPENSHELL_DRIVER_VM_BINARY Path to openshell-driver-vm + OPENSHELL_DRIVER_PODMAN_BINARY Path to openshell-driver-podman + OPENSHELL_DRIVER_DOCKER_BINARY Path to openshell-driver-docker OPENSHELL_DEB_VERSION Debian package version Optional environment: @@ -72,6 +74,8 @@ require_env OPENSHELL_CLI_BINARY require_env OPENSHELL_GATEWAY_BINARY require_env OPENSHELL_PROVER_BINARY require_env OPENSHELL_DRIVER_VM_BINARY +require_env OPENSHELL_DRIVER_PODMAN_BINARY +require_env OPENSHELL_DRIVER_DOCKER_BINARY require_env OPENSHELL_DEB_VERSION OPENSHELL_DEB_ARCH="${OPENSHELL_DEB_ARCH:-$(infer_deb_arch)}" @@ -114,6 +118,8 @@ stage_binary "$OPENSHELL_CLI_BINARY" "$pkgroot/usr/bin/openshell" stage_binary "$OPENSHELL_GATEWAY_BINARY" "$pkgroot/usr/bin/openshell-gateway" stage_binary "$OPENSHELL_PROVER_BINARY" "$pkgroot/usr/bin/openshell-prover" stage_binary "$OPENSHELL_DRIVER_VM_BINARY" "$pkgroot/usr/libexec/openshell/openshell-driver-vm" +stage_binary "$OPENSHELL_DRIVER_PODMAN_BINARY" "$pkgroot/usr/libexec/openshell/openshell-driver-podman" +stage_binary "$OPENSHELL_DRIVER_DOCKER_BINARY" "$pkgroot/usr/libexec/openshell/openshell-driver-docker" # Per-user systemd unit. Each user enables it via `systemctl --user`. install -D -m 0644 "$src_dir/openshell-gateway.service" \ diff --git a/tasks/scripts/release.py b/tasks/scripts/release.py index c62ec0b67a..f41f174b26 100644 --- a/tasks/scripts/release.py +++ b/tasks/scripts/release.py @@ -37,6 +37,8 @@ class Versions: HOMEBREW_CLI_ASSET = f"openshell-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_GATEWAY_ASSET = f"openshell-gateway-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_DRIVER_VM_ASSET = f"openshell-driver-vm-{HOMEBREW_TARGET}.tar.gz" +HOMEBREW_DRIVER_PODMAN_ASSET = f"openshell-driver-podman-{HOMEBREW_TARGET}.tar.gz" +HOMEBREW_DRIVER_DOCKER_ASSET = f"openshell-driver-docker-{HOMEBREW_TARGET}.tar.gz" HOMEBREW_PROVER_ASSET = f"openshell-prover-{HOMEBREW_TARGET}.tar.gz" GITHUB_RELEASE_DOWNLOADS = "https://github.com/ai-openshell/openshell/releases/download" LOCAL_GATEWAY_PORT = 17670 @@ -311,6 +313,8 @@ def render_homebrew_formula( cli_sha256: str, gateway_sha256: str, driver_vm_sha256: str, + driver_podman_sha256: str, + driver_docker_sha256: str, prover_sha256: str, ) -> str: if not _RELEASE_TAG_RE.fullmatch(release_tag): @@ -343,6 +347,16 @@ class Openshell < Formula sha256 "{driver_vm_sha256}" end + resource "openshell-driver-podman" do + url "{_asset_url(release_tag, HOMEBREW_DRIVER_PODMAN_ASSET)}" + sha256 "{driver_podman_sha256}" + end + + resource "openshell-driver-docker" do + url "{_asset_url(release_tag, HOMEBREW_DRIVER_DOCKER_ASSET)}" + sha256 "{driver_docker_sha256}" + end + resource "openshell-prover" do url "{_asset_url(release_tag, HOMEBREW_PROVER_ASSET)}" sha256 "{prover_sha256}" @@ -361,6 +375,14 @@ def install libexec.install "openshell-driver-vm" end + resource("openshell-driver-podman").stage do + libexec.install "openshell-driver-podman" + end + + resource("openshell-driver-docker").stage do + libexec.install "openshell-driver-docker" + end + resource("openshell-prover").stage do bin.install "openshell-prover" end @@ -518,6 +540,16 @@ def generate_homebrew_formula( HOMEBREW_DRIVER_VM_ASSET, checksums_path, ), + driver_podman_sha256=_required_checksum( + checksums, + HOMEBREW_DRIVER_PODMAN_ASSET, + checksums_path, + ), + driver_docker_sha256=_required_checksum( + checksums, + HOMEBREW_DRIVER_DOCKER_ASSET, + checksums_path, + ), prover_sha256=_required_checksum( prover_checksums, HOMEBREW_PROVER_ASSET, diff --git a/tasks/scripts/release_formula_test.py b/tasks/scripts/release_formula_test.py index 789c59b727..faa79a22ed 100644 --- a/tasks/scripts/release_formula_test.py +++ b/tasks/scripts/release_formula_test.py @@ -19,6 +19,8 @@ def test_generate_homebrew_formula_uses_channel_urls_and_exact_version( [ "a" * 64 + " openshell-aarch64-apple-darwin.tar.gz", "b" * 64 + " openshell-driver-vm-aarch64-apple-darwin.tar.gz", + "c" * 64 + " openshell-driver-podman-aarch64-apple-darwin.tar.gz", + "f" * 64 + " openshell-driver-docker-aarch64-apple-darwin.tar.gz", ] ) + "\n", @@ -55,6 +57,20 @@ def test_generate_homebrew_formula_uses_channel_urls_and_exact_version( "https://github.com/ai-openshell/openshell/releases/download/" "v0.1.0-pre.3/openshell-driver-vm-aarch64-apple-darwin.tar.gz" ) in formula + assert ( + "https://github.com/ai-openshell/openshell/releases/download/" + "v0.1.0-pre.3/openshell-driver-podman-aarch64-apple-darwin.tar.gz" + ) in formula + assert 'sha256 "' + "c" * 64 + '"' in formula + assert 'resource("openshell-driver-podman").stage' in formula + assert 'libexec.install "openshell-driver-podman"' in formula + assert ( + "https://github.com/ai-openshell/openshell/releases/download/" + "v0.1.0-pre.3/openshell-driver-docker-aarch64-apple-darwin.tar.gz" + ) in formula + assert 'sha256 "' + "f" * 64 + '"' in formula + assert 'resource("openshell-driver-docker").stage' in formula + assert 'libexec.install "openshell-driver-docker"' in formula assert 'version "0.1.0-pre.3"' in formula assert 'sha256 "' + "b" * 64 + '"' in formula assert ( diff --git a/tasks/scripts/test-install-sh.sh b/tasks/scripts/test-install-sh.sh index fe40564525..4d64178ec8 100755 --- a/tasks/scripts/test-install-sh.sh +++ b/tasks/scripts/test-install-sh.sh @@ -1040,7 +1040,7 @@ if [ "$(cat "$downloaded_checksum")" != "checksums" ]; then exit 1 fi -for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_PROVER_ASSET"; do +for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_DRIVER_PODMAN_ASSET" "$HOMEBREW_DRIVER_DOCKER_ASSET" "$HOMEBREW_PROVER_ASSET"; do : >"${RELEASE_ASSET_DIR}/${asset}" done prerelease_formula="${tmpdir}/openshell.rb" @@ -1048,10 +1048,12 @@ printf '%s\n' \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_CLI_ASSET}\"" \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_GATEWAY_ASSET}\"" \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_DRIVER_VM_ASSET}\"" \ + " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_DRIVER_PODMAN_ASSET}\"" \ + " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_DRIVER_DOCKER_ASSET}\"" \ " url \"${GITHUB_URL}/releases/download/${RELEASE_TAG}/${HOMEBREW_PROVER_ASSET}\"" \ >"$prerelease_formula" patch_prerelease_homebrew_formula_urls "$prerelease_formula" -for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_PROVER_ASSET"; do +for asset in "$HOMEBREW_CLI_ASSET" "$HOMEBREW_GATEWAY_ASSET" "$HOMEBREW_DRIVER_VM_ASSET" "$HOMEBREW_DRIVER_PODMAN_ASSET" "$HOMEBREW_DRIVER_DOCKER_ASSET" "$HOMEBREW_PROVER_ASSET"; do if ! grep -Fq "file://${RELEASE_ASSET_DIR}/${asset}" "$prerelease_formula"; then echo "FAIL: prerelease formula did not use local asset ${asset}" >&2 exit 1 diff --git a/tasks/scripts/test-packaging-assets.sh b/tasks/scripts/test-packaging-assets.sh index 6ae81fe64b..c19be05281 100755 --- a/tasks/scripts/test-packaging-assets.sh +++ b/tasks/scripts/test-packaging-assets.sh @@ -89,6 +89,16 @@ assert_contains "$spec" 'ExecStartPre=/usr/bin/openshell-gateway config prefligh assert_contains "$spec" '%package prover' assert_contains "$spec" '%files prover' assert_contains "$spec" '%{_bindir}/%{name}-prover' +assert_contains "$spec" 'test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-driver-podman"' +assert_contains "$spec" 'test -x "${OPENSHELL_PREBUILT_BINARIES_DIR}/openshell-driver-docker"' +assert_contains "$spec" '%{_libexecdir}/%{name}/%{name}-driver-podman' +assert_contains "$spec" '%{_libexecdir}/%{name}/%{name}-driver-docker' +assert_contains "$ROOT/.github/workflows/build-binaries-linux.yml" 'PACKAGE: openshell-driver-podman' +assert_contains "$ROOT/.github/workflows/build-binaries-linux.yml" 'PACKAGE: openshell-driver-docker' +assert_contains "$ROOT/.github/workflows/deb-package.yml" 'OPENSHELL_DRIVER_PODMAN_BINARY=' +assert_contains "$ROOT/.github/workflows/deb-package.yml" 'OPENSHELL_DRIVER_DOCKER_BINARY=' +assert_contains "$ROOT/.github/workflows/build-rpm.yml" 'openshell-driver-podman-${{ inputs.gateway-target }}' +assert_contains "$ROOT/.github/workflows/build-rpm.yml" 'openshell-driver-docker-${{ inputs.gateway-target }}' assert_not_contains "$spec" '%%S/openshell/tls' # Installed-package qualification must select the candidate trusted runtime @@ -223,7 +233,7 @@ assert_contains "$snap_publish_workflow" 'component_args+=(--component "${compon assert_contains "$snap_publish_workflow" 'group: snap-publish-${{ inputs.upload-channel }}-${{ matrix.arch }}' assert_contains "$snap_publish_workflow" 'cancel-in-progress: false' assert_contains "$snap_publish_workflow" 'queue: max' -assert_contains "$snapcraft" 'for bin in openshell openshell-prover openshell-gateway openshell-sandbox openshell-gateway-wrapper; do' +assert_contains "$snapcraft" 'for bin in openshell openshell-prover openshell-gateway openshell-driver-docker openshell-sandbox openshell-gateway-wrapper; do' assert_contains "$snapcraft" '"$CRAFT_PART_INSTALL/bin/openshell-prover"' if ! awk ' /^ prover:$/ { in_prover = 1; next } @@ -271,6 +281,8 @@ assert_contains "$snap_install_docs" 'tls-backup-$(date +%s%N)' assert_contains "$snap_install_docs" "sudo snap set openshell gateway-mode=user" assert_contains "$snap_install_docs" "sudo snap set openshell gateway-mode=system" assert_contains "$snapcraft" "gateway-mode=disable" +assert_contains "$snapcraft" 'libexec/openshell/openshell-driver-docker' +assert_contains "$ROOT/.github/workflows/snap-package.yml" 'openshell-driver-docker-${{ matrix.rust_arch }}-unknown-linux-gnu' assert_not_contains "$snap_install_docs" "snap services --user" assert_contains "$snap_canary" "install.sh | sh" assert_contains "$snap_canary" "ubuntu-snap-system-docker:" @@ -298,7 +310,7 @@ if command -v dpkg-deb >/dev/null 2>&1; then package_work=$(mktemp -d "${TMPDIR:-/tmp}/openshell-package-assets.XXXXXX") trap 'rm -rf "$package_work"' EXIT mkdir -p "$package_work/bin" "$package_work/output" - for binary in openshell openshell-gateway openshell-prover openshell-driver-vm; do + for binary in openshell openshell-gateway openshell-prover openshell-driver-vm openshell-driver-podman openshell-driver-docker; do printf '#!/bin/sh\nexit 0\n' >"$package_work/bin/$binary" chmod +x "$package_work/bin/$binary" done @@ -306,6 +318,8 @@ if command -v dpkg-deb >/dev/null 2>&1; then OPENSHELL_GATEWAY_BINARY="$package_work/bin/openshell-gateway" \ OPENSHELL_PROVER_BINARY="$package_work/bin/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="$package_work/bin/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="$package_work/bin/openshell-driver-podman" \ + OPENSHELL_DRIVER_DOCKER_BINARY="$package_work/bin/openshell-driver-docker" \ OPENSHELL_DEB_VERSION=0.0.0 \ OPENSHELL_DEB_ARCH=amd64 \ OPENSHELL_OUTPUT_DIR="$package_work/output" \ @@ -322,6 +336,13 @@ if command -v dpkg-deb >/dev/null 2>&1; then echo "FAIL: package-deb did not stage openshell-prover" >&2 exit 1 fi + for driver in openshell-driver-vm openshell-driver-podman openshell-driver-docker; do + if ! dpkg-deb --fsys-tarfile "$package_work/output/openshell_0.0.0_amd64.deb" \ + | tar -tf - | grep -x "./usr/libexec/openshell/$driver" >/dev/null; then + echo "FAIL: package-deb did not stage $driver" >&2 + exit 1 + fi + done else echo "SKIP: dpkg-deb unavailable; Debian artifact staging requires its assigned lane" fi diff --git a/tasks/scripts/vm/smoke-orphan-cleanup.sh b/tasks/scripts/vm/smoke-orphan-cleanup.sh index f747b195f7..2024ce375e 100755 --- a/tasks/scripts/vm/smoke-orphan-cleanup.sh +++ b/tasks/scripts/vm/smoke-orphan-cleanup.sh @@ -58,11 +58,11 @@ version = 2 [openshell.gateway] compute_driver = "vm" +driver_dir = "$ROOT/target/debug" disable_tls = true [openshell.drivers.vm] grpc_endpoint = "http://host.containers.internal:$PORT" -driver_dir = "$ROOT/target/debug" state_dir = "$STATE_DIR" EOF OPENSHELL_SERVER_PORT="$PORT" \ diff --git a/tests/tmachine/artifacts.nix b/tests/tmachine/artifacts.nix index d8b743b803..7b2708473d 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -201,6 +201,8 @@ rec { cargo build --target ${gnuToolchain.target} \ -p openshell-gateway \ + -p openshell-driver-podman \ + -p openshell-driver-docker \ -p openshell-supervisor install -D -m 0755 \ @@ -215,6 +217,14 @@ rec { target/${gnuToolchain.target}/debug/openshell-gateway \ artifacts/binaries/${gnuToolchain.target}/openshell-gateway + install -D -m 0755 \ + target/${gnuToolchain.target}/debug/openshell-driver-podman \ + artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman + + install -D -m 0755 \ + target/${gnuToolchain.target}/debug/openshell-driver-docker \ + artifacts/binaries/${gnuToolchain.target}/openshell-driver-docker + install -D -m 0755 \ target/${gnuToolchain.target}/debug/openshell-supervisor \ artifacts/binaries/${gnuToolchain.target}/openshell-supervisor @@ -385,6 +395,8 @@ rec { OPENSHELL_GATEWAY_BINARY="$root/artifacts/binaries/${gnuToolchain.target}/openshell-gateway" \ OPENSHELL_PROVER_BINARY="$root/artifacts/binaries/${muslToolchain.target}/openshell-prover" \ OPENSHELL_DRIVER_VM_BINARY="$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-vm" \ + OPENSHELL_DRIVER_PODMAN_BINARY="$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman" \ + OPENSHELL_DRIVER_DOCKER_BINARY="$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-docker" \ OPENSHELL_DEB_VERSION="$package_version" \ OPENSHELL_DEB_ARCH=${dockerArch} \ OPENSHELL_OUTPUT_DIR="$root/artifacts/packages" \ @@ -420,6 +432,8 @@ rec { for binary in \ artifacts/binaries/${muslToolchain.target}/openshell \ artifacts/binaries/${gnuToolchain.target}/openshell-gateway \ + artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman \ + artifacts/binaries/${gnuToolchain.target}/openshell-driver-docker \ artifacts/binaries/${muslToolchain.target}/openshell-prover; do if [[ ! -x "$binary" ]]; then echo "missing $binary; run build-artifacts-binaries first" >&2 @@ -438,6 +452,8 @@ rec { --volume "$root:/repo:ro" \ --volume "$root/artifacts/binaries/${muslToolchain.target}/openshell:/binaries/openshell:ro" \ --volume "$root/artifacts/binaries/${gnuToolchain.target}/openshell-gateway:/binaries/openshell-gateway:ro" \ + --volume "$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-podman:/binaries/openshell-driver-podman:ro" \ + --volume "$root/artifacts/binaries/${gnuToolchain.target}/openshell-driver-docker:/binaries/openshell-driver-docker:ro" \ --volume "$root/artifacts/binaries/${muslToolchain.target}/openshell-prover:/binaries/openshell-prover:ro" \ --volume "$output_dir:/out" \ --volume openshell-rpm-cargo:/root/.cargo/registry \