Skip to content

Instantly share code, notes, and snippets.

@AdheipSingh
Created July 13, 2020 14:29
Show Gist options
  • Save AdheipSingh/d7d6e8aca77e71c1e4ce782389f3fd9d to your computer and use it in GitHub Desktop.
Save AdheipSingh/d7d6e8aca77e71c1e4ce782389f3fd9d to your computer and use it in GitHub Desktop.
CRD watcher using dyamic client ( not using queue ds )
package main
import (
"os"
"os/signal"
"github.com/sirupsen/logrus"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/dynamic/dynamicinformer"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
)
func main() {
cfg, err := restConfig()
if err != nil {
logrus.WithError(err).Fatal("could not get config")
}
dc, err := dynamic.NewForConfig(cfg)
if err != nil {
logrus.WithError(err).Fatal("could not generate dynamic client for config")
}
virtualServiceGVR := crd("zookeeper.pravega.io", "v1beta1", "zookeeperclusters")
f := dynamicinformer.NewFilteredDynamicSharedInformerFactory(dc, 0, "druid", nil)
i := f.ForResource(virtualServiceGVR)
stopCh := make(chan struct{})
go startWatching(stopCh, i.Informer())
sigCh := make(chan os.Signal, 0)
signal.Notify(sigCh, os.Kill, os.Interrupt)
<-sigCh
close(stopCh)
}
func restConfig() (*rest.Config, error) {
kubeCfg, err := rest.InClusterConfig()
if kubeconfig := os.Getenv("KUBECONFIG"); kubeconfig != "" {
kubeCfg, err = clientcmd.BuildConfigFromFlags("", kubeconfig)
}
if err != nil {
return nil, err
}
return kubeCfg, nil
}
func startWatching(stopCh <-chan struct{}, s cache.SharedIndexInformer) {
handlers := cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
u := obj.(*unstructured.Unstructured)
logrus.WithFields(logrus.Fields{
"name": u.GetName(),
"namespace": u.GetNamespace(),
"labels": u.GetLabels(),
}).Info("received add event!")
},
UpdateFunc: func(oldObj, obj interface{}) {
logrus.Info("received update event!")
},
DeleteFunc: func(obj interface{}) {
logrus.Info("received delete event!")
},
}
s.AddEventHandler(handlers)
s.Run(stopCh)
}
func crd(group, version, resource string) schema.GroupVersionResource {
return schema.GroupVersionResource{
Group: group,
Version: version,
Resource: resource,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment