controller.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. utilruntime "k8s.io/apimachinery/pkg/util/runtime"
  19. "k8s.io/apimachinery/pkg/util/wait"
  20. "k8s.io/client-go/util/clock"
  21. )
  22. // Config contains all the settings for a Controller.
  23. type Config struct {
  24. // The queue for your objects; either a FIFO or
  25. // a DeltaFIFO. Your Process() function should accept
  26. // the output of this Queue's Pop() method.
  27. Queue
  28. // Something that can list and watch your objects.
  29. 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 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. // ShouldResync, if specified, is invoked when the controller's reflector determines the next
  43. // periodic sync should occur. If this returns true, it means the reflector should proceed with
  44. // the resync.
  45. ShouldResync ShouldResyncFunc
  46. // If true, when Process() returns an error, re-enqueue the object.
  47. // TODO: add interface to let you inject a delay/backoff or drop
  48. // the object completely if desired. Pass the object in
  49. // question to this interface as a parameter.
  50. RetryOnError bool
  51. }
  52. // ShouldResyncFunc is a type of function that indicates if a reflector should perform a
  53. // resync or not. It can be used by a shared informer to support multiple event handlers with custom
  54. // resync periods.
  55. type ShouldResyncFunc func() bool
  56. // ProcessFunc processes a single object.
  57. type ProcessFunc func(obj interface{}) error
  58. // Controller is a generic controller framework.
  59. type controller struct {
  60. config Config
  61. reflector *Reflector
  62. reflectorMutex sync.RWMutex
  63. clock clock.Clock
  64. }
  65. type Controller interface {
  66. Run(stopCh <-chan struct{})
  67. HasSynced() bool
  68. LastSyncResourceVersion() string
  69. }
  70. // New makes a new Controller from the given Config.
  71. func New(c *Config) Controller {
  72. ctlr := &controller{
  73. config: *c,
  74. clock: &clock.RealClock{},
  75. }
  76. return ctlr
  77. }
  78. // Run begins processing items, and will continue until a value is sent down stopCh.
  79. // It's an error to call Run more than once.
  80. // Run blocks; call via go.
  81. func (c *controller) Run(stopCh <-chan struct{}) {
  82. defer utilruntime.HandleCrash()
  83. go func() {
  84. <-stopCh
  85. c.config.Queue.Close()
  86. }()
  87. r := NewReflector(
  88. c.config.ListerWatcher,
  89. c.config.ObjectType,
  90. c.config.Queue,
  91. c.config.FullResyncPeriod,
  92. )
  93. r.ShouldResync = c.config.ShouldResync
  94. r.clock = c.clock
  95. c.reflectorMutex.Lock()
  96. c.reflector = r
  97. c.reflectorMutex.Unlock()
  98. r.RunUntil(stopCh)
  99. wait.Until(c.processLoop, time.Second, stopCh)
  100. }
  101. // Returns true once this controller has completed an initial resource listing
  102. func (c *controller) HasSynced() bool {
  103. return c.config.Queue.HasSynced()
  104. }
  105. func (c *controller) LastSyncResourceVersion() string {
  106. if c.reflector == nil {
  107. return ""
  108. }
  109. return c.reflector.LastSyncResourceVersion()
  110. }
  111. // processLoop drains the work queue.
  112. // TODO: Consider doing the processing in parallel. This will require a little thought
  113. // to make sure that we don't end up processing the same object multiple times
  114. // concurrently.
  115. //
  116. // TODO: Plumb through the stopCh here (and down to the queue) so that this can
  117. // actually exit when the controller is stopped. Or just give up on this stuff
  118. // ever being stoppable. Converting this whole package to use Context would
  119. // also be helpful.
  120. func (c *controller) processLoop() {
  121. for {
  122. obj, err := c.config.Queue.Pop(PopProcessFunc(c.config.Process))
  123. if err != nil {
  124. if err == FIFOClosedError {
  125. return
  126. }
  127. if c.config.RetryOnError {
  128. // This is the safe way to re-enqueue.
  129. c.config.Queue.AddIfNotPresent(obj)
  130. }
  131. }
  132. }
  133. }
  134. // ResourceEventHandler can handle notifications for events that happen to a
  135. // resource. The events are informational only, so you can't return an
  136. // error.
  137. // * OnAdd is called when an object is added.
  138. // * OnUpdate is called when an object is modified. Note that oldObj is the
  139. // last known state of the object-- it is possible that several changes
  140. // were combined together, so you can't use this to see every single
  141. // change. OnUpdate is also called when a re-list happens, and it will
  142. // get called even if nothing changed. This is useful for periodically
  143. // evaluating or syncing something.
  144. // * OnDelete will get the final state of the item if it is known, otherwise
  145. // it will get an object of type DeletedFinalStateUnknown. This can
  146. // happen if the watch is closed and misses the delete event and we don't
  147. // notice the deletion until the subsequent re-list.
  148. type ResourceEventHandler interface {
  149. OnAdd(obj interface{})
  150. OnUpdate(oldObj, newObj interface{})
  151. OnDelete(obj interface{})
  152. }
  153. // ResourceEventHandlerFuncs is an adaptor to let you easily specify as many or
  154. // as few of the notification functions as you want while still implementing
  155. // ResourceEventHandler.
  156. type ResourceEventHandlerFuncs struct {
  157. AddFunc func(obj interface{})
  158. UpdateFunc func(oldObj, newObj interface{})
  159. DeleteFunc func(obj interface{})
  160. }
  161. // OnAdd calls AddFunc if it's not nil.
  162. func (r ResourceEventHandlerFuncs) OnAdd(obj interface{}) {
  163. if r.AddFunc != nil {
  164. r.AddFunc(obj)
  165. }
  166. }
  167. // OnUpdate calls UpdateFunc if it's not nil.
  168. func (r ResourceEventHandlerFuncs) OnUpdate(oldObj, newObj interface{}) {
  169. if r.UpdateFunc != nil {
  170. r.UpdateFunc(oldObj, newObj)
  171. }
  172. }
  173. // OnDelete calls DeleteFunc if it's not nil.
  174. func (r ResourceEventHandlerFuncs) OnDelete(obj interface{}) {
  175. if r.DeleteFunc != nil {
  176. r.DeleteFunc(obj)
  177. }
  178. }
  179. // DeletionHandlingMetaNamespaceKeyFunc checks for
  180. // DeletedFinalStateUnknown objects before calling
  181. // MetaNamespaceKeyFunc.
  182. func DeletionHandlingMetaNamespaceKeyFunc(obj interface{}) (string, error) {
  183. if d, ok := obj.(DeletedFinalStateUnknown); ok {
  184. return d.Key, nil
  185. }
  186. return MetaNamespaceKeyFunc(obj)
  187. }
  188. // NewInformer returns a Store and a controller for populating the store
  189. // while also providing event notifications. You should only used the returned
  190. // Store for Get/List operations; Add/Modify/Deletes will cause the event
  191. // notifications to be faulty.
  192. //
  193. // Parameters:
  194. // * lw is list and watch functions for the source of the resource you want to
  195. // be informed of.
  196. // * objType is an object of the type that you expect to receive.
  197. // * resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
  198. // calls, even if nothing changed). Otherwise, re-list will be delayed as
  199. // long as possible (until the upstream source closes the watch or times out,
  200. // or you stop the controller).
  201. // * h is the object you want notifications sent to.
  202. //
  203. func NewInformer(
  204. lw ListerWatcher,
  205. objType runtime.Object,
  206. resyncPeriod time.Duration,
  207. h ResourceEventHandler,
  208. ) (Store, Controller) {
  209. // This will hold the client state, as we know it.
  210. clientState := NewStore(DeletionHandlingMetaNamespaceKeyFunc)
  211. // This will hold incoming changes. Note how we pass clientState in as a
  212. // KeyLister, that way resync operations will result in the correct set
  213. // of update/delete deltas.
  214. fifo := NewDeltaFIFO(MetaNamespaceKeyFunc, nil, clientState)
  215. cfg := &Config{
  216. Queue: fifo,
  217. ListerWatcher: lw,
  218. ObjectType: objType,
  219. FullResyncPeriod: resyncPeriod,
  220. RetryOnError: false,
  221. Process: func(obj interface{}) error {
  222. // from oldest to newest
  223. for _, d := range obj.(Deltas) {
  224. switch d.Type {
  225. case Sync, Added, Updated:
  226. if old, exists, err := clientState.Get(d.Object); err == nil && exists {
  227. if err := clientState.Update(d.Object); err != nil {
  228. return err
  229. }
  230. h.OnUpdate(old, d.Object)
  231. } else {
  232. if err := clientState.Add(d.Object); err != nil {
  233. return err
  234. }
  235. h.OnAdd(d.Object)
  236. }
  237. case Deleted:
  238. if err := clientState.Delete(d.Object); err != nil {
  239. return err
  240. }
  241. h.OnDelete(d.Object)
  242. }
  243. }
  244. return nil
  245. },
  246. }
  247. return clientState, New(cfg)
  248. }
  249. // NewIndexerInformer returns a Indexer and a controller for populating the index
  250. // while also providing event notifications. You should only used the returned
  251. // Index for Get/List operations; Add/Modify/Deletes will cause the event
  252. // notifications to be faulty.
  253. //
  254. // Parameters:
  255. // * lw is list and watch functions for the source of the resource you want to
  256. // be informed of.
  257. // * objType is an object of the type that you expect to receive.
  258. // * resyncPeriod: if non-zero, will re-list this often (you will get OnUpdate
  259. // calls, even if nothing changed). Otherwise, re-list will be delayed as
  260. // long as possible (until the upstream source closes the watch or times out,
  261. // or you stop the controller).
  262. // * h is the object you want notifications sent to.
  263. //
  264. func NewIndexerInformer(
  265. lw ListerWatcher,
  266. objType runtime.Object,
  267. resyncPeriod time.Duration,
  268. h ResourceEventHandler,
  269. indexers Indexers,
  270. ) (Indexer, Controller) {
  271. // This will hold the client state, as we know it.
  272. clientState := NewIndexer(DeletionHandlingMetaNamespaceKeyFunc, indexers)
  273. // This will hold incoming changes. Note how we pass clientState in as a
  274. // KeyLister, that way resync operations will result in the correct set
  275. // of update/delete deltas.
  276. fifo := NewDeltaFIFO(MetaNamespaceKeyFunc, nil, clientState)
  277. cfg := &Config{
  278. Queue: fifo,
  279. ListerWatcher: lw,
  280. ObjectType: objType,
  281. FullResyncPeriod: resyncPeriod,
  282. RetryOnError: false,
  283. Process: func(obj interface{}) error {
  284. // from oldest to newest
  285. for _, d := range obj.(Deltas) {
  286. switch d.Type {
  287. case Sync, Added, Updated:
  288. if old, exists, err := clientState.Get(d.Object); err == nil && exists {
  289. if err := clientState.Update(d.Object); err != nil {
  290. return err
  291. }
  292. h.OnUpdate(old, d.Object)
  293. } else {
  294. if err := clientState.Add(d.Object); err != nil {
  295. return err
  296. }
  297. h.OnAdd(d.Object)
  298. }
  299. case Deleted:
  300. if err := clientState.Delete(d.Object); err != nil {
  301. return err
  302. }
  303. h.OnDelete(d.Object)
  304. }
  305. }
  306. return nil
  307. },
  308. }
  309. return clientState, New(cfg)
  310. }