controller.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package framework
  14. import (
  15. "sync"
  16. "time"
  17. "k8s.io/kubernetes/pkg/client/cache"
  18. "k8s.io/kubernetes/pkg/runtime"
  19. utilruntime "k8s.io/kubernetes/pkg/util/runtime"
  20. "k8s.io/kubernetes/pkg/util/wait"
  21. )
  22. // Config contains all the settings for a Controller.
  23. type Config struct {
  24. // The queue for your objects; either a cache.FIFO or
  25. // a cache.DeltaFIFO. Your Process() function should accept
  26. // the output of this Oueue's Pop() method.
  27. cache.Queue
  28. // Something that can list and watch your objects.
  29. cache.ListerWatcher
  30. // Something that can process your objects.
  31. Process ProcessFunc
  32. // The type of your objects.
  33. ObjectType runtime.Object
  34. // Reprocess everything at least this often.
  35. // Note that if it takes longer for you to clear the queue than this
  36. // period, you will end up processing items in the order determined
  37. // by cache.FIFO.Replace(). Currently, this is random. If this is a
  38. // problem, we can change that replacement policy to append new
  39. // things to the end of the queue instead of replacing the entire
  40. // queue.
  41. FullResyncPeriod time.Duration
  42. // If true, when Process() returns an error, re-enqueue the object.
  43. // TODO: add interface to let you inject a delay/backoff or drop
  44. // the object completely if desired. Pass the object in
  45. // question to this interface as a parameter.
  46. RetryOnError bool
  47. }
  48. // ProcessFunc processes a single object.
  49. type ProcessFunc func(obj interface{}) error
  50. // Controller is a generic controller framework.
  51. type Controller struct {
  52. config Config
  53. reflector *cache.Reflector
  54. reflectorMutex sync.RWMutex
  55. }
  56. // TODO make the "Controller" private, and convert all references to use ControllerInterface instead
  57. type ControllerInterface interface {
  58. Run(stopCh <-chan struct{})
  59. HasSynced() bool
  60. }
  61. // New makes a new Controller from the given Config.
  62. func New(c *Config) *Controller {
  63. ctlr := &Controller{
  64. config: *c,
  65. }
  66. return ctlr
  67. }
  68. // Run begins processing items, and will continue until a value is sent down stopCh.
  69. // It's an error to call Run more than once.
  70. // Run blocks; call via go.
  71. func (c *Controller) Run(stopCh <-chan struct{}) {
  72. defer utilruntime.HandleCrash()
  73. r := cache.NewReflector(
  74. c.config.ListerWatcher,
  75. c.config.ObjectType,
  76. c.config.Queue,
  77. c.config.FullResyncPeriod,
  78. )
  79. c.reflectorMutex.Lock()
  80. c.reflector = r
  81. c.reflectorMutex.Unlock()
  82. r.RunUntil(stopCh)
  83. wait.Until(c.processLoop, time.Second, stopCh)
  84. }
  85. // Returns true once this controller has completed an initial resource listing
  86. func (c *Controller) HasSynced() bool {
  87. return c.config.Queue.HasSynced()
  88. }
  89. // Requeue adds the provided object back into the queue if it does not already exist.
  90. func (c *Controller) Requeue(obj interface{}) error {
  91. return c.config.Queue.AddIfNotPresent(cache.Deltas{
  92. cache.Delta{
  93. Type: cache.Sync,
  94. Object: obj,
  95. },
  96. })
  97. }
  98. // processLoop drains the work queue.
  99. // TODO: Consider doing the processing in parallel. This will require a little thought
  100. // to make sure that we don't end up processing the same object multiple times
  101. // concurrently.
  102. func (c *Controller) processLoop() {
  103. for {
  104. obj, err := c.config.Queue.Pop(cache.PopProcessFunc(c.config.Process))
  105. if err != nil {
  106. if c.config.RetryOnError {
  107. // This is the safe way to re-enqueue.
  108. c.config.Queue.AddIfNotPresent(obj)
  109. }
  110. }
  111. }
  112. }
  113. // ResourceEventHandler can handle notifications for events that happen to a
  114. // resource. The events are informational only, so you can't return an
  115. // error.
  116. // * OnAdd is called when an object is added.
  117. // * OnUpdate is called when an object is modified. Note that oldObj is the
  118. // last known state of the object-- it is possible that several changes
  119. // were combined together, so you can't use this to see every single
  120. // change. OnUpdate is also called when a re-list happens, and it will
  121. // get called even if nothing changed. This is useful for periodically
  122. // evaluating or syncing something.
  123. // * OnDelete will get the final state of the item if it is known, otherwise
  124. // it will get an object of type cache.DeletedFinalStateUnknown. This can
  125. // happen if the watch is closed and misses the delete event and we don't
  126. // notice the deletion until the subsequent re-list.
  127. type ResourceEventHandler interface {
  128. OnAdd(obj interface{})
  129. OnUpdate(oldObj, newObj interface{})
  130. OnDelete(obj interface{})
  131. }
  132. // ResourceEventHandlerFuncs is an adaptor to let you easily specify as many or
  133. // as few of the notification functions as you want while still implementing
  134. // ResourceEventHandler.
  135. type ResourceEventHandlerFuncs struct {
  136. AddFunc func(obj interface{})
  137. UpdateFunc func(oldObj, newObj interface{})
  138. DeleteFunc func(obj interface{})
  139. }
  140. // OnAdd calls AddFunc if it's not nil.
  141. func (r ResourceEventHandlerFuncs) OnAdd(obj interface{}) {
  142. if r.AddFunc != nil {
  143. r.AddFunc(obj)
  144. }
  145. }
  146. // OnUpdate calls UpdateFunc if it's not nil.
  147. func (r ResourceEventHandlerFuncs) OnUpdate(oldObj, newObj interface{}) {
  148. if r.UpdateFunc != nil {
  149. r.UpdateFunc(oldObj, newObj)
  150. }
  151. }
  152. // OnDelete calls DeleteFunc if it's not nil.
  153. func (r ResourceEventHandlerFuncs) OnDelete(obj interface{}) {
  154. if r.DeleteFunc != nil {
  155. r.DeleteFunc(obj)
  156. }
  157. }
  158. // DeletionHandlingMetaNamespaceKeyFunc checks for
  159. // cache.DeletedFinalStateUnknown objects before calling
  160. // cache.MetaNamespaceKeyFunc.
  161. func DeletionHandlingMetaNamespaceKeyFunc(obj interface{}) (string, error) {
  162. if d, ok := obj.(cache.DeletedFinalStateUnknown); ok {
  163. return d.Key, nil
  164. }
  165. return cache.MetaNamespaceKeyFunc(obj)
  166. }
  167. // NewInformer returns a cache.Store and a controller for populating the store
  168. // while also providing event notifications. You should only used the returned
  169. // cache.Store for Get/List operations; Add/Modify/Deletes will cause the event
  170. // notifications to be faulty.
  171. //
  172. // Parameters:
  173. // * lw is list and watch functions for the source of the resource you want to
  174. // be informed of.
  175. // * objType is an object of the type that you expect to receive.
  176. // * resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
  177. // calls, even if nothing changed). Otherwise, re-list will be delayed as
  178. // long as possible (until the upstream source closes the watch or times out,
  179. // or you stop the controller).
  180. // * h is the object you want notifications sent to.
  181. //
  182. func NewInformer(
  183. lw cache.ListerWatcher,
  184. objType runtime.Object,
  185. resyncPeriod time.Duration,
  186. h ResourceEventHandler,
  187. ) (cache.Store, *Controller) {
  188. // This will hold the client state, as we know it.
  189. clientState := cache.NewStore(DeletionHandlingMetaNamespaceKeyFunc)
  190. // This will hold incoming changes. Note how we pass clientState in as a
  191. // KeyLister, that way resync operations will result in the correct set
  192. // of update/delete deltas.
  193. fifo := cache.NewDeltaFIFO(cache.MetaNamespaceKeyFunc, nil, clientState)
  194. cfg := &Config{
  195. Queue: fifo,
  196. ListerWatcher: lw,
  197. ObjectType: objType,
  198. FullResyncPeriod: resyncPeriod,
  199. RetryOnError: false,
  200. Process: func(obj interface{}) error {
  201. // from oldest to newest
  202. for _, d := range obj.(cache.Deltas) {
  203. switch d.Type {
  204. case cache.Sync, cache.Added, cache.Updated:
  205. if old, exists, err := clientState.Get(d.Object); err == nil && exists {
  206. if err := clientState.Update(d.Object); err != nil {
  207. return err
  208. }
  209. h.OnUpdate(old, d.Object)
  210. } else {
  211. if err := clientState.Add(d.Object); err != nil {
  212. return err
  213. }
  214. h.OnAdd(d.Object)
  215. }
  216. case cache.Deleted:
  217. if err := clientState.Delete(d.Object); err != nil {
  218. return err
  219. }
  220. h.OnDelete(d.Object)
  221. }
  222. }
  223. return nil
  224. },
  225. }
  226. return clientState, New(cfg)
  227. }
  228. // NewIndexerInformer returns a cache.Indexer and a controller for populating the index
  229. // while also providing event notifications. You should only used the returned
  230. // cache.Index for Get/List operations; Add/Modify/Deletes will cause the event
  231. // notifications to be faulty.
  232. //
  233. // Parameters:
  234. // * lw is list and watch functions for the source of the resource you want to
  235. // be informed of.
  236. // * objType is an object of the type that you expect to receive.
  237. // * resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
  238. // calls, even if nothing changed). Otherwise, re-list will be delayed as
  239. // long as possible (until the upstream source closes the watch or times out,
  240. // or you stop the controller).
  241. // * h is the object you want notifications sent to.
  242. //
  243. func NewIndexerInformer(
  244. lw cache.ListerWatcher,
  245. objType runtime.Object,
  246. resyncPeriod time.Duration,
  247. h ResourceEventHandler,
  248. indexers cache.Indexers,
  249. ) (cache.Indexer, *Controller) {
  250. // This will hold the client state, as we know it.
  251. clientState := cache.NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, indexers)
  252. // This will hold incoming changes. Note how we pass clientState in as a
  253. // KeyLister, that way resync operations will result in the correct set
  254. // of update/delete deltas.
  255. fifo := cache.NewDeltaFIFO(cache.MetaNamespaceKeyFunc, nil, clientState)
  256. cfg := &Config{
  257. Queue: fifo,
  258. ListerWatcher: lw,
  259. ObjectType: objType,
  260. FullResyncPeriod: resyncPeriod,
  261. RetryOnError: false,
  262. Process: func(obj interface{}) error {
  263. // from oldest to newest
  264. for _, d := range obj.(cache.Deltas) {
  265. switch d.Type {
  266. case cache.Sync, cache.Added, cache.Updated:
  267. if old, exists, err := clientState.Get(d.Object); err == nil && exists {
  268. if err := clientState.Update(d.Object); err != nil {
  269. return err
  270. }
  271. h.OnUpdate(old, d.Object)
  272. } else {
  273. if err := clientState.Add(d.Object); err != nil {
  274. return err
  275. }
  276. h.OnAdd(d.Object)
  277. }
  278. case cache.Deleted:
  279. if err := clientState.Delete(d.Object); err != nil {
  280. return err
  281. }
  282. h.OnDelete(d.Object)
  283. }
  284. }
  285. return nil
  286. },
  287. }
  288. return clientState, New(cfg)
  289. }