@@ -32,6 +32,7 @@ import (
32
32
"sigs.k8s.io/controller-runtime/pkg/builder"
33
33
"sigs.k8s.io/controller-runtime/pkg/client"
34
34
"sigs.k8s.io/controller-runtime/pkg/controller"
35
+ "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
35
36
"sigs.k8s.io/controller-runtime/pkg/handler"
36
37
37
38
infrav1 "sigs.k8s.io/cluster-api-provider-packet/api/v1beta1"
@@ -103,7 +104,14 @@ func (r *PacketClusterReconciler) Reconcile(ctx context.Context, req ctrl.Reques
103
104
104
105
// Handle deleted clusters
105
106
if ! cluster .DeletionTimestamp .IsZero () {
106
- return r .reconcileDelete (ctx , clusterScope )
107
+ return ctrl.Result {}, r .reconcileDelete (ctx , clusterScope )
108
+ }
109
+
110
+ // Add finalizer first if not set to avoid the race condition between init and delete.
111
+ // Note: Finalizers in general can only be added when the deletionTimestamp is not set.
112
+ if ! controllerutil .ContainsFinalizer (packetcluster , infrav1 .ClusterFinalizer ) {
113
+ controllerutil .AddFinalizer (packetcluster , infrav1 .ClusterFinalizer )
114
+ return ctrl.Result {}, nil
107
115
}
108
116
109
117
err = r .reconcileNormal (ctx , clusterScope )
@@ -178,7 +186,7 @@ func (r *PacketClusterReconciler) reconcileNormal(ctx context.Context, clusterSc
178
186
return nil
179
187
}
180
188
181
- func (r * PacketClusterReconciler ) reconcileDelete (ctx context.Context , clusterScope * scope.ClusterScope ) (ctrl. Result , error ) {
189
+ func (r * PacketClusterReconciler ) reconcileDelete (ctx context.Context , clusterScope * scope.ClusterScope ) error {
182
190
log := ctrl .LoggerFrom (ctx ).WithValues ("cluster" , clusterScope .Cluster .Name )
183
191
log .Info ("Reconciling PacketCluster Deletion" )
184
192
@@ -190,15 +198,17 @@ func (r *PacketClusterReconciler) reconcileDelete(ctx context.Context, clusterSc
190
198
lb := emlb .NewEMLB (r .PacketClient .GetConfig ().DefaultHeader ["X-Auth-Token" ], packetCluster .Spec .ProjectID , packetCluster .Spec .Metro )
191
199
192
200
if err := lb .DeleteLoadBalancer (ctx , clusterScope ); err != nil {
193
- fmt .Println ( "It's ok!" )
201
+ return fmt .Errorf ( "failed to delete load balancer: %w" , err )
194
202
}
195
203
}
196
204
// Initially I created this handler to remove an elastic IP when a cluster
197
205
// gets delete, but it does not sound like a good idea. It is better to
198
206
// leave to the users the ability to decide if they want to keep and resign
199
207
// the IP or if they do not need it anymore
200
208
201
- return ctrl.Result {}, nil
209
+ // Cluster is deleted so remove the finalizer.
210
+ controllerutil .RemoveFinalizer (packetCluster , infrav1 .ClusterFinalizer )
211
+ return nil
202
212
}
203
213
204
214
func (r * PacketClusterReconciler ) SetupWithManager (ctx context.Context , mgr ctrl.Manager , options controller.Options ) error {
0 commit comments