Skip to content

Commit

Permalink
using predicate in the controller watchers to filter out irrelevant e…
Browse files Browse the repository at this point in the history
…vents

Signed-off-by: Moath Qasim <moad.qassem@gmail.com>
  • Loading branch information
moadqassem committed Apr 4, 2023
1 parent 094aa53 commit d727107
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
6 changes: 5 additions & 1 deletion pkg/controller/tinkerbell_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (

"go.uber.org/zap"

"github.com/moadqassem/kubetink/pkg/util"

appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
Expand Down Expand Up @@ -41,10 +43,12 @@ func Add(mgr manager.Manager, log *zap.SugaredLogger, clusterDNS, namespace stri
&appsv1.Deployment{},
&rbacv1.Role{},
&rbacv1.RoleBinding{},
&rbacv1.ClusterRole{},
&rbacv1.ClusterRoleBinding{},
}

for _, t := range typesToWatch {
if err := c.Watch(&source.Kind{Type: t}, &handler.EnqueueRequestForObject{}); err != nil {
if err := c.Watch(&source.Kind{Type: t}, &handler.EnqueueRequestForObject{}, util.ByNamespace(namespace)); err != nil {
return fmt.Errorf("failed to create watch for %T: %w", t, err)
}
}
Expand Down
35 changes: 35 additions & 0 deletions pkg/util/predicate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package util

import (
ctrlruntimeclient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/predicate"
)

// Factory returns a predicate func that applies the given filter function
// on CREATE, UPDATE and DELETE events. For UPDATE events, the filter is applied
// to both the old and new object and OR's the result.
func Factory(filter func(o ctrlruntimeclient.Object) bool) predicate.Funcs {
if filter == nil {
return predicate.Funcs{}
}

return predicate.Funcs{
CreateFunc: func(e event.CreateEvent) bool {
return filter(e.Object)
},
UpdateFunc: func(e event.UpdateEvent) bool {
return filter(e.ObjectOld) || filter(e.ObjectNew)
},
DeleteFunc: func(e event.DeleteEvent) bool {
return filter(e.Object)
},
}
}

// ByNamespace returns a predicate func that only includes objects in the given namespace.
func ByNamespace(namespace string) predicate.Funcs {
return Factory(func(o ctrlruntimeclient.Object) bool {
return o.GetNamespace() == namespace
})
}

0 comments on commit d727107

Please # to comment.