From 57a8e5e436dabf88e6488201831009fbefc20339 Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Thu, 12 Nov 2026 12:10:59 +0000 Subject: [PATCH 01/55] docs: Document the container image Signed-off-by: Justin Chadwell --- README.md | 45 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/README.md b/README.md index c57e5495..d95bd4a9 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,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 From c3ce36c560c16b9ff020e507b4e027e79a7d8814 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Mon, 16 Nov 2026 17:22:58 +0200 Subject: [PATCH 02/55] refactor(config)!: Group the registry settings The registry mirror was a flat profile key, so no other registry setting could go next to it. `registry_mirror` is now `registry.mirror`. The old key is ignored and dropped on the next save. Signed-off-by: Cezar Craciunoiu --- cmd/unikraft/testdata/TestHelp/config | 12 +++++----- internal/config/config_test.go | 33 +++++++++++++++++++++++++++ internal/config/profile.go | 12 +++++++--- internal/images/resolver.go | 4 ++-- 4 files changed, 50 insertions(+), 11 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/config b/cmd/unikraft/testdata/TestHelp/config index 6edf20c8..f5457280 100644 --- a/cmd/unikraft/testdata/TestHelp/config +++ b/cmd/unikraft/testdata/TestHelp/config @@ -14,9 +14,9 @@ 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.mirror, 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 +59,9 @@ 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.mirror, 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/internal/config/config_test.go b/internal/config/config_test.go index 69eecae7..9e2d69f9 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -472,6 +472,39 @@ 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: + mirror: https://console.example.com/proxy/registry + 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{ + Mirror: "https://console.example.com/proxy/registry", + }, 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 8acaf415..b7afbf0c 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -82,15 +82,21 @@ 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 { + // 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."` +} + func (p Profile) GetDefaultMetro() string { if p.MetroDefault != "" { return p.MetroDefault diff --git a/internal/images/resolver.go b/internal/images/resolver.go index 4da6d396..b998a87d 100644 --- a/internal/images/resolver.go +++ b/internal/images/resolver.go @@ -109,8 +109,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.Registry.Mirror) } return docker.ResolverOptions{ From ecfef7227641406fc6ae53cc82588e63fa45780f Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Mon, 16 Nov 2026 17:23:16 +0200 Subject: [PATCH 03/55] fix(images): Skip TLS for tokens of insecure hosts Token requests did not use the insecure client, so a self-signed registry failed at the token step. The authorizer uses the insecure client for the insecure hosts, also for `--insecure-registry`, `--insecure-registries` and the metro index `insecure`. Signed-off-by: Cezar Craciunoiu --- internal/images/resolver.go | 21 +++++++++++++++++- internal/images/resolver_test.go | 38 ++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 internal/images/resolver_test.go diff --git a/internal/images/resolver.go b/internal/images/resolver.go index b998a87d..e6f81698 100644 --- a/internal/images/resolver.go +++ b/internal/images/resolver.go @@ -66,10 +66,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 @@ -142,6 +143,24 @@ func mirrorHosts(hosts docker.RegistryHosts, mirror string) docker.RegistryHosts } } +// 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 diff --git a/internal/images/resolver_test.go b/internal/images/resolver_test.go new file mode 100644 index 00000000..e54d2229 --- /dev/null +++ b/internal/images/resolver_test.go @@ -0,0 +1,38 @@ +// 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" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +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) +} From c8bbac23586ea18b6314f612984583ca9d889ad9 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Mon, 16 Nov 2026 17:23:38 +0200 Subject: [PATCH 04/55] feat(images): Add registry host and insecure Only unikraft.io and index.unikraft.io got the profile token and the mirror, so no other registry host could get them. `registry.host` adds a host that gets both, and `registry.insecure` skips TLS for these hosts. Signed-off-by: Cezar Craciunoiu --- cmd/unikraft/testdata/TestHelp/config | 6 ++-- internal/config/config_test.go | 6 +++- internal/config/profile.go | 4 +++ internal/images/resolver.go | 24 ++++++++++--- internal/images/resolver_test.go | 50 +++++++++++++++++++++++++++ 5 files changed, 82 insertions(+), 8 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/config b/cmd/unikraft/testdata/TestHelp/config index f5457280..e372ba9d 100644 --- a/cmd/unikraft/testdata/TestHelp/config +++ b/cmd/unikraft/testdata/TestHelp/config @@ -15,7 +15,8 @@ Fields: profiles, profiles.*, profiles.*.name, profiles.*.type, profiles.*.token, profiles.*.organization, profiles.*.user-uuid, profiles.*.organization-uuid, profiles.*.control-plane, profiles.*.insecure, profiles.*.registry, - profiles.*.registry.mirror, profiles.*.build-url, profiles.*.metros, + 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 @@ -60,7 +61,8 @@ Fields: profiles, profiles.*, profiles.*.name, profiles.*.type, profiles.*.token, profiles.*.organization, profiles.*.user-uuid, profiles.*.organization-uuid, profiles.*.control-plane, profiles.*.insecure, profiles.*.registry, - profiles.*.registry.mirror, profiles.*.build-url, profiles.*.metros, + 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/internal/config/config_test.go b/internal/config/config_test.go index 9e2d69f9..5c677af5 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -483,7 +483,9 @@ profiles: 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 @@ -496,7 +498,9 @@ profiles: require.NoError(t, err) assert.Equal(t, Registry{ - Mirror: "https://console.example.com/proxy/registry", + Host: "harbor.example:8083", + Mirror: "https://console.example.com/proxy/registry", + Insecure: true, }, config.Profiles["default"].Registry) require.NoError(t, config.Save()) diff --git a/internal/config/profile.go b/internal/config/profile.go index b7afbf0c..b462f997 100644 --- a/internal/config/profile.go +++ b/internal/config/profile.go @@ -93,8 +93,12 @@ type Profile struct { // 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 { diff --git a/internal/images/resolver.go b/internal/images/resolver.go index e6f81698..46fba9b2 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 @@ -111,7 +114,7 @@ func resolverOptions(profile *config.Profile, insecureRegistries []string, allIn }))...), ) if profile != nil && profile.Registry.Mirror != "" { - hosts = mirrorHosts(hosts, profile.Registry.Mirror) + hosts = mirrorHosts(hosts, profile) } return docker.ResolverOptions{ @@ -120,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 { @@ -132,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") @@ -143,6 +148,15 @@ 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) @@ -203,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 index e54d2229..41f28466 100644 --- a/internal/images/resolver_test.go +++ b/internal/images/resolver_test.go @@ -7,6 +7,7 @@ package images import ( "crypto/x509" + "encoding/base64" "net/http" "net/http/httptest" "net/url" @@ -14,8 +15,57 @@ import ( "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() From c51f9ac49c45bdb9a03fcd45285273c2bc5cd068 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Mon, 16 Nov 2026 17:23:45 +0200 Subject: [PATCH 05/55] feat(login): Store the control plane registry Login ignored the registry host that the control plane returns. Login stores it in `registry.host`. It keeps the old value only if the response has none and the control plane is the same. Signed-off-by: Cezar Craciunoiu --- internal/cmd/login/login.go | 7 ++- internal/cmd/login/login_test.go | 80 ++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 internal/cmd/login/login_test.go diff --git a/internal/cmd/login/login.go b/internal/cmd/login/login.go index 60684ab0..38e39f64 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 00000000..7c36ab24 --- /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) + }) + } +} From f77c0b6aa980b863f35408e6d10c1707ba1c1368 Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Tue, 17 Nov 2026 09:04:05 +0000 Subject: [PATCH 06/55] ci: Pin third-party actions by commit A tag can be moved to any commit, so what we run can change under us without a PR. Pin each one by commit instead, with the version in a comment, which Dependabot keeps updating. Signed-off-by: Justin Chadwell --- .github/workflows/actionlint.yaml | 2 +- .github/workflows/build.yaml | 10 +++++----- .github/workflows/check-pr.yaml | 2 +- .github/workflows/check-static.yaml | 8 ++++---- .github/workflows/docs.yaml | 12 ++++++------ .github/workflows/mirror.yaml | 2 +- .github/workflows/release.yaml | 12 ++++++------ .github/workflows/test.yaml | 28 ++++++++++++++-------------- 8 files changed, 38 insertions(+), 38 deletions(-) diff --git a/.github/workflows/actionlint.yaml b/.github/workflows/actionlint.yaml index ea1cd7e3..c33d136e 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 1f55e721..ac225798 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 1f40de4b..0499f84a 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 fa97e4b5..fc8792be 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 5dedcf7e..04349f1e 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 410b4189..7e29b44c 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 dfe1c459..d6b1aa14 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 }} diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 8c97a4a1..3385c751 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,21 +88,21 @@ 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 + uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0 with: platforms: arm64 @@ -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 }} @@ -184,14 +184,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' @@ -199,7 +199,7 @@ jobs: # 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 @@ -219,7 +219,7 @@ jobs: } >>"$GITHUB_OUTPUT" - name: Go caches - uses: actions/cache@v6 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 with: path: | ${{ steps.goenv.outputs.cache }} From 51baad3adbe1514ddea43f3c44bfcb9413177fb6 Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Tue, 17 Nov 2026 09:07:13 +0000 Subject: [PATCH 07/55] ci: Pin images by digest A tag can be pushed over, so what we build from can change under us without a PR. Pin the golang and alpine images by digest, and alpine to the patch release its tag points at today. And drop the syntax line. That pulled the latest dockerfile frontend at build time, and the one built into buildkit already has everything we use. Signed-off-by: Justin Chadwell --- .goreleaser.Dockerfile | 2 +- Dockerfile | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/.goreleaser.Dockerfile b/.goreleaser.Dockerfile index 0f0a9506..7fed6a73 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/Dockerfile b/Dockerfile index cfbeaeff..6c940a52 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"] From 65b41e86a60dc2d625e487afed19bf6fe562a04a Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Tue, 17 Nov 2026 09:07:25 +0000 Subject: [PATCH 08/55] ci(release): Pin the goreleaser version The action installed whatever goreleaser release was latest, so a new release ran in our CI without a PR. Pin the one it resolves to today. Signed-off-by: Justin Chadwell --- .github/workflows/release.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/release.yaml b/.github/workflows/release.yaml index d6b1aa14..8f328ca6 100644 --- a/.github/workflows/release.yaml +++ b/.github/workflows/release.yaml @@ -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 From f2fe387beceae64637f02bf81b56893ccb0d5dea Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Tue, 17 Nov 2026 11:47:46 +0200 Subject: [PATCH 09/55] feat(mcpserver): Export the MCP server Other CLIs cannot import the MCP tools of the CLI, since newMCPServer and the config are under internal/. So add pkg/mcpserver/cli, with New for the server of unikraft mcp and WithToken for the profile of one request. A config with no file is not read again on each tool call. Signed-off-by: Dragos Gheorghioiu --- AGENTS.md | 2 +- internal/cmd/mcp.go | 8 +++--- internal/cmd/mcp_test.go | 32 +++++++++++++++------- pkg/mcpserver/cli/cli.go | 51 +++++++++++++++++++++++++++++++++++ pkg/mcpserver/cli/cli_test.go | 39 +++++++++++++++++++++++++++ 5 files changed, 119 insertions(+), 13 deletions(-) create mode 100644 pkg/mcpserver/cli/cli.go create mode 100644 pkg/mcpserver/cli/cli_test.go diff --git a/AGENTS.md b/AGENTS.md index f103a1d2..1958e597 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/internal/cmd/mcp.go b/internal/cmd/mcp.go index de4fce76..8666a7d8 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 } @@ -237,7 +239,7 @@ func newMCPServer(ctx context.Context, stderr io.Writer, partition *model.Partit 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 bf92b7c6..ed245a58 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/pkg/mcpserver/cli/cli.go b/pkg/mcpserver/cli/cli.go new file mode 100644 index 00000000..c9d7c36c --- /dev/null +++ b/pkg/mcpserver/cli/cli.go @@ -0,0 +1,51 @@ +// 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" + + "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. +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") + } + return cmd.NewMCPServer(ctx, os.Stderr, nil, cmd.MCPCmd{DocsURL: branding.DocsURL, Flags: flags}) +} + +// 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 00000000..eac9b04f --- /dev/null +++ b/pkg/mcpserver/cli/cli_test.go @@ -0,0 +1,39 @@ +// 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 ( + "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 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) +} From 151221b685ceb4c425fb5d40ce77de43fc4f6129 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Tue, 17 Nov 2026 15:42:44 +0200 Subject: [PATCH 10/55] test(mcpserver): Test from inside the package The tests of pkg/mcpserver were in package mcpserver_test, while most tests of the CLI are in the package that they test. So move them into package mcpserver. The test index is now testDocsIndex, since docs.go has a docsIndex. Signed-off-by: Dragos Gheorghioiu --- pkg/mcpserver/docs_test.go | 15 +++++++-------- pkg/mcpserver/flags_test.go | 24 +++++++++++------------- pkg/mcpserver/http_test.go | 15 +++++++-------- 3 files changed, 25 insertions(+), 29 deletions(-) diff --git a/pkg/mcpserver/docs_test.go b/pkg/mcpserver/docs_test.go index 9466fe8e..b10a61c2 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 258ce2d1..b84b564e 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_test.go b/pkg/mcpserver/http_test.go index 20787164..b9471b94 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,7 @@ func TestServe(t *testing.T) { }) } -func testServe(t *testing.T, opts mcpserver.Options, scheme string, client *http.Client) { +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 +62,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"}}) From 6864de95fcf6cc4ab7b4f3729cf4917c5d24a985 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Tue, 17 Nov 2026 16:05:09 +0200 Subject: [PATCH 11/55] ci: Log in to Docker Hub before the QEMU setup The QEMU setup pulls its binfmt image from Docker Hub. It ran before the login, so the pull was anonymous and could hit the pull rate limit. Move the login above the QEMU setup in both integration jobs. Signed-off-by: Dragos Gheorghioiu --- .github/workflows/test.yaml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 3385c751..38be1d37 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -99,6 +99,12 @@ jobs: 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 @@ -106,12 +112,6 @@ jobs: 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: | @@ -195,6 +195,12 @@ jobs: 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 @@ -203,12 +209,6 @@ jobs: 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: | From dc2ffbfff4d8c9100b172f1cf7df7f427e8d0306 Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Tue, 17 Nov 2026 16:41:00 +0000 Subject: [PATCH 12/55] gomod(deps): Bump brotli to v1.3.0 Scanners flag v1.1.1 for CVE-2026-111497, but that's in the C brotli decoder, not this Go port - the version number just happens to land in the affected range. So bump it out of that range to stop the false positive. Signed-off-by: Justin Chadwell --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 4f4e17a6..0a1899b3 100644 --- a/go.mod +++ b/go.mod @@ -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 diff --git a/go.sum b/go.sum index 7d8e7494..726e24b0 100644 --- a/go.sum +++ b/go.sum @@ -32,8 +32,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= From 1d00289078d9ef33f0523bff405a6a7737c99069 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Mon, 16 Nov 2026 17:19:11 +0200 Subject: [PATCH 13/55] feat(cmd): Add UDP services A UDP port could not be published: `-p 53:53/udp` sent `udp` as a handler, and the API rejected it. Take the protocol and IP as `53:53/udp@IP` in --service and --publish. A plain TCP port sends the same request as before, and get shows the protocol and IP of each port. Signed-off-by: Cezar Craciunoiu --- .github/workflows/test.yaml | 1 + cmd/unikraft/integration/service_test.go | 57 +++++++++++++ cmd/unikraft/testdata/TestHelp/instances | 33 +++++--- cmd/unikraft/testdata/TestHelp/run | 11 ++- cmd/unikraft/testdata/TestHelp/services | 42 ++++++---- internal/cmd/instances.go | 8 +- internal/cmd/marshal_test.go | 24 ++++++ internal/cmd/output_test.go | 8 ++ internal/cmd/services.go | 92 ++++++++++++++------- internal/cmd/services_internal_test.go | 47 +++++++++++ internal/cmd/testdata/TestOutput/services | 98 ++++++++++++++++++++++- 11 files changed, 355 insertions(+), 66 deletions(-) create mode 100644 internal/cmd/services_internal_test.go diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 8c97a4a1..9b375dfe 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -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. diff --git a/cmd/unikraft/integration/service_test.go b/cmd/unikraft/integration/service_test.go index ffe07f94..49dc0ce1 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/instances b/cmd/unikraft/testdata/TestHelp/instances index 6c846940..ad4c1642 100644 --- a/cmd/unikraft/testdata/TestHelp/instances +++ b/cmd/unikraft/testdata/TestHelp/instances @@ -583,12 +583,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 @@ -852,12 +855,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 @@ -1107,12 +1113,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 diff --git a/cmd/unikraft/testdata/TestHelp/run b/cmd/unikraft/testdata/TestHelp/run index 14ae617a..b3ead4b5 100644 --- a/cmd/unikraft/testdata/TestHelp/run +++ b/cmd/unikraft/testdata/TestHelp/run @@ -172,12 +172,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 diff --git a/cmd/unikraft/testdata/TestHelp/services b/cmd/unikraft/testdata/TestHelp/services index 542cc4af..5bbce764 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/internal/cmd/instances.go b/internal/cmd/instances.go index 2da4b35b..d058e911 100644 --- a/internal/cmd/instances.go +++ b/internal/cmd/instances.go @@ -259,7 +259,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."` @@ -1437,11 +1437,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": diff --git a/internal/cmd/marshal_test.go b/internal/cmd/marshal_test.go index fb416b1c..3fa05c0a 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/output_test.go b/internal/cmd/output_test.go index d16a927c..49f09786 100644 --- a/internal/cmd/output_test.go +++ b/internal/cmd/output_test.go @@ -324,13 +324,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/services.go b/internal/cmd/services.go index ff588fae..e7251936 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 00000000..7164bf7a --- /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/services b/internal/cmd/testdata/TestOutput/services index 57f85bf2..4c7876f6 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, From 25a924526221bd45bfd5ed9914526c211ce3c51f Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:10:01 +0200 Subject: [PATCH 14/55] fix(cmd): Read the build URL env on bare --remote A bare --remote skipped UNIKRAFT_BUILD_URL, so the build went to the build_url of the profile, or to the public service. Use the variable before the profile when the flag has no value. Closes: TOOL-1875 Signed-off-by: Dragos Gheorghioiu --- internal/cmd/build_remote.go | 2 +- internal/cmd/build_remote_test.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index 9ef4afc1..c87493db 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -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 { diff --git a/internal/cmd/build_remote_test.go b/internal/cmd/build_remote_test.go index 0a23c7d7..4cdec9bb 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() From ab7a8ecab942cbb4135b3c525f3e278e9dc63fb4 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:10:33 +0200 Subject: [PATCH 15/55] fix(cmd): Give builder commands a default URL The builder commands failed without a build_url in the profile, while build --remote fell back to the public build service. Fall back to https://controlplane.unikraft.com in the builder commands too. Closes: TOOL-1886 Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/testdata/TestHelp/build | 12 ++++++------ internal/cmd/builder.go | 18 +++++++----------- internal/cmd/builder_test.go | 7 +------ 3 files changed, 14 insertions(+), 23 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index b645c0ed..0ccbeabc 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -145,7 +145,7 @@ 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. Global flags: -h, --help @@ -198,7 +198,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 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. Global flags: -h, --help @@ -259,7 +259,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 @@ -310,7 +310,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 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. Global flags: -h, --help @@ -349,7 +349,7 @@ 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. Global flags: -h, --help @@ -388,7 +388,7 @@ 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. Global flags: -h, --help diff --git a/internal/cmd/builder.go b/internal/cmd/builder.go index 9bc6c0fb..253ad451 100644 --- a/internal/cmd/builder.go +++ b/internal/cmd/builder.go @@ -177,7 +177,7 @@ type builderRemoteKey struct{} 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."` } func (c *BuilderGetCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { @@ -186,7 +186,7 @@ func (c *BuilderGetCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { 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 (c *BuilderListCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { @@ -195,7 +195,7 @@ 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."` } func (c *BuilderDeleteCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { @@ -207,7 +207,7 @@ 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."` } func (BuilderCreateCmd) Examples() []kingkong.Example { @@ -221,7 +221,7 @@ 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."` } func (BuilderDuCmd) Examples() []kingkong.Example { @@ -235,7 +235,7 @@ 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."` } func (BuilderPruneCmd) Examples() []kingkong.Example { @@ -301,11 +301,7 @@ 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) - } - return buildapi.New(url, buildapi.WithToken(profile.Token)) + return buildapi.New(cmp.Or(url, profile.BuildURL, buildapi.DefaultServer), buildapi.WithToken(profile.Token)) } // builderClientOf returns the client of the build service in ctx, and the current profile. diff --git a/internal/cmd/builder_test.go b/internal/cmd/builder_test.go index 5d0aa696..0da89488 100644 --- a/internal/cmd/builder_test.go +++ b/internal/cmd/builder_test.go @@ -30,12 +30,8 @@ func TestBuilderBuildURL(t *testing.T) { 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) @@ -45,5 +41,4 @@ func TestBuilderBuildURL(t *testing.T) { 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") } From 8da8c243eca68429916c4fe54af3815f6fbac73b Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:11:00 +0200 Subject: [PATCH 16/55] fix(cmd): Refuse plain HTTP in builder commands The builder commands took an http:// build service and sent the bearer token of the profile in plain text. unikraft build refused such a URL. Share the scheme check of unikraft build with the builder commands. Closes: TOOL-1897 Signed-off-by: Dragos Gheorghioiu --- internal/cmd/build_remote.go | 7 +------ internal/cmd/builder.go | 18 +++++++++++++++++- internal/cmd/builder_test.go | 14 ++------------ 3 files changed, 20 insertions(+), 19 deletions(-) diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index c87493db..6ce0b956 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -14,7 +14,6 @@ import ( "encoding/hex" "errors" "fmt" - "net/url" "os" "path/filepath" "slices" @@ -148,13 +147,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") diff --git a/internal/cmd/builder.go b/internal/cmd/builder.go index 253ad451..8eae65b1 100644 --- a/internal/cmd/builder.go +++ b/internal/cmd/builder.go @@ -10,6 +10,7 @@ import ( "context" "errors" "fmt" + "net/url" "github.com/docker/go-units" buildapi "unikraft.com/cloud/sdk/build" @@ -301,7 +302,22 @@ func builderClient(cfg *config.Config, url string) (*buildapi.Client, error) { if err != nil { return nil, err } - return buildapi.New(cmp.Or(url, profile.BuildURL, buildapi.DefaultServer), buildapi.WithToken(profile.Token)) + 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. diff --git a/internal/cmd/builder_test.go b/internal/cmd/builder_test.go index 0da89488..63b1f28b 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,12 +19,6 @@ 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 { 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: "+buildURL+"}\n"), 0o600)) @@ -39,6 +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)) + 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") } From 777141c223814e035a3088f0fd4b4b22267e0745 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:12:07 +0200 Subject: [PATCH 17/55] feat(cmd): Add --metro to builder commands The builder commands sent no metro, so the build service used the first metro of the org. A builder in another metro was listed, but could not be inspected, pruned or deleted. Add --metro to create, get, du, prune and delete, and show the metro of each builder in the list. Closes: TOOL-1881 Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/integration/builder_test.go | 2 +- cmd/unikraft/testdata/TestHelp/build | 14 +++++++ internal/cmd/builder.go | 48 ++++++++++++++++++------ 3 files changed, 51 insertions(+), 13 deletions(-) diff --git a/cmd/unikraft/integration/builder_test.go b/cmd/unikraft/integration/builder_test.go index e34d0a74..4633c783 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/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index 0ccbeabc..165a7091 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -95,6 +95,7 @@ Commands: Fields: name + metro default running waiting @@ -146,6 +147,8 @@ Flags: 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, 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 @@ -199,6 +203,8 @@ Flags: 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, 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 @@ -236,6 +242,7 @@ Examples: Fields: name + metro default running waiting @@ -297,6 +304,7 @@ Examples: Fields: name + metro default running waiting @@ -311,6 +319,8 @@ Flags: 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, 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 @@ -350,6 +360,8 @@ Examples: Flags: --remote= ($UNIKRAFT_BUILD_URL) 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 @@ -389,6 +401,8 @@ Examples: Flags: --remote= ($UNIKRAFT_BUILD_URL) 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/internal/cmd/builder.go b/internal/cmd/builder.go index 8eae65b1..ad913509 100644 --- a/internal/cmd/builder.go +++ b/internal/cmd/builder.go @@ -39,6 +39,7 @@ 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."` @@ -73,11 +74,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 { @@ -121,9 +123,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 @@ -158,9 +161,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 { @@ -176,13 +181,24 @@ 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, 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 { @@ -197,10 +213,12 @@ 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, 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 { @@ -209,6 +227,7 @@ type BuilderCreateCmd struct { 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, 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 { @@ -223,6 +242,7 @@ 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, 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 { @@ -237,6 +257,7 @@ 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, 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 { @@ -263,7 +284,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") @@ -275,9 +296,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 @@ -288,9 +309,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 @@ -333,8 +354,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 From 6c29c98396a5b47239b1555f1704f12acf7770ee Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:13:16 +0200 Subject: [PATCH 18/55] fix(cmd): Cancel a build that lost its progress When the CLI gave up on the progress stream of a remote build, it left the build running. The build kept its builder slot until it failed at the push. Cancel the build on each error of the progress stream, not only when the CLI itself is interrupted. Closes: TOOL-1902 Signed-off-by: Dragos Gheorghioiu --- internal/cmd/build_remote.go | 5 +---- internal/cmd/build_remote_test.go | 33 +++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index 6ce0b956..6b0c6bb5 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -112,10 +112,7 @@ func followRemote(ctx context.Context, client *buildapi.Client, req buildapi.Cre 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)) - } - return err + return errors.Join(err, cancelRemote(ctx, client, b.ID)) } if ev.SolveStatus != nil { disp.Write(ev.SolveStatus) diff --git a/internal/cmd/build_remote_test.go b/internal/cmd/build_remote_test.go index 4cdec9bb..cc13554b 100644 --- a/internal/cmd/build_remote_test.go +++ b/internal/cmd/build_remote_test.go @@ -174,3 +174,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) +} From aa9b94282969be038ef6d56cab411f67691c9012 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:13:36 +0200 Subject: [PATCH 19/55] fix(cmd): Report the cancel of a remote build Ctrl+C during a remote build cancelled the build but printed nothing, so the user could not tell if the cancel had arrived. Log the build ID once the build is cancelled, or a warning that the build may still run. Cancel after the progress display closes, so that the display does not draw over the line. Closes: TOOL-1910 Signed-off-by: Dragos Gheorghioiu --- internal/cmd/build_remote.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index 6b0c6bb5..3ccd86d5 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -96,23 +96,30 @@ 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 { - return errors.Join(err, cancelRemote(ctx, client, b.ID)) + cancel = true + return err } if ev.SolveStatus != nil { disp.Write(ev.SolveStatus) @@ -130,11 +137,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. From 1ce5396c8e2aa49e95a471c5c1a84a7d4d58d6e6 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:13:54 +0200 Subject: [PATCH 20/55] fix(cmd): Skip unset --build-arg in remote builds --build-arg KEY sent an empty value when KEY was not in the environment. The empty value replaced the default of the ARG in the Dockerfile. Leave the argument out when the variable does not exist, as Docker does. Closes: TOOL-1899 Signed-off-by: Dragos Gheorghioiu --- internal/cmd/build_remote.go | 4 +++- internal/cmd/build_remote_test.go | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index 3ccd86d5..828c6024 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -215,7 +215,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 cc13554b..5c81dfab 100644 --- a/internal/cmd/build_remote_test.go +++ b/internal/cmd/build_remote_test.go @@ -63,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"}, From 08e6ba1136a749db7e4dbd28e515e556f210bb11 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:13:57 +0200 Subject: [PATCH 21/55] fix(cmd): Name a missing remote build input A remote build of a path that does not exist failed with the raw error of stat. Give the message of a local build instead. Closes: TOOL-1904 Signed-off-by: Dragos Gheorghioiu --- internal/cmd/build_remote.go | 4 ++++ internal/cmd/build_remote_test.go | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index 828c6024..b505a183 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -14,6 +14,7 @@ import ( "encoding/hex" "errors" "fmt" + "io/fs" "os" "path/filepath" "slices" @@ -174,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 } diff --git a/internal/cmd/build_remote_test.go b/internal/cmd/build_remote_test.go index 5c81dfab..185b9239 100644 --- a/internal/cmd/build_remote_test.go +++ b/internal/cmd/build_remote_test.go @@ -140,6 +140,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) { From 3ee2ef690834f08d3c33ce8a2239443b16df0366 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:14:21 +0200 Subject: [PATCH 22/55] docs(cmd): Fix the --arch help for remote builds The help said that a bare Dockerfile requires --arch. That holds for a local build only: a remote build defaults to x86_64. Closes: TOOL-1894 Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/testdata/TestHelp/build | 2 +- cmd/unikraft/testdata/TestHelp/images | 2 +- internal/cmd/build.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index 165a7091..599202e2 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -36,7 +36,7 @@ Flags: -o, --output Output destination. --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. diff --git a/cmd/unikraft/testdata/TestHelp/images b/cmd/unikraft/testdata/TestHelp/images index bbebf4bb..651b0a26 100644 --- a/cmd/unikraft/testdata/TestHelp/images +++ b/cmd/unikraft/testdata/TestHelp/images @@ -80,7 +80,7 @@ Flags: -o, --output Output destination. --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. diff --git a/internal/cmd/build.go b/internal/cmd/build.go index 896bd98c..e71e707c 100644 --- a/internal/cmd/build.go +++ b/internal/cmd/build.go @@ -14,7 +14,7 @@ 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"` + 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."` From 804f01e9b47b0f2c9a75d8c30c2262c74b8d6d1d Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:14:34 +0200 Subject: [PATCH 23/55] docs(cmd): Say that remote --output needs a tag The build service refuses an output without a tag, and the help of --output did not say that a remote build needs one. Closes: TOOL-1906 Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/testdata/TestHelp/build | 2 +- cmd/unikraft/testdata/TestHelp/images | 2 +- internal/cmd/build.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index 599202e2..b779e774 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -34,7 +34,7 @@ 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. 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] diff --git a/cmd/unikraft/testdata/TestHelp/images b/cmd/unikraft/testdata/TestHelp/images index 651b0a26..426410cc 100644 --- a/cmd/unikraft/testdata/TestHelp/images +++ b/cmd/unikraft/testdata/TestHelp/images @@ -78,7 +78,7 @@ 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. 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] diff --git a/internal/cmd/build.go b/internal/cmd/build.go index e71e707c..f479120c 100644 --- a/internal/cmd/build.go +++ b/internal/cmd/build.go @@ -13,7 +13,7 @@ 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"` + 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 From 33613ef9a1c0524397784cf9d392961c835d2ccd Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 11:14:47 +0200 Subject: [PATCH 24/55] docs(cmd): Show the --remote= form in help The value of --remote is optional, so --remote with a space fails to parse. The help did not say to write --remote=. Closes: TOOL-1898 Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/testdata/TestHelp/build | 2 +- cmd/unikraft/testdata/TestHelp/images | 2 +- internal/cmd/build.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index b779e774..8c8d695e 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -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. diff --git a/cmd/unikraft/testdata/TestHelp/images b/cmd/unikraft/testdata/TestHelp/images index 426410cc..b2c37fc0 100644 --- a/cmd/unikraft/testdata/TestHelp/images +++ b/cmd/unikraft/testdata/TestHelp/images @@ -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/internal/cmd/build.go b/internal/cmd/build.go index f479120c..9e8cfc88 100644 --- a/internal/cmd/build.go +++ b/internal/cmd/build.go @@ -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."` } From 3edb97e73216c835c4b1f659a1b8129dc34d46a9 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 12:14:19 +0200 Subject: [PATCH 25/55] gomod(deps): Bump x/build and x/image-spec x now reads a Containerfile as a Dockerfile, reads dist/app.tar as an archive, and names the --ssh entry that has no agent. x/build pins an x/dockerfile commit that is no longer on the remote, so require the merged one for go mod tidy to pass. Closes: TOOL-1901 Closes: TOOL-1903 Signed-off-by: Dragos Gheorghioiu --- go.mod | 15 ++++++++------- go.sum | 32 ++++++++++++++++++-------------- 2 files changed, 26 insertions(+), 21 deletions(-) diff --git a/go.mod b/go.mod index 0a1899b3..4b7a8c5f 100644 --- a/go.mod +++ b/go.mod @@ -58,18 +58,18 @@ require ( 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/x/build v0.0.0-20261118100745-28172ae5f28c 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-20261118100745-28172ae5f28c 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/log v0.0.0-20261113145058-65fc641f4af8 unikraft.com/x/ptr v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/shell v0.0.0-20261113145058-65fc641f4af8 unikraft.com/x/signal v0.0.0-20261111120215-5177d0f4c7b6 @@ -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,17 +199,18 @@ 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. diff --git a/go.sum b/go.sum index 726e24b0..2e092df7 100644 --- a/go.sum +++ b/go.sum @@ -24,6 +24,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= @@ -295,8 +297,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 +310,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= @@ -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= @@ -595,20 +597,22 @@ unikraft.com/cloud/sdk/build v0.0.0-20261112083743-f904b5bfc966 h1:hJ3PzigJbcAwn 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/x/build v0.0.0-20261118100745-28172ae5f28c h1:P1rdLOvLx6owNl9dM/Hb8TqCWtP8euREBr77OPfbcmg= +unikraft.com/x/build v0.0.0-20261118100745-28172ae5f28c/go.mod h1:BequRft8Wleotb5Hps13DdQLyuCvmo/72Ydwz41+B8A= 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-20261118100745-28172ae5f28c h1:elFIU1+WfpddUjduhY32pUsvNf4IXVxZ0NLpjnsmBhc= +unikraft.com/x/image-spec v0.0.0-20261118100745-28172ae5f28c/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= @@ -619,8 +623,8 @@ unikraft.com/x/kingkong v0.0.0-20261111120215-5177d0f4c7b6 h1:sWT5GFDU1F7bu5XE7q 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/log v0.0.0-20261113145058-65fc641f4af8 h1:bWuK++umow5Ua8JRjD5TWkB0H0hbiupmGQvl1d9Iq1M= +unikraft.com/x/log v0.0.0-20261113145058-65fc641f4af8/go.mod h1:XCwOFKbAMvfdyLfU/pRVtW5lqHu60urteiLHDmsj7tc= 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= From bf338acbc7d3eb9c261787a3877bbb11e0862202 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Wed, 18 Nov 2026 12:14:37 +0200 Subject: [PATCH 26/55] fix(cmd): Send a Containerfile as a Dockerfile A remote build sent a Containerfile, or a dockerfile in lower case, as a Kraftfile, and the build failed in the Kraftfile parser. Tell a Dockerfile with the check of x/build, as a local build does. Closes: TOOL-1900 Signed-off-by: Dragos Gheorghioiu --- internal/cmd/build_remote.go | 5 ++--- internal/cmd/build_remote_test.go | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/internal/cmd/build_remote.go b/internal/cmd/build_remote.go index b505a183..98120951 100644 --- a/internal/cmd/build_remote.go +++ b/internal/cmd/build_remote.go @@ -17,7 +17,6 @@ import ( "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" @@ -206,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)) diff --git a/internal/cmd/build_remote_test.go b/internal/cmd/build_remote_test.go index 185b9239..99b5464b 100644 --- a/internal/cmd/build_remote_test.go +++ b/internal/cmd/build_remote_test.go @@ -92,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", From bb1159da2408f615fe06e7139870bf8327861b18 Mon Sep 17 00:00:00 2001 From: Alex-Andrei Cioc Date: Thu, 19 Nov 2026 12:14:16 +0200 Subject: [PATCH 27/55] fix(model): Print a removed key once `image rm` printed a multi-platform image once per platform. Signed-off-by: Alex-Andrei Cioc --- pkg/model/cmd/cmd.go | 11 +++++++++++ pkg/model/cmd/cmd_test.go | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/pkg/model/cmd/cmd.go b/pkg/model/cmd/cmd.go index 5123c86c..05b314d6 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 4e3f8a99..f891f1ee 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() From 017ef1c5d212693ac75d99bc1bcb4ac543ab10dc Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Fri, 20 Nov 2026 11:51:12 +0200 Subject: [PATCH 28/55] docs(cmd): Say that max builds is per replica builder list shows MAX-BUILDS next to a higher RUNNING count, and the field help says the builder runs that many builds at once. Each replica of the build service has its own slots on the builder. Say that the number is per replica, in the field help and in the help of builder list. Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/testdata/TestHelp/build | 3 +++ internal/cmd/builder.go | 12 +++++++++++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/cmd/unikraft/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index 8c8d695e..dde20119 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -229,6 +229,9 @@ $ 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. + Usage: unikraft builder list [ ...] [flags] diff --git a/internal/cmd/builder.go b/internal/cmd/builder.go index ad913509..4291d128 100644 --- a/internal/cmd/builder.go +++ b/internal/cmd/builder.go @@ -12,6 +12,7 @@ import ( "fmt" "net/url" + "github.com/MakeNowJust/heredoc" "github.com/docker/go-units" buildapi "unikraft.com/cloud/sdk/build" "unikraft.com/x/kingkong" @@ -43,7 +44,7 @@ type Builder struct { 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."` + 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."` @@ -206,6 +207,15 @@ type BuilderListCmd struct { 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. + `) +} + func (c *BuilderListCmd) Run(ctx context.Context, stdio xstdio.Stdio) error { return c.ModelListCmd.Run(context.WithValue(ctx, builderRemoteKey{}, c.Remote), stdio, nil) } From c0a3c5af7d08d58a0d4981ada28eef38def61736 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Fri, 20 Nov 2026 11:51:17 +0200 Subject: [PATCH 29/55] docs(cmd): Say which builds are waiting The WAITING help says it counts the builds waiting for the builder. It counts every build that has not started, also the builds that wait for their client's session. Say which builds it counts, in the field help and in the help of builder list. Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/testdata/TestHelp/build | 4 +++- internal/cmd/builder.go | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/build b/cmd/unikraft/testdata/TestHelp/build index dde20119..e774665f 100644 --- a/cmd/unikraft/testdata/TestHelp/build +++ b/cmd/unikraft/testdata/TestHelp/build @@ -230,7 +230,9 @@ $ 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. +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] diff --git a/internal/cmd/builder.go b/internal/cmd/builder.go index 4291d128..5fb0cc66 100644 --- a/internal/cmd/builder.go +++ b/internal/cmd/builder.go @@ -43,7 +43,7 @@ type Builder struct { 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."` + 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."` @@ -212,7 +212,9 @@ func (BuilderListCmd) Help() string { 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. + 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. `) } From 918804f4d59e10ac1382f790f3c936ff4c924441 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Fri, 20 Nov 2026 12:29:58 +0200 Subject: [PATCH 30/55] gomod(deps): Bump x/build Signed-off-by: Dragos Gheorghioiu --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 4b7a8c5f..accbce4a 100644 --- a/go.mod +++ b/go.mod @@ -58,7 +58,7 @@ require ( 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-20261118100745-28172ae5f28c + unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d 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 diff --git a/go.sum b/go.sum index 2e092df7..fe804e90 100644 --- a/go.sum +++ b/go.sum @@ -597,8 +597,8 @@ unikraft.com/cloud/sdk/build v0.0.0-20261112083743-f904b5bfc966 h1:hJ3PzigJbcAwn 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-20261118100745-28172ae5f28c h1:P1rdLOvLx6owNl9dM/Hb8TqCWtP8euREBr77OPfbcmg= -unikraft.com/x/build v0.0.0-20261118100745-28172ae5f28c/go.mod h1:BequRft8Wleotb5Hps13DdQLyuCvmo/72Ydwz41+B8A= +unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d h1:sTPtr5YO1Ye+xPHlnbYbocbPAD/uupFrc3UDhxJOEF8= +unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d/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= From c06d192492ce9cbfe981fb88f98308df3bcd70b4 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Fri, 20 Nov 2026 13:02:55 +0200 Subject: [PATCH 31/55] test(integration): Keep Dockerfile digests unique The two dockerfile-only builds now make the same image, since a rebuild keeps its digest, and image delete removes every tag of a digest. So the first delete also removed the other build's image. Put the tag of each build in its Dockerfile. Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/integration/build_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cmd/unikraft/integration/build_test.go b/cmd/unikraft/integration/build_test.go index 8041ed1c..a0e05904 100644 --- a/cmd/unikraft/integration/build_test.go +++ b/cmd/unikraft/integration/build_test.go @@ -180,11 +180,12 @@ cmd: ["sh", "/entrypoint.sh"] instName := uniq() image := r.Profile.Organization + "/dockerfile-e2e:" + imageTag + // The tag in the Dockerfile keeps the digest unique: image delete removes every tag of a digest. dir := t.TempDir() 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", "cat /etc/unikraft-e2e && echo UNIKRAFT_E2E_OK"] `), 0o644), ).Apply(dir)) From 72fec6b89719e1d77dafc725638d2cafa6308e37 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Fri, 20 Nov 2026 14:29:21 +0200 Subject: [PATCH 32/55] test(integration): Keep image digests unique Since #665, a Dockerfile build is dated by its base image, so the STABLE and STAGING jobs push one digest under two tags. Image delete removes every tag of a digest, so the cleanup of one job deleted the shared busybox image that the other still used. Put the tag into the Dockerfile of each image: a label for the shared images, and the echoed text for the tests that build their own from a fixed Dockerfile. Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/integration/build_test.go | 6 +++--- cmd/unikraft/integration/instance_test.go | 4 ++-- internal/integration/image.go | 7 ++++++- 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/cmd/unikraft/integration/build_test.go b/cmd/unikraft/integration/build_test.go index a0e05904..0761e099 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 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(` @@ -275,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/instance_test.go b/cmd/unikraft/integration/instance_test.go index fdbbbc75..f49d04ef 100644 --- a/cmd/unikraft/integration/instance_test.go +++ b/cmd/unikraft/integration/instance_test.go @@ -1464,7 +1464,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 +1502,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 diff --git a/internal/integration/image.go b/internal/integration/image.go index dcdaa389..e1e43ef3 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) From 5311c2cb66217ff3d01ccb354efb47b9231a3cda Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Fri, 20 Nov 2026 15:12:38 +0200 Subject: [PATCH 33/55] feat(cmd): Set the pull policy on every image Only `instance create` sent a pull policy. ROMs, plugins, `instance edit` and template edit sent a bare image URL. They now send the image object with `pull_policy`, and template edit can set the image. A policy needs an image in the same create or edit: the stored image is pinned by digest, and the platform ignores the policy for a digest. Signed-off-by: Cezar Craciunoiu --- cmd/unikraft/integration/instance_test.go | 32 +++++ cmd/unikraft/testdata/TestHelp/instances | 114 ++++++++++++------ cmd/unikraft/testdata/TestHelp/run | 16 +-- internal/cmd/instance_templates.go | 23 +++- internal/cmd/instances.go | 65 +++++++--- internal/cmd/instances_test.go | 94 +++++++++++++++ .../testdata/TestOutput/instance-templates | 12 +- internal/cmd/testdata/TestOutput/instances | 23 ++++ .../testdata/TestOutput/instances-http-oci | 13 ++ internal/cmd/util.go | 25 ++++ internal/cmd/util_test.go | 53 ++++++++ 11 files changed, 402 insertions(+), 68 deletions(-) diff --git a/cmd/unikraft/integration/instance_test.go b/cmd/unikraft/integration/instance_test.go index fdbbbc75..51231811 100644 --- a/cmd/unikraft/integration/instance_test.go +++ b/cmd/unikraft/integration/instance_test.go @@ -1556,6 +1556,38 @@ 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}) diff --git a/cmd/unikraft/testdata/TestHelp/instances b/cmd/unikraft/testdata/TestHelp/instances index 6c846940..716995d5 100644 --- a/cmd/unikraft/testdata/TestHelp/instances +++ b/cmd/unikraft/testdata/TestHelp/instances @@ -72,8 +72,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -153,8 +155,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -242,8 +246,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -335,8 +341,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -478,8 +486,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -559,7 +569,7 @@ 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. [examples: always, if_not_present, never] --type= Virtual machine type. @@ -597,11 +607,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=],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. [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=][,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. [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. @@ -747,8 +757,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -828,7 +840,7 @@ 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. [examples: always, if_not_present, never] --type= Virtual machine type. @@ -866,11 +878,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=],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. [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=][,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. [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. @@ -1000,8 +1012,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -1083,7 +1097,7 @@ 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. [examples: always, if_not_present, never] --type= Virtual machine type. @@ -1121,11 +1135,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=],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. [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=][,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. [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 +1216,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 @@ -1238,8 +1255,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + 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 +1334,9 @@ 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. + [examples: always, if_not_present, never] --args= Command-line arguments passed to the instance at start. [example: --port=8080] @@ -1327,11 +1349,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=],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. [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=][,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. [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. @@ -1385,8 +1407,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -1475,6 +1499,7 @@ Fields: autokill, autokill.time state image + pull-policy type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1533,6 +1558,7 @@ Fields: autokill, autokill.time state image + pull-policy type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1599,6 +1625,7 @@ Fields: autokill, autokill.time state image + pull-policy type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1673,6 +1700,7 @@ Fields: autokill, autokill.time state image + pull-policy type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1742,6 +1770,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 +1785,7 @@ Fields: autokill, autokill.time state image + pull-policy type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1815,6 +1848,12 @@ 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. + [examples: always, if_not_present, never] $ unikraft instance template delete --help @@ -1842,6 +1881,7 @@ Fields: autokill, autokill.time state image + pull-policy type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus diff --git a/cmd/unikraft/testdata/TestHelp/run b/cmd/unikraft/testdata/TestHelp/run index 14ae617a..d50ba61a 100644 --- a/cmd/unikraft/testdata/TestHelp/run +++ b/cmd/unikraft/testdata/TestHelp/run @@ -65,8 +65,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.*.dir, + roms.*.at + plugins, plugins.*, plugins.*.name, plugins.*.image, plugins.*.pull-policy, + plugins.*.config private-fqdn networks, networks.*, networks.*.name, networks.*.uuid, networks.*.private-ip, networks.*.mac, networks.*.tap-name, networks.*.relay, networks.*.relay.name, @@ -148,7 +150,7 @@ 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. [examples: always, if_not_present, never] --type= Virtual machine type. @@ -186,11 +188,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=],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. [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=][,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. [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/internal/cmd/instance_templates.go b/internal/cmd/instance_templates.go index d980bbe5..3c8a4844 100644 --- a/internal/cmd/instance_templates.go +++ b/internal/cmd/instance_templates.go @@ -48,9 +48,10 @@ 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." placeholder:"policy" example:"always,if_not_present,never"` + 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 +252,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 +295,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 +479,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: { { diff --git a/internal/cmd/instances.go b/internal/cmd/instances.go index 2da4b35b..ca830906 100644 --- a/internal/cmd/instances.go +++ b/internal/cmd/instances.go @@ -117,7 +117,7 @@ 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"` + 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." 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"` Runtime struct { @@ -133,8 +133,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." placeholder:"name=,image=[,pull-policy=],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." placeholder:"name=,image=[,pull-policy=][,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"` @@ -418,10 +418,11 @@ 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."` + 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 +507,11 @@ 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."` + 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,6 +558,14 @@ func (p *InstancePlugin) UnmarshalJSON(data []byte) error { return p.Validate() } +// imageSource returns url as a plain reference, or as an image object when policy is set. +func imageSource(url string, policy *platform.PullPolicy) platform.ImageSource { + if policy == nil { + return platform.ImageReference(url) + } + return platform.ImageSpec{Url: url, PullPolicy: policy} +} + // 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) { @@ -1006,6 +1016,10 @@ func (Instance) Edit(ctx context.Context, key string, fields []model.Field) erro if err != nil { return err } + patches, err = setImageOptions(fields, platform.MutableInstancePropertyImage, patches) + if err != nil { + return err + } g, err := multimetro.NewClient(ctx) if err != nil { return err @@ -1194,6 +1208,9 @@ 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 && rom.Image == "" { + return zero, nil, fmt.Errorf("pull-policy= needs image= in a ROM") + } if rom.Image == "" && rom.Dir == "" { continue } @@ -1206,7 +1223,7 @@ func instancePatchSpec(path string, op patchOp, value any) (platform.MutableInst } reqRom["files"] = files } else { - reqRom["image"] = rom.Image + reqRom["image"] = imageSource(rom.Image, rom.PullPolicy) } if rom.Name != "" { reqRom["name"] = rom.Name @@ -1230,7 +1247,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), } if plugin.Config != "" { reqPlugin["config"] = jsontext.Value(plugin.Config) @@ -1361,6 +1378,9 @@ 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 && rom.Image == "" { + return nil, fmt.Errorf("pull-policy= needs image= in a ROM") + } var reqRom platform.CreateInstanceRequestRom if rom.Dir != "" { @@ -1370,7 +1390,7 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } reqRom.Files = files } else { - reqRom.Image = platform.ImageReference(rom.Image) + reqRom.Image = imageSource(rom.Image, rom.PullPolicy) } if rom.Name != "" { reqRom.Name = rom.Name @@ -1391,7 +1411,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), } if plugin.Config != "" { var config any = jsontext.Value(plugin.Config) @@ -1530,12 +1550,11 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } } + if pullPolicy != nil && imageURL == "" { + return nil, fmt.Errorf("--pull-policy needs --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) } // Validate that exactly one of image, template, branch, or checkpoint is provided @@ -1751,6 +1770,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{ diff --git a/internal/cmd/instances_test.go b/internal/cmd/instances_test.go index c0c45938..6babe935 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,11 @@ 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: "missing name is rejected", in: "image=plugins/logger:latest", @@ -190,6 +196,94 @@ 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 needs --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= needs 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 needs --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 needs --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= needs 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) + }) + } +} + // TestInstanceCreateRejectsNetworks checks that create stops a bad --network // before it sends a request. func TestInstanceCreateRejectsNetworks(t *testing.T) { diff --git a/internal/cmd/testdata/TestOutput/instance-templates b/internal/cmd/testdata/TestOutput/instance-templates index 880034fe..e17d4435 100644 --- a/internal/cmd/testdata/TestOutput/instance-templates +++ b/internal/cmd/testdata/TestOutput/instance-templates @@ -147,7 +147,17 @@ 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": "type", diff --git a/internal/cmd/testdata/TestOutput/instances b/internal/cmd/testdata/TestOutput/instances index 57dc321f..4d69272a 100644 --- a/internal/cmd/testdata/TestOutput/instances +++ b/internal/cmd/testdata/TestOutput/instances @@ -296,6 +296,9 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "verbosity": "invisible", "create": { "set": null + }, + "edit": { + "set": null } }, { @@ -637,6 +640,11 @@ 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": "dir", "value": "", @@ -664,6 +672,11 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -715,6 +728,11 @@ 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": "config", "value": { @@ -739,6 +757,11 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "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 321a33eb..1c007704 100644 --- a/internal/cmd/testdata/TestOutput/instances-http-oci +++ b/internal/cmd/testdata/TestOutput/instances-http-oci @@ -167,6 +167,9 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "verbosity": "invisible", "create": { "set": null + }, + "edit": { + "set": null } }, { @@ -376,6 +379,11 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -414,6 +422,11 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "value": "", "verbosity": "long" }, + { + "name": "pull-policy", + "value": null, + "verbosity": "invisible" + }, { "name": "config", "value": null, diff --git a/internal/cmd/util.go b/internal/cmd/util.go index a0943f0c..fd0087e7 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,26 @@ func patchRequests[P ~string](fields []model.Field, specFor func(path string, op } return reqs, nil } + +// setImageOptions moves the pull policy in fields into the image patch of patches. +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) + } + if policy == 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 needs --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) + return patches, nil +} diff --git a/internal/cmd/util_test.go b/internal/cmd/util_test.go index 2a0db971..1c7c4ed8 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,55 @@ 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", + value: func(t *testing.T) any { + fields := []model.Field{{Name: "pull-policy", Edit: &model.Patch{Set: new(platform.PullPolicyAlways)}}} + 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"}`, + }, + { + name: "rom with a pull policy", + value: func(t *testing.T) any { + roms := []*InstanceRom{{Name: "r", Image: "r:1", PullPolicy: new(platform.PullPolicyNever)}} + _, value, err := instancePatchSpec("roms", patchOpSet, roms) + require.NoError(t, err) + return value + }, + want: `[{"name":"r","image":{"url":"r:1","pull_policy":"never"}}]`, + }, + { + name: "plugin with a pull policy", + value: func(t *testing.T) any { + plugins := []*InstancePlugin{{Name: "p", Image: "p:1", PullPolicy: new(platform.PullPolicyIfNotPresent)}} + _, value, err := instancePatchSpec("plugins", patchOpSet, plugins) + require.NoError(t, err) + return value + }, + want: `[{"name":"p","image":{"url":"p:1","pull_policy":"if_not_present"}}]`, + }, + } + 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)) + }) + } +} From dc81909668815124502c4d9de93690cb1acfba6c Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Fri, 20 Nov 2026 15:44:01 +0200 Subject: [PATCH 34/55] feat(value): Fill map fields from dotted keys A dotted key could not reach a map field, and a map field rendered as `meta=a=1, b=2`, which does not parse back. `meta.K=V` now sets one entry, `meta={...}` merges into the entries set before it, and a map renders as dotted keys, or as JSON when a value is empty or has a comma. Signed-off-by: Cezar Craciunoiu --- pkg/model/value/format.go | 49 +++++++++++++++++++++++++++++++--- pkg/model/value/format_test.go | 22 +++++++++++++++ pkg/model/value/parse.go | 31 ++++++++++++++++++--- pkg/model/value/parse_test.go | 11 ++++++++ 4 files changed, 106 insertions(+), 7 deletions(-) diff --git a/pkg/model/value/format.go b/pkg/model/value/format.go index 0e57d9b5..b51184ec 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 fb262426..12832cee 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 5aee4e0e..d666d18a 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 0e57f1be..a6b02759 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]") From 5e8fff96202c61eb5a6b7035baea932d044645a7 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Fri, 20 Nov 2026 15:44:02 +0200 Subject: [PATCH 35/55] feat(cmd): Send headers when fetching an image The image object can carry fetch headers, but the CLI had no way to set them. `--image-header K=V` sets them on instance create, edit and template edit, and `headers.K=V` sets them on `--rom` and `--plugin`. Like the pull policy, they need an image in the same create or edit. Signed-off-by: Cezar Craciunoiu --- cmd/unikraft/integration/instance_test.go | 43 ++++++ cmd/unikraft/testdata/TestHelp/instances | 126 +++++++++++------- cmd/unikraft/testdata/TestHelp/run | 20 +-- internal/cmd/instance_templates.go | 9 +- internal/cmd/instances.go | 47 ++++--- internal/cmd/instances_test.go | 49 ++++++- .../testdata/TestOutput/instance-templates | 7 + internal/cmd/testdata/TestOutput/instances | 30 +++++ .../testdata/TestOutput/instances-http-oci | 20 +++ internal/cmd/util.go | 12 +- internal/cmd/util_test.go | 21 +-- 11 files changed, 286 insertions(+), 98 deletions(-) diff --git a/cmd/unikraft/integration/instance_test.go b/cmd/unikraft/integration/instance_test.go index 51231811..0525e0e1 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" @@ -1593,6 +1595,47 @@ cmd: ["cat", "/marker.txt"] 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/testdata/TestHelp/instances b/cmd/unikraft/testdata/TestHelp/instances index 716995d5..2d65b1ff 100644 --- a/cmd/unikraft/testdata/TestHelp/instances +++ b/cmd/unikraft/testdata/TestHelp/instances @@ -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,10 +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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -146,6 +147,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -155,10 +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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -237,6 +239,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -246,10 +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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -332,6 +335,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -341,10 +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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -477,6 +481,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -486,10 +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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -569,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. Needs image in the same create or edit. + 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) @@ -607,11 +615,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=[,pull-policy=],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. + --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=[,pull-policy=][,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. + --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. @@ -748,6 +756,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -757,10 +766,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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -840,8 +849,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. Needs image in the same create or edit. + 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) @@ -878,11 +890,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=[,pull-policy=],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. + --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=[,pull-policy=][,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. + --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. @@ -1003,6 +1015,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -1012,10 +1025,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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -1097,8 +1110,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. Needs image in the same create or edit. + 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) @@ -1135,11 +1151,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=[,pull-policy=],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. + --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=[,pull-policy=][,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. + --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. @@ -1246,6 +1262,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -1255,10 +1272,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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -1335,8 +1352,11 @@ Edit 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. Needs image in the same create or edit. + 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] @@ -1349,11 +1369,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=[,pull-policy=],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. + --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=[,pull-policy=][,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. + --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. @@ -1398,6 +1418,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus, resources.gpus @@ -1407,10 +1428,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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -1500,6 +1521,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1559,6 +1581,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1626,6 +1649,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1701,6 +1725,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1786,6 +1811,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus @@ -1852,8 +1878,11 @@ Edit flags: 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. + 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 @@ -1882,6 +1911,7 @@ Fields: state image pull-policy + image-headers type runtime, runtime.args, runtime.env resources, resources.memory, resources.vcpus diff --git a/cmd/unikraft/testdata/TestHelp/run b/cmd/unikraft/testdata/TestHelp/run index d50ba61a..c143f27a 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,10 +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.*.pull-policy, roms.*.dir, - roms.*.at + 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.*.config + 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, @@ -150,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. Needs image in the same create or edit. + 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) @@ -188,11 +192,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=[,pull-policy=],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. + --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=[,pull-policy=][,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. + --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/internal/cmd/instance_templates.go b/internal/cmd/instance_templates.go index 3c8a4844..f7c33026 100644 --- a/internal/cmd/instance_templates.go +++ b/internal/cmd/instance_templates.go @@ -48,10 +48,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" 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." placeholder:"policy" example:"always,if_not_present,never"` - 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."` diff --git a/internal/cmd/instances.go b/internal/cmd/instances.go index ca830906..53e83855 100644 --- a/internal/cmd/instances.go +++ b/internal/cmd/instances.go @@ -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 `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." 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. Add pull-policy=always|if_not_present|never to control when the image is pulled." placeholder:"name=,image=[,pull-policy=],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." placeholder:"name=,image=[,pull-policy=][,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"` @@ -421,6 +422,7 @@ 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."` 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."` } @@ -510,6 +512,7 @@ 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."` 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."` } @@ -558,12 +561,13 @@ func (p *InstancePlugin) UnmarshalJSON(data []byte) error { return p.Validate() } -// imageSource returns url as a plain reference, or as an image object when policy is set. -func imageSource(url string, policy *platform.PullPolicy) platform.ImageSource { - if policy == nil { +// 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} + return platform.ImageSpec{Url: url, PullPolicy: policy, Headers: headers} } // inlineFilesFromDir walks a local directory and returns its contents as @@ -1208,8 +1212,8 @@ 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 && rom.Image == "" { - return zero, nil, fmt.Errorf("pull-policy= needs image= in a ROM") + 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 @@ -1223,7 +1227,7 @@ func instancePatchSpec(path string, op patchOp, value any) (platform.MutableInst } reqRom["files"] = files } else { - reqRom["image"] = imageSource(rom.Image, rom.PullPolicy) + reqRom["image"] = imageSource(rom.Image, rom.PullPolicy, rom.Headers) } if rom.Name != "" { reqRom["name"] = rom.Name @@ -1247,7 +1251,7 @@ func instancePatchSpec(path string, op patchOp, value any) (platform.MutableInst reqPlugin := map[string]any{ "name": plugin.Name, - "image": imageSource(plugin.Image, plugin.PullPolicy), + "image": imageSource(plugin.Image, plugin.PullPolicy, plugin.Headers), } if plugin.Config != "" { reqPlugin["config"] = jsontext.Value(plugin.Config) @@ -1267,6 +1271,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 { @@ -1290,6 +1295,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": @@ -1378,8 +1385,8 @@ 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 && rom.Image == "" { - return nil, fmt.Errorf("pull-policy= needs image= in 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 @@ -1390,7 +1397,7 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } reqRom.Files = files } else { - reqRom.Image = imageSource(rom.Image, rom.PullPolicy) + reqRom.Image = imageSource(rom.Image, rom.PullPolicy, rom.Headers) } if rom.Name != "" { reqRom.Name = rom.Name @@ -1411,7 +1418,7 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } reqPlugin := platform.CreateInstanceRequestPlugin{ Name: plugin.Name, - Image: imageSource(plugin.Image, plugin.PullPolicy), + Image: imageSource(plugin.Image, plugin.PullPolicy, plugin.Headers), } if plugin.Config != "" { var config any = jsontext.Value(plugin.Config) @@ -1550,11 +1557,11 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model } } - if pullPolicy != nil && imageURL == "" { - return nil, fmt.Errorf("--pull-policy needs --image") + if (pullPolicy != nil || len(headers) > 0) && imageURL == "" { + return nil, fmt.Errorf("--pull-policy and --image-header need --image") } if imageURL != "" { - req.Image = imageSource(imageURL, pullPolicy) + req.Image = imageSource(imageURL, pullPolicy, headers) } // Validate that exactly one of image, template, branch, or checkpoint is provided diff --git a/internal/cmd/instances_test.go b/internal/cmd/instances_test.go index 6babe935..9257a531 100644 --- a/internal/cmd/instances_test.go +++ b/internal/cmd/instances_test.go @@ -63,6 +63,11 @@ func TestInstancePluginUnmarshalText(t *testing.T) { 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", @@ -210,7 +215,15 @@ func TestInstanceCreateRejectsImageOptions(t *testing.T) { "template": {"my-template"}, "pull-policy": {"always"}, }, - wantErr: "--pull-policy needs --image", + 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", @@ -218,7 +231,15 @@ func TestInstanceCreateRejectsImageOptions(t *testing.T) { "image": {"nginx:latest"}, "roms": {"name=r,dir=./does-not-exist,pull-policy=always"}, }, - wantErr: "pull-policy= needs image= in a ROM", + 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", }, } @@ -254,19 +275,37 @@ func TestInstanceEditRejectsImageOptions(t *testing.T) { name: "pull policy without an image", target: cmd.Instance{}, spec: map[string][]string{"pull-policy": {"always"}}, - wantErr: "--pull-policy needs --image in the same edit", + 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 needs --image in the same edit", + 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= needs image= in a ROM", + 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", }, } diff --git a/internal/cmd/testdata/TestOutput/instance-templates b/internal/cmd/testdata/TestOutput/instance-templates index e17d4435..d3509593 100644 --- a/internal/cmd/testdata/TestOutput/instance-templates +++ b/internal/cmd/testdata/TestOutput/instance-templates @@ -159,6 +159,13 @@ fra my-template template nginx 128MiB 1 never "set": null } }, + { + "name": "image-headers", + "verbosity": "invisible", + "edit": { + "set": null + } + }, { "name": "type", "value": "micro", diff --git a/internal/cmd/testdata/TestOutput/instances b/internal/cmd/testdata/TestOutput/instances index 4d69272a..7eca233a 100644 --- a/internal/cmd/testdata/TestOutput/instances +++ b/internal/cmd/testdata/TestOutput/instances @@ -301,6 +301,16 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "set": null } }, + { + "name": "image-headers", + "verbosity": "invisible", + "create": { + "set": null + }, + "edit": { + "set": null + } + }, { "name": "type", "value": "full", @@ -645,6 +655,11 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": null, "verbosity": "invisible" }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -677,6 +692,11 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": null, "verbosity": "invisible" }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -733,6 +753,11 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "value": null, "verbosity": "invisible" }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "config", "value": { @@ -762,6 +787,11 @@ fra my-instance running nginx ["arg1", "arg2"] 256MiB 2 example.uni "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 1c007704..407d0614 100644 --- a/internal/cmd/testdata/TestOutput/instances-http-oci +++ b/internal/cmd/testdata/TestOutput/instances-http-oci @@ -172,6 +172,16 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "set": null } }, + { + "name": "image-headers", + "verbosity": "invisible", + "create": { + "set": null + }, + "edit": { + "set": null + } + }, { "name": "type", "value": null, @@ -384,6 +394,11 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "value": null, "verbosity": "invisible" }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "dir", "value": "", @@ -427,6 +442,11 @@ fra my-instance running https+oci://cdn.example.com/me/app/@sha256:43d3d758 "value": null, "verbosity": "invisible" }, + { + "name": "headers", + "value": null, + "verbosity": "invisible" + }, { "name": "config", "value": null, diff --git a/internal/cmd/util.go b/internal/cmd/util.go index fd0087e7..4f90a3c7 100644 --- a/internal/cmd/util.go +++ b/internal/cmd/util.go @@ -189,25 +189,29 @@ func patchRequests[P ~string](fields []model.Field, specFor func(path string, op return reqs, nil } -// setImageOptions moves the pull policy in fields into the image patch of patches. +// 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) } - if policy == nil { + 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 needs --image in the same edit") + 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) + 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 1c7c4ed8..24e1d9da 100644 --- a/internal/cmd/util_test.go +++ b/internal/cmd/util_test.go @@ -137,9 +137,12 @@ func TestImagePatchWireFormat(t *testing.T) { want string }{ { - name: "image with a pull policy", + 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)}}} + 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, @@ -150,27 +153,27 @@ func TestImagePatchWireFormat(t *testing.T) { require.Len(t, patches, 1) return patches[0].Value }, - want: `{"url":"nginx:latest","pull_policy":"always"}`, + want: `{"url":"nginx:latest","pull_policy":"always","headers":{"X-Foo":"1"}}`, }, { - name: "rom with a pull policy", + 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)}} + roms := []*InstanceRom{{Name: "r", Image: "r:1", PullPolicy: new(platform.PullPolicyNever), Headers: map[string]string{"X-Foo": "1"}}} _, value, err := instancePatchSpec("roms", patchOpSet, roms) require.NoError(t, err) return value }, - want: `[{"name":"r","image":{"url":"r:1","pull_policy":"never"}}]`, + want: `[{"name":"r","image":{"url":"r:1","pull_policy":"never","headers":{"X-Foo":"1"}}}]`, }, { - name: "plugin with a pull policy", + 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)}} + plugins := []*InstancePlugin{{Name: "p", Image: "p:1", PullPolicy: new(platform.PullPolicyIfNotPresent), Headers: map[string]string{"X-Foo": "1"}}} _, value, err := instancePatchSpec("plugins", patchOpSet, plugins) require.NoError(t, err) return value }, - want: `[{"name":"p","image":{"url":"p:1","pull_policy":"if_not_present"}}]`, + want: `[{"name":"p","image":{"url":"p:1","pull_policy":"if_not_present","headers":{"X-Foo":"1"}}}]`, }, } for _, tt := range tests { From 958ca26d5be92db2fcfb4807d27794b47d2045c0 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Fri, 20 Nov 2026 18:46:54 +0200 Subject: [PATCH 36/55] gomod(deps): Bump the SDK and x/kraftfile A remote build whose CLI paused for a minute lost its session for good and failed at the push. A local build of a directory with both a Kraftfile and a kraft.yaml read the Kraftfile, unlike a remote build. The build SDK now attaches a dropped session again, and x/kraftfile tries the default names in order. The SDK and the sandbox SDK move to their v0.4.6-staging.6 tags too. Closes: TOOL-1887 Signed-off-by: Cezar Craciunoiu --- go.mod | 12 ++++++------ go.sum | 24 ++++++++++++------------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/go.mod b/go.mod index accbce4a..16756a62 100644 --- a/go.mod +++ b/go.mod @@ -55,9 +55,9 @@ require ( 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/cloud/sdk v0.4.6-staging.6 + unikraft.com/cloud/sdk/build v0.4.6-staging.6 + unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.6 unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d unikraft.com/x/buildkit v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/colors v0.0.0-20261111120215-5177d0f4c7b6 @@ -68,10 +68,10 @@ require ( 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-20261113145058-65fc641f4af8 + 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 diff --git a/go.sum b/go.sum index fe804e90..32f1b349 100644 --- a/go.sum +++ b/go.sum @@ -591,12 +591,12 @@ 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/cloud/sdk v0.4.6-staging.6 h1:MwCmmpAs67WokCSsRgOj9DobyuM/wJQMbw0vxykRjDs= +unikraft.com/cloud/sdk v0.4.6-staging.6/go.mod h1:0teeiz79WohtMx8rmkpI864KE5PW3YlJWzomcTCLRdk= +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.6 h1:BgT7oj8YZiQ1EOfS6u2//gW0GPLIVzkpweLY3ChxMyg= +unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.6/go.mod h1:Vf254Ugp9TgkEEb23OIxV08bZLSkrxw5kk519em69go= unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d h1:sTPtr5YO1Ye+xPHlnbYbocbPAD/uupFrc3UDhxJOEF8= unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d/go.mod h1:aRRxLJqi1sUh/dFCJ1Kan/6hcGeq14hLs50X6RlUnuM= unikraft.com/x/buildkit v0.0.0-20261111120215-5177d0f4c7b6 h1:/7BTbMIFXN81vbpO3oB2Vh/97BBCpYIAJXP/z3d4qao= @@ -621,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-20261113145058-65fc641f4af8 h1:bWuK++umow5Ua8JRjD5TWkB0H0hbiupmGQvl1d9Iq1M= -unikraft.com/x/log v0.0.0-20261113145058-65fc641f4af8/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= From daf28dd4b6387e8aa2529b34365112289c04b1cd Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:04:14 +0000 Subject: [PATCH 37/55] gomod(deps): Bump the go-deps group with 6 updates Bumps the go-deps group with 6 updates: | Package | From | To | | --- | --- | --- | | charm.land/bubbletea/v2 | `2.1.1` | `2.1.2` | | [github.com/charmbracelet/x/ansi](https://github.com/charmbracelet/x) | `0.11.9` | `0.11.10` | | [github.com/docker/cli](https://github.com/docker/cli) | `29.9.3+incompatible` | `29.10.0+incompatible` | | [github.com/posthog/posthog-go](https://github.com/posthog/posthog-go) | `1.42.4` | `1.44.1` | | [github.com/sergi/go-diff](https://github.com/sergi/go-diff) | `1.4.0` | `1.4.5` | | [github.com/tidwall/gjson](https://github.com/tidwall/gjson) | `1.20.2` | `1.20.4` | Updates `charm.land/bubbletea/v2` from 2.1.1 to 2.1.2 Updates `github.com/charmbracelet/x/ansi` from 0.11.9 to 0.11.10 - [Commits](https://github.com/charmbracelet/x/compare/ansi/v0.11.9...ansi/v0.11.10) Updates `github.com/docker/cli` from 29.9.3+incompatible to 29.10.0+incompatible - [Commits](https://github.com/docker/cli/compare/v29.9.3...v29.10.0) Updates `github.com/posthog/posthog-go` from 1.42.4 to 1.44.1 - [Release notes](https://github.com/posthog/posthog-go/releases) - [Changelog](https://github.com/PostHog/posthog-go/blob/main/CHANGELOG.md) - [Commits](https://github.com/posthog/posthog-go/compare/v1.42.4...v1.44.1) Updates `github.com/sergi/go-diff` from 1.4.0 to 1.4.5 - [Release notes](https://github.com/sergi/go-diff/releases) - [Commits](https://github.com/sergi/go-diff/compare/v1.4.0...v1.4.5) Updates `github.com/tidwall/gjson` from 1.20.2 to 1.20.4 - [Commits](https://github.com/tidwall/gjson/compare/v1.20.2...v1.20.4) --- updated-dependencies: - dependency-name: charm.land/bubbletea/v2 dependency-version: 2.1.2 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: go-deps - dependency-name: github.com/charmbracelet/x/ansi dependency-version: 0.11.10 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: go-deps - dependency-name: github.com/docker/cli dependency-version: 29.10.0+incompatible dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-deps - dependency-name: github.com/posthog/posthog-go dependency-version: 1.44.1 dependency-type: direct:production update-type: version-update:semver-minor dependency-group: go-deps - dependency-name: github.com/sergi/go-diff dependency-version: 1.4.5 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: go-deps - dependency-name: github.com/tidwall/gjson dependency-version: 1.20.4 dependency-type: direct:production update-type: version-update:semver-patch dependency-group: go-deps ... Signed-off-by: dependabot[bot] --- go.mod | 12 ++++++------ go.sum | 24 ++++++++++++------------ 2 files changed, 18 insertions(+), 18 deletions(-) diff --git a/go.mod b/go.mod index 16756a62..92a36ca2 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/bubbletea/v2 v2.1.2 charm.land/lipgloss/v2 v2.0.6 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,12 +38,12 @@ 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 golang.org/x/mod v0.43.0 diff --git a/go.sum b/go.sum index 32f1b349..7d6c8ec4 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ 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= dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8= @@ -88,8 +88,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= @@ -162,8 +162,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= @@ -380,8 +380,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= @@ -408,8 +408,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= @@ -455,8 +455,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= From 0f22ae77cef58bdf34c818cca55775ae0b89f2de Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Mon, 23 Nov 2026 14:04:13 +0200 Subject: [PATCH 38/55] fix(mcpserver): Refuse server files in tool calls The hosted MCP server runs the CLI's tools on its own machine, so a ROM `dir=` and the local paths and `http+oci` URLs that `image_get` and `image_delete` take reach the server's files and network, not the caller's. So `cli.New` marks its tool calls as hosted. Then a ROM `dir=` is refused, and an image key must be a registry reference. `unikraft mcp` is unchanged. Signed-off-by: Dragos Gheorghioiu --- internal/cmd/images.go | 18 ++++++++++++++++-- internal/cmd/images_internal_test.go | 9 +++++++++ internal/cmd/instances.go | 15 ++++++++++----- internal/cmd/instances_test.go | 11 +++++++++++ internal/cmd/mcp.go | 15 +++++++++++++++ internal/cmd/util_test.go | 4 ++-- pkg/mcpserver/cli/cli.go | 16 +++++++++++++++- pkg/mcpserver/cli/cli_test.go | 18 ++++++++++++++++++ 8 files changed, 96 insertions(+), 10 deletions(-) diff --git a/internal/cmd/images.go b/internal/cmd/images.go index 2762620e..cc3ed0c2 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 7a5284d3..9a1dcf5a 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/instances.go b/internal/cmd/instances.go index 53e83855..cc19fea3 100644 --- a/internal/cmd/instances.go +++ b/internal/cmd/instances.go @@ -572,7 +572,10 @@ func imageSource(url string, policy *platform.PullPolicy, headers map[string]str // 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 { @@ -1016,7 +1019,9 @@ 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 } @@ -1148,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": @@ -1221,7 +1226,7 @@ func instancePatchSpec(path string, op patchOp, value any) (platform.MutableInst 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) } @@ -1391,7 +1396,7 @@ func (Instance) Create(ctx context.Context, fields []model.Field) ([]model.Model 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) } diff --git a/internal/cmd/instances_test.go b/internal/cmd/instances_test.go index 9257a531..8ede6f3b 100644 --- a/internal/cmd/instances_test.go +++ b/internal/cmd/instances_test.go @@ -323,6 +323,17 @@ func TestInstanceEditRejectsImageOptions(t *testing.T) { } } +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/mcp.go b/internal/cmd/mcp.go index 8666a7d8..f4e8e8e0 100644 --- a/internal/cmd/mcp.go +++ b/internal/cmd/mcp.go @@ -237,6 +237,21 @@ 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 && config.G(ctx).Path != "" { diff --git a/internal/cmd/util_test.go b/internal/cmd/util_test.go index 24e1d9da..a5906f4a 100644 --- a/internal/cmd/util_test.go +++ b/internal/cmd/util_test.go @@ -159,7 +159,7 @@ func TestImagePatchWireFormat(t *testing.T) { 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("roms", patchOpSet, roms) + _, value, err := instancePatchSpec(t.Context(), "roms", patchOpSet, roms) require.NoError(t, err) return value }, @@ -169,7 +169,7 @@ func TestImagePatchWireFormat(t *testing.T) { 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("plugins", patchOpSet, plugins) + _, value, err := instancePatchSpec(t.Context(), "plugins", patchOpSet, plugins) require.NoError(t, err) return value }, diff --git a/pkg/mcpserver/cli/cli.go b/pkg/mcpserver/cli/cli.go index c9d7c36c..fa101d5e 100644 --- a/pkg/mcpserver/cli/cli.go +++ b/pkg/mcpserver/cli/cli.go @@ -11,6 +11,8 @@ import ( "errors" "os" + sdk "github.com/modelcontextprotocol/go-sdk/mcp" + "unikraft.com/cloud/sdk/controlplane" "unikraft.com/cli/internal/branding" @@ -22,6 +24,9 @@ import ( // 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 @@ -32,7 +37,16 @@ func New(ctx context.Context, flags mcpserver.Flags) (*mcpserver.Server, error) 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") } - return cmd.NewMCPServer(ctx, os.Stderr, nil, cmd.MCPCmd{DocsURL: branding.DocsURL, Flags: flags}) + 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 diff --git a/pkg/mcpserver/cli/cli_test.go b/pkg/mcpserver/cli/cli_test.go index eac9b04f..d268103e 100644 --- a/pkg/mcpserver/cli/cli_test.go +++ b/pkg/mcpserver/cli/cli_test.go @@ -6,6 +6,7 @@ package cli import ( + "encoding/json" "testing" "github.com/stretchr/testify/assert" @@ -30,6 +31,23 @@ func TestNew(t *testing.T) { 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 := `"name=r,dir=` + t.TempDir() + `,at=/r"` + + for _, tc := range []struct{ tool, args, want string }{ + {"instance_create", `{"set":{"image":"nginx:latest","metro":"fra","roms":[` + 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) From b0991d2019f120da562e51efa9419ee27089b75e Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Mon, 23 Nov 2026 14:41:42 +0200 Subject: [PATCH 39/55] fix(cmd): Say when --plugin-image attaches The help of `--plugin-image` said that it attaches the sandbox plugin, but it only does after a prompt, so never without a terminal. The hint printed then said to edit the instance while it is stopped, which is not needed. Say in the help that it asks first, and end the hint with the restart or start that loads the plugin. Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/testdata/TestHelp/instances | 10 +++++----- internal/cmd/sandbox_plugin.go | 12 ++++++------ internal/cmd/sandbox_plugin_test.go | 13 ++++++++++++- 3 files changed, 23 insertions(+), 12 deletions(-) diff --git a/cmd/unikraft/testdata/TestHelp/instances b/cmd/unikraft/testdata/TestHelp/instances index 2d65b1ff..2ace303e 100644 --- a/cmd/unikraft/testdata/TestHelp/instances +++ b/cmd/unikraft/testdata/TestHelp/instances @@ -2881,7 +2881,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. @@ -2951,7 +2951,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. @@ -3022,7 +3022,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. @@ -3079,7 +3079,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. @@ -3139,7 +3139,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/internal/cmd/sandbox_plugin.go b/internal/cmd/sandbox_plugin.go index 469768a6..2c8b11bd 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 0d86ccfb..afaaf243 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) { From bab089b0db0f5733dd6dcb56300df02692d7dee4 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Mon, 23 Nov 2026 14:53:38 +0200 Subject: [PATCH 40/55] test(mcpserver): Quote the temp dir as JSON The test added in #672 pasted t.TempDir() into raw JSON, so on Windows the `\U` of `C:\Users` was an invalid escape, and the test failed before it called the tool. Quote the ROM spec with json.Marshal. Signed-off-by: Dragos Gheorghioiu --- pkg/mcpserver/cli/cli_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/pkg/mcpserver/cli/cli_test.go b/pkg/mcpserver/cli/cli_test.go index d268103e..ad35f5ee 100644 --- a/pkg/mcpserver/cli/cli_test.go +++ b/pkg/mcpserver/cli/cli_test.go @@ -35,10 +35,11 @@ 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 := `"name=r,dir=` + t.TempDir() + `,at=/r"` + 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":[` + rom + `]}}`, "does not send its own files"}, + {"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)) From 79e210b541b43b66328cb8223fe1887580f5a8be Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Tue, 24 Nov 2026 14:59:08 +0200 Subject: [PATCH 41/55] feat(mcpserver): Serve a wrapped handler A caller that serves more than the protocol, or checks each request first, had to copy Serve to serve its own handler. Add Server.Wrap, whose middleware Serve puts around Handler. Also close idle connections after a minute. Signed-off-by: Dragos Gheorghioiu --- pkg/mcpserver/http.go | 20 ++++++++++++++++---- pkg/mcpserver/http_test.go | 24 ++++++++++++++++++++++++ pkg/mcpserver/server.go | 1 + 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/pkg/mcpserver/http.go b/pkg/mcpserver/http.go index fa80c728..5f35c018 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 b9471b94..97f7f01c 100644 --- a/pkg/mcpserver/http_test.go +++ b/pkg/mcpserver/http_test.go @@ -50,6 +50,30 @@ func TestServe(t *testing.T) { }) } +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"}) diff --git a/pkg/mcpserver/server.go b/pkg/mcpserver/server.go index ef4c6961..b07cd378 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) { From f623d3acca7c60b81ffcbbfe462feda58d8af686 Mon Sep 17 00:00:00 2001 From: Alex-Andrei Cioc Date: Mon, 16 Nov 2026 18:00:39 +0200 Subject: [PATCH 42/55] chore(deps): Bump image-spec and go-archivefs Takes the EROFS, tar and CPIO fixes of go-archivefs. Signed-off-by: Alex-Andrei Cioc --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index 92a36ca2..c9c43b24 100644 --- a/go.mod +++ b/go.mod @@ -45,7 +45,7 @@ require ( github.com/stretchr/testify v1.12.1 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 @@ -64,7 +64,7 @@ require ( 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-20261118100745-28172ae5f28c + unikraft.com/x/image-spec v0.0.0-20261124155313-85c0a0fe8c4e 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 diff --git a/go.sum b/go.sum index 7d6c8ec4..775c73bd 100644 --- a/go.sum +++ b/go.sum @@ -479,8 +479,8 @@ github.com/transparency-dev/merkle v0.0.2 h1:Q9nBoQcZcgPamMkGn7ghV8XiTZ/kRxn1yCG 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= @@ -611,8 +611,8 @@ unikraft.com/x/fingerprint v0.0.0-20261111120215-5177d0f4c7b6 h1:ZJ3Pzaej6zNGKQ6 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-20261118100745-28172ae5f28c h1:elFIU1+WfpddUjduhY32pUsvNf4IXVxZ0NLpjnsmBhc= -unikraft.com/x/image-spec v0.0.0-20261118100745-28172ae5f28c/go.mod h1:YIkqwG7NBIMVwPKm2GUB0eMp5DGpk5cVBVD4AGuWAJA= +unikraft.com/x/image-spec v0.0.0-20261124155313-85c0a0fe8c4e h1:hK775KBjbzrALPR4tZ6me5/30XhxxHjPUg/nqnAmpoM= +unikraft.com/x/image-spec v0.0.0-20261124155313-85c0a0fe8c4e/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= From 51772541114da49f25341038f2bce5fdb076a867 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Wed, 25 Nov 2026 12:38:28 +0200 Subject: [PATCH 43/55] fix(mcp): Cap the output of a tool call A tool call kept all of its output in memory. A command such as `yes` in a sandbox grew it until the server ran out of memory, also for the other clients of a hosted server. The output now stops at 1 MiB, and the call fails with an error that says the rest is left out. Signed-off-by: Cezar Craciunoiu --- pkg/model/mcp/tools.go | 37 ++++++++++++++++++++++++++++++++----- pkg/model/mcp/tools_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/pkg/model/mcp/tools.go b/pkg/model/mcp/tools.go index da2ae8f7..2f1c8e24 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 1e9a5027..9f5b6f50 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) + } +} From 3ec8798fa9c6e64cca5d8cd37cc4a079cbda14aa Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Wed, 25 Nov 2026 12:39:31 +0200 Subject: [PATCH 44/55] fix(mcp): Give sandbox commands a time limit `sandbox_exec` ran a command with no time limit unless the call set `timeout_ms`, although the schema promised a default. Such a call held its server resources for as long as the client waited. A command now stops after 5 minutes by default, and `timeout_ms` takes 30 minutes at most. Signed-off-by: Cezar Craciunoiu --- internal/mcp/sandbox.go | 20 +++++++++++++------- internal/mcp/sandbox_test.go | 14 ++++++++++++++ 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/internal/mcp/sandbox.go b/internal/mcp/sandbox.go index e18c4c54..fde2f3fc 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,6 +89,8 @@ 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", @@ -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 a99286d2..bbbfbe98 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`, From ec47d75efd51cc0028de933a91e6b372714d5cd7 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Wed, 25 Nov 2026 16:05:47 +0200 Subject: [PATCH 45/55] gomod(deps): Bump the sandbox SDK It brings the size limit on ReadFile, from unikraft-cloud/go-sdk#366. Signed-off-by: Cezar Craciunoiu --- go.mod | 4 ++-- go.sum | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/go.mod b/go.mod index c9c43b24..787cc370 100644 --- a/go.mod +++ b/go.mod @@ -54,10 +54,10 @@ 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/plugins/sandbox v0.0.0-20261125131623-d66f7dd900a2 unikraft.com/cloud/sdk v0.4.6-staging.6 unikraft.com/cloud/sdk/build v0.4.6-staging.6 - unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.6 + unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.7 unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d unikraft.com/x/buildkit v0.0.0-20261111120215-5177d0f4c7b6 unikraft.com/x/colors v0.0.0-20261111120215-5177d0f4c7b6 diff --git a/go.sum b/go.sum index 775c73bd..27e7e45e 100644 --- a/go.sum +++ b/go.sum @@ -589,14 +589,14 @@ 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/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.6 h1:MwCmmpAs67WokCSsRgOj9DobyuM/wJQMbw0vxykRjDs= unikraft.com/cloud/sdk v0.4.6-staging.6/go.mod h1:0teeiz79WohtMx8rmkpI864KE5PW3YlJWzomcTCLRdk= 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.6 h1:BgT7oj8YZiQ1EOfS6u2//gW0GPLIVzkpweLY3ChxMyg= -unikraft.com/cloud/sdk/plugins/sandbox v0.4.6-staging.6/go.mod h1:Vf254Ugp9TgkEEb23OIxV08bZLSkrxw5kk519em69go= +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-20261120101822-1135355f7e0d h1:sTPtr5YO1Ye+xPHlnbYbocbPAD/uupFrc3UDhxJOEF8= unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d/go.mod h1:aRRxLJqi1sUh/dFCJ1Kan/6hcGeq14hLs50X6RlUnuM= unikraft.com/x/buildkit v0.0.0-20261111120215-5177d0f4c7b6 h1:/7BTbMIFXN81vbpO3oB2Vh/97BBCpYIAJXP/z3d4qao= From a26ebe7b45dba595bcfcd584fe216a5b33c2e232 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Wed, 25 Nov 2026 13:31:37 +0200 Subject: [PATCH 46/55] fix(mcp): Cap the size of a sandbox file read sandbox_read loaded the whole file into the memory of the server, which a hosted server shares among its users. A big file could run it out of memory. Read at most the 1 MiB that a tool call can give, and say so in the description of the tool. Signed-off-by: Cezar Craciunoiu --- internal/cmd/mcp_tools.go | 2 +- internal/mcp/sandbox.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/cmd/mcp_tools.go b/internal/cmd/mcp_tools.go index a1430cb6..3d0a1a79 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/mcp/sandbox.go b/internal/mcp/sandbox.go index fde2f3fc..c5ab178b 100644 --- a/internal/mcp/sandbox.go +++ b/internal/mcp/sandbox.go @@ -95,7 +95,7 @@ func AddSandboxTools(tools *modelmcp.Tools, commands SandboxCommands) error { 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 { From f22ea1b0a564b2e56123bc38ec702243a0894211 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Wed, 25 Nov 2026 18:34:51 +0200 Subject: [PATCH 47/55] gomod(deps): Bump the SDK It brings the lineage package, from unikraft-cloud/go-sdk#356 and unikraft-cloud/go-sdk#364. Signed-off-by: Cezar Craciunoiu --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index 787cc370..e00eea2c 100644 --- a/go.mod +++ b/go.mod @@ -55,7 +55,7 @@ require ( mvdan.cc/sh/v3 v3.14.1 sigs.k8s.io/yaml v1.6.0 unikraft.com/cloud/plugins/sandbox v0.0.0-20261125131623-d66f7dd900a2 - unikraft.com/cloud/sdk v0.4.6-staging.6 + 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-20261120101822-1135355f7e0d diff --git a/go.sum b/go.sum index 27e7e45e..7f1832b1 100644 --- a/go.sum +++ b/go.sum @@ -591,8 +591,8 @@ 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-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.6 h1:MwCmmpAs67WokCSsRgOj9DobyuM/wJQMbw0vxykRjDs= -unikraft.com/cloud/sdk v0.4.6-staging.6/go.mod h1:0teeiz79WohtMx8rmkpI864KE5PW3YlJWzomcTCLRdk= +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= From e6db4e73230507aed5c694c4892aa873c30ea7cf Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Tue, 24 Nov 2026 17:59:59 +0200 Subject: [PATCH 48/55] fix(tui): Send reader messages to their own panel The panel stack sends every message to all subpanels, so a second reader panel took the reader of the first and doubled its polls. Reader messages now carry their panel, and other panels skip them. Signed-off-by: Cezar Craciunoiu --- pkg/model/tui/panel_reader.go | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/pkg/model/tui/panel_reader.go b/pkg/model/tui/panel_reader.go index 843dfbe3..b90d97af 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 } @@ -108,6 +112,9 @@ func (p *ReaderPanel) Update(msg tea.Msg) (tea.Model, tea.Cmd) { 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 +130,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() @@ -251,13 +261,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} }) } From 800d2efde33e4b85139485a1f8bcb170b7dfb446 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Tue, 24 Nov 2026 18:00:00 +0200 Subject: [PATCH 49/55] feat(tui): Load a reader panel on focus A reader panel fetched its reader as soon as it was shown, which is costly when the reader lists a whole metro. LoadOnFocus makes a panel fetch it the first time it gets focus. Signed-off-by: Cezar Craciunoiu --- pkg/model/tui/panel_reader.go | 22 +++++++++++++-- pkg/model/tui/tui_test.go | 53 +++++++++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) diff --git a/pkg/model/tui/panel_reader.go b/pkg/model/tui/panel_reader.go index b90d97af..5a5afb14 100644 --- a/pkg/model/tui/panel_reader.go +++ b/pkg/model/tui/panel_reader.go @@ -50,6 +50,7 @@ type ReaderPanel struct { reader io.ReadCloser readerFunc ReaderFunc follow bool + onFocus bool viewport viewport.Model buf bytes.Buffer @@ -81,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 @@ -109,6 +120,10 @@ 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: @@ -188,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() diff --git a/pkg/model/tui/tui_test.go b/pkg/model/tui/tui_test.go index 26a39ee3..b4486a45 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()) +} From b82cf2dd751160202229fd5ba0bb9a7f06564458 Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Tue, 24 Nov 2026 18:00:05 +0200 Subject: [PATCH 50/55] feat(cmd)!: Show the lineage in history commands The history commands listed only checkpoints, so the clones and templates around an instance stayed hidden. instance, checkpoint and the new template history now draw the whole lineage tree as a graph column of the table. They list the metro and read the checkpoint histories to build it. The TUI shows the graph in a History panel of the instance view. Closes: TOOL-1772 Signed-off-by: Cezar Craciunoiu --- cmd/unikraft/help_test.go | 1 + .../integration/instance_checkpoint_test.go | 29 +- .../integration/instance_template_test.go | 4 + cmd/unikraft/testdata/TestHelp/instances | 118 +++++- internal/cmd/instance_checkpoints.go | 115 +----- internal/cmd/instance_templates.go | 35 +- internal/cmd/instances.go | 34 +- internal/cmd/instances_history.go | 347 ++++++++++++++++++ internal/cmd/instances_tui.go | 27 ++ internal/cmd/output_test.go | 17 +- .../cmd/testdata/TestOutput/instance-history | 70 +++- 11 files changed, 640 insertions(+), 157 deletions(-) create mode 100644 internal/cmd/instances_history.go diff --git a/cmd/unikraft/help_test.go b/cmd/unikraft/help_test.go index 488f2ad2..ee7788e7 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/instance_checkpoint_test.go b/cmd/unikraft/integration/instance_checkpoint_test.go index 99fbb459..bb309546 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 13271c02..377c19cf 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/testdata/TestHelp/instances b/cmd/unikraft/testdata/TestHelp/instances index 51ab4cc9..403a796e 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 @@ -1517,6 +1517,8 @@ Templates: Create an instance template. edit Edit an instance template. + history + Show the lineage of an instance template. Fields: metro @@ -1966,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. @@ -1987,7 +2048,7 @@ Checkpoints: edit Edit an instance checkpoint. history - Show the history of a checkpoint. + Show the lineage of a checkpoint. Fields: metro @@ -2480,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 @@ -2817,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 diff --git a/internal/cmd/instance_checkpoints.go b/internal/cmd/instance_checkpoints.go index 1c26f4e0..580ea49c 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 f7c33026..e7a811d0 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 { @@ -495,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 a820ba1c..f6ab25ae 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."` @@ -2126,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 00000000..bd124719 --- /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_tui.go b/internal/cmd/instances_tui.go index 15bbe259..d8be338e 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/output_test.go b/internal/cmd/output_test.go index 49f09786..9e93d088 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) diff --git a/internal/cmd/testdata/TestOutput/instance-history b/internal/cmd/testdata/TestOutput/instance-history index 0817f328..f95ba22c 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" } ] From 0cbf0fc0d4c4e1dde63980daacee7520d738bcee Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Thu, 26 Nov 2026 16:03:53 +0000 Subject: [PATCH 51/55] gomod(deps): Update x to a81b5204c19b Bump build and image-spec together, since build needs the accessor's resolver from the same commit. Build now returns a Built, with the images or else what the packer pushed. A build here never sets Push, so it only has images. Signed-off-by: Justin Chadwell --- go.mod | 4 ++-- go.sum | 8 ++++---- internal/cmd/build_native.go | 6 ++++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/go.mod b/go.mod index e00eea2c..08260f4e 100644 --- a/go.mod +++ b/go.mod @@ -58,13 +58,13 @@ require ( 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-20261120101822-1135355f7e0d + 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-20261124155313-85c0a0fe8c4e + 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 diff --git a/go.sum b/go.sum index 7f1832b1..5f0fdfa3 100644 --- a/go.sum +++ b/go.sum @@ -597,8 +597,8 @@ unikraft.com/cloud/sdk/build v0.4.6-staging.6 h1:sl5lpnu8FASorQASlE+tXOf6AddsUlg 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-20261120101822-1135355f7e0d h1:sTPtr5YO1Ye+xPHlnbYbocbPAD/uupFrc3UDhxJOEF8= -unikraft.com/x/build v0.0.0-20261120101822-1135355f7e0d/go.mod h1:aRRxLJqi1sUh/dFCJ1Kan/6hcGeq14hLs50X6RlUnuM= +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= @@ -611,8 +611,8 @@ unikraft.com/x/fingerprint v0.0.0-20261111120215-5177d0f4c7b6 h1:ZJ3Pzaej6zNGKQ6 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-20261124155313-85c0a0fe8c4e h1:hK775KBjbzrALPR4tZ6me5/30XhxxHjPUg/nqnAmpoM= -unikraft.com/x/image-spec v0.0.0-20261124155313-85c0a0fe8c4e/go.mod h1:YIkqwG7NBIMVwPKm2GUB0eMp5DGpk5cVBVD4AGuWAJA= +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= diff --git a/internal/cmd/build_native.go b/internal/cmd/build_native.go index d94bca51..b04ca349 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() From 030a4eded7f05fc7fbe60c12dfc02a2a0c1da3eb Mon Sep 17 00:00:00 2001 From: Cezar Craciunoiu Date: Thu, 26 Nov 2026 18:29:10 +0200 Subject: [PATCH 52/55] test(integration): Use the staging sandbox plugin The sandbox tests ran on plugins/sandbox:latest, which does not know the max_size field from #679, so file reads failed with 400. Use plugins/sandbox:staging, which the plugins repo publishes from its prod-staging branch. Only the staging tests use the plugin. Signed-off-by: Cezar Craciunoiu --- cmd/unikraft/integration/instance_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/unikraft/integration/instance_test.go b/cmd/unikraft/integration/instance_test.go index 4a96c8c3..1df7372f 100644 --- a/cmd/unikraft/integration/instance_test.go +++ b/cmd/unikraft/integration/instance_test.go @@ -78,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 From c07fa96d0d0b086dae8d04d235f94d1893743557 Mon Sep 17 00:00:00 2001 From: Justin Chadwell Date: Thu, 26 Nov 2026 17:13:48 +0000 Subject: [PATCH 53/55] gomod(deps): Pin lipgloss to upstream main charmbracelet/lipgloss#746 has merged, so we don't need our fork for the Windows startup hang anymore. No release has it yet though, so pin to the merge commit instead. That moves us past v2.1.1, up from the v2.0.6 we required before. Signed-off-by: Justin Chadwell --- go.mod | 6 +----- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/go.mod b/go.mod index 08260f4e..c62a55e0 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ tool github.com/caarlos0/svu/v3 require ( charm.land/bubbles/v2 v2.2.1 charm.land/bubbletea/v2 v2.1.2 - charm.land/lipgloss/v2 v2.0.6 + 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 @@ -213,10 +213,6 @@ require ( 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 5f0fdfa3..3a407567 100644 --- a/go.sum +++ b/go.sum @@ -4,6 +4,8 @@ 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= @@ -477,8 +479,6 @@ 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-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= From 9e49fa6c1cb0124d520aa0249ef5baa747342881 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Fri, 27 Nov 2026 00:25:43 +0200 Subject: [PATCH 54/55] test(integration): Always pull the sandbox plugin A node pulls a tag other than latest only once, so the staging node kept an old plugins/sandbox:staging and the tests that start a command failed with 400. Set pull-policy=always on the plugin in the sandbox tests, so the node resolves the tag again on every run. Signed-off-by: Dragos Gheorghioiu --- cmd/unikraft/integration/mcp_test.go | 2 +- cmd/unikraft/integration/sandbox_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/unikraft/integration/mcp_test.go b/cmd/unikraft/integration/mcp_test.go index ada97a52..3b88f46c 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 adc17a6f..65160c5a 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", From 492674ae713188c7007f28ccb20eb796812e9f41 Mon Sep 17 00:00:00 2001 From: Dragos Gheorghioiu Date: Fri, 27 Nov 2026 15:32:41 +0200 Subject: [PATCH 55/55] chore: Raise the remote Taskfile timeout Task kills the clone of the x Taskfile after 5 seconds. On the Windows runners the clone often takes that long, so about one job in ten failed before any test ran. So give it 60 seconds. Signed-off-by: Dragos Gheorghioiu --- .taskrc.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.taskrc.yml b/.taskrc.yml index dc000618..04b72742 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: