watchcontroller.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. package costmodel
  2. import (
  3. "fmt"
  4. "reflect"
  5. "time"
  6. "k8s.io/klog"
  7. v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  8. "k8s.io/apimachinery/pkg/fields"
  9. rt "k8s.io/apimachinery/pkg/runtime"
  10. "k8s.io/apimachinery/pkg/util/runtime"
  11. "k8s.io/apimachinery/pkg/util/wait"
  12. "k8s.io/client-go/rest"
  13. "k8s.io/client-go/tools/cache"
  14. "k8s.io/client-go/util/workqueue"
  15. )
  16. // Type alias for a receiver func
  17. type WatchHandler = func(interface{})
  18. // WatchController defines a contract for an object which watches a specific resource set for
  19. // add, updates, and removals
  20. type WatchController interface {
  21. // Run starts the watching process
  22. Run(int, chan struct{})
  23. // GetAll returns all of the resources
  24. GetAll() []interface{}
  25. // SetUpdateHandler sets a specific handler for adding/updating individual resources
  26. SetUpdateHandler(WatchHandler) WatchController
  27. // SetRemovedHandler sets a specific handler for removing individual resources
  28. SetRemovedHandler(WatchHandler) WatchController
  29. }
  30. // CachingWatchController composites the watching behavior and a cache to ensure that all
  31. // up to date resources are readily available
  32. type CachingWatchController struct {
  33. indexer cache.Indexer
  34. queue workqueue.RateLimitingInterface
  35. informer cache.Controller
  36. resource string
  37. resourceType string
  38. updateHandler WatchHandler
  39. removeHandler WatchHandler
  40. }
  41. func NewCachingWatcher(restClient rest.Interface, resource string, resourceType rt.Object, namespace string, fieldSelector fields.Selector) WatchController {
  42. resourceCache := cache.NewListWatchFromClient(restClient, resource, namespace, fieldSelector)
  43. queue := workqueue.NewRateLimitingQueue(workqueue.DefaultControllerRateLimiter())
  44. indexer, informer := cache.NewIndexerInformer(resourceCache, resourceType, 0, cache.ResourceEventHandlerFuncs{
  45. AddFunc: func(obj interface{}) {
  46. key, err := cache.MetaNamespaceKeyFunc(obj)
  47. if err == nil {
  48. queue.Add(key)
  49. }
  50. },
  51. UpdateFunc: func(old interface{}, new interface{}) {
  52. key, err := cache.MetaNamespaceKeyFunc(new)
  53. if err == nil {
  54. queue.Add(key)
  55. }
  56. },
  57. DeleteFunc: func(obj interface{}) {
  58. // IndexerInformer uses a delta queue, therefore for deletes we have to use this
  59. // key function.
  60. key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj)
  61. if err == nil {
  62. queue.Add(key)
  63. }
  64. },
  65. }, cache.Indexers{})
  66. return &CachingWatchController{
  67. indexer: indexer,
  68. queue: queue,
  69. informer: informer,
  70. resource: resource,
  71. resourceType: reflect.TypeOf(resourceType).String(),
  72. }
  73. }
  74. func (c *CachingWatchController) GetAll() []interface{} {
  75. return c.indexer.List()
  76. }
  77. func (c *CachingWatchController) SetUpdateHandler(handler WatchHandler) WatchController {
  78. c.updateHandler = handler
  79. return c
  80. }
  81. func (c *CachingWatchController) SetRemovedHandler(handler WatchHandler) WatchController {
  82. c.removeHandler = handler
  83. return c
  84. }
  85. func (c *CachingWatchController) processNextItem() bool {
  86. // Wait until there is a new item in the working queue
  87. key, quit := c.queue.Get()
  88. if quit {
  89. return false
  90. }
  91. // Tell the queue that we are done with processing this key. This unblocks the key for other workers
  92. // This allows safe parallel processing because two pods with the same key are never processed in
  93. // parallel.
  94. defer c.queue.Done(key)
  95. // Invoke the method containing the business logic
  96. err := c.handle(key.(string))
  97. // Handle the error if something went wrong during the execution of the business logic
  98. c.handleErr(err, key)
  99. return true
  100. }
  101. // handle is the business logic of the controller.
  102. func (c *CachingWatchController) handle(key string) error {
  103. obj, exists, err := c.indexer.GetByKey(key)
  104. if err != nil {
  105. klog.Errorf("Fetching %s with key %s from store failed with %v", c.resourceType, key, err)
  106. return err
  107. }
  108. if !exists {
  109. klog.V(3).Infof("Removed %s for key: %s\n", c.resourceType, key)
  110. if c.removeHandler != nil {
  111. c.removeHandler(key)
  112. }
  113. } else {
  114. klog.V(3).Infof("Updated %s: %s\n", c.resourceType, obj.(v1.Object).GetName())
  115. if c.updateHandler != nil {
  116. c.updateHandler(obj)
  117. }
  118. }
  119. return nil
  120. }
  121. // handleErr checks if an error happened and makes sure we will retry later.
  122. func (c *CachingWatchController) handleErr(err error, key interface{}) {
  123. if err == nil {
  124. // Forget about the #AddRateLimited history of the key on every successful synchronization.
  125. // This ensures that future processing of updates for this key is not delayed because of
  126. // an outdated error history.
  127. c.queue.Forget(key)
  128. return
  129. }
  130. // This controller retries 5 times if something goes wrong. After that, it stops trying.
  131. if c.queue.NumRequeues(key) < 5 {
  132. klog.V(3).Infof("Error syncing %s %v: %v", c.resourceType, key, err)
  133. // Re-enqueue the key rate limited. Based on the rate limiter on the
  134. // queue and the re-enqueue history, the key will be processed later again.
  135. c.queue.AddRateLimited(key)
  136. return
  137. }
  138. c.queue.Forget(key)
  139. // Report to an external entity that, even after several retries, we could not successfully process this key
  140. runtime.HandleError(err)
  141. klog.Infof("Dropping %s %q out of the queue: %v", c.resourceType, key, err)
  142. }
  143. func (c *CachingWatchController) Run(threadiness int, stopCh chan struct{}) {
  144. defer runtime.HandleCrash()
  145. // Let the workers stop when we are done
  146. defer c.queue.ShutDown()
  147. klog.V(3).Infof("Starting %s controller", c.resourceType)
  148. go c.informer.Run(stopCh)
  149. // Wait for all involved caches to be synced, before processing items from the queue is started
  150. if !cache.WaitForCacheSync(stopCh, c.informer.HasSynced) {
  151. runtime.HandleError(fmt.Errorf("Timed out waiting for caches to sync"))
  152. return
  153. }
  154. for i := 0; i < threadiness; i++ {
  155. go wait.Until(c.runWorker, time.Second, stopCh)
  156. }
  157. <-stopCh
  158. klog.V(3).Infof("Stopping %s controller", c.resourceType)
  159. }
  160. func (c *CachingWatchController) runWorker() {
  161. for c.processNextItem() {
  162. }
  163. }