Created
April 29, 2022 13:10
-
-
Save able8/85b28824857a9c438bfa0298ae3527d1 to your computer and use it in GitHub Desktop.
Informer Sample Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"log" | |
"path/filepath" | |
_ "k8s.io/client-go/plugin/pkg/client/auth" | |
v1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"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 | |
if home := homedir.HomeDir(); home != "" { | |
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file") | |
} else { | |
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file") | |
} | |
flag.Parse() | |
// Use the current context in kubeconfig | |
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig) | |
if err != nil { | |
panic(err) | |
} | |
// 创建 clientSet 对象,用于与Kubernetes API Server进行交互 | |
clientSet, err := kubernetes.NewForConfig(config) | |
if err != nil { | |
panic(err) | |
} | |
//创建stopCh对象,该对象用于在程序进程退出之前通知Informer提前退出,因为Informer是一个持久运行的 goroutine | |
stopCh := make(chan struct{}) | |
defer close(stopCh) | |
// Create InformerFactory | |
informerFactory := informers.NewSharedInformerFactory(clientSet, 0) | |
// Create pod informer by informerFactory | |
podInformer := informerFactory.Core().V1().Pods() | |
/* | |
为 Pod 资源添加资源事件回调方法,支持 AddFunc、UpdateFunc 及 DeleteFunc | |
- AddFunc: 当创建Pod资源对象时触发的事件回调方法。 | |
- UpdateFunc:当更新Pod资源对象时触发的事件回调方法。 | |
- DeleteFunc:当删除Pod资源对象时触发的事件回调方法。 | |
*/ | |
podInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ | |
AddFunc: func(obj interface{}) { | |
mObj := obj.(v1.Object) | |
log.Printf("New Pod Added to Store: %s", mObj.GetName()) | |
}, | |
UpdateFunc: func(oldObj, newObj interface{}) { | |
oObj := oldObj.(v1.Object) | |
nObj := newObj.(v1.Object) | |
log.Printf("%s Pod Updated to %s", oObj.GetName(), nObj.GetName()) | |
}, | |
DeleteFunc: func(obj interface{}) { | |
mObj := obj.(v1.Object) | |
log.Printf("Pod Deleted from Store: %s", mObj.GetName()) | |
}, | |
}) | |
podInformer.Informer().Run(stopCh) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment