diff --git a/pkg/controller/node/predict.go b/pkg/controller/node/predict.go index aa841b5f..7460724f 100644 --- a/pkg/controller/node/predict.go +++ b/pkg/controller/node/predict.go @@ -18,6 +18,7 @@ package node import ( corev1 "k8s.io/api/core/v1" + "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/predicate" @@ -30,37 +31,32 @@ type predicateForNodeEvent struct { // Create returns true if the Create event should be processed func (p *predicateForNodeEvent) Create(e event.CreateEvent) bool { - node, ok := e.Object.(*corev1.Node) - if !ok { - return false - } - return isECSNode(node) + return predicateNode(e.Object) } // Delete returns true if the Delete event should be processed func (p *predicateForNodeEvent) Delete(e event.DeleteEvent) bool { - node, ok := e.Object.(*corev1.Node) - if !ok { - return false - } - return isECSNode(node) + return predicateNode(e.Object) } // Update returns true if the Update event should be processed func (p *predicateForNodeEvent) Update(e event.UpdateEvent) bool { - node, ok := e.ObjectNew.(*corev1.Node) - if !ok { - return false - } - return isECSNode(node) + return predicateNode(e.ObjectNew) } // Generic returns true if the Generic event should be processed func (p *predicateForNodeEvent) Generic(e event.GenericEvent) bool { - node, ok := e.Object.(*corev1.Node) + return predicateNode(e.Object) +} + +func predicateNode(o client.Object) bool { + node, ok := o.(*corev1.Node) if !ok { return false } + if node.Labels[corev1.LabelTopologyRegion] == "" { + return false + } return isECSNode(node) } diff --git a/pkg/controller/node/predict_test.go b/pkg/controller/node/predict_test.go index 1effade2..64b03ceb 100644 --- a/pkg/controller/node/predict_test.go +++ b/pkg/controller/node/predict_test.go @@ -5,6 +5,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "sigs.k8s.io/controller-runtime/pkg/client" ) func Test_isECSNode(t *testing.T) { @@ -60,3 +61,49 @@ func Test_isECSNode(t *testing.T) { }) } } + +func Test_predicateNode(t *testing.T) { + type args struct { + o client.Object + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "non node", + args: args{ + o: &corev1.Pod{}, + }, + want: false, + }, + { + name: "empty node", + args: args{ + o: &corev1.Node{}, + }, + want: false, + }, + { + name: "normal node", + args: args{ + o: &corev1.Node{ + ObjectMeta: metav1.ObjectMeta{ + Labels: map[string]string{ + "topology.kubernetes.io/region": "cn-hangzhou", + }, + }, + }, + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := predicateNode(tt.args.o); got != tt.want { + t.Errorf("predicateNode() = %v, want %v", got, tt.want) + } + }) + } +}