k8s sharedIndexInformer机制

sharedIndexInformer的run函数解析

func (s *sharedIndexInformer) Run(stopCh <-chan struct{}) {
   defer utilruntime.HandleCrash()

   fifo := cache.NewDeltaFIFO(cache.MetaNamespaceKeyFunc, nil, s.indexer)

   cfg := &Config{
      Queue:            fifo,
      ListerWatcher:    s.listerWatcher,
      ObjectType:       s.objectType,
      FullResyncPeriod: s.fullResyncPeriod,
      RetryOnError:     false,

      Process: s.HandleDeltas,
   }

   func() {
      s.startedLock.Lock()
      defer s.startedLock.Unlock()

      s.controller = New(cfg)
      s.started = true
   }()

   s.processor.run(stopCh)
   s.controller.Run(stopCh)
}

//controler中的run回新建一个watcher用于监听资源,并将监听到的资源存入reflector的store里面c.config.Queue

func (c *Controller) Run(stopCh <-chan struct{}) {
   defer utilruntime.HandleCrash()
   r := cache.NewReflector(
      c.config.ListerWatcher,
      c.config.ObjectType,
      c.config.Queue,
      c.config.FullResyncPeriod,
   )

   c.reflectorMutex.Lock()
   c.reflector = r
   c.reflectorMutex.Unlock()

   r.RunUntil(stopCh)
//这里进行loop处理,监控config的queue里面,发现有资源,则pop出来然后调用config的Process函数
   wait.Until(c.processLoop, time.Second, stopCh)

}
cfg := &Config{
   Queue:            fifo,
   ListerWatcher:    s.listerWatcher,
   ObjectType:       s.objectType,
   FullResyncPeriod: s.fullResyncPeriod,
   RetryOnError:     false,

   Process: s.HandleDeltas,
}
//处理函数其实就是接受obj资源,然后根据操作类型更新indexer里存入的值,滴啊用processor去发布obj给注册的listener去进行处理
func (s *sharedIndexInformer) HandleDeltas(obj interface{}) error {
   // from oldest to newest
   for _, d := range obj.(cache.Deltas) {
      switch d.Type {
      case cache.Sync, cache.Added, cache.Updated:
         if old, exists, err := s.indexer.Get(d.Object); err == nil && exists {
            if err := s.indexer.Update(d.Object); err != nil {
               return err
            }
            s.processor.distribute(updateNotification{oldObj: old, newObj: d.Object})
         } else {
            if err := s.indexer.Add(d.Object); err != nil {
               return err
            }
            s.processor.distribute(addNotification{newObj: d.Object})
         }
      case cache.Deleted:
         if err := s.indexer.Delete(d.Object); err != nil {
            return err
         }
         s.processor.distribute(deleteNotification{oldObj: d.Object})
      }
   }
   return nil
}

 

所以综上,数据结构中的indexer是真正用来存储资源的,而controler对应的store是queue(创建reflexer watch资源然后等待watch事件,存入controler queue中共后续消费)进行将资源传入informer对象,然后informer对象消费各个资源(存入indexer,分发给listener)。listener就是各个模块注册对于informer的handler.

 

func (p *sharedProcessor) run(stopCh <-chan struct{}) {
   for _, listener := range p.listeners {
     //run就是各个模块消费资源
      go listener.run(stopCh)
    //pop就是监控没有消费的资源,如果存在没有消费的资源就一个一个的发送给run,其去消费
      go listener.pop(stopCh)
   }
}

你可能感兴趣的:(k8s)