From d6c972d567da72c00b310fd4799f963039da3327 Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Mon, 30 Nov 2026 15:38:05 +0000 Subject: [PATCH 1/9] feat(controller): verify external control plane and mark initialized --- config/rbac/role.yaml | 8 ++ controller/stackitcluster_controller.go | 84 +++++++++++++++ controller/stackitcluster_controller_test.go | 107 ++++++++++++++++++- test/e2e/e2e_test.go | 91 +++++++++++++++- 4 files changed, 285 insertions(+), 5 deletions(-) diff --git a/config/rbac/role.yaml b/config/rbac/role.yaml index 75a1891..257686e 100644 --- a/config/rbac/role.yaml +++ b/config/rbac/role.yaml @@ -30,6 +30,14 @@ rules: - get - list - watch +- apiGroups: + - cluster.x-k8s.io + resources: + - clusters/status + verbs: + - get + - patch + - update - apiGroups: - infrastructure.cluster.x-k8s.io resources: diff --git a/controller/stackitcluster_controller.go b/controller/stackitcluster_controller.go index 5db54df..46d1862 100644 --- a/controller/stackitcluster_controller.go +++ b/controller/stackitcluster_controller.go @@ -21,7 +21,9 @@ import ( "errors" "fmt" "maps" + "net" "slices" + "strconv" "time" corev1 "k8s.io/api/core/v1" @@ -30,9 +32,11 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" clusterutil "sigs.k8s.io/cluster-api/util" "sigs.k8s.io/cluster-api/util/collections" + "sigs.k8s.io/cluster-api/util/patch" "sigs.k8s.io/cluster-api/util/record" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/builder" @@ -62,6 +66,18 @@ type StackitClusterReconciler struct { // CloudClientFactory builds a cloud.Client from parsed credentials. It is // injected so tests can swap in the in-memory fake. CloudClientFactory cloud.Factory + + // DialContext dials a network address with a context. Injected for unit testing. + DialContext func(ctx context.Context, netw, addr string) (net.Conn, error) +} + +func (r *StackitClusterReconciler) dialContext(ctx context.Context, netw, addr string) (net.Conn, error) { + if r.DialContext != nil { + return r.DialContext(ctx, netw, addr) + } + var dialer net.Dialer + dialer.Timeout = 5 * time.Second + return dialer.DialContext(ctx, netw, addr) } // SetupWithManager registers the controller with the manager. @@ -84,6 +100,7 @@ func (r *StackitClusterReconciler) SetupWithManager(mgr ctrl.Manager) error { // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=stackitclusters/status,verbs=get;update;patch // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=stackitclusters/finalizers,verbs=update // +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=clusters,verbs=get;list;watch +// +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=clusters/status,verbs=get;update;patch // +kubebuilder:rbac:groups=cluster.x-k8s.io,resources=machines,verbs=get;list;watch // +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch // +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch @@ -426,6 +443,10 @@ func (r *StackitClusterReconciler) reconcileNormal(ctx context.Context, clusterS return ctrl.Result{}, nil } + if err := r.ensureControlPlaneInitialized(ctx, clusterScope); err != nil { + return ctrl.Result{}, err + } + if result, ready, err := r.reconcileBastion(ctx, clusterScope); err != nil { log.Error(err, "Failed to reconcile bastion", "cluster", stackitCluster.Name, @@ -550,3 +571,66 @@ func (r *StackitClusterReconciler) reconcileDelete(ctx context.Context, clusterS controllerutil.RemoveFinalizer(stackitCluster, infrav1.ClusterFinalizer) return ctrl.Result{}, nil } + +func isExternalControlPlane(cluster *clusterv1.Cluster, stackitCluster *infrav1.StackitCluster) bool { + if cluster == nil || cluster.Spec.ControlPlaneRef.IsDefined() { + return false + } + return !stackitCluster.Spec.APIServerLoadBalancer.Enabled && + (stackitCluster.Spec.ControlPlaneEndpoint.Host != "" || cluster.Spec.ControlPlaneEndpoint.Host != "") +} + +func (r *StackitClusterReconciler) ensureControlPlaneInitialized(ctx context.Context, clusterScope *scope.ClusterScope) error { + cluster := clusterScope.Cluster + stackitCluster := clusterScope.StackitCluster + if !isExternalControlPlane(cluster, stackitCluster) { + return nil + } + + if ptr.Deref(cluster.Status.Initialization.ControlPlaneInitialized, false) && + meta.IsStatusConditionTrue(cluster.Status.Conditions, clusterv1.ClusterControlPlaneInitializedCondition) { + return nil + } + + endpoint := stackitCluster.Spec.ControlPlaneEndpoint + if endpoint.Host == "" && cluster.Spec.ControlPlaneEndpoint.Host != "" { + endpoint = cluster.Spec.ControlPlaneEndpoint + } + if endpoint.Host == "" && stackitCluster.Status.APIServerEndpoint.Host != "" { + endpoint = stackitCluster.Status.APIServerEndpoint + } + if endpoint.Host == "" { + return nil + } + + port := endpoint.Port + if port == 0 { + port = loadbalancer.DefaultAPIServerPort + } + addr := net.JoinHostPort(endpoint.Host, strconv.Itoa(int(port))) + + conn, err := r.dialContext(ctx, "tcp", addr) + if err != nil { + return fmt.Errorf("verify control plane endpoint connectivity %s: %w", addr, err) + } + _ = conn.Close() + + patchHelper, err := patch.NewHelper(cluster, r.Client) + if err != nil { + return fmt.Errorf("create cluster patch helper: %w", err) + } + cluster.Status.Initialization.ControlPlaneInitialized = new(true) + meta.SetStatusCondition(&cluster.Status.Conditions, metav1.Condition{ + Type: clusterv1.ClusterControlPlaneInitializedCondition, + Status: metav1.ConditionTrue, + Reason: clusterv1.ClusterControlPlaneInitializedReason, + ObservedGeneration: cluster.Generation, + }) + if err := patchHelper.Patch(ctx, cluster, patch.WithOwnedConditions{Conditions: []string{ + clusterv1.ClusterControlPlaneInitializedCondition, + }}); err != nil { + return fmt.Errorf("patch cluster status controlPlaneInitialized: %w", err) + } + logf.FromContext(ctx).Info("Patched cluster controlPlaneInitialized to true", "cluster", cluster.Name, "endpoint", addr) + return nil +} diff --git a/controller/stackitcluster_controller_test.go b/controller/stackitcluster_controller_test.go index 26a533c..687ace5 100644 --- a/controller/stackitcluster_controller_test.go +++ b/controller/stackitcluster_controller_test.go @@ -12,7 +12,9 @@ package controller import ( "context" + "errors" "fmt" + "net" "time" . "github.com/onsi/ginkgo/v2" @@ -22,7 +24,9 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" + "k8s.io/utils/ptr" clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/reconcile" infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" @@ -35,6 +39,12 @@ import ( "github.com/stackitcloud/cluster-api-provider-stackit/scope" ) +type dummyConn struct { + net.Conn +} + +func (dummyConn) Close() error { return nil } + var _ = Describe("StackitCluster Controller", func() { const namespace = "default" @@ -206,13 +216,19 @@ var _ = Describe("StackitCluster Controller", func() { expectCondition(got.Status.Conditions, infrav1.ClusterNetworkReadyCondition, metav1.ConditionFalse, "NetworkInUse") }) - It("uses an externally provided control plane endpoint when load balancer creation is disabled", func() { + It("uses an externally provided control plane endpoint when load balancer creation is disabled and initializes control plane", func() { got := &infrav1.StackitCluster{} Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) got.Spec.APIServerLoadBalancer.Enabled = false got.Spec.ControlPlaneEndpoint = clusterv1.APIEndpoint{Host: "198.51.100.10", Port: 6443} Expect(k8sClient.Update(ctx, got)).To(Succeed()) + var dialedAddr string + reconciler.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + dialedAddr = addr + return dummyConn{}, nil + } + result, err := reconciler.Reconcile(ctx, request) Expect(err).NotTo(HaveOccurred()) Expect(result).To(Equal(reconcile.Result{})) @@ -222,6 +238,95 @@ var _ = Describe("StackitCluster Controller", func() { Expect(got.Status.APIServerEndpoint.Host).To(Equal("198.51.100.10")) Expect(fakeCloud.LoadBalancerCount()).To(Equal(0)) expectCondition(got.Status.Conditions, infrav1.ClusterLoadBalancerReadyCondition, metav1.ConditionTrue, "Skipped") + Expect(dialedAddr).To(Equal("198.51.100.10:6443")) + + ownerCluster := &clusterv1.Cluster{} + Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, ownerCluster)).To(Succeed()) + Expect(ownerCluster.Status.Initialization.ControlPlaneInitialized).NotTo(BeNil()) + Expect(*ownerCluster.Status.Initialization.ControlPlaneInitialized).To(BeTrue()) + expectCondition(ownerCluster.Status.Conditions, clusterv1.ClusterControlPlaneInitializedCondition, metav1.ConditionTrue, clusterv1.ClusterControlPlaneInitializedReason) + }) + + It("returns an error for backoff when external control plane endpoint connectivity check fails", func() { + got := &infrav1.StackitCluster{} + Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) + got.Spec.APIServerLoadBalancer.Enabled = false + got.Spec.ControlPlaneEndpoint = clusterv1.APIEndpoint{Host: "198.51.100.10", Port: 6443} + Expect(k8sClient.Update(ctx, got)).To(Succeed()) + + reconciler.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + return nil, errors.New("connection refused") + } + + _, err := reconciler.Reconcile(ctx, request) + Expect(err).To(HaveOccurred()) + Expect(err.Error()).To(ContainSubstring("verify control plane endpoint connectivity 198.51.100.10:6443")) + + ownerCluster := &clusterv1.Cluster{} + Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, ownerCluster)).To(Succeed()) + Expect(ptr.Deref(ownerCluster.Status.Initialization.ControlPlaneInitialized, false)).To(BeFalse()) + }) + + It("skips connectivity check when control plane is already initialized", func() { + got := &infrav1.StackitCluster{} + Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) + got.Spec.APIServerLoadBalancer.Enabled = false + got.Spec.ControlPlaneEndpoint = clusterv1.APIEndpoint{Host: "198.51.100.10", Port: 6443} + Expect(k8sClient.Update(ctx, got)).To(Succeed()) + + ownerCluster := &clusterv1.Cluster{} + Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, ownerCluster)).To(Succeed()) + patch := client.MergeFrom(ownerCluster.DeepCopy()) + ownerCluster.Status.Initialization.ControlPlaneInitialized = new(true) + meta.SetStatusCondition(&ownerCluster.Status.Conditions, metav1.Condition{ + Type: clusterv1.ClusterControlPlaneInitializedCondition, + Status: metav1.ConditionTrue, + Reason: clusterv1.ClusterControlPlaneInitializedReason, + ObservedGeneration: ownerCluster.Generation, + }) + Expect(k8sClient.Status().Patch(ctx, ownerCluster, patch)).To(Succeed()) + + dialCalled := false + reconciler.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + dialCalled = true + return nil, errors.New("unexpected dial") + } + + result, err := reconciler.Reconcile(ctx, request) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal(reconcile.Result{})) + Expect(dialCalled).To(BeFalse()) + }) + + It("skips control plane initialization when cluster has a controlPlaneRef", func() { + ownerCluster := &clusterv1.Cluster{} + Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, ownerCluster)).To(Succeed()) + ownerCluster.Spec.ControlPlaneRef = clusterv1.ContractVersionedObjectReference{ + APIGroup: "controlplane.cluster.x-k8s.io", + Kind: "KubeadmControlPlane", + Name: clusterName + "-cp", + } + Expect(k8sClient.Update(ctx, ownerCluster)).To(Succeed()) + + got := &infrav1.StackitCluster{} + Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) + got.Spec.APIServerLoadBalancer.Enabled = false + got.Spec.ControlPlaneEndpoint = clusterv1.APIEndpoint{Host: "198.51.100.20", Port: 6443} + Expect(k8sClient.Update(ctx, got)).To(Succeed()) + + dialCalled := false + reconciler.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + dialCalled = true + return nil, errors.New("unexpected dial") + } + + result, err := reconciler.Reconcile(ctx, request) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal(reconcile.Result{})) + Expect(dialCalled).To(BeFalse()) + + Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, ownerCluster)).To(Succeed()) + Expect(ptr.Deref(ownerCluster.Status.Initialization.ControlPlaneInitialized, false)).To(BeFalse()) }) It("creates the bastion and publishes its public IP when enabled", func() { diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index ff21577..7865efd 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -374,6 +374,89 @@ var _ = Describe("Manager", Ordered, func() { // +kubebuilder:scaffold:e2e-webhooks-checks + It("should verify external control plane connectivity and mark Cluster initialized", func() { + if os.Getenv("STACKIT_E2E_SELF_AWARENESS") != "true" { + Skip("set STACKIT_E2E_SELF_AWARENESS=true to run the control plane self-awareness e2e test") + } + + ns := envDefault("STACKIT_E2E_NAMESPACE", "default") + projectID := requiredEnv("STACKIT_PROJECT_ID") + region := envDefault("STACKIT_REGION", "eu01") + networkID := requiredEnv("STACKIT_NETWORK_ID") + credsName := envDefault("STACKIT_CREDENTIALS_SECRET_NAME", "stackit-credentials") + credsNS := envDefault("STACKIT_CREDENTIALS_SECRET_NAMESPACE", ns) + clusterName := fmt.Sprintf("stackit-e2e-self-aware-%d", time.Now().Unix()) + + fixture := fmt.Sprintf(`apiVersion: infrastructure.cluster.x-k8s.io/v1alpha1 +kind: StackitCluster +metadata: + name: %[1]s + namespace: %[2]s +spec: + projectID: %[3]s + region: %[4]s + credentialsSecretRef: + name: %[5]s + namespace: %[6]s + network: + id: %[7]s + apiServerLoadBalancer: + enabled: false + controlPlaneEndpoint: + host: 127.0.0.1 + port: 16443 +--- +apiVersion: cluster.x-k8s.io/v1beta2 +kind: Cluster +metadata: + name: %[1]s + namespace: %[2]s +spec: + infrastructureRef: + apiGroup: infrastructure.cluster.x-k8s.io + kind: StackitCluster + name: %[1]s +`, clusterName, ns, projectID, region, credsName, credsNS, networkID) + + fixturePath := writeTempManifest("stackit-self-aware-e2e-*.yaml", fixture) + defer func() { + cmd := exec.Command("kubectl", "delete", "cluster", clusterName, "-n", ns, "--ignore-not-found", "--wait=true", "--timeout=5m") + _, _ = utils.Run(cmd) + cmd = exec.Command("kubectl", "delete", "stackitcluster", clusterName, "-n", ns, "--ignore-not-found", "--wait=true", "--timeout=5m") + _, _ = utils.Run(cmd) + _ = os.Remove(fixturePath) + }() + + By("applying a Cluster and StackitCluster with an unreachable controlPlaneEndpoint") + Eventually(func(g Gomega) { + cmd := exec.Command("kubectl", "apply", "-f", fixturePath) + _, err := utils.Run(cmd) + g.Expect(err).NotTo(HaveOccurred(), "Failed to apply self-awareness fixture") + }, 2*time.Minute, 3*time.Second).Should(Succeed()) + + By("verifying Cluster stays uninitialized while endpoint dial fails") + Consistently(func(g Gomega) { + cpInit := kubectlOutput(g, "get", "cluster", clusterName, "-n", ns, "-o", "jsonpath={.status.initialization.controlPlaneInitialized}") + g.Expect(cpInit).NotTo(Equal("true")) + }, 10*time.Second, 2*time.Second).Should(Succeed()) + + By("updating controlPlaneEndpoint to the reachable in-cluster API server") + cmd := exec.Command("kubectl", "patch", "stackitcluster", clusterName, "-n", ns, "--type=merge", + "-p", `{"spec":{"controlPlaneEndpoint":{"host":"kubernetes.default.svc","port":443}}}`) + _, err := utils.Run(cmd) + Expect(err).NotTo(HaveOccurred(), "Failed to patch controlPlaneEndpoint") + + By("verifying StackitCluster becomes Ready and Cluster controlPlaneInitialized is patched to true") + Eventually(func(g Gomega) { + ready := kubectlOutput(g, "get", "stackitcluster", clusterName, "-n", ns, "-o", "jsonpath={.status.ready}") + g.Expect(ready).To(Equal("true")) + cpInit := kubectlOutput(g, "get", "cluster", clusterName, "-n", ns, "-o", "jsonpath={.status.initialization.controlPlaneInitialized}") + g.Expect(cpInit).To(Equal("true")) + condStatus := kubectlOutput(g, "get", "cluster", clusterName, "-n", ns, "-o", "jsonpath={.status.conditions[?(@.type=='ControlPlaneInitialized')].status}") + g.Expect(condStatus).To(Equal("True")) + }, 2*time.Minute, 2*time.Second).Should(Succeed()) + }) + It("should create and delete a real STACKIT VM for a workload Cluster Machine", func() { if os.Getenv("STACKIT_E2E_CREATE_VMS") != "true" { Skip("set STACKIT_E2E_CREATE_VMS=true to run the real STACKIT VM lifecycle e2e test") @@ -1315,8 +1398,8 @@ spec: apiServerLoadBalancer: enabled: false controlPlaneEndpoint: - host: 203.0.113.10 - port: 6443 + host: kubernetes.default.svc + port: 443 --- apiVersion: v1 kind: Secret @@ -1605,8 +1688,8 @@ spec: apiServerLoadBalancer: enabled: false controlPlaneEndpoint: - host: 203.0.113.10 - port: 6443 + host: kubernetes.default.svc + port: 443 --- apiVersion: v1 kind: Secret From 5e295627bdf9eae18f7825e9001808a5d370fdaf Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Tue, 1 Dec 2026 16:54:29 +0100 Subject: [PATCH 2/9] simplify control plane check Signed-off-by: Felix Breuer --- controller/stackitcluster_controller.go | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) diff --git a/controller/stackitcluster_controller.go b/controller/stackitcluster_controller.go index 46d1862..b410415 100644 --- a/controller/stackitcluster_controller.go +++ b/controller/stackitcluster_controller.go @@ -573,11 +573,10 @@ func (r *StackitClusterReconciler) reconcileDelete(ctx context.Context, clusterS } func isExternalControlPlane(cluster *clusterv1.Cluster, stackitCluster *infrav1.StackitCluster) bool { - if cluster == nil || cluster.Spec.ControlPlaneRef.IsDefined() { - return false - } - return !stackitCluster.Spec.APIServerLoadBalancer.Enabled && - (stackitCluster.Spec.ControlPlaneEndpoint.Host != "" || cluster.Spec.ControlPlaneEndpoint.Host != "") + return cluster != nil && + !cluster.Spec.ControlPlaneRef.IsDefined() && + !stackitCluster.Spec.APIServerLoadBalancer.Enabled && + stackitCluster.Spec.ControlPlaneEndpoint.Host != "" } func (r *StackitClusterReconciler) ensureControlPlaneInitialized(ctx context.Context, clusterScope *scope.ClusterScope) error { @@ -593,16 +592,6 @@ func (r *StackitClusterReconciler) ensureControlPlaneInitialized(ctx context.Con } endpoint := stackitCluster.Spec.ControlPlaneEndpoint - if endpoint.Host == "" && cluster.Spec.ControlPlaneEndpoint.Host != "" { - endpoint = cluster.Spec.ControlPlaneEndpoint - } - if endpoint.Host == "" && stackitCluster.Status.APIServerEndpoint.Host != "" { - endpoint = stackitCluster.Status.APIServerEndpoint - } - if endpoint.Host == "" { - return nil - } - port := endpoint.Port if port == 0 { port = loadbalancer.DefaultAPIServerPort From 697e5c71e49ae30ebc67c7c3c74d5e8e51febd1c Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Wed, 2 Dec 2026 08:58:37 +0000 Subject: [PATCH 3/9] feat(feature): add ControlPlaneSelfAwareness feature gate --- feature/feature.go | 37 +++++++++++++++++++++++++++++++++++++ feature/feature_test.go | 27 +++++++++++++++++++++++++++ feature/gates.go | 27 +++++++++++++++++++++++++++ go.mod | 2 +- 4 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 feature/feature.go create mode 100644 feature/feature_test.go create mode 100644 feature/gates.go diff --git a/feature/feature.go b/feature/feature.go new file mode 100644 index 0000000..c40090d --- /dev/null +++ b/feature/feature.go @@ -0,0 +1,37 @@ +/* +Copyright 2026. + +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 feature + +import ( + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/component-base/featuregate" +) + +const ( + // ControlPlaneSelfAwareness enables TCP connectivity verification and automatic + // Cluster.status.initialization.controlPlaneInitialized patching when using an + // external control plane without a ControlPlaneRef. + ControlPlaneSelfAwareness featuregate.Feature = "ControlPlaneSelfAwareness" +) + +func init() { + utilruntime.Must(MutableGates.Add(defaultFeatureGates)) +} + +var defaultFeatureGates = map[featuregate.Feature]featuregate.FeatureSpec{ + ControlPlaneSelfAwareness: {Default: false, PreRelease: featuregate.Alpha}, +} diff --git a/feature/feature_test.go b/feature/feature_test.go new file mode 100644 index 0000000..cab5efc --- /dev/null +++ b/feature/feature_test.go @@ -0,0 +1,27 @@ +package feature_test + +import ( + "testing" + + "github.com/stackitcloud/cluster-api-provider-stackit/feature" + featuregatetesting "k8s.io/component-base/featuregate/testing" +) + +func TestControlPlaneSelfAwarenessDefaultAndParsing(t *testing.T) { + if feature.Gates.Enabled(feature.ControlPlaneSelfAwareness) { + t.Fatal("expected ControlPlaneSelfAwareness to be disabled by default") + } + + gatesCopy := feature.MutableGates.DeepCopy() + if err := gatesCopy.Set("UnknownGate=true"); err == nil { + t.Fatal("expected error for unknown feature gate") + } + if err := gatesCopy.Set("ControlPlaneSelfAwareness=notabool"); err == nil { + t.Fatal("expected error for non-boolean feature gate value") + } + + featuregatetesting.SetFeatureGateDuringTest(t, feature.Gates, feature.ControlPlaneSelfAwareness, true) + if !feature.Gates.Enabled(feature.ControlPlaneSelfAwareness) { + t.Fatal("expected ControlPlaneSelfAwareness to be enabled during override") + } +} diff --git a/feature/gates.go b/feature/gates.go new file mode 100644 index 0000000..eff0ffd --- /dev/null +++ b/feature/gates.go @@ -0,0 +1,27 @@ +/* +Copyright 2026. + +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 feature + +import "k8s.io/component-base/featuregate" + +var ( + // MutableGates is the mutable feature gate registry used for CLI flag binding and tests. + MutableGates featuregate.MutableFeatureGate = featuregate.NewFeatureGate() + + // Gates is the read-only feature gate interface checked by controllers. + Gates featuregate.FeatureGate = MutableGates +) diff --git a/go.mod b/go.mod index e140f31..acc0f58 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( k8s.io/api v0.35.4 k8s.io/apimachinery v0.35.4 k8s.io/client-go v0.35.4 + k8s.io/component-base v0.35.4 k8s.io/utils v0.0.0-20251002143259-bc988d571ff4 sigs.k8s.io/cluster-api v1.13.2 sigs.k8s.io/controller-runtime v0.23.3 @@ -97,7 +98,6 @@ require ( k8s.io/apiextensions-apiserver v0.35.4 // indirect k8s.io/apiserver v0.35.4 // indirect k8s.io/cluster-bootstrap v0.35.4 // indirect - k8s.io/component-base v0.35.4 // indirect k8s.io/klog/v2 v2.130.1 // indirect k8s.io/kube-openapi v0.0.0-20250910181357-589584f1c912 // indirect sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.31.2 // indirect From d1f53099c0cd0ada3ef66818552413b562d9795d Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Wed, 2 Dec 2026 08:59:33 +0000 Subject: [PATCH 4/9] feat(manager): wire --feature-gates flag via pflag --- cmd/manager/main.go | 13 ++++++++++++- cmd/manager/main_test.go | 38 ++++++++++++++++++++++++++++++++++++++ go.mod | 2 +- 3 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 cmd/manager/main_test.go diff --git a/cmd/manager/main.go b/cmd/manager/main.go index 682eb40..e1c84dc 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -25,6 +25,7 @@ import ( // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" + "github.com/spf13/pflag" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" @@ -40,6 +41,7 @@ import ( infrastructurev1alpha1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud" "github.com/stackitcloud/cluster-api-provider-stackit/controller" + "github.com/stackitcloud/cluster-api-provider-stackit/feature" webhookv1alpha1 "github.com/stackitcloud/cluster-api-provider-stackit/webhook/v1alpha1" // +kubebuilder:scaffold:imports ) @@ -57,6 +59,11 @@ func init() { // +kubebuilder:scaffold:scheme } +func bindFlags(fs *pflag.FlagSet, goFS *flag.FlagSet) { + feature.MutableGates.AddFlag(fs) + fs.AddGoFlagSet(goFS) +} + // nolint:gocyclo func main() { var metricsAddr string @@ -88,9 +95,13 @@ func main() { Development: true, } opts.BindFlags(flag.CommandLine) - flag.Parse() + bindFlags(pflag.CommandLine, flag.CommandLine) + pflag.Parse() ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) + setupLog.Info("Feature gates configured", + string(feature.ControlPlaneSelfAwareness), feature.Gates.Enabled(feature.ControlPlaneSelfAwareness), + ) // if the enable-http2 flag is false (the default), http/2 should be disabled // due to its vulnerabilities. More specifically, disabling http/2 will diff --git a/cmd/manager/main_test.go b/cmd/manager/main_test.go new file mode 100644 index 0000000..9f9ba29 --- /dev/null +++ b/cmd/manager/main_test.go @@ -0,0 +1,38 @@ +package main + +import ( + "flag" + "testing" + + "github.com/spf13/pflag" + "github.com/stackitcloud/cluster-api-provider-stackit/feature" + featuregatetesting "k8s.io/component-base/featuregate/testing" +) + +func TestParseFlagsWithFeatureGatesAndExistingGoFlags(t *testing.T) { + featuregatetesting.SetFeatureGateDuringTest(t, feature.Gates, feature.ControlPlaneSelfAwareness, false) + + goFS := flag.NewFlagSet("test", flag.ContinueOnError) + var metricsAddr string + var enableLeaderElection bool + goFS.StringVar(&metricsAddr, "metrics-bind-address", "0", "") + goFS.BoolVar(&enableLeaderElection, "leader-elect", false, "") + + pfs := pflag.NewFlagSet("test", pflag.ContinueOnError) + bindFlags(pfs, goFS) + + if err := pfs.Parse([]string{ + "--leader-elect=true", + "--metrics-bind-address=:9090", + "--feature-gates=ControlPlaneSelfAwareness=true", + }); err != nil { + t.Fatalf("unexpected parse error: %v", err) + } + + if !enableLeaderElection || metricsAddr != ":9090" { + t.Fatalf("unexpected go flag values: leader=%v metrics=%q", enableLeaderElection, metricsAddr) + } + if !feature.Gates.Enabled(feature.ControlPlaneSelfAwareness) { + t.Fatal("expected ControlPlaneSelfAwareness to be enabled after parsing --feature-gates") + } +} diff --git a/go.mod b/go.mod index acc0f58..e162edd 100644 --- a/go.mod +++ b/go.mod @@ -6,6 +6,7 @@ require ( github.com/go-logr/logr v1.4.3 github.com/onsi/ginkgo/v2 v2.28.1 github.com/onsi/gomega v1.39.1 + github.com/spf13/pflag v1.0.10 github.com/stackitcloud/stackit-sdk-go/core v0.26.0 github.com/stackitcloud/stackit-sdk-go/services/iaas v1.12.0 github.com/stackitcloud/stackit-sdk-go/services/loadbalancer v1.13.0 @@ -61,7 +62,6 @@ require ( github.com/prometheus/common v0.66.1 // indirect github.com/prometheus/procfs v0.16.1 // indirect github.com/spf13/cobra v1.10.2 // indirect - github.com/spf13/pflag v1.0.10 // indirect github.com/stoewer/go-strcase v1.3.0 // indirect github.com/x448/float16 v0.8.4 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect From a7e4af0b6ed232d51b3ab1365e7f555041b4c81b Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Wed, 2 Dec 2026 09:01:08 +0000 Subject: [PATCH 5/9] feat(controller): gate external control plane init on ControlPlaneSelfAwareness --- controller/stackitcluster_controller.go | 4 ++- controller/stackitcluster_controller_test.go | 35 ++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/controller/stackitcluster_controller.go b/controller/stackitcluster_controller.go index b410415..a08456b 100644 --- a/controller/stackitcluster_controller.go +++ b/controller/stackitcluster_controller.go @@ -54,6 +54,7 @@ import ( "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/loadbalancer" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/network" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" + "github.com/stackitcloud/cluster-api-provider-stackit/feature" "github.com/stackitcloud/cluster-api-provider-stackit/scope" "github.com/stackitcloud/cluster-api-provider-stackit/util" ) @@ -573,7 +574,8 @@ func (r *StackitClusterReconciler) reconcileDelete(ctx context.Context, clusterS } func isExternalControlPlane(cluster *clusterv1.Cluster, stackitCluster *infrav1.StackitCluster) bool { - return cluster != nil && + return feature.Gates.Enabled(feature.ControlPlaneSelfAwareness) && + cluster != nil && !cluster.Spec.ControlPlaneRef.IsDefined() && !stackitCluster.Spec.APIServerLoadBalancer.Enabled && stackitCluster.Spec.ControlPlaneEndpoint.Host != "" diff --git a/controller/stackitcluster_controller_test.go b/controller/stackitcluster_controller_test.go index 687ace5..987a68b 100644 --- a/controller/stackitcluster_controller_test.go +++ b/controller/stackitcluster_controller_test.go @@ -24,6 +24,7 @@ import ( "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" + featuregatetesting "k8s.io/component-base/featuregate/testing" "k8s.io/utils/ptr" clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/controller-runtime/pkg/client" @@ -36,6 +37,7 @@ import ( "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/securitygroup" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/server" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" + "github.com/stackitcloud/cluster-api-provider-stackit/feature" "github.com/stackitcloud/cluster-api-provider-stackit/scope" ) @@ -216,7 +218,37 @@ var _ = Describe("StackitCluster Controller", func() { expectCondition(got.Status.Conditions, infrav1.ClusterNetworkReadyCondition, metav1.ConditionFalse, "NetworkInUse") }) + It("skips control plane initialization when ControlPlaneSelfAwareness feature gate is disabled", func() { + got := &infrav1.StackitCluster{} + Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) + got.Spec.APIServerLoadBalancer.Enabled = false + got.Spec.ControlPlaneEndpoint = clusterv1.APIEndpoint{Host: "198.51.100.10", Port: 6443} + Expect(k8sClient.Update(ctx, got)).To(Succeed()) + + dialCalled := false + reconciler.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { + dialCalled = true + return nil, errors.New("unexpected dial") + } + + result, err := reconciler.Reconcile(ctx, request) + Expect(err).NotTo(HaveOccurred()) + Expect(result).To(Equal(reconcile.Result{})) + Expect(dialCalled).To(BeFalse()) + + Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) + Expect(got.Status.Ready).To(BeTrue()) + Expect(got.Status.APIServerEndpoint.Host).To(Equal("198.51.100.10")) + Expect(fakeCloud.LoadBalancerCount()).To(Equal(0)) + expectCondition(got.Status.Conditions, infrav1.ClusterLoadBalancerReadyCondition, metav1.ConditionTrue, "Skipped") + + ownerCluster := &clusterv1.Cluster{} + Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, ownerCluster)).To(Succeed()) + Expect(ptr.Deref(ownerCluster.Status.Initialization.ControlPlaneInitialized, false)).To(BeFalse()) + }) + It("uses an externally provided control plane endpoint when load balancer creation is disabled and initializes control plane", func() { + featuregatetesting.SetFeatureGateDuringTest(GinkgoTB(), feature.Gates, feature.ControlPlaneSelfAwareness, true) got := &infrav1.StackitCluster{} Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) got.Spec.APIServerLoadBalancer.Enabled = false @@ -248,6 +280,7 @@ var _ = Describe("StackitCluster Controller", func() { }) It("returns an error for backoff when external control plane endpoint connectivity check fails", func() { + featuregatetesting.SetFeatureGateDuringTest(GinkgoTB(), feature.Gates, feature.ControlPlaneSelfAwareness, true) got := &infrav1.StackitCluster{} Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) got.Spec.APIServerLoadBalancer.Enabled = false @@ -268,6 +301,7 @@ var _ = Describe("StackitCluster Controller", func() { }) It("skips connectivity check when control plane is already initialized", func() { + featuregatetesting.SetFeatureGateDuringTest(GinkgoTB(), feature.Gates, feature.ControlPlaneSelfAwareness, true) got := &infrav1.StackitCluster{} Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) got.Spec.APIServerLoadBalancer.Enabled = false @@ -299,6 +333,7 @@ var _ = Describe("StackitCluster Controller", func() { }) It("skips control plane initialization when cluster has a controlPlaneRef", func() { + featuregatetesting.SetFeatureGateDuringTest(GinkgoTB(), feature.Gates, feature.ControlPlaneSelfAwareness, true) ownerCluster := &clusterv1.Cluster{} Expect(k8sClient.Get(ctx, types.NamespacedName{Namespace: namespace, Name: clusterName}, ownerCluster)).To(Succeed()) ownerCluster.Spec.ControlPlaneRef = clusterv1.ContractVersionedObjectReference{ From d96c3d498b67b005b707d41230f6c37050ae98a3 Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Wed, 2 Dec 2026 09:06:19 +0000 Subject: [PATCH 6/9] test(e2e): enable ControlPlaneSelfAwareness gate in self-awareness spec --- test/e2e/e2e_test.go | 84 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index 7865efd..144f588 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -379,6 +379,9 @@ var _ = Describe("Manager", Ordered, func() { Skip("set STACKIT_E2E_SELF_AWARENESS=true to run the control plane self-awareness e2e test") } + restoreFeatureGate := enableControllerFeatureGate(namespace, "capstk-controller-manager", "ControlPlaneSelfAwareness") + defer restoreFeatureGate() + ns := envDefault("STACKIT_E2E_NAMESPACE", "default") projectID := requiredEnv("STACKIT_PROJECT_ID") region := envDefault("STACKIT_REGION", "eu01") @@ -3024,3 +3027,84 @@ type tokenRequest struct { Token string `json:"token"` } `json:"status"` } + +func enableControllerFeatureGate(ns, deploymentName, gate string) func() { + By(fmt.Sprintf("enabling feature gate %s on deployment/%s in %s", gate, deploymentName, ns)) + cmd := exec.Command("kubectl", "-n", ns, "get", "deployment", deploymentName, "-o", "json") + output, err := utils.Run(cmd) + ExpectWithOffset(1, err).NotTo(HaveOccurred(), "Failed to inspect deployment %s/%s", ns, deploymentName) + + var deployment struct { + Spec struct { + Template struct { + Spec struct { + Containers []struct { + Name string `json:"name"` + Args []string `json:"args"` + } `json:"containers"` + } `json:"spec"` + } `json:"template"` + } `json:"spec"` + } + ExpectWithOffset(1, json.Unmarshal([]byte(output), &deployment)).To(Succeed()) + ExpectWithOffset(1, deployment.Spec.Template.Spec.Containers).NotTo(BeEmpty(), "Deployment %s/%s has no containers", ns, deploymentName) + + containerName := deployment.Spec.Template.Spec.Containers[0].Name + origArgs := append([]string(nil), deployment.Spec.Template.Spec.Containers[0].Args...) + updatedArgs := withFeatureGateArg(origArgs, gate) + + patchDeploymentContainerArgs(ns, deploymentName, containerName, updatedArgs) + waitForDeploymentRollout(ns, deploymentName) + + return func() { + By(fmt.Sprintf("restoring original args on deployment/%s in %s", deploymentName, ns)) + patchDeploymentContainerArgs(ns, deploymentName, containerName, origArgs) + waitForDeploymentRollout(ns, deploymentName) + } +} + +func withFeatureGateArg(args []string, gate string) []string { + updated := append([]string(nil), args...) + enablePair := gate + "=true" + disablePair := gate + "=false" + for i, arg := range updated { + if !strings.HasPrefix(arg, "--feature-gates=") { + continue + } + if strings.Contains(arg, disablePair) { + updated[i] = strings.ReplaceAll(arg, disablePair, enablePair) + } else if !strings.Contains(arg, enablePair) { + updated[i] = arg + "," + enablePair + } + return updated + } + return append(updated, "--feature-gates="+enablePair) +} + +func patchDeploymentContainerArgs(ns, deploymentName, containerName string, args []string) { + patch := map[string]any{ + "spec": map[string]any{ + "template": map[string]any{ + "spec": map[string]any{ + "containers": []map[string]any{ + { + "name": containerName, + "args": args, + }, + }, + }, + }, + }, + } + patchBytes, err := json.Marshal(patch) + ExpectWithOffset(2, err).NotTo(HaveOccurred()) + cmd := exec.Command("kubectl", "-n", ns, "patch", "deployment", deploymentName, "--type=strategic", "-p", string(patchBytes)) + _, err = utils.Run(cmd) + ExpectWithOffset(2, err).NotTo(HaveOccurred(), "Failed to patch args on deployment %s/%s", ns, deploymentName) +} + +func waitForDeploymentRollout(ns, deploymentName string) { + cmd := exec.Command("kubectl", "rollout", "status", "deployment/"+deploymentName, "-n", ns, "--timeout=5m") + _, err := utils.Run(cmd) + ExpectWithOffset(2, err).NotTo(HaveOccurred(), "Deployment %s/%s did not roll out", ns, deploymentName) +} From f0c4a37af9836c2a036a8b3715e7c9817e3ebbaf Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Wed, 2 Dec 2026 09:11:14 +0000 Subject: [PATCH 7/9] fix(e2e): register feature gate cleanup before rollout wait --- test/e2e/e2e_test.go | 71 ++++++++++++++------ test/e2e/feature_gate_helper_test.go | 96 ++++++++++++++++++++++++++++ 2 files changed, 146 insertions(+), 21 deletions(-) create mode 100644 test/e2e/feature_gate_helper_test.go diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index 144f588..e6c0159 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -379,8 +379,7 @@ var _ = Describe("Manager", Ordered, func() { Skip("set STACKIT_E2E_SELF_AWARENESS=true to run the control plane self-awareness e2e test") } - restoreFeatureGate := enableControllerFeatureGate(namespace, "capstk-controller-manager", "ControlPlaneSelfAwareness") - defer restoreFeatureGate() + enableControllerFeatureGate(namespace, "capstk-controller-manager", "ControlPlaneSelfAwareness") ns := envDefault("STACKIT_E2E_NAMESPACE", "default") projectID := requiredEnv("STACKIT_PROJECT_ID") @@ -3028,11 +3027,27 @@ type tokenRequest struct { } `json:"status"` } -func enableControllerFeatureGate(ns, deploymentName, gate string) func() { +func enableControllerFeatureGate(ns, deploymentName, gate string) { By(fmt.Sprintf("enabling feature gate %s on deployment/%s in %s", gate, deploymentName, ns)) + err := enableControllerFeatureGateWith(ns, deploymentName, gate, utils.Run, func(restore func() error) { + DeferCleanup(func() { + By(fmt.Sprintf("restoring original args on deployment/%s in %s", deploymentName, ns)) + ExpectWithOffset(1, restore()).To(Succeed()) + }) + }) + ExpectWithOffset(1, err).NotTo(HaveOccurred()) +} + +func enableControllerFeatureGateWith( + ns, deploymentName, gate string, + run func(*exec.Cmd) (string, error), + registerCleanup func(func() error), +) error { cmd := exec.Command("kubectl", "-n", ns, "get", "deployment", deploymentName, "-o", "json") - output, err := utils.Run(cmd) - ExpectWithOffset(1, err).NotTo(HaveOccurred(), "Failed to inspect deployment %s/%s", ns, deploymentName) + output, err := run(cmd) + if err != nil { + return fmt.Errorf("inspect deployment %s/%s: %w", ns, deploymentName, err) + } var deployment struct { Spec struct { @@ -3046,21 +3061,29 @@ func enableControllerFeatureGate(ns, deploymentName, gate string) func() { } `json:"template"` } `json:"spec"` } - ExpectWithOffset(1, json.Unmarshal([]byte(output), &deployment)).To(Succeed()) - ExpectWithOffset(1, deployment.Spec.Template.Spec.Containers).NotTo(BeEmpty(), "Deployment %s/%s has no containers", ns, deploymentName) + if err := json.Unmarshal([]byte(output), &deployment); err != nil { + return fmt.Errorf("unmarshal deployment %s/%s: %w", ns, deploymentName, err) + } + if len(deployment.Spec.Template.Spec.Containers) == 0 { + return fmt.Errorf("deployment %s/%s has no containers", ns, deploymentName) + } containerName := deployment.Spec.Template.Spec.Containers[0].Name origArgs := append([]string(nil), deployment.Spec.Template.Spec.Containers[0].Args...) updatedArgs := withFeatureGateArg(origArgs, gate) - patchDeploymentContainerArgs(ns, deploymentName, containerName, updatedArgs) - waitForDeploymentRollout(ns, deploymentName) - - return func() { - By(fmt.Sprintf("restoring original args on deployment/%s in %s", deploymentName, ns)) - patchDeploymentContainerArgs(ns, deploymentName, containerName, origArgs) - waitForDeploymentRollout(ns, deploymentName) + if err := patchDeploymentContainerArgsWith(ns, deploymentName, containerName, updatedArgs, run); err != nil { + return err } + // Register restoration immediately after mutating the Deployment so rollout failures still restore args. + registerCleanup(func() error { + if err := patchDeploymentContainerArgsWith(ns, deploymentName, containerName, origArgs, run); err != nil { + return err + } + return waitForDeploymentRolloutWith(ns, deploymentName, run) + }) + + return waitForDeploymentRolloutWith(ns, deploymentName, run) } func withFeatureGateArg(args []string, gate string) []string { @@ -3081,7 +3104,7 @@ func withFeatureGateArg(args []string, gate string) []string { return append(updated, "--feature-gates="+enablePair) } -func patchDeploymentContainerArgs(ns, deploymentName, containerName string, args []string) { +func patchDeploymentContainerArgsWith(ns, deploymentName, containerName string, args []string, run func(*exec.Cmd) (string, error)) error { patch := map[string]any{ "spec": map[string]any{ "template": map[string]any{ @@ -3097,14 +3120,20 @@ func patchDeploymentContainerArgs(ns, deploymentName, containerName string, args }, } patchBytes, err := json.Marshal(patch) - ExpectWithOffset(2, err).NotTo(HaveOccurred()) + if err != nil { + return err + } cmd := exec.Command("kubectl", "-n", ns, "patch", "deployment", deploymentName, "--type=strategic", "-p", string(patchBytes)) - _, err = utils.Run(cmd) - ExpectWithOffset(2, err).NotTo(HaveOccurred(), "Failed to patch args on deployment %s/%s", ns, deploymentName) + if _, err := run(cmd); err != nil { + return fmt.Errorf("patch args on deployment %s/%s: %w", ns, deploymentName, err) + } + return nil } -func waitForDeploymentRollout(ns, deploymentName string) { +func waitForDeploymentRolloutWith(ns, deploymentName string, run func(*exec.Cmd) (string, error)) error { cmd := exec.Command("kubectl", "rollout", "status", "deployment/"+deploymentName, "-n", ns, "--timeout=5m") - _, err := utils.Run(cmd) - ExpectWithOffset(2, err).NotTo(HaveOccurred(), "Deployment %s/%s did not roll out", ns, deploymentName) + if _, err := run(cmd); err != nil { + return fmt.Errorf("rollout deployment %s/%s: %w", ns, deploymentName, err) + } + return nil } diff --git a/test/e2e/feature_gate_helper_test.go b/test/e2e/feature_gate_helper_test.go new file mode 100644 index 0000000..4f0ce33 --- /dev/null +++ b/test/e2e/feature_gate_helper_test.go @@ -0,0 +1,96 @@ +//go:build e2e +// +build e2e + +/* +Copyright 2026. + +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 e2e + +import ( + "encoding/json" + "errors" + "os/exec" + "reflect" + "testing" +) + +func TestEnableControllerFeatureGateRestoresArgsOnRolloutFailure(t *testing.T) { + var patchedArgs [][]string + var cleanups []func() error + rolloutCalls := 0 + + fakeRun := func(cmd *exec.Cmd) (string, error) { + args := cmd.Args + if len(args) >= 4 && args[3] == "get" { + return `{"spec":{"template":{"spec":{"containers":[{"name":"manager","args":["--leader-elect"]}]}}}}`, nil + } + if len(args) >= 4 && args[3] == "patch" { + var payload struct { + Spec struct { + Template struct { + Spec struct { + Containers []struct { + Args []string `json:"args"` + } `json:"containers"` + } `json:"spec"` + } `json:"template"` + } `json:"spec"` + } + if err := json.Unmarshal([]byte(args[len(args)-1]), &payload); err != nil { + t.Fatalf("failed to parse patch payload: %v", err) + } + patchedArgs = append(patchedArgs, payload.Spec.Template.Spec.Containers[0].Args) + return "", nil + } + if len(args) >= 2 && args[1] == "rollout" { + rolloutCalls++ + if rolloutCalls == 1 { + return "", errors.New("rollout timed out") + } + return "", nil + } + t.Fatalf("unexpected command: %v", args) + return "", nil + } + + err := enableControllerFeatureGateWith("capstk-system", "capstk-controller-manager", "ControlPlaneSelfAwareness", fakeRun, func(fn func() error) { + cleanups = append(cleanups, fn) + }) + if err == nil { + t.Fatal("expected rollout error, got nil") + } + if len(cleanups) != 1 { + t.Fatalf("expected cleanup to be registered before rollout failure, got %d cleanups", len(cleanups)) + } + + for _, fn := range cleanups { + if err := fn(); err != nil { + t.Fatalf("unexpected cleanup error: %v", err) + } + } + + if len(patchedArgs) != 2 { + t.Fatalf("expected 2 patch calls (enable + restore), got %d", len(patchedArgs)) + } + wantEnabled := []string{"--leader-elect", "--feature-gates=ControlPlaneSelfAwareness=true"} + if !reflect.DeepEqual(patchedArgs[0], wantEnabled) { + t.Fatalf("first patch args = %v, want %v", patchedArgs[0], wantEnabled) + } + wantRestored := []string{"--leader-elect"} + if !reflect.DeepEqual(patchedArgs[1], wantRestored) { + t.Fatalf("restored patch args = %v, want %v", patchedArgs[1], wantRestored) + } +} From 42f11752a08202e41e1642a7da9730e7da94ce89 Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Wed, 2 Dec 2026 11:24:57 +0000 Subject: [PATCH 8/9] refactor(e2e): inline feature gate patch and restore --- test/e2e/e2e_test.go | 131 ++++----------------------- test/e2e/feature_gate_helper_test.go | 96 -------------------- 2 files changed, 18 insertions(+), 209 deletions(-) delete mode 100644 test/e2e/feature_gate_helper_test.go diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index e6c0159..a471921 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -379,7 +379,23 @@ var _ = Describe("Manager", Ordered, func() { Skip("set STACKIT_E2E_SELF_AWARENESS=true to run the control plane self-awareness e2e test") } - enableControllerFeatureGate(namespace, "capstk-controller-manager", "ControlPlaneSelfAwareness") + By("enabling ControlPlaneSelfAwareness feature gate on capstk-controller-manager") + origArgs, err := utils.Run(exec.Command("kubectl", "-n", namespace, "get", "deployment", "capstk-controller-manager", + "-o", "jsonpath={.spec.template.spec.containers[0].args}")) + Expect(err).NotTo(HaveOccurred(), "Failed to read controller-manager args") + _, err = utils.Run(exec.Command("kubectl", "-n", namespace, "patch", "deployment", "capstk-controller-manager", + "--type=json", "-p", `[{"op":"add","path":"/spec/template/spec/containers/0/args/-","value":"--feature-gates=ControlPlaneSelfAwareness=true"}]`)) + Expect(err).NotTo(HaveOccurred(), "Failed to enable ControlPlaneSelfAwareness feature gate") + DeferCleanup(func() { + By("restoring original args on capstk-controller-manager") + _, err := utils.Run(exec.Command("kubectl", "-n", namespace, "patch", "deployment", "capstk-controller-manager", + "--type=json", "-p", fmt.Sprintf(`[{"op":"replace","path":"/spec/template/spec/containers/0/args","value":%s}]`, strings.TrimSpace(origArgs)))) + Expect(err).NotTo(HaveOccurred(), "Failed to restore controller-manager args") + _, err = utils.Run(exec.Command("kubectl", "rollout", "status", "deployment/capstk-controller-manager", "-n", namespace, "--timeout=5m")) + Expect(err).NotTo(HaveOccurred(), "controller-manager did not roll out after restoring args") + }) + _, err = utils.Run(exec.Command("kubectl", "rollout", "status", "deployment/capstk-controller-manager", "-n", namespace, "--timeout=5m")) + Expect(err).NotTo(HaveOccurred(), "controller-manager did not roll out with feature gate") ns := envDefault("STACKIT_E2E_NAMESPACE", "default") projectID := requiredEnv("STACKIT_PROJECT_ID") @@ -445,7 +461,7 @@ spec: By("updating controlPlaneEndpoint to the reachable in-cluster API server") cmd := exec.Command("kubectl", "patch", "stackitcluster", clusterName, "-n", ns, "--type=merge", "-p", `{"spec":{"controlPlaneEndpoint":{"host":"kubernetes.default.svc","port":443}}}`) - _, err := utils.Run(cmd) + _, err = utils.Run(cmd) Expect(err).NotTo(HaveOccurred(), "Failed to patch controlPlaneEndpoint") By("verifying StackitCluster becomes Ready and Cluster controlPlaneInitialized is patched to true") @@ -3026,114 +3042,3 @@ type tokenRequest struct { Token string `json:"token"` } `json:"status"` } - -func enableControllerFeatureGate(ns, deploymentName, gate string) { - By(fmt.Sprintf("enabling feature gate %s on deployment/%s in %s", gate, deploymentName, ns)) - err := enableControllerFeatureGateWith(ns, deploymentName, gate, utils.Run, func(restore func() error) { - DeferCleanup(func() { - By(fmt.Sprintf("restoring original args on deployment/%s in %s", deploymentName, ns)) - ExpectWithOffset(1, restore()).To(Succeed()) - }) - }) - ExpectWithOffset(1, err).NotTo(HaveOccurred()) -} - -func enableControllerFeatureGateWith( - ns, deploymentName, gate string, - run func(*exec.Cmd) (string, error), - registerCleanup func(func() error), -) error { - cmd := exec.Command("kubectl", "-n", ns, "get", "deployment", deploymentName, "-o", "json") - output, err := run(cmd) - if err != nil { - return fmt.Errorf("inspect deployment %s/%s: %w", ns, deploymentName, err) - } - - var deployment struct { - Spec struct { - Template struct { - Spec struct { - Containers []struct { - Name string `json:"name"` - Args []string `json:"args"` - } `json:"containers"` - } `json:"spec"` - } `json:"template"` - } `json:"spec"` - } - if err := json.Unmarshal([]byte(output), &deployment); err != nil { - return fmt.Errorf("unmarshal deployment %s/%s: %w", ns, deploymentName, err) - } - if len(deployment.Spec.Template.Spec.Containers) == 0 { - return fmt.Errorf("deployment %s/%s has no containers", ns, deploymentName) - } - - containerName := deployment.Spec.Template.Spec.Containers[0].Name - origArgs := append([]string(nil), deployment.Spec.Template.Spec.Containers[0].Args...) - updatedArgs := withFeatureGateArg(origArgs, gate) - - if err := patchDeploymentContainerArgsWith(ns, deploymentName, containerName, updatedArgs, run); err != nil { - return err - } - // Register restoration immediately after mutating the Deployment so rollout failures still restore args. - registerCleanup(func() error { - if err := patchDeploymentContainerArgsWith(ns, deploymentName, containerName, origArgs, run); err != nil { - return err - } - return waitForDeploymentRolloutWith(ns, deploymentName, run) - }) - - return waitForDeploymentRolloutWith(ns, deploymentName, run) -} - -func withFeatureGateArg(args []string, gate string) []string { - updated := append([]string(nil), args...) - enablePair := gate + "=true" - disablePair := gate + "=false" - for i, arg := range updated { - if !strings.HasPrefix(arg, "--feature-gates=") { - continue - } - if strings.Contains(arg, disablePair) { - updated[i] = strings.ReplaceAll(arg, disablePair, enablePair) - } else if !strings.Contains(arg, enablePair) { - updated[i] = arg + "," + enablePair - } - return updated - } - return append(updated, "--feature-gates="+enablePair) -} - -func patchDeploymentContainerArgsWith(ns, deploymentName, containerName string, args []string, run func(*exec.Cmd) (string, error)) error { - patch := map[string]any{ - "spec": map[string]any{ - "template": map[string]any{ - "spec": map[string]any{ - "containers": []map[string]any{ - { - "name": containerName, - "args": args, - }, - }, - }, - }, - }, - } - patchBytes, err := json.Marshal(patch) - if err != nil { - return err - } - cmd := exec.Command("kubectl", "-n", ns, "patch", "deployment", deploymentName, "--type=strategic", "-p", string(patchBytes)) - if _, err := run(cmd); err != nil { - return fmt.Errorf("patch args on deployment %s/%s: %w", ns, deploymentName, err) - } - return nil -} - -func waitForDeploymentRolloutWith(ns, deploymentName string, run func(*exec.Cmd) (string, error)) error { - cmd := exec.Command("kubectl", "rollout", "status", "deployment/"+deploymentName, "-n", ns, "--timeout=5m") - if _, err := run(cmd); err != nil { - return fmt.Errorf("rollout deployment %s/%s: %w", ns, deploymentName, err) - } - return nil -} diff --git a/test/e2e/feature_gate_helper_test.go b/test/e2e/feature_gate_helper_test.go deleted file mode 100644 index 4f0ce33..0000000 --- a/test/e2e/feature_gate_helper_test.go +++ /dev/null @@ -1,96 +0,0 @@ -//go:build e2e -// +build e2e - -/* -Copyright 2026. - -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 e2e - -import ( - "encoding/json" - "errors" - "os/exec" - "reflect" - "testing" -) - -func TestEnableControllerFeatureGateRestoresArgsOnRolloutFailure(t *testing.T) { - var patchedArgs [][]string - var cleanups []func() error - rolloutCalls := 0 - - fakeRun := func(cmd *exec.Cmd) (string, error) { - args := cmd.Args - if len(args) >= 4 && args[3] == "get" { - return `{"spec":{"template":{"spec":{"containers":[{"name":"manager","args":["--leader-elect"]}]}}}}`, nil - } - if len(args) >= 4 && args[3] == "patch" { - var payload struct { - Spec struct { - Template struct { - Spec struct { - Containers []struct { - Args []string `json:"args"` - } `json:"containers"` - } `json:"spec"` - } `json:"template"` - } `json:"spec"` - } - if err := json.Unmarshal([]byte(args[len(args)-1]), &payload); err != nil { - t.Fatalf("failed to parse patch payload: %v", err) - } - patchedArgs = append(patchedArgs, payload.Spec.Template.Spec.Containers[0].Args) - return "", nil - } - if len(args) >= 2 && args[1] == "rollout" { - rolloutCalls++ - if rolloutCalls == 1 { - return "", errors.New("rollout timed out") - } - return "", nil - } - t.Fatalf("unexpected command: %v", args) - return "", nil - } - - err := enableControllerFeatureGateWith("capstk-system", "capstk-controller-manager", "ControlPlaneSelfAwareness", fakeRun, func(fn func() error) { - cleanups = append(cleanups, fn) - }) - if err == nil { - t.Fatal("expected rollout error, got nil") - } - if len(cleanups) != 1 { - t.Fatalf("expected cleanup to be registered before rollout failure, got %d cleanups", len(cleanups)) - } - - for _, fn := range cleanups { - if err := fn(); err != nil { - t.Fatalf("unexpected cleanup error: %v", err) - } - } - - if len(patchedArgs) != 2 { - t.Fatalf("expected 2 patch calls (enable + restore), got %d", len(patchedArgs)) - } - wantEnabled := []string{"--leader-elect", "--feature-gates=ControlPlaneSelfAwareness=true"} - if !reflect.DeepEqual(patchedArgs[0], wantEnabled) { - t.Fatalf("first patch args = %v, want %v", patchedArgs[0], wantEnabled) - } - wantRestored := []string{"--leader-elect"} - if !reflect.DeepEqual(patchedArgs[1], wantRestored) { - t.Fatalf("restored patch args = %v, want %v", patchedArgs[1], wantRestored) - } -} From a725d77cffbe317e52b73c2f0618020dd599b1e6 Mon Sep 17 00:00:00 2001 From: Felix Breuer Date: Wed, 2 Dec 2026 15:00:30 +0000 Subject: [PATCH 9/9] fix(manager): satisfy logcheck with constant log key --- cmd/manager/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/manager/main.go b/cmd/manager/main.go index e1c84dc..ca205c8 100644 --- a/cmd/manager/main.go +++ b/cmd/manager/main.go @@ -100,7 +100,7 @@ func main() { ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) setupLog.Info("Feature gates configured", - string(feature.ControlPlaneSelfAwareness), feature.Gates.Enabled(feature.ControlPlaneSelfAwareness), + "ControlPlaneSelfAwareness", feature.Gates.Enabled(feature.ControlPlaneSelfAwareness), ) // if the enable-http2 flag is false (the default), http/2 should be disabled