I want to watch Kubernetes pod events for a certain application.
I went with NewSharedInformerFactoryWithOptions. I have added appropriate labels selector, But it is not getting filtered out. As I want to filter it using the label: 'app=nats-box'
Here is the code -
req, err := labels.NewRequirement("app", selection.Equals, []string{"nats-box"})
if err != nil {
log.Fatalf("error %s, bad requirement", err.Error())
}
selector := labels.NewSelector()
selector.Add(*req)
filteredFactory := informers.NewSharedInformerFactoryWithOptions(clientset, 0, informers.WithNamespace("default"), informers.WithTweakListOptions(func(options *metav1.ListOptions) {
options.LabelSelector = selector.String()
}))
podInformer := filteredFactory.Core().V1().Pods().Informer()
podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
fmt.Println("pod add")
name := obj.(*corev1.Pod).Name
labels := obj.(*corev1.Pod).Labels
fmt.Printf("pod Name: %s\nLabels - %v\n\n", name, labels)
})
I get the output for all the pods, the namespace is getting filtered but not the labels. Not able to figure out where I am making the mistake.
CodePudding user response:
You can directly provide the label string in the opts.LabelSelector
:
labelOptions := informers.WithTweakListOptions(func(opts *metav1.ListOptions) {
opts.LabelSelector = "app=nats-box"
})
factory := informers.NewSharedInformerFactoryWithOptions(clientset, 0, informers.WithNamespace("default") ,labelOptions)
informer := factory.Core().V1().Pods().Informer()
stopper := make(chan struct{})
defer close(stopper)
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
fmt.Println("pod add")
name := obj.(*corev1.Pod).Name
labels := obj.(*corev1.Pod).Labels
fmt.Printf("pod Name: %s\nLabels - %v\n\n", name, labels)
},
})
informer.Run(stopper)