diff --git a/pkg/install/install.go b/pkg/install/install.go index 7454410..ad44226 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.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) } @@ -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.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 := exec.Command("kubectl", "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) } @@ -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.kubectl("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.kubectl("apply", "-f", "-") exampleBroker.Stdin = strings.NewReader(config) if err := runCommand(exampleBroker); err != nil { return fmt.Errorf("example broker: %w", err) @@ -256,22 +256,30 @@ 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) +func (i Installer) retryingApply(path string) error { + return retryCommand(func() *exec.Cmd { + return i.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++ { - err = runCommand(cmd) + for attempt := 0; attempt < 3; attempt++ { + // An exec.Cmd cannot be run more than once, even if its first run fails. + err = run(command()) if err == nil { - break + return nil + } + if attempt < 2 { + sleep(10 * time.Second) } - time.Sleep(10 * time.Second) } return err } // 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.kubectl("wait", "--for=condition=Established", "--all", "crd")) } // CheckKubectlVersion validates that the user has a recent enough version of @@ -349,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.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. -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) @@ -362,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.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 new file mode 100644 index 0000000..cc894ce --- /dev/null +++ b/pkg/install/installer.go @@ -0,0 +1,31 @@ +// 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) 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...) +} diff --git a/pkg/install/installer_test.go b/pkg/install/installer_test.go new file mode 100644 index 0000000..3c8c515 --- /dev/null +++ b/pkg/install/installer_test.go @@ -0,0 +1,37 @@ +// 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 ( + "slices" + "testing" +) + +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"} + if context != "" { + want = append(want, "--context", context) + } + want = append(want, "get", "pods") + cmd := installer.kubectl("get", "pods") + if !slices.Equal(cmd.Args, want) { + t.Errorf("args = %v, want %v", cmd.Args, want) + } + }) + } +} diff --git a/pkg/install/retry_test.go b/pkg/install/retry_test.go new file mode 100644 index 0000000..48afde4 --- /dev/null +++ b/pkg/install/retry_test.go @@ -0,0 +1,73 @@ +// 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 ( + "errors" + "os/exec" + "testing" + "time" +) + +func TestRetryCommand(t *testing.T) { + for _, tt := range []struct { + name string + failures int + wantCalls int + wantErr bool + }{ + {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) { + 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.Errorf("error = %v, wantErr %v", err, tt.wantErr) + } + if tt.wantErr && !errors.Is(err, failure) { + t.Errorf("error = %v, want original error", err) + } + if calls != tt.wantCalls { + t.Errorf("calls = %d, want %d", calls, tt.wantCalls) + } + if sleeps != tt.wantCalls-1 { + t.Errorf("sleeps = %d, want %d", sleeps, tt.wantCalls-1) + } + }) + } +} diff --git a/pkg/kind/kind.go b/pkg/kind/kind.go index b2a66cd..562c81d 100644 --- a/pkg/kind/kind.go +++ b/pkg/kind/kind.go @@ -80,6 +80,7 @@ func SetUp(name, kVersion string, installServing, installEventing, installKindRe return fmt.Errorf("failed to create kind cluster: %w", err) } if installKnative { + 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. @@ -88,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) } } @@ -232,7 +233,8 @@ 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", "-") + // #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) // } @@ -293,7 +295,8 @@ func checkForExistingCluster(registry bool, extraMountHostPath string, extraMoun } } else { fmt.Println("\n Installation skipped") - checkKnativeNamespace := exec.Command("kubectl", "get", "namespaces") + // #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) if err != nil { diff --git a/pkg/minikube/minikube.go b/pkg/minikube/minikube.go index 0411b2a..5ca284b 100644 --- a/pkg/minikube/minikube.go +++ b/pkg/minikube/minikube.go @@ -98,19 +98,20 @@ func SetUp(name, kVersion string, installServing, installEventing bool, minikube fmt.Println("\nPress the Enter key to continue") fmt.Scanln() if installKnative { + 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) } } @@ -188,7 +189,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 {