From 757fcbc67b07eb95154eb67809bbaf9df2f482fd Mon Sep 17 00:00:00 2001 From: Jan Larwig Date: Mon, 23 Nov 2026 08:22:40 +0100 Subject: [PATCH] refactor: introducing an abstract reconciler interface and moving more logic into the services and scopes Signed-off-by: Jan Larwig --- cloud/cleanup.go | 50 +++- cloud/cleanup_test.go | 77 +++++- cloud/client.go | 9 +- cloud/sdk_client.go | 3 +- cloud/sdk_client_test.go | 9 +- cloud/services/availabilityzone/reconcile.go | 23 +- .../availabilityzone/reconcile_test.go | 28 +- cloud/services/availabilityzone/service.go | 8 +- cloud/services/bastion/reconcile.go | 172 ++++++++++++ cloud/services/bastion/reconcile_test.go | 238 ++++++++++++++++ cloud/services/bastion/service.go | 60 ++++ cloud/services/loadbalancer/reconcile.go | 132 ++++++++- cloud/services/loadbalancer/reconcile_test.go | 189 ++++++++----- cloud/services/loadbalancer/service.go | 27 +- cloud/services/network/reconcile.go | 98 ++++++- cloud/services/network/reconcile_test.go | 118 ++++---- cloud/services/network/service.go | 3 +- cloud/services/publicip/reconcile.go | 31 +-- cloud/services/publicip/reconcile_test.go | 89 +++--- cloud/services/publicip/service.go | 2 +- cloud/services/securitygroup/reconcile.go | 54 +++- .../services/securitygroup/reconcile_test.go | 106 ++++--- cloud/services/securitygroup/service.go | 17 +- cloud/services/server/reconcile.go | 98 ++++++- cloud/services/server/reconcile_test.go | 93 ++++--- cloud/services/server/service.go | 6 +- cloud/services/shared/utils.go | 52 ++++ cmd/cleanup-stackit/main.go | 2 +- controller/constants.go | 2 - controller/controller_test_helpers_test.go | 5 + controller/stackitcluster_bastion.go | 211 -------------- controller/stackitcluster_controller.go | 261 ++---------------- controller/stackitcluster_controller_test.go | 22 +- controller/stackitmachine_controller.go | 88 +----- controller/stackitmachine_controller_test.go | 10 +- scope/cluster_scope.go | 241 +++++++++++----- scope/cluster_scope_test.go | 82 ++---- scope/machine_scope.go | 57 ++-- util/reconcile.go | 2 +- 39 files changed, 1699 insertions(+), 1076 deletions(-) create mode 100644 cloud/services/bastion/reconcile.go create mode 100644 cloud/services/bastion/reconcile_test.go create mode 100644 cloud/services/bastion/service.go delete mode 100644 controller/stackitcluster_bastion.go diff --git a/cloud/cleanup.go b/cloud/cleanup.go index 67b391a..a530f7a 100644 --- a/cloud/cleanup.go +++ b/cloud/cleanup.go @@ -14,6 +14,9 @@ import ( "context" "errors" "fmt" + "time" + + ctrl "sigs.k8s.io/controller-runtime" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/loadbalancer" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/network" @@ -25,6 +28,7 @@ import ( type cleanupScope struct { Client + shared.NoOpReconcileScope tags map[string]string } @@ -43,14 +47,14 @@ func CleanupByTags(ctx context.Context, client Client, tags map[string]string) e tags: tags, } var errs []error - for _, deleteFn := range []func(context.Context) error{ - publicip.New(scope).Delete, - loadbalancer.New(scope).Delete, - server.New(scope).Delete, - securitygroup.New(scope).Delete, - network.New(scope).Delete, + for _, reconciler := range []Reconciler{ + publicip.New(scope), + loadbalancer.New(scope), + server.New(scope), + securitygroup.New(scope), + network.New(scope), } { - if err := deleteFn(ctx); err != nil { + if _, err := reconciler.Delete(ctx); err != nil { errs = append(errs, err) } } @@ -68,18 +72,46 @@ func (s *cleanupScope) PublicIPSpec() publicip.PublicIPSpec { } } +func (s *cleanupScope) SetPublicIP(_ *publicip.PublicIP) {} + +func (s *cleanupScope) APIServerLoadBalancerEnabled() bool { + return true +} + +func (s *cleanupScope) ControlPlaneEndpointHost() string { + return "" +} + +func (s *cleanupScope) UseExternalControlPlaneEndpoint() {} + +func (s *cleanupScope) APIServerEndpointHost() string { + return "" +} + +func (s *cleanupScope) ResolveLoadBalancerSpec(_ context.Context) (loadbalancer.LoadBalancerSpec, error) { + return s.LoadBalancerSpec(), nil +} + func (s *cleanupScope) LoadBalancerSpec() loadbalancer.LoadBalancerSpec { return loadbalancer.LoadBalancerSpec{ Tags: s.tags, } } +func (s *cleanupScope) SetLoadBalancer(_ *loadbalancer.LoadBalancer) {} + +func (s *cleanupScope) TargetPoolFailureResult(err error, _ time.Duration) (ctrl.Result, error) { + return ctrl.Result{}, err +} + func (s *cleanupScope) ServerSpec() server.ServerSpec { return server.ServerSpec{ Tags: s.tags, } } +func (s *cleanupScope) SetServer(_ *server.Server, _ bool) {} + func (s *cleanupScope) SecurityGroupSpecs() []securitygroup.SecurityGroupSpec { return []securitygroup.SecurityGroupSpec{ { @@ -89,9 +121,13 @@ func (s *cleanupScope) SecurityGroupSpecs() []securitygroup.SecurityGroupSpec { } } +func (s *cleanupScope) SetSecurityGroup(_ string, _ *securitygroup.SecurityGroup) {} + func (s *cleanupScope) NetworkSpec() network.NetworkSpec { return network.NetworkSpec{ Tags: s.tags, Managed: true, } } + +func (s *cleanupScope) SetNetwork(_ *network.Network) {} diff --git a/cloud/cleanup_test.go b/cloud/cleanup_test.go index a4902e6..c33691c 100644 --- a/cloud/cleanup_test.go +++ b/cloud/cleanup_test.go @@ -15,6 +15,9 @@ import ( "fmt" "maps" "testing" + "time" + + ctrl "sigs.k8s.io/controller-runtime" "github.com/stackitcloud/cluster-api-provider-stackit/cloud" cloudfake "github.com/stackitcloud/cluster-api-provider-stackit/cloud/fake" @@ -23,13 +26,17 @@ import ( "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/publicip" "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/util" ) type testResourceScope struct { cloud.Client + shared.NoOpReconcileScope networkSpec network.NetworkSpec + setNetwork func(*network.Network) serverSpec server.ServerSpec + setServer func(*server.Server, bool) publicIPSpec publicip.PublicIPSpec loadBalancerSpec loadbalancer.LoadBalancerSpec securityGroupSpec []securitygroup.SecurityGroupSpec @@ -39,44 +46,84 @@ func (s *testResourceScope) NetworkSpec() network.NetworkSpec { return s.networkSpec } +func (s *testResourceScope) SetNetwork(net *network.Network) { + if s.setNetwork != nil { + s.setNetwork(net) + } +} + func (s *testResourceScope) ServerSpec() server.ServerSpec { return s.serverSpec } +func (s *testResourceScope) SetServer(srv *server.Server, created bool) { + if s.setServer != nil { + s.setServer(srv, created) + } +} + func (s *testResourceScope) PublicIPSpec() publicip.PublicIPSpec { return s.publicIPSpec } +func (s *testResourceScope) SetPublicIP(_ *publicip.PublicIP) {} + +func (s *testResourceScope) APIServerLoadBalancerEnabled() bool { + return true +} + +func (s *testResourceScope) ControlPlaneEndpointHost() string { + return "" +} + +func (s *testResourceScope) UseExternalControlPlaneEndpoint() {} + +func (s *testResourceScope) APIServerEndpointHost() string { + return "" +} + +func (s *testResourceScope) ResolveLoadBalancerSpec(_ context.Context) (loadbalancer.LoadBalancerSpec, error) { + return s.loadBalancerSpec, nil +} + func (s *testResourceScope) LoadBalancerSpec() loadbalancer.LoadBalancerSpec { return s.loadBalancerSpec } +func (s *testResourceScope) SetLoadBalancer(_ *loadbalancer.LoadBalancer) {} + +func (s *testResourceScope) TargetPoolFailureResult(err error, _ time.Duration) (ctrl.Result, error) { + return ctrl.Result{}, err +} + func (s *testResourceScope) SecurityGroupSpecs() []securitygroup.SecurityGroupSpec { return s.securityGroupSpec } +func (s *testResourceScope) SetSecurityGroup(_ string, _ *securitygroup.SecurityGroup) {} + func createTestResources(t *testing.T, client cloud.Client, prefix string, tags map[string]string) { t.Helper() ctx := context.Background() var networkID string - if err := network.New(&testResourceScope{ + if _, err := network.New(&testResourceScope{ Client: client, networkSpec: network.NetworkSpec{ Name: prefix + "-net", IPv4Prefix: network.DefaultNetworkPrefix, Tags: tags, Managed: true, - SetNetwork: func(net *network.Network, _ bool) { - networkID = net.ID - }, + }, + setNetwork: func(net *network.Network) { + networkID = net.ID }, }).Reconcile(ctx); err != nil { t.Fatalf("network.Reconcile() error = %v", err) } var workerServerID, bastionServerID string - if err := server.New(&testResourceScope{ + if _, err := server.New(&testResourceScope{ Client: client, serverSpec: server.ServerSpec{ Name: prefix + "-worker", @@ -84,9 +131,9 @@ func createTestResources(t *testing.T, client cloud.Client, prefix string, tags MachineType: "c2i.2", NetworkID: networkID, Tags: tags, - SetServer: func(srv *server.Server, _ bool) { - workerServerID = srv.ID - }, + }, + setServer: func(srv *server.Server, _ bool) { + workerServerID = srv.ID }, }).Reconcile(ctx); err != nil { t.Fatalf("server.Reconcile(worker) error = %v", err) @@ -95,7 +142,7 @@ func createTestResources(t *testing.T, client cloud.Client, prefix string, tags bastionTags := make(map[string]string, len(tags)+1) maps.Copy(bastionTags, tags) bastionTags[util.LabelResourceRole] = util.ResourceRoleBastion - if err := server.New(&testResourceScope{ + if _, err := server.New(&testResourceScope{ Client: client, serverSpec: server.ServerSpec{ Name: prefix + "-bastion", @@ -103,15 +150,15 @@ func createTestResources(t *testing.T, client cloud.Client, prefix string, tags MachineType: "c2i.2", NetworkID: networkID, Tags: bastionTags, - SetServer: func(srv *server.Server, _ bool) { - bastionServerID = srv.ID - }, + }, + setServer: func(srv *server.Server, _ bool) { + bastionServerID = srv.ID }, }).Reconcile(ctx); err != nil { t.Fatalf("server.Reconcile(bastion) error = %v", err) } - if err := publicip.New(&testResourceScope{ + if _, err := publicip.New(&testResourceScope{ Client: client, publicIPSpec: publicip.PublicIPSpec{ Tags: bastionTags, @@ -124,7 +171,7 @@ func createTestResources(t *testing.T, client cloud.Client, prefix string, tags nodeSSHTags := make(map[string]string, len(tags)+1) maps.Copy(nodeSSHTags, tags) nodeSSHTags[util.LabelResourceRole] = util.ResourceRoleNodeSSH - if err := securitygroup.New(&testResourceScope{ + if _, err := securitygroup.New(&testResourceScope{ Client: client, securityGroupSpec: []securitygroup.SecurityGroupSpec{ { @@ -151,7 +198,7 @@ func createTestResources(t *testing.T, client cloud.Client, prefix string, tags t.Fatalf("securitygroup.Reconcile() error = %v", err) } - if err := loadbalancer.New(&testResourceScope{ + if _, err := loadbalancer.New(&testResourceScope{ Client: client, loadBalancerSpec: loadbalancer.LoadBalancerSpec{ Name: prefix + "-apiserver", diff --git a/cloud/client.go b/cloud/client.go index f44c051..b2aff03 100644 --- a/cloud/client.go +++ b/cloud/client.go @@ -15,8 +15,15 @@ import ( iaas "github.com/stackitcloud/stackit-sdk-go/services/iaas/v2api" lb "github.com/stackitcloud/stackit-sdk-go/services/loadbalancer/v2api" + ctrl "sigs.k8s.io/controller-runtime" ) +// Reconciler is a common interface for reconciling and deleting STACKIT cloud resources. +type Reconciler interface { + Reconcile(ctx context.Context) (ctrl.Result, error) + Delete(ctx context.Context) (ctrl.Result, error) +} + // Client provides the target STACKIT project, region, and SDK API clients. type Client interface { ProjectID() string @@ -33,7 +40,7 @@ type Client interface { // // Controllers receive a Factory rather than a Client so that the real // implementation can be swapped for the fake in tests. -type Factory func(ctx context.Context, creds Credentials) (Client, error) +type Factory func(creds Credentials) (Client, error) // Credentials carries the materials needed to construct a STACKIT API client. // For MVP we only need the service-account JSON and project ID. diff --git a/cloud/sdk_client.go b/cloud/sdk_client.go index 45a06e2..efe06ad 100644 --- a/cloud/sdk_client.go +++ b/cloud/sdk_client.go @@ -11,7 +11,6 @@ You may obtain a copy of the License at package cloud import ( - "context" "fmt" "os" @@ -42,7 +41,7 @@ type SDKClient struct { // The credential secret format mirrors machine-controller-manager-provider-stackit: // "project-id" plus "serviceaccount.json". Authentication uses the STACKIT // service-account key flow. -func NewClient(_ context.Context, creds Credentials) (Client, error) { +func NewClient(creds Credentials) (Client, error) { if creds.ProjectID == "" { return nil, fmt.Errorf("%w: project ID is empty", shared.ErrInvalidInput) } diff --git a/cloud/sdk_client_test.go b/cloud/sdk_client_test.go index d3d1856..3661429 100644 --- a/cloud/sdk_client_test.go +++ b/cloud/sdk_client_test.go @@ -11,7 +11,6 @@ You may obtain a copy of the License at package cloud import ( - "context" "errors" "testing" @@ -26,7 +25,7 @@ const ( func TestNewClientValidation(t *testing.T) { t.Run("rejects empty project ID", func(t *testing.T) { - _, err := NewClient(context.Background(), Credentials{ + _, err := NewClient(Credentials{ Region: testSDKRegion, ServiceAccountJSON: []byte(`{}`), }) @@ -36,7 +35,7 @@ func TestNewClientValidation(t *testing.T) { }) t.Run("rejects empty region", func(t *testing.T) { - _, err := NewClient(context.Background(), Credentials{ + _, err := NewClient(Credentials{ ProjectID: testSDKProjectID, ServiceAccountJSON: []byte(`{}`), }) @@ -47,7 +46,7 @@ func TestNewClientValidation(t *testing.T) { t.Run("rejects empty service account JSON when STACKIT_NO_AUTH is not true", func(t *testing.T) { t.Setenv(stackitNoAuthEnv, "false") - _, err := NewClient(context.Background(), Credentials{ + _, err := NewClient(Credentials{ ProjectID: testSDKProjectID, Region: testSDKRegion, }) @@ -58,7 +57,7 @@ func TestNewClientValidation(t *testing.T) { t.Run("creates SDKClient when STACKIT_NO_AUTH is true", func(t *testing.T) { t.Setenv(stackitNoAuthEnv, testBoolTrue) - client, err := NewClient(context.Background(), Credentials{ + client, err := NewClient(Credentials{ ProjectID: testSDKProjectID, Region: testSDKRegion, }) diff --git a/cloud/services/availabilityzone/reconcile.go b/cloud/services/availabilityzone/reconcile.go index d14b7d7..18133f6 100644 --- a/cloud/services/availabilityzone/reconcile.go +++ b/cloud/services/availabilityzone/reconcile.go @@ -14,23 +14,32 @@ import ( "context" "fmt" + ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" + infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) -func (s *Service) Reconcile(ctx context.Context) error { +func (s *Service) Reconcile(ctx context.Context) (ctrl.Result, error) { log := logf.FromContext(ctx) zones, err := s.list(ctx) if err != nil { - return err - } - spec := s.scope.AvailabilityZoneSpec() - if spec.SetZones != nil { - spec.SetZones(zones) + return s.scope.CloudFailureResult( + "AvailabilityZonesError", + err, + shared.RetryableErrorRequeueAfter, + true, + infrav1.ClusterReadyCondition, + ) } + s.scope.SetZones(zones) log.V(1).Info("Reconciled availability zones", "count", len(zones)) - return nil + return ctrl.Result{}, nil +} + +func (s *Service) Delete(_ context.Context) (ctrl.Result, error) { + return ctrl.Result{}, nil } // list retrieves the availability zones for the configured region. diff --git a/cloud/services/availabilityzone/reconcile_test.go b/cloud/services/availabilityzone/reconcile_test.go index 89ab47c..098ff84 100644 --- a/cloud/services/availabilityzone/reconcile_test.go +++ b/cloud/services/availabilityzone/reconcile_test.go @@ -30,10 +30,11 @@ import ( const testRegion = "eu01" type testScope struct { + shared.NoOpReconcileScope projectID string region string iaasClient *iaas.APIClient - spec availabilityzone.AvailabilityZoneSpec + setZones func(zones []string) } func (s *testScope) ProjectID() string { @@ -48,8 +49,10 @@ func (s *testScope) IaaSClient() *iaas.APIClient { return s.iaasClient } -func (s *testScope) AvailabilityZoneSpec() availabilityzone.AvailabilityZoneSpec { - return s.spec +func (s *testScope) SetZones(zones []string) { + if s.setZones != nil { + s.setZones(zones) + } } func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { @@ -68,13 +71,13 @@ func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { return iaasClient } -func newTestService(t *testing.T, spec availabilityzone.AvailabilityZoneSpec, handler http.Handler) *availabilityzone.Service { +func newTestService(t *testing.T, setZones func(zones []string), handler http.Handler) *availabilityzone.Service { t.Helper() return availabilityzone.New(&testScope{ region: testRegion, iaasClient: newTestIaaSClient(t, handler), - spec: spec, + setZones: setZones, }) } @@ -89,13 +92,10 @@ func writeJSON(t *testing.T, w http.ResponseWriter, value any) { func TestServiceReconcile(t *testing.T) { t.Run("lists availability zones and passes them to SetZones", func(t *testing.T) { var recorded []string - spec := availabilityzone.AvailabilityZoneSpec{ - SetZones: func(zones []string) { - recorded = zones - }, - } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestService(t, func(zones []string) { + recorded = zones + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/availability-zones") { writeJSON(t, w, map[string]any{ "items": []string{"eu01-1", "eu01-2", "eu01-3"}, @@ -105,7 +105,7 @@ func TestServiceReconcile(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if !slices.Equal(recorded, []string{"eu01-1", "eu01-2", "eu01-3"}) { @@ -114,12 +114,12 @@ func TestServiceReconcile(t *testing.T) { }) t.Run("returns classified error when API fails", func(t *testing.T) { - svc := newTestService(t, availabilityzone.AvailabilityZoneSpec{}, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + svc := newTestService(t, nil, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusInternalServerError) writeJSON(t, w, map[string]any{"message": "backend error"}) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrTransient) { t.Fatalf("Reconcile() error = %v, want ErrTransient", err) } diff --git a/cloud/services/availabilityzone/service.go b/cloud/services/availabilityzone/service.go index f3c0c86..23c2ca0 100644 --- a/cloud/services/availabilityzone/service.go +++ b/cloud/services/availabilityzone/service.go @@ -12,15 +12,11 @@ package availabilityzone import "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" -// AvailabilityZoneSpec describes the callback used to record discovered availability zones. -type AvailabilityZoneSpec struct { - SetZones func(zones []string) -} - // Scope is an interface that provides scope data needed for availability zone reconciliation. type Scope interface { shared.IaaSClientScope - AvailabilityZoneSpec() AvailabilityZoneSpec + shared.ReconcileScope + SetZones(zones []string) } // Service implements availability zones reconciler. diff --git a/cloud/services/bastion/reconcile.go b/cloud/services/bastion/reconcile.go new file mode 100644 index 0000000..d2b8519 --- /dev/null +++ b/cloud/services/bastion/reconcile.go @@ -0,0 +1,172 @@ +/* +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 +*/ + +package bastion + +import ( + "context" + "time" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" + logf "sigs.k8s.io/controller-runtime/pkg/log" + + infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/publicip" + "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" +) + +func (s *Service) Reconcile(ctx context.Context) (ctrl.Result, error) { + log := logf.FromContext(ctx) + + if !s.scope.BastionEnabled() { + // The reason is set only after a cleanup has succeeded, so anything else + // means bastion resources may still exist. Keying on it rather than on + // the status keeps the tag-based cleanup to once per cluster. + condition := s.scope.FindCondition(infrav1.ClusterBastionReadyCondition) + if condition == nil || condition.Reason != DisabledReason { + if err := s.deleteResources(ctx); err != nil { + return s.handleError(ctx, err) + } + } + s.scope.SetConditions( + metav1.ConditionTrue, + DisabledReason, + "bastion disabled", + infrav1.ClusterBastionReadyCondition, + ) + return ctrl.Result{}, nil + } + + cloudInit, err := s.scope.ResolveBastionCloudInit(ctx) + if err != nil { + log.Error(err, "Failed to resolve bastion cloud-init", "cluster", s.scope.Name()) + s.scope.Warnf("CloudInitRefError", "Failed to resolve bastion cloudInitRef: %v", err) + s.scope.SetNotReady( + "CloudInitRefError", + err.Error(), + infrav1.ClusterBastionReadyCondition, + infrav1.ClusterReadyCondition, + ) + return ctrl.Result{}, nil + } + cloudInitHash := CloudInitHash(cloudInit) + s.scope.SetBastionCloudInit(cloudInit, cloudInitHash) + + if s.needsRecreate(cloudInitHash) { + if err := server.New(s.scope).DeletePrimitive(ctx); err != nil { + return s.handleError(ctx, err) + } + s.scope.SetNotReady( + "Recreating", + "recreating bastion because cloudInitRef content changed", + infrav1.ClusterBastionReadyCondition, + infrav1.ClusterReadyCondition, + ) + s.scope.Event( + "BastionRecreating", + "Recreating bastion because cloudInitRef content changed", + ) + return ctrl.Result{RequeueAfter: shared.RetryableErrorRequeueAfter}, nil + } + + srv, created, err := server.New(s.scope).ReconcilePrimitive(ctx) + if err != nil { + return s.handleError(ctx, err) + } + if created { + s.scope.Eventf("BastionCreated", "Created bastion %s", srv.ID) + } + if err := securitygroup.New(s.scope).ReconcilePrimitive(ctx); err != nil { + return s.handleError(ctx, err) + } + if _, err := publicip.New(s.scope).Reconcile(ctx); err != nil { + return s.handleError(ctx, err) + } + + if ready, reason, message, warn := server.StateCondition(srv.State, srv.PowerStatus); !ready { + previousReason := "" + if previous := s.scope.FindCondition(infrav1.ClusterBastionReadyCondition); previous != nil { + previousReason = previous.Reason + } + s.scope.SetNotReady(reason, "bastion "+message, infrav1.ClusterBastionReadyCondition, infrav1.ClusterReadyCondition) + // Only warn on entering the state, not on every requeue. + if warn && previousReason != reason { + s.scope.Warnf(reason, "Bastion server %s: %s", srv.ID, message) + } + return ctrl.Result{RequeueAfter: 15 * time.Second}, nil + } + if s.scope.BastionPublicIP() == "" { + s.scope.SetNotReady( + "Provisioning", + "waiting for bastion public IP address", + infrav1.ClusterBastionReadyCondition, + infrav1.ClusterReadyCondition, + ) + return ctrl.Result{RequeueAfter: 10 * time.Second}, nil + } + s.scope.SetConditions( + metav1.ConditionTrue, + "Available", + "", + infrav1.ClusterBastionReadyCondition, + ) + return ctrl.Result{}, nil +} + +func (s *Service) Delete(ctx context.Context) (ctrl.Result, error) { + if err := s.deleteResources(ctx); err != nil { + log := logf.FromContext(ctx) + log.Error(err, "Failed to delete bastion", "cluster", s.scope.Name()) + s.scope.Warnf("FailedDeleteBastion", "Failed to delete bastion: %v", err) + return ctrl.Result{}, err + } + return ctrl.Result{}, nil +} + +func (s *Service) deleteResources(ctx context.Context) error { + hadBastion := s.scope.HasBastionStatus() + if _, err := publicip.New(s.scope).Delete(ctx); err != nil { + return err + } + if err := server.New(s.scope).DeletePrimitive(ctx); err != nil { + return err + } + if hadBastion { + s.scope.Event("BastionDeleted", "Deleted bastion") + } + if err := securitygroup.New(s.scope).DeletePrimitive(ctx); err != nil { + return err + } + return nil +} + +func (s *Service) handleError(ctx context.Context, err error) (ctrl.Result, error) { + log := logf.FromContext(ctx) + log.Error(err, "Failed to reconcile bastion", "cluster", s.scope.Name()) + s.scope.Warnf("FailedCreateBastion", "Failed to reconcile bastion: %v", err) + return s.scope.CloudFailureResult( + "BastionError", + err, + shared.RetryableErrorRequeueAfter, + false, + infrav1.ClusterBastionReadyCondition, + infrav1.ClusterReadyCondition, + ) +} + +func (s *Service) needsRecreate(cloudInitHash string) bool { + if s.scope.BastionServerID() == "" { + return false + } + return s.scope.BastionCloudInitHash() != cloudInitHash +} diff --git a/cloud/services/bastion/reconcile_test.go b/cloud/services/bastion/reconcile_test.go new file mode 100644 index 0000000..93e81ee --- /dev/null +++ b/cloud/services/bastion/reconcile_test.go @@ -0,0 +1,238 @@ +/* +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 +*/ + +package bastion_test + +import ( + "context" + "errors" + "testing" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud" + cloudfake "github.com/stackitcloud/cluster-api-provider-stackit/cloud/fake" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/bastion" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/network" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/publicip" + "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" +) + +type testScope struct { + cloud.Client + shared.NoOpReconcileScope + enabled bool + cloudInit []byte + cloudInitErr error + cloudInitHash string + serverID string + publicIPID string + publicIP string + securityGroupID string + networkID string + conditionReason string + conditionStatus metav1.ConditionStatus + notReadyReason string + savedCloudHash string + existingCond *metav1.Condition +} + +func (s *testScope) BastionEnabled() bool { + return s.enabled +} + +func (s *testScope) ResolveBastionCloudInit(_ context.Context) ([]byte, error) { + return s.cloudInit, s.cloudInitErr +} + +func (s *testScope) SetBastionCloudInit(cloudInit []byte, cloudInitHash string) { + s.cloudInit = cloudInit + s.savedCloudHash = cloudInitHash +} + +func (s *testScope) BastionServerID() string { + return s.serverID +} + +func (s *testScope) BastionCloudInitHash() string { + return s.cloudInitHash +} + +func (s *testScope) BastionPublicIP() string { + return s.publicIP +} + +func (s *testScope) HasBastionStatus() bool { + return s.serverID != "" || s.publicIPID != "" || s.securityGroupID != "" +} + +func (s *testScope) ServerSpec() server.ServerSpec { + return server.ServerSpec{ + ID: s.serverID, + Name: "cluster-bastion", + MachineType: "t1.1", + ImageID: "img-1", + NetworkID: s.networkID, + Tags: map[string]string{"cluster": "c1", "role": "bastion"}, + UserData: s.cloudInit, + } +} + +func (s *testScope) SetServer(srv *server.Server, created bool) { + if srv == nil { + s.serverID = "" + return + } + s.serverID = srv.ID + if created || s.cloudInitHash == "" { + s.cloudInitHash = s.savedCloudHash + } +} + +func (s *testScope) SecurityGroupSpecs() []securitygroup.SecurityGroupSpec { + var serverIDs []string + if s.serverID != "" { + serverIDs = []string{s.serverID} + } + return []securitygroup.SecurityGroupSpec{ + { + ID: s.securityGroupID, + Name: "cluster-bastion-sg", + Tags: map[string]string{"cluster": "c1", "role": "bastion"}, + ServerIDs: serverIDs, + Rules: []securitygroup.Rule{ + { + Direction: securitygroup.DirectionIngress, + Protocol: securitygroup.ProtocolTCP, + PortMin: 22, + PortMax: 22, + IPRange: "0.0.0.0/0", + }, + }, + }, + } +} + +func (s *testScope) SetSecurityGroup(_ string, sg *securitygroup.SecurityGroup) { + if sg == nil { + s.securityGroupID = "" + return + } + s.securityGroupID = sg.ID +} + +func (s *testScope) PublicIPSpec() publicip.PublicIPSpec { + return publicip.PublicIPSpec{ + ID: s.publicIPID, + ServerID: s.serverID, + Tags: map[string]string{"cluster": "c1", "role": "bastion"}, + } +} + +func (s *testScope) SetPublicIP(pip *publicip.PublicIP) { + if pip == nil { + s.publicIPID = "" + s.publicIP = "" + return + } + s.publicIPID = pip.ID + s.publicIP = pip.IP +} + +func (s *testScope) FindCondition(conditionType string) *metav1.Condition { + if conditionType == infrav1.ClusterBastionReadyCondition { + return s.existingCond + } + return nil +} + +func (s *testScope) SetConditions(status metav1.ConditionStatus, reason, _ string, _ ...string) { + s.conditionStatus = status + s.conditionReason = reason +} + +func (s *testScope) SetNotReady(reason, _ string, _ ...string) { + s.notReadyReason = reason +} + +func TestReconcile(t *testing.T) { + ctx := context.Background() + + t.Run("marks condition Skipped when bastion is disabled", func(t *testing.T) { + client := cloudfake.New() + scope := &testScope{ + Client: client, + enabled: false, + } + + res, err := bastion.New(scope).Reconcile(ctx) + if err != nil { + t.Fatalf("Reconcile() error = %v", err) + } + if !res.IsZero() { + t.Fatalf("Reconcile() result = %#v, want zero", res) + } + if scope.conditionReason != bastion.DisabledReason { + t.Fatalf("conditionReason = %q, want %q", scope.conditionReason, bastion.DisabledReason) + } + }) + + t.Run("provisions server, security group, and public IP when enabled", func(t *testing.T) { + client := cloudfake.New(network.Network{ + ID: "net-1", + Name: "net-1", + }) + + scope := &testScope{ + Client: client, + enabled: true, + networkID: "net-1", + cloudInit: []byte("#cloud-config"), + } + + res, err := bastion.New(scope).Reconcile(ctx) + if err != nil { + t.Fatalf("Reconcile() error = %v", err) + } + if !res.IsZero() { + t.Fatalf("Reconcile() result = %#v, want zero", res) + } + if scope.serverID == "" || scope.securityGroupID == "" || scope.publicIP == "" { + t.Fatalf("expected serverID, securityGroupID, and publicIP to be set, got %q / %q / %q", + scope.serverID, scope.securityGroupID, scope.publicIP) + } + if scope.conditionStatus != metav1.ConditionTrue || scope.conditionReason != "Available" { + t.Fatalf("condition = (%s, %s), want (True, Available)", scope.conditionStatus, scope.conditionReason) + } + }) + + t.Run("sets NotReady when cloudInit resolution fails", func(t *testing.T) { + client := cloudfake.New() + scope := &testScope{ + Client: client, + enabled: true, + cloudInitErr: errors.New("configmap not found"), + } + + res, err := bastion.New(scope).Reconcile(ctx) + if err != nil { + t.Fatalf("Reconcile() error = %v, want nil", err) + } + if !res.IsZero() { + t.Fatalf("Reconcile() result = %#v, want zero", res) + } + if scope.notReadyReason != "CloudInitRefError" { + t.Fatalf("notReadyReason = %q, want CloudInitRefError", scope.notReadyReason) + } + }) +} diff --git a/cloud/services/bastion/service.go b/cloud/services/bastion/service.go new file mode 100644 index 0000000..44a3a72 --- /dev/null +++ b/cloud/services/bastion/service.go @@ -0,0 +1,60 @@ +/* +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 +*/ + +package bastion + +import ( + "context" + "crypto/sha256" + "fmt" + + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/publicip" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/securitygroup" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/server" +) + +// DisabledReason is read back to decide whether the disabled cleanup already +// ran, so it must not drift. +const DisabledReason = "Skipped" + +// Scope is an interface that provides scope data needed for bastion reconciliation. +type Scope interface { + server.Scope + securitygroup.Scope + publicip.Scope + BastionEnabled() bool + ResolveBastionCloudInit(ctx context.Context) ([]byte, error) + SetBastionCloudInit(cloudInit []byte, cloudInitHash string) + BastionServerID() string + BastionCloudInitHash() string + BastionPublicIP() string + HasBastionStatus() bool +} + +// Service implements the bastion reconciler. +type Service struct { + scope Scope +} + +// New returns Service from given scope. +func New(scope Scope) *Service { + return &Service{ + scope: scope, + } +} + +// CloudInitHash returns the SHA-256 hex digest of cloudInit, or an empty string +// when cloudInit is empty. +func CloudInitHash(cloudInit []byte) string { + if len(cloudInit) == 0 { + return "" + } + return fmt.Sprintf("%x", sha256.Sum256(cloudInit)) +} diff --git a/cloud/services/loadbalancer/reconcile.go b/cloud/services/loadbalancer/reconcile.go index 419a88c..6380594 100644 --- a/cloud/services/loadbalancer/reconcile.go +++ b/cloud/services/loadbalancer/reconcile.go @@ -13,51 +13,146 @@ package loadbalancer import ( "cmp" "context" + "errors" "fmt" "strings" + "time" lb "github.com/stackitcloud/stackit-sdk-go/services/loadbalancer/v2api" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" + infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) -func (s *Service) Reconcile(ctx context.Context) error { +func (s *Service) Reconcile(ctx context.Context) (ctrl.Result, error) { log := logf.FromContext(ctx) - spec := s.scope.LoadBalancerSpec() + if !s.scope.APIServerLoadBalancerEnabled() { + if s.scope.ControlPlaneEndpointHost() != "" { + s.scope.UseExternalControlPlaneEndpoint() + s.scope.SetConditions( + metav1.ConditionTrue, + "Skipped", + "external endpoint provided", + infrav1.ClusterLoadBalancerReadyCondition, + ) + return ctrl.Result{}, nil + } + log.Error(errors.New("controlPlaneEndpoint host is empty"), "API server load balancer is disabled and controlPlaneEndpoint is empty", "cluster", s.scope.Name()) + s.scope.Warn("EndpointMissing", "apiServerLoadBalancer.enabled is false and controlPlaneEndpoint is empty") + s.scope.SetNotReady( + "EndpointMissing", + "apiServerLoadBalancer.enabled is false and controlPlaneEndpoint is empty", + infrav1.ClusterLoadBalancerReadyCondition, + infrav1.ClusterReadyCondition, + ) + return ctrl.Result{}, nil + } + + spec, err := s.scope.ResolveLoadBalancerSpec(ctx) + if err != nil { + return ctrl.Result{}, err + } if err := spec.validate(); err != nil { - return err + return s.handleCreateError(ctx, err) } + previousEndpointHost := s.scope.APIServerEndpointHost() + cond := s.scope.FindCondition(infrav1.ClusterLoadBalancerReadyCondition) + wasLBReady := cond != nil && cond.Status == metav1.ConditionTrue + loadBalancer, created, err := s.ensureLoadBalancer(ctx, spec) if err != nil { - return err + return s.handleCreateError(ctx, err) } loadBalancer.Port = spec.Port - if spec.SetLoadBalancer != nil { - spec.SetLoadBalancer(loadBalancer, created) + s.scope.SetLoadBalancer(loadBalancer) + if created { + s.scope.Eventf( + "LoadBalancerCreated", + "Created API server load balancer %s", loadBalancer.ID, + ) } if loadBalancer.IP == "" { - return nil + s.scope.SetNotReady( + "Provisioning", + "waiting for API server load balancer IP address", + infrav1.ClusterLoadBalancerReadyCondition, + infrav1.ClusterReadyCondition, + ) + return ctrl.Result{RequeueAfter: 10 * time.Second}, nil } // An empty set never overwrites a populated pool: cluster deletion filters // out every machine while the API server is still needed for drain. if len(spec.Targets) > 0 { if err := s.setTargets(ctx, loadBalancer.ID, spec.Port, spec.Targets); err != nil { - return fmt.Errorf("%w: %w", errTargetPoolUpdate, err) + targetErr := fmt.Errorf("%w: %w", errTargetPoolUpdate, err) + if !shared.IsRetryable(targetErr) { + s.scope.Warnf( + "LoadBalancerTargetError", + "Cannot update API server load balancer target pool: %v", targetErr, + ) + } + // Scoped to the load balancer condition: failing the cluster would + // stop the machine reconciler from replacing the broken machine. + s.scope.SetConditions( + metav1.ConditionFalse, + "LoadBalancerTargetError", + targetErr.Error(), + infrav1.ClusterLoadBalancerReadyCondition, + ) + // Requeue even on a permanent error: this return skips SetReady, so + // no machine exists yet whose events could retry it. + return s.scope.TargetPoolFailureResult(targetErr, shared.RetryableErrorRequeueAfter) } log.V(1).Info("Reconciled API server load balancer target pool", "targets", len(spec.Targets)) } + + isLBReady := wasLBReady && previousEndpointHost == loadBalancer.IP + if !isLBReady { + s.scope.SetConditions( + metav1.ConditionTrue, + "Available", + "", + infrav1.ClusterLoadBalancerReadyCondition, + ) + s.scope.Eventf( + "LoadBalancerReady", + "API server load balancer is ready at %s", loadBalancer.IP, + ) + } log.V(1).Info("Reconciled load balancer resources", "loadBalancerID", loadBalancer.ID, "created", created) - return nil + return ctrl.Result{}, nil } -func (s *Service) Delete(ctx context.Context) error { +func (s *Service) handleCreateError(ctx context.Context, err error) (ctrl.Result, error) { + log := logf.FromContext(ctx) + log.Error(err, "Failed to create API server load balancer", + "cluster", s.scope.Name(), + "region", s.scope.Region(), + ) + s.scope.Warnf( + "FailedCreateLoadBalancer", + "Failed to create API server load balancer: %v", err, + ) + return s.scope.CloudFailureResult( + "LoadBalancerError", + err, + shared.RetryableErrorRequeueAfter, + false, + infrav1.ClusterLoadBalancerReadyCondition, + infrav1.ClusterReadyCondition, + ) +} + +func (s *Service) Delete(ctx context.Context) (ctrl.Result, error) { log := logf.FromContext(ctx) spec := s.scope.LoadBalancerSpec() if spec.ID == "" && len(spec.Tags) == 0 { - return fmt.Errorf("%w: load balancer ID or tags are required", shared.ErrInvalidInput) + return ctrl.Result{}, fmt.Errorf("%w: load balancer ID or tags are required", shared.ErrInvalidInput) } deletedIDs, err := shared.DeleteByIDOrTags(ctx, spec.ID, spec.Tags, s.deleteByID, s.listIDsByTags) @@ -65,12 +160,19 @@ func (s *Service) Delete(ctx context.Context) error { log.V(1).Info("Deleted load balancer", "loadBalancerID", deletedID) } if err != nil { - return err + log.Error(err, "Failed to delete API server load balancer", "cluster", s.scope.Name(), "loadBalancerID", spec.ID) + s.scope.Warnf("FailedDeleteLoadBalancer", + "Failed to delete API server load balancer %s: %v", spec.ID, err) + return ctrl.Result{}, err } - if spec.SetLoadBalancer != nil { - spec.SetLoadBalancer(nil, false) + s.scope.SetLoadBalancer(nil) + if spec.ID != "" { + s.scope.Eventf( + "LoadBalancerDeleted", + "Deleted API server load balancer %s", spec.ID, + ) } - return nil + return ctrl.Result{}, nil } // get retrieves a STACKIT load balancer by ID. diff --git a/cloud/services/loadbalancer/reconcile_test.go b/cloud/services/loadbalancer/reconcile_test.go index 8df0b30..85e8182 100644 --- a/cloud/services/loadbalancer/reconcile_test.go +++ b/cloud/services/loadbalancer/reconcile_test.go @@ -19,9 +19,11 @@ import ( "strings" "sync" "testing" + "time" "github.com/stackitcloud/stackit-sdk-go/core/config" lb "github.com/stackitcloud/stackit-sdk-go/services/loadbalancer/v2api" + ctrl "sigs.k8s.io/controller-runtime" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/loadbalancer" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" @@ -36,10 +38,13 @@ const ( ) type testScope struct { - projectID string - region string - lbClient *lb.APIClient - spec loadbalancer.LoadBalancerSpec + shared.NoOpReconcileScope + projectID string + region string + lbClient *lb.APIClient + spec loadbalancer.LoadBalancerSpec + setLoadBalancer func(apiServerLB *loadbalancer.LoadBalancer) + created bool } func (s *testScope) ProjectID() string { @@ -54,10 +59,44 @@ func (s *testScope) LoadBalancerClient() *lb.APIClient { return s.lbClient } +func (s *testScope) APIServerLoadBalancerEnabled() bool { + return true +} + +func (s *testScope) ControlPlaneEndpointHost() string { + return "" +} + +func (s *testScope) UseExternalControlPlaneEndpoint() {} + +func (s *testScope) APIServerEndpointHost() string { + return "" +} + +func (s *testScope) ResolveLoadBalancerSpec(_ context.Context) (loadbalancer.LoadBalancerSpec, error) { + return s.spec, nil +} + func (s *testScope) LoadBalancerSpec() loadbalancer.LoadBalancerSpec { return s.spec } +func (s *testScope) SetLoadBalancer(apiServerLB *loadbalancer.LoadBalancer) { + if s.setLoadBalancer != nil { + s.setLoadBalancer(apiServerLB) + } +} + +func (s *testScope) Eventf(reason, _ string, _ ...any) { + if reason == "LoadBalancerCreated" { + s.created = true + } +} + +func (s *testScope) TargetPoolFailureResult(err error, _ time.Duration) (ctrl.Result, error) { + return ctrl.Result{}, err +} + func newTestLBClient(t *testing.T, handler http.Handler) *lb.APIClient { t.Helper() @@ -74,15 +113,29 @@ func newTestLBClient(t *testing.T, handler http.Handler) *lb.APIClient { return lbClient } +func newTestServiceWithScope( + t *testing.T, + spec loadbalancer.LoadBalancerSpec, + setLB func(*loadbalancer.LoadBalancer), + handler http.Handler, +) (*loadbalancer.Service, *testScope) { + t.Helper() + + scope := &testScope{ + projectID: testProjectID, + region: testRegion, + lbClient: newTestLBClient(t, handler), + spec: spec, + setLoadBalancer: setLB, + } + return loadbalancer.New(scope), scope +} + func newTestService(t *testing.T, spec loadbalancer.LoadBalancerSpec, handler http.Handler) *loadbalancer.Service { t.Helper() - return loadbalancer.New(&testScope{ - projectID: testProjectID, - region: testRegion, - lbClient: newTestLBClient(t, handler), - spec: spec, - }) + svc, _ := newTestServiceWithScope(t, spec, nil, handler) + return svc } func writeJSON(t *testing.T, w http.ResponseWriter, value any) { @@ -120,11 +173,10 @@ func sdkLoadBalancerJSON(name string, labels map[string]any, targetPools []any) func TestServiceReconcile(t *testing.T) { t.Run("creates load balancer with expected payload and updates target pool", func(t *testing.T) { var ( - createPayload map[string]any - recordedID string - recordedIP string - recordedPort int32 - recordedCreated bool + createPayload map[string]any + recordedID string + recordedIP string + recordedPort int32 ) spec := loadbalancer.LoadBalancerSpec{ Name: testLBName, @@ -140,12 +192,6 @@ func TestServiceReconcile(t *testing.T) { SeedTargets: []loadbalancer.Target{ {Name: "cp-0", IP: "10.0.0.10"}, }, - SetLoadBalancer: func(apiServerLB *loadbalancer.LoadBalancer, created bool) { - recordedID = apiServerLB.ID - recordedIP = apiServerLB.IP - recordedPort = apiServerLB.Port - recordedCreated = created - }, } targetPool := []any{ @@ -158,7 +204,11 @@ func TestServiceReconcile(t *testing.T) { }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, scope := newTestServiceWithScope(t, spec, func(apiServerLB *loadbalancer.LoadBalancer) { + recordedID = apiServerLB.ID + recordedIP = apiServerLB.IP + recordedPort = apiServerLB.Port + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/load-balancers"): @@ -173,7 +223,7 @@ func TestServiceReconcile(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } @@ -183,8 +233,8 @@ func TestServiceReconcile(t *testing.T) { if recordedIP != testPublicIP || recordedPort != 6443 { t.Fatalf("recorded address = %s:%d, want %s:6443", recordedIP, recordedPort, testPublicIP) } - if !recordedCreated { - t.Fatal("recordedCreated = false, want true") + if !scope.created { + t.Fatal("scope.created = false, want true") } if createPayload["name"] != testLBName { t.Fatalf("payload name = %v, want %q", createPayload["name"], testLBName) @@ -228,7 +278,7 @@ func TestServiceReconcile(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } @@ -250,23 +300,18 @@ func TestServiceReconcile(t *testing.T) { func TestServiceReconcileReuseAndErrors(t *testing.T) { t.Run("reuses existing load balancer found by ID without listing by tags", func(t *testing.T) { - var ( - recordedID string - recordedCreated = true - ) + var recordedID string spec := loadbalancer.LoadBalancerSpec{ ID: testLBName, Name: testLBName, NetworkID: testNetworkID, Port: loadbalancer.DefaultAPIServerPort, Tags: map[string]string{"cluster.x-k8s.io/cluster-name": "test"}, - SetLoadBalancer: func(apiServerLB *loadbalancer.LoadBalancer, created bool) { - recordedID = apiServerLB.ID - recordedCreated = created - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, scope := newTestServiceWithScope(t, spec, func(apiServerLB *loadbalancer.LoadBalancer) { + recordedID = apiServerLB.ID + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/load-balancers/"+testLBName) { writeJSON(t, w, sdkLoadBalancerJSON(testLBName, nil, nil)) return @@ -274,14 +319,14 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recordedID != testLBName { t.Fatalf("recordedID = %q, want %q", recordedID, testLBName) } - if recordedCreated { - t.Fatal("recordedCreated = true on reused load balancer, want false") + if scope.created { + t.Fatal("scope.created = true on reused load balancer, want false") } }) @@ -296,12 +341,11 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { NetworkID: testNetworkID, Port: loadbalancer.DefaultAPIServerPort, Tags: map[string]string{"cluster.x-k8s.io/cluster-name": "test"}, - SetLoadBalancer: func(apiServerLB *loadbalancer.LoadBalancer, _ bool) { - recordedID = apiServerLB.ID - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, _ := newTestServiceWithScope(t, spec, func(apiServerLB *loadbalancer.LoadBalancer) { + recordedID = apiServerLB.ID + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/load-balancers/stale-lb"): @@ -319,7 +363,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if !getByIDCalled { @@ -337,12 +381,11 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { NetworkID: testNetworkID, Port: loadbalancer.DefaultAPIServerPort, Tags: map[string]string{"cluster.x-k8s.io/cluster-name": "test"}, - SetLoadBalancer: func(apiServerLB *loadbalancer.LoadBalancer, _ bool) { - recordedID = apiServerLB.ID - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, _ := newTestServiceWithScope(t, spec, func(apiServerLB *loadbalancer.LoadBalancer) { + recordedID = apiServerLB.ID + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/load-balancers") { writeJSON(t, w, map[string]any{"loadBalancers": []any{ sdkLoadBalancerJSON(testLBName, map[string]any{ @@ -354,7 +397,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recordedID != testLBName { @@ -377,7 +420,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { }}) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrConflict) { t.Fatalf("Reconcile() error = %v, want ErrConflict", err) } @@ -394,13 +437,12 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { Port: loadbalancer.DefaultAPIServerPort, Tags: map[string]string{"cluster.x-k8s.io/cluster-name": "test"}, Targets: []loadbalancer.Target{{Name: "cp-0", IP: "10.0.0.10"}}, - SetLoadBalancer: func(apiServerLB *loadbalancer.LoadBalancer, _ bool) { - recordedID = apiServerLB.ID - recordedIP = apiServerLB.IP - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, _ := newTestServiceWithScope(t, spec, func(apiServerLB *loadbalancer.LoadBalancer) { + recordedID = apiServerLB.ID + recordedIP = apiServerLB.IP + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/load-balancers"): @@ -417,7 +459,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !loadbalancer.IsTargetPoolUpdateError(err) { t.Fatalf("Reconcile() error = %v, want IsTargetPoolUpdateError", err) } @@ -481,7 +523,7 @@ func TestSetTargets(t *testing.T) { {Name: "cp-1", IP: "10.0.0.11"}, } scope.spec.Targets = desired - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if len(updatePayloads) != 1 { @@ -489,7 +531,7 @@ func TestSetTargets(t *testing.T) { } // Unchanged pool must not trigger another write. - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() repeat error = %v", err) } if len(updatePayloads) != 1 { @@ -498,7 +540,7 @@ func TestSetTargets(t *testing.T) { // Shrinking pool updates targets. scope.spec.Targets = desired[:1] - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() shrink error = %v", err) } if len(updatePayloads) != 2 { @@ -507,7 +549,7 @@ func TestSetTargets(t *testing.T) { // Target missing name or IP is rejected. scope.spec.Targets = []loadbalancer.Target{{Name: "", IP: "10.0.0.10"}} - if err := svc.Reconcile(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { + if _, err := svc.Reconcile(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Reconcile(invalid target) error = %v, want ErrInvalidInput", err) } } @@ -557,7 +599,7 @@ func TestServiceReconcileValidation(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Reconcile() error = %v, want ErrInvalidInput", err) } @@ -568,19 +610,16 @@ func TestServiceReconcileValidation(t *testing.T) { func TestServiceDelete(t *testing.T) { t.Run("deletes load balancer using ID when provided and clears state", func(t *testing.T) { var ( - deletedID string - clearedLB = &loadbalancer.LoadBalancer{ID: "not-cleared"} - clearedCreated = true + deletedID string + clearedLB = &loadbalancer.LoadBalancer{ID: "not-cleared"} ) spec := loadbalancer.LoadBalancerSpec{ ID: testLBName, - SetLoadBalancer: func(apiServerLB *loadbalancer.LoadBalancer, created bool) { - clearedLB = apiServerLB - clearedCreated = created - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, _ := newTestServiceWithScope(t, spec, func(apiServerLB *loadbalancer.LoadBalancer) { + clearedLB = apiServerLB + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/load-balancers/"+testLBName) { deletedID = testLBName writeJSON(t, w, map[string]any{}) @@ -589,14 +628,14 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if deletedID != testLBName { t.Fatalf("deletedID = %q, want %q", deletedID, testLBName) } - if clearedLB != nil || clearedCreated { - t.Fatalf("cleared state = (%#v, %v), want (nil, false)", clearedLB, clearedCreated) + if clearedLB != nil { + t.Fatalf("cleared state = %#v, want nil", clearedLB) } }) @@ -632,7 +671,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if len(deletedIDs) != 2 || deletedIDs[0] != testLBName || deletedIDs[1] != "second-lb" { @@ -667,7 +706,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if deletedID != testLBName { @@ -684,7 +723,7 @@ func TestServiceDelete(t *testing.T) { writeJSON(t, w, map[string]any{"loadBalancers": []any{}}) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v, want nil", err) } }) @@ -694,7 +733,7 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { + if _, err := svc.Delete(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Delete() error = %v, want ErrInvalidInput", err) } }) diff --git a/cloud/services/loadbalancer/service.go b/cloud/services/loadbalancer/service.go index 1f12001..eda8a9a 100644 --- a/cloud/services/loadbalancer/service.go +++ b/cloud/services/loadbalancer/service.go @@ -11,7 +11,11 @@ You may obtain a copy of the License at package loadbalancer import ( + "context" "errors" + "time" + + ctrl "sigs.k8s.io/controller-runtime" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) @@ -55,20 +59,27 @@ type Target struct { // LoadBalancerSpec describes the desired state of a STACKIT API server load balancer. type LoadBalancerSpec struct { - ID string - Name string - NetworkID string - Port int32 - Tags map[string]string - Targets []Target - SeedTargets []Target - SetLoadBalancer func(loadBalancer *LoadBalancer, created bool) + ID string + Name string + NetworkID string + Port int32 + Tags map[string]string + Targets []Target + SeedTargets []Target } // Scope is an interface that provides scope data needed for load balancer reconciliation. type Scope interface { shared.LoadBalancerClientScope + shared.ReconcileScope + APIServerLoadBalancerEnabled() bool + ControlPlaneEndpointHost() string + UseExternalControlPlaneEndpoint() + APIServerEndpointHost() string + ResolveLoadBalancerSpec(ctx context.Context) (LoadBalancerSpec, error) LoadBalancerSpec() LoadBalancerSpec + SetLoadBalancer(loadBalancer *LoadBalancer) + TargetPoolFailureResult(err error, requeueAfter time.Duration) (ctrl.Result, error) } // Service implements load balancer reconciler. diff --git a/cloud/services/network/reconcile.go b/cloud/services/network/reconcile.go index 985e99b..4b3f5cc 100644 --- a/cloud/services/network/reconcile.go +++ b/cloud/services/network/reconcile.go @@ -15,16 +15,19 @@ import ( "fmt" iaas "github.com/stackitcloud/stackit-sdk-go/services/iaas/v2api" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" + infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) -func (s *Service) Reconcile(ctx context.Context) error { +func (s *Service) Reconcile(ctx context.Context) (ctrl.Result, error) { log := logf.FromContext(ctx) spec := s.scope.NetworkSpec() if err := spec.validate(); err != nil { - return err + return s.handleReconcileError(ctx, spec, err) } var ( @@ -38,23 +41,70 @@ func (s *Service) Reconcile(ctx context.Context) error { net, err = s.get(ctx, spec.ID) } if err != nil { - return err + return s.handleReconcileError(ctx, spec, err) } - if spec.SetNetwork != nil { - spec.SetNetwork(net, created) + s.scope.SetNetwork(net) + if created { + s.scope.Eventf("NetworkCreated", "Created managed network %s", net.ID) } + s.scope.SetConditions( + metav1.ConditionTrue, + "Available", + "", + infrav1.ClusterNetworkReadyCondition, + ) log.V(1).Info("Reconciled network resources", "networkID", net.ID, "created", created) - return nil + return ctrl.Result{}, nil } -func (s *Service) Delete(ctx context.Context) error { +func (s *Service) handleReconcileError(ctx context.Context, spec NetworkSpec, err error) (ctrl.Result, error) { + log := logf.FromContext(ctx) + if !spec.Managed { + log.Error(err, "Failed to get network", + "networkID", spec.ID, + "region", s.scope.Region(), + ) + s.scope.Warnf( + "FailedGetNetwork", + "Failed to get network %s in region %s: %v", + spec.ID, s.scope.Region(), err, + ) + return s.scope.CloudFailureResult( + "NetworkNotFound", + err, + shared.RetryableErrorRequeueAfter, + false, + infrav1.ClusterNetworkReadyCondition, + infrav1.ClusterReadyCondition, + ) + } + log.Error(err, "Failed to reconcile managed network", + "cluster", s.scope.Name(), + "region", s.scope.Region(), + ) + s.scope.Warnf( + "FailedCreateNetwork", + "Failed to reconcile managed network in region %s: %v", + s.scope.Region(), err, + ) + return s.scope.CloudFailureResult( + "NetworkCreateError", + err, + shared.RetryableErrorRequeueAfter, + false, + infrav1.ClusterNetworkReadyCondition, + infrav1.ClusterReadyCondition, + ) +} + +func (s *Service) Delete(ctx context.Context) (ctrl.Result, error) { log := logf.FromContext(ctx) spec := s.scope.NetworkSpec() if !spec.Managed { - return nil + return ctrl.Result{}, nil } if spec.ID == "" && len(spec.Tags) == 0 { - return fmt.Errorf("%w: network ID or tags are required", shared.ErrInvalidInput) + return ctrl.Result{}, fmt.Errorf("%w: network ID or tags are required", shared.ErrInvalidInput) } deletedIDs, err := shared.DeleteByIDOrTags(ctx, spec.ID, spec.Tags, s.deleteByID, s.listIDsByTags) @@ -62,12 +112,34 @@ func (s *Service) Delete(ctx context.Context) error { log.V(1).Info("Deleted network", "networkID", deletedID) } if err != nil { - return err + if shared.IsConflict(err) { + log.Info("Managed network still has resources attached; requeueing deletion", + "cluster", s.scope.Name(), + "networkID", spec.ID, + ) + s.scope.SetConditions( + metav1.ConditionFalse, + "NetworkInUse", + err.Error(), + infrav1.ClusterNetworkReadyCondition, + ) + s.scope.Warnf("NetworkInUse", + "Managed network %s still has active resources attached; retrying deletion: %v", spec.ID, err) + return ctrl.Result{RequeueAfter: shared.DeleteRequeueAfter}, nil + } + log.Error(err, "Failed to delete managed network", + "cluster", s.scope.Name(), + "networkID", spec.ID, + ) + s.scope.Warnf("FailedDeleteNetwork", + "Failed to delete managed network %s: %v", spec.ID, err) + return ctrl.Result{}, err } - if spec.SetNetwork != nil { - spec.SetNetwork(nil, false) + s.scope.SetNetwork(nil) + if spec.ID != "" { + s.scope.Eventf("NetworkDeleted", "Deleted managed network %s", spec.ID) } - return nil + return ctrl.Result{}, nil } // get retrieves a STACKIT network by ID. diff --git a/cloud/services/network/reconcile_test.go b/cloud/services/network/reconcile_test.go index 5f8f337..8ff8fe4 100644 --- a/cloud/services/network/reconcile_test.go +++ b/cloud/services/network/reconcile_test.go @@ -34,10 +34,13 @@ const ( ) type testScope struct { - projectID string - region string - iaasClient *iaas.APIClient - spec network.NetworkSpec + shared.NoOpReconcileScope + projectID string + region string + iaasClient *iaas.APIClient + spec network.NetworkSpec + setNetwork func(network *network.Network) + eventReason string } func (s *testScope) ProjectID() string { @@ -56,6 +59,16 @@ func (s *testScope) NetworkSpec() network.NetworkSpec { return s.spec } +func (s *testScope) SetNetwork(net *network.Network) { + if s.setNetwork != nil { + s.setNetwork(net) + } +} + +func (s *testScope) Eventf(reason, _ string, _ ...any) { + s.eventReason = reason +} + func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { t.Helper() @@ -72,15 +85,24 @@ func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { return iaasClient } -func newTestService(t *testing.T, spec network.NetworkSpec, handler http.Handler) *network.Service { +func newTestServiceWithScope(t *testing.T, spec network.NetworkSpec, setNetwork func(*network.Network), handler http.Handler) (*network.Service, *testScope) { t.Helper() - return network.New(&testScope{ + scope := &testScope{ projectID: testProjectID, region: testRegion, iaasClient: newTestIaaSClient(t, handler), spec: spec, - }) + setNetwork: setNetwork, + } + return network.New(scope), scope +} + +func newTestService(t *testing.T, spec network.NetworkSpec, handler http.Handler) *network.Service { + t.Helper() + + svc, _ := newTestServiceWithScope(t, spec, nil, handler) + return svc } func writeJSON(t *testing.T, w http.ResponseWriter, value any) { @@ -120,19 +142,14 @@ func newCreateNetworkHandler(t *testing.T, createdPayload *map[string]any, prefi func TestServiceReconcile(t *testing.T) { t.Run("fetches network and records IPv4 prefixes via SetNetwork", func(t *testing.T) { - var ( - recorded *network.Network - created bool - ) + var recorded *network.Network spec := network.NetworkSpec{ ID: testNetworkID, - SetNetwork: func(n *network.Network, c bool) { - recorded = n - created = c - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, scope := newTestServiceWithScope(t, spec, func(n *network.Network) { + recorded = n + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/networks/"+testNetworkID) { writeJSON(t, w, map[string]any{ "id": testNetworkID, @@ -148,14 +165,14 @@ func TestServiceReconcile(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recorded == nil || recorded.ID != testNetworkID || recorded.Name != "cluster-net" { t.Fatalf("recorded = %#v, want ID=%s Name=cluster-net", recorded, testNetworkID) } - if created { - t.Fatal("created = true, want false for unmanaged network") + if scope.eventReason != "" { + t.Fatalf("eventReason = %q, want empty for unmanaged network", scope.eventReason) } if !slices.Equal(recorded.IPv4Prefixes, []string{"10.20.0.0/24"}) { t.Fatalf("recorded.IPv4Prefixes = %v, want [10.20.0.0/24]", recorded.IPv4Prefixes) @@ -172,7 +189,7 @@ func TestServiceReconcile(t *testing.T) { writeJSON(t, w, map[string]any{"message": "not found"}) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrNotFound) { t.Fatalf("Reconcile() error = %v, want ErrNotFound", err) } @@ -183,7 +200,7 @@ func TestServiceReconcile(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Reconcile() error = %v, want ErrInvalidInput", err) } @@ -194,7 +211,6 @@ func TestServiceReconcileManagedNetwork(t *testing.T) { t.Run("creates managed network when none exists", func(t *testing.T) { var ( recorded *network.Network - created bool createdPayload map[string]any ) spec := network.NetworkSpec{ @@ -202,23 +218,21 @@ func TestServiceReconcileManagedNetwork(t *testing.T) { IPv4Prefix: network.DefaultNetworkPrefix, Tags: map[string]string{"cluster": "test-cluster"}, Managed: true, - SetNetwork: func(n *network.Network, c bool) { - recorded = n - created = c - }, } handler := newCreateNetworkHandler(t, &createdPayload, []any{"10.0.0.0/24"}) - svc := newTestService(t, spec, handler) + svc, scope := newTestServiceWithScope(t, spec, func(n *network.Network) { + recorded = n + }, handler) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recorded == nil || recorded.ID != testNetworkID { t.Fatalf("recorded = %#v, want ID=%s", recorded, testNetworkID) } - if !created { - t.Fatal("created = false, want true") + if scope.eventReason != "NetworkCreated" { + t.Fatalf("eventReason = %q, want NetworkCreated", scope.eventReason) } if createdPayload["name"] != "test-network" { t.Fatalf("payload name = %v, want test-network", createdPayload["name"]) @@ -237,7 +251,7 @@ func TestServiceReconcileManagedNetwork(t *testing.T) { handler := newCreateNetworkHandler(t, &createdPayload, []any{"10.0.1.0/24"}) svc := newTestService(t, spec, handler) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } ipv4, ok := createdPayload["ipv4"].(map[string]any) @@ -259,7 +273,7 @@ func TestServiceReconcileManagedNetwork(t *testing.T) { handler := newCreateNetworkHandler(t, &createdPayload, []any{"10.0.2.0/24"}) svc := newTestService(t, spec, handler) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } ipv4, ok := createdPayload["ipv4"].(map[string]any) @@ -282,29 +296,24 @@ func TestServiceReconcileManagedNetwork(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Reconcile() error = %v, want ErrInvalidInput", err) } }) t.Run("adopts existing managed network by tags without creating duplicate", func(t *testing.T) { - var ( - recorded *network.Network - created bool - ) + var recorded *network.Network spec := network.NetworkSpec{ Name: "existing-network", IPv4Prefix: network.DefaultNetworkPrefix, Tags: map[string]string{"cluster": "test-cluster"}, Managed: true, - SetNetwork: func(n *network.Network, c bool) { - recorded = n - created = c - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, scope := newTestServiceWithScope(t, spec, func(n *network.Network) { + recorded = n + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/networks") { writeJSON(t, w, map[string]any{ "items": []any{ @@ -326,14 +335,14 @@ func TestServiceReconcileManagedNetwork(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recorded == nil || recorded.ID != testNetworkID { t.Fatalf("recorded = %#v, want ID=%s", recorded, testNetworkID) } - if created { - t.Fatal("created = true, want false when adopting existing network") + if scope.eventReason != "" { + t.Fatalf("eventReason = %q, want empty when adopting existing network", scope.eventReason) } }) } @@ -347,7 +356,7 @@ func TestServiceDelete(t *testing.T) { svc := newTestService(t, spec, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } }) @@ -359,14 +368,13 @@ func TestServiceDelete(t *testing.T) { ID: testNetworkID, Tags: map[string]string{"cluster": "test-cluster"}, Managed: true, - SetNetwork: func(n *network.Network, _ bool) { - if n == nil { - cleared = true - } - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc, _ := newTestServiceWithScope(t, spec, func(n *network.Network) { + if n == nil { + cleared = true + } + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/networks/"+testNetworkID) { deletedID = testNetworkID w.WriteHeader(http.StatusNoContent) @@ -375,14 +383,14 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if deletedID != testNetworkID { t.Fatalf("deletedID = %s, want %s", deletedID, testNetworkID) } if !cleared { - t.Fatal("expected SetNetwork(nil, false) to be called") + t.Fatal("expected SetNetwork(nil) to be called") } }) @@ -417,7 +425,7 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if deletedID != testNetworkID { diff --git a/cloud/services/network/service.go b/cloud/services/network/service.go index 99b279d..cb013bd 100644 --- a/cloud/services/network/service.go +++ b/cloud/services/network/service.go @@ -30,13 +30,14 @@ type NetworkSpec struct { IPv4PrefixLength *int32 Tags map[string]string Managed bool - SetNetwork func(network *Network, created bool) } // Scope is an interface that provides scope data needed for network reconciliation. type Scope interface { shared.IaaSClientScope + shared.ReconcileScope NetworkSpec() NetworkSpec + SetNetwork(network *Network) } // Service implements network reconciler. diff --git a/cloud/services/publicip/reconcile.go b/cloud/services/publicip/reconcile.go index d3ee05c..f9b2f1f 100644 --- a/cloud/services/publicip/reconcile.go +++ b/cloud/services/publicip/reconcile.go @@ -15,50 +15,49 @@ import ( "fmt" iaas "github.com/stackitcloud/stackit-sdk-go/services/iaas/v2api" + ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) -func (s *Service) Reconcile(ctx context.Context) error { +func (s *Service) Reconcile(ctx context.Context) (ctrl.Result, error) { log := logf.FromContext(ctx) spec := s.scope.PublicIPSpec() if err := spec.validate(); err != nil { - return err + return ctrl.Result{}, err } publicIP, err := s.ensurePublicIP(ctx, spec) if err != nil { - return err + return ctrl.Result{}, err } if spec.ServerID != "" && publicIP.NetworkInterfaceID == "" { if err := s.attachToServer(ctx, spec.ServerID, publicIP.ID); err != nil { - return err + return ctrl.Result{}, err } publicIP, err = s.get(ctx, publicIP.ID) if err != nil { - return err + return ctrl.Result{}, err } } - if spec.SetPublicIP != nil { - spec.SetPublicIP(publicIP) - } + s.scope.SetPublicIP(publicIP) log.V(1).Info("Reconciled public IP resources", "publicIPID", publicIP.ID) - return nil + return ctrl.Result{}, nil } -func (s *Service) Delete(ctx context.Context) error { +func (s *Service) Delete(ctx context.Context) (ctrl.Result, error) { log := logf.FromContext(ctx) spec := s.scope.PublicIPSpec() if spec.ID == "" && len(spec.Tags) == 0 { - return fmt.Errorf("%w: public IP ID or tags are required", shared.ErrInvalidInput) + return ctrl.Result{}, fmt.Errorf("%w: public IP ID or tags are required", shared.ErrInvalidInput) } serverIDs, err := s.resolveServerIDs(ctx, spec) if err != nil { - return err + return ctrl.Result{}, err } deletedIDs, err := shared.DeleteByIDOrTags(ctx, spec.ID, spec.Tags, func(ctx context.Context, id string) (bool, error) { return s.detachAndDeleteByID(ctx, id, serverIDs) @@ -67,13 +66,11 @@ func (s *Service) Delete(ctx context.Context) error { log.V(1).Info("Deleted public IP", "publicIPID", deletedID) } if err != nil { - return err + return ctrl.Result{}, err } - if spec.SetPublicIP != nil { - spec.SetPublicIP(nil) - } - return nil + s.scope.SetPublicIP(nil) + return ctrl.Result{}, nil } // get retrieves a STACKIT public IP by ID. diff --git a/cloud/services/publicip/reconcile_test.go b/cloud/services/publicip/reconcile_test.go index 78af6ac..9630161 100644 --- a/cloud/services/publicip/reconcile_test.go +++ b/cloud/services/publicip/reconcile_test.go @@ -41,10 +41,11 @@ const ( ) type testScope struct { - projectID string - region string - iaasClient *iaas.APIClient - spec publicip.PublicIPSpec + projectID string + region string + iaasClient *iaas.APIClient + spec publicip.PublicIPSpec + setPublicIP func(publicIP *publicip.PublicIP) } func (s *testScope) ProjectID() string { @@ -63,6 +64,12 @@ func (s *testScope) PublicIPSpec() publicip.PublicIPSpec { return s.spec } +func (s *testScope) SetPublicIP(pip *publicip.PublicIP) { + if s.setPublicIP != nil { + s.setPublicIP(pip) + } +} + func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { t.Helper() @@ -79,17 +86,24 @@ func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { return iaasClient } -func newTestService(t *testing.T, spec publicip.PublicIPSpec, handler http.Handler) *publicip.Service { +func newTestServiceWithSetter(t *testing.T, spec publicip.PublicIPSpec, setPublicIP func(*publicip.PublicIP), handler http.Handler) *publicip.Service { t.Helper() return publicip.New(&testScope{ - projectID: testProjectID, - region: testRegion, - iaasClient: newTestIaaSClient(t, handler), - spec: spec, + projectID: testProjectID, + region: testRegion, + iaasClient: newTestIaaSClient(t, handler), + spec: spec, + setPublicIP: setPublicIP, }) } +func newTestService(t *testing.T, spec publicip.PublicIPSpec, handler http.Handler) *publicip.Service { + t.Helper() + + return newTestServiceWithSetter(t, spec, nil, handler) +} + func writeJSON(t *testing.T, w http.ResponseWriter, value any) { t.Helper() w.Header().Set("Content-Type", "application/json") @@ -124,12 +138,11 @@ func TestServiceReconcile(t *testing.T) { spec := publicip.PublicIPSpec{ Tags: map[string]string{"cluster": "test"}, ServerID: testServerID, - SetPublicIP: func(pip *publicip.PublicIP) { - recorded = pip - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(pip *publicip.PublicIP) { + recorded = pip + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/public-ips"): @@ -154,7 +167,7 @@ func TestServiceReconcile(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if attachedPair != testServerID+":"+testPublicIPID { @@ -175,12 +188,11 @@ func TestServiceReconcile(t *testing.T) { ID: testPublicIPID, Tags: map[string]string{"cluster": "test"}, ServerID: testServerID, - SetPublicIP: func(pip *publicip.PublicIP) { - recorded = pip - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(pip *publicip.PublicIP) { + recorded = pip + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/public-ips/"+testPublicIPID) { writeJSON(t, w, map[string]any{ "id": testPublicIPID, @@ -192,7 +204,7 @@ func TestServiceReconcile(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recorded == nil || recorded.ID != testPublicIPID || recorded.IP != testPublicIPAddress { @@ -206,12 +218,11 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { var recordedID string spec := publicip.PublicIPSpec{ Tags: map[string]string{"cluster": "test"}, - SetPublicIP: func(pip *publicip.PublicIP) { - recordedID = pip.ID - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(pip *publicip.PublicIP) { + recordedID = pip.ID + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/public-ips") { writeJSON(t, w, map[string]any{"items": []any{ map[string]any{ @@ -225,7 +236,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recordedID != testPublicIPID { @@ -242,12 +253,11 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { ID: testPublicIPID, Tags: map[string]string{"cluster": "test"}, ServerID: testServerID, - SetPublicIP: func(pip *publicip.PublicIP) { - recordedID = pip.ID - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(pip *publicip.PublicIP) { + recordedID = pip.ID + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/public-ips/"+testPublicIPID): @@ -263,7 +273,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - if err := svc.Reconcile(contextWithLogCapture(&logs)); err != nil { + if _, err := svc.Reconcile(contextWithLogCapture(&logs)); err != nil { t.Fatalf("Reconcile() error = %v, want nil on conflict", err) } if recordedID != testPublicIPID { @@ -290,7 +300,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { }}) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrConflict) { t.Fatalf("Reconcile() error = %v, want ErrConflict", err) } @@ -301,7 +311,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Reconcile(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { + if _, err := svc.Reconcile(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Reconcile() error = %v, want ErrInvalidInput", err) } }) @@ -317,12 +327,11 @@ func TestServiceDelete(t *testing.T) { spec := publicip.PublicIPSpec{ ID: testPublicIPID, ServerID: testServerID, - SetPublicIP: func(pip *publicip.PublicIP) { - cleared = pip - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(pip *publicip.PublicIP) { + cleared = pip + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodDelete && strings.HasSuffix(path, "/servers/"+testServerID+"/public-ips/"+testPublicIPID): @@ -336,7 +345,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if detachedPair != testServerID+":"+testPublicIPID { @@ -359,7 +368,7 @@ func TestServiceDelete(t *testing.T) { writeJSON(t, w, map[string]any{"items": []any{}}) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v, want nil", err) } }) @@ -385,7 +394,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(contextWithLogCapture(&logs)); err != nil { + if _, err := svc.Delete(contextWithLogCapture(&logs)); err != nil { t.Fatalf("Delete() error = %v", err) } joined := strings.Join(logs, "\n") @@ -403,7 +412,7 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { + if _, err := svc.Delete(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Delete() error = %v, want ErrInvalidInput", err) } }) @@ -475,7 +484,7 @@ func TestServiceDeleteTagFallback(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if len(detachedPairs) != 2 || detachedPairs[0] != testServerID+":"+testPublicIPID || detachedPairs[1] != testServerID+":"+testOtherPublicIPID { diff --git a/cloud/services/publicip/service.go b/cloud/services/publicip/service.go index e1181b3..66a4f6d 100644 --- a/cloud/services/publicip/service.go +++ b/cloud/services/publicip/service.go @@ -25,13 +25,13 @@ type PublicIPSpec struct { Tags map[string]string ServerID string ServerSelector map[string]string - SetPublicIP func(publicIP *PublicIP) } // Scope is an interface that provides scope data needed for public IP reconciliation. type Scope interface { shared.IaaSClientScope PublicIPSpec() PublicIPSpec + SetPublicIP(publicIP *PublicIP) } // Service implements public IPs reconciler. diff --git a/cloud/services/securitygroup/reconcile.go b/cloud/services/securitygroup/reconcile.go index 325cec8..99a8c12 100644 --- a/cloud/services/securitygroup/reconcile.go +++ b/cloud/services/securitygroup/reconcile.go @@ -17,12 +17,42 @@ import ( "slices" iaas "github.com/stackitcloud/stackit-sdk-go/services/iaas/v2api" + ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" + infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) -func (s *Service) Reconcile(ctx context.Context) error { +func (s *Service) Reconcile(ctx context.Context) (ctrl.Result, error) { + if err := s.ReconcilePrimitive(ctx); err != nil { + log := logf.FromContext(ctx) + log.Error(err, "Failed to configure bastion SSH access for node", "machine", s.scope.Name()) + s.scope.Warnf( + "FailedNodeSSHAccess", + "Failed to configure bastion SSH access for server %s: %v", firstServerID(s.scope.SecurityGroupSpecs()), err, + ) + return s.scope.CloudFailureResult( + "BastionSSHAccessError", + err, + shared.RetryableErrorRequeueAfter, + true, + infrav1.MachineReadyCondition, + ) + } + return ctrl.Result{}, nil +} + +func (s *Service) Delete(ctx context.Context) (ctrl.Result, error) { + if err := s.DeletePrimitive(ctx); err != nil { + return ctrl.Result{}, err + } + return ctrl.Result{}, nil +} + +// ReconcilePrimitive reconciles the configured security groups without setting +// StackitMachine-specific conditions or events. +func (s *Service) ReconcilePrimitive(ctx context.Context) error { log := logf.FromContext(ctx) for _, spec := range s.scope.SecurityGroupSpecs() { if err := s.reconcileSecurityGroup(ctx, spec); err != nil { @@ -33,7 +63,8 @@ func (s *Service) Reconcile(ctx context.Context) error { return nil } -func (s *Service) Delete(ctx context.Context) error { +// DeletePrimitive deletes the configured security groups in reverse order. +func (s *Service) DeletePrimitive(ctx context.Context) error { log := logf.FromContext(ctx) var errs []error for _, spec := range slices.Backward(s.scope.SecurityGroupSpecs()) { @@ -48,6 +79,17 @@ func (s *Service) Delete(ctx context.Context) error { return nil } +func firstServerID(specs []SecurityGroupSpec) string { + for _, spec := range specs { + for _, id := range spec.ServerIDs { + if id != "" { + return id + } + } + } + return "" +} + // get retrieves a STACKIT security group by ID. func (s *Service) get(ctx context.Context, id string) (*SecurityGroup, error) { if id == "" { @@ -140,9 +182,7 @@ func (s *Service) reconcileSecurityGroup(ctx context.Context, spec SecurityGroup if err != nil { return err } - if spec.SetSecurityGroup != nil { - spec.SetSecurityGroup(securityGroup) - } + s.scope.SetSecurityGroup(spec.Name, securityGroup) if err := s.ensureSecurityGroupRules(ctx, securityGroup.ID, spec.Rules); err != nil { return err } @@ -171,9 +211,7 @@ func (s *Service) deleteSecurityGroup(ctx context.Context, spec SecurityGroupSpe if err != nil { return err } - if spec.SetSecurityGroup != nil { - spec.SetSecurityGroup(nil) - } + s.scope.SetSecurityGroup(spec.Name, nil) return nil } diff --git a/cloud/services/securitygroup/reconcile_test.go b/cloud/services/securitygroup/reconcile_test.go index f84b194..1a2f7e5 100644 --- a/cloud/services/securitygroup/reconcile_test.go +++ b/cloud/services/securitygroup/reconcile_test.go @@ -41,10 +41,12 @@ const ( ) type testScope struct { - projectID string - region string - iaasClient *iaas.APIClient - specs []securitygroup.SecurityGroupSpec + shared.NoOpReconcileScope + projectID string + region string + iaasClient *iaas.APIClient + specs []securitygroup.SecurityGroupSpec + setSecurityGroup func(specName string, sg *securitygroup.SecurityGroup) } func (s *testScope) ProjectID() string { @@ -63,6 +65,12 @@ func (s *testScope) SecurityGroupSpecs() []securitygroup.SecurityGroupSpec { return s.specs } +func (s *testScope) SetSecurityGroup(specName string, sg *securitygroup.SecurityGroup) { + if s.setSecurityGroup != nil { + s.setSecurityGroup(specName, sg) + } +} + func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { t.Helper() @@ -79,17 +87,29 @@ func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { return iaasClient } -func newTestService(t *testing.T, specs []securitygroup.SecurityGroupSpec, handler http.Handler) *securitygroup.Service { +func newTestServiceWithSetter( + t *testing.T, + specs []securitygroup.SecurityGroupSpec, + setSG func(specName string, sg *securitygroup.SecurityGroup), + handler http.Handler, +) *securitygroup.Service { t.Helper() return securitygroup.New(&testScope{ - projectID: testProjectID, - region: testRegion, - iaasClient: newTestIaaSClient(t, handler), - specs: specs, + projectID: testProjectID, + region: testRegion, + iaasClient: newTestIaaSClient(t, handler), + specs: specs, + setSecurityGroup: setSG, }) } +func newTestService(t *testing.T, specs []securitygroup.SecurityGroupSpec, handler http.Handler) *securitygroup.Service { + t.Helper() + + return newTestServiceWithSetter(t, specs, nil, handler) +} + func writeJSON(t *testing.T, w http.ResponseWriter, value any) { t.Helper() w.Header().Set("Content-Type", "application/json") @@ -163,7 +183,7 @@ func TestServiceReconcile(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } @@ -196,12 +216,11 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { ID: testSecurityGroupID, Name: "cluster-sg", Tags: map[string]string{"cluster": "test"}, - SetSecurityGroup: func(sg *securitygroup.SecurityGroup) { - recordedID = sg.ID - }, }} - svc := newTestService(t, specs, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, specs, func(_ string, sg *securitygroup.SecurityGroup) { + recordedID = sg.ID + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/security-groups/"+testSecurityGroupID): @@ -216,7 +235,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if recordedID != testSecurityGroupID { @@ -234,12 +253,11 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { ID: staleID, Name: "cluster-sg", Tags: map[string]string{"cluster": "test"}, - SetSecurityGroup: func(sg *securitygroup.SecurityGroup) { - recordedID = sg.ID - }, }} - svc := newTestService(t, specs, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, specs, func(_ string, sg *securitygroup.SecurityGroup) { + recordedID = sg.ID + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/security-groups/"+staleID): @@ -261,7 +279,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if !getByIDCalled { @@ -296,7 +314,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } }) @@ -314,7 +332,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { }}) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrConflict) { t.Fatalf("Reconcile() error = %v, want ErrConflict", err) } @@ -348,7 +366,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrTransient) { t.Fatalf("Reconcile() error = %v, want ErrTransient", err) } @@ -380,7 +398,7 @@ func TestServiceReconcileAttachNoOpLogging(t *testing.T) { } })) - if err := svc.Reconcile(contextWithLogCapture(&logs)); err != nil { + if _, err := svc.Reconcile(contextWithLogCapture(&logs)); err != nil { t.Fatalf("status %d: Reconcile() error = %v", status, err) } joined := strings.Join(logs, "\n") @@ -404,9 +422,6 @@ func TestServiceReconcileBastionAndNodeSSH(t *testing.T) { { Name: "cluster-bastion-ssh", Tags: map[string]string{"role": "bastion"}, - SetSecurityGroup: func(sg *securitygroup.SecurityGroup) { - bastionSGID = sg.ID - }, Rules: []securitygroup.Rule{ { Direction: securitygroup.DirectionIngress, @@ -439,7 +454,11 @@ func TestServiceReconcileBastionAndNodeSSH(t *testing.T) { }, } - svc := newTestService(t, specs, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, specs, func(specName string, sg *securitygroup.SecurityGroup) { + if specName == "cluster-bastion-ssh" && sg != nil { + bastionSGID = sg.ID + } + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/security-groups"): @@ -483,7 +502,7 @@ func TestServiceReconcileBastionAndNodeSSH(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if bastionSGID != testRemoteSGID { @@ -576,7 +595,7 @@ func TestServiceReconcileRules(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } @@ -683,7 +702,7 @@ func TestServiceReconcileValidation(t *testing.T) { t.Fatalf("unexpected request before validation failure: %s %s", r.Method, r.URL.String()) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Reconcile() error = %v, want ErrInvalidInput", err) } @@ -700,12 +719,11 @@ func TestServiceDelete(t *testing.T) { ) specs := []securitygroup.SecurityGroupSpec{{ ID: testSecurityGroupID, - SetSecurityGroup: func(sg *securitygroup.SecurityGroup) { - cleared = sg - }, }} - svc := newTestService(t, specs, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, specs, func(_ string, sg *securitygroup.SecurityGroup) { + cleared = sg + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { path := r.URL.Path switch { case r.Method == http.MethodGet && strings.HasSuffix(path, "/security-groups/"+testSecurityGroupID+"/rules"): @@ -725,7 +743,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if !slices.Equal(deletedRules, []string{testRuleID1, testRuleID2}) { @@ -779,7 +797,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if !slices.Equal(deletedRules, []string{testRuleID1, testRuleID2}) { @@ -799,7 +817,7 @@ func TestServiceDelete(t *testing.T) { writeJSON(t, w, map[string]any{"items": []any{}}) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v, want nil", err) } }) @@ -809,7 +827,7 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - err := svc.Delete(context.Background()) + _, err := svc.Delete(context.Background()) if !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Delete() error = %v, want ErrInvalidInput", err) } @@ -839,7 +857,7 @@ func TestServiceDeleteDetachNoOpLogging(t *testing.T) { } })) - if err := svc.Delete(contextWithLogCapture(&logs)); err != nil { + if _, err := svc.Delete(contextWithLogCapture(&logs)); err != nil { t.Fatalf("status %d: Delete() error = %v", status, err) } joined := strings.Join(logs, "\n") @@ -910,7 +928,7 @@ func TestServiceDeleteStaleIDFallbackAndDetach(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if !slices.Equal(detachedPairs, []string{testServerID + ":" + testSecurityGroupID}) { @@ -990,7 +1008,7 @@ func TestServiceReconcileToleratesNonCanonicalCIDR(t *testing.T) { } svc := newTestService(t, specs, newHandler(t, existing, &createdRules, &deletedRuleIDs)) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if len(createdRules) != 0 { @@ -1044,7 +1062,7 @@ func TestServiceReconcileToleratesNonCanonicalCIDR(t *testing.T) { } svc := newTestService(t, specs, newHandler(t, existing, &createdRules, &deletedRuleIDs)) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if len(createdRules) != 0 { @@ -1082,7 +1100,7 @@ func TestServiceReconcileToleratesNonCanonicalCIDR(t *testing.T) { }} svc := newTestService(t, specs, newHandler(t, []any{}, &createdRules, &deletedRuleIDs)) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if len(createdRules) != 1 || createdRules[0]["ipRange"] != canonicalCIDR { diff --git a/cloud/services/securitygroup/service.go b/cloud/services/securitygroup/service.go index 309098a..f4d0b2e 100644 --- a/cloud/services/securitygroup/service.go +++ b/cloud/services/securitygroup/service.go @@ -48,20 +48,21 @@ type Rule struct { // SecurityGroupSpec describes the desired state of a STACKIT security group and its rules. type SecurityGroupSpec struct { - ID string - Name string - Description string - Tags map[string]string - Rules []Rule - ServerIDs []string - ServerSelector map[string]string - SetSecurityGroup func(securityGroup *SecurityGroup) + ID string + Name string + Description string + Tags map[string]string + Rules []Rule + ServerIDs []string + ServerSelector map[string]string } // Scope is an interface that provides scope data needed for security group reconciliation. type Scope interface { shared.IaaSClientScope + shared.ReconcileScope SecurityGroupSpecs() []SecurityGroupSpec + SetSecurityGroup(specName string, securityGroup *SecurityGroup) } // Service implements security groups reconciler. diff --git a/cloud/services/server/reconcile.go b/cloud/services/server/reconcile.go index d890288..5d91181 100644 --- a/cloud/services/server/reconcile.go +++ b/cloud/services/server/reconcile.go @@ -14,32 +14,110 @@ import ( "context" "encoding/base64" "fmt" + "time" iaas "github.com/stackitcloud/stackit-sdk-go/services/iaas/v2api" + ctrl "sigs.k8s.io/controller-runtime" logf "sigs.k8s.io/controller-runtime/pkg/log" + infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) -func (s *Service) Reconcile(ctx context.Context) error { +func (s *Service) Reconcile(ctx context.Context) (ctrl.Result, error) { + log := logf.FromContext(ctx) + spec := s.scope.ServerSpec() + srv, created, err := s.ReconcilePrimitive(ctx) + if IsServerGone(err) { + s.scope.SetNotReady( + "InstanceNotFound", + err.Error(), + infrav1.MachineInstanceReadyCondition, + infrav1.MachineReadyCondition, + ) + s.scope.Warnf( + "InstanceNotFound", + "Server %s no longer exists; the Machine must be replaced", spec.ID, + ) + return s.scope.ServerGoneResult(err) + } + if err != nil { + log.Error(err, "Failed to create server", + "machine", s.scope.Name(), + "imageID", spec.ImageID, + "networkID", spec.NetworkID, + "region", s.scope.Region(), + ) + s.scope.Warnf( + "FailedCreateInstance", + "Failed to create server %s (imageID: %s, networkID: %s, region: %s): %v", + s.scope.Name(), spec.ImageID, spec.NetworkID, s.scope.Region(), err, + ) + return s.scope.CloudFailureResult( + "InstanceError", + err, + shared.RetryableErrorRequeueAfter, + true, + infrav1.MachineInstanceReadyCondition, + infrav1.MachineReadyCondition, + ) + } + if created { + s.scope.Eventf("InstanceCreated", "Created instance %s", srv.ID) + } + + if ready, reason, message, warn := StateCondition(srv.State, srv.PowerStatus); !ready { + previousReason := "" + if previous := s.scope.FindCondition(infrav1.MachineInstanceReadyCondition); previous != nil { + previousReason = previous.Reason + } + s.scope.SetNotReady(reason, message, infrav1.MachineInstanceReadyCondition, infrav1.MachineReadyCondition) + // Only warn on entering the state, not on every requeue. + if warn && previousReason != reason { + s.scope.Warnf(reason, "Server %s: %s", srv.ID, message) + } + return ctrl.Result{RequeueAfter: 15 * time.Second}, nil + } + + return ctrl.Result{}, nil +} + +func (s *Service) Delete(ctx context.Context) (ctrl.Result, error) { + log := logf.FromContext(ctx) + instanceID := s.scope.ServerSpec().ID + if err := s.DeletePrimitive(ctx); err != nil { + log.Error(err, "Failed to delete server", "machine", s.scope.Name(), "instanceID", instanceID) + s.scope.Warnf("FailedDeleteInstance", + "Failed to delete server %s: %v", instanceID, err) + return ctrl.Result{}, err + } + if instanceID != "" { + s.scope.Eventf("InstanceDeleted", "Deleted instance %s", instanceID) + } + return ctrl.Result{}, nil +} + +// ReconcilePrimitive reconciles the server and updates the scope without setting +// StackitMachine-specific conditions or events. +func (s *Service) ReconcilePrimitive(ctx context.Context) (*Server, bool, error) { log := logf.FromContext(ctx) spec := s.scope.ServerSpec() if err := spec.validate(); err != nil { - return err + return nil, false, err } srv, created, err := s.ensureServer(ctx, spec) if err != nil { - return err - } - if spec.SetServer != nil { - spec.SetServer(srv, created) + return nil, false, err } + s.scope.SetServer(srv, created) log.V(1).Info("Reconciled server resources", "serverID", srv.ID, "created", created) - return nil + return srv, created, nil } -func (s *Service) Delete(ctx context.Context) error { +// DeletePrimitive deletes the server matching ServerSpec without emitting +// StackitMachine-specific events. +func (s *Service) DeletePrimitive(ctx context.Context) error { log := logf.FromContext(ctx) spec := s.scope.ServerSpec() if spec.ID == "" && len(spec.Tags) == 0 { @@ -55,9 +133,7 @@ func (s *Service) Delete(ctx context.Context) error { if err != nil { return err } - if spec.SetServer != nil { - spec.SetServer(nil, false) - } + s.scope.SetServer(nil, false) return nil } diff --git a/cloud/services/server/reconcile_test.go b/cloud/services/server/reconcile_test.go index d8a4d7e..6f5b21a 100644 --- a/cloud/services/server/reconcile_test.go +++ b/cloud/services/server/reconcile_test.go @@ -39,10 +39,12 @@ const ( ) type testScope struct { + shared.NoOpReconcileScope projectID string region string iaasClient *iaas.APIClient spec server.ServerSpec + setServer func(srv *server.Server, created bool) } func (s *testScope) ProjectID() string { @@ -61,6 +63,12 @@ func (s *testScope) ServerSpec() server.ServerSpec { return s.spec } +func (s *testScope) SetServer(srv *server.Server, created bool) { + if s.setServer != nil { + s.setServer(srv, created) + } +} + func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { t.Helper() @@ -77,7 +85,12 @@ func newTestIaaSClient(t *testing.T, handler http.Handler) *iaas.APIClient { return iaasClient } -func newTestService(t *testing.T, spec server.ServerSpec, handler http.Handler) *server.Service { +func newTestServiceWithSetter( + t *testing.T, + spec server.ServerSpec, + setServer func(*server.Server, bool), + handler http.Handler, +) *server.Service { t.Helper() return server.New(&testScope{ @@ -85,9 +98,16 @@ func newTestService(t *testing.T, spec server.ServerSpec, handler http.Handler) region: testRegion, iaasClient: newTestIaaSClient(t, handler), spec: spec, + setServer: setServer, }) } +func newTestService(t *testing.T, spec server.ServerSpec, handler http.Handler) *server.Service { + t.Helper() + + return newTestServiceWithSetter(t, spec, nil, handler) +} + func writeJSON(t *testing.T, w http.ResponseWriter, value any) { t.Helper() w.Header().Set("Content-Type", "application/json") @@ -189,13 +209,12 @@ func TestServiceReconcile(t *testing.T) { DeleteOnTermination: true, }, Tags: map[string]string{"cluster": "test"}, - SetServer: func(srv *server.Server, created bool) { - recordedServer = srv - wasCreated = created - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(srv *server.Server, created bool) { + recordedServer = srv + wasCreated = created + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers"): if got := r.URL.Query().Get("label_selector"); got != "cluster=test" { @@ -225,7 +244,7 @@ func TestServiceReconcile(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if !wasCreated { @@ -288,7 +307,7 @@ func TestServiceReconcile(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } assertStringField(t, createPayload, "imageId", testImageID) @@ -304,12 +323,11 @@ func TestServiceReconcile(t *testing.T) { ImageID: testImageID, NetworkID: testNetworkID, Tags: map[string]string{"cluster": "test"}, - SetServer: func(srv *server.Server, _ bool) { - recordedServer = srv - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(srv *server.Server, _ bool) { + recordedServer = srv + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers/"+testServerID): writeJSON(t, w, map[string]any{ @@ -329,7 +347,7 @@ func TestServiceReconcile(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } wantAddresses := []server.Address{ @@ -354,13 +372,12 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { ImageID: testImageID, NetworkID: testNetworkID, Tags: map[string]string{"cluster": "test"}, - SetServer: func(srv *server.Server, created bool) { - recordedServer = srv - wasCreated = created - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(srv *server.Server, created bool) { + recordedServer = srv + wasCreated = created + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers/"+testServerID): writeJSON(t, w, map[string]any{ @@ -376,7 +393,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if wasCreated { @@ -398,13 +415,12 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { ImageID: testImageID, NetworkID: testNetworkID, Tags: map[string]string{"cluster": "test"}, - SetServer: func(srv *server.Server, created bool) { - recordedServer = srv - wasCreated = created - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(srv *server.Server, created bool) { + recordedServer = srv + wasCreated = created + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch { case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/servers"): writeJSON(t, w, map[string]any{"items": []any{ @@ -423,7 +439,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - if err := svc.Reconcile(context.Background()); err != nil { + if _, err := svc.Reconcile(context.Background()); err != nil { t.Fatalf("Reconcile() error = %v", err) } if wasCreated { @@ -457,7 +473,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { } })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !server.IsServerGone(err) { t.Fatalf("Reconcile() error = %v, want ErrServerGone", err) } @@ -483,7 +499,7 @@ func TestServiceReconcileReuseAndErrors(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrConflict) { t.Fatalf("Reconcile() error = %v, want ErrConflict", err) } @@ -559,7 +575,7 @@ func TestServiceReconcileValidation(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - err := svc.Reconcile(context.Background()) + _, err := svc.Reconcile(context.Background()) if !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Reconcile() error = %v, want ErrInvalidInput", err) } @@ -577,14 +593,13 @@ func TestServiceDelete(t *testing.T) { ) spec := server.ServerSpec{ ID: testServerID, - SetServer: func(srv *server.Server, created bool) { - setServerCalls++ - clearedServer = srv - clearedCreated = created - }, } - svc := newTestService(t, spec, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + svc := newTestServiceWithSetter(t, spec, func(srv *server.Server, created bool) { + setServerCalls++ + clearedServer = srv + clearedCreated = created + }, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodDelete && strings.HasSuffix(r.URL.Path, "/servers/"+testServerID) { deletedID = testServerID w.WriteHeader(http.StatusNoContent) @@ -593,7 +608,7 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if deletedID != testServerID { @@ -632,7 +647,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if len(deletedIDs) != 2 || deletedIDs[0] != testServerID || deletedIDs[1] != testOtherServerID { @@ -664,7 +679,7 @@ func TestServiceDelete(t *testing.T) { } })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v", err) } if deletedID != testServerID { @@ -681,7 +696,7 @@ func TestServiceDelete(t *testing.T) { writeJSON(t, w, map[string]any{"items": []any{}}) })) - if err := svc.Delete(context.Background()); err != nil { + if _, err := svc.Delete(context.Background()); err != nil { t.Fatalf("Delete() error = %v, want nil", err) } }) @@ -691,7 +706,7 @@ func TestServiceDelete(t *testing.T) { t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String()) })) - if err := svc.Delete(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { + if _, err := svc.Delete(context.Background()); !errors.Is(err, shared.ErrInvalidInput) { t.Fatalf("Delete() error = %v, want ErrInvalidInput", err) } }) diff --git a/cloud/services/server/service.go b/cloud/services/server/service.go index 5c2e184..0353594 100644 --- a/cloud/services/server/service.go +++ b/cloud/services/server/service.go @@ -13,6 +13,8 @@ package server import ( "errors" + ctrl "sigs.k8s.io/controller-runtime" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/shared" ) @@ -71,13 +73,15 @@ type ServerSpec struct { Tags map[string]string RootVolume RootVolume DisallowRecreate bool - SetServer func(server *Server, created bool) } // Scope is an interface that provides scope data needed for server reconciliation. type Scope interface { shared.IaaSClientScope + shared.ReconcileScope ServerSpec() ServerSpec + SetServer(server *Server, created bool) + ServerGoneResult(err error) (ctrl.Result, error) } // Service implements server reconciler. diff --git a/cloud/services/shared/utils.go b/cloud/services/shared/utils.go index 79e0464..1d9f7e1 100644 --- a/cloud/services/shared/utils.go +++ b/cloud/services/shared/utils.go @@ -16,10 +16,21 @@ import ( "fmt" "net/http" "strings" + "time" "github.com/stackitcloud/stackit-sdk-go/core/oapierror" iaas "github.com/stackitcloud/stackit-sdk-go/services/iaas/v2api" lb "github.com/stackitcloud/stackit-sdk-go/services/loadbalancer/v2api" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + ctrl "sigs.k8s.io/controller-runtime" +) + +const ( + // RetryableErrorRequeueAfter paces retries of transient or conflicting cloud API operations. + RetryableErrorRequeueAfter = 5 * time.Second + + // DeleteRequeueAfter paces the wait for dependent resources to disappear during deletion. + DeleteRequeueAfter = 5 * time.Second ) // IaaSClientScope is an interface that provides the IaaS client and target scope for IaaS operations. @@ -36,6 +47,47 @@ type LoadBalancerClientScope interface { LoadBalancerClient() *lb.APIClient } +// ReconcileScope provides condition, event, and failure result helpers for cloud resource reconcilers. +type ReconcileScope interface { + Name() string + SetConditions(status metav1.ConditionStatus, reason, message string, conditionTypes ...string) + SetNotReady(reason, message string, conditionTypes ...string) + CloudFailureResult(reason string, err error, requeueAfter time.Duration, returnError bool, conditionTypes ...string) (ctrl.Result, error) + FindCondition(conditionType string) *metav1.Condition + Event(reason, message string) + Eventf(reason, messageFmt string, args ...any) + Warn(reason, message string) + Warnf(reason, messageFmt string, args ...any) +} + +// NoOpReconcileScope provides default no-op implementations of ReconcileScope +// for headless callers (such as tag cleanup) and service unit tests. +type NoOpReconcileScope struct{} + +func (NoOpReconcileScope) Name() string { return "" } + +func (NoOpReconcileScope) SetConditions(_ metav1.ConditionStatus, _, _ string, _ ...string) {} + +func (NoOpReconcileScope) SetNotReady(_, _ string, _ ...string) {} + +func (NoOpReconcileScope) CloudFailureResult(_ string, err error, _ time.Duration, _ bool, _ ...string) (ctrl.Result, error) { + return ctrl.Result{}, err +} + +func (NoOpReconcileScope) FindCondition(_ string) *metav1.Condition { return nil } + +func (NoOpReconcileScope) Event(_, _ string) {} + +func (NoOpReconcileScope) Eventf(_, _ string, _ ...any) {} + +func (NoOpReconcileScope) Warn(_, _ string) {} + +func (NoOpReconcileScope) Warnf(_, _ string, _ ...any) {} + +func (NoOpReconcileScope) ServerGoneResult(err error) (ctrl.Result, error) { + return ctrl.Result{}, err +} + // ListByTags validates that tags are non-empty, lists SDK items using the tag label selector, // filters items whose labels contain all tags, and maps each matching item via convert. func ListByTags[T any, Out any]( diff --git a/cmd/cleanup-stackit/main.go b/cmd/cleanup-stackit/main.go index 579ff62..fd2a0ad 100644 --- a/cmd/cleanup-stackit/main.go +++ b/cmd/cleanup-stackit/main.go @@ -49,7 +49,7 @@ func run(ctx context.Context) error { return err } - client, err := cloud.NewClient(ctx, cloud.Credentials{ + client, err := cloud.NewClient(cloud.Credentials{ ProjectID: projectID, Region: region, ServiceAccountJSON: serviceAccountJSON, diff --git a/controller/constants.go b/controller/constants.go index 3a2b1ce..610431e 100644 --- a/controller/constants.go +++ b/controller/constants.go @@ -13,8 +13,6 @@ package controller import "time" const ( - cloudInitRefKindSecret = "Secret" - retryableErrorRequeueAfter = 5 * time.Second // deleteRequeueAfter paces the wait for dependent objects to disappear during deletion. diff --git a/controller/controller_test_helpers_test.go b/controller/controller_test_helpers_test.go index 8407de9..f2fa686 100644 --- a/controller/controller_test_helpers_test.go +++ b/controller/controller_test_helpers_test.go @@ -23,9 +23,14 @@ import ( clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/bastion" "github.com/stackitcloud/cluster-api-provider-stackit/scope" ) +func bastionCloudInitHash(cloudInit []byte) string { + return bastion.CloudInitHash(cloudInit) +} + const ( testProjectID = "11111111-1111-1111-1111-111111111111" testNetworkID = "22222222-2222-2222-2222-222222222222" diff --git a/controller/stackitcluster_bastion.go b/controller/stackitcluster_bastion.go deleted file mode 100644 index 42de08a..0000000 --- a/controller/stackitcluster_bastion.go +++ /dev/null @@ -1,211 +0,0 @@ -/* -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 -*/ - -package controller - -import ( - "context" - "crypto/sha256" - "fmt" - "time" - - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/types" - "sigs.k8s.io/cluster-api/util/record" - ctrl "sigs.k8s.io/controller-runtime" - logf "sigs.k8s.io/controller-runtime/pkg/log" - - infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" - "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/publicip" - "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/scope" -) - -// bastionDisabledReason is read back to decide whether the cleanup below -// already ran, so it must not drift. -const bastionDisabledReason = "Skipped" - -func (r *StackitClusterReconciler) reconcileBastion( - ctx context.Context, - clusterScope *scope.ClusterScope, -) (ctrl.Result, bool, error) { - log := logf.FromContext(ctx) - stackitCluster := clusterScope.StackitCluster - - if !stackitCluster.Spec.Bastion.Enabled { - // The reason is set only after a cleanup has succeeded, so anything else - // means bastion resources may still exist. Keying on it rather than on - // the status keeps the tag-based cleanup to once per cluster. - condition := meta.FindStatusCondition(stackitCluster.Status.Conditions, infrav1.ClusterBastionReadyCondition) - if condition == nil || condition.Reason != bastionDisabledReason { - if err := deleteBastion(ctx, clusterScope); err != nil { - return ctrl.Result{}, false, err - } - } - clusterScope.SetConditions( - metav1.ConditionTrue, - bastionDisabledReason, - "bastion disabled", - infrav1.ClusterBastionReadyCondition, - ) - return ctrl.Result{}, true, nil - } - - cloudInit, err := r.resolveBastionCloudInit(ctx, stackitCluster) - if err != nil { - log.Error(err, "Failed to resolve bastion cloud-init", "cluster", stackitCluster.Name) - record.Warnf(stackitCluster, "CloudInitRefError", "Failed to resolve bastion cloudInitRef: %v", err) - clusterScope.SetNotReady( - "CloudInitRefError", - err.Error(), - infrav1.ClusterBastionReadyCondition, - infrav1.ClusterReadyCondition, - ) - return ctrl.Result{}, false, nil - } - clusterScope.SetBastionCloudInit(cloudInit, bastionCloudInitHash(cloudInit)) - - if bastionNeedsRecreate(stackitCluster, cloudInit) { - if err := server.New(clusterScope).Delete(ctx); err != nil { - return ctrl.Result{}, false, err - } - clusterScope.SetNotReady( - "Recreating", - "recreating bastion because cloudInitRef content changed", - infrav1.ClusterBastionReadyCondition, - infrav1.ClusterReadyCondition, - ) - record.Event( - stackitCluster, "BastionRecreating", - "Recreating bastion because cloudInitRef content changed", - ) - return ctrl.Result{RequeueAfter: retryableErrorRequeueAfter}, false, nil - } - - if err := server.New(clusterScope).Reconcile(ctx); err != nil { - return ctrl.Result{}, false, err - } - if clusterScope.BastionServerCreated() { - record.Eventf( - stackitCluster, "BastionCreated", "Created bastion %s", stackitCluster.Status.Bastion.ServerID, - ) - } - if err := securitygroup.New(clusterScope).Reconcile(ctx); err != nil { - return ctrl.Result{}, false, err - } - if err := publicip.New(clusterScope).Reconcile(ctx); err != nil { - return ctrl.Result{}, false, err - } - state, powerStatus := clusterScope.BastionServerState() - if ready, reason, message, warn := server.StateCondition(state, powerStatus); !ready { - previousReason := "" - if previous := meta.FindStatusCondition(stackitCluster.Status.Conditions, infrav1.ClusterBastionReadyCondition); previous != nil { - previousReason = previous.Reason - } - clusterScope.SetNotReady(reason, "bastion "+message, infrav1.ClusterBastionReadyCondition, infrav1.ClusterReadyCondition) - // Only warn on entering the state, not on every requeue. - if warn && previousReason != reason { - record.Warnf(stackitCluster, reason, "Bastion server %s: %s", stackitCluster.Status.Bastion.ServerID, message) - } - return ctrl.Result{RequeueAfter: 15 * time.Second}, false, nil - } - if stackitCluster.Status.Bastion.PublicIP == "" { - clusterScope.SetNotReady( - "Provisioning", - "waiting for bastion public IP address", - infrav1.ClusterBastionReadyCondition, - infrav1.ClusterReadyCondition, - ) - return ctrl.Result{RequeueAfter: 10 * time.Second}, false, nil - } - clusterScope.SetConditions( - metav1.ConditionTrue, - "Available", - "", - infrav1.ClusterBastionReadyCondition, - ) - return ctrl.Result{}, true, nil -} - -func deleteBastion( - ctx context.Context, - clusterScope *scope.ClusterScope, -) error { - hadBastion := clusterScope.HasBastionStatus() - if err := publicip.New(clusterScope).Delete(ctx); err != nil { - return err - } - if err := server.New(clusterScope).Delete(ctx); err != nil { - return err - } - if hadBastion { - record.Event(clusterScope.StackitCluster, "BastionDeleted", "Deleted bastion") - } - if err := securitygroup.New(clusterScope).Delete(ctx); err != nil { - return err - } - return nil -} - -func bastionNeedsRecreate(stackitCluster *infrav1.StackitCluster, cloudInit []byte) bool { - if stackitCluster.Status.Bastion.ServerID == "" { - return false - } - return stackitCluster.Status.Bastion.CloudInitHash != bastionCloudInitHash(cloudInit) -} - -func bastionCloudInitHash(cloudInit []byte) string { - if len(cloudInit) == 0 { - return "" - } - return fmt.Sprintf("%x", sha256.Sum256(cloudInit)) -} - -func (r *StackitClusterReconciler) resolveBastionCloudInit(ctx context.Context, stackitCluster *infrav1.StackitCluster) ([]byte, error) { - ref := stackitCluster.Spec.Bastion.CloudInitRef - if ref == nil { - return nil, nil - } - key := types.NamespacedName{Namespace: stackitCluster.Namespace, Name: ref.Name} - switch ref.Kind { - case "ConfigMap": - configMap := &corev1.ConfigMap{} - if err := r.Get(ctx, key, configMap); err != nil { - if apierrors.IsNotFound(err) { - return nil, fmt.Errorf("bastion.cloudInitRef ConfigMap %s not found", key) - } - return nil, err - } - value, ok := configMap.Data[ref.Key] - if !ok { - return nil, fmt.Errorf("bastion.cloudInitRef key %q not found in ConfigMap %s", ref.Key, key) - } - return []byte(value), nil - case cloudInitRefKindSecret: - secret := &corev1.Secret{} - if err := r.Get(ctx, key, secret); err != nil { - if apierrors.IsNotFound(err) { - return nil, fmt.Errorf("bastion.cloudInitRef Secret %s not found", key) - } - return nil, err - } - value, ok := secret.Data[ref.Key] - if !ok { - return nil, fmt.Errorf("bastion.cloudInitRef key %q not found in Secret %s", ref.Key, key) - } - return append([]byte(nil), value...), nil - default: - return nil, fmt.Errorf("bastion.cloudInitRef.kind must be ConfigMap or Secret") - } -} diff --git a/controller/stackitcluster_controller.go b/controller/stackitcluster_controller.go index 5db54df..7f7068e 100644 --- a/controller/stackitcluster_controller.go +++ b/controller/stackitcluster_controller.go @@ -22,11 +22,9 @@ import ( "fmt" "maps" "slices" - "time" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -47,9 +45,9 @@ import ( infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud" "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/availabilityzone" + "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/bastion" "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/scope" "github.com/stackitcloud/cluster-api-provider-stackit/util" ) @@ -248,202 +246,17 @@ func (r *StackitClusterReconciler) reconcileNormal(ctx context.Context, clusterS infrav1.ClusterCredentialsReadyCondition, ) - if err := availabilityzone.New(clusterScope).Reconcile(ctx); err != nil { - return clusterScope.CloudFailureResult( - "AvailabilityZonesError", - err, - retryableErrorRequeueAfter, - true, - infrav1.ClusterReadyCondition, - ) + reconcilers := []cloud.Reconciler{ + availabilityzone.New(clusterScope), + network.New(clusterScope), + loadbalancer.New(clusterScope), + bastion.New(clusterScope), } - - if err := network.New(clusterScope).Reconcile(ctx); err != nil { - if stackitCluster.Spec.Network.ID != "" { - log.Error(err, "Failed to get network", - "networkID", stackitCluster.Spec.Network.ID, - "region", stackitCluster.Spec.Region, - ) - record.Warnf( - stackitCluster, "FailedGetNetwork", - "Failed to get network %s in region %s: %v", - stackitCluster.Spec.Network.ID, stackitCluster.Spec.Region, err, - ) - return clusterScope.CloudFailureResult( - "NetworkNotFound", - err, - retryableErrorRequeueAfter, - false, - infrav1.ClusterNetworkReadyCondition, - infrav1.ClusterReadyCondition, - ) - } - log.Error(err, "Failed to reconcile managed network", - "cluster", stackitCluster.Name, - "region", stackitCluster.Spec.Region, - ) - record.Warnf( - stackitCluster, "FailedCreateNetwork", - "Failed to reconcile managed network in region %s: %v", - stackitCluster.Spec.Region, err, - ) - return clusterScope.CloudFailureResult( - "NetworkCreateError", - err, - retryableErrorRequeueAfter, - false, - infrav1.ClusterNetworkReadyCondition, - infrav1.ClusterReadyCondition, - ) - } - if clusterScope.NetworkCreated() { - record.Eventf(stackitCluster, "NetworkCreated", "Created managed network %s", stackitCluster.Status.Network.ID) - } - clusterScope.SetConditions( - metav1.ConditionTrue, - "Available", - "", - infrav1.ClusterNetworkReadyCondition, - ) - - if stackitCluster.Spec.APIServerLoadBalancer.Enabled { - // STACKIT takes an explicit target list rather than label-based - // membership, so exactly one reconciler owns the pool. Machines being - // deleted drop out here, before the node is drained. - machines, err := collections.GetFilteredMachinesForCluster( - ctx, - r.Client, - clusterScope.Cluster, - collections.ControlPlaneMachines(clusterScope.Cluster.Name), - collections.ActiveMachines, - ) - if err != nil { - clusterScope.SetConditions( - metav1.ConditionFalse, - "MachineListError", - err.Error(), - infrav1.ClusterLoadBalancerReadyCondition, - ) - return ctrl.Result{}, fmt.Errorf("list control plane machines: %w", err) - } - targets := loadbalancer.APIServerTargets(machines.UnsortedList()) - - // Seeding with the real targets lets a load balancer deleted out of band - // come back with the control plane behind it. - seed := targets - if len(seed) == 0 { - seed = []loadbalancer.Target{loadbalancer.BootstrapTarget(clusterScope.BootstrapTargetIP())} - } - clusterScope.SetAPIServerLoadBalancerTargets(targets, seed) - - previousEndpointHost := stackitCluster.Status.APIServerEndpoint.Host - wasLBReady := meta.IsStatusConditionTrue(stackitCluster.Status.Conditions, infrav1.ClusterLoadBalancerReadyCondition) - - err = loadbalancer.New(clusterScope).Reconcile(ctx) - if clusterScope.APIServerLoadBalancerCreated() { - record.Eventf( - stackitCluster, "LoadBalancerCreated", - "Created API server load balancer %s", stackitCluster.Status.APIServerLoadBalancerID, - ) - } - if loadbalancer.IsTargetPoolUpdateError(err) { - if !shared.IsRetryable(err) { - record.Warnf( - stackitCluster, "LoadBalancerTargetError", - "Cannot update API server load balancer target pool: %v", err, - ) - } - // Scoped to the load balancer condition: failing the cluster would - // stop the machine reconciler from replacing the broken machine. - clusterScope.SetConditions( - metav1.ConditionFalse, - "LoadBalancerTargetError", - err.Error(), - infrav1.ClusterLoadBalancerReadyCondition, - ) - // Requeue even on a permanent error: this return skips SetReady, so - // no machine exists yet whose events could retry it. - return ctrl.Result{RequeueAfter: retryableErrorRequeueAfter}, nil + for _, s := range reconcilers { + res, err := s.Reconcile(ctx) + if err != nil || !res.IsZero() || clusterScope.NotReady() { + return res, err } - if err != nil { - log.Error(err, "Failed to create API server load balancer", - "cluster", stackitCluster.Name, - "region", stackitCluster.Spec.Region, - ) - record.Warnf( - stackitCluster, "FailedCreateLoadBalancer", - "Failed to create API server load balancer: %v", err, - ) - return clusterScope.CloudFailureResult( - "LoadBalancerError", - err, - retryableErrorRequeueAfter, - false, - infrav1.ClusterLoadBalancerReadyCondition, - infrav1.ClusterReadyCondition, - ) - } - if stackitCluster.Status.APIServerEndpoint.Host == "" { - clusterScope.SetNotReady( - "Provisioning", - "waiting for API server load balancer IP address", - infrav1.ClusterLoadBalancerReadyCondition, - infrav1.ClusterReadyCondition, - ) - return ctrl.Result{RequeueAfter: 10 * time.Second}, nil - } - - isLBReady := wasLBReady && previousEndpointHost == stackitCluster.Status.APIServerEndpoint.Host - if !isLBReady { - clusterScope.SetConditions( - metav1.ConditionTrue, - "Available", - "", - infrav1.ClusterLoadBalancerReadyCondition, - ) - record.Eventf( - stackitCluster, "LoadBalancerReady", - "API server load balancer is ready at %s", stackitCluster.Status.APIServerEndpoint.Host, - ) - } - } else if stackitCluster.Spec.ControlPlaneEndpoint.Host != "" { - stackitCluster.Status.APIServerEndpoint = stackitCluster.Spec.ControlPlaneEndpoint - clusterScope.SetConditions( - metav1.ConditionTrue, - "Skipped", - "external endpoint provided", - infrav1.ClusterLoadBalancerReadyCondition, - ) - } else { - log.Error(errors.New("controlPlaneEndpoint host is empty"), "API server load balancer is disabled and controlPlaneEndpoint is empty", "cluster", stackitCluster.Name) - record.Warn(stackitCluster, "EndpointMissing", "apiServerLoadBalancer.enabled is false and controlPlaneEndpoint is empty") - clusterScope.SetNotReady( - "EndpointMissing", - "apiServerLoadBalancer.enabled is false and controlPlaneEndpoint is empty", - infrav1.ClusterLoadBalancerReadyCondition, - infrav1.ClusterReadyCondition, - ) - return ctrl.Result{}, nil - } - - if result, ready, err := r.reconcileBastion(ctx, clusterScope); err != nil { - log.Error(err, "Failed to reconcile bastion", - "cluster", stackitCluster.Name, - ) - record.Warnf( - stackitCluster, "FailedCreateBastion", - "Failed to reconcile bastion: %v", err, - ) - return clusterScope.CloudFailureResult( - "BastionError", - err, - retryableErrorRequeueAfter, - false, - infrav1.ClusterBastionReadyCondition, - infrav1.ClusterReadyCondition, - ) - } else if !ready { - return result, nil } clusterScope.SetReady() @@ -500,53 +313,19 @@ func (r *StackitClusterReconciler) reconcileDelete(ctx context.Context, clusterS ) } clusterScope.SetCloudClient(cloudClient) - loadBalancerID := stackitCluster.Status.APIServerLoadBalancerID - if err := loadbalancer.New(clusterScope).Delete(ctx); err != nil { - log.Error(err, "Failed to delete API server load balancer", "cluster", stackitCluster.Name, "loadBalancerID", loadBalancerID) - record.Warnf(stackitCluster, "FailedDeleteLoadBalancer", - "Failed to delete API server load balancer %s: %v", loadBalancerID, err) - return ctrl.Result{}, err - } - if loadBalancerID != "" { - record.Eventf( - stackitCluster, "LoadBalancerDeleted", - "Deleted API server load balancer %s", loadBalancerID, - ) - } - if err := deleteBastion(ctx, clusterScope); err != nil { - log.Error(err, "Failed to delete bastion", "cluster", stackitCluster.Name) - record.Warnf(stackitCluster, "FailedDeleteBastion", - "Failed to delete bastion: %v", err) - return ctrl.Result{}, err + + reconcilers := []cloud.Reconciler{ + loadbalancer.New(clusterScope), + bastion.New(clusterScope), + network.New(clusterScope), } - networkID := stackitCluster.Status.Network.ID - if err := network.New(clusterScope).Delete(ctx); err != nil { - if shared.IsConflict(err) { - log.Info("Managed network still has resources attached; requeueing deletion", - "cluster", stackitCluster.Name, - "networkID", networkID, - ) - clusterScope.SetConditions( - metav1.ConditionFalse, - "NetworkInUse", - err.Error(), - infrav1.ClusterNetworkReadyCondition, - ) - record.Warnf(stackitCluster, "NetworkInUse", - "Managed network %s still has active resources attached; retrying deletion: %v", networkID, err) - return ctrl.Result{RequeueAfter: deleteRequeueAfter}, nil + for _, s := range reconcilers { + res, err := s.Delete(ctx) + if err != nil || !res.IsZero() { + return res, err } - log.Error(err, "Failed to delete managed network", - "cluster", stackitCluster.Name, - "networkID", networkID, - ) - record.Warnf(stackitCluster, "FailedDeleteNetwork", - "Failed to delete managed network %s: %v", networkID, err) - return ctrl.Result{}, err - } - if networkID != "" && stackitCluster.Spec.Network.ID == "" { - record.Eventf(stackitCluster, "NetworkDeleted", "Deleted managed network %s", networkID) } + controllerutil.RemoveFinalizer(stackitCluster, infrav1.ClusterFinalizer) return ctrl.Result{}, nil } diff --git a/controller/stackitcluster_controller_test.go b/controller/stackitcluster_controller_test.go index 26a533c..2672093 100644 --- a/controller/stackitcluster_controller_test.go +++ b/controller/stackitcluster_controller_test.go @@ -59,7 +59,7 @@ var _ = Describe("StackitCluster Controller", func() { reconciler = &StackitClusterReconciler{ Client: k8sClient, Scheme: k8sClient.Scheme(), - CloudClientFactory: func(context.Context, cloud.Credentials) (cloud.Client, error) { + CloudClientFactory: func(cloud.Credentials) (cloud.Client, error) { return fakeCloud, nil }, } @@ -316,7 +316,9 @@ var _ = Describe("StackitCluster Controller", func() { ) Expect(err).NotTo(HaveOccurred()) machineScope.SetCloudClient(fakeCloud) - Expect(server.New(machineScope).Reconcile(ctx)).To(Succeed()) + serverRes, err := server.New(machineScope).Reconcile(ctx) + Expect(err).NotTo(HaveOccurred()) + Expect(serverRes).To(Equal(reconcile.Result{})) workerServerID := stackitMachine.Status.InstanceID Expect(fakeCloud.ServerHasSecurityGroup(workerServerID, nodeSG.ID)).To(BeTrue()) @@ -446,7 +448,7 @@ var _ = Describe("StackitCluster Controller", func() { Expect(k8sClient.Get(ctx, stackitKey, got)).To(Succeed()) Expect(k8sClient.Delete(ctx, got)).To(Succeed()) - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { return nil, fmt.Errorf("authenticate: %w", shared.ErrUnauthorized) } @@ -460,7 +462,7 @@ var _ = Describe("StackitCluster Controller", func() { expectCondition(got.Status.Conditions, infrav1.ClusterCredentialsReadyCondition, metav1.ConditionFalse, "CredentialsInvalid") By("correcting the credentials so deletion succeeds") - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { return fakeCloud, nil } @@ -633,7 +635,9 @@ var _ = Describe("StackitCluster Controller", func() { ) Expect(err).NotTo(HaveOccurred()) machineScope.SetCloudClient(fakeCloud) - Expect(server.New(machineScope).Reconcile(ctx)).To(Succeed()) + serverRes, err := server.New(machineScope).Reconcile(ctx) + Expect(err).NotTo(HaveOccurred()) + Expect(serverRes).To(Equal(reconcile.Result{})) workerServerID := stackitMachine.Status.InstanceID Expect(fakeCloud.ServerHasSecurityGroup(workerServerID, nodeSG.ID)).To(BeTrue()) @@ -774,7 +778,7 @@ var _ = Describe("StackitCluster Controller", func() { // The requeue is what lets a corrected Secret take effect: nothing else // enqueues the cluster once the credentials are rejected. It("requeues on unauthorized credentials and recovers once they are corrected", func() { - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { return nil, fmt.Errorf("authenticate: %w", shared.ErrUnauthorized) } @@ -789,7 +793,7 @@ var _ = Describe("StackitCluster Controller", func() { expectCondition(got.Status.Conditions, infrav1.ClusterReadyCondition, metav1.ConditionFalse, "CredentialsInvalid") By("correcting the credentials") - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { return fakeCloud, nil } @@ -809,7 +813,7 @@ var _ = Describe("StackitCluster Controller", func() { Expect(k8sClient.Update(ctx, cluster)).To(Succeed()) cloudClientFactoryCalls := 0 - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { cloudClientFactoryCalls++ return fakeCloud, nil } @@ -832,7 +836,7 @@ var _ = Describe("StackitCluster Controller", func() { Expect(k8sClient.Update(ctx, got)).To(Succeed()) cloudClientFactoryCalls := 0 - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { cloudClientFactoryCalls++ return fakeCloud, nil } diff --git a/controller/stackitmachine_controller.go b/controller/stackitmachine_controller.go index b8b5de4..5608b33 100644 --- a/controller/stackitmachine_controller.go +++ b/controller/stackitmachine_controller.go @@ -20,11 +20,9 @@ import ( "context" "errors" "fmt" - "time" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" - "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" @@ -194,74 +192,15 @@ func (r *StackitMachineReconciler) reconcileNormal(ctx context.Context, machineS machineScope.SetConditions(metav1.ConditionTrue, "Available", "", infrav1.MachineCredentialsReadyCondition) machineScope.SetBootstrapData(bootstrapData) - err = server.New(machineScope).Reconcile(ctx) - if server.IsServerGone(err) { - machineScope.SetNotReady( - "InstanceNotFound", - err.Error(), - infrav1.MachineInstanceReadyCondition, - infrav1.MachineReadyCondition, - ) - record.Warnf( - stackitMachine, "InstanceNotFound", - "Server %s no longer exists; the Machine must be replaced", stackitMachine.Status.InstanceID, - ) - return ctrl.Result{}, nil - } - if err != nil { - log.Error(err, "Failed to create server", - "machine", stackitMachine.Name, - "imageID", stackitMachine.Spec.ImageID, - "networkID", machineScope.NetworkID(), - "region", machineScope.StackitCluster.Spec.Region, - ) - record.Warnf( - stackitMachine, "FailedCreateInstance", - "Failed to create server %s (imageID: %s, networkID: %s, region: %s): %v", - stackitMachine.Name, stackitMachine.Spec.ImageID, machineScope.NetworkID(), - machineScope.StackitCluster.Spec.Region, err, - ) - return machineScope.CloudFailureResult( - "InstanceError", - err, - retryableErrorRequeueAfter, - true, - infrav1.MachineInstanceReadyCondition, - infrav1.MachineReadyCondition, - ) - } - if machineScope.InstanceCreated() { - record.Eventf( - stackitMachine, "InstanceCreated", "Created instance %s", stackitMachine.Status.InstanceID, - ) - } - - if ready, reason, message, warn := server.StateCondition(stackitMachine.Status.InstanceState, machineScope.InstancePowerStatus()); !ready { - previousReason := "" - if previous := meta.FindStatusCondition(stackitMachine.Status.Conditions, infrav1.MachineInstanceReadyCondition); previous != nil { - previousReason = previous.Reason - } - machineScope.SetNotReady(reason, message, infrav1.MachineInstanceReadyCondition, infrav1.MachineReadyCondition) - // Only warn on entering the state, not on every requeue. - if warn && previousReason != reason { - record.Warnf(stackitMachine, reason, "Server %s: %s", stackitMachine.Status.InstanceID, message) + reconcilers := []cloud.Reconciler{ + server.New(machineScope), + securitygroup.New(machineScope), + } + for _, s := range reconcilers { + res, err := s.Reconcile(ctx) + if err != nil || !res.IsZero() || machineScope.NotReady() { + return res, err } - return ctrl.Result{RequeueAfter: 15 * time.Second}, nil - } - - if err := securitygroup.New(machineScope).Reconcile(ctx); err != nil { - log.Error(err, "Failed to configure bastion SSH access for node", "machine", stackitMachine.Name) - record.Warnf( - stackitMachine, "FailedNodeSSHAccess", - "Failed to configure bastion SSH access for server %s: %v", stackitMachine.Status.InstanceID, err, - ) - return machineScope.CloudFailureResult( - "BastionSSHAccessError", - err, - retryableErrorRequeueAfter, - true, - infrav1.MachineReadyCondition, - ) } machineScope.SetReady() @@ -326,18 +265,9 @@ func (r *StackitMachineReconciler) reconcileDelete(ctx context.Context, machineS } machineScope.SetCloudClient(cloudClient) - instanceID := stackitMachine.Status.InstanceID - if err := server.New(machineScope).Delete(ctx); err != nil { - log.Error(err, "Failed to delete server", "machine", stackitMachine.Name, "instanceID", instanceID) - record.Warnf(stackitMachine, "FailedDeleteInstance", - "Failed to delete server %s: %v", instanceID, err) + if _, err := server.New(machineScope).Delete(ctx); err != nil { return err } - if instanceID != "" { - record.Eventf( - stackitMachine, "InstanceDeleted", "Deleted instance %s", instanceID, - ) - } controllerutil.RemoveFinalizer(stackitMachine, infrav1.MachineFinalizer) return nil } diff --git a/controller/stackitmachine_controller_test.go b/controller/stackitmachine_controller_test.go index 2568e4c..2d72bd3 100644 --- a/controller/stackitmachine_controller_test.go +++ b/controller/stackitmachine_controller_test.go @@ -65,7 +65,7 @@ var _ = Describe("StackitMachine Controller", func() { reconciler = &StackitMachineReconciler{ Client: k8sClient, Scheme: k8sClient.Scheme(), - CloudClientFactory: func(context.Context, cloud.Credentials) (cloud.Client, error) { + CloudClientFactory: func(cloud.Credentials) (cloud.Client, error) { return fakeCloud, nil }, } @@ -386,7 +386,7 @@ var _ = Describe("StackitMachine Controller", func() { }) It("requeues on unauthorized credentials and recovers once they are corrected", func() { - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { return nil, fmt.Errorf("authenticate: %w", shared.ErrUnauthorized) } @@ -401,7 +401,7 @@ var _ = Describe("StackitMachine Controller", func() { expectCondition(got.Status.Conditions, infrav1.MachineReadyCondition, metav1.ConditionFalse, "CredentialsInvalid") By("correcting the credentials") - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { return fakeCloud, nil } @@ -421,7 +421,7 @@ var _ = Describe("StackitMachine Controller", func() { Expect(k8sClient.Update(ctx, cluster)).To(Succeed()) cloudClientFactoryCalls := 0 - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { cloudClientFactoryCalls++ return fakeCloud, nil } @@ -444,7 +444,7 @@ var _ = Describe("StackitMachine Controller", func() { Expect(k8sClient.Update(ctx, got)).To(Succeed()) cloudClientFactoryCalls := 0 - reconciler.CloudClientFactory = func(context.Context, cloud.Credentials) (cloud.Client, error) { + reconciler.CloudClientFactory = func(cloud.Credentials) (cloud.Client, error) { cloudClientFactoryCalls++ return fakeCloud, nil } diff --git a/scope/cluster_scope.go b/scope/cluster_scope.go index 75b24f9..dbf3eba 100644 --- a/scope/cluster_scope.go +++ b/scope/cluster_scope.go @@ -16,22 +16,27 @@ package scope import ( "context" "errors" + "fmt" "net/netip" "slices" "strings" "time" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" + "sigs.k8s.io/cluster-api/util/collections" "sigs.k8s.io/cluster-api/util/patch" + "sigs.k8s.io/cluster-api/util/record" infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud" - "github.com/stackitcloud/cluster-api-provider-stackit/cloud/services/availabilityzone" "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/publicip" @@ -43,27 +48,27 @@ import ( lb "github.com/stackitcloud/stackit-sdk-go/services/loadbalancer/v2api" ) -const bastionSSHPort = 22 +const ( + bastionSSHPort = 22 + cloudInitRefKindSecret = "Secret" +) // ClusterScope holds the per-reconcile state for a StackitCluster. type ClusterScope struct { Cluster *clusterv1.Cluster StackitCluster *infrav1.StackitCluster + client client.Client cloudClient cloud.Client - network *network.Network - networkCreated bool + network *network.Network loadBalancerTargets []loadbalancer.Target loadBalancerSeedTargets []loadbalancer.Target - loadBalancerCreated bool - bastionCloudInit []byte - bastionCloudInitHash string - bastionServerState string - bastionServerPowerStatus string - bastionServerCreated bool + bastionCloudInit []byte + bastionCloudInitHash string + notReady bool patchHelper *patch.Helper } @@ -81,6 +86,7 @@ func NewClusterScope( return &ClusterScope{ Cluster: cluster, StackitCluster: stackitCluster, + client: k8sClient, patchHelper: patchHelper, }, nil } @@ -91,11 +97,36 @@ func (s *ClusterScope) PatchObject(ctx context.Context) error { infrav1.ClusterReadyCondition, infrav1.ClusterNetworkReadyCondition, infrav1.ClusterLoadBalancerReadyCondition, + infrav1.ClusterBastionReadyCondition, infrav1.ClusterCredentialsReadyCondition, clusterv1.PausedCondition, }}) } +func (s *ClusterScope) Name() string { + return s.StackitCluster.Name +} + +func (s *ClusterScope) FindCondition(conditionType string) *metav1.Condition { + return meta.FindStatusCondition(s.StackitCluster.Status.Conditions, conditionType) +} + +func (s *ClusterScope) Event(reason, message string) { + record.Event(s.StackitCluster, reason, message) +} + +func (s *ClusterScope) Eventf(reason, messageFmt string, args ...any) { + record.Eventf(s.StackitCluster, reason, messageFmt, args...) +} + +func (s *ClusterScope) Warn(reason, message string) { + record.Warn(s.StackitCluster, reason, message) +} + +func (s *ClusterScope) Warnf(reason, messageFmt string, args ...any) { + record.Warnf(s.StackitCluster, reason, messageFmt, args...) +} + func (s *ClusterScope) SetConditions(status metav1.ConditionStatus, reason, message string, conditionTypes ...string) { setConditions(&s.StackitCluster.Status.Conditions, s.StackitCluster.Generation, status, reason, message, conditionTypes...) } @@ -138,9 +169,14 @@ func (s *ClusterScope) SetReady() { func (s *ClusterScope) SetNotReady(reason, message string, conditionTypes ...string) { s.StackitCluster.Status.Ready = false + s.notReady = true s.SetConditions(metav1.ConditionFalse, reason, message, conditionTypes...) } +func (s *ClusterScope) NotReady() bool { + return s.notReady +} + // CredentialFailureResult records the failure and decides how to retry. // // Invalid credentials need an operator to fix the Secret, so they requeue on a @@ -188,37 +224,81 @@ func (s *ClusterScope) setAPIServerEndpoint(endpoint clusterv1.APIEndpoint) { s.StackitCluster.Status.APIServerEndpoint = endpoint } +func (s *ClusterScope) BastionEnabled() bool { + return s.StackitCluster.Spec.Bastion.Enabled +} + +func (s *ClusterScope) ResolveBastionCloudInit(ctx context.Context) ([]byte, error) { + ref := s.StackitCluster.Spec.Bastion.CloudInitRef + if ref == nil { + return nil, nil + } + key := types.NamespacedName{Namespace: s.StackitCluster.Namespace, Name: ref.Name} + switch ref.Kind { + case "ConfigMap": + configMap := &corev1.ConfigMap{} + if err := s.client.Get(ctx, key, configMap); err != nil { + if apierrors.IsNotFound(err) { + return nil, fmt.Errorf("bastion.cloudInitRef ConfigMap %s not found", key) + } + return nil, err + } + value, ok := configMap.Data[ref.Key] + if !ok { + return nil, fmt.Errorf("bastion.cloudInitRef key %q not found in ConfigMap %s", ref.Key, key) + } + return []byte(value), nil + case cloudInitRefKindSecret: + secret := &corev1.Secret{} + if err := s.client.Get(ctx, key, secret); err != nil { + if apierrors.IsNotFound(err) { + return nil, fmt.Errorf("bastion.cloudInitRef Secret %s not found", key) + } + return nil, err + } + value, ok := secret.Data[ref.Key] + if !ok { + return nil, fmt.Errorf("bastion.cloudInitRef key %q not found in Secret %s", ref.Key, key) + } + return append([]byte(nil), value...), nil + default: + return nil, fmt.Errorf("bastion.cloudInitRef.kind must be ConfigMap or Secret") + } +} + func (s *ClusterScope) SetBastionCloudInit(cloudInit []byte, cloudInitHash string) { s.bastionCloudInit = cloudInit s.bastionCloudInitHash = cloudInitHash } -func (s *ClusterScope) BastionServerState() (state, powerStatus string) { - return s.bastionServerState, s.bastionServerPowerStatus +func (s *ClusterScope) BastionServerID() string { + return s.StackitCluster.Status.Bastion.ServerID +} + +func (s *ClusterScope) BastionCloudInitHash() string { + return s.StackitCluster.Status.Bastion.CloudInitHash } -func (s *ClusterScope) BastionServerCreated() bool { - return s.bastionServerCreated +func (s *ClusterScope) BastionPublicIP() string { + return s.StackitCluster.Status.Bastion.PublicIP } -func (s *ClusterScope) setBastionServer(srv *server.Server, created bool) { +func (s *ClusterScope) SetServer(srv *server.Server, created bool) { if srv == nil { - s.bastionServerCreated = false - s.bastionServerState = "" - s.bastionServerPowerStatus = "" s.StackitCluster.Status.Bastion.ServerID = "" s.StackitCluster.Status.Bastion.CloudInitHash = "" return } - s.bastionServerCreated = created - s.bastionServerState = srv.State - s.bastionServerPowerStatus = srv.PowerStatus s.StackitCluster.Status.Bastion.ServerID = srv.ID if created { s.StackitCluster.Status.Bastion.CloudInitHash = s.bastionCloudInitHash } } +func (s *ClusterScope) ServerGoneResult(err error) (ctrl.Result, error) { + return ctrl.Result{}, err +} + func (s *ClusterScope) ServerSpec() server.ServerSpec { return server.ServerSpec{ ID: s.StackitCluster.Status.Bastion.ServerID, @@ -232,7 +312,6 @@ func (s *ClusterScope) ServerSpec() server.ServerSpec { UserData: s.bastionCloudInit, Tags: s.bastionTags(), RootVolume: rootVolumeFromSpec(s.StackitCluster.Spec.Bastion.RootVolume), - SetServer: s.setBastionServer, } } @@ -248,7 +327,10 @@ func rootVolumeFromSpec(in infrav1.StackitRootVolumeSpec) server.RootVolume { } } -func (s *ClusterScope) setBastionSecurityGroup(sg *securitygroup.SecurityGroup) { +func (s *ClusterScope) SetSecurityGroup(specName string, sg *securitygroup.SecurityGroup) { + if specName != s.StackitCluster.Name+"-bastion-ssh" { + return + } if sg == nil { s.StackitCluster.Status.Bastion.SecurityGroupID = "" return @@ -265,6 +347,10 @@ func (s *ClusterScope) SetFailureDomains(failureDomains []clusterv1.FailureDomai s.StackitCluster.Status.FailureDomains = failureDomains } +func (s *ClusterScope) SetZones(zones []string) { + s.SetFailureDomains(failureDomainsFromZones(s.Region(), zones)) +} + // defaultAvailabilityZone returns the default single availability zone for a // StackitCluster (the alphabetically first published failure domain, falling // back to -1). This prevents the STACKIT IaaS API from defaulting to @@ -317,18 +403,28 @@ func (s *ClusterScope) apiServerLoadBalancerTags() map[string]string { return util.ClusterTags(s.StackitCluster.Name, s.StackitCluster.Namespace, s.StackitCluster.Spec.AdditionalLabels) } -func (s *ClusterScope) APIServerLoadBalancerCreated() bool { - return s.loadBalancerCreated +func (s *ClusterScope) APIServerLoadBalancerEnabled() bool { + return s.StackitCluster.Spec.APIServerLoadBalancer.Enabled +} + +func (s *ClusterScope) ControlPlaneEndpointHost() string { + return s.StackitCluster.Spec.ControlPlaneEndpoint.Host +} + +func (s *ClusterScope) UseExternalControlPlaneEndpoint() { + s.StackitCluster.Status.APIServerEndpoint = s.StackitCluster.Spec.ControlPlaneEndpoint +} + +func (s *ClusterScope) APIServerEndpointHost() string { + return s.StackitCluster.Status.APIServerEndpoint.Host } -func (s *ClusterScope) setAPIServerLoadBalancer(apiServerLB *loadbalancer.LoadBalancer, created bool) { +func (s *ClusterScope) SetLoadBalancer(apiServerLB *loadbalancer.LoadBalancer) { if apiServerLB == nil { - s.loadBalancerCreated = false s.StackitCluster.Status.APIServerLoadBalancerID = "" s.StackitCluster.Status.APIServerEndpoint = clusterv1.APIEndpoint{} return } - s.loadBalancerCreated = created s.StackitCluster.Status.APIServerLoadBalancerID = apiServerLB.ID if apiServerLB.IP == "" { s.StackitCluster.Status.APIServerEndpoint = clusterv1.APIEndpoint{} @@ -340,45 +436,68 @@ func (s *ClusterScope) setAPIServerLoadBalancer(apiServerLB *loadbalancer.LoadBa }) } +func (s *ClusterScope) TargetPoolFailureResult(_ error, requeueAfter time.Duration) (ctrl.Result, error) { + return ctrl.Result{RequeueAfter: requeueAfter}, nil +} + func (s *ClusterScope) SetAPIServerLoadBalancerTargets(targets, seedTargets []loadbalancer.Target) { s.loadBalancerTargets = targets s.loadBalancerSeedTargets = seedTargets } -func (s *ClusterScope) LoadBalancerSpec() loadbalancer.LoadBalancerSpec { - return loadbalancer.LoadBalancerSpec{ - ID: s.StackitCluster.Status.APIServerLoadBalancerID, - Name: s.StackitCluster.Name + "-apiserver", - NetworkID: s.NetworkID(), - Port: loadbalancer.DefaultAPIServerPort, - Tags: s.apiServerLoadBalancerTags(), - Targets: s.loadBalancerTargets, - SeedTargets: s.loadBalancerSeedTargets, - SetLoadBalancer: s.setAPIServerLoadBalancer, - } -} +func (s *ClusterScope) ResolveLoadBalancerSpec(ctx context.Context) (loadbalancer.LoadBalancerSpec, error) { + if s.client != nil && s.Cluster != nil { + // STACKIT takes an explicit target list rather than label-based + // membership, so exactly one reconciler owns the pool. Machines being + // deleted drop out here, before the node is drained. + machines, err := collections.GetFilteredMachinesForCluster( + ctx, + s.client, + s.Cluster, + collections.ControlPlaneMachines(s.Cluster.Name), + collections.ActiveMachines, + ) + if err != nil { + s.SetConditions( + metav1.ConditionFalse, + "MachineListError", + err.Error(), + infrav1.ClusterLoadBalancerReadyCondition, + ) + return loadbalancer.LoadBalancerSpec{}, fmt.Errorf("list control plane machines: %w", err) + } + targets := loadbalancer.APIServerTargets(machines.UnsortedList()) -func (s *ClusterScope) AvailabilityZoneSpec() availabilityzone.AvailabilityZoneSpec { - return availabilityzone.AvailabilityZoneSpec{ - SetZones: func(zones []string) { - s.SetFailureDomains(failureDomainsFromZones(s.Region(), zones)) - }, + // Seeding with the real targets lets a load balancer deleted out of band + // come back with the control plane behind it. + seed := targets + if len(seed) == 0 { + seed = []loadbalancer.Target{loadbalancer.BootstrapTarget(s.BootstrapTargetIP())} + } + s.SetAPIServerLoadBalancerTargets(targets, seed) } + return s.LoadBalancerSpec(), nil } -func (s *ClusterScope) NetworkCreated() bool { - return s.networkCreated +func (s *ClusterScope) LoadBalancerSpec() loadbalancer.LoadBalancerSpec { + return loadbalancer.LoadBalancerSpec{ + ID: s.StackitCluster.Status.APIServerLoadBalancerID, + Name: s.StackitCluster.Name + "-apiserver", + NetworkID: s.NetworkID(), + Port: loadbalancer.DefaultAPIServerPort, + Tags: s.apiServerLoadBalancerTags(), + Targets: s.loadBalancerTargets, + SeedTargets: s.loadBalancerSeedTargets, + } } -func (s *ClusterScope) setNetwork(net *network.Network, created bool) { +func (s *ClusterScope) SetNetwork(net *network.Network) { if net == nil { s.network = nil - s.networkCreated = false s.StackitCluster.Status.Network = infrav1.StackitNetworkStatus{} return } s.network = net - s.networkCreated = created s.StackitCluster.Status.Network = infrav1.StackitNetworkStatus{ ID: net.ID, Managed: s.StackitCluster.Spec.Network.ID == "", @@ -389,8 +508,7 @@ func (s *ClusterScope) setNetwork(net *network.Network, created bool) { func (s *ClusterScope) NetworkSpec() network.NetworkSpec { if s.StackitCluster.Spec.Network.ID != "" { return network.NetworkSpec{ - ID: s.StackitCluster.Spec.Network.ID, - SetNetwork: s.setNetwork, + ID: s.StackitCluster.Spec.Network.ID, } } spec := network.NetworkSpec{ @@ -398,7 +516,6 @@ func (s *ClusterScope) NetworkSpec() network.NetworkSpec { Name: s.StackitCluster.Name + "-network", Tags: util.ClusterTags(s.StackitCluster.Name, s.StackitCluster.Namespace, s.StackitCluster.Spec.AdditionalLabels), Managed: true, - SetNetwork: s.setNetwork, IPv4PrefixLength: s.StackitCluster.Spec.Network.PrefixLength, } if s.StackitCluster.Spec.Network.Prefix != "" { @@ -435,7 +552,6 @@ func (s *ClusterScope) PublicIPSpec() publicip.PublicIPSpec { Tags: s.bastionTags(), ServerID: s.StackitCluster.Status.Bastion.ServerID, ServerSelector: s.bastionTags(), - SetPublicIP: s.setBastionPublicIP, } } @@ -507,7 +623,7 @@ func NodeSSHTags(stackitCluster *infrav1.StackitCluster) map[string]string { return tags } -func (s *ClusterScope) setBastionPublicIP(pip *publicip.PublicIP) { +func (s *ClusterScope) SetPublicIP(pip *publicip.PublicIP) { if pip == nil { s.StackitCluster.Status.Bastion.PublicIPID = "" s.StackitCluster.Status.Bastion.PublicIP = "" @@ -537,14 +653,13 @@ func (s *ClusterScope) SecurityGroupSpecs() []securitygroup.SecurityGroupSpec { }) return []securitygroup.SecurityGroupSpec{ { - ID: s.StackitCluster.Status.Bastion.SecurityGroupID, - Name: s.StackitCluster.Name + "-bastion-ssh", - Description: "Cluster API Provider STACKIT bastion SSH access", - Tags: s.bastionTags(), - Rules: rules, - ServerIDs: []string{s.StackitCluster.Status.Bastion.ServerID}, - ServerSelector: s.bastionTags(), - SetSecurityGroup: s.setBastionSecurityGroup, + ID: s.StackitCluster.Status.Bastion.SecurityGroupID, + Name: s.StackitCluster.Name + "-bastion-ssh", + Description: "Cluster API Provider STACKIT bastion SSH access", + Tags: s.bastionTags(), + Rules: rules, + ServerIDs: []string{s.StackitCluster.Status.Bastion.ServerID}, + ServerSelector: s.bastionTags(), }, nodeSSHSecurityGroupSpec(s.StackitCluster, ""), } diff --git a/scope/cluster_scope_test.go b/scope/cluster_scope_test.go index 18437f6..ed4ef6c 100644 --- a/scope/cluster_scope_test.go +++ b/scope/cluster_scope_test.go @@ -82,13 +82,13 @@ func TestDefaultAvailabilityZone(t *testing.T) { } } -func TestAvailabilityZoneSpecUsesResolvedRegion(t *testing.T) { +func TestSetZonesUsesResolvedRegion(t *testing.T) { clusterScope := &ClusterScope{ StackitCluster: &infrav1.StackitCluster{}, cloudClient: cloudfake.New(), } - clusterScope.AvailabilityZoneSpec().SetZones([]string{"eu01-1"}) + clusterScope.SetZones([]string{"eu01-1"}) if len(clusterScope.StackitCluster.Status.FailureDomains) != 1 { t.Fatalf("FailureDomains = %#v, want 1 entry", clusterScope.StackitCluster.Status.FailureDomains) @@ -99,37 +99,24 @@ func TestAvailabilityZoneSpecUsesResolvedRegion(t *testing.T) { } } -func TestServerSpecSetServerPreservesCloudInitHashOnAdoptedServer(t *testing.T) { +func TestSetServerPreservesCloudInitHashOnAdoptedServer(t *testing.T) { clusterScope := &ClusterScope{ StackitCluster: &infrav1.StackitCluster{}, } clusterScope.SetBastionCloudInit([]byte("#cloud-config\npackages:\n- jq\n"), "new-hash") - spec := clusterScope.ServerSpec() - spec.SetServer(&server.Server{ID: "srv-adopted", State: "ACTIVE", PowerStatus: "RUNNING"}, false) + clusterScope.SetServer(&server.Server{ID: "srv-adopted", State: "ACTIVE", PowerStatus: "RUNNING"}, false) - if clusterScope.BastionServerCreated() { - t.Fatal("BastionServerCreated() = true on adopted server, want false") - } if got := clusterScope.StackitCluster.Status.Bastion.CloudInitHash; got != "" { t.Fatalf("Status.Bastion.CloudInitHash on adopted server = %q, want empty", got) } - spec.SetServer(&server.Server{ID: "srv-created", State: "ACTIVE", PowerStatus: "RUNNING"}, true) - if !clusterScope.BastionServerCreated() { - t.Fatal("BastionServerCreated() = false on created server, want true") - } + clusterScope.SetServer(&server.Server{ID: "srv-created", State: "ACTIVE", PowerStatus: "RUNNING"}, true) if got := clusterScope.StackitCluster.Status.Bastion.CloudInitHash; got != "new-hash" { t.Fatalf("Status.Bastion.CloudInitHash on created server = %q, want %q", got, "new-hash") } - spec.SetServer(nil, false) - if clusterScope.BastionServerCreated() { - t.Fatal("BastionServerCreated() = true after SetServer(nil, false), want false") - } - if state, powerStatus := clusterScope.BastionServerState(); state != "" || powerStatus != "" { - t.Fatalf("BastionServerState() after SetServer(nil, false) = (%q, %q), want empty", state, powerStatus) - } + clusterScope.SetServer(nil, false) if got := clusterScope.StackitCluster.Status.Bastion.ServerID; got != "" { t.Fatalf("Status.Bastion.ServerID after SetServer(nil, false) = %q, want empty", got) } @@ -138,21 +125,17 @@ func TestServerSpecSetServerPreservesCloudInitHashOnAdoptedServer(t *testing.T) } } -func TestLoadBalancerSpecSetLoadBalancerClearsOnNil(t *testing.T) { +func TestSetLoadBalancerClearsOnNil(t *testing.T) { clusterScope := &ClusterScope{ StackitCluster: &infrav1.StackitCluster{}, } - spec := clusterScope.LoadBalancerSpec() - spec.SetLoadBalancer(&loadbalancer.LoadBalancer{ + clusterScope.SetLoadBalancer(&loadbalancer.LoadBalancer{ ID: "lb-1", IP: "203.0.113.10", Port: 6443, - }, true) + }) - if !clusterScope.APIServerLoadBalancerCreated() { - t.Fatal("APIServerLoadBalancerCreated() = false on created load balancer, want true") - } if clusterScope.StackitCluster.Status.APIServerLoadBalancerID != "lb-1" { t.Fatalf("Status.APIServerLoadBalancerID = %q, want lb-1", clusterScope.StackitCluster.Status.APIServerLoadBalancerID) } @@ -164,10 +147,7 @@ func TestLoadBalancerSpecSetLoadBalancerClearsOnNil(t *testing.T) { t.Fatalf("Status.APIServerEndpoint = %#v, want %#v", clusterScope.StackitCluster.Status.APIServerEndpoint, wantEndpoint) } - spec.SetLoadBalancer(nil, false) - if clusterScope.APIServerLoadBalancerCreated() { - t.Fatal("APIServerLoadBalancerCreated() = true after SetLoadBalancer(nil, false), want false") - } + clusterScope.SetLoadBalancer(nil) if clusterScope.StackitCluster.Status.APIServerLoadBalancerID != "" { t.Fatalf("Status.APIServerLoadBalancerID after clear = %q, want empty", clusterScope.StackitCluster.Status.APIServerLoadBalancerID) } @@ -179,13 +159,12 @@ func TestLoadBalancerSpecSetLoadBalancerClearsOnNil(t *testing.T) { } } -func TestPublicIPSpecSetPublicIPClearsOnNil(t *testing.T) { +func TestSetPublicIPClearsOnNil(t *testing.T) { clusterScope := &ClusterScope{ StackitCluster: &infrav1.StackitCluster{}, } - spec := clusterScope.PublicIPSpec() - spec.SetPublicIP(&publicip.PublicIP{ + clusterScope.SetPublicIP(&publicip.PublicIP{ ID: "pip-1", IP: "203.0.113.22", }) @@ -197,7 +176,7 @@ func TestPublicIPSpecSetPublicIPClearsOnNil(t *testing.T) { t.Fatalf("Status.Bastion.PublicIP = %q, want 203.0.113.22", clusterScope.StackitCluster.Status.Bastion.PublicIP) } - spec.SetPublicIP(nil) + clusterScope.SetPublicIP(nil) if clusterScope.StackitCluster.Status.Bastion.PublicIPID != "" { t.Fatalf("Status.Bastion.PublicIPID after clear = %q, want empty", clusterScope.StackitCluster.Status.Bastion.PublicIPID) } @@ -206,9 +185,11 @@ func TestPublicIPSpecSetPublicIPClearsOnNil(t *testing.T) { } } -func TestSecurityGroupSpecsSetSecurityGroupClearsOnNil(t *testing.T) { +func TestSetSecurityGroupClearsOnNil(t *testing.T) { clusterScope := &ClusterScope{ - StackitCluster: &infrav1.StackitCluster{}, + StackitCluster: &infrav1.StackitCluster{ + ObjectMeta: metav1.ObjectMeta{Name: "my-cluster"}, + }, } specs := clusterScope.SecurityGroupSpecs() @@ -216,7 +197,7 @@ func TestSecurityGroupSpecsSetSecurityGroupClearsOnNil(t *testing.T) { t.Fatalf("SecurityGroupSpecs() count = %d, want 2", len(specs)) } - specs[0].SetSecurityGroup(&securitygroup.SecurityGroup{ + clusterScope.SetSecurityGroup(specs[0].Name, &securitygroup.SecurityGroup{ ID: "sg-1", Name: "bastion-ssh", }) @@ -224,13 +205,13 @@ func TestSecurityGroupSpecsSetSecurityGroupClearsOnNil(t *testing.T) { t.Fatalf("Status.Bastion.SecurityGroupID = %q, want sg-1", clusterScope.StackitCluster.Status.Bastion.SecurityGroupID) } - specs[0].SetSecurityGroup(nil) + clusterScope.SetSecurityGroup(specs[0].Name, nil) if clusterScope.StackitCluster.Status.Bastion.SecurityGroupID != "" { t.Fatalf("Status.Bastion.SecurityGroupID after clear = %q, want empty", clusterScope.StackitCluster.Status.Bastion.SecurityGroupID) } } -func TestMachineScopeServerSpecSetServerClearsOnNil(t *testing.T) { +func TestMachineScopeSetServerClearsOnNil(t *testing.T) { machineScope := &MachineScope{ cluster: &clusterv1.Cluster{}, Machine: &clusterv1.Machine{}, @@ -238,8 +219,7 @@ func TestMachineScopeServerSpecSetServerClearsOnNil(t *testing.T) { StackitMachine: &infrav1.StackitMachine{}, } - spec := machineScope.ServerSpec() - spec.SetServer(&server.Server{ + machineScope.SetServer(&server.Server{ ID: "srv-1", State: "ACTIVE", PowerStatus: "RUNNING", @@ -247,17 +227,11 @@ func TestMachineScopeServerSpecSetServerClearsOnNil(t *testing.T) { Addresses: []server.Address{{Type: "InternalIP", Address: "10.0.0.5"}}, }, true) - if !machineScope.InstanceCreated() || machineScope.InstancePowerStatus() != "RUNNING" { - t.Fatalf("InstanceCreated=%v, InstancePowerStatus=%q", machineScope.InstanceCreated(), machineScope.InstancePowerStatus()) - } if machineScope.StackitMachine.Status.InstanceID != "srv-1" { t.Fatalf("Status.InstanceID = %q, want srv-1", machineScope.StackitMachine.Status.InstanceID) } - spec.SetServer(nil, false) - if machineScope.InstanceCreated() || machineScope.InstancePowerStatus() != "" { - t.Fatalf("after SetServer(nil, false): InstanceCreated=%v, InstancePowerStatus=%q, want false and empty", machineScope.InstanceCreated(), machineScope.InstancePowerStatus()) - } + machineScope.SetServer(nil, false) if machineScope.StackitMachine.Status.InstanceID != "" || machineScope.StackitMachine.Status.InstanceState != "" || machineScope.StackitMachine.Status.AvailabilityZone != "" || @@ -457,10 +431,10 @@ func TestNetworkSpec(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: "my-cluster"}, }, } - clusterScope.NetworkSpec().SetNetwork(&network.Network{ + clusterScope.SetNetwork(&network.Network{ ID: "net-123", IPv4Prefixes: []string{"10.0.5.0/24"}, - }, true) + }) if clusterScope.StackitCluster.Status.Network.ID != "net-123" { t.Fatalf("Status.Network.ID = %q, want net-123", clusterScope.StackitCluster.Status.Network.ID) } @@ -478,18 +452,18 @@ func TestBootstrapTargetIP(t *testing.T) { t.Fatalf("BootstrapTargetIP() with nil network = %q, want %q", got, loadbalancer.DefaultBootstrapTargetIP) } - clusterScope.NetworkSpec().SetNetwork(&network.Network{ + clusterScope.SetNetwork(&network.Network{ ID: "net-1", IPv4Prefixes: []string{"192.168.10.0/24"}, - }, false) + }) if got := clusterScope.BootstrapTargetIP(); got != "192.168.10.10" { t.Fatalf("BootstrapTargetIP() with /24 network = %q, want %q", got, "192.168.10.10") } - clusterScope.NetworkSpec().SetNetwork(&network.Network{ + clusterScope.SetNetwork(&network.Network{ ID: "net-2", IPv4Prefixes: []string{"invalid"}, - }, false) + }) if got := clusterScope.BootstrapTargetIP(); got != loadbalancer.DefaultBootstrapTargetIP { t.Fatalf("BootstrapTargetIP() with invalid prefix = %q, want %q", got, loadbalancer.DefaultBootstrapTargetIP) } diff --git a/scope/machine_scope.go b/scope/machine_scope.go index 652a6e9..8ad8af1 100644 --- a/scope/machine_scope.go +++ b/scope/machine_scope.go @@ -15,12 +15,14 @@ import ( "fmt" "time" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" clusterv1 "sigs.k8s.io/cluster-api/api/core/v1beta2" "sigs.k8s.io/cluster-api/util/patch" + "sigs.k8s.io/cluster-api/util/record" infrav1 "github.com/stackitcloud/cluster-api-provider-stackit/api/v1alpha1" "github.com/stackitcloud/cluster-api-provider-stackit/cloud" @@ -38,9 +40,8 @@ type MachineScope struct { cluster *clusterv1.Cluster cloudClient cloud.Client - bootstrapData []byte - instancePowerStatus string - instanceCreated bool + bootstrapData []byte + notReady bool patchHelper *patch.Helper } @@ -78,6 +79,30 @@ func (s *MachineScope) PatchObject(ctx context.Context) error { }}) } +func (s *MachineScope) Name() string { + return s.StackitMachine.Name +} + +func (s *MachineScope) FindCondition(conditionType string) *metav1.Condition { + return meta.FindStatusCondition(s.StackitMachine.Status.Conditions, conditionType) +} + +func (s *MachineScope) Event(reason, message string) { + record.Event(s.StackitMachine, reason, message) +} + +func (s *MachineScope) Eventf(reason, messageFmt string, args ...any) { + record.Eventf(s.StackitMachine, reason, messageFmt, args...) +} + +func (s *MachineScope) Warn(reason, message string) { + record.Warn(s.StackitMachine, reason, message) +} + +func (s *MachineScope) Warnf(reason, messageFmt string, args ...any) { + record.Warnf(s.StackitMachine, reason, messageFmt, args...) +} + func (s *MachineScope) SetConditions(status metav1.ConditionStatus, reason, message string, conditionTypes ...string) { setConditions(&s.StackitMachine.Status.Conditions, s.StackitMachine.Generation, status, reason, message, conditionTypes...) } @@ -93,9 +118,14 @@ func (s *MachineScope) SetReady() { func (s *MachineScope) SetNotReady(reason, message string, conditionTypes ...string) { s.StackitMachine.Status.Ready = false + s.notReady = true s.SetConditions(metav1.ConditionFalse, reason, message, conditionTypes...) } +func (s *MachineScope) NotReady() bool { + return s.notReady +} + // CredentialFailureResult records the failure and decides how to retry. func (s *MachineScope) CredentialFailureResult( err error, @@ -127,18 +157,14 @@ func (s *MachineScope) tags() map[string]string { ) } -func (s *MachineScope) setInstance(srv *server.Server, created bool) { +func (s *MachineScope) SetServer(srv *server.Server, _ bool) { if srv == nil { - s.instanceCreated = false - s.instancePowerStatus = "" s.StackitMachine.Status.Addresses = nil s.StackitMachine.Status.InstanceID = "" s.StackitMachine.Status.InstanceState = "" s.StackitMachine.Status.AvailabilityZone = "" return } - s.instanceCreated = created - s.instancePowerStatus = srv.PowerStatus s.StackitMachine.Status.Addresses = machineAddressesFromServer(srv.Addresses) providerID := fmt.Sprintf("stackit://%s", srv.ID) s.StackitMachine.Status.InstanceID = srv.ID @@ -149,6 +175,10 @@ func (s *MachineScope) setInstance(srv *server.Server, created bool) { s.StackitMachine.Status.Initialization.Provisioned = true } +func (s *MachineScope) ServerGoneResult(_ error) (ctrl.Result, error) { + return ctrl.Result{}, nil +} + // availabilityZone returns the resolved availability zone for the machine. // Following Cluster API conventions: // 1. If Machine.Spec.FailureDomain is set (e.g. by KCP spreading control plane nodes or MachineDeployment), @@ -195,14 +225,6 @@ func (s *MachineScope) SetBootstrapData(data []byte) { s.bootstrapData = data } -func (s *MachineScope) InstancePowerStatus() string { - return s.instancePowerStatus -} - -func (s *MachineScope) InstanceCreated() bool { - return s.instanceCreated -} - func (s *MachineScope) ServerSpec() server.ServerSpec { return server.ServerSpec{ ID: s.StackitMachine.Status.InstanceID, @@ -217,7 +239,6 @@ func (s *MachineScope) ServerSpec() server.ServerSpec { Tags: s.tags(), RootVolume: rootVolumeFromSpec(s.StackitMachine.Spec.RootVolume), DisallowRecreate: s.StackitMachine.Status.Initialization.Provisioned, - SetServer: s.setInstance, } } @@ -234,6 +255,8 @@ func (s *MachineScope) SecurityGroupSpecs() []securitygroup.SecurityGroupSpec { } } +func (s *MachineScope) SetSecurityGroup(_ string, _ *securitygroup.SecurityGroup) {} + func machineAddressesFromServer(in []server.Address) []clusterv1.MachineAddress { if len(in) == 0 { return nil diff --git a/util/reconcile.go b/util/reconcile.go index 84eff37..00bf360 100644 --- a/util/reconcile.go +++ b/util/reconcile.go @@ -69,7 +69,7 @@ func BuildCloudClient( return nil, err } - return factory(ctx, creds) + return factory(creds) } func CredentialsSecretKey(stackitCluster *infrav1.StackitCluster) types.NamespacedName {