Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
tsuzu committed Jan 1, 2025
1 parent 8c1da40 commit 6b6e7c0
Showing 1 changed file with 13 additions and 6 deletions.
19 changes: 13 additions & 6 deletions internal/controller/incusmachine_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,13 @@ func (r *IncusMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request
if err != nil {
return ctrl.Result{}, err
}
deleted := !incusMachine.ObjectMeta.DeletionTimestamp.IsZero()
containsFinalizer := controllerutil.ContainsFinalizer(incusMachine, infrav1alpha1.MachineFinalizer)

if deleted && !containsFinalizer {
// Return early since the object is being deleted and doesn't have the finalizer.
return ctrl.Result{}, nil
}
// Always attempt to Patch the IncusMachine object and status after each reconciliation.
defer func() {
if err := patchIncusMachine(ctx, patchHelper, incusMachine); err != nil {
Expand All @@ -154,9 +161,14 @@ func (r *IncusMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request

log.Info("Reconciling IncusMachine")

// Handle deleted machines
if deleted {
return r.reconcileDelete(ctx, incusCluster, machine, incusMachine)
}

// Add finalizer first if not set to avoid the race condition between init and delete.
// Note: Finalizers in general can only be added when the deletionTimestamp is not set.
if incusMachine.ObjectMeta.DeletionTimestamp.IsZero() && !controllerutil.ContainsFinalizer(incusMachine, infrav1alpha1.MachineFinalizer) {
if !containsFinalizer {
log.Info("Adding finalizer for IncusMachine")

controllerutil.AddFinalizer(incusMachine, infrav1alpha1.MachineFinalizer)
Expand All @@ -165,11 +177,6 @@ func (r *IncusMachineReconciler) Reconcile(ctx context.Context, req ctrl.Request
}, nil
}

// Handle deleted machines
if !incusMachine.ObjectMeta.DeletionTimestamp.IsZero() {
return r.reconcileDelete(ctx, incusCluster, machine, incusMachine)
}

// Handle non-deleted machines
return r.reconcileNormal(ctx, cluster, incusCluster, machine, incusMachine)
}
Expand Down

0 comments on commit 6b6e7c0

Please sign in to comment.