Repository: syself/cluster-api-provider-hetzner
Pull request #663 (2023-03-12 19:14:25)

:seedling: Update code of bm controller


<!-- If this is your first PR, welcome! Please make sure you read the [contributing guidelines](../CONTRIBUTING.md#contributing-a-patch). -->
<!-- please add a icon to the title of this PR and delete this line and similar ones -->
<!-- the icon will be either ⚠️ (:warning:, major or breaking changes), ✨ (:sparkles:, feature additions), 🐛 (:bug:, patch and bugfixes), 📖 (:book:, documentation or proposals), or 🌱 (:seedling:, minor or other) -->

**What this PR does / why we need it**:
Mainly updating imports to align them and error handling

**TODOs**:
- [x] squashed commits
- [ ] includes documentation
- [ ] adds unit tests




Patch:
diff --git a/controllers/hcloudmachinetemplate_controller.go b/controllers/hcloudmachinetemplate_controller.go
index c22c7a29..320294d8 100644
--- a/controllers/hcloudmachinetemplate_controller.go
+++ b/controllers/hcloudmachinetemplate_controller.go
@@ -18,9 +18,9 @@ package controllers
 
 import (
 	"context"
+	"fmt"
 	"time"
 
-	"github.com/pkg/errors"
 	infrav1 "github.com/syself/cluster-api-provider-hetzner/api/v1beta1"
 	"github.com/syself/cluster-api-provider-hetzner/pkg/scope"
 	secretutil "github.com/syself/cluster-api-provider-hetzner/pkg/secrets"
@@ -47,14 +47,14 @@ type HCloudMachineTemplateReconciler struct {
 // +kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=hcloudmachinetemplates/status,verbs=get;update;patch
 
 // Reconcile manages the lifecycle of an HCloudMachineTemplate object.
-func (r *HCloudMachineTemplateReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
+func (r *HCloudMachineTemplateReconciler) Reconcile(ctx context.Context, req reconcile.Request) (_ reconcile.Result, reterr error) {
 	log := ctrl.LoggerFrom(ctx)
 	log.Info("Reconcile HCloudMachineTemplate")
 
 	machineTemplate := &infrav1.HCloudMachineTemplate{}
 	if err := r.Get(ctx, req.NamespacedName, machineTemplate); err != nil {
 		log.Error(err, "unable to fetch HCloudMachineTemplate")
-		return ctrl.Result{}, client.IgnoreNotFound(err)
+		return reconcile.Result{}, client.IgnoreNotFound(err)
 	}
 
 	log = log.WithValues("HCloudMachineTemplate", klog.KObj(machineTemplate))
@@ -63,13 +63,14 @@ func (r *HCloudMachineTemplateReconciler) Reconcile(ctx context.Context, req ctr
 	cluster, err := util.GetClusterFromMetadata(ctx, r.Client, machineTemplate.ObjectMeta)
 	if err != nil {
 		log.Info("Machine is missing cluster label or cluster does not exist")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	log = log.WithValues("Cluster", klog.KObj(cluster))
 
+	// Requeue if cluster has no infrastructure yet.
 	if cluster.Spec.InfrastructureRef == nil {
-		return ctrl.Result{Requeue: true}, nil
+		return reconcile.Result{Requeue: true}, nil
 	}
 
 	hetznerCluster := &infrav1.HetznerCluster{}
@@ -80,7 +81,7 @@ func (r *HCloudMachineTemplateReconciler) Reconcile(ctx context.Context, req ctr
 	}
 	if err := r.Client.Get(ctx, hetznerClusterName, hetznerCluster); err != nil {
 		log.Info("HetznerCluster is not available yet")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	log = log.WithValues("HetznerCluster", klog.KObj(hetznerCluster))
@@ -102,7 +103,7 @@ func (r *HCloudMachineTemplateReconciler) Reconcile(ctx context.Context, req ctr
 		HCloudClient:          hcc,
 	})
 	if err != nil {
-		return reconcile.Result{}, errors.Errorf("failed to create scope: %+v", err)
+		return reconcile.Result{}, fmt.Errorf("failed to create scope: %w", err)
 	}
 
 	// Always close the scope when exiting this function so we can persist any HCloudMachine changes.
@@ -114,7 +115,7 @@ func (r *HCloudMachineTemplateReconciler) Reconcile(ctx context.Context, req ctr
 
 	// check whether rate limit has been reached and if so, then wait.
 	if wait := reconcileRateLimit(machineTemplate); wait {
-		return ctrl.Result{RequeueAfter: 30 * time.Second}, nil
+		return reconcile.Result{RequeueAfter: 30 * time.Second}, nil
 	}
 
 	return r.reconcile(ctx, machineTemplateScope)
@@ -129,12 +130,13 @@ func (r *HCloudMachineTemplateReconciler) reconcile(ctx context.Context, machine
 
 	// Register the finalizer immediately to avoid orphaning HCloud resources on delete
 	if err := machineTemplateScope.PatchObject(ctx); err != nil {
-		return ctrl.Result{}, err
+		return reconcile.Result{}, err
 	}
 
-	// reconcile machinetemplate
+	// reconcile machine template
 	if result, brk, err := breakReconcile(machinetemplate.NewService(machineTemplateScope).Reconcile(ctx)); brk {
-		return result, errors.Wrapf(err, "failed to reconcile machinetemplate for HCloudMachineTemplate %s/%s", hcloudMachine.Namespace, hcloudMachine.Name)
+		return result, fmt.Errorf("failed to reconcile machine template for HCloudMachineTemplate %s/%s: %w",
+			hcloudMachine.Namespace, hcloudMachine.Name, err)
 	}
 
 	return reconcile.Result{}, nil
diff --git a/controllers/hetznerbaremetalmachine_controller.go b/controllers/hetznerbaremetalmachine_controller.go
index a983fcf9..a9c918dd 100644
--- a/controllers/hetznerbaremetalmachine_controller.go
+++ b/controllers/hetznerbaremetalmachine_controller.go
@@ -18,9 +18,10 @@ package controllers
 
 import (
 	"context"
+	"errors"
+	"fmt"
 
 	"github.com/go-logr/logr"
-	"github.com/pkg/errors"
 	infrav1 "github.com/syself/cluster-api-provider-hetzner/api/v1beta1"
 	"github.com/syself/cluster-api-provider-hetzner/pkg/scope"
 	secretutil "github.com/syself/cluster-api-provider-hetzner/pkg/secrets"
@@ -56,18 +57,14 @@ type HetznerBareMetalMachineReconciler struct {
 //+kubebuilder:rbac:groups=infrastructure.cluster.x-k8s.io,resources=hetznerbaremetalmachines/finalizers,verbs=update
 
 // Reconcile implements the reconcilement of HetznerBareMetalMachine objects.
-func (r *HetznerBareMetalMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
+func (r *HetznerBareMetalMachineReconciler) Reconcile(ctx context.Context, req reconcile.Request) (_ reconcile.Result, reterr error) {
 	log := ctrl.LoggerFrom(ctx)
 
 	// Fetch the Hetzner bare metal instance.
 	hbmMachine := &infrav1.HetznerBareMetalMachine{}
 	err := r.Get(ctx, req.NamespacedName, hbmMachine)
 	if err != nil {
-		if apierrors.IsNotFound(err) {
-			log.Info("BareMetalMachine not found", "namespacedName", req.NamespacedName)
-			return ctrl.Result{}, nil
-		}
-		return ctrl.Result{}, err
+		return reconcile.Result{}, client.IgnoreNotFound(err)
 	}
 
 	log = log.WithValues("HetznerBareMetalMachine", klog.KObj(hbmMachine))
@@ -75,11 +72,12 @@ func (r *HetznerBareMetalMachineReconciler) Reconcile(ctx context.Context, req c
 	// Fetch the Machine.
 	machine, err := util.GetOwnerMachine(ctx, r.Client, hbmMachine.ObjectMeta)
 	if err != nil {
-		return ctrl.Result{}, errors.Wrapf(err, "failed to get owner machine. BareMetalMachine.ObjectMeta.OwnerReferences: %v", hbmMachine.ObjectMeta.OwnerReferences)
+		return reconcile.Result{}, fmt.Errorf("failed to get owner machine. BareMetalMachine.ObjectMeta.OwnerReferences %v: %w",
+			hbmMachine.ObjectMeta.OwnerReferences, err)
 	}
 	if machine == nil {
 		log.Info("Machine Controller has not yet set OwnerRef")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	log = log.WithValues("Machine", klog.KObj(machine))
@@ -88,12 +86,12 @@ func (r *HetznerBareMetalMachineReconciler) Reconcile(ctx context.Context, req c
 	cluster, err := util.GetClusterFromMetadata(ctx, r.Client, machine.ObjectMeta)
 	if err != nil {
 		log.Info("Machine is missing cluster label or cluster does not exist")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	if annotations.IsPaused(cluster, hbmMachine) {
 		log.Info("HetznerBareMetalMachine or linked Cluster is marked as paused. Won't reconcile")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	log = log.WithValues("Cluster", klog.KObj(cluster))
@@ -124,14 +122,14 @@ func (r *HetznerBareMetalMachineReconciler) Reconcile(ctx context.Context, req c
 	// Create the scope.
 	machineScope, err := scope.NewBareMetalMachineScope(ctx, scope.BareMetalMachineScopeParams{
 		Client:           r.Client,
-		Logger:           &log,
+		Logger:           log,
 		Machine:          machine,
 		BareMetalMachine: hbmMachine,
 		HetznerCluster:   hetznerCluster,
 		HCloudClient:     hcc,
 	})
 	if err != nil {
-		return reconcile.Result{}, errors.Errorf("failed to create scope: %+v", err)
+		return reconcile.Result{}, fmt.Errorf("failed to create scope: %w", err)
 	}
 
 	// Always close the scope when exiting this function so we can persist any HetznerBareMetalMachine changes.
@@ -152,15 +150,12 @@ func (r *HetznerBareMetalMachineReconciler) reconcileDelete(ctx context.Context,
 	machineScope.Info("Reconciling HetznerBareMetalMachine delete")
 	// delete servers
 	if result, brk, err := breakReconcile(baremetal.NewService(machineScope).Delete(ctx)); brk {
-		if requeueErr, ok := errors.Cause(err).(scope.HasRequeueAfterError); ok {
-			return ctrl.Result{Requeue: true, RequeueAfter: requeueErr.GetRequeueAfter()}, nil
+		var requeueError *scope.RequeueAfterError
+		if ok := errors.As(err, &requeueError); ok {
+			return reconcile.Result{Requeue: true, RequeueAfter: requeueError.GetRequeueAfter()}, nil
 		}
-		return result, errors.Wrapf(
-			err,
-			"failed to delete servers for HetznerBareMetalMachine %s/%s",
-			machineScope.BareMetalMachine.Namespace,
-			machineScope.BareMetalMachine.Name,
-		)
+		return result, fmt.Errorf("failed to delete servers for HetznerBareMetalMachine %s/%s: %w",
+			machineScope.BareMetalMachine.Namespace, machineScope.BareMetalMachine.Name, err)
 	}
 
 	// Machine is deleted so remove the finalizer.
@@ -177,17 +172,13 @@ func (r *HetznerBareMetalMachineReconciler) reconcileNormal(ctx context.Context,
 
 	// Register the finalizer immediately to avoid orphaning HetznerBareMetal resources on delete
 	if err := machineScope.PatchObject(ctx); err != nil {
-		return ctrl.Result{}, err
+		return reconcile.Result{}, err
 	}
 
 	// reconcile server
 	if result, brk, err := breakReconcile(baremetal.NewService(machineScope).Reconcile(ctx)); brk {
-		return result, errors.Wrapf(
-			err,
-			"failed to reconcile server for HetznerBareMetalMachine %s/%s",
-			machineScope.BareMetalMachine.Namespace,
-			machineScope.BareMetalMachine.Name,
-		)
+		return result, fmt.Errorf("failed to reconcile server for HetznerBareMetalMachine %s/%s: %w",
+			machineScope.BareMetalMachine.Namespace, machineScope.BareMetalMachine.Name, err)
 	}
 
 	return reconcile.Result{}, nil
@@ -199,7 +190,7 @@ func (r *HetznerBareMetalMachineReconciler) SetupWithManager(ctx context.Context
 	c, err := ctrl.NewControllerManagedBy(mgr).
 		WithOptions(options).
 		For(&infrav1.HetznerBareMetalMachine{}).
-		WithEventFilter(predicates.ResourceNotPausedAndHasFilterLabel(ctrl.LoggerFrom(ctx), r.WatchFilterValue)).
+		WithEventFilter(predicates.ResourceNotPausedAndHasFilterLabel(log, r.WatchFilterValue)).
 		Watches(
 			&source.Kind{Type: &clusterv1.Machine{}},
 			handler.EnqueueRequestsFromMapFunc(util.MachineToInfrastructureMapFunc(infrav1.GroupVersion.WithKind("HetznerBareMetalMachine"))),
@@ -218,12 +209,12 @@ func (r *HetznerBareMetalMachineReconciler) SetupWithManager(ctx context.Context
 		).
 		Build(r)
 	if err != nil {
-		return errors.Wrap(err, "error creating controller")
+		return fmt.Errorf("error creating controller: %w", err)
 	}
 
 	clusterToObjectFunc, err := util.ClusterToObjectsMapper(r.Client, &infrav1.HetznerBareMetalMachineList{}, mgr.GetScheme())
 	if err != nil {
-		return errors.Wrap(err, "failed to create mapper for Cluster to BareMetalMachines")
+		return fmt.Errorf("failed to create mapper for Cluster to BareMetalMachines: %w", err)
 	}
 
 	// Add a watch on clusterv1.Cluster object for unpause & ready notifications.
@@ -232,7 +223,7 @@ func (r *HetznerBareMetalMachineReconciler) SetupWithManager(ctx context.Context
 		handler.EnqueueRequestsFromMapFunc(clusterToObjectFunc),
 		predicates.ClusterUnpausedAndInfrastructureReady(log),
 	); err != nil {
-		return errors.Wrap(err, "failed adding a watch for ready clusters")
+		return fmt.Errorf("failed adding a watch for ready clusters: %w", err)
 	}
 
 	return nil
@@ -241,14 +232,15 @@ func (r *HetznerBareMetalMachineReconciler) SetupWithManager(ctx context.Context
 // HetznerClusterToBareMetalMachines is a handler.ToRequestsFunc to be used to enqeue requests for reconciliation
 // of BareMetalMachines.
 func (r *HetznerBareMetalMachineReconciler) HetznerClusterToBareMetalMachines(ctx context.Context) handler.MapFunc {
-	return func(o client.Object) []ctrl.Request {
-		result := []ctrl.Request{}
+	return func(o client.Object) []reconcile.Request {
+		result := []reconcile.Request{}
 
 		log := log.FromContext(ctx)
 
 		c, ok := o.(*infrav1.HetznerCluster)
 		if !ok {
-			log.Error(errors.Errorf("expected a HetznerCluster but got a %T", o), "failed to get BareMetalMachine for HetznerCluster")
+			log.Error(fmt.Errorf("expected a HetznerCluster but got a %T", o),
+				"failed to get BareMetalMachine for HetznerCluster")
 			return nil
 		}
 
@@ -256,39 +248,41 @@ func (r *HetznerBareMetalMachineReconciler) HetznerClusterToBareMetalMachines(ct
 
 		// Don't handle deleted HetznerCluster
 		if !c.ObjectMeta.DeletionTimestamp.IsZero() {
-			log.V(1).Info("HetznerCluster has a deletion timestamp, skipping mapping.")
+			log.V(1).Info("HetznerCluster has a deletion timestamp, skipping mapping")
 			return nil
 		}
 
 		cluster, err := util.GetOwnerCluster(ctx, r.Client, c.ObjectMeta)
 		switch {
 		case apierrors.IsNotFound(err) || cluster == nil:
-			log.V(1).Info("Cluster for HetznerCluster not found, skipping mapping.")
+			log.V(1).Info("Cluster for HetznerCluster not found, skipping mapping")
 			return result
 		case err != nil:
-			log.Error(err, "failed to get owning cluster, skipping mapping.")
+			log.Error(err, "failed to get owning cluster, skipping mapping")
 			return result
 		}
 
 		labels := map[string]string{clusterv1.ClusterLabelName: cluster.Name}
 		machineList := &clusterv1.MachineList{}
 		if err := r.List(ctx, machineList, client.InNamespace(c.Namespace), client.MatchingLabels(labels)); err != nil {
-			log.Error(err, "failed to list Machines, skipping mapping.")
+			log.Error(err, "failed to list Machines, skipping mapping")
 			return nil
 		}
 		for _, m := range machineList.Items {
-			log.WithValues("machine", m.Name)
+			log = log.WithValues("machine", m.Name)
 			if m.Spec.InfrastructureRef.GroupVersionKind().Kind != "HetznerBareMetalMachine" {
-				log.V(1).Info("Machine has an InfrastructureRef for a different type, will not add to reconciliation request.")
+				log.V(1).Info("Machine has an InfrastructureRef for a different type, will not add to reconciliation request")
 				continue
 			}
 			if m.Spec.InfrastructureRef.Name == "" {
 				continue
 			}
+
 			name := client.ObjectKey{Namespace: m.Namespace, Name: m.Spec.InfrastructureRef.Name}
-			log.WithValues("bareMetalMachine", name.Name)
-			log.V(1).Info("Adding BareMetalMachine to reconciliation request.")
-			result = append(result, ctrl.Request{NamespacedName: name})
+
+			log.V(1).Info("Adding BareMetalMachine to reconciliation request", "bareMetalMachine", name.Name)
+
+			result = append(result, reconcile.Request{NamespacedName: name})
 		}
 
 		return result
@@ -298,14 +292,13 @@ func (r *HetznerBareMetalMachineReconciler) HetznerClusterToBareMetalMachines(ct
 // ClusterToBareMetalMachines is a handler.ToRequestsFunc to be used to enqeue
 // requests for reconciliation of BareMetalMachines.
 func (r *HetznerBareMetalMachineReconciler) ClusterToBareMetalMachines(ctx context.Context, log logr.Logger) handler.MapFunc {
-	return func(obj client.Object) []ctrl.Request {
-		result := []ctrl.Request{}
+	return func(obj client.Object) []reconcile.Request {
+		result := []reconcile.Request{}
 		c, ok := obj.(*clusterv1.Cluster)
 
 		if !ok {
-			log.Error(errors.Errorf("expected a Cluster but got a %T", obj),
-				"failed to get BareMetalMachine for Cluster",
-			)
+			log.Error(fmt.Errorf("expected a Cluster but got a %T", obj),
+				"failed to get BareMetalMachine for Cluster")
 			return nil
 		}
 
@@ -325,7 +318,7 @@ func (r *HetznerBareMetalMachineReconciler) ClusterToBareMetalMachines(ctx conte
 			if m.Spec.InfrastructureRef.Namespace != "" {
 				name = client.ObjectKey{Namespace: m.Spec.InfrastructureRef.Namespace, Name: m.Spec.InfrastructureRef.Name}
 			}
-			result = append(result, ctrl.Request{NamespacedName: name})
+			result = append(result, reconcile.Request{NamespacedName: name})
 		}
 
 		return result
@@ -335,12 +328,12 @@ func (r *HetznerBareMetalMachineReconciler) ClusterToBareMetalMachines(ctx conte
 // BareMetalHostToBareMetalMachines will return a reconcile request for a BareMetalMachine if the event is for a
 // BareMetalHost and that BareMetalHost references a BareMetalMachine.
 func (r *HetznerBareMetalMachineReconciler) BareMetalHostToBareMetalMachines(log logr.Logger) handler.MapFunc {
-	return func(obj client.Object) []ctrl.Request {
+	return func(obj client.Object) []reconcile.Request {
 		if host, ok := obj.(*infrav1.HetznerBareMetalHost); ok {
 			if host.Spec.ConsumerRef != nil &&
 				host.Spec.ConsumerRef.Kind == "HetznerBareMetalMachine" &&
 				host.Spec.ConsumerRef.GroupVersionKind().Group == infrav1.GroupVersion.Group {
-				return []ctrl.Request{
+				return []reconcile.Request{
 					{
 						NamespacedName: types.NamespacedName{
 							Name:      host.Spec.ConsumerRef.Name,
@@ -350,10 +343,9 @@ func (r *HetznerBareMetalMachineReconciler) BareMetalHostToBareMetalMachines(log
 				}
 			}
 		} else {
-			log.Error(errors.Errorf("expected a BareMetalHost but got a %T", obj),
-				"failed to get BareMetalMachine for BareMetalHost",
-			)
+			log.Error(fmt.Errorf("expected a BareMetalHost but got a %T", obj),
+				"failed to get BareMetalMachine for BareMetalHost")
 		}
-		return []ctrl.Request{}
+		return []reconcile.Request{}
 	}
 }
diff --git a/controllers/hetznerbaremetalremediation_controller.go b/controllers/hetznerbaremetalremediation_controller.go
index ea0d6576..4d3888da 100644
--- a/controllers/hetznerbaremetalremediation_controller.go
+++ b/controllers/hetznerbaremetalremediation_controller.go
@@ -18,8 +18,8 @@ package controllers
 
 import (
 	"context"
+	"fmt"
 
-	"github.com/pkg/errors"
 	infrav1 "github.com/syself/cluster-api-provider-hetzner/api/v1beta1"
 	"github.com/syself/cluster-api-provider-hetzner/pkg/scope"
 	"github.com/syself/cluster-api-provider-hetzner/pkg/services/baremetal/remediation"
@@ -47,7 +47,7 @@ type HetznerBareMetalRemediationReconciler struct {
 //+kubebuilder:rbac:groups=cluster.x-k8s.io,resources=machines;machines/status,verbs=get;update;patch
 
 // Reconcile reconciles the hetznerBareMetalRemediation object.
-func (r *HetznerBareMetalRemediationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Result, reterr error) {
+func (r *HetznerBareMetalRemediationReconciler) Reconcile(ctx context.Context, req reconcile.Request) (_ reconcile.Result, reterr error) {
 	log := ctrl.LoggerFrom(ctx)
 
 	// Fetch the Hetzner bare metal host instance.
@@ -55,9 +55,9 @@ func (r *HetznerBareMetalRemediationReconciler) Reconcile(ctx context.Context, r
 	err := r.Get(ctx, req.NamespacedName, bareMetalRemediation)
 	if err != nil {
 		if apierrors.IsNotFound(err) {
-			return ctrl.Result{}, nil
+			return reconcile.Result{}, nil
 		}
-		return ctrl.Result{}, err
+		return reconcile.Result{}, err
 	}
 
 	log = log.WithValues("HetznerBareMetalRemediation", klog.KObj(bareMetalRemediation))
@@ -65,11 +65,11 @@ func (r *HetznerBareMetalRemediationReconciler) Reconcile(ctx context.Context, r
 	// Fetch the Machine.
 	machine, err := util.GetOwnerMachine(ctx, r.Client, bareMetalRemediation.ObjectMeta)
 	if err != nil {
-		return ctrl.Result{}, err
+		return reconcile.Result{}, err
 	}
 	if machine == nil {
 		log.Info("Machine Controller has not yet set OwnerRef")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	log = log.WithValues("Machine", klog.KObj(machine))
@@ -84,9 +84,9 @@ func (r *HetznerBareMetalRemediationReconciler) Reconcile(ctx context.Context, r
 
 	if err := r.Get(ctx, key, bareMetalMachine); err != nil {
 		if apierrors.IsNotFound(err) {
-			return ctrl.Result{}, nil
+			return reconcile.Result{}, nil
 		}
-		return ctrl.Result{}, err
+		return reconcile.Result{}, err
 	}
 
 	log = log.WithValues("HetznerBareMetalMachine", klog.KObj(bareMetalMachine))
@@ -95,12 +95,12 @@ func (r *HetznerBareMetalRemediationReconciler) Reconcile(ctx context.Context, r
 	cluster, err := util.GetClusterFromMetadata(ctx, r.Client, machine.ObjectMeta)
 	if err != nil {
 		log.Info("Machine is missing cluster label or cluster does not exist")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	if annotations.IsPaused(cluster, bareMetalMachine) {
 		log.Info("HCloudMachine or linked Cluster is marked as paused. Won't reconcile")
-		return ctrl.Result{}, nil
+		return reconcile.Result{}, nil
 	}
 
 	log = log.WithValues("Cluster", klog.KObj(cluster))
@@ -129,7 +129,7 @@ func (r *HetznerBareMetalRemediationReconciler) Reconcile(ctx context.Context, r
 		BareMetalRemediation: bareMetalRemediation,
 	})
 	if err != nil {
-		return reconcile.Result{}, errors.Errorf("failed to create scope: %+v", err)
+		return reconcile.Result{}, fmt.Errorf("failed to create scope: %w", err)
 	}
 
 	// Always close the scope when exiting this function so we can persist any BareMetalRemediation changes.
@@ -158,7 +158,8 @@ func (r *HetznerBareMetalRemediationReconciler) reconcileNormal(ctx context.Cont
 
 	// reconcile bare metal remediation
 	if result, brk, err := breakReconcile(remediation.NewService(remediationScope).Reconcile(ctx)); brk {
-		return result, errors.Wrapf(err, "failed to reconcile server for BareMetalRemediation %s/%s", bareMetalRemediation.Namespace, bareMetalRemediation.Name)
+		return result, fmt.Errorf("failed to reconcile server for BareMetalRemediation %s/%s: %w",
+			bareMetalRemediation.Namespace, bareMetalRemediation.Name, err)
 	}
 
 	return reconcile.Result{}, nil
diff --git a/pkg/scope/baremetalmachine.go b/pkg/scope/baremetalmachine.go
index 4663e949..c2d7274c 100644
--- a/pkg/scope/baremetalmachine.go
+++ b/pkg/scope/baremetalmachine.go
@@ -18,12 +18,12 @@ package scope
 
 import (
 	"context"
+	"fmt"
 
 	"github.com/go-logr/logr"
 	"github.com/pkg/errors"
 	infrav1 "github.com/syself/cluster-api-provider-hetzner/api/v1beta1"
 	hcloudclient "github.com/syself/cluster-api-provider-hetzner/pkg/services/hcloud/client"
-	"k8s.io/klog/v2/klogr"
 	clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
 	capierrors "sigs.k8s.io/cluster-api/errors"
 	"sigs.k8s.io/cluster-api/util"
@@ -33,7 +33,7 @@ import (
 
 // BareMetalMachineScopeParams defines the input parameters used to create a new Scope.
 type BareMetalMachineScopeParams struct {
-	Logger           *logr.Logger
+	Logger           logr.Logger
 	Client           client.Client
 	Machine          *clusterv1.Machine
 	BareMetalMachine *infrav1.HetznerBareMetalMachine
@@ -45,24 +45,24 @@ type BareMetalMachineScopeParams struct {
 // This is meant to be called for each reconcile iteration.
 func NewBareMetalMachineScope(ctx context.Context, params BareMetalMachineScopeParams) (*BareMetalMachineScope, error) {
 	if params.Client == nil {
-		return nil, errors.New("cannot create baremetal host scope without client")
+		return nil, fmt.Errorf("cannot create baremetal host scope without client")
 	}
 	if params.Machine == nil {
-		return nil, errors.New("failed to generate new scope from nil Machine")
+		return nil, fmt.Errorf("failed to generate new scope from nil Machine")
 	}
 	if params.BareMetalMachine == nil {
-		return nil, errors.New("failed to generate new scope from nil BareMetalMachine")
+		return nil, fmt.Errorf("failed to generate new scope from nil BareMetalMachine")
 	}
 	if params.HetznerCluster == nil {
-		return nil, errors.New("failed to generate new scope from nil HetznerCluster")
+		return nil, fmt.Errorf("failed to generate new scope from nil HetznerCluster")
 	}
 	if params.HCloudClient == nil {
-		return nil, errors.New("failed to generate new scope from nil HCloudClient")
+		return nil, fmt.Errorf("failed to generate new scope from nil HCloudClient")
 	}
 
-	if params.Logger == nil {
-		logger := klogr.New()
-		params.Logger = &logger
+	var emptyLogger logr.Logger
+	if params.Logger == emptyLogger {
+		return nil, fmt.Errorf("failed to generate new scope from nil Logger")
 	}
 
 	patchHelper, err := patch.NewHelper(params.BareMetalMachine, params.Client)
@@ -83,7 +83,7 @@ func NewBareMetalMachineScope(ctx context.Context, params BareMetalMachineScopeP
 
 // BareMetalMachineScope defines the basic context for an actuator to operate upon.
 type BareMetalMachineScope struct {
-	*logr.Logger
+	logr.Logger
 	Client           client.Client
 	patchHelper      *patch.Helper
 	Machine          *clusterv1.Machine
diff --git a/pkg/scope/requeue_error.go b/pkg/scope/requeue_error.go
index d3f41fac..3109a423 100644
--- a/pkg/scope/requeue_error.go
+++ b/pkg/scope/requeue_error.go
@@ -42,6 +42,11 @@ func (e *RequeueAfterError) Error() string {
 	return fmt.Sprintf("requeue in: %s", e.RequeueAfter)
 }
 
+// Unwrap implements the error interface.
+func (e *RequeueAfterError) Unwrap() error {
+	return fmt.Errorf("%s", e.Error())
+}
+
 // GetRequeueAfter gets the duration to wait until the managed object is
 // requeued for further processing.
 func (e *RequeueAfterError) GetRequeueAfter() time.Duration {
diff --git a/pkg/services/baremetal/baremetal/baremetal.go b/pkg/services/baremetal/baremetal/baremetal.go
index 3d7ed21a..0a701660 100644
--- a/pkg/services/baremetal/baremetal/baremetal.go
+++ b/pkg/services/baremetal/baremetal/baremetal.go
@@ -19,6 +19,7 @@ package baremetal
 
 import (
 	"context"
+	"errors"
 	"fmt"
 	"math/rand"
 	"net"
@@ -28,11 +29,9 @@ import (
 
 	"github.com/go-logr/logr"
 	"github.com/hetznercloud/hcloud-go/hcloud"
-	"github.com/pkg/errors"
 	infrav1 "github.com/syself/cluster-api-provider-hetzner/api/v1beta1"
 	"github.com/syself/cluster-api-provider-hetzner/pkg/scope"
 	corev1 "k8s.io/api/core/v1"
-	clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
 	"k8s.io/apimachinery/pkg/api/equality"
 	apierrors "k8s.io/apimachinery/pkg/api/errors"
 	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
@@ -42,13 +41,14 @@ import (
 	kerrors "k8s.io/apimachinery/pkg/util/errors"
 	"k8s.io/client-go/tools/cache"
 	"k8s.io/utils/pointer"
-	capi "sigs.k8s.io/cluster-api/api/v1beta1"
+	clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
 	capierrors "sigs.k8s.io/cluster-api/errors"
 	"sigs.k8s.io/cluster-api/util/conditions"
 	"sigs.k8s.io/cluster-api/util/patch"
 	"sigs.k8s.io/cluster-api/util/record"
 	ctrl "sigs.k8s.io/controller-runtime"
 	"sigs.k8s.io/controller-runtime/pkg/client"
+	"sigs.k8s.io/controller-runtime/pkg/reconcile"
 )
 
 // TODO: Implement logic for removal of unpaid servers.
@@ -96,7 +96,7 @@ func (s *Service) Reconcile(ctx context.Context) (_ *ctrl.Result, err error) {
 			s.scope.BareMetalMachine,
 			infrav1.InstanceBootstrapReadyCondition,
 			infrav1.InstanceBootstrapNotReadyReason,
-			capi.ConditionSeverityInfo,
+			clusterv1.ConditionSeverityInfo,
 			"bootstrap not ready yet",
 		)
 		return &ctrl.Result{}, nil
@@ -155,7 +155,7 @@ func (s *Service) Delete(ctx context.Context) (_ *ctrl.Result, err error) {
 	if host != nil && host.Spec.ConsumerRef != nil {
 		if s.scope.IsControlPlane() && s.scope.HetznerCluster.Spec.ControlPlaneLoadBalancer.Enabled {
 			if err := s.deleteServerOfLoadBalancer(ctx, host); err != nil {
-				return nil, errors.Errorf("Error while deleting attached server of loadbalancer: %s", err)
+				return nil, fmt.Errorf("failed to delet attached server of loadbalancer: %w", err)
 			}
 		}
 
@@ -198,8 +198,8 @@ func (s *Service) Delete(ctx context.Context) (_ *ctrl.Result, err error) {
 			return nil, err
 		}
 
-		if host.Labels != nil && host.Labels[capi.ClusterLabelName] == s.scope.Machine.Spec.ClusterName {
-			delete(host.Labels, capi.ClusterLabelName)
+		if host.Labels != nil && host.Labels[clusterv1.ClusterLabelName] == s.scope.Machine.Spec.ClusterName {
+			delete(host.Labels, clusterv1.ClusterLabelName)
 		}
 
 		// Update the BMH object, if the errors are NotFound, do not return the
@@ -233,7 +233,7 @@ func removeMachineSpecsFromHost(host *infrav1.HetznerBareMetalHost) (updatedHost
 		host.Spec.Status.SSHSpec = nil
 		updatedHost = true
 	}
-	var emptySSHStatus = infrav1.SSHStatus{}
+	emptySSHStatus := infrav1.SSHStatus{}
 	if host.Spec.Status.SSHStatus != emptySSHStatus {
 		host.Spec.Status.SSHStatus = emptySSHStatus
 		updatedHost = true
@@ -250,7 +250,7 @@ func (s *Service) update(ctx context.Context, log logr.Logger) error {
 		return err
 	}
 	if host == nil {
-		return errors.Errorf("host not found for machine %s", s.scope.Machine.Name)
+		return fmt.Errorf("host not found for machine %s: %w", s.scope.Machine.Name, err)
 	}
 
 	if host.Spec.MaintenanceMode && s.scope.BareMetalMachine.Status.FailureReason == nil {
@@ -299,7 +299,7 @@ func (s *Service) update(ctx context.Context, log logr.Logger) error {
 
 	if s.scope.IsControlPlane() {
 		if err := s.reconcileLoadBalancerAttachment(ctx, host); err != nil {
-			return errors.Wrap(err, "failed to reconcile load balancer attachement")
+			return fmt.Errorf("failed to reconcile load balancer attachement: %w", err)
 		}
 	}
 
@@ -461,7 +461,7 @@ func (s *Service) associate(ctx context.Context, log logr.Logger) error {
 	if host.Labels == nil {
 		host.Labels = make(map[string]string)
 	}
-	host.Labels[capi.ClusterLabelName] = s.scope.Machine.Spec.ClusterName
+	host.Labels[clusterv1.ClusterLabelName] = s.scope.Machine.Spec.ClusterName
 
 	err = s.setHostConsumerRef(host)
 	if err != nil {
@@ -545,12 +545,12 @@ func (s *Service) chooseHost(ctx context.Context) (*infrav1.HetznerBareMetalHost
 	}
 
 	if err := s.scope.Client.List(ctx, &hosts, opts); err != nil {
-		return nil, nil, errors.Wrap(err, "failed to list hosts")
+		return nil, nil, fmt.Errorf("failed to list hosts: %w", err)
 	}
 
 	labelSelector, err := s.getLabelSelector()
 	if err != nil {
-		return nil, nil, errors.Wrap(err, "failed to get label selector")
+		return nil, nil, fmt.Errorf("failed to get label selector: %w", err)
 	}
 
 	availableHosts := []*infrav1.HetznerBareMetalHost{}
@@ -902,16 +902,17 @@ func (s *Service) checkMachineError(err error, errMessage string, errType capier
 	if err == nil {
 		return &ctrl.Result{}, nil
 	}
-	if requeueErr, ok := errors.Cause(err).(scope.HasRequeueAfterError); ok {
-		return &ctrl.Result{Requeue: true, RequeueAfter: requeueErr.GetRequeueAfter()}, nil
+	var requeueError *scope.RequeueAfterError
+	if ok := errors.As(err, &requeueError); ok {
+		return &reconcile.Result{Requeue: true, RequeueAfter: requeueError.GetRequeueAfter()}, nil
 	}
+
 	s.scope.SetError(errMessage, errType)
-	return &ctrl.Result{}, errors.Wrap(err, errMessage)
+	return &ctrl.Result{}, fmt.Errorf("%s: %w", errMessage, err)
 }
 
 // NotFoundError represents that an object was not found.
-type NotFoundError struct {
-}
+type NotFoundError struct{}
 
 // Error implements the error interface.
 func (e *NotFoundError) Error() string {


Test patch:
diff --git a/pkg/services/baremetal/baremetal/baremetal_suite_test.go b/pkg/services/baremetal/baremetal/baremetal_suite_test.go
index f055ae66..e368d8cc 100644
--- a/pkg/services/baremetal/baremetal/baremetal_suite_test.go
+++ b/pkg/services/baremetal/baremetal/baremetal_suite_test.go
@@ -27,9 +27,7 @@ import (
 	"sigs.k8s.io/controller-runtime/pkg/client"
 )
 
-var (
-	log = klogr.New()
-)
+var log = klogr.New()
 
 func TestBaremetal(t *testing.T) {
 	RegisterFailHandler(Fail)
@@ -42,7 +40,7 @@ func newTestService(
 ) *Service {
 	return &Service{
 		&scope.BareMetalMachineScope{
-			Logger:           &log,
+			Logger:           log,
 			Client:           client,
 			BareMetalMachine: bmMachine,
 		},