@@ -35,6 +35,7 @@ import (
35
35
"sigs.k8s.io/cluster-api/internal/controllers/topology/machineset"
36
36
"sigs.k8s.io/cluster-api/util"
37
37
"sigs.k8s.io/cluster-api/util/annotations"
38
+ "sigs.k8s.io/cluster-api/util/finalizers"
38
39
"sigs.k8s.io/cluster-api/util/labels"
39
40
"sigs.k8s.io/cluster-api/util/patch"
40
41
"sigs.k8s.io/cluster-api/util/predicates"
@@ -124,6 +125,17 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Re
124
125
log = log .WithValues ("Cluster" , klog .KRef (md .Namespace , md .Spec .ClusterName ))
125
126
ctx = ctrl .LoggerInto (ctx , log )
126
127
128
+ // Return early if the MachineDeployment is not topology owned.
129
+ if ! labels .IsTopologyOwned (md ) {
130
+ log .Info (fmt .Sprintf ("Reconciliation is skipped because the MachineDeployment does not have the %q label" , clusterv1 .ClusterTopologyOwnedLabel ))
131
+ return ctrl.Result {}, nil
132
+ }
133
+
134
+ // Add finalizer first if not set to avoid the race condition between init and delete.
135
+ if finalizerAdded , err := finalizers .EnsureFinalizer (ctx , r .Client , md , clusterv1 .MachineDeploymentTopologyFinalizer ); err != nil || finalizerAdded {
136
+ return ctrl.Result {}, err
137
+ }
138
+
127
139
cluster , err := util .GetClusterByName (ctx , r .Client , md .Namespace , md .Spec .ClusterName )
128
140
if err != nil {
129
141
return ctrl.Result {}, err
@@ -135,12 +147,6 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Re
135
147
return ctrl.Result {}, nil
136
148
}
137
149
138
- // Return early if the MachineDeployment is not topology owned.
139
- if ! labels .IsTopologyOwned (md ) {
140
- log .Info (fmt .Sprintf ("Reconciliation is skipped because the MachineDeployment does not have the %q label" , clusterv1 .ClusterTopologyOwnedLabel ))
141
- return ctrl.Result {}, nil
142
- }
143
-
144
150
// Create a patch helper to add or remove the finalizer from the MachineDeployment.
145
151
patchHelper , err := patch .NewHelper (md , r .Client )
146
152
if err != nil {
@@ -157,13 +163,6 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (_ ctrl.Re
157
163
return ctrl.Result {}, r .reconcileDelete (ctx , md )
158
164
}
159
165
160
- // Add finalizer first if not set to avoid the race condition between init and delete.
161
- // Note: Finalizers in general can only be added when the deletionTimestamp is not set.
162
- if ! controllerutil .ContainsFinalizer (md , clusterv1 .MachineDeploymentTopologyFinalizer ) {
163
- controllerutil .AddFinalizer (md , clusterv1 .MachineDeploymentTopologyFinalizer )
164
- return ctrl.Result {}, nil
165
- }
166
-
167
166
return ctrl.Result {}, nil
168
167
}
169
168
0 commit comments