Skip to content

Commit 81c6d05

Browse files
committed
Add IgnoreSameContentPredicate to filter updates
This predicate filters updates for a managed object to avoid triggering of reconciliation loop if the content of the object was not changed. This helps to fix the issue of never-ending synchronization. Signed-off-by: Yury Kulazhenkov <[email protected]>
1 parent 07672e5 commit 81c6d05

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

controllers/nicclusterpolicy_controller.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ func (r *NicClusterPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error {
280280
ctl = ctl.Watches(ws[i], &handler.EnqueueRequestForOwner{
281281
IsController: true,
282282
OwnerType: &mellanoxv1alpha1.NicClusterPolicy{},
283-
})
283+
}, builder.WithPredicates(IgnoreSameContentPredicate{}))
284284
}
285285

286286
return ctl.Complete(r)

controllers/predicate.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,11 @@ limitations under the License.
1717
package controllers
1818

1919
import (
20+
"reflect"
21+
22+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
23+
"k8s.io/apimachinery/pkg/runtime"
24+
"sigs.k8s.io/controller-runtime/pkg/client"
2025
"sigs.k8s.io/controller-runtime/pkg/event"
2126
"sigs.k8s.io/controller-runtime/pkg/predicate"
2227

@@ -36,3 +41,35 @@ func (p MlnxLabelChangedPredicate) hasMlnxLabel(labels map[string]string) bool {
3641
func (p MlnxLabelChangedPredicate) Update(e event.UpdateEvent) bool {
3742
return p.hasMlnxLabel(e.ObjectOld.GetLabels()) != p.hasMlnxLabel(e.ObjectNew.GetLabels())
3843
}
44+
45+
// IgnoreSameContentPredicate filters updates if old and new object are the same,
46+
// ignores ResourceVersion and ManagedFields while comparing
47+
type IgnoreSameContentPredicate struct {
48+
predicate.Funcs
49+
}
50+
51+
func (p IgnoreSameContentPredicate) Update(e event.UpdateEvent) bool {
52+
if e.ObjectOld == nil {
53+
return false
54+
}
55+
if e.ObjectNew == nil {
56+
return false
57+
}
58+
oldObj := e.ObjectOld.DeepCopyObject().(client.Object)
59+
newObj := e.ObjectNew.DeepCopyObject().(client.Object)
60+
// ignore resource version
61+
oldObj.SetResourceVersion("")
62+
newObj.SetResourceVersion("")
63+
// ignore managed fields
64+
oldObj.SetManagedFields([]metav1.ManagedFieldsEntry{})
65+
newObj.SetManagedFields([]metav1.ManagedFieldsEntry{})
66+
oldUnstr, err := runtime.DefaultUnstructuredConverter.ToUnstructured(oldObj)
67+
if err != nil {
68+
return false
69+
}
70+
newUnstr, err := runtime.DefaultUnstructuredConverter.ToUnstructured(newObj)
71+
if err != nil {
72+
return false
73+
}
74+
return !reflect.DeepEqual(oldUnstr, newUnstr)
75+
}

0 commit comments

Comments
 (0)