什么是informers?
informers是k8s一种重要的通知机制, 通过list&watch来监听变更事.
示例代码:
监听deployment变化
import (
"fmt"
"time"
v1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/client/config"
)
func main() {
conf, err := config.GetConfig()
if err != nil {
fmt.Println("error")
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(conf)
if err != nil {
fmt.Println("error")
panic(err.Error())
}
//获取informers
informersFactory := informers.NewSharedInformerFactory(clientset, 30*time.Second)
//获取deployInformer
deployInformer := informersFactory.Apps().V1().Deployments()
informer := deployInformer.Informer()
deployLister := deployInformer.Lister()
if err != nil {
fmt.Println("error")
panic(err.Error())
}
informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: create,
UpdateFunc: update,
DeleteFunc: delete,
})
stopper := make(chan struct{})
defer close(stopper)
//开启list & watch 机制
informersFactory.Start(stopper)
//等待缓存队列更新
informersFactory.WaitForCacheSync(stopper)
deploys, err := deployLister.Deployments("default").List(labels.Everything())
if err != nil {
panic(err.Error())
}
for _, v := range deploys {
fmt.Println("deploy is ", v.Name)
}
<-stopper
}
func update(oldObj, newObj interface{}) {
fmt.Println("old ", oldObj.(*v1.Deployment).Name, "update replicas at", oldObj.(*v1.Deployment).Status.Replicas)
fmt.Println("new ", oldObj.(*v1.Deployment).Name, " update replicas at", newObj.(*v1.Deployment).Status.Replicas)
}
func delete(obj interface{}) {
fmt.Println("delete at ", obj.(*v1.Deployment).Name)
}
func create(obj interface{}) {
fmt.Println("create at ", obj.(*v1.Deployment).Name)
}
运行
新建一个deploy监听变化
控制日志,看见nginx已经被创建了,并且副本数已经从0改成1
更新deploy
$ kubectl edit deploy nginx
deployment.apps/nginx edited
删除deploy, 也被正常监听到了
总结:
list&watch是k8s动态更新通知的重要渠道, 我们不止可以监听k8s内置资源,也可以监听自定义资源.
注:k8内置资源对象大概以下几种
类别 | 名称 |
---|---|
资源对象 | Pod、ReplicaSet、ReplicationController、Deployment、StatefulSet、 DaemonSet、Job、CronJob、HorizontalPodAutoscaling、Node、 Namespace、Service、Ingress、Label、CustomResourceDefinition |
存储对象 | Volume、PersistentVolume、Secret、ConfigMap |
策略对象 | SecurityContext、ResourceQuota、LimitRange |
身份对象 | ServiceAccount、Role、ClusterRole |
Q.E.D.