controller.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 cache
  14. import (
  15. "sync"
  16. "time"
  17. "k8s.io/apimachinery/pkg/runtime"
  18. "k8s.io/apimachinery/pkg/util/clock"
  19. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  20. "k8s.io/apimachinery/pkg/util/wait"
  21. )
  22. // This file implements a low-level controller that is used in
  23. // sharedIndexInformer, which is an implementation of
  24. // SharedIndexInformer. Such informers, in turn, are key components
  25. // in the high level controllers that form the backbone of the
  26. // Kubernetes control plane. Look at those for examples, or the
  27. // example in
  28. // https://github.com/kubernetes/client-go/tree/master/examples/workqueue
  29. // .
  30. // Config contains all the settings for one of these low-level controllers.
  31. type Config struct {
  32. // The queue for your objects - has to be a DeltaFIFO due to
  33. // assumptions in the implementation. Your Process() function
  34. // should accept the output of this Queue's Pop() method.
  35. Queue
  36. // Something that can list and watch your objects.
  37. ListerWatcher
  38. // Something that can process a popped Deltas.
  39. Process ProcessFunc
  40. // ObjectType is an example object of the type this controller is
  41. // expected to handle. Only the type needs to be right, except
  42. // that when that is `unstructured.Unstructured` the object's
  43. // `"apiVersion"` and `"kind"` must also be right.
  44. ObjectType runtime.Object
  45. // FullResyncPeriod is the period at which ShouldResync is considered.
  46. FullResyncPeriod time.Duration
  47. // ShouldResync is periodically used by the reflector to determine
  48. // whether to Resync the Queue. If ShouldResync is `nil` or
  49. // returns true, it means the reflector should proceed with the
  50. // resync.
  51. ShouldResync ShouldResyncFunc
  52. // If true, when Process() returns an error, re-enqueue the object.
  53. // TODO: add interface to let you inject a delay/backoff or drop
  54. // the object completely if desired. Pass the object in
  55. // question to this interface as a parameter. This is probably moot
  56. // now that this functionality appears at a higher level.
  57. RetryOnError bool
  58. // Called whenever the ListAndWatch drops the connection with an error.
  59. WatchErrorHandler WatchErrorHandler
  60. }
  61. // ShouldResyncFunc is a type of function that indicates if a reflector should perform a
  62. // resync or not. It can be used by a shared informer to support multiple event handlers with custom
  63. // resync periods.
  64. type ShouldResyncFunc func() bool
  65. // ProcessFunc processes a single object.
  66. type ProcessFunc func(obj interface{}) error
  67. // `*controller` implements Controller
  68. type controller struct {
  69. config Config
  70. reflector *Reflector
  71. reflectorMutex sync.RWMutex
  72. clock clock.Clock
  73. }
  74. // Controller is a low-level controller that is parameterized by a
  75. // Config and used in sharedIndexInformer.
  76. type Controller interface {
  77. // Run does two things. One is to construct and run a Reflector
  78. // to pump objects/notifications from the Config's ListerWatcher
  79. // to the Config's Queue and possibly invoke the occasional Resync
  80. // on that Queue. The other is to repeatedly Pop from the Queue
  81. // and process with the Config's ProcessFunc. Both of these
  82. // continue until `stopCh` is closed.
  83. Run(stopCh <-chan struct{})
  84. // HasSynced delegates to the Config's Queue
  85. HasSynced() bool
  86. // LastSyncResourceVersion delegates to the Reflector when there
  87. // is one, otherwise returns the empty string
  88. LastSyncResourceVersion() string
  89. }
  90. // New makes a new Controller from the given Config.
  91. func New(c *Config) Controller {
  92. ctlr := &controller{
  93. config: *c,
  94. clock: &clock.RealClock{},
  95. }
  96. return ctlr
  97. }
  98. // Run begins processing items, and will continue until a value is sent down stopCh or it is closed.
  99. // It's an error to call Run more than once.
  100. // Run blocks; call via go.
  101. func (c *controller) Run(stopCh <-chan struct{}) {
  102. defer utilruntime.HandleCrash()
  103. go func() {
  104. <-stopCh
  105. c.config.Queue.Close()
  106. }()
  107. r := NewReflector(
  108. c.config.ListerWatcher,
  109. c.config.ObjectType,
  110. c.config.Queue,
  111. c.config.FullResyncPeriod,
  112. )
  113. r.ShouldResync = c.config.ShouldResync
  114. r.clock = c.clock
  115. if c.config.WatchErrorHandler != nil {
  116. r.watchErrorHandler = c.config.WatchErrorHandler
  117. }
  118. c.reflectorMutex.Lock()
  119. c.reflector = r
  120. c.reflectorMutex.Unlock()
  121. var wg wait.Group
  122. wg.StartWithChannel(stopCh, r.Run)
  123. wait.Until(c.processLoop, time.Second, stopCh)
  124. wg.Wait()
  125. }
  126. // Returns true once this controller has completed an initial resource listing
  127. func (c *controller) HasSynced() bool {
  128. return c.config.Queue.HasSynced()
  129. }
  130. func (c *controller) LastSyncResourceVersion() string {
  131. c.reflectorMutex.RLock()
  132. defer c.reflectorMutex.RUnlock()
  133. if c.reflector == nil {
  134. return ""
  135. }
  136. return c.reflector.LastSyncResourceVersion()
  137. }
  138. // processLoop drains the work queue.
  139. // TODO: Consider doing the processing in parallel. This will require a little thought
  140. // to make sure that we don't end up processing the same object multiple times
  141. // concurrently.
  142. //
  143. // TODO: Plumb through the stopCh here (and down to the queue) so that this can
  144. // actually exit when the controller is stopped. Or just give up on this stuff
  145. // ever being stoppable. Converting this whole package to use Context would
  146. // also be helpful.
  147. func (c *controller) processLoop() {
  148. for {
  149. obj, err := c.config.Queue.Pop(PopProcessFunc(c.config.Process))
  150. if err != nil {
  151. if err == ErrFIFOClosed {
  152. return
  153. }
  154. if c.config.RetryOnError {
  155. // This is the safe way to re-enqueue.
  156. c.config.Queue.AddIfNotPresent(obj)
  157. }
  158. }
  159. }
  160. }
  161. // ResourceEventHandler can handle notifications for events that
  162. // happen to a resource. The events are informational only, so you
  163. // can't return an error. The handlers MUST NOT modify the objects
  164. // received; this concerns not only the top level of structure but all
  165. // the data structures reachable from it.
  166. // * OnAdd is called when an object is added.
  167. // * OnUpdate is called when an object is modified. Note that oldObj is the
  168. // last known state of the object-- it is possible that several changes
  169. // were combined together, so you can't use this to see every single
  170. // change. OnUpdate is also called when a re-list happens, and it will
  171. // get called even if nothing changed. This is useful for periodically
  172. // evaluating or syncing something.
  173. // * OnDelete will get the final state of the item if it is known, otherwise
  174. // it will get an object of type DeletedFinalStateUnknown. This can
  175. // happen if the watch is closed and misses the delete event and we don't
  176. // notice the deletion until the subsequent re-list.
  177. type ResourceEventHandler interface {
  178. OnAdd(obj interface{})
  179. OnUpdate(oldObj, newObj interface{})
  180. OnDelete(obj interface{})
  181. }
  182. // ResourceEventHandlerFuncs is an adaptor to let you easily specify as many or
  183. // as few of the notification functions as you want while still implementing
  184. // ResourceEventHandler. This adapter does not remove the prohibition against
  185. // modifying the objects.
  186. type ResourceEventHandlerFuncs struct {
  187. AddFunc func(obj interface{})
  188. UpdateFunc func(oldObj, newObj interface{})
  189. DeleteFunc func(obj interface{})
  190. }
  191. // OnAdd calls AddFunc if it's not nil.
  192. func (r ResourceEventHandlerFuncs) OnAdd(obj interface{}) {
  193. if r.AddFunc != nil {
  194. r.AddFunc(obj)
  195. }
  196. }
  197. // OnUpdate calls UpdateFunc if it's not nil.
  198. func (r ResourceEventHandlerFuncs) OnUpdate(oldObj, newObj interface{}) {
  199. if r.UpdateFunc != nil {
  200. r.UpdateFunc(oldObj, newObj)
  201. }
  202. }
  203. // OnDelete calls DeleteFunc if it's not nil.
  204. func (r ResourceEventHandlerFuncs) OnDelete(obj interface{}) {
  205. if r.DeleteFunc != nil {
  206. r.DeleteFunc(obj)
  207. }
  208. }
  209. // FilteringResourceEventHandler applies the provided filter to all events coming
  210. // in, ensuring the appropriate nested handler method is invoked. An object
  211. // that starts passing the filter after an update is considered an add, and an
  212. // object that stops passing the filter after an update is considered a delete.
  213. // Like the handlers, the filter MUST NOT modify the objects it is given.
  214. type FilteringResourceEventHandler struct {
  215. FilterFunc func(obj interface{}) bool
  216. Handler ResourceEventHandler
  217. }
  218. // OnAdd calls the nested handler only if the filter succeeds
  219. func (r FilteringResourceEventHandler) OnAdd(obj interface{}) {
  220. if !r.FilterFunc(obj) {
  221. return
  222. }
  223. r.Handler.OnAdd(obj)
  224. }
  225. // OnUpdate ensures the proper handler is called depending on whether the filter matches
  226. func (r FilteringResourceEventHandler) OnUpdate(oldObj, newObj interface{}) {
  227. newer := r.FilterFunc(newObj)
  228. older := r.FilterFunc(oldObj)
  229. switch {
  230. case newer && older:
  231. r.Handler.OnUpdate(oldObj, newObj)
  232. case newer && !older:
  233. r.Handler.OnAdd(newObj)
  234. case !newer && older:
  235. r.Handler.OnDelete(oldObj)
  236. default:
  237. // do nothing
  238. }
  239. }
  240. // OnDelete calls the nested handler only if the filter succeeds
  241. func (r FilteringResourceEventHandler) OnDelete(obj interface{}) {
  242. if !r.FilterFunc(obj) {
  243. return
  244. }
  245. r.Handler.OnDelete(obj)
  246. }
  247. // DeletionHandlingMetaNamespaceKeyFunc checks for
  248. // DeletedFinalStateUnknown objects before calling
  249. // MetaNamespaceKeyFunc.
  250. func DeletionHandlingMetaNamespaceKeyFunc(obj interface{}) (string, error) {
  251. if d, ok := obj.(DeletedFinalStateUnknown); ok {
  252. return d.Key, nil
  253. }
  254. return MetaNamespaceKeyFunc(obj)
  255. }
  256. // NewInformer returns a Store and a controller for populating the store
  257. // while also providing event notifications. You should only used the returned
  258. // Store for Get/List operations; Add/Modify/Deletes will cause the event
  259. // notifications to be faulty.
  260. //
  261. // Parameters:
  262. // * lw is list and watch functions for the source of the resource you want to
  263. // be informed of.
  264. // * objType is an object of the type that you expect to receive.
  265. // * resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
  266. // calls, even if nothing changed). Otherwise, re-list will be delayed as
  267. // long as possible (until the upstream source closes the watch or times out,
  268. // or you stop the controller).
  269. // * h is the object you want notifications sent to.
  270. //
  271. func NewInformer(
  272. lw ListerWatcher,
  273. objType runtime.Object,
  274. resyncPeriod time.Duration,
  275. h ResourceEventHandler,
  276. ) (Store, Controller) {
  277. // This will hold the client state, as we know it.
  278. clientState := NewStore(DeletionHandlingMetaNamespaceKeyFunc)
  279. return clientState, newInformer(lw, objType, resyncPeriod, h, clientState)
  280. }
  281. // NewIndexerInformer returns a Indexer and a controller for populating the index
  282. // while also providing event notifications. You should only used the returned
  283. // Index for Get/List operations; Add/Modify/Deletes will cause the event
  284. // notifications to be faulty.
  285. //
  286. // Parameters:
  287. // * lw is list and watch functions for the source of the resource you want to
  288. // be informed of.
  289. // * objType is an object of the type that you expect to receive.
  290. // * resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
  291. // calls, even if nothing changed). Otherwise, re-list will be delayed as
  292. // long as possible (until the upstream source closes the watch or times out,
  293. // or you stop the controller).
  294. // * h is the object you want notifications sent to.
  295. // * indexers is the indexer for the received object type.
  296. //
  297. func NewIndexerInformer(
  298. lw ListerWatcher,
  299. objType runtime.Object,
  300. resyncPeriod time.Duration,
  301. h ResourceEventHandler,
  302. indexers Indexers,
  303. ) (Indexer, Controller) {
  304. // This will hold the client state, as we know it.
  305. clientState := NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, indexers)
  306. return clientState, newInformer(lw, objType, resyncPeriod, h, clientState)
  307. }
  308. // newInformer returns a controller for populating the store while also
  309. // providing event notifications.
  310. //
  311. // Parameters
  312. // * lw is list and watch functions for the source of the resource you want to
  313. // be informed of.
  314. // * objType is an object of the type that you expect to receive.
  315. // * resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
  316. // calls, even if nothing changed). Otherwise, re-list will be delayed as
  317. // long as possible (until the upstream source closes the watch or times out,
  318. // or you stop the controller).
  319. // * h is the object you want notifications sent to.
  320. // * clientState is the store you want to populate
  321. //
  322. func newInformer(
  323. lw ListerWatcher,
  324. objType runtime.Object,
  325. resyncPeriod time.Duration,
  326. h ResourceEventHandler,
  327. clientState Store,
  328. ) Controller {
  329. // This will hold incoming changes. Note how we pass clientState in as a
  330. // KeyLister, that way resync operations will result in the correct set
  331. // of update/delete deltas.
  332. fifo := NewDeltaFIFOWithOptions(DeltaFIFOOptions{
  333. KnownObjects: clientState,
  334. EmitDeltaTypeReplaced: true,
  335. })
  336. cfg := &Config{
  337. Queue: fifo,
  338. ListerWatcher: lw,
  339. ObjectType: objType,
  340. FullResyncPeriod: resyncPeriod,
  341. RetryOnError: false,
  342. Process: func(obj interface{}) error {
  343. // from oldest to newest
  344. for _, d := range obj.(Deltas) {
  345. switch d.Type {
  346. case Sync, Replaced, Added, Updated:
  347. if old, exists, err := clientState.Get(d.Object); err == nil && exists {
  348. if err := clientState.Update(d.Object); err != nil {
  349. return err
  350. }
  351. h.OnUpdate(old, d.Object)
  352. } else {
  353. if err := clientState.Add(d.Object); err != nil {
  354. return err
  355. }
  356. h.OnAdd(d.Object)
  357. }
  358. case Deleted:
  359. if err := clientState.Delete(d.Object); err != nil {
  360. return err
  361. }
  362. h.OnDelete(d.Object)
  363. }
  364. }
  365. return nil
  366. },
  367. }
  368. return New(cfg)
  369. }