From cdf3ccc87c9675e8cc390f2c051e46ad2027ddb8 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 15 Nov 2026 00:20:38 -0500 Subject: [PATCH 1/6] Fix kubectl apply retries by creating a fresh command per attempt Signed-off-by: Dave Protasowski --- pkg/install/install.go | 10 +++--- pkg/install/retry_test.go | 75 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 81 insertions(+), 4 deletions(-) create mode 100644 pkg/install/retry_test.go diff --git a/pkg/install/install.go b/pkg/install/install.go index 7454410..19bad2c 100644 --- a/pkg/install/install.go +++ b/pkg/install/install.go @@ -257,14 +257,16 @@ func runCommand(c *exec.Cmd) error { // retryingApply retries a kubectl apply call with the given path 3 times, sleeping // for 10s between each try. func retryingApply(path string) error { - cmd := exec.Command("kubectl", "apply", "-f", path) var err error for i := 0; i < 3; i++ { - err = runCommand(cmd) + // An exec.Cmd cannot be run more than once, even if its first run fails. + err = runCommand(exec.Command("kubectl", "apply", "-f", path)) if err == nil { - break + return nil + } + if i < 2 { + time.Sleep(10 * time.Second) } - time.Sleep(10 * time.Second) } return err } diff --git a/pkg/install/retry_test.go b/pkg/install/retry_test.go new file mode 100644 index 0000000..964bb9e --- /dev/null +++ b/pkg/install/retry_test.go @@ -0,0 +1,75 @@ +// Copyright © 2026 The Knative Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package install + +import ( + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" +) + +func TestRetryingApply(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake kubectl uses a shell script") + } + for _, tt := range []struct { + name string + failures string + wantCalls int + wantErr bool + }{ + {name: "first attempt succeeds", failures: "0", wantCalls: 1}, + {name: "transient failure", failures: "1", wantCalls: 2}, + {name: "attempts exhausted", failures: "3", wantCalls: 3, wantErr: true}, + } { + t.Run(tt.name, func(t *testing.T) { + dir := t.TempDir() + calls := filepath.Join(dir, "calls") + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("QUICKSTART_TEST_CALLS", calls) + t.Setenv("QUICKSTART_TEST_FAILURES", tt.failures) + script := `#!/bin/sh +count=0 +if [ -f "$QUICKSTART_TEST_CALLS" ]; then + read -r count < "$QUICKSTART_TEST_CALLS" +fi +count=$((count + 1)) +printf '%s\n' "$count" > "$QUICKSTART_TEST_CALLS" +if [ "$*" != 'apply -f test.yaml' ]; then exit 99; fi +if [ "$count" -le "$QUICKSTART_TEST_FAILURES" ]; then exit 1; fi +` + if err := os.WriteFile(filepath.Join(dir, "kubectl"), []byte(script), 0755); err != nil { + t.Fatal(err) + } + err := retryingApply("test.yaml") + if (err != nil) != tt.wantErr { + t.Fatalf("retryingApply() error = %v, wantErr %v", err, tt.wantErr) + } + if err != nil && err.Error() != "exit status 1" { + t.Fatalf("got %v, want the final kubectl error", err) + } + out, readErr := os.ReadFile(calls) + if readErr != nil { + t.Fatal(readErr) + } + if got := strings.TrimSpace(string(out)); got != strconv.Itoa(tt.wantCalls) { + t.Errorf("kubectl ran %s times, want %d", got, tt.wantCalls) + } + }) + } +} From 8727371caa2e44c8bc79dd5699a0e501f99245f6 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 15 Nov 2026 00:37:06 -0500 Subject: [PATCH 2/6] Test retry behavior with small in-memory callbacks Signed-off-by: Dave Protasowski --- pkg/install/install.go | 14 +++++-- pkg/install/retry_test.go | 78 +++++++++++++++++++-------------------- 2 files changed, 48 insertions(+), 44 deletions(-) diff --git a/pkg/install/install.go b/pkg/install/install.go index 19bad2c..101bbbf 100644 --- a/pkg/install/install.go +++ b/pkg/install/install.go @@ -257,15 +257,21 @@ func runCommand(c *exec.Cmd) error { // retryingApply retries a kubectl apply call with the given path 3 times, sleeping // for 10s between each try. func retryingApply(path string) error { + return retryCommand(func() *exec.Cmd { + return exec.Command("kubectl", "apply", "-f", path) + }, runCommand, time.Sleep) +} + +func retryCommand(command func() *exec.Cmd, run func(*exec.Cmd) error, sleep func(time.Duration)) error { var err error - for i := 0; i < 3; i++ { + for attempt := 0; attempt < 3; attempt++ { // An exec.Cmd cannot be run more than once, even if its first run fails. - err = runCommand(exec.Command("kubectl", "apply", "-f", path)) + err = run(command()) if err == nil { return nil } - if i < 2 { - time.Sleep(10 * time.Second) + if attempt < 2 { + sleep(10 * time.Second) } } return err diff --git a/pkg/install/retry_test.go b/pkg/install/retry_test.go index 964bb9e..48afde4 100644 --- a/pkg/install/retry_test.go +++ b/pkg/install/retry_test.go @@ -15,60 +15,58 @@ package install import ( - "os" - "path/filepath" - "runtime" - "strconv" - "strings" + "errors" + "os/exec" "testing" + "time" ) -func TestRetryingApply(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("fake kubectl uses a shell script") - } +func TestRetryCommand(t *testing.T) { for _, tt := range []struct { name string - failures string + failures int wantCalls int wantErr bool }{ - {name: "first attempt succeeds", failures: "0", wantCalls: 1}, - {name: "transient failure", failures: "1", wantCalls: 2}, - {name: "attempts exhausted", failures: "3", wantCalls: 3, wantErr: true}, + {name: "immediate success", wantCalls: 1}, + {name: "transient failure", failures: 1, wantCalls: 2}, + {name: "attempts exhausted", failures: 3, wantCalls: 3, wantErr: true}, } { t.Run(tt.name, func(t *testing.T) { - dir := t.TempDir() - calls := filepath.Join(dir, "calls") - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("QUICKSTART_TEST_CALLS", calls) - t.Setenv("QUICKSTART_TEST_FAILURES", tt.failures) - script := `#!/bin/sh -count=0 -if [ -f "$QUICKSTART_TEST_CALLS" ]; then - read -r count < "$QUICKSTART_TEST_CALLS" -fi -count=$((count + 1)) -printf '%s\n' "$count" > "$QUICKSTART_TEST_CALLS" -if [ "$*" != 'apply -f test.yaml' ]; then exit 99; fi -if [ "$count" -le "$QUICKSTART_TEST_FAILURES" ]; then exit 1; fi -` - if err := os.WriteFile(filepath.Join(dir, "kubectl"), []byte(script), 0755); err != nil { - t.Fatal(err) - } - err := retryingApply("test.yaml") + failure := errors.New("apply failed") + calls, sleeps := 0, 0 + seen := map[*exec.Cmd]bool{} + err := retryCommand( + func() *exec.Cmd { return &exec.Cmd{} }, + func(cmd *exec.Cmd) error { + if seen[cmd] { + t.Error("reused a command") + } + seen[cmd] = true + calls++ + if calls <= tt.failures { + return failure + } + return nil + }, + func(delay time.Duration) { + sleeps++ + if delay != 10*time.Second { + t.Errorf("delay = %s, want 10s", delay) + } + }, + ) if (err != nil) != tt.wantErr { - t.Fatalf("retryingApply() error = %v, wantErr %v", err, tt.wantErr) + t.Errorf("error = %v, wantErr %v", err, tt.wantErr) } - if err != nil && err.Error() != "exit status 1" { - t.Fatalf("got %v, want the final kubectl error", err) + if tt.wantErr && !errors.Is(err, failure) { + t.Errorf("error = %v, want original error", err) } - out, readErr := os.ReadFile(calls) - if readErr != nil { - t.Fatal(readErr) + if calls != tt.wantCalls { + t.Errorf("calls = %d, want %d", calls, tt.wantCalls) } - if got := strings.TrimSpace(string(out)); got != strconv.Itoa(tt.wantCalls) { - t.Errorf("kubectl ran %s times, want %d", got, tt.wantCalls) + if sleeps != tt.wantCalls-1 { + t.Errorf("sleeps = %d, want %d", sleeps, tt.wantCalls-1) } }) } From e3dc4c0d02a2e07aa08bc0d29c006961e1dde48b Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 15 Nov 2026 00:20:38 -0500 Subject: [PATCH 3/6] Select the requested cluster context before installing Knative Signed-off-by: Dave Protasowski --- pkg/kind/context_test.go | 131 +++++++++++++++++++++++++++++++++++ pkg/kind/kind.go | 9 ++- pkg/minikube/context_test.go | 120 ++++++++++++++++++++++++++++++++ pkg/minikube/minikube.go | 7 +- 4 files changed, 264 insertions(+), 3 deletions(-) create mode 100644 pkg/kind/context_test.go create mode 100644 pkg/minikube/context_test.go diff --git a/pkg/kind/context_test.go b/pkg/kind/context_test.go new file mode 100644 index 0000000..48dbf8f --- /dev/null +++ b/pkg/kind/context_test.go @@ -0,0 +1,131 @@ +// Copyright © 2026 The Knative Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package kind + +import ( + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestReuseSelectsRequestedContext(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake commands use shell scripts") + } + for _, tt := range []struct { + name string + failSelection bool + wantErr bool + }{ + {name: "install into requested cluster"}, + {name: "missing context prevents installation", failSelection: true, wantErr: true}, + } { + t.Run(tt.name, func(t *testing.T) { + oldName, oldInstall := clusterName, installKnative + clusterName, installKnative = "demo", true + t.Cleanup(func() { clusterName, installKnative = oldName, oldInstall }) + dir := t.TempDir() + calls := filepath.Join(dir, "calls") + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("QUICKSTART_TEST_CALLS", calls) + fail := "" + if tt.failSelection { + fail = "yes" + } + t.Setenv("QUICKSTART_TEST_FAIL_SELECTION", fail) + for name, script := range map[string]string{ + "kind": `#!/bin/sh +case "$*" in + 'version -q') echo v0.31.0;; + 'get clusters -q') echo demo;; + *) exit 99;; +esac +`, + "kubectl": `#!/bin/sh +printf '%s\n' "$*" >> "$QUICKSTART_TEST_CALLS" +case "$*" in + 'version --client -o json') echo '{"clientVersion":{"gitVersion":"v1.35.0"}}';; + *'get namespaces') echo default;; + 'config use-context kind-demo') if [ -n "$QUICKSTART_TEST_FAIL_SELECTION" ]; then exit 1; fi;; + 'get endpointslice '*) echo ready;; + 'apply -f -') while IFS= read -r line; do :; done;; +esac +`, + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0755); err != nil { + t.Fatal(err) + } + } + input, err := os.CreateTemp(dir, "answers") + if err != nil { + t.Fatal(err) + } + defer input.Close() + if _, err := input.WriteString("n\n"); err != nil { + t.Fatal(err) + } + if _, err := input.Seek(0, 0); err != nil { + t.Fatal(err) + } + oldStdin := os.Stdin + os.Stdin = input + t.Cleanup(func() { os.Stdin = oldStdin }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/v1.47/info" { + t.Errorf("unexpected Docker call: %s %s", r.Method, r.URL.Path) + w.WriteHeader(500) + return + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{}`) + })) + defer server.Close() + t.Setenv("DOCKER_HOST", server.URL) + t.Setenv("DOCKER_API_VERSION", "1.47") + t.Setenv("DOCKER_TLS_VERIFY", "") + + err = SetUp("demo", "", true, true, false, "", "", 80) + if (err != nil) != tt.wantErr { + t.Fatalf("SetUp() error = %v, wantErr %v", err, tt.wantErr) + } + out, err := os.ReadFile(calls) + if err != nil { + t.Fatal(err) + } + log := string(out) + namespaceCheck := strings.Index(log, "--context kind-demo get namespaces\n") + selection := strings.Index(log, "config use-context kind-demo\n") + apply := strings.Index(log, "apply -f ") + if namespaceCheck < 0 { + t.Errorf("namespace check did not target kind-demo: %s", log) + } + if selection < namespaceCheck || selection < 0 { + t.Errorf("requested context was not selected after checking its namespaces: %s", log) + } + if tt.failSelection { + if apply >= 0 { + t.Errorf("applied manifests after context selection failed: %s", log) + } + } else if apply < selection || apply < 0 { + t.Errorf("manifests were not applied after selecting the requested context: %s", log) + } + }) + } +} diff --git a/pkg/kind/kind.go b/pkg/kind/kind.go index b2a66cd..40d12c1 100644 --- a/pkg/kind/kind.go +++ b/pkg/kind/kind.go @@ -80,6 +80,11 @@ func SetUp(name, kVersion string, installServing, installEventing, installKindRe return fmt.Errorf("failed to create kind cluster: %w", err) } if installKnative { + // Creating a cluster selects its context, but reusing one does not. + // Fail before applying manifests if the requested context is unavailable. + if err := runCommandWithOutput(exec.Command("kubectl", "config", "use-context", "kind-"+clusterName)); err != nil { + return fmt.Errorf("failed to select kind cluster %s: %w", clusterName, err) + } if installServing { // Disable tag resolution for localhost registry, since there's no // way to redirect Knative Serving to use the kind-registry name. @@ -232,7 +237,7 @@ data: localRegistryHosting.v1: | host: "localhost:%s" help: "https://kind.sigs.k8s.io/docs/user/local-registry/"`, container_reg_port) - createLocalRegistryConfigMap := exec.Command("kubectl", "apply", "-f", "-") + createLocalRegistryConfigMap := exec.Command("kubectl", "--context", "kind-"+clusterName, "apply", "-f", "-") createLocalRegistryConfigMap.Stdin = strings.NewReader(cm) // } @@ -293,7 +298,7 @@ func checkForExistingCluster(registry bool, extraMountHostPath string, extraMoun } } else { fmt.Println("\n Installation skipped") - checkKnativeNamespace := exec.Command("kubectl", "get", "namespaces") + checkKnativeNamespace := exec.Command("kubectl", "--context", "kind-"+clusterName, "get", "namespaces") output, err := checkKnativeNamespace.CombinedOutput() namespaces := string(output) if err != nil { diff --git a/pkg/minikube/context_test.go b/pkg/minikube/context_test.go new file mode 100644 index 0000000..fb00fcc --- /dev/null +++ b/pkg/minikube/context_test.go @@ -0,0 +1,120 @@ +// Copyright © 2026 The Knative Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package minikube + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestReuseSelectsRequestedContext(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("fake commands use shell scripts") + } + for _, tt := range []struct { + name string + cluster string + args []string + profile string + failSelection bool + }{ + {name: "default profile", cluster: "knative", profile: "knative"}, + {name: "named profile", cluster: "demo", profile: "demo"}, + {name: "passthrough profile override", cluster: "unused", args: []string{"--profile=demo"}, profile: "demo"}, + {name: "missing context prevents installation", cluster: "demo", profile: "demo", failSelection: true}, + } { + t.Run(tt.name, func(t *testing.T) { + oldName, oldInstall, oldArgs := clusterName, installKnative, customMinikubeArgs + installKnative, customMinikubeArgs = true, nil + t.Cleanup(func() { clusterName, installKnative, customMinikubeArgs = oldName, oldInstall, oldArgs }) + dir := t.TempDir() + calls := filepath.Join(dir, "calls") + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + t.Setenv("QUICKSTART_TEST_CALLS", calls) + t.Setenv("QUICKSTART_TEST_PROFILE", tt.profile) + fail := "" + if tt.failSelection { + fail = "yes" + } + t.Setenv("QUICKSTART_TEST_FAIL_SELECTION", fail) + for name, script := range map[string]string{ + "minikube": `#!/bin/sh +case "$*" in + 'version --short') echo v1.38.0;; + 'profile list') echo "$QUICKSTART_TEST_PROFILE";; + *) exit 99;; +esac +`, + "kubectl": `#!/bin/sh +printf '%s\n' "$*" >> "$QUICKSTART_TEST_CALLS" +case "$*" in + 'version --client -o json') echo '{"clientVersion":{"gitVersion":"v1.35.0"}}';; + *'get namespaces') echo default;; + "config use-context $QUICKSTART_TEST_PROFILE") if [ -n "$QUICKSTART_TEST_FAIL_SELECTION" ]; then exit 1; fi;; + 'get endpointslice '*) echo ready;; + 'apply -f -') while IFS= read -r line; do :; done;; +esac +`, + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0755); err != nil { + t.Fatal(err) + } + } + input, err := os.CreateTemp(dir, "answers") + if err != nil { + t.Fatal(err) + } + defer input.Close() + if _, err := input.WriteString("n\n\n"); err != nil { + t.Fatal(err) + } + if _, err := input.Seek(0, 0); err != nil { + t.Fatal(err) + } + oldStdin := os.Stdin + os.Stdin = input + t.Cleanup(func() { os.Stdin = oldStdin }) + + err = SetUp(tt.cluster, "", true, true, tt.args) + if (err != nil) != tt.failSelection { + t.Fatalf("SetUp() error = %v, wantErr %v", err, tt.failSelection) + } + out, err := os.ReadFile(calls) + if err != nil { + t.Fatal(err) + } + log := string(out) + namespaceCheck := strings.Index(log, "--context "+tt.profile+" get namespaces\n") + selection := strings.Index(log, "config use-context "+tt.profile+"\n") + apply := strings.Index(log, "apply -f ") + if namespaceCheck < 0 { + t.Errorf("namespace check did not target %s: %s", tt.profile, log) + } + if selection < namespaceCheck || selection < 0 { + t.Errorf("requested context was not selected after checking its namespaces: %s", log) + } + if tt.failSelection { + if apply >= 0 { + t.Errorf("applied manifests after context selection failed: %s", log) + } + } else if apply < selection || apply < 0 { + t.Errorf("manifests were not applied after selecting the requested context: %s", log) + } + }) + } +} diff --git a/pkg/minikube/minikube.go b/pkg/minikube/minikube.go index 0411b2a..59d2a40 100644 --- a/pkg/minikube/minikube.go +++ b/pkg/minikube/minikube.go @@ -98,6 +98,11 @@ func SetUp(name, kVersion string, installServing, installEventing bool, minikube fmt.Println("\nPress the Enter key to continue") fmt.Scanln() if installKnative { + // Reusing a profile (or starting with --keep-context) does not select + // its context. Never install into an unrelated current context. + if err := runCommandWithOutput(exec.Command("kubectl", "config", "use-context", clusterName)); err != nil { + return fmt.Errorf("failed to select minikube cluster %s: %w", clusterName, err) + } if installServing { if err := install.Serving(""); err != nil { return fmt.Errorf("failed to install serving to minikube cluster %s: %w", clusterName, err) @@ -188,7 +193,7 @@ func checkForExistingCluster() error { fmt.Scanf("%s", &resp) if strings.ToLower(resp) != "y" { fmt.Println("Installation skipped") - checkKnativeNamespace := exec.Command("kubectl", "get", "namespaces") + checkKnativeNamespace := exec.Command("kubectl", "--context", clusterName, "get", "namespaces") output, err := checkKnativeNamespace.CombinedOutput() namespaces := string(output) if err != nil { From 4d96c3080d7ffc2603fe13bb969549e9fb7f51b3 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 15 Nov 2026 00:24:58 -0500 Subject: [PATCH 4/6] Document safe context arguments for gosec Signed-off-by: Dave Protasowski --- pkg/kind/kind.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pkg/kind/kind.go b/pkg/kind/kind.go index 40d12c1..7c8ed28 100644 --- a/pkg/kind/kind.go +++ b/pkg/kind/kind.go @@ -82,6 +82,7 @@ func SetUp(name, kVersion string, installServing, installEventing, installKindRe if installKnative { // Creating a cluster selects its context, but reusing one does not. // Fail before applying manifests if the requested context is unavailable. + // #nosec G204 -- Fixed executable; the context is one argument, not shell input. if err := runCommandWithOutput(exec.Command("kubectl", "config", "use-context", "kind-"+clusterName)); err != nil { return fmt.Errorf("failed to select kind cluster %s: %w", clusterName, err) } @@ -237,6 +238,7 @@ data: localRegistryHosting.v1: | host: "localhost:%s" help: "https://kind.sigs.k8s.io/docs/user/local-registry/"`, container_reg_port) + // #nosec G204 -- Fixed executable; the context is one argument, not shell input. createLocalRegistryConfigMap := exec.Command("kubectl", "--context", "kind-"+clusterName, "apply", "-f", "-") createLocalRegistryConfigMap.Stdin = strings.NewReader(cm) @@ -298,6 +300,7 @@ func checkForExistingCluster(registry bool, extraMountHostPath string, extraMoun } } else { fmt.Println("\n Installation skipped") + // #nosec G204 -- Fixed executable; the context is one argument, not shell input. checkKnativeNamespace := exec.Command("kubectl", "--context", "kind-"+clusterName, "get", "namespaces") output, err := checkKnativeNamespace.CombinedOutput() namespaces := string(output) From 736e265db7b06f1ed1b29ab5eb1c91f2515f4e15 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 15 Nov 2026 00:37:06 -0500 Subject: [PATCH 5/6] Target each installation command without changing current context Signed-off-by: Dave Protasowski --- pkg/install/install.go | 72 +++++++++---------- pkg/install/installer.go | 49 +++++++++++++ pkg/install/installer_test.go | 43 +++++++++++ pkg/kind/context_test.go | 131 ---------------------------------- pkg/kind/kind.go | 15 ++-- pkg/minikube/context_test.go | 120 ------------------------------- pkg/minikube/minikube.go | 14 ++-- 7 files changed, 138 insertions(+), 306 deletions(-) create mode 100644 pkg/install/installer.go create mode 100644 pkg/install/installer_test.go delete mode 100644 pkg/kind/context_test.go delete mode 100644 pkg/minikube/context_test.go diff --git a/pkg/install/install.go b/pkg/install/install.go index 101bbbf..95e7cd7 100644 --- a/pkg/install/install.go +++ b/pkg/install/install.go @@ -63,21 +63,21 @@ var KourierVersion string var EventingVersion string // Kourier installs Kourier networking layer from Github YAML files -func Kourier() error { +func (i Installer) Kourier() error { fmt.Println("🕸️ Installing Kourier networking layer v" + KourierVersion + " ...") - if err := retryingApply("https://github.com/knative-sandbox/net-kourier/releases/download/knative-v" + KourierVersion + "/kourier.yaml"); err != nil { + if err := i.retryingApply("https://github.com/knative-sandbox/net-kourier/releases/download/knative-v" + KourierVersion + "/kourier.yaml"); err != nil { return fmt.Errorf("wait: %w", err) } - if err := waitForPodsReady("kourier-system"); err != nil { + if err := i.waitForPodsReady("kourier-system"); err != nil { return fmt.Errorf("kourier: %w", err) } - if err := waitForPodsReady("knative-serving"); err != nil { + if err := i.waitForPodsReady("knative-serving"); err != nil { return fmt.Errorf("serving: %w", err) } fmt.Println(" Kourier installed...") - ingress := exec.Command("kubectl", "patch", "configmap/config-network", "--namespace", "knative-serving", "--type", "merge", "--patch", "{\"data\":{\"ingress.class\":\"kourier.ingress.networking.knative.dev\"}}") + ingress := i.command("patch", "configmap/config-network", "--namespace", "knative-serving", "--type", "merge", "--patch", "{\"data\":{\"ingress.class\":\"kourier.ingress.networking.knative.dev\"}}") if err := runCommand(ingress); err != nil { return fmt.Errorf("ingress error: %w", err) } @@ -89,7 +89,7 @@ func Kourier() error { } // KourierKind runs the kind-specific setup for Kourier -func KourierKind() error { +func (i Installer) KourierKind() error { fmt.Println("🕸️ Configuring Kourier for Kind...") config := `apiVersion: v1 @@ -109,7 +109,7 @@ spec: port: 80 targetPort: 8080` - kourierIngress := exec.Command("kubectl", "apply", "-f", "-") + kourierIngress := i.command("apply", "-f", "-") kourierIngress.Stdin = strings.NewReader(config) if err := runCommand(kourierIngress); err != nil { return fmt.Errorf("kourier service: %w", err) @@ -117,7 +117,7 @@ spec: fmt.Println(" Kourier service installed...") - domainDns := exec.Command("kubectl", "patch", "configmap", "-n", "knative-serving", "config-domain", "-p", "{\"data\": {\"127.0.0.1.sslip.io\": \"\"}}") + domainDns := i.command("patch", "configmap", "-n", "knative-serving", "config-domain", "-p", "{\"data\": {\"127.0.0.1.sslip.io\": \"\"}}") if err := runCommand(domainDns); err != nil { return fmt.Errorf("domain dns: %w", err) } @@ -128,13 +128,13 @@ spec: } // KourierMinikube runs the minikube-specific setup for Kourier -func KourierMinikube() error { +func (i Installer) KourierMinikube() error { fmt.Println("🕸️ Configuring Kourier for Minikube...") - if err := retryingApply("https://github.com/knative/serving/releases/download/knative-v" + ServingVersion + "/serving-default-domain.yaml"); err != nil { + if err := i.retryingApply("https://github.com/knative/serving/releases/download/knative-v" + ServingVersion + "/serving-default-domain.yaml"); err != nil { return fmt.Errorf("default domain: %w", err) } - if err := waitForPodsReady("knative-serving"); err != nil { + if err := i.waitForPodsReady("knative-serving"); err != nil { return fmt.Errorf("core: %w", err) } @@ -145,37 +145,37 @@ func KourierMinikube() error { } // Serving installs Knative Serving from Github YAML files -func Serving(registries string) error { +func (i Installer) Serving(registries string) error { fmt.Println("🍿 Installing Knative Serving v" + ServingVersion + " ...") baseURL := "https://github.com/knative/serving/releases/download/knative-v" + ServingVersion - if err := retryingApply(baseURL + "/serving-crds.yaml"); err != nil { + if err := i.retryingApply(baseURL + "/serving-crds.yaml"); err != nil { return fmt.Errorf("wait: %w", err) } - if err := waitForCRDsEstablished(); err != nil { + if err := i.waitForCRDsEstablished(); err != nil { return fmt.Errorf("crds: %w", err) } fmt.Println(" CRDs installed...") - if err := retryingApply(baseURL + "/serving-core.yaml"); err != nil { + if err := i.retryingApply(baseURL + "/serving-core.yaml"); err != nil { return fmt.Errorf("wait: %w", err) } - if err := waitForPodsReady("knative-serving"); err != nil { + if err := i.waitForPodsReady("knative-serving"); err != nil { return fmt.Errorf("core: %w", err) } fmt.Println(" Core installed...") // Wait for webhook to be ready before attempting to patch configmaps - if err := waitForWebhookReady(); err != nil { + if err := i.waitForWebhookReady(); err != nil { return fmt.Errorf("webhook: %w", err) } if registries != "" { configPatch := fmt.Sprintf(`{"data":{"registries-skipping-tag-resolving":"%s"}}`, registries) - ignoreRegistry := exec.Command("kubectl", "patch", "configmap", "-n", "knative-serving", "config-deployment", "-p", configPatch) + ignoreRegistry := i.command("patch", "configmap", "-n", "knative-serving", "config-deployment", "-p", configPatch) if err := runCommand(ignoreRegistry); err != nil { return fmt.Errorf("tag resolving configuration: %w", err) } @@ -188,42 +188,42 @@ func Serving(registries string) error { } // Eventing installs Knative Eventing from Github YAML files -func Eventing() error { +func (i Installer) Eventing() error { fmt.Println("🔥 Installing Knative Eventing v" + EventingVersion + " ... ") baseURL := "https://github.com/knative/eventing/releases/download/knative-v" + EventingVersion - if err := retryingApply(baseURL + "/eventing-crds.yaml"); err != nil { + if err := i.retryingApply(baseURL + "/eventing-crds.yaml"); err != nil { return fmt.Errorf("wait: %w", err) } - if err := waitForCRDsEstablished(); err != nil { + if err := i.waitForCRDsEstablished(); err != nil { return fmt.Errorf("crds: %w", err) } fmt.Println(" CRDs installed...") - if err := retryingApply(baseURL + "/eventing-core.yaml"); err != nil { + if err := i.retryingApply(baseURL + "/eventing-core.yaml"); err != nil { return fmt.Errorf("wait: %w", err) } - if err := waitForPodsReady("knative-eventing"); err != nil { + if err := i.waitForPodsReady("knative-eventing"); err != nil { return fmt.Errorf("core: %w", err) } fmt.Println(" Core installed...") - if err := retryingApply(baseURL + "/in-memory-channel.yaml"); err != nil { + if err := i.retryingApply(baseURL + "/in-memory-channel.yaml"); err != nil { return fmt.Errorf("wait: %w", err) } - if err := waitForPodsReady("knative-eventing"); err != nil { + if err := i.waitForPodsReady("knative-eventing"); err != nil { return fmt.Errorf("channel: %w", err) } fmt.Println(" In-memory channel installed...") - if err := retryingApply(baseURL + "/mt-channel-broker.yaml"); err != nil { + if err := i.retryingApply(baseURL + "/mt-channel-broker.yaml"); err != nil { return fmt.Errorf("wait: %w", err) } - if err := waitForPodsReady("knative-eventing"); err != nil { + if err := i.waitForPodsReady("knative-eventing"); err != nil { return fmt.Errorf("broker: %w", err) } fmt.Println(" Mt-channel broker installed...") @@ -234,7 +234,7 @@ metadata: name: example-broker namespace: default` - exampleBroker := exec.Command("kubectl", "apply", "-f", "-") + exampleBroker := i.command("apply", "-f", "-") exampleBroker.Stdin = strings.NewReader(config) if err := runCommand(exampleBroker); err != nil { return fmt.Errorf("example broker: %w", err) @@ -256,9 +256,9 @@ func runCommand(c *exec.Cmd) error { // retryingApply retries a kubectl apply call with the given path 3 times, sleeping // for 10s between each try. -func retryingApply(path string) error { +func (i Installer) retryingApply(path string) error { return retryCommand(func() *exec.Cmd { - return exec.Command("kubectl", "apply", "-f", path) + return i.command("apply", "-f", path) }, runCommand, time.Sleep) } @@ -278,8 +278,8 @@ func retryCommand(command func() *exec.Cmd, run func(*exec.Cmd) error, sleep fun } // waitForCRDsEstablished waits for all CRDs to be established. -func waitForCRDsEstablished() error { - return runCommand(exec.Command("kubectl", "wait", "--for=condition=Established", "--all", "crd")) +func (i Installer) waitForCRDsEstablished() error { + return runCommand(i.command("wait", "--for=condition=Established", "--all", "crd")) } // CheckKubectlVersion validates that the user has a recent enough version of @@ -357,12 +357,12 @@ func parseKubectlVersion(jsonOut string) (int, int, error) { // is always evaluated first, so this waits for the pods to appear and then for // them to become Ready. This requires kubectl >= 1.33 for label-selector waits, // which is within the versions this plugin already supports. -func waitForPodsReady(ns string) error { - return runCommand(exec.Command("kubectl", "wait", "pod", "--timeout=10m", "--for=create", "--for=condition=Ready", "-l", "!job-name", "-n", ns)) +func (i Installer) waitForPodsReady(ns string) error { + return runCommand(i.command("wait", "pod", "--timeout=10m", "--for=create", "--for=condition=Ready", "-l", "!job-name", "-n", ns)) } // waitForWebhookReady waits for the Knative Serving webhook to be ready. -func waitForWebhookReady() error { +func (i Installer) waitForWebhookReady() error { fmt.Println(" Waiting for webhook to be ready...") // Retry for up to 2 minutes (12 attempts with 10s intervals) @@ -370,7 +370,7 @@ func waitForWebhookReady() error { // Check if the webhook service has ready endpointslices // NOTE: We use 'kubectl get' instead of 'kubectl wait' because kubectl wait's JSONPath // doesn't support checking if ANY endpoint is ready (wildcard [*] fails with multiple endpoints) - checkEndpointSlices := exec.Command("kubectl", "get", "endpointslice", + checkEndpointSlices := i.command("get", "endpointslice", "-l", "kubernetes.io/service-name=webhook", "-n", "knative-serving", "-o", "jsonpath={.items[*].endpoints[?(@.conditions.ready==true)]}") diff --git a/pkg/install/installer.go b/pkg/install/installer.go new file mode 100644 index 0000000..324ee91 --- /dev/null +++ b/pkg/install/installer.go @@ -0,0 +1,49 @@ +// Copyright © 2026 The Knative Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package install + +import "os/exec" + +// Installer targets every installation command at Context without changing the +// kubeconfig's current context. Its zero value uses kubectl's current context. +type Installer struct { + Context string +} + +func (i Installer) command(args ...string) *exec.Cmd { + if i.Context != "" { + args = append([]string{"--context", i.Context}, args...) + } + // #nosec G204 -- Fixed executable; arguments are passed directly, never through a shell. + return exec.Command("kubectl", args...) +} + +// Keep the package-level entry points available to callers using the current +// context. Quickstart uses an Installer with an explicit context instead. + +// Kourier installs Kourier using the current kubeconfig context. +func Kourier() error { return (Installer{}).Kourier() } + +// KourierKind configures Kourier for Kind using the current kubeconfig context. +func KourierKind() error { return (Installer{}).KourierKind() } + +// KourierMinikube configures Kourier for Minikube using the current context. +func KourierMinikube() error { return (Installer{}).KourierMinikube() } + +// Serving installs Knative Serving using the current kubeconfig context. +func Serving(registries string) error { return (Installer{}).Serving(registries) } + +// Eventing installs Knative Eventing using the current kubeconfig context. +func Eventing() error { return (Installer{}).Eventing() } diff --git a/pkg/install/installer_test.go b/pkg/install/installer_test.go new file mode 100644 index 0000000..e69f1b8 --- /dev/null +++ b/pkg/install/installer_test.go @@ -0,0 +1,43 @@ +// Copyright © 2026 The Knative Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package install + +import ( + "reflect" + "testing" +) + +func TestInstallerCommand(t *testing.T) { + for _, context := range []string{"", "knative", "kind-custom", "custom-profile"} { + t.Run("context="+context, func(t *testing.T) { + installer := Installer{Context: context} + want := []string{"kubectl"} + if context != "" { + want = append(want, "--context", context) + } + want = append(want, "get", "pods") + cmd := installer.command("get", "pods") + if !reflect.DeepEqual(cmd.Args, want) { + t.Errorf("args = %v, want %v", cmd.Args, want) + } + // Each command must carry its own context, rather than relying on a prior + // `kubectl config use-context` call that would override --keep-context. + again := installer.command("get", "pods") + if !reflect.DeepEqual(again.Args, want) { + t.Errorf("second command args = %v, want %v", again.Args, want) + } + }) + } +} diff --git a/pkg/kind/context_test.go b/pkg/kind/context_test.go deleted file mode 100644 index 48dbf8f..0000000 --- a/pkg/kind/context_test.go +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright © 2026 The Knative Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package kind - -import ( - "fmt" - "net/http" - "net/http/httptest" - "os" - "path/filepath" - "runtime" - "strings" - "testing" -) - -func TestReuseSelectsRequestedContext(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("fake commands use shell scripts") - } - for _, tt := range []struct { - name string - failSelection bool - wantErr bool - }{ - {name: "install into requested cluster"}, - {name: "missing context prevents installation", failSelection: true, wantErr: true}, - } { - t.Run(tt.name, func(t *testing.T) { - oldName, oldInstall := clusterName, installKnative - clusterName, installKnative = "demo", true - t.Cleanup(func() { clusterName, installKnative = oldName, oldInstall }) - dir := t.TempDir() - calls := filepath.Join(dir, "calls") - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("QUICKSTART_TEST_CALLS", calls) - fail := "" - if tt.failSelection { - fail = "yes" - } - t.Setenv("QUICKSTART_TEST_FAIL_SELECTION", fail) - for name, script := range map[string]string{ - "kind": `#!/bin/sh -case "$*" in - 'version -q') echo v0.31.0;; - 'get clusters -q') echo demo;; - *) exit 99;; -esac -`, - "kubectl": `#!/bin/sh -printf '%s\n' "$*" >> "$QUICKSTART_TEST_CALLS" -case "$*" in - 'version --client -o json') echo '{"clientVersion":{"gitVersion":"v1.35.0"}}';; - *'get namespaces') echo default;; - 'config use-context kind-demo') if [ -n "$QUICKSTART_TEST_FAIL_SELECTION" ]; then exit 1; fi;; - 'get endpointslice '*) echo ready;; - 'apply -f -') while IFS= read -r line; do :; done;; -esac -`, - } { - if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0755); err != nil { - t.Fatal(err) - } - } - input, err := os.CreateTemp(dir, "answers") - if err != nil { - t.Fatal(err) - } - defer input.Close() - if _, err := input.WriteString("n\n"); err != nil { - t.Fatal(err) - } - if _, err := input.Seek(0, 0); err != nil { - t.Fatal(err) - } - oldStdin := os.Stdin - os.Stdin = input - t.Cleanup(func() { os.Stdin = oldStdin }) - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path != "/v1.47/info" { - t.Errorf("unexpected Docker call: %s %s", r.Method, r.URL.Path) - w.WriteHeader(500) - return - } - w.Header().Set("Content-Type", "application/json") - fmt.Fprint(w, `{}`) - })) - defer server.Close() - t.Setenv("DOCKER_HOST", server.URL) - t.Setenv("DOCKER_API_VERSION", "1.47") - t.Setenv("DOCKER_TLS_VERIFY", "") - - err = SetUp("demo", "", true, true, false, "", "", 80) - if (err != nil) != tt.wantErr { - t.Fatalf("SetUp() error = %v, wantErr %v", err, tt.wantErr) - } - out, err := os.ReadFile(calls) - if err != nil { - t.Fatal(err) - } - log := string(out) - namespaceCheck := strings.Index(log, "--context kind-demo get namespaces\n") - selection := strings.Index(log, "config use-context kind-demo\n") - apply := strings.Index(log, "apply -f ") - if namespaceCheck < 0 { - t.Errorf("namespace check did not target kind-demo: %s", log) - } - if selection < namespaceCheck || selection < 0 { - t.Errorf("requested context was not selected after checking its namespaces: %s", log) - } - if tt.failSelection { - if apply >= 0 { - t.Errorf("applied manifests after context selection failed: %s", log) - } - } else if apply < selection || apply < 0 { - t.Errorf("manifests were not applied after selecting the requested context: %s", log) - } - }) - } -} diff --git a/pkg/kind/kind.go b/pkg/kind/kind.go index 7c8ed28..562c81d 100644 --- a/pkg/kind/kind.go +++ b/pkg/kind/kind.go @@ -80,12 +80,7 @@ func SetUp(name, kVersion string, installServing, installEventing, installKindRe return fmt.Errorf("failed to create kind cluster: %w", err) } if installKnative { - // Creating a cluster selects its context, but reusing one does not. - // Fail before applying manifests if the requested context is unavailable. - // #nosec G204 -- Fixed executable; the context is one argument, not shell input. - if err := runCommandWithOutput(exec.Command("kubectl", "config", "use-context", "kind-"+clusterName)); err != nil { - return fmt.Errorf("failed to select kind cluster %s: %w", clusterName, err) - } + installer := install.Installer{Context: "kind-" + clusterName} if installServing { // Disable tag resolution for localhost registry, since there's no // way to redirect Knative Serving to use the kind-registry name. @@ -94,18 +89,18 @@ func SetUp(name, kVersion string, installServing, installEventing, installKindRe if installKindRegistry { registries = fmt.Sprintf("localhost:%s", container_reg_port) } - if err := install.Serving(registries); err != nil { + if err := installer.Serving(registries); err != nil { return fmt.Errorf("failed to install serving to kind cluster %s: %w", clusterName, err) } - if err := install.Kourier(); err != nil { + if err := installer.Kourier(); err != nil { return fmt.Errorf("failed to install kourier to kind cluster %s: %w", clusterName, err) } - if err := install.KourierKind(); err != nil { + if err := installer.KourierKind(); err != nil { return fmt.Errorf("failed while configuring kourier for kind cluster %s: %w", clusterName, err) } } if installEventing { - if err := install.Eventing(); err != nil { + if err := installer.Eventing(); err != nil { return fmt.Errorf("failed to install eventing to king cluster %s: %w", clusterName, err) } } diff --git a/pkg/minikube/context_test.go b/pkg/minikube/context_test.go deleted file mode 100644 index fb00fcc..0000000 --- a/pkg/minikube/context_test.go +++ /dev/null @@ -1,120 +0,0 @@ -// Copyright © 2026 The Knative Authors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package minikube - -import ( - "os" - "path/filepath" - "runtime" - "strings" - "testing" -) - -func TestReuseSelectsRequestedContext(t *testing.T) { - if runtime.GOOS == "windows" { - t.Skip("fake commands use shell scripts") - } - for _, tt := range []struct { - name string - cluster string - args []string - profile string - failSelection bool - }{ - {name: "default profile", cluster: "knative", profile: "knative"}, - {name: "named profile", cluster: "demo", profile: "demo"}, - {name: "passthrough profile override", cluster: "unused", args: []string{"--profile=demo"}, profile: "demo"}, - {name: "missing context prevents installation", cluster: "demo", profile: "demo", failSelection: true}, - } { - t.Run(tt.name, func(t *testing.T) { - oldName, oldInstall, oldArgs := clusterName, installKnative, customMinikubeArgs - installKnative, customMinikubeArgs = true, nil - t.Cleanup(func() { clusterName, installKnative, customMinikubeArgs = oldName, oldInstall, oldArgs }) - dir := t.TempDir() - calls := filepath.Join(dir, "calls") - t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) - t.Setenv("QUICKSTART_TEST_CALLS", calls) - t.Setenv("QUICKSTART_TEST_PROFILE", tt.profile) - fail := "" - if tt.failSelection { - fail = "yes" - } - t.Setenv("QUICKSTART_TEST_FAIL_SELECTION", fail) - for name, script := range map[string]string{ - "minikube": `#!/bin/sh -case "$*" in - 'version --short') echo v1.38.0;; - 'profile list') echo "$QUICKSTART_TEST_PROFILE";; - *) exit 99;; -esac -`, - "kubectl": `#!/bin/sh -printf '%s\n' "$*" >> "$QUICKSTART_TEST_CALLS" -case "$*" in - 'version --client -o json') echo '{"clientVersion":{"gitVersion":"v1.35.0"}}';; - *'get namespaces') echo default;; - "config use-context $QUICKSTART_TEST_PROFILE") if [ -n "$QUICKSTART_TEST_FAIL_SELECTION" ]; then exit 1; fi;; - 'get endpointslice '*) echo ready;; - 'apply -f -') while IFS= read -r line; do :; done;; -esac -`, - } { - if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0755); err != nil { - t.Fatal(err) - } - } - input, err := os.CreateTemp(dir, "answers") - if err != nil { - t.Fatal(err) - } - defer input.Close() - if _, err := input.WriteString("n\n\n"); err != nil { - t.Fatal(err) - } - if _, err := input.Seek(0, 0); err != nil { - t.Fatal(err) - } - oldStdin := os.Stdin - os.Stdin = input - t.Cleanup(func() { os.Stdin = oldStdin }) - - err = SetUp(tt.cluster, "", true, true, tt.args) - if (err != nil) != tt.failSelection { - t.Fatalf("SetUp() error = %v, wantErr %v", err, tt.failSelection) - } - out, err := os.ReadFile(calls) - if err != nil { - t.Fatal(err) - } - log := string(out) - namespaceCheck := strings.Index(log, "--context "+tt.profile+" get namespaces\n") - selection := strings.Index(log, "config use-context "+tt.profile+"\n") - apply := strings.Index(log, "apply -f ") - if namespaceCheck < 0 { - t.Errorf("namespace check did not target %s: %s", tt.profile, log) - } - if selection < namespaceCheck || selection < 0 { - t.Errorf("requested context was not selected after checking its namespaces: %s", log) - } - if tt.failSelection { - if apply >= 0 { - t.Errorf("applied manifests after context selection failed: %s", log) - } - } else if apply < selection || apply < 0 { - t.Errorf("manifests were not applied after selecting the requested context: %s", log) - } - }) - } -} diff --git a/pkg/minikube/minikube.go b/pkg/minikube/minikube.go index 59d2a40..5ca284b 100644 --- a/pkg/minikube/minikube.go +++ b/pkg/minikube/minikube.go @@ -98,24 +98,20 @@ func SetUp(name, kVersion string, installServing, installEventing bool, minikube fmt.Println("\nPress the Enter key to continue") fmt.Scanln() if installKnative { - // Reusing a profile (or starting with --keep-context) does not select - // its context. Never install into an unrelated current context. - if err := runCommandWithOutput(exec.Command("kubectl", "config", "use-context", clusterName)); err != nil { - return fmt.Errorf("failed to select minikube cluster %s: %w", clusterName, err) - } + installer := install.Installer{Context: clusterName} if installServing { - if err := install.Serving(""); err != nil { + if err := installer.Serving(""); err != nil { return fmt.Errorf("failed to install serving to minikube cluster %s: %w", clusterName, err) } - if err := install.Kourier(); err != nil { + if err := installer.Kourier(); err != nil { return fmt.Errorf("failed to install kourier to minikube cluster %s: %w", clusterName, err) } - if err := install.KourierMinikube(); err != nil { + if err := installer.KourierMinikube(); err != nil { return fmt.Errorf("failed while configuring kourier for minikube cluster %s: %w", clusterName, err) } } if installEventing { - if err := install.Eventing(); err != nil { + if err := installer.Eventing(); err != nil { return fmt.Errorf("failed to install eventing to minikube cluster %s: %w", clusterName, err) } } From 3bf92d071dc9486882d887598077f31cea191108 Mon Sep 17 00:00:00 2001 From: Dave Protasowski Date: Sun, 15 Nov 2026 00:44:27 -0500 Subject: [PATCH 6/6] Simplify Installer API and name its command helper kubectl Signed-off-by: Dave Protasowski --- pkg/install/install.go | 18 +++++++++--------- pkg/install/installer.go | 20 +------------------- pkg/install/installer_test.go | 16 +++++----------- 3 files changed, 15 insertions(+), 39 deletions(-) diff --git a/pkg/install/install.go b/pkg/install/install.go index 95e7cd7..ad44226 100644 --- a/pkg/install/install.go +++ b/pkg/install/install.go @@ -77,7 +77,7 @@ func (i Installer) Kourier() error { } fmt.Println(" Kourier installed...") - ingress := i.command("patch", "configmap/config-network", "--namespace", "knative-serving", "--type", "merge", "--patch", "{\"data\":{\"ingress.class\":\"kourier.ingress.networking.knative.dev\"}}") + ingress := i.kubectl("patch", "configmap/config-network", "--namespace", "knative-serving", "--type", "merge", "--patch", "{\"data\":{\"ingress.class\":\"kourier.ingress.networking.knative.dev\"}}") if err := runCommand(ingress); err != nil { return fmt.Errorf("ingress error: %w", err) } @@ -109,7 +109,7 @@ spec: port: 80 targetPort: 8080` - kourierIngress := i.command("apply", "-f", "-") + kourierIngress := i.kubectl("apply", "-f", "-") kourierIngress.Stdin = strings.NewReader(config) if err := runCommand(kourierIngress); err != nil { return fmt.Errorf("kourier service: %w", err) @@ -117,7 +117,7 @@ spec: fmt.Println(" Kourier service installed...") - domainDns := i.command("patch", "configmap", "-n", "knative-serving", "config-domain", "-p", "{\"data\": {\"127.0.0.1.sslip.io\": \"\"}}") + domainDns := i.kubectl("patch", "configmap", "-n", "knative-serving", "config-domain", "-p", "{\"data\": {\"127.0.0.1.sslip.io\": \"\"}}") if err := runCommand(domainDns); err != nil { return fmt.Errorf("domain dns: %w", err) } @@ -175,7 +175,7 @@ func (i Installer) Serving(registries string) error { if registries != "" { configPatch := fmt.Sprintf(`{"data":{"registries-skipping-tag-resolving":"%s"}}`, registries) - ignoreRegistry := i.command("patch", "configmap", "-n", "knative-serving", "config-deployment", "-p", configPatch) + ignoreRegistry := i.kubectl("patch", "configmap", "-n", "knative-serving", "config-deployment", "-p", configPatch) if err := runCommand(ignoreRegistry); err != nil { return fmt.Errorf("tag resolving configuration: %w", err) } @@ -234,7 +234,7 @@ metadata: name: example-broker namespace: default` - exampleBroker := i.command("apply", "-f", "-") + exampleBroker := i.kubectl("apply", "-f", "-") exampleBroker.Stdin = strings.NewReader(config) if err := runCommand(exampleBroker); err != nil { return fmt.Errorf("example broker: %w", err) @@ -258,7 +258,7 @@ func runCommand(c *exec.Cmd) error { // for 10s between each try. func (i Installer) retryingApply(path string) error { return retryCommand(func() *exec.Cmd { - return i.command("apply", "-f", path) + return i.kubectl("apply", "-f", path) }, runCommand, time.Sleep) } @@ -279,7 +279,7 @@ func retryCommand(command func() *exec.Cmd, run func(*exec.Cmd) error, sleep fun // waitForCRDsEstablished waits for all CRDs to be established. func (i Installer) waitForCRDsEstablished() error { - return runCommand(i.command("wait", "--for=condition=Established", "--all", "crd")) + return runCommand(i.kubectl("wait", "--for=condition=Established", "--all", "crd")) } // CheckKubectlVersion validates that the user has a recent enough version of @@ -358,7 +358,7 @@ func parseKubectlVersion(jsonOut string) (int, int, error) { // them to become Ready. This requires kubectl >= 1.33 for label-selector waits, // which is within the versions this plugin already supports. func (i Installer) waitForPodsReady(ns string) error { - return runCommand(i.command("wait", "pod", "--timeout=10m", "--for=create", "--for=condition=Ready", "-l", "!job-name", "-n", ns)) + return runCommand(i.kubectl("wait", "pod", "--timeout=10m", "--for=create", "--for=condition=Ready", "-l", "!job-name", "-n", ns)) } // waitForWebhookReady waits for the Knative Serving webhook to be ready. @@ -370,7 +370,7 @@ func (i Installer) waitForWebhookReady() error { // Check if the webhook service has ready endpointslices // NOTE: We use 'kubectl get' instead of 'kubectl wait' because kubectl wait's JSONPath // doesn't support checking if ANY endpoint is ready (wildcard [*] fails with multiple endpoints) - checkEndpointSlices := i.command("get", "endpointslice", + checkEndpointSlices := i.kubectl("get", "endpointslice", "-l", "kubernetes.io/service-name=webhook", "-n", "knative-serving", "-o", "jsonpath={.items[*].endpoints[?(@.conditions.ready==true)]}") diff --git a/pkg/install/installer.go b/pkg/install/installer.go index 324ee91..cc894ce 100644 --- a/pkg/install/installer.go +++ b/pkg/install/installer.go @@ -22,28 +22,10 @@ type Installer struct { Context string } -func (i Installer) command(args ...string) *exec.Cmd { +func (i Installer) kubectl(args ...string) *exec.Cmd { if i.Context != "" { args = append([]string{"--context", i.Context}, args...) } // #nosec G204 -- Fixed executable; arguments are passed directly, never through a shell. return exec.Command("kubectl", args...) } - -// Keep the package-level entry points available to callers using the current -// context. Quickstart uses an Installer with an explicit context instead. - -// Kourier installs Kourier using the current kubeconfig context. -func Kourier() error { return (Installer{}).Kourier() } - -// KourierKind configures Kourier for Kind using the current kubeconfig context. -func KourierKind() error { return (Installer{}).KourierKind() } - -// KourierMinikube configures Kourier for Minikube using the current context. -func KourierMinikube() error { return (Installer{}).KourierMinikube() } - -// Serving installs Knative Serving using the current kubeconfig context. -func Serving(registries string) error { return (Installer{}).Serving(registries) } - -// Eventing installs Knative Eventing using the current kubeconfig context. -func Eventing() error { return (Installer{}).Eventing() } diff --git a/pkg/install/installer_test.go b/pkg/install/installer_test.go index e69f1b8..3c8c515 100644 --- a/pkg/install/installer_test.go +++ b/pkg/install/installer_test.go @@ -15,12 +15,12 @@ package install import ( - "reflect" + "slices" "testing" ) -func TestInstallerCommand(t *testing.T) { - for _, context := range []string{"", "knative", "kind-custom", "custom-profile"} { +func TestInstallerKubectl(t *testing.T) { + for _, context := range []string{"", "kind-custom"} { t.Run("context="+context, func(t *testing.T) { installer := Installer{Context: context} want := []string{"kubectl"} @@ -28,16 +28,10 @@ func TestInstallerCommand(t *testing.T) { want = append(want, "--context", context) } want = append(want, "get", "pods") - cmd := installer.command("get", "pods") - if !reflect.DeepEqual(cmd.Args, want) { + cmd := installer.kubectl("get", "pods") + if !slices.Equal(cmd.Args, want) { t.Errorf("args = %v, want %v", cmd.Args, want) } - // Each command must carry its own context, rather than relying on a prior - // `kubectl config use-context` call that would override --keep-context. - again := installer.command("get", "pods") - if !reflect.DeepEqual(again.Args, want) { - t.Errorf("second command args = %v, want %v", again.Args, want) - } }) } }