Skip to content

Commit 3d97937

Browse files
committed
fix: cascase deletion for AG -> AFBinding
1 parent ec35e4f commit 3d97937

File tree

1 file changed

+62
-114
lines changed

1 file changed

+62
-114
lines changed

internal/controller/addressgroupbinding_controller.go

Lines changed: 62 additions & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ import (
2424
"time"
2525

2626
apierrors "k8s.io/apimachinery/pkg/api/errors"
27-
"k8s.io/apimachinery/pkg/api/meta"
2827
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2928
"k8s.io/apimachinery/pkg/runtime"
3029
"k8s.io/apimachinery/pkg/types"
@@ -182,65 +181,24 @@ func (r *AddressGroupBindingReconciler) reconcileNormal(ctx context.Context, bin
182181
}
183182
if err := r.Get(ctx, addressGroupKey, addressGroup); err != nil {
184183
if apierrors.IsNotFound(err) {
185-
// Check if we already have a condition for AddressGroupNotFound with the same generation
186-
var existingCondition *metav1.Condition
187-
for i := range binding.Status.Conditions {
188-
if binding.Status.Conditions[i].Type == netguardv1alpha1.ConditionReady &&
189-
binding.Status.Conditions[i].Reason == "AddressGroupNotFound" &&
190-
binding.Status.Conditions[i].ObservedGeneration == binding.Generation {
191-
existingCondition = &binding.Status.Conditions[i]
192-
break
193-
}
194-
}
195-
196-
// If condition already exists with the same generation, update with detailed message and don't requeue
197-
if existingCondition != nil {
198-
logger.Info("AddressGroup not found, not requeuing until resource changes",
199-
"addressGroupName", addressGroupRef.GetName(),
200-
"addressGroupNamespace", addressGroupNamespace)
201-
202-
// Update the message with more detailed information
203-
meta.SetStatusCondition(&binding.Status.Conditions, metav1.Condition{
204-
Type: netguardv1alpha1.ConditionReady,
205-
Status: metav1.ConditionFalse,
206-
Reason: "AddressGroupNotFound",
207-
Message: fmt.Sprintf("AddressGroup %s not found in namespace %s. This binding will not be reconciled until the AddressGroup is created or the resource is modified.",
208-
addressGroupRef.GetName(), addressGroupNamespace),
209-
ObservedGeneration: binding.Generation,
210-
LastTransitionTime: existingCondition.LastTransitionTime,
211-
})
212-
213-
if err := UpdateStatusWithRetry(ctx, r.Client, binding, DefaultMaxRetries); err != nil {
214-
logger.Error(err, "Failed to update AddressGroupBinding status")
215-
return ctrl.Result{}, err
216-
}
217-
218-
// Don't requeue
219-
return ctrl.Result{}, nil
220-
}
221-
222-
// First time seeing this issue or generation changed, set condition and requeue once
223-
logger.Info("AddressGroup not found, will requeue once to update status",
184+
logger.Info("AddressGroup not found, deleting AddressGroupBinding to maintain consistency",
224185
"addressGroupName", addressGroupRef.GetName(),
225-
"addressGroupNamespace", addressGroupNamespace)
226-
227-
meta.SetStatusCondition(&binding.Status.Conditions, metav1.Condition{
228-
Type: netguardv1alpha1.ConditionReady,
229-
Status: metav1.ConditionFalse,
230-
Reason: "AddressGroupNotFound",
231-
Message: fmt.Sprintf("AddressGroup %s not found in namespace %s. This binding will be reconciled once more to update status.",
232-
addressGroupRef.GetName(), addressGroupNamespace),
233-
ObservedGeneration: binding.Generation,
234-
LastTransitionTime: metav1.Now(),
235-
})
186+
"addressGroupNamespace", addressGroupNamespace,
187+
"binding", binding.GetName())
236188

237-
if err := UpdateStatusWithRetry(ctx, r.Client, binding, DefaultMaxRetries); err != nil {
238-
logger.Error(err, "Failed to update AddressGroupBinding status")
189+
// Delete the binding since its referenced AddressGroup no longer exists
190+
if err := r.Delete(ctx, binding); err != nil {
191+
logger.Error(err, "Failed to delete AddressGroupBinding after AddressGroup deletion",
192+
"addressGroup", addressGroupRef.GetName(),
193+
"binding", binding.GetName())
239194
return ctrl.Result{}, err
240195
}
241196

242-
// Requeue after a short time to update the status with the final message
243-
return ctrl.Result{RequeueAfter: time.Second * 5}, nil
197+
logger.Info("Successfully initiated deletion of AddressGroupBinding",
198+
"addressGroup", addressGroupRef.GetName(),
199+
"binding", binding.GetName())
200+
201+
return ctrl.Result{}, nil
244202
}
245203
logger.Error(err, "Failed to get AddressGroup")
246204
return ctrl.Result{}, err
@@ -343,7 +301,18 @@ func (r *AddressGroupBindingReconciler) reconcileNormal(ctx context.Context, bin
343301
"addressGroup", fmt.Sprintf("%s/%s", addressGroup.Kind, addressGroup.Name),
344302
"addressGroupUID", addressGroup.UID)
345303

346-
binding.OwnerReferences = append(binding.OwnerReferences, agOwnerRef)
304+
// Remove existing owner references for the same AddressGroup (by Kind+Name+APIVersion)
305+
var updatedOwnerRefs []metav1.OwnerReference
306+
for _, ref := range binding.GetOwnerReferences() {
307+
if !(ref.Kind == agOwnerRef.Kind &&
308+
ref.Name == agOwnerRef.Name &&
309+
ref.APIVersion == agOwnerRef.APIVersion) {
310+
updatedOwnerRefs = append(updatedOwnerRefs, ref)
311+
}
312+
}
313+
// Add the new owner reference
314+
updatedOwnerRefs = append(updatedOwnerRefs, agOwnerRef)
315+
binding.OwnerReferences = updatedOwnerRefs
347316
ownerRefsUpdated = true
348317
}
349318

@@ -424,18 +393,14 @@ func (r *AddressGroupBindingReconciler) reconcileNormal(ctx context.Context, bin
424393
logger.Info("Ports have changed, updating ServicePortsRef",
425394
"service", fmt.Sprintf("%s/%s", sp.GetNamespace(), sp.GetName()))
426395

427-
// Create a copy for patching
428396
original := portMapping.DeepCopy()
429-
430-
// Update the ports
431397
portMapping.AccessPorts.Items[i].Ports = servicePortsRef.Ports
432-
433-
// Apply patch with retry
434398
patch := client.MergeFrom(original)
435399
if err := PatchWithRetry(ctx, r.Client, portMapping, patch, DefaultMaxRetries); err != nil {
436400
logger.Error(err, "Failed to update AddressGroupPortMapping.AccessPorts")
437401
return ctrl.Result{}, err
438402
}
403+
439404
logger.Info("Successfully updated Service ports in AddressGroupPortMapping",
440405
"service", service.GetName(),
441406
"addressGroup", addressGroupRef.GetName())
@@ -454,11 +419,7 @@ func (r *AddressGroupBindingReconciler) reconcileNormal(ctx context.Context, bin
454419

455420
// Create a copy for patching
456421
original := portMapping.DeepCopy()
457-
458-
// Add the service to the list
459422
portMapping.AccessPorts.Items = append(portMapping.AccessPorts.Items, servicePortsRef)
460-
461-
// Apply patch with retry
462423
patch := client.MergeFrom(original)
463424
if err := PatchWithRetry(ctx, r.Client, portMapping, patch, DefaultMaxRetries); err != nil {
464425
logger.Error(err, "Failed to add Service to AddressGroupPortMapping.AccessPorts")
@@ -490,22 +451,6 @@ func (r *AddressGroupBindingReconciler) reconcileNormal(ctx context.Context, bin
490451
"namespace", binding.Namespace,
491452
"generation", binding.Generation,
492453
"resourceVersion", binding.ResourceVersion)
493-
494-
// TEMPORARY-DEBUG-CODE: Final state logging for problematic resources
495-
if binding.Name == "dynamic-2rx8z" || binding.Name == "dynamic-7dls7" ||
496-
binding.Name == "dynamic-fb5qw" || binding.Name == "dynamic-g6jfj" ||
497-
binding.Name == "dynamic-jd2b7" || binding.Name == "dynamic-lsjlt" {
498-
499-
logger.Info("TEMPORARY-DEBUG-CODE: Final state of problematic binding after successful reconciliation",
500-
"name", binding.Name,
501-
"namespace", binding.Namespace,
502-
"generation", binding.Generation,
503-
"resourceVersion", binding.ResourceVersion,
504-
"finalizers", binding.Finalizers,
505-
"ownerReferences", formatOwnerReferences(binding.OwnerReferences),
506-
"conditions", formatConditions(binding.Status.Conditions))
507-
}
508-
509454
return ctrl.Result{}, nil
510455
}
511456

@@ -518,23 +463,6 @@ func (r *AddressGroupBindingReconciler) reconcileDelete(ctx context.Context, bin
518463
"finalizers", binding.Finalizers,
519464
"conditions", formatConditions(binding.Status.Conditions))
520465

521-
// TEMPORARY-DEBUG-CODE: Detailed logging for problematic resources being deleted
522-
if binding.Name == "dynamic-2rx8z" || binding.Name == "dynamic-7dls7" ||
523-
binding.Name == "dynamic-fb5qw" || binding.Name == "dynamic-g6jfj" ||
524-
binding.Name == "dynamic-jd2b7" || binding.Name == "dynamic-lsjlt" {
525-
526-
logger.Info("TEMPORARY-DEBUG-CODE: Detailed state of problematic binding being deleted",
527-
"name", binding.Name,
528-
"namespace", binding.Namespace,
529-
"generation", binding.Generation,
530-
"resourceVersion", binding.ResourceVersion,
531-
"finalizers", binding.Finalizers,
532-
"ownerReferences", formatOwnerReferences(binding.OwnerReferences),
533-
"serviceRef", formatObjectReference(binding.Spec.ServiceRef),
534-
"addressGroupRef", formatNamespacedObjectReference(binding.Spec.AddressGroupRef),
535-
"conditions", formatConditions(binding.Status.Conditions))
536-
}
537-
538466
// 1. Remove AddressGroup from Service.AddressGroups
539467
serviceRef := binding.Spec.ServiceRef
540468
service := &netguardv1alpha1.Service{}
@@ -683,19 +611,6 @@ func (r *AddressGroupBindingReconciler) reconcileDelete(ctx context.Context, bin
683611
"name", binding.GetName(),
684612
"namespace", binding.GetNamespace())
685613

686-
// TEMPORARY-DEBUG-CODE: Final state logging for problematic resources being deleted
687-
if binding.Name == "dynamic-2rx8z" || binding.Name == "dynamic-7dls7" ||
688-
binding.Name == "dynamic-fb5qw" || binding.Name == "dynamic-g6jfj" ||
689-
binding.Name == "dynamic-jd2b7" || binding.Name == "dynamic-lsjlt" {
690-
691-
logger.Info("TEMPORARY-DEBUG-CODE: Final state of problematic binding after successful deletion",
692-
"name", binding.Name,
693-
"namespace", binding.Namespace,
694-
"generation", binding.Generation,
695-
"resourceVersion", binding.ResourceVersion,
696-
"finalizers", binding.Finalizers)
697-
}
698-
699614
return ctrl.Result{}, nil
700615
}
701616

@@ -721,20 +636,34 @@ func setCondition(binding *netguardv1alpha1.AddressGroupBinding, conditionType s
721636
}
722637
}
723638

724-
// Condition not found, append it
725639
binding.Status.Conditions = append(binding.Status.Conditions, condition)
726640
}
727641

728642
// containsOwnerReference checks if the list of owner references contains a reference with the same UID
729643
func containsOwnerReference(refs []metav1.OwnerReference, ref metav1.OwnerReference) bool {
730644
for _, r := range refs {
731645
if r.UID == ref.UID {
646+
// Если BlockOwnerDeletion отличается, считаем что нужно обновить
647+
if !equalBoolPtr(r.BlockOwnerDeletion, ref.BlockOwnerDeletion) {
648+
return false
649+
}
732650
return true
733651
}
734652
}
735653
return false
736654
}
737655

656+
// equalBoolPtr сравнивает два указателя на bool
657+
func equalBoolPtr(a, b *bool) bool {
658+
if a == nil && b == nil {
659+
return true
660+
}
661+
if a == nil || b == nil {
662+
return false
663+
}
664+
return *a == *b
665+
}
666+
738667
// formatConditions formats a slice of conditions into a readable string
739668
func formatConditions(conditions []metav1.Condition) string {
740669
var result []string
@@ -832,19 +761,34 @@ func (r *AddressGroupBindingReconciler) findBindingsForAddressGroup(ctx context.
832761
return nil
833762
}
834763

764+
logger := log.FromContext(ctx)
765+
logger.Info("Finding bindings for AddressGroup",
766+
"addressGroup", addressGroup.GetName(),
767+
"namespace", addressGroup.GetNamespace())
768+
835769
// Get all AddressGroupBinding
836770
bindingList := &netguardv1alpha1.AddressGroupBindingList{}
837771
if err := r.List(ctx, bindingList); err != nil {
772+
logger.Error(err, "Failed to list AddressGroupBindings")
838773
return nil
839774
}
840775

841776
var requests []reconcile.Request
842777

843778
// Filter bindings that reference this address group
844779
for _, binding := range bindingList.Items {
780+
// Resolve the namespace for the AddressGroupRef
781+
resolvedNamespace := v1alpha1.ResolveNamespace(binding.Spec.AddressGroupRef.GetNamespace(), binding.GetNamespace())
782+
845783
if binding.Spec.AddressGroupRef.GetName() == addressGroup.GetName() &&
846-
(binding.Spec.AddressGroupRef.GetNamespace() == addressGroup.GetNamespace() ||
847-
binding.Spec.AddressGroupRef.GetNamespace() == "") {
784+
resolvedNamespace == addressGroup.GetNamespace() {
785+
786+
logger.Info("Found binding that references this AddressGroup",
787+
"binding", binding.GetName(),
788+
"bindingNamespace", binding.GetNamespace(),
789+
"addressGroupRef", binding.Spec.AddressGroupRef.GetName(),
790+
"resolvedNamespace", resolvedNamespace)
791+
848792
requests = append(requests, reconcile.Request{
849793
NamespacedName: types.NamespacedName{
850794
Name: binding.GetName(),
@@ -854,6 +798,10 @@ func (r *AddressGroupBindingReconciler) findBindingsForAddressGroup(ctx context.
854798
}
855799
}
856800

801+
logger.Info("Found bindings for AddressGroup",
802+
"addressGroup", addressGroup.GetName(),
803+
"bindingsCount", len(requests))
804+
857805
return requests
858806
}
859807

0 commit comments

Comments
 (0)