client-go workqueue demo
生活随笔
收集整理的這篇文章主要介紹了
client-go workqueue demo
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
鏈接地址:https://github.com/kubernetes/client-go
[root@wangjq examples]# tree . ├── create-update-delete-deployment │?? ├── main.go │?? └── README.md ├── dynamic-create-update-delete-deployment │?? ├── main.go │?? └── README.md ├── fake-client │?? ├── doc.go │?? ├── main_test.go │?? └── README.md ├── in-cluster-client-configuration │?? ├── Dockerfile │?? ├── main.go │?? └── README.md ├── leader-election │?? ├── main.go │?? └── README.md ├── out-of-cluster-client-configuration │?? ├── main.go │?? └── README.md ├── README.md └── workqueue├── main.go└── README.md?demo1
[root@wangjq workqueue]# cat main.go /* Copyright 2017 The Kubernetes Authors.Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */package mainimport ("flag""fmt""time""k8s.io/klog"v1 "k8s.io/api/core/v1"meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/apimachinery/pkg/fields""k8s.io/apimachinery/pkg/util/runtime""k8s.io/apimachinery/pkg/util/wait""k8s.io/client-go/kubernetes""k8s.io/client-go/tools/cache""k8s.io/client-go/tools/clientcmd""k8s.io/client-go/util/workqueue" )type Controller struct {indexer cache.Indexerqueue workqueue.RateLimitingInterfaceinformer cache.Controller }func NewController(queue workqueue.RateLimitingInterface, indexer cache.Indexer, informer cache.Controller) *Controller {return &Controller{informer: informer,indexer: indexer,queue: queue,} }func (c *Controller) processNextItem() bool {// Wait until there is a new item in the working queuekey, quit := c.queue.Get()if quit {return false}// Tell the queue that we are done with processing this key. This unblocks the key for other workers// This allows safe parallel processing because two pods with the same key are never processed in// parallel. defer c.queue.Done(key)// Invoke the method containing the business logicerr := c.syncToStdout(key.(string))// Handle the error if something went wrong during the execution of the business logic c.handleErr(err, key)return true }// syncToStdout is the business logic of the controller. In this controller it simply prints // information about the pod to stdout. In case an error happened, it has to simply return the error. // The retry logic should not be part of the business logic. func (c *Controller) syncToStdout(key string) error {obj, exists, err := c.indexer.GetByKey(key)if err != nil {klog.Errorf("Fetching object with key %s from store failed with %v", key, err)return err}if !exists {// Below we will warm up our cache with a Pod, so that we will see a delete for one podfmt.Printf("Pod %s does not exist anymore\n", key)} else {// Note that you also have to check the uid if you have a local controlled resource, which// is dependent on the actual instance, to detect that a Pod was recreated with the same namefmt.Printf("Sync/Add/Update for Pod %s\n", obj.(*v1.Pod).GetName())}return nil }// handleErr checks if an error happened and makes sure we will retry later. func (c *Controller) handleErr(err error, key interface{}) {if err == nil {// Forget about the #AddRateLimited history of the key on every successful synchronization.// This ensures that future processing of updates for this key is not delayed because of// an outdated error history. c.queue.Forget(key)return}// This controller retries 5 times if something goes wrong. After that, it stops trying.if c.queue.NumRequeues(key) < 5 {klog.Infof("Error syncing pod %v: %v", key, err)// Re-enqueue the key rate limited. Based on the rate limiter on the// queue and the re-enqueue history, the key will be processed later again. c.queue.AddRateLimited(key)return}c.queue.Forget(key)// Report to an external entity that, even after several retries, we could not successfully process this key runtime.HandleError(err)klog.Infof("Dropping pod %q out of the queue: %v", key, err) }func (c *Controller) Run(threadiness int, stopCh chan struct{}) {defer runtime.HandleCrash()// Let the workers stop when we are done defer c.queue.ShutDown()klog.Info("Starting Pod controller")go c.informer.Run(stopCh)// Wait for all involved caches to be synced, before processing items from the queue is startedif !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {runtime.HandleError(fmt.Errorf("Timed out waiting for caches to sync"))return}for i := 0; i < threadiness; i++ {go wait.Until(c.runWorker, time.Second, stopCh)}<-stopChklog.Info("Stopping Pod controller") }func (c *Controller) runWorker() {for c.processNextItem() {} }func main() {var kubeconfig stringvar master stringflag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")flag.StringVar(&master, "master", "", "master url")flag.Parse()// creates the connectionconfig, err := clientcmd.BuildConfigFromFlags(master, kubeconfig)if err != nil {klog.Fatal(err)}// creates the clientsetclientset, err := kubernetes.NewForConfig(config)if err != nil {klog.Fatal(err)}// create the pod watcherpodListWatcher := cache.NewListWatchFromClient(clientset.CoreV1().RESTClient(), "pods", v1.NamespaceDefault, fields.Everything())// create the workqueuequeue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())// Bind the workqueue to a cache with the help of an informer. This way we make sure that// whenever the cache is updated, the pod key is added to the workqueue.// Note that when we finally process the item from the workqueue, we might see a newer version// of the Pod than the version which was responsible for triggering the update.indexer, informer := cache.NewIndexerInformer(podListWatcher, &v1.Pod{}, 0, cache.ResourceEventHandlerFuncs{AddFunc: func(obj interface{}) {key, err := cache.MetaNamespaceKeyFunc(obj)if err == nil {queue.Add(key)}},UpdateFunc: func(old interface{}, new interface{}) {key, err := cache.MetaNamespaceKeyFunc(new)if err == nil {queue.Add(key)}},DeleteFunc: func(obj interface{}) {// IndexerInformer uses a delta queue, therefore for deletes we have to use this// key function.key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)if err == nil {queue.Add(key)}},}, cache.Indexers{})controller := NewController(queue, indexer, informer)// We can now warm up the cache for initial synchronization.// Let's suppose that we knew about a pod "mypod" on our last run, therefore add it to the cache.// If this pod is not there anymore, the controller will be notified about the removal after the// cache has synchronized.indexer.Add(&v1.Pod{ObjectMeta: meta_v1.ObjectMeta{Name: "mypod",Namespace: v1.NamespaceDefault,},})// Now let's start the controllerstop := make(chan struct{})defer close(stop)go controller.Run(1, stop)// Wait foreverselect {} }demo2:
package mainimport ("flag""k8s.io/client-go/kubernetes""k8s.io/client-go/util/workqueue""k8s.io/sample-controller/pkg/signals""k8s.io/client-go/tools/cache""k8s.io/client-go/tools/clientcmd""github.com/golang/glog""k8s.io/apimachinery/pkg/watch"metav1 "k8s.io/apimachinery/pkg/apis/meta/v1""k8s.io/apimachinery/pkg/runtime"utilruntime "k8s.io/apimachinery/pkg/util/runtime"apiv1 "k8s.io/api/core/v1""fmt""k8s.io/apimachinery/pkg/util/wait""time" )/* 控制器 */ type Controller struct {// 此控制器使用的客戶端 clientset kubernetes.Interface// 此控制器使用的工作隊(duì)列 queue workqueue.RateLimitingInterface// 此控制器使用的共享Informer,SharedIndexInformer可以維護(hù)緩存中對(duì)象的索引 informer cache.SharedIndexInformer }/* 主函數(shù) */ var (// 參數(shù)變量masterURL stringkubeconfig string ) // 啟動(dòng)控制器 func (c *Controller) Run(stopCh <-chan struct{}) {// 捕獲應(yīng)用程序崩潰并打印日志 defer utilruntime.HandleCrash()// 關(guān)閉隊(duì)列,從而導(dǎo)致Worker結(jié)束 defer c.queue.ShutDown()glog.Info("啟動(dòng)控制器……")// 運(yùn)行Informer go c.informer.Run(stopCh)// 在啟動(dòng)Worker之前,等待緩存同步完成if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {utilruntime.HandleError(fmt.Errorf("同步緩存超時(shí)"))return}glog.Info("緩存已經(jīng)同步,準(zhǔn)備啟動(dòng)Worker")// 循環(huán)執(zhí)行Worker,直到TERM wait.Until(c.runWorker, time.Second, stopCh) }// 啟動(dòng)Worker func (c *Controller) runWorker() {for c.processNextItem() {} }// Worker的邏輯框架 func (c *Controller) processNextItem() bool {// 最大重試次數(shù)maxRetries := 3// 獲取下一個(gè)元素,第2個(gè)出參提示隊(duì)列是否已經(jīng)關(guān)閉key, quit := c.queue.Get()if quit {return false}// 總是移除Key defer c.queue.Done(key)// 處理Keyerr := c.processItem(key.(string))if err == nil {// 處理成功,提示隊(duì)列不再跟蹤事件歷史 c.queue.Forget(key)} else if c.queue.NumRequeues(key) < maxRetries {glog.Errorf("處理%s事件失敗,準(zhǔn)備重試: %v", key, err)c.queue.AddRateLimited(key)} else {glog.Errorf("處理%s事件失敗,放棄: %v", key, err)c.queue.Forget(key)utilruntime.HandleError(err)}return true }// Worker核心邏輯 func (c *Controller) processItem(key string) error {glog.Infof("開始處理事件%s", key)// 根據(jù)Key獲取對(duì)象obj, exists, err := c.informer.GetIndexer().GetByKey(key)if err != nil {return fmt.Errorf("獲取對(duì)象%s失敗: %v", key, err)}fmt.Print(obj)if !exists {// 在這里處理對(duì)象刪除事件} else {// 在這里處理對(duì)象創(chuàng)建事件 }// 因?yàn)椴贿M(jìn)行Resync,不會(huì)有更新事件return nil }func main() {// 解析參數(shù),存入上述變量 flag.Parse()cfg, err := clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)if err != nil {glog.Fatalf("構(gòu)建kubeconfig失敗: %s", err.Error())}// 創(chuàng)建客戶端,Clientset是一系列K8S API的集合clientset, err := kubernetes.NewForConfig(cfg)if err != nil {glog.Fatalf("構(gòu)建clientset失敗: %s", err.Error())}// 信號(hào)處理通道,當(dāng)進(jìn)程接收到信號(hào)后,此通道可讀stopCh := signals.SetupSignalHandler()queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())informer := cache.NewSharedIndexInformer(&cache.ListWatch{ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {// 僅僅列出所有命名空間的Podreturn clientset.CoreV1().Pods(metav1.NamespaceAll).List(options)},WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {return clientset.CoreV1().Pods(metav1.NamespaceAll).Watch(options)},},&apiv1.Pod{},0, // 不進(jìn)行relistcache.Indexers{}, // map[string]IndexFunc )// 添加事件處理回調(diào),僅僅是簡(jiǎn)單的入隊(duì)informer.AddEventHandler(cache.ResourceEventHandlerFuncs{// 此結(jié)構(gòu)實(shí)現(xiàn)ResourceEventHandlerAddFunc: func(obj interface{}) {// 從對(duì)象中抽取Keykey, err := cache.MetaNamespaceKeyFunc(obj)if err == nil {queue.Add(key)}},DeleteFunc: func(obj interface{}) {key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)if err == nil {queue.Add(key)}},})// 構(gòu)建控制器對(duì)象ctrl := Controller{clientset,queue,informer,}// 啟動(dòng) ctrl.Run(stopCh) }?
轉(zhuǎn)載于:https://www.cnblogs.com/wangjq19920210/p/11551825.html
與50位技術(shù)專家面對(duì)面20年技術(shù)見證,附贈(zèng)技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的client-go workqueue demo的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: beego 快速入门
- 下一篇: 通过自定义资源扩展Kubernetes