Kubernetes Informer

贺波
2023-12-01

Informer 使用方法见注释

package main

import (
	"fmt"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/client-go/tools/clientcmd"
	"time"
)

func main() {
	config, err := clientcmd.BuildConfigFromFlags("", clientcmd.RecommendedHomeFile)
	if err != nil {
		panic(fmt.Sprintf("failed to get k8s config err: %s", err.Error()))
	}
	cli, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(fmt.Sprintf("failed to get cli err: %s", err.Error()))
	}

	stopCh := make(chan struct{})
	defer close(stopCh)

	informerFactory := informers.NewSharedInformerFactoryWithOptions(cli, 0)

	// 添加 pod 和 service 的 informer
	informerFactory.Core().V1().Pods().Informer()
	informerFactory.Core().V1().Services().Informer()

	// 添加一些 informer 更新的 hook
	informerFactory.Core().V1().Pods().Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
		UpdateFunc: func(oldObj, newObj interface{}) {
			oldO := oldObj.(*v1.Pod)
			newO := newObj.(*v1.Pod)
			fmt.Printf("old: %s/%s\n", oldO.Namespace, oldO.Name)
			fmt.Printf("new: %s/%s\n", newO.Namespace, newO.Name)
		},
	})

	// 启动添加的所有 informer,等价于在每个 informer().Run(stopCh)
	informerFactory.Start(stopCh)

	// 同步到缓存中
	informerFactory.WaitForCacheSync(stopCh)

	// 通过 lister 去拿 informer 中的数据
	podLister := informerFactory.Core().V1().Pods().Lister()
	pods, err := podLister.List(labels.Everything())
	if err != nil {
		panic(fmt.Sprintf("failed to list pod, err: %s", err.Error()))
	}
	for _, pod := range pods {
		fmt.Printf("%s/%s\n", pod.Namespace, pod.Name)
	}

    // 等待 informer 事件
	time.Sleep(time.Hour)
}

 类似资料:

相关阅读

相关文章

相关问答