diff --git a/.github/workflows/actionlint.yaml b/.github/workflows/actionlint.yaml index ea1cd7e3c..c33d136e1 100644 --- a/.github/workflows/actionlint.yaml +++ b/.github/workflows/actionlint.yaml @@ -15,7 +15,7 @@ jobs: actionlint: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Run actionlint uses: unikraft-cloud/x/.github/actions/actionlint@prod-staging diff --git a/.github/workflows/build.yaml b/.github/workflows/build.yaml index 1f55e7217..ac2257981 100644 --- a/.github/workflows/build.yaml +++ b/.github/workflows/build.yaml @@ -47,12 +47,12 @@ jobs: steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 - name: Setup Go - uses: actions/setup-go@v7 + uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod @@ -66,7 +66,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} @@ -76,7 +76,7 @@ jobs: ${{ github.job }}-${{ runner.os }}-go- - name: Install Task - uses: go-task/setup-task@v2 + uses: go-task/setup-task@a00fbb05ce67b35648be3c78cbc9fd85354c757e # v2.2.0 - name: Build shell: bash @@ -84,7 +84,7 @@ jobs: VERSION=pr-${{ github.event.number }} GOOS=${{ matrix.GOOS }} GOARCH=${{ matrix.GOARCH }} task --yes ${{ matrix.task || 'cli' }} - name: Upload build artifacts to GitHub - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: github.event_name == 'push' with: name: unikraft-cli-${{ matrix.GOOS }}-${{ matrix.GOARCH }}-${{ github.sha }} diff --git a/.github/workflows/check-pr.yaml b/.github/workflows/check-pr.yaml index 1f40de4b9..0499f84ae 100644 --- a/.github/workflows/check-pr.yaml +++ b/.github/workflows/check-pr.yaml @@ -9,7 +9,7 @@ jobs: check-pr: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 diff --git a/.github/workflows/check-static.yaml b/.github/workflows/check-static.yaml index fa97e4b5f..fc8792be8 100644 --- a/.github/workflows/check-static.yaml +++ b/.github/workflows/check-static.yaml @@ -24,11 +24,11 @@ jobs: go: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - uses: go-task/setup-task@v2 + - uses: go-task/setup-task@a00fbb05ce67b35648be3c78cbc9fd85354c757e # v2.2.0 - - uses: actions/setup-go@v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod @@ -42,7 +42,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} diff --git a/.github/workflows/docs.yaml b/.github/workflows/docs.yaml index 5dedcf7e5..04349f1ec 100644 --- a/.github/workflows/docs.yaml +++ b/.github/workflows/docs.yaml @@ -32,13 +32,13 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Setup Task - uses: go-task/setup-task@v2 + uses: go-task/setup-task@a00fbb05ce67b35648be3c78cbc9fd85354c757e # v2.2.0 - name: Setup Go - uses: actions/setup-go@v7 + uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod @@ -52,7 +52,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} @@ -67,7 +67,7 @@ jobs: make docs - name: Upload docs artifacts to GitHub - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: github.event_name == 'push' with: name: unikraft-docs-${{ github.event.pull_request.number || github.sha }} @@ -77,7 +77,7 @@ jobs: overwrite: true - name: Upload man artifacts to GitHub - uses: actions/upload-artifact@v7 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: github.event_name == 'push' with: name: unikraft-man-${{ github.sha }} diff --git a/.github/workflows/mirror.yaml b/.github/workflows/mirror.yaml index 410b4189a..7e29b44ce 100644 --- a/.github/workflows/mirror.yaml +++ b/.github/workflows/mirror.yaml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout - uses: actions/checkout@v7 + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 persist-credentials: false diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index dfe1c4597..8f328ca65 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -19,7 +19,7 @@ jobs: release: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v7 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: fetch-depth: 0 @@ -27,7 +27,7 @@ jobs: shell: bash run: git fetch --force --tags - - uses: actions/setup-go@v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: go.mod @@ -41,7 +41,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} @@ -124,16 +124,16 @@ jobs: export YTT_DEB_PRERELEASE_VERSION make goreleaser-yaml - - uses: docker/setup-buildx-action@v4 + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - uses: docker/login-action@v4 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Run GoReleaser - uses: goreleaser/goreleaser-action@v7 + uses: goreleaser/goreleaser-action@a4f02ab5355a589de60d917a659ce617ed19b3de # v7.3.0 env: GITHUB_TOKEN: ${{ secrets.GH_PAT }} GITHUB_TOKEN_UNIKRAFT: ${{ secrets.GH_MIRROR_PAT }} @@ -142,7 +142,7 @@ jobs: UNIKRAFT_POSTHOG_API_KEY: ${{ secrets.UNIKRAFT_POSTHOG_API_KEY }} UNIKRAFT_POSTHOG_HOST: ${{ secrets.UNIKRAFT_POSTHOG_HOST }} with: - version: latest + version: v2.20.2 args: release --clean - name: Publish to APT repository diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 8c97a4a18..99be60b32 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -27,14 +27,14 @@ jobs: run: shell: bash steps: - - uses: actions/checkout@v7 - - uses: go-task/setup-task@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: go-task/setup-task@a00fbb05ce67b35648be3c78cbc9fd85354c757e # v2.2.0 - name: Authenticate git for remote Taskfiles env: GH_TOKEN: ${{ github.token }} run: | git config --global url."https://x-access-token:${GH_TOKEN}@github.com/".insteadOf "https://github.com/" - - uses: actions/setup-go@v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: 'go.mod' @@ -48,7 +48,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} @@ -88,30 +88,30 @@ jobs: UNIKRAFT_SERVER_STABLE: stable UNIKRAFT_SERVER_PROD: prod steps: - - uses: actions/checkout@v7 - - uses: go-task/setup-task@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: go-task/setup-task@a00fbb05ce67b35648be3c78cbc9fd85354c757e # v2.2.0 - name: Authenticate git for remote Taskfiles env: GH_TOKEN: ${{ github.token }} run: | git config --global url."https://x-access-token:${GH_TOKEN}@github.com/".insteadOf "https://github.com/" - - uses: actions/setup-go@v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: 'go.mod' - # Multi-platform rootfs builds run the target architecture's binaries, - # which needs a binfmt handler registered with the kernel. - - name: Set up QEMU - uses: docker/setup-qemu-action@v4 - with: - platforms: arm64 - - name: Login to Docker Hub uses: unikraft-cloud/x/.github/actions/login-docker-hub@prod-staging with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} + # Multi-platform rootfs builds run the target architecture's binaries, + # which needs a binfmt handler registered with the kernel. + - name: Set up QEMU + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 + with: + platforms: arm64 + - name: Set Go variables id: goenv run: | @@ -122,7 +122,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} @@ -165,6 +165,7 @@ jobs: UNIKRAFT_ENDPOINT: ${{ secrets[format('UNIKRAFT_ENDPOINT_{0}', matrix.target)] }} UNIKRAFT_X_TEST_SERVER: ${{ env[format('UNIKRAFT_SERVER_{0}', matrix.target)] }} UNIKRAFT_X_TEST_BUILD_URL: ${{ matrix.target == 'STABLE' && secrets.UNIKRAFT_BUILD_URL_STABLE || '' }} + UNIKRAFT_X_TEST_UDP_IP: ${{ matrix.target == 'STAGING' && vars.UNIKRAFT_UDP_IP_STAGING || '' }} # The hosted Windows runners reach only the public prod endpoint. The runners # take turns, so that both do not use the same organization at once. @@ -184,31 +185,31 @@ jobs: run: shell: bash steps: - - uses: actions/checkout@v7 - - uses: go-task/setup-task@v2 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: go-task/setup-task@a00fbb05ce67b35648be3c78cbc9fd85354c757e # v2.2.0 - name: Authenticate git for remote Taskfiles env: GH_TOKEN: ${{ github.token }} run: | git config --global url."https://x-access-token:${GH_TOKEN}@github.com/".insteadOf "https://github.com/" - - uses: actions/setup-go@v7 + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 with: go-version-file: 'go.mod' + - name: Login to Docker Hub + uses: unikraft-cloud/x/.github/actions/login-docker-hub@prod-staging + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + # Multi-platform rootfs builds run the target architecture's binaries, # which needs a binfmt handler registered with the kernel. - name: Set up QEMU if: runner.os == 'Linux' - uses: docker/setup-qemu-action@v4 + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 with: platforms: arm64 - - name: Login to Docker Hub - uses: unikraft-cloud/x/.github/actions/login-docker-hub@prod-staging - with: - username: ${{ secrets.DOCKERHUB_USERNAME }} - password: ${{ secrets.DOCKERHUB_TOKEN }} - - name: Set Go variables id: goenv run: | @@ -219,7 +220,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} diff --git a/.goreleaser.Dockerfile b/.goreleaser.Dockerfile index 0f0a95069..7fed6a738 100644 --- a/.goreleaser.Dockerfile +++ b/.goreleaser.Dockerfile @@ -1,4 +1,4 @@ -FROM alpine:3.24 +FROM alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf ARG TARGETPLATFORM COPY $TARGETPLATFORM/unikraft /usr/local/bin/unikraft ENTRYPOINT ["unikraft"] diff --git a/.taskrc.yml b/.taskrc.yml index dc0006181..04b727428 100644 --- a/.taskrc.yml +++ b/.taskrc.yml @@ -1,7 +1,7 @@ remote: insecure: false offline: false - timeout: "5s" + timeout: "30s" cache-dir: ~/.cache/taskfiles cache-expiry: "24h" trusted-hosts: diff --git a/AGENTS.md b/AGENTS.md index f103a1d2a..1958e5970 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,7 +20,7 @@ This repo contains the Go-based Unikraft CLI. Use this file for contributor-faci - Core `Model` interface (`pkg/model`) models API objects with `Type`, `Key`, `Fields`, and `Raw`, and is extended by get/list/create/edit/delete behaviors. - Model data is expressed as a tree of `Field` nodes: each node has a name, optional value, nested subfields, and an `Elem` template for homogeneous arrays; patch metadata and verbosity drive editing and output. - Model utilities live alongside the model layer (inside `pkg/model`): struct↔field conversion, field cloning/merging/deduping, map/slice encoding, path-based filtering/selection, and patch helpers for edits. -- `pkg/` is public API, used by other CLIs (like consolectl) to build their own commands, TUI and MCP server on the model layer: `pkg/model` (with `cmd`, `tui`, `mcp`, `patch` and `value`), `pkg/mcpserver` and `pkg/logfmt`. Keep anything specific to Unikraft Cloud out of it, and avoid exposing `internal/` types in its exported API. +- `pkg/` is public API. `pkg/model` (with `cmd`, `tui`, `mcp`, `patch` and `value`), `pkg/mcpserver` and `pkg/logfmt` are generic: other CLIs (like consolectl) build their own commands, TUI and MCP server on them, so keep anything specific to Unikraft Cloud out of them. `pkg/mcpserver/cli` serves the MCP server of `unikraft mcp` to other CLIs, which cannot import its tools from `internal/`. Avoid exposing `internal/` types in the exported API of `pkg/`. - Everything else lives under `internal/` and is organized by domain: configuration/profile handling, API client communication, the Unikraft Cloud models and commands, output utilities, multi-region support, and shared helpers. - Build artifacts and generated docs go to `dist/`; developer tooling/scripts live at the repo root and under `tools/`. diff --git a/Dockerfile b/Dockerfile index cfbeaeffa..6c940a52a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,4 @@ -# syntax=docker/dockerfile:1 - -FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine AS build +FROM --platform=$BUILDPLATFORM golang:1.27.4-alpine@sha256:70bd7ddea8b6cbe5d6943cde279d6b67feb10cc924fb9100d1d8757c1575b280 AS build WORKDIR /src ARG TARGETOS TARGETARCH RUN --mount=type=bind,target=. \ @@ -13,6 +11,6 @@ RUN --mount=type=bind,target=. \ -X unikraft.com/x/version.Issues=https://github.com/unikraft-cloud/cli/issues" \ ./cmd/unikraft -FROM alpine:3.24 +FROM alpine:3.24.4@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf COPY --from=build /out/unikraft /usr/local/bin/unikraft ENTRYPOINT ["unikraft"] diff --git a/README.md b/README.md index fda946f5c..548a35983 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,51 @@ to install the CLI in your workflow: +
+Docker + +The CLI is published as a container image for `linux/amd64` and `linux/arm64`, with `unikraft` as the entrypoint: + +```sh +docker run --rm \ + -e UNIKRAFT_PROFILE_ENV=true \ + -e UKC_TOKEN \ + -e UKC_METRO=fra \ + ghcr.io/unikraft-cloud/cli instances list +``` + +Or reuse the profiles from your existing config: + +```sh +docker run --rm \ + -v ~/.config/unikraft:/root/.config/unikraft \ + ghcr.io/unikraft-cloud/cli instances list +``` + +| Tag | Description | +| ----------- | ---------------------------------------------- | +| `latest` | Latest **stable** release | +| `X.Y` | Latest **stable** release in the `X.Y` series | +| `staging` | Latest **pre-release** (`-staging`) build | +| `` | A specific release, e.g. `0.9.0` | + +The image has a shell, so it also works as a CI job image. GitLab CI runs `script:` through a shell, so it needs the entrypoint cleared: + +```yaml +deploy: + image: + name: ghcr.io/unikraft-cloud/cli:latest + entrypoint: [""] + variables: + UNIKRAFT_PROFILE_ENV: "true" + UKC_METRO: fra + # UKC_TOKEN set as a masked CI/CD variable + script: + - unikraft instances list +``` + +
+
From Source diff --git a/cmd/unikraft/help_test.go b/cmd/unikraft/help_test.go index 488f2ad27..ee7788e7c 100644 --- a/cmd/unikraft/help_test.go +++ b/cmd/unikraft/help_test.go @@ -113,6 +113,7 @@ func instancesHelpTests(t *testing.T, unikraftPath string) { []string{"unikraft", "instance", "template", "create", "--help"}, []string{"unikraft", "instance", "template", "edit", "--help"}, []string{"unikraft", "instance", "template", "delete", "--help"}, + []string{"unikraft", "instance", "template", "history", "--help"}, []string{"unikraft", "instance", "checkpoint", "--help"}, []string{"unikraft", "instance", "checkpoint", "get", "--help"}, []string{"unikraft", "instance", "checkpoint", "list", "--help"}, diff --git a/cmd/unikraft/integration/build_test.go b/cmd/unikraft/integration/build_test.go index 8041ed1c0..0761e099d 100644 --- a/cmd/unikraft/integration/build_test.go +++ b/cmd/unikraft/integration/build_test.go @@ -114,7 +114,7 @@ roms: require.NoError(t, fstest.Apply( fstest.CreateFile("Dockerfile", []byte(` FROM busybox:latest -RUN echo "unikraft-e2e" > /etc/unikraft-e2e +RUN echo "unikraft-e2e `+imageTag+`" > /etc/unikraft-e2e COPY < /etc/unikraft-e2e +RUN echo "unikraft-e2e `+imageTag+`" > /etc/unikraft-e2e CMD ["sh", "-c", "cat /etc/unikraft-e2e && echo UNIKRAFT_E2E_OK"] `), 0o644), ).Apply(dir)) @@ -228,7 +229,7 @@ RUN echo "wrong-context" > /etc/unikraft-e2e fstest.CreateDir("proj", 0o755), fstest.CreateFile("proj/Dockerfile", []byte(` FROM busybox:latest -RUN echo "right-context" > /etc/unikraft-e2e +RUN echo "right-context `+imageTag+`" > /etc/unikraft-e2e CMD ["sh", "-c", "echo DOCKERFILE_CMD_USED"] `), 0o644), fstest.CreateFile("proj/Kraftfile", []byte(` @@ -274,7 +275,7 @@ cmd: ["sh", "-c", "cat /etc/unikraft-e2e && echo UNIKRAFT_E2E_OK"] require.NoError(t, fstest.Apply( fstest.CreateFile("Dockerfile", []byte(` FROM busybox:latest -RUN echo "unikraft-e2e" > /etc/unikraft-e2e +RUN echo "unikraft-e2e `+imageTag+`" > /etc/unikraft-e2e CMD ["sh", "-c", "echo DOCKERFILE_CMD_USED"] `), 0o644), fstest.CreateFile("Kraftfile", []byte(` diff --git a/cmd/unikraft/integration/builder_test.go b/cmd/unikraft/integration/builder_test.go index e34d0a74d..4633c7836 100644 --- a/cmd/unikraft/integration/builder_test.go +++ b/cmd/unikraft/integration/builder_test.go @@ -38,7 +38,7 @@ func TestBuilder(t *testing.T) { assert.Regexp(t, `(?m)^instance: +.*name=remote-builder-default\b`, out) out = r.Run(t, []string{"unikraft", "builder", "list"}, env) - assert.Regexp(t, `(?m)^default +true +`, out) + assert.Regexp(t, `(?m)^default +\S+ +true +`, out) out = r.Run(t, []string{"unikraft", "builder", "du"}, env) assert.Regexp(t, `(?m)^Reclaimable: +\S+\nTotal: +\S+$`, out) diff --git a/cmd/unikraft/integration/instance_checkpoint_test.go b/cmd/unikraft/integration/instance_checkpoint_test.go index 99fbb459d..bb309546c 100644 --- a/cmd/unikraft/integration/instance_checkpoint_test.go +++ b/cmd/unikraft/integration/instance_checkpoint_test.go @@ -50,22 +50,37 @@ func TestInstanceCheckpoints(t *testing.T) { out = r.Run(t, []string{"unikraft", "instance", "checkpoint", "inspect", checkpointName, "-f", "all"}) assert.Contains(t, out, "env-dev") - // The source instance's history lists its checkpoints. + r.Run(t, []string{ + "unikraft", "instance", "create", + "--output", "quiet", + "--set", "name=test-" + instName + "-fork", + "--set", "metro=" + r.MetroName, + "--set", "autostart=false", + "--checkpoint", checkpointName, + }) + + // The default view draws the lineage of the source as a graph. out = r.Run(t, []string{"unikraft", "instance", "history", "test-" + instName}) assert.Contains(t, out, checkpointName) + assert.Contains(t, out, "◉") + assert.Contains(t, out, "test-"+instName+"-fork") - // A checkpoint's own history (ancestor checkpoints) is empty for a - // freshly-created checkpoint; the command should still succeed and - // render the table header. + // The lineage of the checkpoint is the same tree. out = r.Run(t, []string{"unikraft", "instance", "checkpoint", "history", checkpointName}) - assert.Contains(t, out, "CREATED") + assert.Contains(t, out, "test-"+instName+"-fork") + + r.Run(t, []string{"unikraft", "instance", "delete", "test-" + instName + "-fork"}) + r.Run(t, []string{"unikraft", "instance", "delete", "test-" + instName}) + + // A checkpoint of a deleted instance hangs under a deleted node. + out = r.Run(t, []string{"unikraft", "instance", "checkpoint", "history", checkpointName}) + assert.Contains(t, out, checkpointName) + assert.Contains(t, out, "deleted") r.Run(t, []string{"unikraft", "instance", "checkpoint", "delete", checkpointName}) out = r.Run(t, []string{"unikraft", "instance", "checkpoint", "list", "--output", "quiet"}) assert.NotContains(t, out, checkpointName) - - r.Run(t, []string{"unikraft", "instance", "delete", "test-" + instName}) }) t.Run("create-is-immediately-visible", func(t *testing.T) { diff --git a/cmd/unikraft/integration/instance_template_test.go b/cmd/unikraft/integration/instance_template_test.go index 13271c026..377c19cf8 100644 --- a/cmd/unikraft/integration/instance_template_test.go +++ b/cmd/unikraft/integration/instance_template_test.go @@ -110,6 +110,10 @@ func TestInstanceTemplates(t *testing.T) { assert.Regexp(t, `state:\s+(stopping|stopped)\b`, out) assert.Regexp(t, `memory:\s+128`, out) + // The lineage of the template lists the instance created from it. + out = r.Run(t, []string{"unikraft", "instance", "template", "history", templateName, "-o", "json", "-f", "name,relation"}) + assert.Regexp(t, `"name": "test-from-template-`+instName+`",\s+"relation": "created-from"`, out) + r.Run(t, []string{"unikraft", "instance", "template", "delete", templateName}) }) diff --git a/cmd/unikraft/integration/instance_test.go b/cmd/unikraft/integration/instance_test.go index fdbbbc754..1df7372fc 100644 --- a/cmd/unikraft/integration/instance_test.go +++ b/cmd/unikraft/integration/instance_test.go @@ -9,7 +9,9 @@ import ( "context" _ "embed" "encoding/json" + "fmt" "regexp" + "slices" "strings" "testing" "time" @@ -76,7 +78,7 @@ func scriptArgs(t *testing.T, script string) string { return "runtime.args=" + string(args) } -const sandboxPluginRom = "plugins/sandbox:latest" +const sandboxPluginRom = "plugins/sandbox:staging" // tunnelProxyUUIDs queries the platform directly (bypassing the CLI's // resource partition, which never tracks the tunnel command's internal proxy @@ -1464,7 +1466,7 @@ func TestInstances(t *testing.T) { fstest.CreateDir("v1", 0o755), fstest.CreateFile("v1/Dockerfile", []byte(` FROM busybox:latest -RUN echo pull-policy-v1 > /marker.txt +RUN echo pull-policy-v1 `+imageTag+` > /marker.txt `), 0o644), fstest.CreateFile("v1/Kraftfile", []byte(` spec: v0.7 @@ -1502,7 +1504,7 @@ cmd: ["cat", "/marker.txt"] fstest.CreateDir("v2", 0o755), fstest.CreateFile("v2/Dockerfile", []byte(` FROM busybox:latest -RUN echo pull-policy-v2 > /marker.txt +RUN echo pull-policy-v2 `+imageTag+` > /marker.txt `), 0o644), fstest.CreateFile("v2/Kraftfile", []byte(` spec: v0.7 @@ -1556,11 +1558,84 @@ cmd: ["cat", "/marker.txt"] out = r.Run(t, []string{"unikraft", "instance", "logs", "test-" + alwaysName}) assert.Contains(t, out, "pull-policy-v2") assert.NotContains(t, out, "pull-policy-v1") + + require.NoError(t, fstest.Apply( + fstest.CreateDir("v3", 0o755), + fstest.CreateFile("v3/Dockerfile", []byte(` +FROM busybox:latest +RUN echo pull-policy-v3 > /marker.txt +`), 0o644), + fstest.CreateFile("v3/Kraftfile", []byte(` +spec: v0.7 +name: pull-policy-e2e +runtime: base-compat:latest +rootfs: + format: erofs + source: ./Dockerfile +cmd: ["cat", "/marker.txt"] +`), 0o644), + ).Apply(dir)) + r.Run(t, []string{"unikraft", "build", "v3", "--output", image}, integ.WithWorkDir(dir)) + + r.Run(t, []string{ + "unikraft", "instance", "edit", "test-" + alwaysName, + "--output", "quiet", + "--image", image, + "--pull-policy", "always", + }) + out = r.Run(t, []string{ + "unikraft", "instance", "start", + "--follow", + "test-" + alwaysName, + }, integ.WithTimeout(60*time.Second)) + assert.Contains(t, out, "pull-policy-v3") + assert.NotContains(t, out, "pull-policy-v2") r.Run(t, []string{"unikraft", "instance", "delete", "test-" + alwaysName}) r.Run(t, []string{"unikraft", "image", "delete", image}) }) + t.Run("image-headers", func(t *testing.T) { + r := runner(t, true, []string{staging, stable}) + instName := uniq() + + create := []string{ + "unikraft", "instance", "create", + "--output", "quiet", + "--name", "test-" + instName, + "--metro", r.MetroName, + "--image", "nginx:latest", + "--memory", "128", + } + edit := []string{ + "unikraft", "instance", "edit", "test-" + instName, + "--output", "quiet", + "--image", "nginx:latest", + } + var flags []string + var keys string + for i := range 17 { + flags = append(flags, "--image-header", fmt.Sprintf("X-Unikraft-Test-%d=1", i)) + keys += fmt.Sprintf(",headers.X-Unikraft-Test-%d=1", i) + } + + for _, tooMany := range [][]string{ + flags, + {"--rom", "name=r,image=nginx:latest" + keys}, + {"--plugin", "name=p,image=nginx:latest" + keys}, + } { + out := r.Run(t, slices.Concat(create, tooMany), integ.ExpectFail()) + assert.Regexp(t, `more than 16 headers`, out) + } + + r.Run(t, slices.Concat(create, []string{"--image-header", "X-Unikraft-Test=1"})) + r.Run(t, slices.Concat(edit, []string{"--image-header", "X-Unikraft-Test=2"})) + out := r.Run(t, slices.Concat(edit, flags), integ.ExpectFail()) + assert.Regexp(t, `more than 16 headers`, out) + + r.Run(t, []string{"unikraft", "instance", "delete", "test-" + instName}) + }) + t.Run("replicas", func(t *testing.T) { r := runner(t, true, []string{staging, stable}) instName := uniq() diff --git a/cmd/unikraft/integration/mcp_test.go b/cmd/unikraft/integration/mcp_test.go index ada97a522..3b88f46cb 100644 --- a/cmd/unikraft/integration/mcp_test.go +++ b/cmd/unikraft/integration/mcp_test.go @@ -38,7 +38,7 @@ func TestMCP(t *testing.T) { "metro": r.MetroName, "image": image, "runtime.args": "tail -f /dev/null", - "plugins": []string{"name=" + sandboxPlugin + ",rom=" + sandboxPluginRom}, + "plugins": []string{"name=" + sandboxPlugin + ",rom=" + sandboxPluginRom + ",pull-policy=always"}, "resources.memory": "512MiB", "resources.vcpus": 1, }}) diff --git a/cmd/unikraft/integration/sandbox_test.go b/cmd/unikraft/integration/sandbox_test.go index adc17a6f2..65160c5ab 100644 --- a/cmd/unikraft/integration/sandbox_test.go +++ b/cmd/unikraft/integration/sandbox_test.go @@ -40,7 +40,7 @@ func newSandboxInstance(t *testing.T, r *integ.TestEnv) string { "--metro", r.MetroName, "--image", image, "--args", "tail -f /dev/null", - "--plugin", "name=" + sandboxPlugin + ",rom=" + sandboxPluginRom, + "--plugin", "name=" + sandboxPlugin + ",rom=" + sandboxPluginRom + ",pull-policy=always", "--memory", "512", "--vcpus", "1", "--autostart", diff --git a/cmd/unikraft/integration/service_test.go b/cmd/unikraft/integration/service_test.go index ffe07f94b..49dc0ce16 100644 --- a/cmd/unikraft/integration/service_test.go +++ b/cmd/unikraft/integration/service_test.go @@ -6,6 +6,10 @@ package integration import ( + "fmt" + "math/rand/v2" + "os" + "regexp" "strings" "testing" @@ -143,6 +147,59 @@ func TestServices(t *testing.T) { r.Run(t, []string{"unikraft", "service", "delete", "test-" + svcName}) }) + t.Run("udp", func(t *testing.T) { + r := runner(t, true, []string{staging}) + + out := r.Run(t, []string{ + "unikraft", "service", "create", + "--metro", r.MetroName, + "--service", "53:53/udp", + }, integ.ExpectFail()) + assert.Contains(t, out, "UDP services must have an IP address configured") + }) + + t.Run("udp-ip", func(t *testing.T) { + ip := os.Getenv("UNIKRAFT_X_TEST_UDP_IP") + if ip == "" { + t.Skip("udp test requires UNIKRAFT_X_TEST_UDP_IP") + } + r := runner(t, true, []string{staging}) + svcName := "test-" + uniq() + port := 20000 + rand.IntN(40000) + udpSvc := fmt.Sprintf("%d:%d/udp@%s", port, port, ip) + tcpSvc := fmt.Sprintf("%d:8080/tls@%s", port, ip) + udpOut := fmt.Sprintf(`source:\s+%d\s+destination:\s+%d\s+protocol:\s+udp\s+ip:\s+%s`, port, port, regexp.QuoteMeta(ip)) + tcpOut := fmt.Sprintf(`source:\s+%d\s+destination:\s+8080\s+protocol:\s+tcp\s+ip:\s+%s`, port, regexp.QuoteMeta(ip)) + + out := r.Run(t, []string{ + "unikraft", "service", "create", + "--name", svcName, + "--metro", r.MetroName, + "--service", udpSvc, + }) + assert.Regexp(t, udpOut, out) + + r.Run(t, []string{ + "unikraft", "service", "edit", svcName, + "--output", "quiet", + "--add", "services=" + tcpSvc, + }) + out = r.Run(t, []string{"unikraft", "service", "inspect", svcName}) + assert.Regexp(t, udpOut, out) + assert.Regexp(t, tcpOut, out) + + r.Run(t, []string{ + "unikraft", "service", "edit", svcName, + "--output", "quiet", + "--del", "services=" + udpSvc, + }) + out = r.Run(t, []string{"unikraft", "service", "inspect", svcName}) + assert.NotRegexp(t, udpOut, out) + assert.Regexp(t, tcpOut, out) + + r.Run(t, []string{"unikraft", "service", "delete", svcName}) + }) + t.Run("delete-drain", func(t *testing.T) { r := runner(t, true, []string{staging, stable}) svcName := "test-" + uniq() diff --git a/cmd/unikraft/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index b645c0ed2..e774665f9 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -34,9 +34,9 @@ Examples: Flags: -o, --output - Output destination. + Output destination. A remote build needs an image with a tag, such as my-org/my-app:latest. --arch - Only build the Kraftfile targets of these architectures. Defaults to every declared target, or x86_64 when only a runtime is declared. Required when the project declares no targets and no runtime, such as a bare Dockerfile. + Only build the Kraftfile targets of these architectures. Defaults to every declared target, or x86_64 when only a runtime is declared. A local build requires it when the project declares no targets and no runtime, such as a bare Dockerfile. A remote build of such a project defaults to x86_64. [examples: x86_64, arm64] --build-arg Set build-time variables. @@ -49,7 +49,7 @@ Flags: --insecure Allow insecure (HTTP/unverified TLS) connections to registries. Specify hostnames to restrict, or omit to apply to all. --remote= ($UNIKRAFT_BUILD_URL) - Build on the build service at this URL and push the image from there, instead of building locally. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. Creates a builder with the default sizes if you have none. To set the sizes, use 'unikraft builder create'. + Build on the build service at this URL and push the image from there, instead of building locally. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. Write a URL as --remote=, because the flag does not take the next argument. Creates a builder with the default sizes if you have none. To set the sizes, use 'unikraft builder create'. --metro= ... Metros that a remote build may run in, by name or API URL. Defaults to the build service's choice. @@ -95,6 +95,7 @@ Commands: Fields: name + metro default running waiting @@ -145,7 +146,9 @@ Flags: --cache= Size of the builder's cache volume. Defaults to the build service's. --remote= ($UNIKRAFT_BUILD_URL) - URL of the build service that manages the builder. Defaults to the build_url of the profile. + URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. + --metro= + Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in. Global flags: -h, --help @@ -183,6 +186,7 @@ Examples: Fields: name + metro default running waiting @@ -198,7 +202,9 @@ Flags: -o, --output Output format. One of: kv, table, json, yaml, raw, quiet, template. --remote= ($UNIKRAFT_BUILD_URL) - URL of the build service that manages the builder. Defaults to the build_url of the profile. + URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. + --metro= + Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in. Global flags: -h, --help @@ -223,6 +229,11 @@ $ unikraft builder list --help List builders. +Each replica of the build service runs up to max-builds builds on a +builder at once, so running can be higher than max-builds. Waiting +counts the builds that have not started: those that wait for a build +slot and those that wait for their client's session. + Usage: unikraft builder list [ ...] [flags] @@ -236,6 +247,7 @@ Examples: Fields: name + metro default running waiting @@ -259,7 +271,7 @@ Flags: -o, --output Output format. One of: kv, table, json, yaml, raw, quiet, template. --remote= ($UNIKRAFT_BUILD_URL) - URL of the build service that manages the builders. Defaults to the build_url of the profile. + URL of the build service that manages the builders. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. Global flags: -h, --help @@ -297,6 +309,7 @@ Examples: Fields: name + metro default running waiting @@ -310,7 +323,9 @@ Flags: -o, --output Output format. One of: kv, table, json, yaml, raw, quiet, template. --remote= ($UNIKRAFT_BUILD_URL) - URL of the build service that manages the builder. Defaults to the build_url of the profile. + URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. + --metro= + Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in. Global flags: -h, --help @@ -349,7 +364,9 @@ Examples: Flags: --remote= ($UNIKRAFT_BUILD_URL) - URL of the build service that manages the builder. Defaults to the build_url of the profile. + URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. + --metro= + Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in. Global flags: -h, --help @@ -388,7 +405,9 @@ Examples: Flags: --remote= ($UNIKRAFT_BUILD_URL) - URL of the build service that manages the builder. Defaults to the build_url of the profile. + URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. + --metro= + Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in. Global flags: -h, --help diff --git a/cmd/unikraft/testdata/TestHelp/config b/cmd/unikraft/testdata/TestHelp/config index 6edf20c8d..e372ba9dd 100644 --- a/cmd/unikraft/testdata/TestHelp/config +++ b/cmd/unikraft/testdata/TestHelp/config @@ -14,9 +14,10 @@ Fields: profile profiles, profiles.*, profiles.*.name, profiles.*.type, profiles.*.token, profiles.*.organization, profiles.*.user-uuid, profiles.*.organization-uuid, - profiles.*.control-plane, profiles.*.insecure, profiles.*.registry-mirror, - profiles.*.build-url, profiles.*.metros, profiles.*.metros.*, - profiles.*.metros.*.name, profiles.*.metros.*.endpoint, + profiles.*.control-plane, profiles.*.insecure, profiles.*.registry, + profiles.*.registry.host, profiles.*.registry.mirror, + profiles.*.registry.insecure, profiles.*.build-url, profiles.*.metros, + profiles.*.metros.*, profiles.*.metros.*.name, profiles.*.metros.*.endpoint, profiles.*.metros.*.proxy, profiles.*.metros.*.location, profiles.*.metros.*.insecure, profiles.*.metro-default @@ -59,9 +60,10 @@ Fields: profile profiles, profiles.*, profiles.*.name, profiles.*.type, profiles.*.token, profiles.*.organization, profiles.*.user-uuid, profiles.*.organization-uuid, - profiles.*.control-plane, profiles.*.insecure, profiles.*.registry-mirror, - profiles.*.build-url, profiles.*.metros, profiles.*.metros.*, - profiles.*.metros.*.name, profiles.*.metros.*.endpoint, + profiles.*.control-plane, profiles.*.insecure, profiles.*.registry, + profiles.*.registry.host, profiles.*.registry.mirror, + profiles.*.registry.insecure, profiles.*.build-url, profiles.*.metros, + profiles.*.metros.*, profiles.*.metros.*.name, profiles.*.metros.*.endpoint, profiles.*.metros.*.proxy, profiles.*.metros.*.location, profiles.*.metros.*.insecure, profiles.*.metro-default diff --git a/cmd/unikraft/testdata/TestHelp/images b/cmd/unikraft/testdata/TestHelp/images index bbebf4bba..b2c37fc0b 100644 --- a/cmd/unikraft/testdata/TestHelp/images +++ b/cmd/unikraft/testdata/TestHelp/images @@ -78,9 +78,9 @@ Examples: Flags: -o, --output - Output destination. + Output destination. A remote build needs an image with a tag, such as my-org/my-app:latest. --arch - Only build the Kraftfile targets of these architectures. Defaults to every declared target, or x86_64 when only a runtime is declared. Required when the project declares no targets and no runtime, such as a bare Dockerfile. + Only build the Kraftfile targets of these architectures. Defaults to every declared target, or x86_64 when only a runtime is declared. A local build requires it when the project declares no targets and no runtime, such as a bare Dockerfile. A remote build of such a project defaults to x86_64. [examples: x86_64, arm64] --build-arg Set build-time variables. @@ -93,7 +93,7 @@ Flags: --insecure Allow insecure (HTTP/unverified TLS) connections to registries. Specify hostnames to restrict, or omit to apply to all. --remote= ($UNIKRAFT_BUILD_URL) - Build on the build service at this URL and push the image from there, instead of building locally. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. Creates a builder with the default sizes if you have none. To set the sizes, use 'unikraft builder create'. + Build on the build service at this URL and push the image from there, instead of building locally. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. Write a URL as --remote=, because the flag does not take the next argument. Creates a builder with the default sizes if you have none. To set the sizes, use 'unikraft builder create'. --metro= ... Metros that a remote build may run in, by name or API URL. Defaults to the build service's choice. diff --git a/cmd/unikraft/testdata/TestHelp/instances b/cmd/unikraft/testdata/TestHelp/instances index 6c8469401..403a796e4 100644 --- a/cmd/unikraft/testdata/TestHelp/instances +++ b/cmd/unikraft/testdata/TestHelp/instances @@ -33,7 +33,7 @@ Resources: tunnel, port-forward Forward a local port to an unexposed instance. history - Show checkpoint history for an instance. + Show the lineage of an instance. shell, sh Open an interactive shell on a sandbox instance. exec @@ -63,6 +63,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -72,8 +73,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -144,6 +147,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -153,8 +157,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -233,6 +239,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -242,8 +249,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -326,6 +335,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -335,8 +345,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -469,6 +481,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -478,8 +491,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -559,8 +574,11 @@ Create flags: Image to deploy, as an OCI reference or a full registry URL. On create, required unless template, branch or checkpoint is given, and cannot be combined with them. [examples: nginx:latest, my-app:v1.2.3] --pull-policy= - When to pull the image relative to the node's cache: always, if_not_present or never. + When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. [examples: always, if_not_present, never] + --image-header== ... + HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. + [example: Authorization=Bearer ] --type= Virtual machine type. micro: Firecracker microVM (default) @@ -583,12 +601,15 @@ Create flags: [examples: 0, 1] --service= Service group to join, by name or UUID. Leave unset and give service.services or service.domains to create a group owned by the instance. Without any service the instance is reachable only privately. - -p, --publish=:[/] ... - Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only. + -p, --publish=:[/][@] ... + Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP. http: load balance per HTTP request instead of per TCP connection tls: terminate TLS at the platform - redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect. - [examples: 443:8080/http+tls, 80:443/http+redirect] + redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect + tcp: publish a TCP port, the default + udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10 + @IP: public IP assigned to you on the group's node. + [examples: 443:8080/http+tls, 80:443/http+redirect, 53:53/udp@203.0.113.10] --domain= ... Domain for the group. myapp: a bare label becomes a subdomain of the metro @@ -597,11 +618,11 @@ Create flags: -v, --volume=[]:[:] ... Volume to attach as NAME:/MOUNT[:ro], where the mount path is absolute and outside /uk. On create, leave NAME empty and add :size=SIZE, as in :/data:size=1GiB, to make a new volume with a generated name. [examples: my-vol:/data, cache:/tmp:ro, :/data:size=1GiB] - --rom=name=,image=,at= ... - Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. + --rom=name=,image=[,pull-policy=][,headers.=],at= ... + Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=my-rom,image=myuser/my-rom:latest,at=/rom0, name=mydata,dir=./mydata,at=/rom] - --plugin=name=,image=[,config=] ... - Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. + --plugin=name=,image=[,pull-policy=][,headers.=][,config=] ... + Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=sandbox,image=plugins/sandbox:latest, name=sandbox,image=plugins/sandbox:latest,config={"persist_path":"/data"}] --network== ... Network interface to attach, one per flag and up to 4. The first one is the primary interface. Needs the net_manager permission. @@ -738,6 +759,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -747,8 +769,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -828,8 +852,11 @@ Create flags: Image to deploy, as an OCI reference or a full registry URL. On create, required unless template, branch or checkpoint is given, and cannot be combined with them. [examples: nginx:latest, my-app:v1.2.3] --pull-policy= - When to pull the image relative to the node's cache: always, if_not_present or never. + When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. [examples: always, if_not_present, never] + --image-header== ... + HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. + [example: Authorization=Bearer ] --type= Virtual machine type. micro: Firecracker microVM (default) @@ -852,12 +879,15 @@ Create flags: [examples: 0, 1] --service= Service group to join, by name or UUID. Leave unset and give service.services or service.domains to create a group owned by the instance. Without any service the instance is reachable only privately. - -p, --publish=:[/] ... - Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only. + -p, --publish=:[/][@] ... + Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP. http: load balance per HTTP request instead of per TCP connection tls: terminate TLS at the platform - redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect. - [examples: 443:8080/http+tls, 80:443/http+redirect] + redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect + tcp: publish a TCP port, the default + udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10 + @IP: public IP assigned to you on the group's node. + [examples: 443:8080/http+tls, 80:443/http+redirect, 53:53/udp@203.0.113.10] --domain= ... Domain for the group. myapp: a bare label becomes a subdomain of the metro @@ -866,11 +896,11 @@ Create flags: -v, --volume=[]:[:] ... Volume to attach as NAME:/MOUNT[:ro], where the mount path is absolute and outside /uk. On create, leave NAME empty and add :size=SIZE, as in :/data:size=1GiB, to make a new volume with a generated name. [examples: my-vol:/data, cache:/tmp:ro, :/data:size=1GiB] - --rom=name=,image=,at= ... - Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. + --rom=name=,image=[,pull-policy=][,headers.=],at= ... + Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=my-rom,image=myuser/my-rom:latest,at=/rom0, name=mydata,dir=./mydata,at=/rom] - --plugin=name=,image=[,config=] ... - Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. + --plugin=name=,image=[,pull-policy=][,headers.=][,config=] ... + Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=sandbox,image=plugins/sandbox:latest, name=sandbox,image=plugins/sandbox:latest,config={"persist_path":"/data"}] --network== ... Network interface to attach, one per flag and up to 4. The first one is the primary interface. Needs the net_manager permission. @@ -991,6 +1021,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -1000,8 +1031,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -1083,8 +1116,11 @@ Create flags: Image to deploy, as an OCI reference or a full registry URL. On create, required unless template, branch or checkpoint is given, and cannot be combined with them. [examples: nginx:latest, my-app:v1.2.3] --pull-policy= - When to pull the image relative to the node's cache: always, if_not_present or never. + When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. [examples: always, if_not_present, never] + --image-header== ... + HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. + [example: Authorization=Bearer ] --type= Virtual machine type. micro: Firecracker microVM (default) @@ -1107,12 +1143,15 @@ Create flags: [examples: 0, 1] --service= Service group to join, by name or UUID. Leave unset and give service.services or service.domains to create a group owned by the instance. Without any service the instance is reachable only privately. - -p, --publish=:[/] ... - Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only. + -p, --publish=:[/][@] ... + Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP. http: load balance per HTTP request instead of per TCP connection tls: terminate TLS at the platform - redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect. - [examples: 443:8080/http+tls, 80:443/http+redirect] + redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect + tcp: publish a TCP port, the default + udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10 + @IP: public IP assigned to you on the group's node. + [examples: 443:8080/http+tls, 80:443/http+redirect, 53:53/udp@203.0.113.10] --domain= ... Domain for the group. myapp: a bare label becomes a subdomain of the metro @@ -1121,11 +1160,11 @@ Create flags: -v, --volume=[]:[:] ... Volume to attach as NAME:/MOUNT[:ro], where the mount path is absolute and outside /uk. On create, leave NAME empty and add :size=SIZE, as in :/data:size=1GiB, to make a new volume with a generated name. [examples: my-vol:/data, cache:/tmp:ro, :/data:size=1GiB] - --rom=name=,image=,at= ... - Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. + --rom=name=,image=[,pull-policy=][,headers.=],at= ... + Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=my-rom,image=myuser/my-rom:latest,at=/rom0, name=mydata,dir=./mydata,at=/rom] - --plugin=name=,image=[,config=] ... - Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. + --plugin=name=,image=[,pull-policy=][,headers.=][,config=] ... + Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=sandbox,image=plugins/sandbox:latest, name=sandbox,image=plugins/sandbox:latest,config={"persist_path":"/data"}] --network== ... Network interface to attach, one per flag and up to 4. The first one is the primary interface. Needs the net_manager permission. @@ -1202,6 +1241,9 @@ Examples: # Resize instance memory unikraft instance edit demo-instance --memory 256 + # Change the image and always pull it, even if the node has it cached + unikraft instance edit demo-instance --image my-app:v2 --pull-policy always + # Attach a ROM image to an instance unikraft instance edit demo-instance \ --set roms=name=my-rom,image=myuser/my-rom:latest,at=/rom0 @@ -1229,6 +1271,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -1238,8 +1281,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -1315,6 +1360,12 @@ Edit flags: --image=: Image to deploy, as an OCI reference or a full registry URL. On create, required unless template, branch or checkpoint is given, and cannot be combined with them. [examples: nginx:latest, my-app:v1.2.3] + --pull-policy= + When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. + [examples: always, if_not_present, never] + --image-header== ... + HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. + [example: Authorization=Bearer ] --args= Command-line arguments passed to the instance at start. [example: --port=8080] @@ -1327,11 +1378,11 @@ Edit flags: --vcpus= Number of vCPUs, within the range the plan allows (see quotas.limits.vcpus on the metro). Defaults to 1 on create. [examples: 1, 2, 4] - --rom=name=,image=,at= ... - Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. + --rom=name=,image=[,pull-policy=][,headers.=],at= ... + Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=my-rom,image=myuser/my-rom:latest,at=/rom0, name=mydata,dir=./mydata,at=/rom] - --plugin=name=,image=[,config=] ... - Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. + --plugin=name=,image=[,pull-policy=][,headers.=][,config=] ... + Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=sandbox,image=plugins/sandbox:latest, name=sandbox,image=plugins/sandbox:latest,config={"persist_path":"/data"}] --scale-to-zero== Scale-to-zero options. Traffic through a service or to the private IP wakes the instance. @@ -1376,6 +1427,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -1385,8 +1437,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -1463,6 +1517,8 @@ Templates: Create an instance template. edit Edit an instance template. + history + Show the lineage of an instance template. Fields: metro @@ -1475,6 +1531,8 @@ Fields: autokill, autokill.time state image + pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1533,6 +1591,8 @@ Fields: autokill, autokill.time state image + pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1599,6 +1659,8 @@ Fields: autokill, autokill.time state image + pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1673,6 +1735,8 @@ Fields: autokill, autokill.time state image + pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1742,6 +1806,10 @@ Examples: # Update template tags unikraft instance template edit demo-template --set tags=env-dev + # Change the template image and always pull it + unikraft instance template edit demo-template --image my-app:v2 --pull-policy + always + Fields: metro name @@ -1753,6 +1821,8 @@ Fields: autokill, autokill.time state image + pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1815,6 +1885,15 @@ Edit flags: Autokill options. time: time since the template was last cloned before it is deleted, such as 24h, 0 disables. [example: time=24h] + --image=: + Image of the template, as an OCI reference or a full registry URL. + [examples: nginx:latest, my-app:v1.2.3] + --pull-policy= + When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same edit. Each image edit replaces the pull policy and headers, so set both again. + [examples: always, if_not_present, never] + --image-header== ... + HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same edit. Each image edit replaces the pull policy and headers, so set both again. + [example: Authorization=Bearer ] $ unikraft instance template delete --help @@ -1842,6 +1921,8 @@ Fields: autokill, autokill.time state image + pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1887,6 +1968,65 @@ Global flags: --timeout= ($UNIKRAFT_TIMEOUT) Set a deadline for the command (e.g. 30s, 5m, 1h). +$ unikraft instance template history --help + +Show the whole lineage tree of an instance template: every instance, template +and checkpoint in it. A table draws the tree in its graph column: ◉ is the +target, ● an instance, ○ a checkpoint, ◎ a template and ◌ a deleted instance. + +Usage: + unikraft instances template history ... [flags] + +Arguments: + ... + Target templates to show the lineage of. + +Examples: + # Show the lineage of a template + unikraft instance template history my-template + + # Show the lineage with the UUID of each node + unikraft instance template history my-template -f +uuid + +Fields: + graph + metro + name + kind + state + created + uuid + parent + relation + target + +Flags: + --limit + Show at most this many nodes of each lineage: the newest ones and the target. 0 shows all. + -f, --field + Specify which fields to include in the output. + -o, --output + Output format. One of: kv, table, json, yaml, raw, quiet, template. + +Global flags: + -h, --help + Show context-sensitive help. + --config= ($UNIKRAFT_CONFIG) + Path to the configuration file. + --log-level= ($UNIKRAFT_LOG_LEVEL) + Set the logging level. + [default: info, choices: trace, debug, info, warn, error, fatal] + --log-type= ($UNIKRAFT_LOG_TYPE) + Set the log type. + [default: text, choices: text, json] + --profile= ($UNIKRAFT_PROFILE) + Set the current profile. + --[no-]telemetry ($UNIKRAFT_TELEMETRY) + Toggle usage analytics. + [default: true] + --timeout= ($UNIKRAFT_TIMEOUT) + Set a deadline for the command (e.g. 30s, 5m, 1h). + $ unikraft instance checkpoint --help Manage instance checkpoints. @@ -1908,7 +2048,7 @@ Checkpoints: edit Edit an instance checkpoint. history - Show the history of a checkpoint. + Show the lineage of a checkpoint. Fields: metro @@ -2401,20 +2541,39 @@ Global flags: $ unikraft instance checkpoint history --help -Show the history of a checkpoint. +Show the whole lineage tree of a checkpoint: every instance, template and +checkpoint in it. A table draws the tree in its graph column: ◉ is the target, ● +an instance, ○ a checkpoint, ◎ a template and ◌ a deleted instance. Usage: unikraft instances checkpoint history ... [flags] Arguments: ... - Target checkpoints to show history for. + Target checkpoints to show the lineage of. Examples: - # Show the history of a checkpoint + # Show the lineage of a checkpoint unikraft instance checkpoint history my-checkpoint + # Show the lineage with the UUID of each node + unikraft instance checkpoint history my-checkpoint -f +uuid + +Fields: + graph + metro + name + kind + state + created + uuid + parent + relation + target + Flags: + --limit + Show at most this many nodes of each lineage: the newest ones and the target. 0 shows all. -f, --field Specify which fields to include in the output. -o, --output @@ -2738,20 +2897,42 @@ Global flags: $ unikraft instance history --help -Show checkpoint history for an instance. +Show the whole lineage tree of an instance: every instance, template and +checkpoint in it. A table draws the tree in its graph column: ◉ is the target, ● +an instance, ○ a checkpoint, ◎ a template and ◌ a deleted instance. Usage: unikraft instances history ... [flags] Arguments: ... - Target instances to show history for. + Target instances to show the lineage of. Examples: - # Show the checkpoint history of an instance + # Show the lineage of an instance unikraft instance history my-instance + # Show the lineage with the UUID of each node + unikraft instance history my-instance -f +uuid + + # Show the lineage as JSON + unikraft instance history my-instance -o json + +Fields: + graph + metro + name + kind + state + created + uuid + parent + relation + target + Flags: + --limit + Show at most this many nodes of each lineage: the newest ones and the target. 0 shows all. -f, --field Specify which fields to include in the output. -o, --output @@ -2811,7 +2992,7 @@ Flags: Name of the sandbox plugin to use. [default: sandbox] --plugin-image= - Image of the sandbox plugin to attach when the instance has none. + Image of the sandbox plugin to attach when the instance has none. It asks first, so it only attaches from a terminal. [default: plugins/sandbox:latest] -w, --dir= Directory to start the shell in. @@ -2881,7 +3062,7 @@ Flags: Name of the sandbox plugin to use. [default: sandbox] --plugin-image= - Image of the sandbox plugin to attach when the instance has none. + Image of the sandbox plugin to attach when the instance has none. It asks first, so it only attaches from a terminal. [default: plugins/sandbox:latest] -w, --dir= Directory to execute the command from. @@ -2952,7 +3133,7 @@ Flags: Name of the sandbox plugin to use. [default: sandbox] --plugin-image= - Image of the sandbox plugin to attach when the instance has none. + Image of the sandbox plugin to attach when the instance has none. It asks first, so it only attaches from a terminal. [default: plugins/sandbox:latest] --force Overwrite the local file if it already exists. @@ -3009,7 +3190,7 @@ Flags: Name of the sandbox plugin to use. [default: sandbox] --plugin-image= - Image of the sandbox plugin to attach when the instance has none. + Image of the sandbox plugin to attach when the instance has none. It asks first, so it only attaches from a terminal. [default: plugins/sandbox:latest] --append Append to the remote file instead of overwriting it. @@ -3069,7 +3250,7 @@ Flags: Name of the sandbox plugin to use. [default: sandbox] --plugin-image= - Image of the sandbox plugin to attach when the instance has none. + Image of the sandbox plugin to attach when the instance has none. It asks first, so it only attaches from a terminal. [default: plugins/sandbox:latest] --force Overwrite the local file if it already exists. diff --git a/cmd/unikraft/testdata/TestHelp/run b/cmd/unikraft/testdata/TestHelp/run index 14ae617ab..4c0a03b0b 100644 --- a/cmd/unikraft/testdata/TestHelp/run +++ b/cmd/unikraft/testdata/TestHelp/run @@ -56,6 +56,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -65,8 +66,10 @@ Fields: service.soft-limit, service.hard-limit volumes, volumes.*, volumes.*.name, volumes.*.uuid, volumes.*.at, volumes.*.readonly, volumes.*.size - roms, roms.*, roms.*.name, roms.*.image, roms.*.dir, roms.*.at - plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.config + roms, roms.*, roms.*.name, roms.*.image, roms.*.pull-policy, roms.*.headers, + roms.*.dir, roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.headers, plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -148,8 +151,11 @@ Create flags: Image to deploy, as an OCI reference or a full registry URL. On create, required unless template, branch or checkpoint is given, and cannot be combined with them. [examples: nginx:latest, my-app:v1.2.3] --pull-policy= - When to pull the image relative to the node's cache: always, if_not_present or never. + When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. [examples: always, if_not_present, never] + --image-header== ... + HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again. + [example: Authorization=Bearer ] --type= Virtual machine type. micro: Firecracker microVM (default) @@ -172,12 +178,15 @@ Create flags: [examples: 0, 1] --service= Service group to join, by name or UUID. Leave unset and give service.services or service.domains to create a group owned by the instance. Without any service the instance is reachable only privately. - -p, --publish=:[/] ... - Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only. + -p, --publish=:[/][@] ... + Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP. http: load balance per HTTP request instead of per TCP connection tls: terminate TLS at the platform - redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect. - [examples: 443:8080/http+tls, 80:443/http+redirect] + redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect + tcp: publish a TCP port, the default + udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10 + @IP: public IP assigned to you on the group's node. + [examples: 443:8080/http+tls, 80:443/http+redirect, 53:53/udp@203.0.113.10] --domain= ... Domain for the group. myapp: a bare label becomes a subdomain of the metro @@ -186,11 +195,11 @@ Create flags: -v, --volume=[]:[:] ... Volume to attach as NAME:/MOUNT[:ro], where the mount path is absolute and outside /uk. On create, leave NAME empty and add :size=SIZE, as in :/data:size=1GiB, to make a new volume with a generated name. [examples: my-vol:/data, cache:/tmp:ro, :/data:size=1GiB] - --rom=name=,image=,at= ... - Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. + --rom=name=,image=[,pull-policy=][,headers.=],at= ... + Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=my-rom,image=myuser/my-rom:latest,at=/rom0, name=mydata,dir=./mydata,at=/rom] - --plugin=name=,image=[,config=] ... - Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. + --plugin=name=,image=[,pull-policy=][,headers.=][,config=] ... + Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={"KEY":"a,b"}. [examples: name=sandbox,image=plugins/sandbox:latest, name=sandbox,image=plugins/sandbox:latest,config={"persist_path":"/data"}] --network== ... Network interface to attach, one per flag and up to 4. The first one is the primary interface. Needs the net_manager permission. diff --git a/cmd/unikraft/testdata/TestHelp/services b/cmd/unikraft/testdata/TestHelp/services index 542cc4af0..5bbce7649 100644 --- a/cmd/unikraft/testdata/TestHelp/services +++ b/cmd/unikraft/testdata/TestHelp/services @@ -33,7 +33,7 @@ Fields: domains.*.certificate.name, domains.*.certificate.uuid instances, instances.*, instances.*.name, instances.*.uuid services, services.*, services.*.source, services.*.destination, - services.*.handlers + services.*.protocol, services.*.ip, services.*.handlers Global flags: -h, --help @@ -83,7 +83,7 @@ Fields: domains.*.certificate.name, domains.*.certificate.uuid instances, instances.*, instances.*.name, instances.*.uuid services, services.*, services.*.source, services.*.destination, - services.*.handlers + services.*.protocol, services.*.ip, services.*.handlers Flags: -w, --watch= @@ -141,7 +141,7 @@ Fields: domains.*.certificate.name, domains.*.certificate.uuid instances, instances.*, instances.*.name, instances.*.uuid services, services.*, services.*.source, services.*.destination, - services.*.handlers + services.*.protocol, services.*.ip, services.*.handlers Flags: --filter @@ -203,7 +203,7 @@ Fields: domains.*.certificate.name, domains.*.certificate.uuid instances, instances.*, instances.*.name, instances.*.uuid services, services.*, services.*.source, services.*.destination, - services.*.handlers + services.*.protocol, services.*.ip, services.*.handlers Flags: --until, --filter @@ -251,6 +251,12 @@ Examples: --domain demo \ --service 443:8080/tls+http + # Create a service group with a UDP port on a dedicated IP + unikraft service create \ + --name dns \ + --metro fra \ + --service 53:53/udp@203.0.113.10 + Fields: metro name @@ -265,7 +271,7 @@ Fields: domains.*.certificate.name, domains.*.certificate.uuid instances, instances.*, instances.*.name, instances.*.uuid services, services.*, services.*.source, services.*.destination, - services.*.handlers + services.*.protocol, services.*.ip, services.*.handlers Flags: --set== ..., --set-file== ... @@ -325,12 +331,15 @@ Create flags: myapp: a bare label becomes a subdomain of the metro example.com: a dotted name is a custom domain, with a certificate issued automatically unless given as fqdn=example.com,certificate=my-cert. [examples: example.com, myapp] - --service=:[/] ... - Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only. + --service=:[/][@] ... + Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP. http: load balance per HTTP request instead of per TCP connection tls: terminate TLS at the platform - redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect. - [examples: 443:8080/http+tls, 80:443/http+redirect] + redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect + tcp: publish a TCP port, the default + udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10 + @IP: public IP assigned to you on the group's node. + [examples: 443:8080/http+tls, 80:443/http+redirect, 53:53/udp@203.0.113.10] $ unikraft service edit --help @@ -361,7 +370,7 @@ Fields: domains.*.certificate.name, domains.*.certificate.uuid instances, instances.*, instances.*.name, instances.*.uuid services, services.*, services.*.source, services.*.destination, - services.*.handlers + services.*.protocol, services.*.ip, services.*.handlers Flags: --set== ..., --set-file== ... @@ -418,12 +427,15 @@ Edit flags: myapp: a bare label becomes a subdomain of the metro example.com: a dotted name is a custom domain, with a certificate issued automatically unless given as fqdn=example.com,certificate=my-cert. [examples: example.com, myapp] - --service=:[/] ... - Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only. + --service=:[/][@] ... + Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP. http: load balance per HTTP request instead of per TCP connection tls: terminate TLS at the platform - redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect. - [examples: 443:8080/http+tls, 80:443/http+redirect] + redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect + tcp: publish a TCP port, the default + udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10 + @IP: public IP assigned to you on the group's node. + [examples: 443:8080/http+tls, 80:443/http+redirect, 53:53/udp@203.0.113.10] $ unikraft service delete --help @@ -460,7 +472,7 @@ Fields: domains.*.certificate.name, domains.*.certificate.uuid instances, instances.*, instances.*.name, instances.*.uuid services, services.*, services.*.source, services.*.destination, - services.*.handlers + services.*.protocol, services.*.ip, services.*.handlers Flags: --all diff --git a/go.mod b/go.mod index 4f4e17a67..c62a55e02 100644 --- a/go.mod +++ b/go.mod @@ -6,14 +6,14 @@ tool github.com/caarlos0/svu/v3 require ( charm.land/bubbles/v2 v2.2.1 - charm.land/bubbletea/v2 v2.1.1 - charm.land/lipgloss/v2 v2.0.6 + charm.land/bubbletea/v2 v2.1.2 + charm.land/lipgloss/v2 v2.1.2-0.20261126165533-22b09d7f3566 github.com/MakeNowJust/heredoc v1.0.0 github.com/Masterminds/sprig/v3 v3.3.0 github.com/alecthomas/kong v1.17.0 github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de github.com/charmbracelet/colorprofile v0.4.3 - github.com/charmbracelet/x/ansi v0.11.9 + github.com/charmbracelet/x/ansi v0.11.10 github.com/charmbracelet/x/term v0.2.2 github.com/coder/websocket v1.8.15 github.com/containerd/containerd/v2 v2.4.2 @@ -23,7 +23,7 @@ require ( github.com/containerd/platforms v1.0.0-rc.5 github.com/cpuguy83/go-md2man/v2 v2.0.7 github.com/creack/pty v1.1.24 - github.com/docker/cli v29.9.3+incompatible + github.com/docker/cli v29.10.0+incompatible github.com/docker/go-units v0.5.0 github.com/ettle/strcase v0.2.0 github.com/go-json-experiment/json v1.27.2 @@ -38,14 +38,14 @@ require ( github.com/opencontainers/image-spec v1.1.1 github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c github.com/posener/complete v1.2.3 - github.com/posthog/posthog-go v1.42.4 + github.com/posthog/posthog-go v1.44.1 github.com/rs/zerolog v1.35.1 - github.com/sergi/go-diff v1.4.0 + github.com/sergi/go-diff v1.4.5 github.com/sirupsen/logrus v1.10.2 github.com/stretchr/testify v1.12.1 - github.com/tidwall/gjson v1.20.2 + github.com/tidwall/gjson v1.20.4 github.com/tonistiigi/fsutil v0.0.0-20261103125000-e075fd9305eb - github.com/unikraft/go-archivefs v0.0.0-20261106133356-c81ad57e55c4 + github.com/unikraft/go-archivefs v0.0.0-20261124155100-7c53c03d86ce golang.org/x/mod v0.43.0 golang.org/x/sync v0.25.0 golang.org/x/sys v0.50.0 @@ -54,24 +54,24 @@ require ( gotest.tools/v3 v3.5.2 mvdan.cc/sh/v3 v3.14.1 sigs.k8s.io/yaml v1.6.0 - unikraft.com/cloud/plugins/sandbox v0.0.0-20261110115830-def4e9d2e457 - unikraft.com/cloud/sdk v0.4.1-staging.14 - unikraft.com/cloud/sdk/build v0.0.0-20261112083743-f904b5bfc966 - unikraft.com/cloud/sdk/plugins/sandbox v0.0.0-20261113085313-a2a9f94fc300 - unikraft.com/x/build v0.0.0-20261111120215-5177d0f4c7b6 + unikraft.com/cloud/plugins/sandbox v0.0.0-20261125131623-d66f7dd900a2 + unikraft.com/cloud/sdk v0.4.6-staging.9 + unikraft.com/cloud/sdk/build v0.4.6-staging.6 + unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.7 + unikraft.com/x/build v0.0.0-20261126162113-a81b5204c19b unikraft.com/x/buildkit v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/colors v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/filters v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/fingerprint v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/guesstermwidth v0.0.0-20261111120215-5177d0f4c7b6 - unikraft.com/x/image-spec v0.0.0-20261111120215-5177d0f4c7b6 + unikraft.com/x/image-spec v0.0.0-20261126162113-a81b5204c19b unikraft.com/x/io v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/joinerrgroup v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/kingkong v0.0.0-20261111120215-5177d0f4c7b6 - unikraft.com/x/kraftfile v0.0.0-20261111120215-5177d0f4c7b6 - unikraft.com/x/log v0.0.0-20261111120215-5177d0f4c7b6 + unikraft.com/x/kraftfile v0.0.0-20261120151658-ea11ec33af9a + unikraft.com/x/log v0.0.0-20261116145447-f4dbf6ae0056 unikraft.com/x/ptr v0.0.0-20261111120215-5177d0f4c7b6 - unikraft.com/x/shell v0.0.0-20261113145058-65fc641f4af8 + unikraft.com/x/shell v0.0.0-20261117090838-250b71577700 unikraft.com/x/signal v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/stdio v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/version v0.0.0-20261111120215-5177d0f4c7b6 @@ -83,7 +83,7 @@ require ( github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.5.0 // indirect github.com/Microsoft/go-winio v0.6.4 // indirect - github.com/andybalholm/brotli v1.1.1 // indirect + github.com/andybalholm/brotli v1.3.0 // indirect github.com/atotto/clipboard v0.1.4 // indirect github.com/bahlo/generic-list-go v0.2.0 // indirect github.com/buger/jsonparser v1.1.2 // indirect @@ -131,10 +131,10 @@ require ( github.com/in-toto/in-toto-golang v0.11.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/invopop/jsonschema v0.14.0 // indirect - github.com/klauspost/compress v1.20.3 // indirect + github.com/klauspost/compress v1.20.4 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect - github.com/mattn/go-colorable v0.1.15 // indirect + github.com/mattn/go-colorable v0.1.16 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/mattn/go-runewidth v0.0.31 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect @@ -199,23 +199,20 @@ require ( go.yaml.in/yaml/v3 v3.0.6 // indirect go.yaml.in/yaml/v4 v4.0.0 // indirect go4.org/mem v0.0.0-20240501181205-ae6ca9944745 // indirect - golang.org/x/crypto v0.58.0 // indirect + golang.org/x/crypto v0.59.0 // indirect golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect golang.org/x/net v0.62.0 // indirect golang.org/x/oauth2 v0.37.0 // indirect - golang.org/x/term v0.47.0 // indirect + golang.org/x/term v0.48.0 // indirect golang.org/x/time v0.16.0 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20261012220534-4341edf3f941 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20261012220534-4341edf3f941 // indirect google.golang.org/grpc v1.85.0 // indirect google.golang.org/protobuf v1.36.12 // indirect tailscale.com v1.104.5 // indirect + unikraft.com/x/dockerfile v0.0.0-20261118100745-28172ae5f28c // indirect ) -// Use the fork with charmbracelet/lipgloss#746 until a release has it. -// It stops the Windows hang at startup when stdin is redirected. -replace charm.land/lipgloss/v2 => github.com/unikraft-cloud/lipgloss/v2 v2.0.0-20260921145830-9a285e5dd507 - // Use master with mvdan/sh#1433 until a release has it. // It resolves the instance's Unix paths as such on Windows. replace mvdan.cc/sh/v3 => mvdan.cc/sh/v3 v3.14.1-0.20261019164542-27edea01b10f diff --git a/go.sum b/go.sum index 7d8e74949..3a4075677 100644 --- a/go.sum +++ b/go.sum @@ -1,9 +1,11 @@ charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU= charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc= -charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU= -charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= +charm.land/bubbletea/v2 v2.1.2 h1:vB3XAcHhLB2gR3HOHpwO3lHB3nbvaowIgL3e5x/DUZo= +charm.land/bubbletea/v2 v2.1.2/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= charm.land/fang/v2 v2.0.1 h1:zQCM8JQJ1JnQX/66B5jlCYBUxL2as5JXQZ2KJ6EL0mY= charm.land/fang/v2 v2.0.1/go.mod h1:S1GmkpcvK+OB5w9caywUnJcsMew45Ot8FXqoz8ALrII= +charm.land/lipgloss/v2 v2.1.2-0.20261126165533-22b09d7f3566 h1:JjEXjT4hwlmmlQW4JjKa0C4EpgBw9uDPVM8y1SodE/s= +charm.land/lipgloss/v2 v2.1.2-0.20261126165533-22b09d7f3566/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc= dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA= filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= @@ -24,6 +26,8 @@ github.com/Microsoft/hcsshim v0.15.0 h1:AWiHGf0+9f7cDcfhuU3zXORCAPmIOWzTYfHhcrMc github.com/Microsoft/hcsshim v0.15.0/go.mod h1:eStXUkML1Fmkgmwr6XHbYkBC1j7p2FA8ZtA9dyRMbts= github.com/ProtonMail/go-crypto v1.4.1 h1:9RfcZHqEQUvP8RzecWEUafnZVtEvrBVL9BiF67IQOfM= github.com/ProtonMail/go-crypto v1.4.1/go.mod h1:e1OaTyu5SYVrO9gKOEhTc+5UcXtTUa+P3uLudwcgPqo= +github.com/agext/levenshtein v1.2.3 h1:YB2fHEn0UJagG8T1rrWknE3ZQzWM06O8AMAatNn7lmo= +github.com/agext/levenshtein v1.2.3/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/kong v1.17.0 h1:f52BVWChYMDkMkCoqkEWRuFOk/K4B5LO7xIijeLJRdk= @@ -32,8 +36,8 @@ github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/anchore/go-struct-converter v0.1.0 h1:2rDRssAl6mgKBSLNiVCMADgZRhoqtw9dedlWa0OhD30= github.com/anchore/go-struct-converter v0.1.0/go.mod h1:rYqSE9HbjzpHTI74vwPvae4ZVYZd1lue2ta6xHPdblA= -github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= -github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY= +github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de h1:FxWPpzIjnTlhPwqqXc4/vE0f7GvRjuAsbW+HOIe8KnA= github.com/araddon/dateparse v0.0.0-20210429162001-6b43995a97de/go.mod h1:DCaWoUhZrYW9p1lxo/cm8EmUOOzAPSEZNGF2DK1dJgw= github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so= @@ -86,8 +90,8 @@ github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao= github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4 h1:hISLzUbwcvJbGoNR6A3L/TpguRRnACBmZOee8LcHLJw= github.com/charmbracelet/ultraviolet v0.0.0-20261008173134-6b8d4baf91b4/go.mod h1:aJDVk+WOVM1K04rdc/71PMPoUGfjxjhvXfP3Pjz1Zio= -github.com/charmbracelet/x/ansi v0.11.9 h1:kIrqLBxtTVbLyyHO2Evoi93EjQo1mylWmpNEsfPxXAM= -github.com/charmbracelet/x/ansi v0.11.9/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= +github.com/charmbracelet/x/ansi v0.11.10 h1:GjcX3+rAk+8wDX/jY0XwrZstxkjRcLkYU3TvwzZWiRA= +github.com/charmbracelet/x/ansi v0.11.10/go.mod h1:DG/hpOnaI2QJ/KMMqLL2h0KVhluuJLazf8973P+Vy5w= github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444 h1:IJDiTgVE56gkAGfq0lBEloWgkXMk4hl/bmuPoicI4R0= github.com/charmbracelet/x/exp/charmtone v0.0.0-20250603201427-c31516f43444/go.mod h1:T9jr8CzFpjhFVHjNjKwbAD7KwBNyFnj2pntAO7F2zw0= github.com/charmbracelet/x/exp/golden v0.0.0-20250806222409-83e3a29d542f h1:pk6gmGpCE7F3FcjaOEKYriCvpmIN4+6OS/RD0vm4uIA= @@ -160,8 +164,8 @@ github.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7 h1:lxmTCgmHE1G github.com/digitorus/timestamp v0.0.0-20231217203849-220c5c2851b7/go.mod h1:GvWntX9qiTlOud0WkQ6ewFm0LPy5JUR1Xo0Ngbd1w6Y= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= -github.com/docker/cli v29.9.3+incompatible h1:SBaMp7ecohadEHMDrUJg22t9I3awqsAVhnJ7GOcWpfE= -github.com/docker/cli v29.9.3+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/cli v29.10.0+incompatible h1:lCL+clBUJnHsmjBCr6TwvfQFkmBidPxi5SkuXCoYxc0= +github.com/docker/cli v29.10.0+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/docker-credential-helpers v0.9.9 h1:BkydjIgZ46JnDbqyM2p2fc63KMw6y+KHL3Em/2AGJ7w= github.com/docker/docker-credential-helpers v0.9.9/go.mod h1:v1S+hepowrQXITkEfw6o4+BMbGot02wiKpzWhGUZK6c= github.com/docker/go-connections v0.8.2 h1:9d9DEokx5W7qlr0shkFXIxEA7+TTD+llwzcykSlxMNc= @@ -295,8 +299,8 @@ github.com/jotaen/kong-completion v0.0.15 h1:ygxUE1S2Ec4OOnJxQEXDf8UdSQryrQzYksg github.com/jotaen/kong-completion v0.0.15/go.mod h1:dyIG20e3qq128SUBtF8jzI7YtkfzjWMlgbqkAJd6xHQ= github.com/juju/errors v1.0.0 h1:yiq7kjCLll1BiaRuNY53MGI0+EQ3rF6GB+wvboZDefM= github.com/juju/errors v1.0.0/go.mod h1:B5x9thDqx0wIMH3+aLIMP9HjItInYWObRovoCFM5Qe8= -github.com/klauspost/compress v1.20.3 h1:zWNoFqq/lSuYQRim3dUXlXeA0IqwuZGicdG5ZTfY5j4= -github.com/klauspost/compress v1.20.3/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= @@ -308,8 +312,8 @@ github.com/lucasb-eyer/go-colorful v1.4.1 h1:1EO+WB73+EH8EVbzlrG3KLAfEypQWVHIBql github.com/lucasb-eyer/go-colorful v1.4.1/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 h1:6E+4a0GO5zZEnZ81pIr0yLvtUWk2if982qA3F3QD6H4= github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0/go.mod h1:zJYVVT2jmtg6P3p1VtQj7WsuWi/y4VnjVBn7F8KPB3I= -github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= -github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-colorable v0.1.16 h1:+2YjeAe7xP1OQbZW1jERPWWCDLlNqFNCvjiqGiAt84A= +github.com/mattn/go-colorable v0.1.16/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= @@ -378,8 +382,8 @@ github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1 github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/posener/complete v1.2.3 h1:NP0eAhjcjImqslEwo/1hq7gpajME0fTLTezBKDqfXqo= github.com/posener/complete v1.2.3/go.mod h1:WZIdtGGp+qx0sLrYKtIRAruyNpv6hFCicSgv7Sy7s/s= -github.com/posthog/posthog-go v1.42.4 h1:uPmI3fqx7pSZuPofvf30KbKOtJPKjlMTEbwWd9pn3UY= -github.com/posthog/posthog-go v1.42.4/go.mod h1:rN0C9Urenhytgo3KQ/QVorGkyGfpouquDTSs2Ujzr+g= +github.com/posthog/posthog-go v1.44.1 h1:0EWi9vEXwW0u6NGtCYArOsPGPLiFuMFLyvTs+7a9X9o= +github.com/posthog/posthog-go v1.44.1/go.mod h1:rN0C9Urenhytgo3KQ/QVorGkyGfpouquDTSs2Ujzr+g= github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6 h1:jL3a8soXdzuTCcRnKhOmtcsVOObdDTFf4O2B403HPRU= github.com/power-devops/perfstat v0.0.0-20260805114148-88456608a4f6/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE= github.com/reeflective/readline v1.3.0 h1:uh9c2SEmyoy7A/auequfXZjvK0NP5HVEAJFcL9Uf7qE= @@ -406,8 +410,8 @@ github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= -github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= -github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/sergi/go-diff v1.4.5 h1:3LvhZn2aCAWagLwIhga3BZiEZ82j5+oQ0vKDwkhjHCI= +github.com/sergi/go-diff v1.4.5/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= github.com/shibumi/go-pathspec v1.3.0 h1:QUyMZhFo0Md5B8zV8x2tesohbb5kfbpTi9rBnKh5dkI= github.com/shibumi/go-pathspec v1.3.0/go.mod h1:Xutfslp817l2I1cZvgcfeMQJG5QnU2lh5tVaaMCl3jE= github.com/shirou/gopsutil/v4 v4.26.10 h1:MJN6euesJx53MVEjscYeyRSRcrdIcy3sz5k9nosjldg= @@ -453,8 +457,8 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8 github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/theupdateframework/go-tuf/v2 v2.4.2 h1:w7976/W8uTwlsegP5nRymlpjPgrwSh+AXUf85is6nJk= github.com/theupdateframework/go-tuf/v2 v2.4.2/go.mod h1:JqBrIUnNLAaNq/8GmBcEMFWfAFBbqp/MkJEJseXKbks= -github.com/tidwall/gjson v1.20.2 h1:Ag48cSOUCOq/sheSLXV3M4ZS0FOd4YMnY1N7FRoxGQY= -github.com/tidwall/gjson v1.20.2/go.mod h1:jV1Xkr7LRLVFhesDFU/nInoQ+MjVlnuqkUreTWMveUo= +github.com/tidwall/gjson v1.20.4 h1:3A/Gmx6kyM902v2nepualaq7aYIGhF0eykJBTiIxryw= +github.com/tidwall/gjson v1.20.4/go.mod h1:jV1Xkr7LRLVFhesDFU/nInoQ+MjVlnuqkUreTWMveUo= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.3.0 h1:DZmEzADnMIbThFXXslDgq9C0LCC/xzMrONm7iM77RM0= @@ -475,10 +479,8 @@ github.com/transparency-dev/formats v0.1.1 h1:4bVHJc+KdBgpA1OJD1yjI+g0i5Z1graCpp github.com/transparency-dev/formats v0.1.1/go.mod h1:qtZ8goRuJ8FTBG9c9+Bj0rn2rUG7eG/AUTkr+Aw3jFw= github.com/transparency-dev/merkle v0.0.2 h1:Q9nBoQcZcgPamMkGn7ghV8XiTZ/kRxn1yCG81+twTK4= github.com/transparency-dev/merkle v0.0.2/go.mod h1:pqSy+OXefQ1EDUVmAJ8MUhHB9TXGuzVAT58PqBoHz1A= -github.com/unikraft-cloud/lipgloss/v2 v2.0.0-20260921145830-9a285e5dd507 h1:Pshbef+pR9j+qiRihFkbpBZK5ptj6ikk70uO0MJj1D8= -github.com/unikraft-cloud/lipgloss/v2 v2.0.0-20260921145830-9a285e5dd507/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI= -github.com/unikraft/go-archivefs v0.0.0-20261106133356-c81ad57e55c4 h1:Do8BfD6VM6bYg44KYvaB+xd9Q+BQs10QDziwMkMqdQk= -github.com/unikraft/go-archivefs v0.0.0-20261106133356-c81ad57e55c4/go.mod h1:NLWtSTdsTRLGQN87zqm9+vN01Ei9JX+FWwuOme2wJXw= +github.com/unikraft/go-archivefs v0.0.0-20261124155100-7c53c03d86ce h1:iDLanVjLs39hVbWid8dkIWCmcCihhfq0M0OOUY6EQao= +github.com/unikraft/go-archivefs v0.0.0-20261124155100-7c53c03d86ce/go.mod h1:NLWtSTdsTRLGQN87zqm9+vN01Ei9JX+FWwuOme2wJXw= github.com/vbatts/tar-split v0.12.3 h1:Cd46rkGXI3Td4yrVNwU8ripbxFaQbmesqhjBUUYAJSw= github.com/vbatts/tar-split v0.12.3/go.mod h1:sQOc6OlqGCr7HkGx/IDBeKiTIvqhmj8KffNhEXG4Nq0= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= @@ -530,8 +532,8 @@ go.yaml.in/yaml/v4 v4.0.0 h1:/LG1pNO84Z4l603j/xMn69CcS5OYhMQ/f7l2LoQUGuw= go.yaml.in/yaml/v4 v4.0.0/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= go4.org/mem v0.0.0-20240501181205-ae6ca9944745 h1:Tl++JLUCe4sxGu8cTpDzRLd3tN7US4hOxG5YpKCzkek= go4.org/mem v0.0.0-20240501181205-ae6ca9944745/go.mod h1:reUoABIJ9ikfM5sgtSF3Wushcza7+WeD01VB9Lirh3g= -golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= -golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c= +golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U= golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba h1:Ck8QetSgk912qxWLMCKxd0in+aiyBQyDSMae6e/xmpU= golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba/go.mod h1:50RgIsmK7OwqzTTeqcSXQW8SswW0o8fRcDxmqGluJ8E= golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg= @@ -547,8 +549,8 @@ golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs= golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= -golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= +golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk= +golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4= golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= @@ -587,28 +589,30 @@ sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= tailscale.com v1.104.5 h1:TLemRww20+bcQ0FEVTTZ7yMtVDZ4pOpSCL86Oo9g3mA= tailscale.com v1.104.5/go.mod h1:Hq4zB8UpaxMW1fvqO30CLVQo3A7Ith0t9MnvEyiuoSA= -unikraft.com/cloud/plugins/sandbox v0.0.0-20261110115830-def4e9d2e457 h1:Y+yniFXgmhVcywvhkgEDUHEvTgdUbXu/E4L2uBO52YE= -unikraft.com/cloud/plugins/sandbox v0.0.0-20261110115830-def4e9d2e457/go.mod h1:FEt8GD8sVIPGfh4taRsjIg0Qi6FctdsAtC2Nmf55Wjg= -unikraft.com/cloud/sdk v0.4.1-staging.14 h1:bCy/7+NekMTflCTJgGnxm0fz1tfAjL1cbKFPqEVSOck= -unikraft.com/cloud/sdk v0.4.1-staging.14/go.mod h1:fqJuz5qVQraUc+7+o35ejswZc1hRDZlmBGWLdU4pkPQ= -unikraft.com/cloud/sdk/build v0.0.0-20261112083743-f904b5bfc966 h1:hJ3PzigJbcAwnD51e8+sNMHULSgosSC62Mm8SraGx4w= -unikraft.com/cloud/sdk/build v0.0.0-20261112083743-f904b5bfc966/go.mod h1:donDzooDSHxIveRqivrltY/k2BYf8P1usqxJsR9MlVA= -unikraft.com/cloud/sdk/plugins/sandbox v0.0.0-20261113085313-a2a9f94fc300 h1:Kd2UFcrIAzOBb6kHrfSpcKT/7I7eaKyjfkMidlbw/ls= -unikraft.com/cloud/sdk/plugins/sandbox v0.0.0-20261113085313-a2a9f94fc300/go.mod h1:IcBVuNwBfN5aZYT0tl17J/T0jwDUqhPQsuF5o8RMNzo= -unikraft.com/x/build v0.0.0-20261111120215-5177d0f4c7b6 h1:v6faME7Yc5iVNtPmNTCaO7UxNQA+x7Dtv0kQmMz/GdU= -unikraft.com/x/build v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:MzRYfAFG0ID5dRVJVKykdEDYCIbygQO0FiUQ4ryYD3M= +unikraft.com/cloud/plugins/sandbox v0.0.0-20261125131623-d66f7dd900a2 h1:6+KBOBG2QnqxBvi6ArHn+Lo7pTQW1GbozRiNN2un9to= +unikraft.com/cloud/plugins/sandbox v0.0.0-20261125131623-d66f7dd900a2/go.mod h1:FEt8GD8sVIPGfh4taRsjIg0Qi6FctdsAtC2Nmf55Wjg= +unikraft.com/cloud/sdk v0.4.6-staging.9 h1:wVzAbp1FFx2Z07RsYuEF1uwZZPLpbGSHdnPjYFURqCM= +unikraft.com/cloud/sdk v0.4.6-staging.9/go.mod h1:TGgPvZueyiNCuuyuP7WBmyRdXNbxqq8Y5V4BTLqX7MI= +unikraft.com/cloud/sdk/build v0.4.6-staging.6 h1:sl5lpnu8FASorQASlE+tXOf6AddsUlgkP5adlGqiEOY= +unikraft.com/cloud/sdk/build v0.4.6-staging.6/go.mod h1:Hc6vOMp7HnJmUAazNXwiz3ym3AYVMqyjkU/r9TexGRM= +unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.7 h1:0emZQzXuijIXCYirW2w06voptUCozXNbVd0MS6JM8+Y= +unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.7/go.mod h1:6VzCR9HrTVD1gNzKWMv1UMLyFqcHUS6caXq0vGDMqiQ= +unikraft.com/x/build v0.0.0-20261126162113-a81b5204c19b h1:zp4RrO4xx7RbU8iGN7YmgXKhueRa9Yg1v6YaOHvZH9Q= +unikraft.com/x/build v0.0.0-20261126162113-a81b5204c19b/go.mod h1:aRRxLJqi1sUh/dFCJ1Kan/6hcGeq14hLs50X6RlUnuM= unikraft.com/x/buildkit v0.0.0-20261111120215-5177d0f4c7b6 h1:/7BTbMIFXN81vbpO3oB2Vh/97BBCpYIAJXP/z3d4qao= unikraft.com/x/buildkit v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:wOWsRBT0lyV3uWHiQX3Tbr3bzwtfQmZN9SUnyKQNi38= unikraft.com/x/colors v0.0.0-20261111120215-5177d0f4c7b6 h1:HnCSAluQGFRfZ01FK6pjoK3sYWUjDYA9Rs9ZjTw7juM= unikraft.com/x/colors v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:udM/yr1HbZbG9qs33/kqZZ/B9LVdTgcFy/TTS3szEMw= +unikraft.com/x/dockerfile v0.0.0-20261118100745-28172ae5f28c h1:rAUIn2lBKfT2LawKOzXQFcRZArKnXmhCqD4lmZmz1U8= +unikraft.com/x/dockerfile v0.0.0-20261118100745-28172ae5f28c/go.mod h1:v4ffngl0ivI3eCZcPlL0s25Fn7wYTo0Po7faaVx3IaA= unikraft.com/x/filters v0.0.0-20261111120215-5177d0f4c7b6 h1:cbbVGw1wGf7AlkUgO8HEcJtR52miZTDW2nJb54D+fRg= unikraft.com/x/filters v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:l01AijxdrSNT6W3tREzUbHZVMxfX+b2UK/B16FOII30= unikraft.com/x/fingerprint v0.0.0-20261111120215-5177d0f4c7b6 h1:ZJ3Pzaej6zNGKQ61Z7EvVIMYzH0S+4Z6smP8ohVcLHg= unikraft.com/x/fingerprint v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:A49h7MGEJpnhuqXONsNMI7OMHgz2HpD4o3UmJnrM8i4= unikraft.com/x/guesstermwidth v0.0.0-20261111120215-5177d0f4c7b6 h1:9XUQLejScr6+iKixqZFMPg+NmGYQJCc8O8BFjzcfpns= unikraft.com/x/guesstermwidth v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:Ottq5zN7Zuge2ySDoWllICAVudREPmCvv00d0FPx35w= -unikraft.com/x/image-spec v0.0.0-20261111120215-5177d0f4c7b6 h1:t6u3lNymtj7tL1XledsXYv4mTfgyqRSdEhkll55hJE8= -unikraft.com/x/image-spec v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:0WpdrxA0kZEzzkZiwjMpWJSo3/xbZwhnOIwnc0tDyBc= +unikraft.com/x/image-spec v0.0.0-20261126162113-a81b5204c19b h1:uRIUKQSbm8bwO9pq/3X6dr/gCqp6wvtBNf5wUxZSXNA= +unikraft.com/x/image-spec v0.0.0-20261126162113-a81b5204c19b/go.mod h1:YIkqwG7NBIMVwPKm2GUB0eMp5DGpk5cVBVD4AGuWAJA= unikraft.com/x/integration v0.0.0-20261029083025-f2d161e6abc8 h1:R48wpvUv46CfArM0GdTKWxhDlkagFnRtAaFmRu45O7g= unikraft.com/x/integration v0.0.0-20261029083025-f2d161e6abc8/go.mod h1:yUzpOnSm68CH1Ujou0bTEJimecGiAjyqfCPiRrFWQI4= unikraft.com/x/io v0.0.0-20261111120215-5177d0f4c7b6 h1:PGFwRBtzJzxgyuLb4uNk0Ucs3i1U/bY9tZmp/kB+bqs= @@ -617,14 +621,14 @@ unikraft.com/x/joinerrgroup v0.0.0-20261111120215-5177d0f4c7b6 h1:AnGpM5eeQfP834 unikraft.com/x/joinerrgroup v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:0qnGxrE3hao0DVREueSDclONRwth1sCBfZjdX4/2mpg= unikraft.com/x/kingkong v0.0.0-20261111120215-5177d0f4c7b6 h1:sWT5GFDU1F7bu5XE7qyp8eaJ6ft7w3emhFvfJetw6a0= unikraft.com/x/kingkong v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:zmUUwkpfQBJaz99ErDMpef0ABijcnwpOcW02plhJxOM= -unikraft.com/x/kraftfile v0.0.0-20261111120215-5177d0f4c7b6 h1:8hLPDvncyC4bwhX8td+C2q/b5pjLKo9zqSism14rR08= -unikraft.com/x/kraftfile v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:QK+7/geX7b/Dwiy3CVbsI/+9Ys5m/r+RRu/BG6qX5tk= -unikraft.com/x/log v0.0.0-20261111120215-5177d0f4c7b6 h1:tTlHiTnp8FgfAV/UPv2ddaV7vH2IUsT1sbOzc2KgSm4= -unikraft.com/x/log v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:XCwOFKbAMvfdyLfU/pRVtW5lqHu60urteiLHDmsj7tc= +unikraft.com/x/kraftfile v0.0.0-20261120151658-ea11ec33af9a h1:OPibyR7tHkWqXhjDA06I78wy9mrAVyMoLoo+YQ1nQj4= +unikraft.com/x/kraftfile v0.0.0-20261120151658-ea11ec33af9a/go.mod h1:dXz/eyg7hoRI0RMvaCzbR0GvFyGMJj9Em7VTdNZpFR4= +unikraft.com/x/log v0.0.0-20261116145447-f4dbf6ae0056 h1:WCCv524/W8gBiBGxopg1mueM82SGtQuCrsPs955En5U= +unikraft.com/x/log v0.0.0-20261116145447-f4dbf6ae0056/go.mod h1:uNZR+KiFX+1Pj2z1x5oJLH0GG2ufJyIiMFe8BJ5cZFI= unikraft.com/x/ptr v0.0.0-20261111120215-5177d0f4c7b6 h1:MSng9itL6/GROsKNwiSBScXwjda16wdTegJphP5zjQw= unikraft.com/x/ptr v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:IZpTTnftvOzfw7QT9SBZKBhPfPcbJ0VgXmDQIjuHUOM= -unikraft.com/x/shell v0.0.0-20261113145058-65fc641f4af8 h1:WfoTFZuyXmEJMOwedM1pGxyvyMo5lHOlqLW8xZM940o= -unikraft.com/x/shell v0.0.0-20261113145058-65fc641f4af8/go.mod h1:QpNFjczQ8PkEt/OwRz56gQFOjVsHUDCfViNq3fsiJD4= +unikraft.com/x/shell v0.0.0-20261117090838-250b71577700 h1:yW57fQvpgpvmab7R+SkwRU+9Bz7SiG7m7xGfIYHiKJs= +unikraft.com/x/shell v0.0.0-20261117090838-250b71577700/go.mod h1:kjMnnvZy9A0WAJUs6/Sjgi/TzKRyGZCq7h9Q2fncdu4= unikraft.com/x/signal v0.0.0-20261111120215-5177d0f4c7b6 h1:dYBrChU3VwjOHXAbOsVT1BRFbTisP8pcOTP3VwlQVlw= unikraft.com/x/signal v0.0.0-20261111120215-5177d0f4c7b6/go.mod h1:BemdputO8Po0JUUXCoOKVQ/Kbd2fPcz3AATOE2Uy3bU= unikraft.com/x/stdio v0.0.0-20261111120215-5177d0f4c7b6 h1:rL7uxbhJeZrSFhg/TXLIn//cVoUMAIt7+Z0yIHks9Pw= diff --git a/internal/cmd/build.go b/internal/cmd/build.go index 896bd98cf..9e8cfc88f 100644 --- a/internal/cmd/build.go +++ b/internal/cmd/build.go @@ -13,8 +13,8 @@ import ( type ImageBuildCmd struct { Input string `arg:"" default:"." help:"Path to the project directory, Kraftfile, or Dockerfile. A directory without a Kraftfile is built from its Dockerfile."` - Output string `short:"o" help:"Output destination"` - Arch []string `help:"Only build the Kraftfile targets of these architectures. Defaults to every declared target, or x86_64 when only a runtime is declared. Required when the project declares no targets and no runtime, such as a bare Dockerfile." example:"x86_64,arm64"` + Output string `short:"o" help:"Output destination. A remote build needs an image with a tag, such as my-org/my-app:latest."` + Arch []string `help:"Only build the Kraftfile targets of these architectures. Defaults to every declared target, or x86_64 when only a runtime is declared. A local build requires it when the project declares no targets and no runtime, such as a bare Dockerfile. A remote build of such a project defaults to x86_64." example:"x86_64,arm64"` // similar to docker compose build BuildArg []string `sep:"none" help:"Set build-time variables."` @@ -24,7 +24,7 @@ type ImageBuildCmd struct { Insecure []string `help:"Allow insecure (HTTP/unverified TLS) connections to registries. Specify hostnames to restrict, or omit to apply to all." type:"optional"` - Remote *string `env:"UNIKRAFT_BUILD_URL" type:"optional" placeholder:"url" help:"Build on the build service at this URL and push the image from there, instead of building locally. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. Creates a builder with the default sizes if you have none. To set the sizes, use 'unikraft builder create'."` + Remote *string `env:"UNIKRAFT_BUILD_URL" type:"optional" placeholder:"url" help:"Build on the build service at this URL and push the image from there, instead of building locally. Defaults to the build_url of the profile, or https://controlplane.unikraft.com. Write a URL as --remote=, because the flag does not take the next argument. Creates a builder with the default sizes if you have none. To set the sizes, use 'unikraft builder create'."` Metro []string `placeholder:"metro" help:"Metros that a remote build may run in, by name or API URL. Defaults to the build service's choice."` } diff --git a/internal/cmd/build_native.go b/internal/cmd/build_native.go index d94bca511..b04ca3493 100644 --- a/internal/cmd/build_native.go +++ b/internal/cmd/build_native.go @@ -138,9 +138,9 @@ func (c *ImageBuildCmd) Run(ctx context.Context, cfg *config.Config, partition * buildOpts.SSH = ssh } - var imgs []*imagespec.Image + var built build.Built err = buildWithProgress(ctx, func(b build.Builder) (err error) { - imgs, err = b.Build(ctx, buildOpts) + built, err = b.Build(ctx, buildOpts) return err }) if errors.Is(err, build.ErrNoRuntimeTarget) { @@ -148,6 +148,8 @@ func (c *ImageBuildCmd) Run(ctx context.Context, cfg *config.Config, partition * } else if err != nil { return err } + // The packer pushes only to BuildOpts.Push, which is not set here. + imgs := built.Images defer func() { for _, img := range imgs { img.Close() diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index 9ef4afc14..98120951e 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -14,10 +14,9 @@ import ( "encoding/hex" "errors" "fmt" - "net/url" + "io/fs" "os" "path/filepath" - "slices" "strings" "time" @@ -26,6 +25,7 @@ import ( "github.com/moby/buildkit/util/progress/progressui" "github.com/tonistiigi/fsutil" buildapi "unikraft.com/cloud/sdk/build" + "unikraft.com/x/build" "unikraft.com/x/build/buildflags" "unikraft.com/x/build/progress" imagespec "unikraft.com/x/image-spec" @@ -47,7 +47,7 @@ func (c *ImageBuildCmd) runRemote(ctx context.Context, cfg *config.Config, parti if err != nil { return err } - c.Remote = new(cmp.Or(*c.Remote, profile.BuildURL, buildapi.DefaultServer)) + c.Remote = new(cmp.Or(*c.Remote, os.Getenv("UNIKRAFT_BUILD_URL"), profile.BuildURL, buildapi.DefaultServer)) secrets, err := buildflags.ParseSecretSpecs(c.Secret) if err != nil { @@ -97,25 +97,29 @@ func followRemote(ctx context.Context, client *buildapi.Client, req buildapi.Cre // A live display draws over a line logged after it starts. disp, err := progress.NewDisplay(ctx, os.Stderr, progressui.AutoMode) if err != nil { - return errors.Join(err, cancelRemote(ctx, client, b.ID)) + cancelRemote(ctx, client, b.ID) + return err } + cancel := false defer func() { if cerr := disp.Close(); err == nil { err = cerr } + if cancel { + cancelRemote(ctx, client, b.ID) + } }() if b.Session != nil { if err := client.Attach(ctx, b.ID, s); err != nil { - return errors.Join(err, cancelRemote(ctx, client, b.ID)) + cancel = true + return err } } for ev, err := range client.Logs(ctx, b.ID) { if err != nil { - if ctx.Err() != nil { - return errors.Join(err, cancelRemote(ctx, client, b.ID)) - } + cancel = true return err } if ev.SolveStatus != nil { @@ -134,11 +138,14 @@ func followRemote(ctx context.Context, client *buildapi.Client, req buildapi.Cre } // cancelRemote cancels the remote build id, also once ctx has ended, waiting at most 10 seconds. -func cancelRemote(ctx context.Context, client *buildapi.Client, id string) error { +func cancelRemote(ctx context.Context, client *buildapi.Client, id string) { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) defer cancel() - _, err := client.CancelBuild(ctx, id) - return err + if _, err := client.CancelBuild(ctx, id); err != nil { + log.G(ctx).Warn().Err(err).Str("id", id).Msg("could not cancel build, it may still run") + return + } + log.G(ctx).Info().Str("id", id).Msg("cancelled build") } // remoteRequest returns the request for a remote build of c, and the directory its session serves. @@ -148,13 +155,9 @@ func (c *ImageBuildCmd) remoteRequest(secrets []*buildflags.Secret, ssh []*build } // The service gets the profile's token, the project and its secrets. if c.Remote != nil { - u, err := url.Parse(*c.Remote) - if err != nil { + if err := checkBuildURL(*c.Remote); err != nil { return buildapi.CreateBuildRequest{}, "", err } - if u.Scheme == "http" { - return buildapi.CreateBuildRequest{}, "", fmt.Errorf("the build service %s must be https", *c.Remote) - } } if c.Output == "" { return buildapi.CreateBuildRequest{}, "", errors.New("a remote build needs --output, the image to push") @@ -172,6 +175,9 @@ func (c *ImageBuildCmd) remoteRequest(secrets []*buildflags.Secret, ssh []*build } fi, err := os.Stat(c.Input) + if errors.Is(err, fs.ErrNotExist) { + return buildapi.CreateBuildRequest{}, "", fmt.Errorf("build input %q does not exist", c.Input) + } if err != nil { return buildapi.CreateBuildRequest{}, "", err } @@ -200,8 +206,7 @@ func (c *ImageBuildCmd) remoteRequest(secrets []*buildflags.Secret, ssh []*build } switch { case name == "": // a directory without a Kraftfile builds its Dockerfile - case slices.Contains(strings.Split(name, "."), "Dockerfile"): // as x/build tells one - + case build.IsDockerfile(name): req.Contexts.Dockerfile = new(src.WithFilename(name)) default: req.Kraftfile = buildapi.KraftfileFrom(src.WithFilename(name)) @@ -213,7 +218,9 @@ func (c *ImageBuildCmd) remoteRequest(secrets []*buildflags.Secret, ssh []*build return buildapi.CreateBuildRequest{}, "", fmt.Errorf("invalid build-arg %q", arg) } if !ok { - val, _ = os.LookupEnv(key) + if val, ok = os.LookupEnv(key); !ok { + continue + } } if req.BuildArgs == nil { req.BuildArgs = map[string]string{} diff --git a/internal/cmd/build_remote_test.go b/internal/cmd/build_remote_test.go index 0a23c7d72..99b5464b6 100644 --- a/internal/cmd/build_remote_test.go +++ b/internal/cmd/build_remote_test.go @@ -23,6 +23,24 @@ import ( "unikraft.com/x/build/buildflags" ) +func TestRunRemoteBuildURL(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + require.NoError(t, os.WriteFile(path, []byte("profile: a\nprofiles:\n a: {type: cloud, token: a, build_url: http://profile.invalid}\n"), 0o600)) + cfg, err := loadConfig(path, "") + require.NoError(t, err) + + run := func(remote string) error { + cmd := ImageBuildCmd{Remote: &remote, Output: "my-org/my-app:1"} + return cmd.runRemote(t.Context(), cfg, nil) + } + + t.Setenv("UNIKRAFT_BUILD_URL", "") + require.ErrorContains(t, run(""), "http://profile.invalid") + t.Setenv("UNIKRAFT_BUILD_URL", "http://env.invalid") + require.ErrorContains(t, run(""), "http://env.invalid") + require.ErrorContains(t, run("http://flag.invalid"), "http://flag.invalid") +} + func TestRemoteRequest(t *testing.T) { t.Parallel() @@ -45,7 +63,7 @@ func TestRemoteRequest(t *testing.T) { cmd: ImageBuildCmd{ Output: "my-org/my-app:latest", Arch: []string{"arm64"}, - BuildArg: []string{"VERSION=1.2.3"}, + BuildArg: []string{"VERSION=1.2.3", "NOT_IN_THE_ENVIRONMENT"}, NoCache: true, Secret: []string{"id=npm,src=/home/me/.npmrc"}, SSH: []string{"default"}, @@ -74,6 +92,20 @@ func TestRemoteRequest(t *testing.T) { "output": [{"image": "ghcr.io/acme/app:1"}] }`, }, + "a Containerfile is built as a Dockerfile": { + files: []string{"Containerfile"}, + input: "Containerfile", + cmd: ImageBuildCmd{Output: "ghcr.io/acme/app:1"}, + want: `{ + "contexts": { + "context": {"session": "context"}, + "dockerfile": {"session": "context", "filename": "Containerfile"} + }, + "no_cache": false, + "registries": {"*": {"session": true}}, + "output": [{"image": "ghcr.io/acme/app:1"}] + }`, + }, "a Dockerfile is built from its directory": { files: []string{"app.Dockerfile"}, input: "app.Dockerfile", @@ -122,6 +154,14 @@ func TestRemoteRequest(t *testing.T) { require.Error(t, err) }) } + + t.Run("names a missing input", func(t *testing.T) { + t.Parallel() + + cmd := ImageBuildCmd{Input: filepath.Join(t.TempDir(), "missing"), Output: "my-org/my-app:1"} + _, _, err := cmd.remoteRequest(nil, nil) + require.EqualError(t, err, fmt.Sprintf("build input %q does not exist", cmd.Input)) + }) } func TestFollowRemoteCancelsARefusedSession(t *testing.T) { @@ -156,3 +196,36 @@ func TestFollowRemoteCancelsARefusedSession(t *testing.T) { assert.Equal(t, buildapi.ErrorCodeInvalid, apiErr.Code) assert.Len(t, cancelled, 1) } + +func TestFollowRemoteCancelsALostProgressStream(t *testing.T) { + t.Parallel() + + cancelled := make(chan struct{}, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/v1/builds": + w.WriteHeader(http.StatusCreated) + fmt.Fprint(w, `{"id": "b1", "status": "waiting"}`) + case "/v1/builds/b1/logs": + w.WriteHeader(http.StatusForbidden) + fmt.Fprint(w, `{"error": {"code": "forbidden", "message": "no access"}}`) + case "/v1/builds/b1/cancel": + cancelled <- struct{}{} + w.WriteHeader(http.StatusAccepted) + fmt.Fprint(w, `{"id": "b1", "status": "waiting"}`) + } + })) + t.Cleanup(srv.Close) + + client, err := buildapi.New(srv.URL) + require.NoError(t, err) + s, err := session.NewSession(t.Context(), "") + require.NoError(t, err) + + err = followRemote(t.Context(), client, buildapi.CreateBuildRequest{}, s) + var apiErr *buildapi.APIError + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, http.StatusForbidden, apiErr.StatusCode) + assert.Len(t, cancelled, 1) +} diff --git a/internal/cmd/builder.go b/internal/cmd/builder.go index 9bc6c0fb6..5fb0cc662 100644 --- a/internal/cmd/builder.go +++ b/internal/cmd/builder.go @@ -10,7 +10,9 @@ import ( "context" "errors" "fmt" + "net/url" + "github.com/MakeNowJust/heredoc" "github.com/docker/go-units" buildapi "unikraft.com/cloud/sdk/build" "unikraft.com/x/kingkong" @@ -38,10 +40,11 @@ type BuilderCmd struct { // Builder is a builder of the build service, and the builds the service runs on it. type Builder struct { Name string `mirror:"status.name" field:",short" help:"Name of the builder."` + Metro string `field:",short" help:"Metro the builder runs in."` IsDefault bool `mirror:"status.default" field:"default,short" help:"Whether builds that name no builder run on it."` Running int `mirror:"status.builds.#" field:",short" help:"Number of builds running on the builder."` - Waiting int32 `mirror:"status.waiting_builds" field:",short" help:"Number of builds waiting for the builder, or for any builder of the pool for default."` - MaxBuilds int32 `mirror:"status.max_builds" field:",short" help:"Number of builds that run on the builder at once."` + Waiting int32 `mirror:"status.waiting_builds" field:",short" help:"Number of builds that have not started: waiting for a build slot or for their client's session."` + MaxBuilds int32 `mirror:"status.max_builds" field:",short" help:"Number of builds that each replica of the build service runs on the builder at once."` Images []string `field:",long" help:"Images that the running builds push."` Instance Link[Instance] `mirror:"status.instance" field:",long" help:"Instance the builder runs as, for its image, sizes and state."` @@ -72,11 +75,12 @@ func (Builder) Get(ctx context.Context, keys []string) ([]model.Model, error) { if err != nil { return nil, err } + metro, _ := ctx.Value(builderMetroKey{}).(string) var results []model.Model for _, name := range keys { - s, err := client.GetBuilder(ctx, name, buildapi.GetBuilderOptions{}) + s, err := client.GetBuilder(ctx, name, buildapi.GetBuilderOptions{Metro: builderMetro(metro)}) if err != nil { - return results, builderError(err, name) + return results, builderError(err, name, metro) } b, err := builderOf(profile, *s) if err != nil { @@ -120,9 +124,10 @@ func (Builder) Delete(ctx context.Context, keys []string) error { if err != nil { return err } + metro, _ := ctx.Value(builderMetroKey{}).(string) for _, name := range keys { - if err := client.DeleteBuilder(ctx, name, buildapi.DeleteBuilderOptions{}); err != nil { - return builderError(err, name) + if err := client.DeleteBuilder(ctx, name, buildapi.DeleteBuilderOptions{Metro: builderMetro(metro)}); err != nil { + return builderError(err, name, metro) } } return nil @@ -157,9 +162,11 @@ func builderOf(profile *config.Profile, s buildapi.BuilderStatus) (Builder, erro if err := mirror.Mirror(b, &b); err != nil { return Builder{}, fmt.Errorf("could not mirror builder data: %w", err) } + b.Metro = s.Instance.Metro for _, metro := range profile.Metros { if metro.Endpoint == s.Instance.Metro { b.Instance.Metro = metro.Name + b.Metro = metro.Name } } for _, build := range s.Builds { @@ -175,18 +182,40 @@ func builderOf(profile *config.Profile, s buildapi.BuilderStatus) (Builder, erro // builderRemoteKey holds the URL of the build service for the methods of Builder. type builderRemoteKey struct{} +type builderMetroKey struct{} + +func builderMetro(metro string) *string { + if metro == "" { + return nil + } + return &metro +} + type BuilderGetCmd struct { cmd.ModelGetCmd[Builder] - Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile."` + Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com."` + Metro string `placeholder:"metro" help:"Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in."` } func (c *BuilderGetCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { - return c.ModelGetCmd.Run(context.WithValue(ctx, builderRemoteKey{}, c.Remote), stdio, nil) + ctx = context.WithValue(ctx, builderRemoteKey{}, c.Remote) + return c.ModelGetCmd.Run(context.WithValue(ctx, builderMetroKey{}, c.Metro), stdio, nil) } type BuilderListCmd struct { cmd.ModelListCmd[Builder] - Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builders. Defaults to the build_url of the profile."` + Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builders. Defaults to the build_url of the profile, or https://controlplane.unikraft.com."` +} + +func (BuilderListCmd) Help() string { + return heredoc.Doc(` + List builders. + + Each replica of the build service runs up to max-builds builds on a + builder at once, so running can be higher than max-builds. Waiting + counts the builds that have not started: those that wait for a build + slot and those that wait for their client's session. + `) } func (c *BuilderListCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { @@ -195,11 +224,13 @@ func (c *BuilderListCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { type BuilderDeleteCmd struct { cmd.ModelRemoveCmd[Builder] - Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile."` + Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com."` + Metro string `placeholder:"metro" help:"Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in."` } func (c *BuilderDeleteCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { - return c.ModelRemoveCmd.Run(context.WithValue(ctx, builderRemoteKey{}, c.Remote), stdio, nil) + ctx = context.WithValue(ctx, builderRemoteKey{}, c.Remote) + return c.ModelRemoveCmd.Run(context.WithValue(ctx, builderMetroKey{}, c.Metro), stdio, nil) } type BuilderCreateCmd struct { @@ -207,7 +238,8 @@ type BuilderCreateCmd struct { VCPUs int32 `name:"vcpus" placeholder:"n" help:"Number of vCPUs of the builder, within the range the plan allows. Defaults to the build service's."` Memory types.SizeMebibytes `placeholder:"size" help:"Memory of the builder, within the range the plan allows. Defaults to the build service's."` Cache types.SizeMebibytes `placeholder:"size" help:"Size of the builder's cache volume. Defaults to the build service's."` - Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile."` + Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com."` + Metro string `placeholder:"metro" help:"Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in."` } func (BuilderCreateCmd) Examples() []kingkong.Example { @@ -221,7 +253,8 @@ func (BuilderCreateCmd) Examples() []kingkong.Example { type BuilderDuCmd struct { Name string `arg:"" optional:"" default:"default" help:"Name of the builder."` - Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile."` + Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com."` + Metro string `placeholder:"metro" help:"Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in."` } func (BuilderDuCmd) Examples() []kingkong.Example { @@ -235,7 +268,8 @@ func (BuilderDuCmd) Examples() []kingkong.Example { type BuilderPruneCmd struct { Name string `arg:"" optional:"" default:"default" help:"Name of the builder."` - Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile."` + Remote string `env:"UNIKRAFT_BUILD_URL" placeholder:"url" help:"URL of the build service that manages the builder. Defaults to the build_url of the profile, or https://controlplane.unikraft.com."` + Metro string `placeholder:"metro" help:"Metro of the builder, by name or API URL. Defaults to the first metro that your builds may run in."` } func (BuilderPruneCmd) Examples() []kingkong.Example { @@ -262,7 +296,7 @@ func (c *BuilderCreateCmd) Run(ctx context.Context, cfg *config.Config) error { if c.Cache != 0 { b.CacheMb = new(int64(c.Cache)) } - if _, err := client.CreateBuilder(ctx, b, buildapi.CreateBuilderOptions{}); err != nil { + if _, err := client.CreateBuilder(ctx, b, buildapi.CreateBuilderOptions{Metro: builderMetro(c.Metro)}); err != nil { return err } log.G(ctx).Info().Str("name", c.Name).Msg("builder ready") @@ -274,9 +308,9 @@ func (c *BuilderDuCmd) Run(ctx context.Context, cfg *config.Config, stdio xstdio if err != nil { return err } - u, err := client.GetBuilderUsage(ctx, c.Name, buildapi.GetBuilderUsageOptions{}) + u, err := client.GetBuilderUsage(ctx, c.Name, buildapi.GetBuilderUsageOptions{Metro: builderMetro(c.Metro)}) if err != nil { - return builderError(err, c.Name) + return builderError(err, c.Name, c.Metro) } _, err = fmt.Fprintf(stdio.Stdout, "Reclaimable: %s\nTotal: %s\n", units.BytesSize(float64(u.ReclaimableBytes)), units.BytesSize(float64(u.TotalBytes))) return err @@ -287,9 +321,9 @@ func (c *BuilderPruneCmd) Run(ctx context.Context, cfg *config.Config) error { if err != nil { return err } - resp, err := client.PruneBuilder(ctx, c.Name, buildapi.PruneBuilderOptions{}) + resp, err := client.PruneBuilder(ctx, c.Name, buildapi.PruneBuilderOptions{Metro: builderMetro(c.Metro)}) if err != nil { - return builderError(err, c.Name) + return builderError(err, c.Name, c.Metro) } log.G(ctx).Info().Str("freed", units.BytesSize(float64(resp.FreedBytes))).Msg("pruned the builder's cache") return nil @@ -301,13 +335,24 @@ func builderClient(cfg *config.Config, url string) (*buildapi.Client, error) { if err != nil { return nil, err } - url = cmp.Or(url, profile.BuildURL) - if url == "" { - return nil, fmt.Errorf("no build service: set build_url in profile %s, or pass --remote", profile.Name) + url = cmp.Or(url, profile.BuildURL, buildapi.DefaultServer) + if err := checkBuildURL(url); err != nil { + return nil, err } return buildapi.New(url, buildapi.WithToken(profile.Token)) } +func checkBuildURL(remote string) error { + u, err := url.Parse(remote) + if err != nil { + return err + } + if u.Scheme == "http" { + return fmt.Errorf("the build service %s must be https", remote) + } + return nil +} + // builderClientOf returns the client of the build service in ctx, and the current profile. func builderClientOf(ctx context.Context) (*buildapi.Client, *config.Profile, error) { cfg := config.G(ctx) @@ -321,8 +366,11 @@ func builderClientOf(ctx context.Context) (*buildapi.Client, *config.Profile, er } // builderError tells how to create the named builder when the service has none. -func builderError(err error, name string) error { +func builderError(err error, name, metro string) error { if apiErr, ok := errors.AsType[*buildapi.APIError](err); ok && apiErr.Code == buildapi.ErrorCodeNotFound { + if metro != "" { + return fmt.Errorf("there is no builder %s in metro %s: create it with unikraft builder create %s --metro %s", name, metro, name, metro) + } return fmt.Errorf("there is no builder %s: create it with unikraft builder create %s", name, name) } return err diff --git a/internal/cmd/builder_test.go b/internal/cmd/builder_test.go index 5d0aa6963..63b1f28be 100644 --- a/internal/cmd/builder_test.go +++ b/internal/cmd/builder_test.go @@ -7,14 +7,10 @@ package cmd import ( "context" - "fmt" - "net/http" - "net/http/httptest" "os" "path/filepath" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "unikraft.com/cli/internal/config" @@ -23,19 +19,9 @@ import ( func TestBuilderBuildURL(t *testing.T) { t.Parallel() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{"builders": [{"name": "default", "default": true}]}`) - })) - t.Cleanup(srv.Close) - list := func(buildURL, remote string) error { - profile := "{type: cloud, token: a}" - if buildURL != "" { - profile = "{type: cloud, token: a, build_url: " + buildURL + "}" - } path := filepath.Join(t.TempDir(), "config.yaml") - require.NoError(t, os.WriteFile(path, []byte("profile: a\nprofiles:\n a: "+profile+"\n"), 0o600)) + require.NoError(t, os.WriteFile(path, []byte("profile: a\nprofiles:\n a: {type: cloud, token: a, build_url: "+buildURL+"}\n"), 0o600)) cfg, err := loadConfig(path, "") require.NoError(t, err) ctx := context.WithValue(config.WithConfig(t.Context(), cfg), builderRemoteKey{}, remote) @@ -43,7 +29,6 @@ func TestBuilderBuildURL(t *testing.T) { return err } - assert.NoError(t, list(srv.URL, "")) - assert.NoError(t, list("http://127.0.0.1:1", srv.URL)) - assert.ErrorContains(t, list("", ""), "set build_url in profile a, or pass --remote") + require.ErrorContains(t, list("http://profile.invalid", ""), "the build service http://profile.invalid must be https") + require.ErrorContains(t, list("http://profile.invalid", "http://flag.invalid"), "the build service http://flag.invalid must be https") } diff --git a/internal/cmd/images.go b/internal/cmd/images.go index 2762620e7..cc3ed0c24 100644 --- a/internal/cmd/images.go +++ b/internal/cmd/images.go @@ -143,7 +143,7 @@ func (Image) Get(ctx context.Context, keys []string) ([]model.Model, error) { eg := joinerrgroup.Group{} for i, key := range keys { eg.Go(func() error { - src, err := imagespec.GuessLocation(key) + src, err := imageLocation(ctx, key) if err != nil { return fmt.Errorf("parsing image reference %q: %w", key, err) } @@ -212,7 +212,7 @@ func (Image) Delete(ctx context.Context, keys []string) error { eg := joinerrgroup.Group{} for i, key := range keys { eg.Go(func() error { - uri, err := imagespec.GuessLocation(key) + uri, err := imageLocation(ctx, key) if err != nil { return fmt.Errorf("parsing image reference %q: %w", key, err) } @@ -230,6 +230,20 @@ func (Image) Delete(ctx context.Context, keys []string) error { return errors.Join(eg.Wait(), imagesNotFound(keys, missing)) } +// imageLocation parses key as GuessLocation does. A hosted server takes only +// registry references: the other locations are its own files, or addresses +// that the caller picks. It does not look at its files to tell them apart. +func imageLocation(ctx context.Context, key string) (*imagespec.Location, error) { + if !hosted(ctx) { + return imagespec.GuessLocation(key) + } + src, err := imagespec.ParseLocationDefault(key) + if err == nil && src.Scheme != schemes.OCI { + err = fmt.Errorf("the server takes only registry references, not %s", src.Scheme) + } + return src, err +} + // imagesNotFound returns one not-found error for every missing key, so that // errors.As sees all of them rather than only the first. func imagesNotFound(keys []string, missing []bool) error { diff --git a/internal/cmd/images_internal_test.go b/internal/cmd/images_internal_test.go index 7a5284d33..9a1dcf5ad 100644 --- a/internal/cmd/images_internal_test.go +++ b/internal/cmd/images_internal_test.go @@ -27,3 +27,12 @@ func TestImagesNotFound(t *testing.T) { } assert.Equal(t, []string{"a", "c"}, keys) } + +func TestImageDeleteOfAHostedServerKeepsItsFiles(t *testing.T) { + dir := t.TempDir() + + err := Image{}.Delete(WithHosted(t.Context()), []string{"oci-layout://" + dir}) + + require.ErrorContains(t, err, "only registry references") + assert.DirExists(t, dir) +} diff --git a/internal/cmd/instance_checkpoints.go b/internal/cmd/instance_checkpoints.go index 1c26f4e06..580ea49cc 100644 --- a/internal/cmd/instance_checkpoints.go +++ b/internal/cmd/instance_checkpoints.go @@ -10,7 +10,6 @@ import ( "context" "errors" "fmt" - "io" "unikraft.com/cloud/sdk/platform" "unikraft.com/cloud/sdk/platform/group" @@ -37,7 +36,7 @@ type InstanceCheckpointsCmd struct { Create cmd.ModelCreateCmd[InstanceCheckpoint] `cmd:"" help:"Create a checkpoint from an instance."` Edit cmd.ModelEditCmd[InstanceCheckpoint] `cmd:"" help:"Edit an instance checkpoint."` - History InstanceCheckpointHistoryCmd `cmd:"" help:"Show the history of a checkpoint."` + History InstanceCheckpointHistoryCmd `cmd:"" help:"Show the lineage of a checkpoint."` } type InstanceCheckpoint struct { @@ -478,117 +477,31 @@ func (InstanceCheckpoint) Examples() map[cmd.CmdType][]kingkong.Example { } } -// InstanceHistoryEntry represents a single checkpoint in the history of an -// instance or checkpoint. It models one row of history output as a resource so -// that it can be rendered through the standard printer framework. -type InstanceHistoryEntry struct { - Metro LinkName[Metro] `field:"metro,short" json:"metro" help:"Metro the checkpoint is in."` - Target string `field:",short" json:"target" help:"Instance or checkpoint the history was requested for."` - Name string `field:",short" json:"name" help:"Checkpoint name."` - UUID string `field:",long" json:"uuid" help:"Unique identifier assigned at creation."` - Created types.RelativeTime `field:"created,short" json:"created" help:"Creation time."` - - key multimetro.Key -} - -func (InstanceHistoryEntry) Type() model.Type { - return model.Type{ - Name: "instance-history-entry", - Names: "instance-history-entries", - } -} - -func (i InstanceHistoryEntry) Key() model.Key { - return i.key -} - -func (i InstanceHistoryEntry) Raw() any { - return i -} - -func (i InstanceHistoryEntry) Fields(ctx context.Context) ([]model.Field, error) { - return model.FieldsFromStruct(i) -} - -// getInstanceHistory fetches checkpoint history entries for the given targets -// using the provided fetch function (either the instance or checkpoint history -// endpoint) and flattens them into InstanceHistoryEntry rows. -func getInstanceHistory(ctx context.Context, targets []string, fetch func(ctx context.Context, c multimetro.MetroClient, ids []platform.NameOrUUID) (*platform.Response[platform.GetCheckpointHistoryResponseData], error)) ([]model.Model, error) { - keys := multimetro.ParseKeys(targets) - - g, err := multimetro.NewClient(ctx) - if err != nil { - return nil, err - } - - return group.CollectRefsSlices(ctx, g, keys.Refs(), func(ctx context.Context, c multimetro.MetroClient, refs group.Refs) ([]model.Model, group.Refs, error) { - log.G(ctx).Trace().Msg("getting checkpoint history") - resp, err := fetch(ctx, c, refs.NameOrUUIDs()) - if err != nil && !platform.ErrorContainsOnly(err, platform.APIHTTPErrorNotFound) { - return nil, nil, err - } - var found []group.Ref - var results []model.Model - if resp == nil || resp.Data == nil { - return nil, nil, nil - } - for _, inst := range resp.Data.Instances { - if inst.Status == nil || *inst.Status != platform.ResponseStatusSuccess { - continue - } - found = append(found, group.Ref{ - Metro: c.Metro.Name, - Name: inst.Name, - UUID: inst.Uuid, - }) - target := multimetro.Key{Metro: c.Metro.Name, Name: inst.Name, UUID: inst.Uuid} - for _, entry := range inst.History { - results = append(results, InstanceHistoryEntry{ - Metro: LinkName[Metro](c.Metro.Name), - Target: target.String(), - Name: entry.Name, - UUID: entry.Uuid, - Created: types.RelativeTime(entry.CreatedAt), - key: multimetro.Key{Metro: c.Metro.Name, Name: entry.Name, UUID: entry.Uuid}, - }) - } - } - return results, found, nil - }) -} +// InstanceCheckpointHistoryCmd shows the lineage of a checkpoint. +type InstanceCheckpointHistoryCmd struct { + Targets []string `arg:"" name:"target" completion-predictor:"resource-key-instance-checkpoint" help:"Target checkpoints to show the lineage of."` -// renderInstanceHistory prints history entries through the printer framework. -func renderInstanceHistory(ctx context.Context, out io.Writer, opts cmd.FormatOpts, entries []model.Model) error { - return opts.Output. - WithDefault(cmd.PrinterTypeTable). - Print(ctx, out, opts.Field, InstanceHistoryEntry{}, entries...) + InstanceHistoryOpts } -// InstanceCheckpointHistoryCmd shows the checkpoint history for a checkpoint. -type InstanceCheckpointHistoryCmd struct { - Targets []string `arg:"" name:"target" completion-predictor:"resource-key-instance-checkpoint" help:"Target checkpoints to show history for."` - - cmd.FormatOpts +func (cmd InstanceCheckpointHistoryCmd) Help() string { + return "Show the whole lineage tree of a checkpoint: every instance, template and checkpoint in it." + lineageHelp } func (cmd InstanceCheckpointHistoryCmd) Examples() []kingkong.Example { return []kingkong.Example{ { - Description: "Show the history of a checkpoint", + Description: "Show the lineage of a checkpoint", Commands: []string{"unikraft instance checkpoint history my-checkpoint"}, }, + { + Description: "Show the lineage with the UUID of each node", + Commands: []string{"unikraft instance checkpoint history my-checkpoint -f +uuid"}, + }, } } func (c *InstanceCheckpointHistoryCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { - entries, err := getInstanceHistory(ctx, c.Targets, func(ctx context.Context, mc multimetro.MetroClient, ids []platform.NameOrUUID) (*platform.Response[platform.GetCheckpointHistoryResponseData], error) { - return mc.GetCheckpointHistory(ctx, ids, platform.GetCheckpointHistoryOpts{}) - }) - if err != nil && len(entries) == 0 { - return err - } - if printErr := renderInstanceHistory(ctx, stdio.Stdout, c.FormatOpts, entries); printErr != nil { - return errors.Join(err, printErr) - } - return err + found, err := InstanceCheckpoint{}.Get(ctx, c.Targets) + return runInstanceHistory(ctx, stdio, c.InstanceHistoryOpts, c.Targets, found, err) } diff --git a/internal/cmd/instance_templates.go b/internal/cmd/instance_templates.go index d980bbe54..e7a811d0e 100644 --- a/internal/cmd/instance_templates.go +++ b/internal/cmd/instance_templates.go @@ -24,6 +24,7 @@ import ( "unikraft.com/cli/internal/types" "unikraft.com/cli/pkg/model" "unikraft.com/cli/pkg/model/cmd" + xstdio "unikraft.com/x/stdio" ) type InstanceTemplatesCmd struct { @@ -32,8 +33,9 @@ type InstanceTemplatesCmd struct { cmd.ListableModelCmd[InstanceTemplate] cmd.BulkDeletableModelCmd[InstanceTemplate] - Create cmd.ModelCreateCmd[InstanceTemplate] `cmd:"" help:"Create an instance template."` - Edit cmd.ModelEditCmd[InstanceTemplate] `cmd:"" help:"Edit an instance template."` + Create cmd.ModelCreateCmd[InstanceTemplate] `cmd:"" help:"Create an instance template."` + Edit cmd.ModelEditCmd[InstanceTemplate] `cmd:"" help:"Edit an instance template."` + History InstanceTemplateHistoryCmd `cmd:"" help:"Show the lineage of an instance template."` } type InstanceTemplate struct { @@ -48,9 +50,11 @@ type InstanceTemplate struct { Autokill Autokill `field:",embed" mirror:"instance.template_autokill" create:"set" edit:"set" flag:"autokill" help:"Autokill options.\n time: time since the template was last cloned before it is deleted, such as 24h, 0 disables" placeholder:"=" example:"time=24h"` - State types.InstanceState `mirror:"instance.state" field:",short" help:"Lifecycle state: stopped, starting, running, draining (finishing requests before a stop), stopping, standby (scaled to zero, woken by traffic), template, checkpoint or deleted."` - Image types.ImageRef `mirror:"instance.image" field:",short" help:"Image of the template, as an OCI reference or a full registry URL."` - Type_ *platform.InstanceType `mirror:"instance.type" field:"type,long" help:"Virtual machine type.\n micro: Firecracker microVM (default)\n full: QEMU virtual machine with GPU support, needs a plan with full VM support and has no branching, checkpoints, vertical scaling, annotations or virtiofs volumes"` + State types.InstanceState `mirror:"instance.state" field:",short" help:"Lifecycle state: stopped, starting, running, draining (finishing requests before a stop), stopping, standby (scaled to zero, woken by traffic), template, checkpoint or deleted."` + Image types.ImageRef `mirror:"instance.image" field:",short" edit:"set" flag:"image" help:"Image of the template, as an OCI reference or a full registry URL." placeholder:":" example:"nginx:latest,my-app:v1.2.3"` + PullPolicy *platform.PullPolicy `mirror:"-" field:"pull-policy,invisible,valueless" edit:"set" flag:"pull-policy" help:"When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same edit. Each image edit replaces the pull policy and headers, so set both again." placeholder:"policy" example:"always,if_not_present,never"` + ImageHeaders map[string]string `mirror:"-" field:"image-headers,invisible,valueless" edit:"set" flag:"image-header" sep:"none" mapsep:"none" help:"HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same edit. Each image edit replaces the pull policy and headers, so set both again." placeholder:"=" example:"Authorization=Bearer "` + Type_ *platform.InstanceType `mirror:"instance.type" field:"type,long" help:"Virtual machine type.\n micro: Firecracker microVM (default)\n full: QEMU virtual machine with GPU support, needs a plan with full VM support and has no branching, checkpoints, vertical scaling, annotations or virtiofs volumes"` Runtime struct { Args InstanceArgs `mirror:"instance.args" field:",short" help:"Command-line arguments passed to the instance at start."` @@ -251,6 +255,10 @@ func (InstanceTemplate) Edit(ctx context.Context, key string, fields []model.Fie if err != nil { return err } + patches, err = setImageOptions(fields, platform.MutableTemplateInstancePropertyImage, patches) + if err != nil { + return err + } g, err := multimetro.NewClient(ctx) if err != nil { @@ -290,6 +298,12 @@ func instanceTemplatePatchSpec(path string, op patchOp, value any) (platform.Mut switch path { case "tags": return platform.MutableTemplateInstancePropertyTags, value.([]string), nil + case "image": + ref := value.(types.ImageRef) + if ref.Reference().IsZero() { + return zero, nil, fmt.Errorf("image cannot be empty") + } + return platform.MutableTemplateInstancePropertyImage, ref.String(), nil case "autokill": autokill := value.(Autokill) req := map[string]any{} @@ -468,6 +482,12 @@ func (InstanceTemplate) Examples() map[cmd.CmdType][]kingkong.Example { "unikraft instance template edit demo-template --set tags=env-dev", }, }, + { + Description: "Change the template image and always pull it", + Commands: []string{ + "unikraft instance template edit demo-template --image my-app:v2 --pull-policy always", + }, + }, }, cmd.CmdTypeDelete: { { @@ -477,3 +497,32 @@ func (InstanceTemplate) Examples() map[cmd.CmdType][]kingkong.Example { }, } } + +// InstanceTemplateHistoryCmd shows the lineage of an instance template. +type InstanceTemplateHistoryCmd struct { + Targets []string `arg:"" name:"target" completion-predictor:"resource-key-instance-template" help:"Target templates to show the lineage of."` + + InstanceHistoryOpts +} + +func (cmd InstanceTemplateHistoryCmd) Help() string { + return "Show the whole lineage tree of an instance template: every instance, template and checkpoint in it." + lineageHelp +} + +func (cmd InstanceTemplateHistoryCmd) Examples() []kingkong.Example { + return []kingkong.Example{ + { + Description: "Show the lineage of a template", + Commands: []string{"unikraft instance template history my-template"}, + }, + { + Description: "Show the lineage with the UUID of each node", + Commands: []string{"unikraft instance template history my-template -f +uuid"}, + }, + } +} + +func (c *InstanceTemplateHistoryCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { + found, err := InstanceTemplate{}.Get(ctx, c.Targets) + return runInstanceHistory(ctx, stdio, c.InstanceHistoryOpts, c.Targets, found, err) +} diff --git a/internal/cmd/instances.go b/internal/cmd/instances.go index 2da4b35bb..f6ab25ae9 100644 --- a/internal/cmd/instances.go +++ b/internal/cmd/instances.go @@ -60,7 +60,7 @@ type InstancesCmd struct { Suspend InstancesSuspendCmd `cmd:"" help:"Suspend one or more instances."` Restart InstancesRestartCmd `cmd:"" help:"Restart one or more instances."` Tunnel InstancesTunnelCmd `cmd:"" aliases:"port-forward" help:"Forward a local port to an unexposed instance."` - History InstanceHistoryCmd `cmd:"" help:"Show checkpoint history for an instance."` + History InstanceHistoryCmd `cmd:"" help:"Show the lineage of an instance."` Shell ShellSandboxInstanceCmd `cmd:"" aliases:"sh" help:"Open an interactive shell on a sandbox instance."` Exec ExecSandboxInstanceCmd `cmd:"" help:"Execute a command on a sandbox instance."` @@ -116,9 +116,10 @@ type Instance struct { State types.InstanceState `mirror:"instance.state" field:",short" edit:"set" help:"Lifecycle state: stopped, starting, running, draining (finishing requests before a stop), stopping, standby (scaled to zero, woken by traffic), template, checkpoint or deleted. Setting stopped on edit stops a running instance." example:"stopped"` - Image types.ImageRef `mirror:"instance.image" field:",short" create:"set" edit:"set" flag:"image" help:"Image to deploy, as an OCI reference or a full registry URL. On create, required unless template, branch or checkpoint is given, and cannot be combined with them." placeholder:":" example:"nginx:latest,my-app:v1.2.3"` - PullPolicy *platform.PullPolicy `field:"pull-policy,invisible,valueless" create:"set" flag:"pull-policy" help:"When to pull the image relative to the node's cache: always, if_not_present or never." placeholder:"policy" example:"always,if_not_present,never"` - Type_ *platform.InstanceType `mirror:"instance.type" field:"type,long" create:"set" flag:"type" help:"Virtual machine type.\n micro: Firecracker microVM (default)\n full: QEMU virtual machine with GPU support, needs a plan with full VM support and has no branching, checkpoints, vertical scaling, annotations or virtiofs volumes" placeholder:"type" example:"micro,full"` + Image types.ImageRef `mirror:"instance.image" field:",short" create:"set" edit:"set" flag:"image" help:"Image to deploy, as an OCI reference or a full registry URL. On create, required unless template, branch or checkpoint is given, and cannot be combined with them." placeholder:":" example:"nginx:latest,my-app:v1.2.3"` + PullPolicy *platform.PullPolicy `mirror:"-" field:"pull-policy,invisible,valueless" create:"set" edit:"set" flag:"pull-policy" help:"When to pull the image relative to the node's cache: always, if_not_present or never. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again." placeholder:"policy" example:"always,if_not_present,never"` + ImageHeaders map[string]string `mirror:"-" field:"image-headers,invisible,valueless" create:"set" edit:"set" flag:"image-header" sep:"none" mapsep:"none" help:"HTTP header sent when fetching the image, as KEY=value, up to 16. Needs image in the same create or edit. Each image edit replaces the pull policy and headers, so set both again." placeholder:"=" example:"Authorization=Bearer "` + Type_ *platform.InstanceType `mirror:"instance.type" field:"type,long" create:"set" flag:"type" help:"Virtual machine type.\n micro: Firecracker microVM (default)\n full: QEMU virtual machine with GPU support, needs a plan with full VM support and has no branching, checkpoints, vertical scaling, annotations or virtiofs volumes" placeholder:"type" example:"micro,full"` Runtime struct { Args InstanceArgs `mirror:"instance.args" field:",short" create:"set" edit:"set" flag:"args" help:"Command-line arguments passed to the instance at start." placeholder:"arg" example:"--port=8080"` @@ -133,8 +134,8 @@ type Instance struct { Service *InstanceService `mirror:"instance.service_group" field:",embed" create:"set" flag:"service" help:"Service group to join, by name or UUID. Leave unset and give service.services or service.domains to create a group owned by the instance. Without any service the instance is reachable only privately." placeholder:"name"` Volumes []*InstanceVolume `mirror:"instance.volumes" field:",embed" create:"set" edit:"add,del=strings" flag:"volume" short:"v" sep:"none" help:"Volume to attach as NAME:/MOUNT[:ro], where the mount path is absolute and outside /uk. On create, leave NAME empty and add :size=SIZE, as in :/data:size=1GiB, to make a new volume with a generated name." placeholder:"[]:[:]" example:"my-vol:/data,cache:/tmp:ro,:/data:size=1GiB"` - Roms []*InstanceRom `mirror:"instance.roms" field:",embed" create:"set" edit:"set,add,del=strings" flag:"rom" sep:"none" help:"Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest." placeholder:"name=,image=,at=" example:"name=my-rom\\,image=myuser/my-rom:latest\\,at=/rom0,name=mydata\\,dir=./mydata\\,at=/rom"` - Plugins []*InstancePlugin `mirror:"instance.plugins" field:",embed" create:"set" edit:"set,add,del=strings" flag:"plugin" sep:"none" help:"Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance." placeholder:"name=,image=[,config=]" example:"name=sandbox\\,image=plugins/sandbox:latest,name=sandbox\\,image=plugins/sandbox:latest\\,config={\"persist_path\":\"/data\"}"` + Roms []*InstanceRom `mirror:"instance.roms" field:",embed" create:"set" edit:"set,add,del=strings" flag:"rom" sep:"none" help:"Read-only ROM device from an image or a local directory. The name uses letters, digits, - and _, and appears as /dev/ukp_rom_NAME in the guest. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={\"KEY\":\"a,b\"}." placeholder:"name=,image=[,pull-policy=][,headers.=],at=" example:"name=my-rom\\,image=myuser/my-rom:latest\\,at=/rom0,name=mydata\\,dir=./mydata\\,at=/rom"` + Plugins []*InstancePlugin `mirror:"instance.plugins" field:",embed" create:"set" edit:"set,add,del=strings" flag:"plugin" sep:"none" help:"Plugin loaded from an image, with an optional JSON config passed to it on start. Up to 8 per instance. Add pull-policy=always|if_not_present|never to control when the image is pulled. Add headers.KEY=value for each HTTP header sent when fetching the image; for a value with a comma, use headers={\"KEY\":\"a,b\"}." placeholder:"name=,image=[,pull-policy=][,headers.=][,config=]" example:"name=sandbox\\,image=plugins/sandbox:latest,name=sandbox\\,image=plugins/sandbox:latest\\,config={\"persist_path\":\"/data\"}"` PrivateFQDN string `mirror:"instance.private_fqdn" field:"private-fqdn,long" help:"Private hostname, reachable only from your other instances in the metro."` Networks []*InstanceNetwork `mirror:"instance.network_interfaces" field:",embed" create:"set" flag:"network" sep:"none" help:"Network interface to attach, one per flag and up to 4. The first one is the primary interface. Needs the net_manager permission.\n name: interface name, unique in the account. Set it on a relay, so that other instances can refer to it. While its clients run, the relay instance stops only with --force and cannot be deleted\n relay.name: name of the interface, not of the instance, that gets all the traffic of this one. It must be a platform interface of another instance, with no relay of its own\n relay.uuid: the same, by UUID\n relay.dns: false sends DNS requests to the platform's DNS server instead of the relay (default true)\n tap-name: host TAP device, to bring your own interface\n ip: address in CIDR notation, needs tap-name\n mac: unicast MAC address, needs tap-name\n autoconfig: whether the platform configures the interface inside the guest" placeholder:"=" example:"name=my-relay,relay.name=my-relay,relay.name=my-relay\\,relay.dns=false,name=my-vpc\\,tap-name=tap0\\,ip=10.0.0.5/24"` @@ -259,7 +260,7 @@ type InstanceGpu struct { type InstanceService struct { Link[ServiceGroup] - Services []*Service `mirror:"services" json:"services,omitempty" field:",invisible,valueless" create:"set" flag:"publish" short:"p" sep:"none" help:"Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only.\n http: load balance per HTTP request instead of per TCP connection\n tls: terminate TLS at the platform\n redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect" placeholder:":[/]" example:"443:8080/http+tls,80:443/http+redirect"` + Services []*Service `mirror:"services" json:"services,omitempty" field:",invisible,valueless" create:"set" flag:"publish" short:"p" sep:"none" help:"Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP.\n http: load balance per HTTP request instead of per TCP connection\n tls: terminate TLS at the platform\n redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect\n tcp: publish a TCP port, the default\n udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10\n @IP: public IP assigned to you on the group's node" placeholder:":[/][@]" example:"443:8080/http+tls,80:443/http+redirect,53:53/udp@203.0.113.10"` Domains []Domain `mirror:"domains" json:"domains,omitempty" field:",short,embed" create:"set" flag:"domain" sep:"none" help:"Domain for the group.\n myapp: a bare label becomes a subdomain of the metro\n example.com: a dotted name is a custom domain, with a certificate issued automatically unless given as fqdn=example.com,certificate=my-cert" placeholder:"fqdn" example:"example.com,myapp"` SoftLimit uint32 `json:"soft-limit,omitempty" field:"soft-limit,invisible,valueless" create:"set" help:"Concurrent requests per instance before the load balancer wakes a standby instance of the group. Between 1 and 65535, defaults to 1."` HardLimit uint32 `json:"hard-limit,omitempty" field:"hard-limit,invisible,valueless" create:"set" help:"Maximum concurrent requests per instance. Between 1 and 65535, defaults to 65535, and at least the soft limit. Excess requests go to another instance or fail."` @@ -418,10 +419,12 @@ func (v *InstanceVolume) UnmarshalText(data []byte) error { // // name= may be omitted when at= is given; it is then derived from the mount path. type InstanceRom struct { - Name string `name:"name" mirror:"name" json:"name,omitempty" field:",long" help:"ROM name of letters, digits, - and _, which appears as /dev/ukp_rom_NAME in the guest."` - Image string `name:"image" mirror:"image" json:"image,omitempty" field:",long" help:"Image the ROM is loaded from. Cannot be combined with dir."` - Dir string `name:"dir" json:"-" field:"dir,invisible,long" help:"Local directory packed into the ROM instead of an image."` - At string `name:"at" mirror:"at" json:"at,omitempty" field:",long" help:"Path the ROM is mounted at inside the instance. When omitted, the guest mounts the raw device itself."` + Name string `name:"name" mirror:"name" json:"name,omitempty" field:",long" help:"ROM name of letters, digits, - and _, which appears as /dev/ukp_rom_NAME in the guest."` + Image string `name:"image" mirror:"image" json:"image,omitempty" field:",long" help:"Image the ROM is loaded from. Cannot be combined with dir."` + PullPolicy *platform.PullPolicy `name:"pull-policy" mirror:"-" json:"pull-policy,omitempty" field:"pull-policy,invisible,long" help:"When to pull the image relative to the node's cache: always, if_not_present or never."` + Headers map[string]string `name:"headers" mirror:"-" json:"headers,omitempty" field:"headers,invisible,long" help:"HTTP headers sent when fetching the image, as headers.KEY=value, up to 16."` + Dir string `name:"dir" json:"-" field:"dir,invisible,long" help:"Local directory packed into the ROM instead of an image."` + At string `name:"at" mirror:"at" json:"at,omitempty" field:",long" help:"Path the ROM is mounted at inside the instance. When omitted, the guest mounts the raw device itself."` } func (r *InstanceRom) UnmarshalText(data []byte) error { @@ -506,10 +509,12 @@ func (c PluginConfig) MarshalJSON() ([]byte, error) { // // rom= is accepted as a deprecated alias for image=. type InstancePlugin struct { - Name string `name:"name" mirror:"name" json:"name" field:",long" help:"Plugin name: up to 63 letters, digits, - and _. The plugin is mounted at /uk/plugins/NAME."` - Image string `name:"image" mirror:"image" json:"image" field:",long" help:"Image the plugin is loaded from. Its init program runs when the plugin starts."` - Rom string `name:"rom" mirror:"-" json:"rom,omitempty" field:"-"` - Config PluginConfig `name:"config" mirror:"config" json:"config,omitempty" field:",long" help:"JSON configuration passed to the plugin init program on stdin."` + Name string `name:"name" mirror:"name" json:"name" field:",long" help:"Plugin name: up to 63 letters, digits, - and _. The plugin is mounted at /uk/plugins/NAME."` + Image string `name:"image" mirror:"image" json:"image" field:",long" help:"Image the plugin is loaded from. Its init program runs when the plugin starts."` + PullPolicy *platform.PullPolicy `name:"pull-policy" mirror:"-" json:"pull-policy,omitempty" field:"pull-policy,invisible,long" help:"When to pull the image relative to the node's cache: always, if_not_present or never."` + Headers map[string]string `name:"headers" mirror:"-" json:"headers,omitempty" field:"headers,invisible,long" help:"HTTP headers sent when fetching the image, as headers.KEY=value, up to 16."` + Rom string `name:"rom" mirror:"-" json:"rom,omitempty" field:"-"` + Config PluginConfig `name:"config" mirror:"config" json:"config,omitempty" field:",long" help:"JSON configuration passed to the plugin init program on stdin."` } func (p *InstancePlugin) Validate() error { @@ -556,9 +561,21 @@ func (p *InstancePlugin) UnmarshalJSON(data []byte) error { return p.Validate() } +// imageSource returns url as a plain reference, or as an image object +// when policy or headers are set. +func imageSource(url string, policy *platform.PullPolicy, headers map[string]string) platform.ImageSource { + if policy == nil && len(headers) == 0 { + return platform.ImageReference(url) + } + return platform.ImageSpec{Url: url, PullPolicy: policy, Headers: headers} +} + // inlineFilesFromDir walks a local directory and returns its contents as // base64-encoded InlineFile entries suitable for the platform API. -func inlineFilesFromDir(dir string) ([]platform.InlineFile, error) { +func inlineFilesFromDir(ctx context.Context, dir string) ([]platform.InlineFile, error) { + if hosted(ctx) { + return nil, errors.New("the server does not send its own files, use image=") + } var files []platform.InlineFile err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error { if err != nil { @@ -1002,7 +1019,13 @@ func (Instance) Edit(ctx context.Context, key string, fields []model.Field) erro break } - patches, err := patchRequests(fields, instancePatchSpec) + patches, err := patchRequests(fields, func(path string, op patchOp, value any) (platform.MutableInstanceProperty, any, error) { + return instancePatchSpec(ctx, path, op, value) + }) + if err != nil { + return err + } + patches, err = setImageOptions(fields, platform.MutableInstancePropertyImage, patches) if err != nil { return err } @@ -1130,7 +1153,7 @@ func (Instance) Edit(ctx context.Context, key string, fields []model.Field) erro return nil } -func instancePatchSpec(path string, op patchOp, value any) (platform.MutableInstanceProperty, any, error) { +func instancePatchSpec(ctx context.Context, path string, op patchOp, value any) (platform.MutableInstanceProperty, any, error) { var zero platform.MutableInstanceProperty switch path { case "tags": @@ -1194,19 +1217,22 @@ func instancePatchSpec(path string, op patchOp, value any) (platform.MutableInst roms := value.([]*InstanceRom) var reqRoms []map[string]any for _, rom := range roms { + if (rom.PullPolicy != nil || len(rom.Headers) > 0) && rom.Image == "" { + return zero, nil, fmt.Errorf("pull-policy= and headers= need image= in a ROM") + } if rom.Image == "" && rom.Dir == "" { continue } reqRom := map[string]any{} if rom.Dir != "" { - files, err := inlineFilesFromDir(rom.Dir) + files, err := inlineFilesFromDir(ctx, rom.Dir) if err != nil { return zero, nil, fmt.Errorf("reading rom dir %q: %w", rom.Dir, err) } reqRom["files"] = files } else { - reqRom["image"] = rom.Image + reqRom["image"] = imageSource(rom.Image, rom.PullPolicy, rom.Headers) } if rom.Name != "" { reqRom["name"] = rom.Name @@ -1230,7 +1256,7 @@ func instancePatchSpec(path string, op patchOp, value any) (platform.MutableInst reqPlugin := map[string]any{ "name": plugin.Name, - "image": plugin.Image, + "image": imageSource(plugin.Image, plugin.PullPolicy, plugin.Headers), } if plugin.Config != "" { reqPlugin["config"] = jsontext.Value(plugin.Config) @@ -1250,6 +1276,7 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model var metro string var imageURL string var pullPolicy *platform.PullPolicy + var headers map[string]string var autostart bool for key, field := range model.IterFields(fields) { if field.Create == nil || field.Create.Set == nil { @@ -1273,6 +1300,8 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } case "pull-policy": pullPolicy = field.Create.Set.(*platform.PullPolicy) + case "image-headers": + headers = field.Create.Set.(map[string]string) case "type": req.Type = field.Create.Set.(*platform.InstanceType) case "runtime.args": @@ -1361,16 +1390,19 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model if sources == 0 { return nil, fmt.Errorf("must specify one of image= or dir= for a ROM") } + if (rom.PullPolicy != nil || len(rom.Headers) > 0) && rom.Image == "" { + return nil, fmt.Errorf("pull-policy= and headers= need image= in a ROM") + } var reqRom platform.CreateInstanceRequestRom if rom.Dir != "" { - files, err := inlineFilesFromDir(rom.Dir) + files, err := inlineFilesFromDir(ctx, rom.Dir) if err != nil { return nil, fmt.Errorf("reading rom dir %q: %w", rom.Dir, err) } reqRom.Files = files } else { - reqRom.Image = platform.ImageReference(rom.Image) + reqRom.Image = imageSource(rom.Image, rom.PullPolicy, rom.Headers) } if rom.Name != "" { reqRom.Name = rom.Name @@ -1391,7 +1423,7 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } reqPlugin := platform.CreateInstanceRequestPlugin{ Name: plugin.Name, - Image: platform.ImageReference(plugin.Image), + Image: imageSource(plugin.Image, plugin.PullPolicy, plugin.Headers), } if plugin.Config != "" { var config any = jsontext.Value(plugin.Config) @@ -1437,11 +1469,7 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model req.ServiceGroup = &platform.CreateInstanceRequestServiceGroup{} } for _, svc := range services { - req.ServiceGroup.Services = append(req.ServiceGroup.Services, platform.Service{ - Port: svc.Source, - DestinationPort: &svc.Destination, - Handlers: svc.Handlers, - }) + req.ServiceGroup.Services = append(req.ServiceGroup.Services, svc.request()) } } case "service.domains": @@ -1530,12 +1558,11 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } } + if (pullPolicy != nil || len(headers) > 0) && imageURL == "" { + return nil, fmt.Errorf("--pull-policy and --image-header need --image") + } if imageURL != "" { - if pullPolicy != nil { - req.Image = platform.ImageSpec{Url: imageURL, PullPolicy: pullPolicy} - } else { - req.Image = platform.ImageReference(imageURL) - } + req.Image = imageSource(imageURL, pullPolicy, headers) } // Validate that exactly one of image, template, branch, or checkpoint is provided @@ -1751,6 +1778,12 @@ func (Instance) Examples() map[cmd.CmdType][]kingkong.Example { "unikraft instance edit demo-instance --memory 256", }, }, + { + Description: "Change the image and always pull it, even if the node has it cached", + Commands: []string{ + "unikraft instance edit demo-instance --image my-app:v2 --pull-policy always", + }, + }, { Description: "Attach a ROM image to an instance", Commands: []string{ @@ -2093,33 +2126,37 @@ func (c *InstancesRestartCmd) Run(ctx context.Context, stdio xstdio.Stdio) error return l.Copy(stdio.Stdout) } -// InstanceHistoryCmd shows the checkpoint history for an instance. +// InstanceHistoryCmd shows the lineage of an instance. type InstanceHistoryCmd struct { - Targets []string `arg:"" name:"target" completion-predictor:"resource-key-instance" help:"Target instances to show history for."` + Targets []string `arg:"" name:"target" completion-predictor:"resource-key-instance" help:"Target instances to show the lineage of."` - cmd.FormatOpts + InstanceHistoryOpts +} + +func (cmd InstanceHistoryCmd) Help() string { + return "Show the whole lineage tree of an instance: every instance, template and checkpoint in it." + lineageHelp } func (cmd InstanceHistoryCmd) Examples() []kingkong.Example { return []kingkong.Example{ { - Description: "Show the checkpoint history of an instance", + Description: "Show the lineage of an instance", Commands: []string{"unikraft instance history my-instance"}, }, + { + Description: "Show the lineage with the UUID of each node", + Commands: []string{"unikraft instance history my-instance -f +uuid"}, + }, + { + Description: "Show the lineage as JSON", + Commands: []string{"unikraft instance history my-instance -o json"}, + }, } } func (c *InstanceHistoryCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { - entries, err := getInstanceHistory(ctx, c.Targets, func(ctx context.Context, mc multimetro.MetroClient, ids []platform.NameOrUUID) (*platform.Response[platform.GetCheckpointHistoryResponseData], error) { - return mc.GetInstanceHistory(ctx, ids, platform.GetInstanceHistoryOpts{}) - }) - if err != nil && len(entries) == 0 { - return err - } - if printErr := renderInstanceHistory(ctx, stdio.Stdout, c.FormatOpts, entries); printErr != nil { - return errors.Join(err, printErr) - } - return err + found, err := Instance{}.Get(ctx, c.Targets) + return runInstanceHistory(ctx, stdio, c.InstanceHistoryOpts, c.Targets, found, err) } type StopOpts struct { diff --git a/internal/cmd/instances_history.go b/internal/cmd/instances_history.go new file mode 100644 index 000000000..bd1247196 --- /dev/null +++ b/internal/cmd/instances_history.go @@ -0,0 +1,347 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, Unikraft GmbH and The Unikraft CLI Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. + +package cmd + +import ( + "cmp" + "context" + "errors" + "fmt" + "io" + "maps" + "slices" + "strings" + + "charm.land/lipgloss/v2" + "charm.land/lipgloss/v2/compat" + "unikraft.com/cloud/sdk/platform" + "unikraft.com/cloud/sdk/platform/group" + "unikraft.com/cloud/sdk/platform/lineage" + "unikraft.com/x/colors" + xio "unikraft.com/x/io" + "unikraft.com/x/kingkong" + "unikraft.com/x/log" + xstdio "unikraft.com/x/stdio" + + "unikraft.com/cli/internal/multimetro" + "unikraft.com/cli/internal/types" + "unikraft.com/cli/pkg/model" + "unikraft.com/cli/pkg/model/cmd" +) + +// lineagePalette colors the lines of a lineage graph. The colors repeat. +var lineagePalette = []compat.AdaptiveColor{ + {Light: colors.Blue600, Dark: colors.Blue400}, + {Light: colors.Emerald600, Dark: colors.Emerald400}, + {Light: colors.Orange600, Dark: colors.Orange400}, + {Light: colors.Rose600, Dark: colors.Rose400}, +} + +// lineageHelp ends the help of the lineage commands. +const lineageHelp = " A table draws the tree in its graph column: ◉ is the target, ● an instance, ○ a checkpoint, ◎ a template and ◌ a deleted instance." + +// InstanceHistoryOpts are the options of the lineage commands. +type InstanceHistoryOpts struct { + Limit uint `help:"Show at most this many nodes of each lineage: the newest ones and the target. 0 shows all."` + + cmd.FormatOpts +} + +func (InstanceHistoryOpts) HelpSections() []kingkong.HelpSection { + return cmd.ModelCmd[InstanceHistoryEntry]{}.HelpSections() +} + +// InstanceHistoryEntry is one instance, template or checkpoint in the lineage +// of a target. +type InstanceHistoryEntry struct { + Graph string `field:",short" json:"-" help:"Lineage graph line of the node. Only tables show it."` + Metro LinkName[Metro] `field:"metro,long" json:"metro" help:"Metro the node is in."` + Name string `field:",short" json:"name" help:"Instance, template or checkpoint name. Empty for a deleted instance."` + Kind lineage.Kind `field:",long" json:"kind" help:"Node kind: instance, template or checkpoint."` + State *types.InstanceState `field:",short" json:"state,omitempty" help:"Lifecycle state: an instance state, template, checkpoint, or deleted for a deleted instance."` + Created *types.RelativeTime `field:"created,short" json:"created,omitempty" help:"Creation time."` + UUID string `field:",long" json:"uuid" help:"Unique identifier assigned at creation."` + Parent string `field:",long" json:"parent" help:"Name or UUID of the instance, template or checkpoint that the node comes from."` + Relation lineage.Relation `field:",long" json:"relation" help:"How the node relates to its parent."` + Target string `field:",long" json:"target" help:"Instance, template or checkpoint the lineage was requested for."` + + key multimetro.Key +} + +func (InstanceHistoryEntry) Type() model.Type { + return model.Type{ + Name: "instance-history-entry", + Names: "instance-history-entries", + } +} + +func (i InstanceHistoryEntry) Key() model.Key { + return i.key +} + +func (i InstanceHistoryEntry) Raw() any { + return i +} + +func (i InstanceHistoryEntry) Fields(ctx context.Context) ([]model.Field, error) { + return model.FieldsFromStruct(i) +} + +// lineageTarget is an instance, template or checkpoint to show the lineage +// of. order is its position in the keys given by the user. +type lineageTarget struct { + key multimetro.Key + inst platform.Instance + order int +} + +// instanceLineage is the lineage of a target. nodes holds every tree of the +// metro, and scope the tree of the target. +type instanceLineage struct { + target lineageTarget + nodes, scope lineage.Tree +} + +// readInstanceLineages reads the lineage of each target once per UUID, in their +// order. It lists all instances, templates and checkpoints of their metros. +func readInstanceLineages(ctx context.Context, targets []lineageTarget, limit uint) ([]instanceLineage, error) { + targets = slices.SortedStableFunc(slices.Values(targets), func(a, b lineageTarget) int { + return cmp.Compare(a.order, b.order) + }) + seen := map[string]bool{} + byMetro := map[string][]lineageTarget{} + for _, t := range targets { + if seen[t.inst.Uuid] { + continue + } + seen[t.inst.Uuid] = true + byMetro[t.key.Metro] = append(byMetro[t.key.Metro], t) + } + + g, err := multimetro.NewClient(ctx) + if err != nil { + return nil, err + } + lins, err := group.CollectMetrosSlices(ctx, g, slices.Collect(maps.Keys(byMetro)), func(ctx context.Context, c multimetro.MetroClient) ([]instanceLineage, error) { + log.G(ctx).Trace().Msg("listing instances, templates and checkpoints for their lineage") + resp, err := c.GetInstances(ctx, nil, platform.GetInstancesOpts{Details: new(true)}) + if err != nil { + return nil, fmt.Errorf("could not list the instances of %s: %w", c.Metro.Name, err) + } + tresp, err := c.GetTemplateInstances(ctx, nil, platform.GetTemplateInstancesOpts{Details: new(true)}) + if err != nil { + log.G(ctx).Warn().Err(err).Msgf("could not list the templates of %s, so instances created from them show as roots", c.Metro.Name) + } + cresp, err := c.GetCheckpointInstances(ctx, nil, platform.GetCheckpointInstancesOpts{Details: new(true)}) + if err != nil { + log.G(ctx).Warn().Err(err).Msgf("could not list the checkpoints of %s, so checkpoints of deleted instances may not show", c.Metro.Name) + } + var listed, insts []platform.Instance + if resp != nil && resp.Data != nil { + listed = resp.Data.Instances + } + if tresp != nil && tresp.Data != nil { + listed = append(slices.Clip(listed), tresp.Data.Instances...) + } + if cresp != nil && cresp.Data != nil { + listed = append(slices.Clip(listed), cresp.Data.Instances...) + } + for _, t := range byMetro[c.Metro.Name] { + if t.inst.State == platform.InstanceStateCheckpoint || t.inst.State == platform.InstanceStateTemplate { + listed = append(slices.Clip(listed), t.inst) + } + } + for _, inst := range listed { + if inst.Status != nil && *inst.Status != platform.ResponseStatusSuccess { + continue + } + insts = append(insts, inst) + } + read, err := lineage.FetchHistories(ctx, c, insts) + if err := context.Cause(ctx); err != nil { + return nil, err + } + if err != nil { + return nil, fmt.Errorf("could not read the checkpoint histories of %s: %w", c.Metro.Name, err) + } + for _, err := range read.Errs { + log.G(ctx).Debug().Err(err).Msg("could not read some checkpoint histories") + } + + nodes := lineage.Build(insts, read.Instances) + var lins []instanceLineage + for _, t := range byMetro[c.Metro.Name] { + scope, truncated, found := nodes.ScopeOf(t.inst, int(limit)) + switch { + case !found: + log.G(ctx).Warn().Msgf("the lineage of %s is not known, so it shows alone", t.key) + case nodes.MissesHistory(t.inst.Uuid, read.Missing): + log.G(ctx).Warn().Msgf("some checkpoint histories could not be read, the lineage of %s may be incomplete", t.key) + } + if truncated { + log.G(ctx).Info().Msgf("the lineage of %s has more than %d nodes, --limit 0 shows all", t.key, limit) + } + lins = append(lins, instanceLineage{target: t, nodes: nodes, scope: scope}) + } + return lins, nil + }) + slices.SortStableFunc(lins, func(a, b instanceLineage) int { + return cmp.Or(cmp.Compare(a.target.order, b.target.order), cmp.Compare(a.target.key.Metro, b.target.key.Metro)) + }) + return lins, err +} + +// lineageGraph draws the rows of l, with current marked as ◉. +func lineageGraph(l lineage.Layout, current string) []string { + grid := l.Grid() + if row, ok := l.RowOf[current]; ok { + grid[row][l.Lane[current]*lineage.LaneWidth].Rune = '◉' + } + + rows := make([]string, len(grid)) + var b, run strings.Builder + for i, cells := range grid { + b.Reset() + for j := 0; j < len(cells); { + color := cells[j].Color + run.Reset() + for ; j < len(cells) && cells[j].Color == color; j++ { + run.WriteRune(cells[j].Rune) + } + if color < 0 { + b.WriteString(run.String()) + continue + } + style := lipgloss.NewStyle().Foreground(lineagePalette[color%len(lineagePalette)]) + b.WriteString(style.Render(run.String())) + } + rows[i] = strings.TrimRight(b.String(), " ") + } + return rows +} + +// historyEntries returns a row for each node of lin, in the order of l, the +// layout of lin.scope. +func historyEntries(lin instanceLineage, l lineage.Layout) []InstanceHistoryEntry { + metro := lin.target.key.Metro + target := lin.target.key.String() + + entries := make([]InstanceHistoryEntry, len(l.Rows)) + for i, n := range l.Rows { + relation, parent := lin.nodes.RelationOf(n) + e := InstanceHistoryEntry{ + Metro: LinkName[Metro](metro), + Name: n.Name, + Kind: n.Kind, + Relation: relation, + Target: target, + } + if !parent.Deleted { + e.Parent = cmp.Or(parent.Name, parent.UUID) + } + if n.Deleted { + e.State = new(types.InstanceState(platform.InstanceStateDeleted)) + } else { + e.UUID = n.UUID + e.Created = new(types.RelativeTime(n.CreatedAt)) + e.key = multimetro.Key{Metro: metro, Name: n.Name, UUID: n.UUID} + state := n.State + if state == "" && n.Kind == lineage.KindCheckpoint { + state = platform.InstanceStateCheckpoint + } + if state != "" { + e.State = new(types.InstanceState(state)) + } + } + entries[i] = e + } + return entries +} + +// printLineageTables prints a table of each lineage with p, with its graph at +// most half the terminal wide. With more than one lineage, it writes each key. +func printLineageTables(ctx context.Context, w io.Writer, p cmd.Printer, fields []string, lins []instanceLineage) error { + width := 80 + if xio.IsTTY(w) && xio.TermWidth(w) > 0 { + width = xio.TermWidth(w) + } + lanes := max((width/2-1)/lineage.LaneWidth, 1) + + for i, lin := range lins { + if len(lins) > 1 { + if i > 0 { + fmt.Fprintln(w) + } + fmt.Fprintln(w, lin.target.key) + } + l := lin.scope.Layout(lineage.WithMaxLanes(lanes)) + graph := lineageGraph(l, lin.target.inst.Uuid) + var entries []model.Model + for j, e := range historyEntries(lin, l) { + e.Graph = graph[j] + entries = append(entries, e) + } + if err := p.Print(ctx, w, fields, InstanceHistoryEntry{}, entries...); err != nil { + return err + } + } + return nil +} + +// runInstanceHistory prints the lineages of the instances, templates or +// checkpoints in found, which a Get of keys returned with getErr. +func runInstanceHistory(ctx context.Context, stdio xstdio.Stdio, opts InstanceHistoryOpts, keys []string, found []model.Model, getErr error) error { + if len(found) == 0 { + return getErr + } + parsed := multimetro.ParseKeys(keys) + targets := make([]lineageTarget, 0, len(found)) + for _, m := range found { + var t lineageTarget + switch m := m.(type) { + case Instance: + t = lineageTarget{key: m.key, inst: m.Instance} + case InstanceTemplate: + t = lineageTarget{key: m.key, inst: m.Instance} + case InstanceCheckpoint: + t = lineageTarget{key: m.key, inst: m.Instance} + } + t.key = multimetro.Key{Metro: t.key.Metro, Name: t.inst.Name, UUID: t.inst.Uuid} + t.order = slices.IndexFunc(parsed, func(k multimetro.Key) bool { + return (k.Metro == "" || k.Metro == t.key.Metro) && + (k.UUID == t.inst.Uuid || (k.UUID == "" && k.Name == t.inst.Name)) + }) + targets = append(targets, t) + } + + lins, err := readInstanceLineages(ctx, targets, opts.Limit) + err = errors.Join(getErr, err) + if len(lins) == 0 { + return err + } + + p := opts.Output.WithDefault(cmd.PrinterTypeTable) + if p.Type == cmd.PrinterTypeTable { + return errors.Join(err, printLineageTables(ctx, stdio.Stdout, p, opts.Field, lins)) + } + fields := opts.Field + if len(fields) == 0 && (p.Type == cmd.PrinterTypeJSON || p.Type == cmd.PrinterTypeYAML) { + fields = []string{cmd.FieldSpecAll, "-graph"} + } + var entries []model.Model + seen := map[string]bool{} + for _, lin := range lins { + for _, e := range historyEntries(lin, lin.scope.Layout()) { + if p.Type == cmd.PrinterTypeQuiet && len(fields) == 0 && (e.UUID == "" || seen[e.UUID]) { + continue + } + seen[e.UUID] = true + entries = append(entries, e) + } + } + printErr := p.Print(ctx, stdio.Stdout, fields, InstanceHistoryEntry{}, entries...) + return errors.Join(err, printErr) +} diff --git a/internal/cmd/instances_test.go b/internal/cmd/instances_test.go index c0c45938a..8ede6f3b1 100644 --- a/internal/cmd/instances_test.go +++ b/internal/cmd/instances_test.go @@ -17,6 +17,7 @@ import ( "unikraft.com/cli/internal/cmd" "unikraft.com/cli/internal/mirror" "unikraft.com/cli/internal/types" + "unikraft.com/cli/pkg/model" "unikraft.com/cli/pkg/model/patch" ) @@ -57,6 +58,16 @@ func TestInstancePluginUnmarshalText(t *testing.T) { in: "name=logger,image=r:1,config=5", want: cmd.InstancePlugin{Name: "logger", Image: "r:1", Config: "5"}, }, + { + name: "pull policy", + in: "name=logger,image=r:1,pull-policy=never", + want: cmd.InstancePlugin{Name: "logger", Image: "r:1", PullPolicy: new(platform.PullPolicyNever)}, + }, + { + name: "headers", + in: "name=logger,image=r:1,headers.Authorization=Bearer x,headers.X-Foo=1", + want: cmd.InstancePlugin{Name: "logger", Image: "r:1", Headers: map[string]string{"Authorization": "Bearer x", "X-Foo": "1"}}, + }, { name: "missing name is rejected", in: "image=plugins/logger:latest", @@ -190,6 +201,139 @@ func TestInstanceRomName(t *testing.T) { } } +func TestInstanceCreateRejectsImageOptions(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + spec map[string][]string + wantErr string + }{ + { + name: "pull policy without an image", + spec: map[string][]string{ + "template": {"my-template"}, + "pull-policy": {"always"}, + }, + wantErr: "--pull-policy and --image-header need --image", + }, + { + name: "image header without an image", + spec: map[string][]string{ + "template": {"my-template"}, + "image-headers": {"X-Foo=1"}, + }, + wantErr: "--pull-policy and --image-header need --image", + }, + { + name: "pull policy on a directory rom", + spec: map[string][]string{ + "image": {"nginx:latest"}, + "roms": {"name=r,dir=./does-not-exist,pull-policy=always"}, + }, + wantErr: "pull-policy= and headers= need image= in a ROM", + }, + { + name: "headers on a directory rom", + spec: map[string][]string{ + "image": {"nginx:latest"}, + "roms": {"name=r,dir=./does-not-exist,headers.X-Foo=1"}, + }, + wantErr: "pull-policy= and headers= need image= in a ROM", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + fields, err := cmd.Instance{}.Fields(t.Context()) + require.NoError(t, err) + + patched, err := patch.PatchedFields(t.Context(), fields, patch.PatchSpec{ + Create: true, + Set: tt.spec, + }) + require.NoError(t, err) + + _, err = cmd.Instance{}.Create(t.Context(), patched) + require.ErrorContains(t, err, tt.wantErr) + }) + } +} + +func TestInstanceEditRejectsImageOptions(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + target model.EditableModel + spec map[string][]string + wantErr string + }{ + { + name: "pull policy without an image", + target: cmd.Instance{}, + spec: map[string][]string{"pull-policy": {"always"}}, + wantErr: "--pull-policy and --image-header need --image in the same edit", + }, + { + name: "template pull policy without an image", + target: cmd.InstanceTemplate{}, + spec: map[string][]string{"pull-policy": {"always"}}, + wantErr: "--pull-policy and --image-header need --image in the same edit", + }, + { + name: "image header without an image", + target: cmd.Instance{}, + spec: map[string][]string{"image-headers": {"X-Foo=1"}}, + wantErr: "--pull-policy and --image-header need --image in the same edit", + }, + { + name: "empty image headers without an image", + target: cmd.Instance{}, + spec: map[string][]string{"image-headers": {"{}"}}, + wantErr: "--pull-policy and --image-header need --image in the same edit", + }, + { + name: "pull policy on a directory rom", + target: cmd.Instance{}, + spec: map[string][]string{"roms": {"name=r,dir=./does-not-exist,pull-policy=always"}}, + wantErr: "pull-policy= and headers= need image= in a ROM", + }, + { + name: "headers on a directory rom", + target: cmd.Instance{}, + spec: map[string][]string{"roms": {"name=r,dir=./does-not-exist,headers.X-Foo=1"}}, + wantErr: "pull-policy= and headers= need image= in a ROM", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + fields, err := tt.target.Fields(t.Context()) + require.NoError(t, err) + patched, err := patch.PatchedFields(t.Context(), fields, patch.PatchSpec{Set: tt.spec}) + require.NoError(t, err) + + require.ErrorContains(t, tt.target.Edit(t.Context(), "x", patched), tt.wantErr) + }) + } +} + +func TestInstanceEditOfAHostedServerRefusesADirectoryRom(t *testing.T) { + t.Parallel() + + fields, err := cmd.Instance{}.Fields(t.Context()) + require.NoError(t, err) + patched, err := patch.PatchedFields(t.Context(), fields, patch.PatchSpec{Set: map[string][]string{"roms": {"name=r,dir=" + t.TempDir()}}}) + require.NoError(t, err) + + require.ErrorContains(t, cmd.Instance{}.Edit(cmd.WithHosted(t.Context()), "x", patched), "does not send its own files") +} + // TestInstanceCreateRejectsNetworks checks that create stops a bad --network // before it sends a request. func TestInstanceCreateRejectsNetworks(t *testing.T) { diff --git a/internal/cmd/instances_tui.go b/internal/cmd/instances_tui.go index 15bbe259c..d8be338e0 100644 --- a/internal/cmd/instances_tui.go +++ b/internal/cmd/instances_tui.go @@ -8,18 +8,23 @@ package cmd import ( + "bytes" + "cmp" "context" "errors" "fmt" "io" tea "charm.land/bubbletea/v2" + "github.com/rs/zerolog" "unikraft.com/cloud/sdk/platform" "unikraft.com/cloud/sdk/platform/group" "unikraft.com/cloud/sdk/platform/logs" + "unikraft.com/x/log" "unikraft.com/cli/internal/multimetro" "unikraft.com/cli/pkg/model" + "unikraft.com/cli/pkg/model/cmd" modeltui "unikraft.com/cli/pkg/model/tui" ) @@ -41,8 +46,30 @@ func (Instance) Subpanels(ctx context.Context, key string) []tea.Model { return io.NopCloser(r), nil } + // Logs on the terminal break the view, so the lineage is read without them. + historyFunc := func(ctx context.Context) (io.ReadCloser, error) { + nop := zerolog.Nop() + ctx = log.WithLogger(ctx, &nop) + found, err := Instance{}.Get(ctx, []string{key}) + if len(found) == 0 { + return nil, cmp.Or(err, fmt.Errorf("instance %s not found", key)) + } + inst := found[0].(Instance) + target := lineageTarget{key: inst.key, inst: inst.Instance} + lins, err := readInstanceLineages(ctx, []lineageTarget{target}, 0) + if err != nil { + return nil, err + } + var buf bytes.Buffer + if err := printLineageTables(ctx, &buf, cmd.Printer{Type: cmd.PrinterTypeTable}, nil, lins); err != nil { + return nil, err + } + return io.NopCloser(&buf), nil + } + return []tea.Model{ modeltui.NewReaderPanelFunc(ctx, "Logs", readerFunc, true), + modeltui.NewReaderPanelFunc(ctx, "History", historyFunc, false).LoadOnFocus(), } } diff --git a/internal/cmd/login/login.go b/internal/cmd/login/login.go index 60684ab03..38e39f640 100644 --- a/internal/cmd/login/login.go +++ b/internal/cmd/login/login.go @@ -49,7 +49,7 @@ func (cmd *LoginCmd) Run(ctx context.Context, cfg *config.Config) error { } // Get the token either from file or via browser authentication - var token, organization, userUUID, orgUUID string + var token, organization, userUUID, orgUUID, registry string if cmd.Token != nil { log.G(ctx).Info(). Msg("reading authentication token from file") @@ -80,6 +80,7 @@ func (cmd *LoginCmd) Run(ctx context.Context, cfg *config.Config) error { organization = cmp.Or(resp.Data.OrganizationName, cmd.Organization) userUUID = resp.Data.UserUuid orgUUID = resp.Data.OrganizationUuid + registry = resp.Data.Registry } tempProfile.Token = token @@ -102,6 +103,7 @@ func (cmd *LoginCmd) Run(ctx context.Context, cfg *config.Config) error { } organization = cmp.Or(organization, auth.OrganizationName) orgUUID = auth.OrganizationUuid + registry = cmp.Or(registry, auth.Registry) } } @@ -126,6 +128,9 @@ func (cmd *LoginCmd) Run(ctx context.Context, cfg *config.Config) error { if orgUUID != "" { profile.OrganizationUUID = orgUUID } + if registry != "" || profile.ControlPlane != loginControlPlane { + profile.Registry.Host = registry + } profile.ControlPlane = loginControlPlane profile.Insecure = cmd.AllowInsecure diff --git a/internal/cmd/login/login_test.go b/internal/cmd/login/login_test.go new file mode 100644 index 000000000..7c36ab24f --- /dev/null +++ b/internal/cmd/login/login_test.go @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, Unikraft GmbH and The Unikraft CLI Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. + +package login + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "unikraft.com/cli/internal/config" +) + +func TestLoginRegistry(t *testing.T) { + tests := []struct { + name string + profiles map[string]config.Profile + registry string + expected string + }{ + { + name: "stores the registry", + registry: "harbor.example:8083", + expected: "harbor.example:8083", + }, + { + name: "control plane change clears a stale host", + profiles: map[string]config.Profile{ + "acme": { + Type: config.ProfileTypeCloud, + ControlPlane: "https://old.example", + Registry: config.Registry{Host: "old.host"}, + }, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1/auth" { + http.NotFound(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "status": "success", + "data": map[string]any{ + "organization_name": "acme", + "registry": tt.registry, + }, + }) + })) + defer srv.Close() + + dir := t.TempDir() + tokenPath := filepath.Join(dir, "token") + require.NoError(t, os.WriteFile(tokenPath, []byte("test-token"), 0o600)) + token, err := os.Open(tokenPath) + require.NoError(t, err) + + path := filepath.Join(dir, "config.yaml") + cmd := &LoginCmd{ControlPlane: srv.URL, Token: token} + err = cmd.Run(t.Context(), &config.Config{Path: path, Profiles: tt.profiles}) + require.NoError(t, err) + + cfg, err := config.Load(path) + require.NoError(t, err) + assert.Equal(t, tt.expected, cfg.Profiles["acme"].Registry.Host) + }) + } +} diff --git a/internal/cmd/marshal_test.go b/internal/cmd/marshal_test.go index fb416b1c3..3fa05c0a8 100644 --- a/internal/cmd/marshal_test.go +++ b/internal/cmd/marshal_test.go @@ -370,6 +370,30 @@ func TestEditPatches(t *testing.T) { spec: patch.PatchSpec{Set: map[string][]string{"services": {"443:8080/tls", "80:80/http"}}}, want: map[string]string{"services.set": "[443:8080/tls, 80:80/http]"}, }, + { + name: "services add udp", + res: cmd.ServiceGroup{}, + spec: patch.PatchSpec{Add: map[string][]string{"services": {"53:53/udp@203.0.113.10"}}}, + want: map[string]string{"services.add": "[53:53/udp@203.0.113.10]"}, + }, + { + name: "services set explicit tcp", + res: cmd.ServiceGroup{}, + spec: patch.PatchSpec{Set: map[string][]string{"services": {"443:8080/TCP+http+tls"}}}, + want: map[string]string{"services.set": "[443:8080/http+tls]"}, + }, + { + name: "services bad ip", + res: cmd.ServiceGroup{}, + spec: patch.PatchSpec{Add: map[string][]string{"services": {"53:53/udp@nope"}}}, + wantErr: "invalid IP address", + }, + { + name: "services two protocols", + res: cmd.ServiceGroup{}, + spec: patch.PatchSpec{Add: map[string][]string{"services": {"53:53/udp+tcp@203.0.113.10"}}}, + wantErr: "protocol given more than once", + }, { name: "domains add with certificate", res: cmd.ServiceGroup{}, diff --git a/internal/cmd/mcp.go b/internal/cmd/mcp.go index de4fce761..f4e8e8e0e 100644 --- a/internal/cmd/mcp.go +++ b/internal/cmd/mcp.go @@ -155,7 +155,7 @@ func (c *MCPCmd) Run(ctx context.Context, stdio xstdio.Stdio, partition *model.P if err := c.Check(); err != nil { return err } - srv, err := newMCPServer(ctx, stdio.Stderr, partition, *c) + srv, err := NewMCPServer(ctx, stdio.Stderr, partition, *c) if err != nil { return err } @@ -163,7 +163,9 @@ func (c *MCPCmd) Run(ctx context.Context, stdio xstdio.Stdio, partition *model.P return c.Serve(ctx, srv) } -func newMCPServer(ctx context.Context, stderr io.Writer, partition *model.Partition, c MCPCmd) (*mcpserver.Server, error) { +// NewMCPServer returns the server of unikraft mcp. pkg/mcpserver/cli serves +// it to other programs. +func NewMCPServer(ctx context.Context, stderr io.Writer, partition *model.Partition, c MCPCmd) (*mcpserver.Server, error) { if err := checkResources(c.Resources); err != nil { return nil, err } @@ -235,9 +237,24 @@ func newMCPServer(ctx context.Context, stderr io.Writer, partition *model.Partit return srv, nil } +// hostedKey marks the context of a tool call of a hosted server. +type hostedKey struct{} + +// WithHosted returns ctx for a tool call of a server that runs for others, on +// a machine that is not theirs. Its tools then refuse the inputs that read +// the files of the server or reach addresses that the caller picks. +func WithHosted(ctx context.Context) context.Context { + return context.WithValue(ctx, hostedKey{}, true) +} + +func hosted(ctx context.Context) bool { + h, _ := ctx.Value(hostedKey{}).(bool) + return h +} + func reloadConfig(next sdk.MethodHandler) sdk.MethodHandler { return func(ctx context.Context, method string, req sdk.Request) (sdk.Result, error) { - if _, ok := req.(*sdk.CallToolRequest); ok { + if _, ok := req.(*sdk.CallToolRequest); ok && config.G(ctx).Path != "" { started := config.G(ctx) profile, _ := started.OverriddenCurrentProfile() cfg, err := loadConfig(started.Path, profile) diff --git a/internal/cmd/mcp_test.go b/internal/cmd/mcp_test.go index bf92b7c6d..ed245a58b 100644 --- a/internal/cmd/mcp_test.go +++ b/internal/cmd/mcp_test.go @@ -39,11 +39,11 @@ func TestMCPServerTools(t *testing.T) { "sandbox_exec", "sandbox_write", "profile_use", } - srv, err := newMCPServer(ctx, io.Discard, nil, MCPCmd{}) + srv, err := NewMCPServer(ctx, io.Discard, nil, MCPCmd{}) require.NoError(t, err) assert.ElementsMatch(t, append(readOnlyTools, mutatingTools...), mcptest.ConnectServer(t, ctx, srv.MCP()).ToolNames()) - srv, err = newMCPServer(ctx, io.Discard, nil, MCPCmd{ReadOnly: true}) + srv, err = NewMCPServer(ctx, io.Discard, nil, MCPCmd{ReadOnly: true}) require.NoError(t, err) assert.ElementsMatch(t, readOnlyTools, mcptest.ConnectServer(t, ctx, srv.MCP()).ToolNames()) } @@ -51,7 +51,7 @@ func TestMCPServerTools(t *testing.T) { func TestMCPServerResources(t *testing.T) { ctx := config.WithConfig(t.Context(), &config.Config{}) - srv, err := newMCPServer(ctx, io.Discard, nil, MCPCmd{Resources: []string{"instance", "metro"}}) + srv, err := NewMCPServer(ctx, io.Discard, nil, MCPCmd{Resources: []string{"instance", "metro"}}) require.NoError(t, err) session := mcptest.ConnectServer(t, ctx, srv.MCP()) assert.ElementsMatch(t, []string{ @@ -59,14 +59,14 @@ func TestMCPServerResources(t *testing.T) { }, session.ToolNames()) assert.Contains(t, session.Instructions, "Only the tools of these resource types are served: instance, metro.") - _, err = newMCPServer(ctx, io.Discard, nil, MCPCmd{Resources: []string{"instance", "nope"}}) + _, err = NewMCPServer(ctx, io.Discard, nil, MCPCmd{Resources: []string{"instance", "nope"}}) assert.EqualError(t, err, "--resources: unknown resource types: nope; known: certificate, image, instance, instance_checkpoint, instance_template, metro, profile, sandbox, service, volume, volume_template") } func TestMCPResourceTypes(t *testing.T) { ctx := config.WithConfig(t.Context(), &config.Config{}) - srv, err := newMCPServer(ctx, io.Discard, nil, MCPCmd{}) + srv, err := NewMCPServer(ctx, io.Discard, nil, MCPCmd{}) require.NoError(t, err) for _, tool := range mcptest.ConnectServer(t, ctx, srv.MCP()).ToolNames() { assert.Truef(t, slices.ContainsFunc(mcpResourceTypes, func(typ string) bool { @@ -75,7 +75,7 @@ func TestMCPResourceTypes(t *testing.T) { } for _, typ := range mcpResourceTypes { - srv, err := newMCPServer(ctx, io.Discard, nil, MCPCmd{Resources: []string{typ}}) + srv, err := NewMCPServer(ctx, io.Discard, nil, MCPCmd{Resources: []string{typ}}) require.NoError(t, err) assert.NotEmptyf(t, mcptest.ConnectServer(t, ctx, srv.MCP()).ToolNames(), "type %s serves no tools", typ) } @@ -94,7 +94,7 @@ profiles: cfg, err := loadConfig(path, "") require.NoError(t, err) ctx := config.WithConfig(t.Context(), cfg) - srv, err := newMCPServer(ctx, io.Discard, nil, MCPCmd{}) + srv, err := NewMCPServer(ctx, io.Discard, nil, MCPCmd{}) require.NoError(t, err) session := mcptest.ConnectServer(t, ctx, srv.MCP()) @@ -125,7 +125,7 @@ profiles: cfg, err = loadConfig(path, "b") require.NoError(t, err) pinned := config.WithConfig(t.Context(), cfg) - srv, err = newMCPServer(pinned, io.Discard, nil, MCPCmd{}) + srv, err = NewMCPServer(pinned, io.Discard, nil, MCPCmd{}) require.NoError(t, err) session = mcptest.ConnectServer(t, pinned, srv.MCP()) assert.NotContains(t, session.ToolNames(), "profile_use") @@ -133,7 +133,21 @@ profiles: assert.Equal(t, []map[string]any{{"name": "was"}}, mcptest.Resources(t, res)) t.Setenv("UNIKRAFT_PROFILE_ENV", "1") - srv, err = newMCPServer(ctx, io.Discard, nil, MCPCmd{}) + srv, err = NewMCPServer(ctx, io.Discard, nil, MCPCmd{}) require.NoError(t, err) assert.NotContains(t, mcptest.ConnectServer(t, ctx, srv.MCP()).ToolNames(), "profile_use") } + +func TestMCPConfigWithoutFile(t *testing.T) { + cfg := &config.Config{Profiles: map[string]config.Profile{ + "a": {Name: "a", Type: config.ProfileTypeCloud, Token: "a", Metros: []config.Metro{{Name: "fra", Endpoint: "https://api.fra.unikraft.cloud"}}}, + }} + cfg.OverrideCurrentProfile("a") + ctx := config.WithConfig(t.Context(), cfg) + srv, err := NewMCPServer(ctx, io.Discard, nil, MCPCmd{}) + require.NoError(t, err) + + res := mcptest.CallTool(t, ctx, mcptest.ConnectServer(t, ctx, srv.MCP()), "metro_list", map[string]any{"fields": []string{"name"}}) + require.False(t, res.IsError, mcptest.Text(res)) + assert.Equal(t, []map[string]any{{"name": "fra"}}, mcptest.Resources(t, res)) +} diff --git a/internal/cmd/mcp_tools.go b/internal/cmd/mcp_tools.go index a1430cb62..3d0a1a794 100644 --- a/internal/cmd/mcp_tools.go +++ b/internal/cmd/mcp_tools.go @@ -114,7 +114,7 @@ func (c mcpSandboxCommands) ReadFile(ctx context.Context, instance, remote strin if err != nil { return nil, err } - return target.ReadFile(ctx, remote) + return target.ReadFile(ctx, remote, modelmcp.MaxOutput) } func (c mcpSandboxCommands) WriteFile(ctx context.Context, instance, remote string, data []byte, opts mcp.SandboxWriteOptions) error { diff --git a/internal/cmd/output_test.go b/internal/cmd/output_test.go index d16a927ce..9e93d0884 100644 --- a/internal/cmd/output_test.go +++ b/internal/cmd/output_test.go @@ -18,6 +18,7 @@ import ( integ "unikraft.com/cli/internal/integration" "unikraft.com/cloud/sdk/platform" + "unikraft.com/cloud/sdk/platform/lineage" "unikraft.com/cli/internal/cmd" "unikraft.com/cli/internal/types" @@ -264,12 +265,16 @@ func instanceCheckpointsOutputTests(t *testing.T) { func instanceHistoryOutputTests(t *testing.T) { sample := cmd.InstanceHistoryEntry{ - Metro: "fra", - Target: "fra/my-instance", - Name: "my-checkpoint", - UUID: "f6a7b8c9-d0e1-2345-f012-3456789abcde", - // Created is left as the zero value so it renders deterministically - // ("never") instead of a wall-clock-relative string. + Metro: "fra", + Name: "my-fork", + Kind: lineage.KindInstance, + State: new(types.InstanceState(platform.InstanceStateRunning)), + UUID: "f6a7b8c9-d0e1-2345-f012-3456789abcde", + Parent: "my-checkpoint", + Relation: lineage.RelationForkedFrom, + Target: "fra/my-fork", + // Created is left nil so it renders deterministically instead of + // as a wall-clock-relative string. } integ.Gild[model.Model](t, dumpResource, sample) @@ -324,13 +329,21 @@ func servicesOutputTests(t *testing.T) { { Source: 443, Destination: 8080, + Protocol: "tcp", Handlers: []platform.ConnectionHandler{"tls", "http"}, }, { Source: 80, Destination: 443, + Protocol: "tcp", Handlers: []platform.ConnectionHandler{"http", "redirect"}, }, + { + Source: 53, + Destination: 53, + Protocol: "udp", + IP: "203.0.113.10", + }, }, Domains: []cmd.Domain{ {FQDN: "example.unikraft.app"}, diff --git a/internal/cmd/sandbox_plugin.go b/internal/cmd/sandbox_plugin.go index 469768a63..2c8b11bdd 100644 --- a/internal/cmd/sandbox_plugin.go +++ b/internal/cmd/sandbox_plugin.go @@ -31,7 +31,7 @@ const ( defaultPluginImage = "plugins/sandbox:latest" startHint = "%[1]s it with `unikraft instance %[1]s %[2]s`" - attachHint = "attach it with `unikraft instance edit %s --plugin name=%s,image=%s` while the instance is stopped" + attachHint = "attach it with `unikraft instance edit %s --plugin name=%s,image=%s`" ) const ( @@ -47,7 +47,7 @@ var sandboxKongVars = kong.Vars{ type SandboxPluginOpts struct { PluginName string `name:"plugin-name" default:"${sandbox_plugin}" help:"Name of the sandbox plugin to use." placeholder:"name"` - PluginImage string `name:"plugin-image" default:"${sandbox_plugin_image}" help:"Image of the sandbox plugin to attach when the instance has none." placeholder:"ref"` + PluginImage string `name:"plugin-image" default:"${sandbox_plugin_image}" help:"Image of the sandbox plugin to attach when the instance has none. It asks first, so it only attaches from a terminal." placeholder:"ref"` } func attachPlugin(ctx context.Context, stdio xstdio.Stdio, partition *model.Partition, instance Instance, opts SandboxPluginOpts) error { @@ -105,14 +105,14 @@ func tryAttachPlugin(ctx context.Context, stdio xstdio.Stdio, partition *model.P if slices.Contains(instance.Instance.Features, platform.InstanceFeatureDeleteOnStop) { return fmt.Errorf("%w\nhint: the instance is deleted when it stops, so the plugin cannot be attached in place; recreate it with --plugin name=%s,image=%s", cause, plugin, image) } - if !xio.IsTTYReader(stdio.Stdin) || !xio.IsTTY(stdio.Stdout) { - return fmt.Errorf("%w\nhint: %s", cause, fmt.Sprintf(attachHint, instance.Key().String(), plugin, image)) - } - verb := "start" if instance.State.IsRunning() { verb = "restart" } + if !xio.IsTTYReader(stdio.Stdin) || !xio.IsTTY(stdio.Stdout) { + return fmt.Errorf("%w\nhint: %s, then %s", cause, fmt.Sprintf(attachHint, instance.Key().String(), plugin, image), fmt.Sprintf(startHint, verb, instance.Key().String())) + } + question := fmt.Sprintf("instance %q has no plugin %q; attach %s", instance.Name, plugin, image) options := []string{ "no", diff --git a/internal/cmd/sandbox_plugin_test.go b/internal/cmd/sandbox_plugin_test.go index 0d86ccfbb..afaaf243b 100644 --- a/internal/cmd/sandbox_plugin_test.go +++ b/internal/cmd/sandbox_plugin_test.go @@ -66,7 +66,18 @@ func TestTryAttachPluginWithoutTTY(t *testing.T) { err := tryAttachPlugin(t.Context(), stdio, nil, instance, opts, cause) require.ErrorIs(t, err, cause) - assert.Equal(t, cause.Error()+"\nhint: attach it with `unikraft instance edit fra/my-inst --plugin name=sandbox,image=plugins/sandbox:latest` while the instance is stopped", err.Error()) + assert.Equal(t, cause.Error()+"\nhint: attach it with `unikraft instance edit fra/my-inst --plugin name=sandbox,image=plugins/sandbox:latest`, then restart it with `unikraft instance restart fra/my-inst`", err.Error()) + }) + + t.Run("hint-stopped", func(t *testing.T) { + stopped := instance + stopped.State = types.InstanceState(platform.InstanceStateStopped) + stdio := xstdio.Stdio{Stdin: strings.NewReader("y\n"), Stdout: &bytes.Buffer{}} + + err := tryAttachPlugin(t.Context(), stdio, nil, stopped, opts, cause) + + require.ErrorIs(t, err, cause) + assert.Equal(t, cause.Error()+"\nhint: attach it with `unikraft instance edit fra/my-inst --plugin name=sandbox,image=plugins/sandbox:latest`, then start it with `unikraft instance start fra/my-inst`", err.Error()) }) t.Run("delete-on-stop", func(t *testing.T) { diff --git a/internal/cmd/services.go b/internal/cmd/services.go index ff588fae2..e72519360 100644 --- a/internal/cmd/services.go +++ b/internal/cmd/services.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "maps" + "net/netip" "slices" "strconv" "strings" @@ -21,6 +22,7 @@ import ( "unikraft.com/cloud/sdk/platform/group" "unikraft.com/x/kingkong" "unikraft.com/x/log" + "unikraft.com/x/ptr" "unikraft.com/cli/internal/config" "unikraft.com/cli/internal/mirror" @@ -189,7 +191,7 @@ type ServiceGroup struct { Link[Instance] } `mirror:"service_group.instances" help:"Instances in the group."` - Services []*Service `mirror:"service_group.services" field:",embed" create:"set,required" edit:"set,add,del" flag:"service" sep:"none" help:"Published port as SOURCE:DESTINATION[/HANDLERS], with handlers joined by +. Port 80 must use http, port 443 http+tls, and any other port tls only.\n http: load balance per HTTP request instead of per TCP connection\n tls: terminate TLS at the platform\n redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect" placeholder:":[/]" example:"443:8080/http+tls,80:443/http+redirect"` + Services []*Service `mirror:"service_group.services" field:",embed" create:"set,required" edit:"set,add,del" flag:"service" sep:"none" help:"Published port as SOURCE:DESTINATION[/OPTIONS][@IP], with options joined by +. TCP port 80 must use http, port 443 http+tls, and any other port tls only. UDP ports take no handlers and need an IP.\n http: load balance per HTTP request instead of per TCP connection\n tls: terminate TLS at the platform\n redirect: redirect HTTP on port 80 to HTTPS, as in 80:443/http+redirect\n tcp: publish a TCP port, the default\n udp: publish a UDP port instead of TCP, as in 53:53/udp@203.0.113.10\n @IP: public IP assigned to you on the group's node" placeholder:":[/][@]" example:"443:8080/http+tls,80:443/http+redirect,53:53/udp@203.0.113.10"` ServiceGroup platform.ServiceGroup `field:"-" json:"service_group"` @@ -199,20 +201,40 @@ type ServiceGroup struct { type Service struct { Source uint32 `mirror:"port" json:"source" field:",short" help:"Public port."` Destination uint32 `mirror:"destination_port" json:"destination" field:",short" help:"Port the instance listens on."` + Protocol platform.ServiceProtocol `mirror:"protocol" json:"protocol,omitempty" field:",short" help:"Transport protocol: tcp or udp."` + IP string `mirror:"ip" json:"ip,omitempty" field:",short" help:"Public IP address the port listens on. Required for udp."` Handlers []platform.ConnectionHandler `mirror:"handlers" json:"handlers" field:",short" help:"Connection handlers: http, tls, redirect."` } +// MarshalText writes SOURCE:DESTINATION[/OPTIONS][@IP]. It does not write +// the default tcp protocol. func (s *Service) MarshalText() ([]byte, error) { - handlers := make([]string, len(s.Handlers)) - for i, handler := range s.Handlers { - handlers[i] = string(handler) - } - return fmt.Appendf( - []byte{}, "%d:%d/%s", - s.Source, - s.Destination, - strings.Join(handlers, "+"), - ), nil + var opts []string + if s.Protocol != "" && s.Protocol != platform.ServiceProtocolTcp { + opts = append(opts, string(s.Protocol)) + } + for _, handler := range s.Handlers { + opts = append(opts, string(handler)) + } + text := fmt.Appendf(nil, "%d:%d", s.Source, s.Destination) + if len(opts) > 0 { + text = fmt.Appendf(text, "/%s", strings.Join(opts, "+")) + } + if s.IP != "" { + text = fmt.Appendf(text, "@%s", s.IP) + } + return text, nil +} + +// request returns the API form of the service. +func (s *Service) request() platform.Service { + return platform.Service{ + Port: s.Source, + DestinationPort: &s.Destination, + Protocol: ptr.NilIfZero(s.Protocol), + Ip: ptr.NilIfZero(s.IP), + Handlers: s.Handlers, + } } // MarshalJSON outputs the struct form (not the short text form). @@ -237,11 +259,19 @@ func (s *Service) UnmarshalJSON(data []byte) error { } func (s *Service) UnmarshalText(text []byte) error { - str := string(text) - ports, handlers, _ := strings.Cut(str, "/") + str, ip, hasIP := strings.Cut(string(text), "@") + if hasIP { + addr, err := netip.ParseAddr(ip) + if err != nil { + return fmt.Errorf("invalid IP address: %w", err) + } + s.IP = addr.String() + } + + ports, opts, _ := strings.Cut(str, "/") src, dest, ok := strings.Cut(ports, ":") if !ok { - return fmt.Errorf("invalid service format, expected SOURCE:DESTINATION/HANDLERS") + return fmt.Errorf("invalid service format, expected SOURCE:DESTINATION[/OPTIONS][@IP]") } srcPort, err := strconv.Atoi(src) @@ -256,9 +286,16 @@ func (s *Service) UnmarshalText(text []byte) error { } s.Destination = uint32(destPort) - if handlers != "" { - for handler := range strings.SplitSeq(handlers, "+") { - s.Handlers = append(s.Handlers, platform.ConnectionHandler(handler)) + if opts != "" { + for opt := range strings.SplitSeq(opts, "+") { + if !strings.EqualFold(opt, "tcp") && !strings.EqualFold(opt, "udp") { + s.Handlers = append(s.Handlers, platform.ConnectionHandler(opt)) + continue + } + if s.Protocol != "" { + return fmt.Errorf("protocol given more than once") + } + s.Protocol = platform.ServiceProtocol(strings.ToLower(opt)) } } @@ -490,11 +527,7 @@ func (ServiceGroup) Create(ctx context.Context, fields []model.Field) ([]model.M } case "services": for _, svc := range field.Create.Set.([]*Service) { - req.Services = append(req.Services, platform.Service{ - Port: svc.Source, - DestinationPort: &svc.Destination, - Handlers: svc.Handlers, - }) + req.Services = append(req.Services, svc.request()) } } } @@ -604,6 +637,15 @@ func (ServiceGroup) Examples() map[cmd.CmdType][]kingkong.Example { --service 443:8080/tls+http`, }, }, + { + Description: "Create a service group with a UDP port on a dedicated IP", + Commands: []string{ + `unikraft service create \ + --name dns \ + --metro fra \ + --service 53:53/udp@203.0.113.10`, + }, + }, }, cmd.CmdTypeEdit: { { @@ -664,11 +706,7 @@ func serviceGroupPatchSpec(path string, _ patchOp, value any) (platform.MutableS case "services": nvalue := []platform.Service{} for _, svc := range value.([]*Service) { - nvalue = append(nvalue, platform.Service{ - Port: svc.Source, - DestinationPort: &svc.Destination, - Handlers: svc.Handlers, - }) + nvalue = append(nvalue, svc.request()) } return platform.MutableServiceGroupPropertyServices, nvalue, nil default: diff --git a/internal/cmd/services_internal_test.go b/internal/cmd/services_internal_test.go new file mode 100644 index 000000000..7164bf7a2 --- /dev/null +++ b/internal/cmd/services_internal_test.go @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, Unikraft GmbH and The Unikraft CLI Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. + +package cmd + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "unikraft.com/cloud/sdk/platform" +) + +func TestServiceRequest(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + svc Service + want string + }{ + { + name: "tcp omits protocol and ip", + svc: Service{Source: 443, Destination: 8080, Handlers: []platform.ConnectionHandler{"tls"}}, + want: `{"port":443,"destination_port":8080,"handlers":["tls"]}`, + }, + { + name: "udp sends protocol and ip", + svc: Service{Source: 53, Destination: 53, Protocol: "udp", IP: "203.0.113.10"}, + want: `{"port":53,"destination_port":53,"protocol":"udp","ip":"203.0.113.10"}`, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + + got, err := json.Marshal(tt.svc.request()) + require.NoError(t, err) + assert.JSONEq(t, tt.want, string(got)) + }) + } +} diff --git a/internal/cmd/testdata/TestOutput/instance-history b/internal/cmd/testdata/TestOutput/instance-history index 0817f328d..f95ba22ce 100644 --- a/internal/cmd/testdata/TestOutput/instance-history +++ b/internal/cmd/testdata/TestOutput/instance-history @@ -1,22 +1,36 @@ ====================================== kv ====================================== -metro: fra -target: fra/my-instance -name: my-checkpoint -uuid: f6a7b8c9-d0e1-2345-f012-3456789abcde +metro: fra +name: my-fork +kind: instance +state: running +uuid: f6a7b8c9-d0e1-2345-f012-3456789abcde +parent: my-checkpoint +relation: forked-from +target: fra/my-fork ==================================== kv-all ==================================== -metro: fra -target: fra/my-instance -name: my-checkpoint -uuid: f6a7b8c9-d0e1-2345-f012-3456789abcde -created: never +graph: +metro: fra +name: my-fork +kind: instance +state: running +created: +uuid: f6a7b8c9-d0e1-2345-f012-3456789abcde +parent: my-checkpoint +relation: forked-from +target: fra/my-fork ==================================== table ===================================== -METRO TARGET NAME CREATED -fra fra/my-instance my-checkpoint never +GRAPH NAME STATE CREATED + my-fork running ==================================== debug ===================================== [ + { + "name": "graph", + "value": "", + "verbosity": "short" + }, { "name": "metro", "value": "fra", @@ -26,16 +40,26 @@ fra fra/my-instance my-checkpoint never "key": "fra" } ], + "verbosity": "long" + }, + { + "name": "name", + "value": "my-fork", "verbosity": "short" }, { - "name": "target", - "value": "fra/my-instance", + "name": "kind", + "value": "instance", + "verbosity": "long" + }, + { + "name": "state", + "value": "running", "verbosity": "short" }, { - "name": "name", - "value": "my-checkpoint", + "name": "created", + "value": null, "verbosity": "short" }, { @@ -44,8 +68,18 @@ fra fra/my-instance my-checkpoint never "verbosity": "long" }, { - "name": "created", - "value": "never", - "verbosity": "short" + "name": "parent", + "value": "my-checkpoint", + "verbosity": "long" + }, + { + "name": "relation", + "value": "forked-from", + "verbosity": "long" + }, + { + "name": "target", + "value": "fra/my-fork", + "verbosity": "long" } ] diff --git a/internal/cmd/testdata/TestOutput/instance-templates b/internal/cmd/testdata/TestOutput/instance-templates index 880034fef..d35095937 100644 --- a/internal/cmd/testdata/TestOutput/instance-templates +++ b/internal/cmd/testdata/TestOutput/instance-templates @@ -147,7 +147,24 @@ fra my-template template nginx 128MiB 1 never "key": "unikraft.io/official/nginx:latest" } ], - "verbosity": "short" + "verbosity": "short", + "edit": { + "set": "nginx" + } + }, + { + "name": "pull-policy", + "verbosity": "invisible", + "edit": { + "set": null + } + }, + { + "name": "image-headers", + "verbosity": "invisible", + "edit": { + "set": null + } }, { "name": "type", diff --git a/internal/cmd/testdata/TestOutput/instances b/internal/cmd/testdata/TestOutput/instances index 57dc321f7..7eca233a0 100644 --- a/internal/cmd/testdata/TestOutput/instances +++ b/internal/cmd/testdata/TestOutput/instances @@ -296,6 +296,19 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "verbosity": "invisible", "create": { "set": null + }, + "edit": { + "set": null + } + }, + { + "name": "image-headers", + "verbosity": "invisible", + "create": { + "set": null + }, + "edit": { + "set": null } }, { @@ -637,6 +650,16 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": "myuser/my-rom:latest", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -664,6 +687,16 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -715,6 +748,16 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": "plugins/sandbox:latest", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "config", "value": { @@ -739,6 +782,16 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "config", "value": null, diff --git a/internal/cmd/testdata/TestOutput/instances-http-oci b/internal/cmd/testdata/TestOutput/instances-http-oci index 321a33ebc..407d06141 100644 --- a/internal/cmd/testdata/TestOutput/instances-http-oci +++ b/internal/cmd/testdata/TestOutput/instances-http-oci @@ -167,6 +167,19 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "verbosity": "invisible", "create": { "set": null + }, + "edit": { + "set": null + } + }, + { + "name": "image-headers", + "verbosity": "invisible", + "create": { + "set": null + }, + "edit": { + "set": null } }, { @@ -376,6 +389,16 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -414,6 +437,16 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "config", "value": null, diff --git a/internal/cmd/testdata/TestOutput/services b/internal/cmd/testdata/TestOutput/services index 57f85bf24..4c7876f64 100644 --- a/internal/cmd/testdata/TestOutput/services +++ b/internal/cmd/testdata/TestOutput/services @@ -12,10 +12,16 @@ domains: services: - source: 443 destination: 8080 + protocol: tcp handlers: ["tls", "http"] - source: 80 destination: 443 + protocol: tcp handlers: ["http", "redirect"] +- source: 53 + destination: 53 + protocol: udp + ip: 203.0.113.10 ==================================== kv-all ==================================== metro: fra @@ -40,14 +46,23 @@ instances: services: - source: 443 destination: 8080 + protocol: tcp + ip: handlers: ["tls", "http"] - source: 80 destination: 443 + protocol: tcp + ip: handlers: ["http", "redirect"] +- source: 53 + destination: 53 + protocol: udp + ip: 203.0.113.10 + handlers: ==================================== table ===================================== -METRO NAME AUTOSCALE CREATED FQDN SOURCE DESTINATION HANDLERS SOURCE DESTINATION HANDLERS -fra my-service true never example.unikraft.app 443 8080 ["tls", "http"] 80 443 ["http", "redirect"] +METRO NAME AUTOSCALE CREATED FQDN SOURCE DESTINATION PROTOCOL IP HANDLERS SOURCE DESTINATION PROTOCOL IP HANDLERS SOURCE DESTINATION PROTOCOL IP HANDLERS +fra my-service true never example.unikraft.app 443 8080 tcp ["tls", "http"] 80 443 tcp ["http", "redirect"] 53 53 udp 203.0.113.10 ==================================== debug ===================================== [ @@ -265,6 +280,16 @@ fra my-service true never example.unikraft.app 443 8080 "value": 8080, "verbosity": "short" }, + { + "name": "protocol", + "value": "tcp", + "verbosity": "short" + }, + { + "name": "ip", + "value": "", + "verbosity": "short" + }, { "name": "handlers", "value": [ @@ -289,6 +314,16 @@ fra my-service true never example.unikraft.app 443 8080 "value": 443, "verbosity": "short" }, + { + "name": "protocol", + "value": "tcp", + "verbosity": "short" + }, + { + "name": "ip", + "value": "", + "verbosity": "short" + }, { "name": "handlers", "value": [ @@ -299,6 +334,37 @@ fra my-service true never example.unikraft.app 443 8080 } ], "verbosity": "short" + }, + { + "name": "2", + "subfields": [ + { + "name": "source", + "value": 53, + "verbosity": "short" + }, + { + "name": "destination", + "value": 53, + "verbosity": "short" + }, + { + "name": "protocol", + "value": "udp", + "verbosity": "short" + }, + { + "name": "ip", + "value": "203.0.113.10", + "verbosity": "short" + }, + { + "name": "handlers", + "value": null, + "verbosity": "short" + } + ], + "verbosity": "short" } ], "elem": { @@ -314,6 +380,16 @@ fra my-service true never example.unikraft.app 443 8080 "value": 0, "verbosity": "short" }, + { + "name": "protocol", + "value": "", + "verbosity": "short" + }, + { + "name": "ip", + "value": "", + "verbosity": "short" + }, { "name": "handlers", "value": null, @@ -328,6 +404,7 @@ fra my-service true never example.unikraft.app 443 8080 { "source": 443, "destination": 8080, + "protocol": "tcp", "handlers": [ "tls", "http" @@ -336,10 +413,18 @@ fra my-service true never example.unikraft.app 443 8080 { "source": 80, "destination": 443, + "protocol": "tcp", "handlers": [ "http", "redirect" ] + }, + { + "source": 53, + "destination": 53, + "protocol": "udp", + "ip": "203.0.113.10", + "handlers": null } ], "required": true @@ -349,6 +434,7 @@ fra my-service true never example.unikraft.app 443 8080 { "source": 443, "destination": 8080, + "protocol": "tcp", "handlers": [ "tls", "http" @@ -357,10 +443,18 @@ fra my-service true never example.unikraft.app 443 8080 { "source": 80, "destination": 443, + "protocol": "tcp", "handlers": [ "http", "redirect" ] + }, + { + "source": 53, + "destination": 53, + "protocol": "udp", + "ip": "203.0.113.10", + "handlers": null } ], "add": null, diff --git a/internal/cmd/util.go b/internal/cmd/util.go index a0943f0cf..4f90a3c76 100644 --- a/internal/cmd/util.go +++ b/internal/cmd/util.go @@ -7,10 +7,12 @@ package cmd import ( "context" + "fmt" "maps" "slices" "strings" + "unikraft.com/cloud/sdk/platform" "unikraft.com/cloud/sdk/platform/group" "unikraft.com/x/log" @@ -186,3 +188,30 @@ func patchRequests[P ~string](fields []model.Field, specFor func(path string, op } return reqs, nil } + +// setImageOptions moves the pull policy and headers in fields into the image patch. +func setImageOptions[P ~string](fields []model.Field, prop P, patches []patchReq[P]) ([]patchReq[P], error) { + var policy *platform.PullPolicy + if found := model.GetFieldByPath(fields, model.FieldPath{"pull-policy"}); len(found) > 0 && found[0].Edit != nil { + policy, _ = found[0].Edit.Set.(*platform.PullPolicy) + } + var headers map[string]string + if found := model.GetFieldByPath(fields, model.FieldPath{"image-headers"}); len(found) > 0 && found[0].Edit != nil { + headers, _ = found[0].Edit.Set.(map[string]string) + } + if policy == nil && headers == nil { + return patches, nil + } + i := slices.IndexFunc(patches, func(p patchReq[P]) bool { + return p.Prop == prop && p.Op == patchOpSet + }) + if i < 0 { + return nil, fmt.Errorf("--pull-policy and --image-header need --image in the same edit") + } + url, ok := patches[i].Value.(string) + if !ok { + return nil, fmt.Errorf("unexpected image patch value %T", patches[i].Value) + } + patches[i].Value = imageSource(url, policy, headers) + return patches, nil +} diff --git a/internal/cmd/util_test.go b/internal/cmd/util_test.go index 2a0db9715..a5906f4a2 100644 --- a/internal/cmd/util_test.go +++ b/internal/cmd/util_test.go @@ -6,6 +6,7 @@ package cmd import ( + "encoding/json" "testing" "github.com/stretchr/testify/assert" @@ -128,3 +129,58 @@ func TestResourcesWithoutAnOrganizationHaveNoLink(t *testing.T) { require.NoError(t, err) assert.Empty(t, nameLink(fields)) } + +func TestImagePatchWireFormat(t *testing.T) { + tests := []struct { + name string + value func(t *testing.T) any + want string + }{ + { + name: "image with a pull policy and headers", + value: func(t *testing.T) any { + fields := []model.Field{ + {Name: "pull-policy", Edit: &model.Patch{Set: new(platform.PullPolicyAlways)}}, + {Name: "image-headers", Edit: &model.Patch{Set: map[string]string{"X-Foo": "1"}}}, + } + patches := []patchReq[platform.MutableInstanceProperty]{{ + Op: patchOpSet, + Prop: platform.MutableInstancePropertyImage, + Value: "nginx:latest", + }} + patches, err := setImageOptions(fields, platform.MutableInstancePropertyImage, patches) + require.NoError(t, err) + require.Len(t, patches, 1) + return patches[0].Value + }, + want: `{"url":"nginx:latest","pull_policy":"always","headers":{"X-Foo":"1"}}`, + }, + { + name: "rom with a pull policy and headers", + value: func(t *testing.T) any { + roms := []*InstanceRom{{Name: "r", Image: "r:1", PullPolicy: new(platform.PullPolicyNever), Headers: map[string]string{"X-Foo": "1"}}} + _, value, err := instancePatchSpec(t.Context(), "roms", patchOpSet, roms) + require.NoError(t, err) + return value + }, + want: `[{"name":"r","image":{"url":"r:1","pull_policy":"never","headers":{"X-Foo":"1"}}}]`, + }, + { + name: "plugin with a pull policy and headers", + value: func(t *testing.T) any { + plugins := []*InstancePlugin{{Name: "p", Image: "p:1", PullPolicy: new(platform.PullPolicyIfNotPresent), Headers: map[string]string{"X-Foo": "1"}}} + _, value, err := instancePatchSpec(t.Context(), "plugins", patchOpSet, plugins) + require.NoError(t, err) + return value + }, + want: `[{"name":"p","image":{"url":"p:1","pull_policy":"if_not_present","headers":{"X-Foo":"1"}}}]`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := json.Marshal(tt.value(t)) + require.NoError(t, err) + assert.JSONEq(t, tt.want, string(got)) + }) + } +} diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 69eecae70..5c677af56 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -472,6 +472,43 @@ profiles: assert.Equal(t, "index.was.unikraft.cloud", direct.Index().Host) } +func TestCloudProfileRegistry(t *testing.T) { + root := t.TempDir() + path := filepath.Join(root, "config.yaml") + + input := strings.TrimSpace(` +profile: default +profiles: + default: + type: cloud + token: test-token + registry: + host: harbor.example:8083 + mirror: https://console.example.com/proxy/registry + insecure: true + plain: + type: cloud + token: test-token +`) + "\n" + + err := os.WriteFile(path, []byte(input), 0o600) + require.NoError(t, err) + + config, err := Load(path) + require.NoError(t, err) + + assert.Equal(t, Registry{ + Host: "harbor.example:8083", + Mirror: "https://console.example.com/proxy/registry", + Insecure: true, + }, config.Profiles["default"].Registry) + + require.NoError(t, config.Save()) + saved, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, 1, strings.Count(string(saved), "registry:")) +} + func TestDefaultConfigFilePath(t *testing.T) { tests := []struct { name string diff --git a/internal/config/profile.go b/internal/config/profile.go index 8acaf4150..b462f9970 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -82,15 +82,25 @@ type Profile struct { ControlPlane string `json:"controlplane,omitempty" field:",long" help:"Control plane endpoint."` // Insecure indicates whether to allow insecure connections to the control plane, skipping TLS verification. Insecure bool `json:"controlplane_insecure,omitempty" field:",long" help:"Skip TLS verification when connecting to the control plane."` - // RegistryMirror is the endpoint that gets the requests for the Unikraft image registry. - RegistryMirror string `json:"registry_mirror,omitempty" field:",long" help:"Endpoint that serves requests for the Unikraft image registry."` - BuildURL string `json:"build_url,omitempty" field:",long" help:"URL of the build service that remote builds and the builder commands use."` + // Registry is the configuration of the Unikraft image registry. + Registry Registry `json:"registry,omitzero" field:",long,embed" help:"Unikraft image registry settings."` + BuildURL string `json:"build_url,omitempty" field:",long" help:"URL of the build service that remote builds and the builder commands use."` // Metros is a static list of metros. Metros []Metro `json:"metros,omitempty" field:",long,embed" help:"Metros of the profile."` // MetroDefault is the default metro to use when creating resources. MetroDefault string `json:"metro_default,omitempty" help:"Metro that create commands and unikraft api use when none is given. Without it, a profile with a single metro uses that one."` } +// Registry is the Unikraft image registry configuration of a profile. +type Registry struct { + // Host is the host of the Unikraft image registry. + Host string `json:"host,omitempty" field:",long" help:"Host of the Unikraft image registry. Login sets it from the control plane."` + // Mirror is the endpoint that gets the requests for the Unikraft image registry. + Mirror string `json:"mirror,omitempty" field:",long" help:"Endpoint that serves requests for the Unikraft image registry."` + // Insecure skips TLS verification when connecting to the Unikraft image registry. + Insecure bool `json:"insecure,omitempty" field:",long" help:"Skip TLS verification when connecting to the Unikraft image registry."` +} + func (p Profile) GetDefaultMetro() string { if p.MetroDefault != "" { return p.MetroDefault diff --git a/internal/images/resolver.go b/internal/images/resolver.go index 4da6d396f..46fba9b22 100644 --- a/internal/images/resolver.go +++ b/internal/images/resolver.go @@ -58,6 +58,9 @@ func resolverOptions(profile *config.Profile, insecureRegistries []string, allIn if isInsecureRegistry(host) { return true, nil } + if profile != nil && profile.Registry.Insecure && isUnikraftRegistry(profile, host) { + return true, nil + } for _, index := range indexes { if host == index.Host { return index.Insecure, nil @@ -66,10 +69,11 @@ func resolverOptions(profile *config.Profile, insecureRegistries []string, allIn return false, nil } + authClient := &http.Client{Transport: insecureTransport(insecureHost)} dockerConfig := dockerconfig.LoadDefaultConfigFile(os.Stderr) opts := []docker.RegistryOpt{ docker.WithClient(httpclient.RegistryHTTPClient), - docker.WithAuthorizer(docker.NewDockerAuthorizer(docker.WithAuthCreds(func(hostname string) (string, string, error) { + docker.WithAuthorizer(docker.NewDockerAuthorizer(docker.WithAuthClient(authClient), docker.WithAuthCreds(func(hostname string) (string, string, error) { username, password, err := hostCreds(profile, hostname) if err != nil { return "", "", err @@ -109,8 +113,8 @@ func resolverOptions(profile *config.Profile, insecureRegistries []string, allIn return s, nil }))...), ) - if profile != nil && profile.RegistryMirror != "" { - hosts = mirrorHosts(hosts, profile.RegistryMirror) + if profile != nil && profile.Registry.Mirror != "" { + hosts = mirrorHosts(hosts, profile) } return docker.ResolverOptions{ @@ -119,8 +123,10 @@ func resolverOptions(profile *config.Profile, insecureRegistries []string, allIn } } -// mirrorHosts sends the requests for the Unikraft registry to mirror. -func mirrorHosts(hosts docker.RegistryHosts, mirror string) docker.RegistryHosts { +// mirrorHosts sends the requests for the Unikraft registry to the mirror of +// profile. +func mirrorHosts(hosts docker.RegistryHosts, profile *config.Profile) docker.RegistryHosts { + mirror := profile.Registry.Mirror return func(host string) ([]docker.RegistryHost, error) { u, err := url.Parse(mirror) if err != nil { @@ -131,7 +137,7 @@ func mirrorHosts(hosts docker.RegistryHosts, mirror string) docker.RegistryHosts return nil, err } for i, host := range hosts { - if slices.Contains(defaultRegistries, host.Host) { + if isUnikraftRegistry(profile, host.Host) { host.Scheme = u.Scheme host.Host = u.Host host.Path = path.Join("/", u.Path, "v2") @@ -142,6 +148,33 @@ func mirrorHosts(hosts docker.RegistryHosts, mirror string) docker.RegistryHosts } } +// isUnikraftRegistry returns true if host is a default Unikraft registry host +// or the registry host of profile. +func isUnikraftRegistry(profile *config.Profile, host string) bool { + if slices.Contains(defaultRegistries, host) { + return true + } + return profile != nil && profile.Registry.Host != "" && host == profile.Registry.Host +} + +// insecureTransport sends a request through the insecure registry client if +// the function accepts its host. Else, it uses the registry client. +type insecureTransport func(host string) (bool, error) + +func (t insecureTransport) RoundTrip(req *http.Request) (*http.Response, error) { + ok, err := t(req.URL.Host) + if err != nil { + if req.Body != nil { + req.Body.Close() + } + return nil, err + } + if ok { + return httpclient.InsecureRegistryHTTPClient.Transport.RoundTrip(req) + } + return httpclient.RegistryHTTPClient.Transport.RoundTrip(req) +} + func fallbackHost(registryHosts ...docker.RegistryHosts) docker.RegistryHosts { return func(host string) ([]docker.RegistryHost, error) { var allHosts []docker.RegistryHost @@ -184,7 +217,7 @@ func hostCreds(profile *config.Profile, hostname string) (string, string, error) } // FIXME: why are there two different auth schemes? - if slices.Contains(defaultRegistries, hostname) { + if isUnikraftRegistry(profile, hostname) { return decodeAuth(profile.Token) } for _, metro := range profile.Metros { diff --git a/internal/images/resolver_test.go b/internal/images/resolver_test.go new file mode 100644 index 000000000..41f28466e --- /dev/null +++ b/internal/images/resolver_test.go @@ -0,0 +1,88 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, Unikraft GmbH and The Unikraft CLI Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. + +package images + +import ( + "crypto/x509" + "encoding/base64" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "unikraft.com/cli/internal/config" + "unikraft.com/cli/internal/httpclient" +) + +func TestHostCredsRegistryHost(t *testing.T) { + profile := &config.Profile{ + Token: base64.StdEncoding.EncodeToString([]byte("user:pass")), + Registry: config.Registry{Host: "harbor.example:8083"}, + } + + username, password, err := hostCreds(profile, "harbor.example:8083") + require.NoError(t, err) + assert.Equal(t, "user", username) + assert.Equal(t, "pass", password) +} + +func TestResolverOptionsRegistry(t *testing.T) { + t.Setenv("DOCKER_CONFIG", t.TempDir()) + + t.Run("mirror", func(t *testing.T) { + profile := &config.Profile{Registry: config.Registry{ + Host: "harbor.example:8083", + Mirror: "https://console.example.com/proxy/registry", + }} + + hosts, err := resolverOptions(profile, nil, false).Hosts("harbor.example:8083") + require.NoError(t, err) + require.NotEmpty(t, hosts) + assert.Equal(t, "console.example.com", hosts[0].Host) + }) + + t.Run("insecure", func(t *testing.T) { + profile := &config.Profile{Registry: config.Registry{ + Host: "harbor.example:8083", + Insecure: true, + }} + options := resolverOptions(profile, nil, false) + + hosts, err := options.Hosts("harbor.example:8083") + require.NoError(t, err) + require.NotEmpty(t, hosts) + assert.Same(t, httpclient.InsecureRegistryHTTPClient, hosts[0].Client) + + hosts, err = options.Hosts("ghcr.io") + require.NoError(t, err) + require.NotEmpty(t, hosts) + assert.Same(t, httpclient.RegistryHTTPClient, hosts[0].Client) + }) +} + +func TestInsecureTransport(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + defer srv.Close() + u, err := url.Parse(srv.URL) + require.NoError(t, err) + + insecure := &http.Client{Transport: insecureTransport(func(host string) (bool, error) { + return host == u.Host, nil + })} + resp, err := insecure.Get(srv.URL) + require.NoError(t, err) + resp.Body.Close() + + secure := &http.Client{Transport: insecureTransport(func(string) (bool, error) { + return false, nil + })} + _, err = secure.Get(srv.URL) + var unknownAuthority x509.UnknownAuthorityError + assert.ErrorAs(t, err, &unknownAuthority) +} diff --git a/internal/integration/image.go b/internal/integration/image.go index dcdaa3890..e1e43ef30 100644 --- a/internal/integration/image.go +++ b/internal/integration/image.go @@ -10,6 +10,7 @@ import ( "crypto/rand" "encoding/hex" "fmt" + "maps" "os" "path/filepath" "slices" @@ -125,7 +126,11 @@ func (s *SharedImage) Build(t *testing.T, env *TestEnv) string { func (s *SharedImage) build(t *testing.T, env *TestEnv) (string, error) { t.Helper() ref := s.Ref(env, sharedImageTag) - if err := s.Image.Build(t, env, ref, WithNoPartition(), WithoutCancel()); err != nil { + // The label keeps the digest unique: image delete removes every tag of a digest. + img := s.Image + img.Files = maps.Clone(s.Files) + img.Files["Dockerfile"] += "\nLABEL unikraft-e2e=" + sharedImageTag + "\n" + if err := img.Build(t, env, ref, WithNoPartition(), WithoutCancel()); err != nil { return "", err } registerImageConfig(env.Config, ref) diff --git a/internal/mcp/sandbox.go b/internal/mcp/sandbox.go index e18c4c543..c5ab178b0 100644 --- a/internal/mcp/sandbox.go +++ b/internal/mcp/sandbox.go @@ -6,6 +6,7 @@ package mcp import ( + "cmp" "context" "encoding/json/jsontext" "encoding/json/v2" @@ -46,7 +47,7 @@ type sandboxExecArgs struct { Dir string `json:"dir,omitzero" jsonschema:"Directory to run the command in."` Env map[string]string `json:"env,omitzero" jsonschema:"The whole environment the command sees, not an addition to it."` Stdin string `json:"stdin,omitzero" jsonschema:"Text fed to the command's standard input."` - TimeoutMS int64 `json:"timeout_ms,omitzero" jsonschema:"Milliseconds to wait before the command is stopped. Defaults to the server's timeout."` + TimeoutMS int64 `json:"timeout_ms,omitzero" jsonschema:"Milliseconds to wait before the command is stopped: 5 minutes by default, and 30 minutes at most."` } type sandboxReadArgs struct { @@ -64,6 +65,12 @@ type sandboxWriteArgs struct { var errExecTimeout = errors.New("sandbox command timed out") +// A command holds its tool call until it ends, thus each command has a time limit. +const ( + defaultExecTimeout = 5 * time.Minute + maxExecTimeout = 30 * time.Minute +) + func AddSandboxTools(tools *modelmcp.Tools, commands SandboxCommands) error { const key = "The sandbox instance: " + modelmcp.KeyFormat + "." exec, err := schemaWithKey[sandboxExecArgs]("key", key) @@ -82,11 +89,13 @@ func AddSandboxTools(tools *modelmcp.Tools, commands SandboxCommands) error { AnyOf: []*jsonschema.Schema{{Type: "array", Items: &jsonschema.Schema{Type: "string"}}, {Type: "string"}}, Description: "The program and its arguments as an array of strings, or one string for the shell to interpret, so that pipes and redirections work.", } + exec.Properties["timeout_ms"].Minimum = new(0.0) + exec.Properties["timeout_ms"].Maximum = new(float64(maxExecTimeout.Milliseconds())) return errors.Join( tools.AddTool("sandbox", &mcp.Tool{ Name: "sandbox_read", Title: "Read sandbox file", - Description: "Read a text file from a running sandbox instance. Returns its content.", + Description: fmt.Sprintf("Read a text file of at most %d MiB from a running sandbox instance. Returns its content.", modelmcp.MaxOutput>>20), InputSchema: read, Annotations: modelmcp.ReadOnlyAnnotations(), }, false, func(ctx context.Context, in sandboxReadArgs, stdio xstdio.Stdio) error { @@ -123,12 +132,9 @@ func AddSandboxTools(tools *modelmcp.Tools, commands SandboxCommands) error { if len(opts.Args) == 0 && opts.Cmdline == "" { return errors.New("invalid command: it is empty") } - timeout := time.Duration(in.TimeoutMS) * time.Millisecond - if timeout > 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeoutCause(ctx, timeout, errExecTimeout) - defer cancel() - } + timeout := cmp.Or(time.Duration(in.TimeoutMS)*time.Millisecond, defaultExecTimeout) + ctx, cancel := context.WithTimeoutCause(ctx, timeout, errExecTimeout) + defer cancel() code, err := commands.Exec(ctx, stdio, in.Key, opts) if errors.Is(context.Cause(ctx), errExecTimeout) { return fmt.Errorf("command timed out after %s", timeout) diff --git a/internal/mcp/sandbox_test.go b/internal/mcp/sandbox_test.go index a99286d22..bbbfbe98c 100644 --- a/internal/mcp/sandbox_test.go +++ b/internal/mcp/sandbox_test.go @@ -10,6 +10,7 @@ import ( "errors" "fmt" "testing" + "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -33,6 +34,10 @@ func (f *fakeSandbox) Exec(ctx context.Context, stdio xstdio.Stdio, instance str return 0, ctx.Err() case "boom": return 0, errors.New("transport broke") + case "deadline": + deadline, _ := ctx.Deadline() + fmt.Fprint(stdio.Stdout, time.Until(deadline).Round(time.Minute)) + return 0, nil } fmt.Fprint(stdio.Stdout, "out\n") if opts.Cmdline == "false" { @@ -84,6 +89,14 @@ func TestSandboxTools(t *testing.T) { assert.True(t, res.IsError) assert.Contains(t, mcptest.Text(res), "command timed out after 20ms") + res = mcptest.CallTool(t, ctx, session, "sandbox_exec", map[string]any{"key": "scratch", "command": "deadline"}) + require.False(t, res.IsError, mcptest.Text(res)) + assert.Equal(t, "5m0s", mcptest.Text(res)) + + res = mcptest.CallTool(t, ctx, session, "sandbox_exec", map[string]any{"key": "scratch", "command": "deadline", "timeout_ms": 30*60*1000 + 1}) + assert.True(t, res.IsError) + assert.Contains(t, mcptest.Text(res), "validating /properties/timeout_ms") + res = mcptest.CallTool(t, ctx, session, "sandbox_exec", map[string]any{"key": "scratch", "command": 7}) assert.True(t, res.IsError) assert.Contains(t, mcptest.Text(res), "validating /properties/command") @@ -114,6 +127,7 @@ func TestSandboxTools(t *testing.T) { `exec scratch args=[] cmdline="false" dir="" env=map[] stdin=""`, `exec scratch args=[] cmdline="boom" dir="" env=map[] stdin=""`, `exec scratch args=[] cmdline="sleep" dir="" env=map[] stdin=""`, + `exec scratch args=[] cmdline="deadline" dir="" env=map[] stdin=""`, "read scratch /data/x", "read scratch /data/bin", `write scratch /data/y "hi\n" append=true parents=true`, diff --git a/pkg/mcpserver/cli/cli.go b/pkg/mcpserver/cli/cli.go new file mode 100644 index 000000000..fa101d5e1 --- /dev/null +++ b/pkg/mcpserver/cli/cli.go @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, Unikraft GmbH and The Unikraft CLI Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. + +// Package cli serves the MCP server of unikraft mcp to other CLIs. +package cli + +import ( + "context" + "errors" + "os" + + sdk "github.com/modelcontextprotocol/go-sdk/mcp" + + "unikraft.com/cloud/sdk/controlplane" + + "unikraft.com/cli/internal/branding" + "unikraft.com/cli/internal/cmd" + "unikraft.com/cli/internal/config" + "unikraft.com/cli/pkg/mcpserver" +) + +// New returns the server of unikraft mcp, with every tool and the +// documentation as resources. Its tool calls use the profile that WithToken +// puts on their context. It serves HTTPS with the TLS files of flags. +// +// The callers are not on the machine of the server, thus its tools refuse a +// ROM of a dir= and image references that are not of a registry. +func New(ctx context.Context, flags mcpserver.Flags) (*mcpserver.Server, error) { + if err := flags.Check(); err != nil { + return nil, err + } + // A pinned profile drops profile_use, which writes the configuration file. + ctx = WithToken(ctx, "") + // The profile of the environment wins over the one of WithToken. + if config.G(ctx).CurrentProfileName() == config.EnvProfile { + return nil, errors.New("UNIKRAFT_PROFILE_ENV is set, so every tool call would use UKC_TOKEN and not its own token") + } + srv, err := cmd.NewMCPServer(ctx, os.Stderr, nil, cmd.MCPCmd{DocsURL: branding.DocsURL, Flags: flags}) + if err != nil { + return nil, err + } + srv.MCP().AddReceivingMiddleware(func(next sdk.MethodHandler) sdk.MethodHandler { + return func(ctx context.Context, method string, req sdk.Request) (sdk.Result, error) { + return next(cmd.WithHosted(ctx), method, req) + } + }) + return srv, nil +} + +// WithToken returns a context whose tool calls use a cloud profile that +// authenticates with token. +func WithToken(ctx context.Context, token string) context.Context { + cfg := &config.Config{Profiles: map[string]config.Profile{ + config.DefaultProfile: { + Name: config.DefaultProfile, + Type: config.ProfileTypeCloud, + Token: token, + ControlPlane: controlplane.DefaultEndpoint, + }, + }} + cfg.OverrideCurrentProfile(config.DefaultProfile) + return config.WithConfig(ctx, cfg) +} diff --git a/pkg/mcpserver/cli/cli_test.go b/pkg/mcpserver/cli/cli_test.go new file mode 100644 index 000000000..ad35f5ee4 --- /dev/null +++ b/pkg/mcpserver/cli/cli_test.go @@ -0,0 +1,58 @@ +// SPDX-License-Identifier: BSD-3-Clause +// Copyright (c) 2026, Unikraft GmbH and The Unikraft CLI Authors. +// Licensed under the BSD-3-Clause License (the "License"). +// You may not use this file except in compliance with the License. + +package cli + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "unikraft.com/cloud/sdk/controlplane" + + "unikraft.com/cli/internal/config" + "unikraft.com/cli/pkg/mcpserver" + "unikraft.com/cli/pkg/mcpserver/mcptest" +) + +func TestNew(t *testing.T) { + srv, err := New(t.Context(), mcpserver.Flags{}) + require.NoError(t, err) + names := mcptest.ConnectServer(t, t.Context(), srv.MCP()).ToolNames() + assert.Contains(t, names, "instance_list") + assert.NotContains(t, names, "profile_use") + + t.Setenv("UNIKRAFT_PROFILE_ENV", "true") + _, err = New(t.Context(), mcpserver.Flags{}) + assert.ErrorContains(t, err, "UNIKRAFT_PROFILE_ENV") +} + +func TestNewServerFiles(t *testing.T) { + srv, err := New(t.Context(), mcpserver.Flags{}) + require.NoError(t, err) + s := mcptest.ConnectServer(t, WithToken(t.Context(), "secret"), srv.MCP()) + rom, err := json.Marshal("name=r,dir=" + t.TempDir() + ",at=/r") + require.NoError(t, err) + + for _, tc := range []struct{ tool, args, want string }{ + {"instance_create", `{"set":{"image":"nginx:latest","metro":"fra","roms":[` + string(rom) + `]}}`, "does not send its own files"}, + {"image_get", `{"keys":["http+oci://127.0.0.1:1/x:latest"]}`, "only registry references"}, + } { + out, isErr, err := s.Call(t.Context(), tc.tool, json.RawMessage(tc.args)) + require.NoError(t, err, tc.tool) + assert.True(t, isErr, tc.tool) + assert.Contains(t, out, tc.want, tc.tool) + } +} + +func TestWithToken(t *testing.T) { + profile, err := config.G(WithToken(t.Context(), "secret")).CurrentProfile() + require.NoError(t, err) + assert.Equal(t, config.ProfileTypeCloud, profile.Type) + assert.Equal(t, "secret", profile.Token) + assert.Equal(t, controlplane.DefaultEndpoint, profile.ControlPlane) +} diff --git a/pkg/mcpserver/docs_test.go b/pkg/mcpserver/docs_test.go index 9466fe8ee..b10a61c27 100644 --- a/pkg/mcpserver/docs_test.go +++ b/pkg/mcpserver/docs_test.go @@ -3,7 +3,7 @@ // Licensed under the BSD-3-Clause License (the "License"). // You may not use this file except in compliance with the License. -package mcpserver_test +package mcpserver import ( "bytes" @@ -21,11 +21,10 @@ import ( "unikraft.com/x/log" - "unikraft.com/cli/pkg/mcpserver" "unikraft.com/cli/pkg/mcpserver/mcptest" ) -const docsIndex = `# Documentation +const testDocsIndex = `# Documentation > Documentation files for Large Language Models @@ -53,7 +52,7 @@ func newDocsSite(t *testing.T, indexStatus int) (*httptest.Server, *atomic.Int32 switch r.URL.Path { case "/docs/llms.txt": w.WriteHeader(indexStatus) - fmt.Fprint(w, docsIndex) + fmt.Fprint(w, testDocsIndex) case "/docs/cli/fields.md": pageRequests.Add(1) fmt.Fprint(w, "# Fields\n\nBody.\n") @@ -80,7 +79,7 @@ func TestDocsResources(t *testing.T) { var logs bytes.Buffer logger := zerolog.New(&logs).Level(zerolog.DebugLevel) ctx := log.WithLogger(t.Context(), &logger) - session := mcptest.ConnectServer(t, ctx, newServer(t, mcpserver.Options{DocsURL: site.URL + "/docs", HTTPClient: site.Client()}).MCP()) + session := mcptest.ConnectServer(t, ctx, newServer(t, Options{DocsURL: site.URL + "/docs", HTTPClient: site.Client()}).MCP()) templates, err := session.ListResourceTemplates(ctx, nil) require.NoError(t, err) @@ -132,7 +131,7 @@ func TestDocsResources(t *testing.T) { func TestDocsIndexUnavailable(t *testing.T) { site, _ := newDocsSite(t, http.StatusInternalServerError) ctx := t.Context() - session := mcptest.ConnectServer(t, ctx, newServer(t, mcpserver.Options{DocsURL: site.URL + "/docs/", HTTPClient: site.Client()}).MCP()) + session := mcptest.ConnectServer(t, ctx, newServer(t, Options{DocsURL: site.URL + "/docs/", HTTPClient: site.Client()}).MCP()) page, err := session.ReadResource(ctx, &mcp.ReadResourceParams{URI: "unikraft://docs/introduction"}) require.NoError(t, err) @@ -144,11 +143,11 @@ func TestDocsIndexUnavailable(t *testing.T) { func TestDocsDisabledAndInvalid(t *testing.T) { ctx := t.Context() - session := mcptest.ConnectServer(t, ctx, newServer(t, mcpserver.Options{}).MCP()) + session := mcptest.ConnectServer(t, ctx, newServer(t, Options{}).MCP()) res, err := session.ListResources(ctx, nil) require.NoError(t, err) assert.Empty(t, res.Resources) - _, err = mcpserver.New(mcpserver.Options{DocsURL: "unikraft.com/docs"}) + _, err = New(Options{DocsURL: "unikraft.com/docs"}) require.ErrorContains(t, err, "invalid documentation URL") } diff --git a/pkg/mcpserver/flags_test.go b/pkg/mcpserver/flags_test.go index 258ce2d13..b84b564e8 100644 --- a/pkg/mcpserver/flags_test.go +++ b/pkg/mcpserver/flags_test.go @@ -3,30 +3,28 @@ // Licensed under the BSD-3-Clause License (the "License"). // You may not use this file except in compliance with the License. -package mcpserver_test +package mcpserver import ( "testing" "github.com/stretchr/testify/assert" - - "unikraft.com/cli/pkg/mcpserver" ) func TestFlagsCheck(t *testing.T) { tests := []struct { - flags mcpserver.Flags + flags Flags err string }{ - {flags: mcpserver.Flags{}}, - {flags: mcpserver.Flags{Listen: "127.0.0.1:8080"}}, - {flags: mcpserver.Flags{Listen: "localhost:8080"}}, - {flags: mcpserver.Flags{Listen: "[::1]:8080"}}, - {flags: mcpserver.Flags{Listen: "0.0.0.0:8080", AllowRemote: true}}, - {flags: mcpserver.Flags{Listen: "0.0.0.0:8080"}, err: "pass --allow-remote"}, - {flags: mcpserver.Flags{Listen: "example.com:8080"}, err: "pass --allow-remote"}, - {flags: mcpserver.Flags{Listen: "localhost"}, err: "invalid listen address"}, - {flags: mcpserver.Flags{Listen: "localhost:http"}, err: "port must be a number"}, + {flags: Flags{}}, + {flags: Flags{Listen: "127.0.0.1:8080"}}, + {flags: Flags{Listen: "localhost:8080"}}, + {flags: Flags{Listen: "[::1]:8080"}}, + {flags: Flags{Listen: "0.0.0.0:8080", AllowRemote: true}}, + {flags: Flags{Listen: "0.0.0.0:8080"}, err: "pass --allow-remote"}, + {flags: Flags{Listen: "example.com:8080"}, err: "pass --allow-remote"}, + {flags: Flags{Listen: "localhost"}, err: "invalid listen address"}, + {flags: Flags{Listen: "localhost:http"}, err: "port must be a number"}, } for _, tt := range tests { t.Run(tt.flags.Listen, func(t *testing.T) { diff --git a/pkg/mcpserver/http.go b/pkg/mcpserver/http.go index fa80c728d..5f35c018c 100644 --- a/pkg/mcpserver/http.go +++ b/pkg/mcpserver/http.go @@ -24,6 +24,7 @@ const HTTPPath = "/mcp" const ( healthPath = "/healthz" readHeaderTimeout = 10 * time.Second + idleTimeout = time.Minute shutdownTimeout = 10 * time.Second ) @@ -47,13 +48,24 @@ func (s *Server) Handler() http.Handler { return http.NewCrossOriginProtection().Handler(mux) } -// Serve serves Handler on l until ctx is cancelled, then stops accepting and -// drains in-flight calls for up to shutdownTimeout. It returns nil after a -// clean shutdown. +// Wrap makes Serve serve mw(Handler()), for a caller that serves more than +// the protocol or checks each request first. A later call replaces mw. +func (s *Server) Wrap(mw func(http.Handler) http.Handler) { + s.wrap = mw +} + +// Serve serves Handler, wrapped by Wrap, on l until ctx is cancelled, then +// stops accepting and drains in-flight calls for up to shutdownTimeout. It +// returns nil after a clean shutdown. func (s *Server) Serve(ctx context.Context, l net.Listener) error { + h := s.Handler() + if s.wrap != nil { + h = s.wrap(h) + } srv := &http.Server{ - Handler: s.Handler(), + Handler: h, ReadHeaderTimeout: readHeaderTimeout, + IdleTimeout: idleTimeout, BaseContext: func(net.Listener) context.Context { return context.WithoutCancel(ctx) }, } diff --git a/pkg/mcpserver/http_test.go b/pkg/mcpserver/http_test.go index 207871642..97f7f01cf 100644 --- a/pkg/mcpserver/http_test.go +++ b/pkg/mcpserver/http_test.go @@ -3,7 +3,7 @@ // Licensed under the BSD-3-Clause License (the "License"). // You may not use this file except in compliance with the License. -package mcpserver_test +package mcpserver import ( "context" @@ -23,27 +23,26 @@ import ( integ "unikraft.com/cli/internal/integration" modelt "unikraft.com/cli/internal/model/testing" - "unikraft.com/cli/pkg/mcpserver" "unikraft.com/cli/pkg/mcpserver/mcptest" modelmcp "unikraft.com/cli/pkg/model/mcp" ) -func newServer(t *testing.T, opts mcpserver.Options) *mcpserver.Server { +func newServer(t *testing.T, opts Options) *Server { t.Helper() opts.Name, opts.Title = "unikraft", "Unikraft Cloud" - srv, err := mcpserver.New(opts) + srv, err := New(opts) require.NoError(t, err) return srv } func TestServe(t *testing.T) { t.Run("http", func(t *testing.T) { - testServe(t, mcpserver.Options{}, "http", http.DefaultClient) + testServe(t, Options{}, "http", http.DefaultClient) }) t.Run("https", func(t *testing.T) { cert := integ.GenerateCert(t, "localhost") dir := t.TempDir() - opts := mcpserver.Options{TLSCertFile: filepath.Join(dir, "cert.pem"), TLSKeyFile: filepath.Join(dir, "key.pem")} + opts := Options{TLSCertFile: filepath.Join(dir, "cert.pem"), TLSKeyFile: filepath.Join(dir, "key.pem")} require.NoError(t, os.WriteFile(opts.TLSCertFile, []byte(cert.Chain), 0o600)) require.NoError(t, os.WriteFile(opts.TLSKeyFile, []byte(cert.Key), 0o600)) client := &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}} @@ -51,7 +50,31 @@ func TestServe(t *testing.T) { }) } -func testServe(t *testing.T, opts mcpserver.Options, scheme string, client *http.Client) { +func TestServeWrap(t *testing.T) { + ctx := t.Context() + srv := newServer(t, Options{}) + srv.Wrap(func(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Wrapped", "yes") + h.ServeHTTP(w, r) + }) + }) + l, err := net.Listen("tcp", "127.0.0.1:0") + require.NoError(t, err) + go func() { _ = srv.Serve(ctx, l) }() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://"+l.Addr().String()+healthPath, nil) + require.NoError(t, err) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + require.NoError(t, resp.Body.Close()) + assert.Equal(t, "yes", resp.Header.Get("X-Wrapped")) + assert.Equal(t, "ok\n", string(body)) +} + +func testServe(t *testing.T, opts Options, scheme string, client *http.Client) { env := modelt.NewTestEnv() env.Add(modelt.TestModel{ID: "1", Name: "a"}) ctx, cancel := context.WithCancel(modelt.WithTestEnv(t.Context(), env)) @@ -63,7 +86,7 @@ func testServe(t *testing.T, opts mcpserver.Options, scheme string, client *http require.NoError(t, err) errc := make(chan error, 1) go func() { errc <- srv.Serve(ctx, l) }() - url := scheme + "://" + l.Addr().String() + mcpserver.HTTPPath + url := scheme + "://" + l.Addr().String() + HTTPPath session := mcptest.Connect(t, &mcp.StreamableClientTransport{Endpoint: url, HTTPClient: client}) res := mcptest.CallTool(t, ctx, session, "test_list", map[string]any{"fields": []string{"name"}}) diff --git a/pkg/mcpserver/server.go b/pkg/mcpserver/server.go index ef4c69618..b07cd3788 100644 --- a/pkg/mcpserver/server.go +++ b/pkg/mcpserver/server.go @@ -36,6 +36,7 @@ type Options struct { type Server struct { srv *mcp.Server opts Options + wrap func(http.Handler) http.Handler } func New(opts Options) (*Server, error) { diff --git a/pkg/model/cmd/cmd.go b/pkg/model/cmd/cmd.go index 5123c86ce..05b314d64 100644 --- a/pkg/model/cmd/cmd.go +++ b/pkg/model/cmd/cmd.go @@ -464,6 +464,17 @@ func (cmd *ModelRemoveCmd[R]) Run(ctx context.Context, stdio xstdio.Stdio, parti } } + // A key can name more than one resource, like the platforms of an image, and Delete removes it once. + seen := make(map[string]struct{}, len(toPrint)) + toPrint = slices.DeleteFunc(slices.Clone(toPrint), func(r model.Model) bool { + key := r.Key().String() + if _, ok := seen[key]; ok { + return true + } + seen[key] = struct{}{} + return false + }) + if _, ok := errors.AsType[model.ErrNotFound](deleteErr); ok { // Delete reports the same missing keys, so only report them once. getErr = withoutNotFound(getErr) diff --git a/pkg/model/cmd/cmd_test.go b/pkg/model/cmd/cmd_test.go index 4e3f8a997..f891f1ee8 100644 --- a/pkg/model/cmd/cmd_test.go +++ b/pkg/model/cmd/cmd_test.go @@ -761,6 +761,25 @@ func TestModelRemoveReportsMissingOnce(t *testing.T) { } } +func TestModelRemovePrintsKeyOnce(t *testing.T) { + env := modelt.NewTestEnv() + env.Add(modelt.TestModel{Name: "web", ID: "id-1"}) + // Like the platforms of one image, the key names two resources. + env.Hooks.Get = func(ctx context.Context, keys []string, next func(context.Context, []string) ([]model.Model, error)) ([]model.Model, error) { + resources, err := next(ctx, keys) + return append(resources, resources...), err + } + ctx := modelt.WithTestEnv(context.Background(), env) + + var out bytes.Buffer + cmd := &ModelRemoveCmd[modelt.TestModel]{ + Targets: []string{"web"}, + Output: Printer{Type: PrinterTypeQuiet}, + } + require.NoError(t, cmd.Run(ctx, testStdio(&out), nil)) + assert.Equal(t, 1, strings.Count(out.String(), "web"), out.String()) +} + func TestPartialResultsOrderWhenCallerPrintsError(t *testing.T) { t.Run("list/table", func(t *testing.T) { env := setupTestEnv() diff --git a/pkg/model/mcp/tools.go b/pkg/model/mcp/tools.go index da2ae8f7c..2f1c8e249 100644 --- a/pkg/model/mcp/tools.go +++ b/pkg/model/mcp/tools.go @@ -10,6 +10,7 @@ import ( "context" "encoding/json/jsontext" "encoding/json/v2" + "errors" "fmt" "io" "maps" @@ -310,25 +311,51 @@ func destructiveAnnotations() *mcp.ToolAnnotations { return &mcp.ToolAnnotations{DestructiveHint: new(true), IdempotentHint: true} } +// MaxOutput is the size limit of the output of a tool call. A server keeps +// the output of each call in memory until the call ends. +const MaxOutput = 1 << 20 + +var errOutputLimit = fmt.Errorf("the output is over %d MiB, and the rest is left out", MaxOutput>>20) + +// limitedBuffer keeps the first MaxOutput bytes, and refuses the rest. +type limitedBuffer struct { + buf bytes.Buffer + over bool +} + +func (b *limitedBuffer) Write(p []byte) (int, error) { + room := MaxOutput - b.buf.Len() + if len(p) <= room { + return b.buf.Write(p) + } + b.over = true + n, _ := b.buf.Write(p[:room]) + return n, errOutputLimit +} + func (ts *Tools) capture(ctx context.Context, structured bool, run func(context.Context, xstdio.Stdio) error) *mcp.CallToolResult { start := time.Now() - var out bytes.Buffer + var out limitedBuffer err := run(ctx, xstdio.Stdio{Stdin: bytes.NewReader(nil), Stdout: &out, Stderr: ts.opts.Stderr}) + // A command can ignore the error of a write, thus the buffer also gives it. + if out.over && !errors.Is(err, errOutputLimit) { + err = errors.Join(err, errOutputLimit) + } msg := "tool call complete" if err != nil { msg = "tool call failed" } log.G(ctx).Debug(). Dur("took", time.Since(start)). - Int("output_bytes", out.Len()). + Int("output_bytes", out.buf.Len()). Err(err). Msg(msg) res := &mcp.CallToolResult{Content: []mcp.Content{}} - if out.Len() > 0 { - res.Content = append(res.Content, &mcp.TextContent{Text: out.String()}) + if out.buf.Len() > 0 { + res.Content = append(res.Content, &mcp.TextContent{Text: out.buf.String()}) var parsed any - if structured && json.Unmarshal(out.Bytes(), &parsed) == nil { + if structured && json.Unmarshal(out.buf.Bytes(), &parsed) == nil { res.StructuredContent = map[string]any{"resources": parsed} } } diff --git a/pkg/model/mcp/tools_test.go b/pkg/model/mcp/tools_test.go index 1e9a50271..9f5b6f50e 100644 --- a/pkg/model/mcp/tools_test.go +++ b/pkg/model/mcp/tools_test.go @@ -24,6 +24,7 @@ import ( modelt "unikraft.com/cli/internal/model/testing" "unikraft.com/cli/pkg/mcpserver/mcptest" modelmcp "unikraft.com/cli/pkg/model/mcp" + xstdio "unikraft.com/x/stdio" ) func newServer(t *testing.T, ctx context.Context, opts modelmcp.Options) *mcp.Server { @@ -220,3 +221,29 @@ func TestCallLogging(t *testing.T) { assert.Contains(t, out, `"error":"unknown fields: [nope]","message":"tool call failed"`) assert.Contains(t, out, `"tool":"test_delete","error":"invalid arguments: validating root: required: missing properties: [\"keys\"]","message":"tool call rejected"`) } + +func TestCallOutputLimit(t *testing.T) { + ctx := t.Context() + srv := mcp.NewServer(&mcp.Implementation{Name: "test"}, nil) + type args struct { + IgnoreErrors bool `json:"ignore_errors"` + } + line := bytes.Repeat([]byte("yes\n"), 3000) + require.NoError(t, modelmcp.New(srv, modelmcp.Options{}).AddTool("test", &mcp.Tool{Name: "test_yes", Annotations: modelmcp.ReadOnlyAnnotations()}, false, func(_ context.Context, in args, stdio xstdio.Stdio) error { + for range 2 * modelmcp.MaxOutput / len(line) { + if _, err := stdio.Stdout.Write(line); err != nil && !in.IgnoreErrors { + return err + } + } + return nil + })) + session := mcptest.ConnectServer(t, ctx, srv) + + for _, ignore := range []bool{false, true} { + res := mcptest.CallTool(t, ctx, session, "test_yes", map[string]any{"ignore_errors": ignore}) + assert.True(t, res.IsError) + require.Len(t, res.Content, 2) + assert.Len(t, res.Content[0].(*mcp.TextContent).Text, modelmcp.MaxOutput) + assert.Equal(t, "the output is over 1 MiB, and the rest is left out", res.Content[1].(*mcp.TextContent).Text) + } +} diff --git a/pkg/model/tui/panel_reader.go b/pkg/model/tui/panel_reader.go index 843dfbe38..5a5afb143 100644 --- a/pkg/model/tui/panel_reader.go +++ b/pkg/model/tui/panel_reader.go @@ -29,11 +29,15 @@ const ( // ReaderFunc is a function that returns a reader. Used for lazy initialization. type ReaderFunc func(ctx context.Context) (io.ReadCloser, error) -// readerContentMsg is sent when new content is available from the reader -type readerContentMsg struct{} +// readerContentMsg is sent when new content is available from the reader. +// A panel stack sends it to every panel, so panel tells which one it is for. +type readerContentMsg struct { + panel *ReaderPanel +} -// readerReadyMsg is sent when the reader is ready +// readerReadyMsg is sent when the reader of panel is ready. type readerReadyMsg struct { + panel *ReaderPanel reader io.ReadCloser err error } @@ -46,6 +50,7 @@ type ReaderPanel struct { reader io.ReadCloser readerFunc ReaderFunc follow bool + onFocus bool viewport viewport.Model buf bytes.Buffer @@ -77,9 +82,19 @@ func NewReaderPanelFunc(ctx context.Context, title string, readerFunc ReaderFunc } } +// LoadOnFocus makes the panel call its ReaderFunc when it first gets the focus, +// not when it starts. Use it for a reader that is expensive to get. +func (p *ReaderPanel) LoadOnFocus() *ReaderPanel { + p.onFocus = true + return p +} + func (p *ReaderPanel) Init() tea.Cmd { // If we have a readerFunc, fetch the reader lazily if p.readerFunc != nil && !p.ready { + if p.onFocus { + return nil + } return p.fetchReader() } // Otherwise start reading immediately @@ -105,9 +120,16 @@ func (p *ReaderPanel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { case uitui.PanelFocusMsg: p.focused = msg.Focused + if p.onFocus && p.focused && p.readerFunc != nil && !p.ready { + p.onFocus = false + return p, p.fetchReader() + } return p, nil case readerReadyMsg: + if msg.panel != p { + return p, nil + } if msg.err != nil { p.mu.Lock() p.err = msg.err @@ -123,6 +145,9 @@ func (p *ReaderPanel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { return p, p.pollCmd() case readerContentMsg: + if msg.panel != p { + return p, nil + } p.mu.Lock() newContent := p.buf.Len() != p.lastLen p.lastLen = p.buf.Len() @@ -178,8 +203,11 @@ func (p *ReaderPanel) View() tea.View { } if !p.ready { - body := styles.Hint.Render("Connecting...") - return tea.NewView(body) + hint := "Connecting..." + if p.onFocus { + hint = "Focus this panel to load." + } + return tea.NewView(styles.Hint.Render(hint)) } p.mu.Lock() @@ -251,13 +279,13 @@ func (p *ReaderPanel) Close() error { func (p *ReaderPanel) fetchReader() tea.Cmd { return func() tea.Msg { reader, err := p.readerFunc(p.ctx) - return readerReadyMsg{reader: reader, err: err} + return readerReadyMsg{panel: p, reader: reader, err: err} } } func (p *ReaderPanel) pollCmd() tea.Cmd { return tea.Tick(readerPollInterval, func(time.Time) tea.Msg { - return readerContentMsg{} + return readerContentMsg{panel: p} }) } diff --git a/pkg/model/tui/tui_test.go b/pkg/model/tui/tui_test.go index 26a39ee35..b4486a450 100644 --- a/pkg/model/tui/tui_test.go +++ b/pkg/model/tui/tui_test.go @@ -10,6 +10,7 @@ import ( "io" "os" "strings" + "sync/atomic" "testing" "time" @@ -42,6 +43,26 @@ func (subpanelTestModel) Subpanels(ctx context.Context, key string) []tea.Model return []tea.Model{tui.NewReaderPanelFunc(ctx, "Logs", readerFunc, true)} } +type lazySubpanelTestModel struct { + modelt.TestModel +} + +var lazyLoads atomic.Int32 + +func (lazySubpanelTestModel) Subpanels(ctx context.Context, key string) []tea.Model { + logs := func(ctx context.Context) (io.ReadCloser, error) { + return io.NopCloser(strings.NewReader("sample logs\n")), nil + } + history := func(ctx context.Context) (io.ReadCloser, error) { + lazyLoads.Add(1) + return io.NopCloser(strings.NewReader("sample history\n")), nil + } + return []tea.Model{ + tui.NewReaderPanelFunc(ctx, "Logs", logs, true), + tui.NewReaderPanelFunc(ctx, "History", history, false).LoadOnFocus(), + } +} + func setupTestEnv() *modelt.TestEnv { env := modelt.NewTestEnv() for _, r := range modelt.BaseTestStore() { @@ -190,3 +211,35 @@ func TestTUIDetailWithSubpanel(t *testing.T) { golden.Assert(t, output, t.Name(), "\n"+output) } + +func TestTUIDetailWithLazySubpanel(t *testing.T) { + lazyLoads.Store(0) + env := setupTestEnv() + ctx := modelt.WithTestEnv(context.Background(), env) + + registry := model.NewRegistry() + desc := registry.Register(lazySubpanelTestModel{}, lazySubpanelTestModel{}) + m, err := tui.New(ctx, registry, tui.Home{}, desc.Name, "") + require.NoError(t, err) + runner := testkit.New(m, 80, 40) + defer runner.Stop() + + _, err = runner.WaitUntilSnapshot(2*time.Second, 0, func(s string) bool { + return strings.Contains(s, "id-test1") && !strings.Contains(s, "Loading...") + }) + require.NoErrorf(t, err, "wait failed: %v\n\nlast snapshot:\n%s", err, runner.Snapshot()) + + runner.PressKeys(tea.Key{Code: tea.KeyEnter}) + _, err = runner.WaitUntilSnapshot(2*time.Second, 0, func(s string) bool { + return strings.Contains(s, "sample logs") && strings.Contains(s, "Focus this panel to load.") + }) + require.NoErrorf(t, err, "wait failed: %v\n\nlast snapshot:\n%s", err, runner.Snapshot()) + require.Zero(t, lazyLoads.Load(), "the panel loads only on focus") + + runner.PressKeys(tea.Key{Code: tea.KeyTab}, tea.Key{Code: tea.KeyTab}) + _, err = runner.WaitUntilSnapshot(2*time.Second, 0, func(s string) bool { + return strings.Contains(s, "sample logs") && strings.Contains(s, "sample history") + }) + require.NoErrorf(t, err, "wait failed: %v\n\nlast snapshot:\n%s", err, runner.Snapshot()) + require.EqualValues(t, 1, lazyLoads.Load()) +} diff --git a/pkg/model/value/format.go b/pkg/model/value/format.go index 0e57d9b51..b51184ec9 100644 --- a/pkg/model/value/format.go +++ b/pkg/model/value/format.go @@ -7,6 +7,7 @@ package value import ( "encoding" + "encoding/json" "fmt" "iter" "reflect" @@ -124,14 +125,19 @@ var ( renderer = reflect.TypeFor[Renderer]() ) -// walkFields gives each leaf field of struct v with its dotted key. -// Parse can then read the rendered nested fields back. +// walkFields gives each leaf field of struct v with its dotted key, and each +// map entry as one leaf. Parse can then read the rendered nested fields back. func walkFields(v reflect.Value, prefix string) iter.Seq2[string, reflect.Value] { return func(yield func(string, reflect.Value) bool) { for field := range namedFields(v) { path := prefix + field.Name - if sub, ok := field.structValue(false); ok && - !field.implements(renderer, stringer, textMarshaler) { + if field.implements(renderer, stringer, textMarshaler) { + if !yield(path, field.Value) { + return + } + continue + } + if sub, ok := field.structValue(false); ok { for path, leaf := range walkFields(sub, path+".") { if !yield(path, leaf) { return @@ -139,9 +145,44 @@ func walkFields(v reflect.Value, prefix string) iter.Seq2[string, reflect.Value] } continue } + if m := field.Value; m.Kind() == reflect.Map && m.Type().Key().Kind() == reflect.String { + if !dottable(m) { + if b, err := json.Marshal(m.Interface()); err == nil { + if !yield(path, reflect.ValueOf(string(b))) { + return + } + continue + } + } + keys := m.MapKeys() + slices.SortFunc(keys, func(a, b reflect.Value) int { + return strings.Compare(a.String(), b.String()) + }) + for _, key := range keys { + if !yield(path+"."+key.String(), m.MapIndex(key)) { + return + } + } + continue + } if !yield(path, field.Value) { return } } } } + +// dottable reports if Parse reads back each entry of map m as one key.K=V pair. +func dottable(m reflect.Value) bool { + for it := m.MapRange(); it.Next(); { + if strings.ContainsAny(it.Key().String(), ",=") { + return false + } + v, err := Render(it.Value().Interface(), RenderOpts{}) + if err != nil || v == "" || v != strings.TrimSpace(v) || + strings.Contains(v, ",") || strings.ContainsAny(v[:1], `{["`) { + return false + } + } + return true +} diff --git a/pkg/model/value/format_test.go b/pkg/model/value/format_test.go index fb2624261..12832cee5 100644 --- a/pkg/model/value/format_test.go +++ b/pkg/model/value/format_test.go @@ -119,6 +119,28 @@ func TestFormatNestedPaths(t *testing.T) { assert.Equal(t, want, got, "rendered as %q", rendered) }) + for _, tt := range []struct { + name string + meta map[string]string + rendered string + }{ + {"map entries render as dotted keys and round-trip", map[string]string{"b": "2", "a": "1"}, "meta.a=1, meta.b=2"}, + {"map with a comma renders as JSON and round-trips", map[string]string{"a": "1,2", "b": "2"}, `meta={"a":"1,2","b":"2"}`}, + {"map with an empty value renders as JSON and round-trips", map[string]string{"a": ""}, `meta={"a":""}`}, + } { + t.Run(tt.name, func(t *testing.T) { + want := testStructCollections{Meta: tt.meta} + + rendered, err := Render(&want, RenderOpts{}) + require.NoError(t, err) + assert.Equal(t, tt.rendered, rendered) + + got, err := Parse[testStructCollections]([]string{rendered}) + require.NoError(t, err) + assert.Equal(t, want, got) + }) + } + t.Run("opacity follows MarshalText alone", func(t *testing.T) { v := testStructNested{} v.WriteTo.Raw = "opaque" diff --git a/pkg/model/value/parse.go b/pkg/model/value/parse.go index 5aee4e0e0..d666d18aa 100644 --- a/pkg/model/value/parse.go +++ b/pkg/model/value/parse.go @@ -291,18 +291,43 @@ func parseReflect(input []string, value reflect.Value) error { var textUnmarshaler = reflect.TypeFor[encoding.TextUnmarshaler]() -// assignField sets one key=value pair on struct s. A dotted key goes into the -// named struct field. It reports if a field matched the key. +// assignField sets one key=value pair on struct s. Dotted keys go into struct fields +// and map entries, and map values merge. It reports if a field matched the key. func assignField(s reflect.Value, k, v string) (bool, error) { head, rest, dotted := strings.Cut(k, ".") for field := range namedFields(s) { if k == field.Name { - return true, parseReflect([]string{v}, field.Value) + m := field.Value + if m.Kind() != reflect.Map || m.IsNil() { + return true, parseReflect([]string{v}, m) + } + parsed := reflect.New(m.Type()).Elem() + if err := parseReflect([]string{v}, parsed); err != nil { + return true, err + } + for entry := parsed.MapRange(); entry.Next(); { + m.SetMapIndex(entry.Key(), entry.Value()) + } + return true, nil } if !dotted || head != field.Name || field.implements(textUnmarshaler) { continue } + if m := field.Value; m.Kind() == reflect.Map && m.Type().Key().Kind() == reflect.String { + if rest == "" { + return true, fmt.Errorf("missing map key in %q", k) + } + elem := reflect.New(m.Type().Elem()).Elem() + if err := parseReflect([]string{v}, elem); err != nil { + return true, err + } + if m.IsNil() { + m.Set(reflect.MakeMap(m.Type())) + } + m.SetMapIndex(reflect.ValueOf(rest).Convert(m.Type().Key()), elem) + return true, nil + } if sub, ok := field.structValue(true); ok { return assignField(sub, rest, v) } diff --git a/pkg/model/value/parse_test.go b/pkg/model/value/parse_test.go index 0e57f1be6..a6b027590 100644 --- a/pkg/model/value/parse_test.go +++ b/pkg/model/value/parse_test.go @@ -187,6 +187,17 @@ func TestParseNestedPaths(t *testing.T) { assert.False(t, *got.Ptr.Flag) }) + t.Run("map field merges dotted keys and the JSON form", func(t *testing.T) { + got, err := Parse[testStructCollections]([]string{`meta.a=1,meta={"b":"2"},meta.c=3`}) + require.NoError(t, err) + assert.Equal(t, testStructCollections{Meta: map[string]string{"a": "1", "b": "2", "c": "3"}}, got) + }) + + t.Run("map field needs a key after the dot", func(t *testing.T) { + _, err := Parse[testStructCollections]([]string{"meta.=1"}) + require.ErrorContains(t, err, "missing map key") + }) + t.Run("unknown nested key reports the whole path", func(t *testing.T) { _, err := Parse[testStructNested]([]string{"inner.bogus=1"}) require.ErrorContains(t, err, "unknown fields: [inner.bogus]")