1
0
Files
monitor/tests/informer/informer.go
dragonflylee 696f6ba425 update demo
Signed-off-by: dragonflylee <dragonflylee@outlook.com>
2023-12-22 16:55:35 +08:00

53 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package main
import (
"context"
"flag"
"log"
"path/filepath"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
)
func main() {
var kubeconfig string
flag.StringVar(&kubeconfig, "kubeconfig", filepath.Join(homedir.HomeDir(), ".kube", "config"), "(optional) absolute path to the kubeconfig file")
flag.Parse()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
AddPod := func(obj interface{}) {
}
DeletePod := func(obj interface{}) {
}
UpdatePod := func(oldObj, newObj interface{}) {
}
clientset := kubernetes.NewForConfigOrDie(config)
// 基于GVK 操作资源,假设需要操作数十种不同资源时,我们需要为每一种资源实现各自的函数
podInformer := informers.NewSharedInformerFactory(clientset, 0).
Core().V1().Pods().Informer()
podInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: AddPod,
DeleteFunc: DeletePod,
UpdateFunc: UpdatePod,
})
// 启动informer
podInformer.Run(ctx.Done())
cache.WaitForCacheSync(ctx.Done(), podInformer.HasSynced)
// 此处没有使用workqueue但一般都是会用workqueue 增强处理逻辑的
}