diff --git a/cmd/manager/main.go b/cmd/manager/main.go index 682eb40..ca205c8 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", + "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/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..a08456b 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" @@ -50,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" ) @@ -62,6 +67,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 +101,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 +444,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 +572,56 @@ 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 { + return feature.Gates.Enabled(feature.ControlPlaneSelfAwareness) && + 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 { + 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 + 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..987a68b 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,10 @@ 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" "sigs.k8s.io/controller-runtime/pkg/reconcile" infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" @@ -32,9 +37,16 @@ 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" ) +type dummyConn struct { + net.Conn +} + +func (dummyConn) Close() error { return nil } + var _ = Describe("StackitCluster Controller", func() { const namespace = "default" @@ -206,22 +218,150 @@ 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("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 + 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{})) + + 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") + 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() { + featuregatetesting.SetFeatureGateDuringTest(GinkgoTB(), feature.Gates, feature.ControlPlaneSelfAwareness, true) + 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() { + featuregatetesting.SetFeatureGateDuringTest(GinkgoTB(), feature.Gates, feature.ControlPlaneSelfAwareness, true) + 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() { + 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{ + 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/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..e162edd 100644 --- a/go.mod +++ b/go.mod @@ -6,12 +6,14 @@ 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 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 @@ -60,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 @@ -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 diff --git a/test/e2e/e2e_test.go b/test/e2e/e2e_test.go index ff21577..a471921 100644 --- a/test/e2e/e2e_test.go +++ b/test/e2e/e2e_test.go @@ -374,6 +374,107 @@ 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") + } + + 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") + 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 +1416,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 +1706,8 @@ spec: apiServerLoadBalancer: enabled: false controlPlaneEndpoint: - host: 203.0.113.10 - port: 6443 + host: kubernetes.default.svc + port: 443 --- apiVersion: v1 kind: Secret