mux.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. /*
  2. Copyright 2014 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 watch
  14. import (
  15. "sync"
  16. "k8s.io/apimachinery/pkg/runtime"
  17. "k8s.io/apimachinery/pkg/runtime/schema"
  18. )
  19. // FullChannelBehavior controls how the Broadcaster reacts if a watcher's watch
  20. // channel is full.
  21. type FullChannelBehavior int
  22. const (
  23. WaitIfChannelFull FullChannelBehavior = iota
  24. DropIfChannelFull
  25. )
  26. // Buffer the incoming queue a little bit even though it should rarely ever accumulate
  27. // anything, just in case a few events are received in such a short window that
  28. // Broadcaster can't move them onto the watchers' queues fast enough.
  29. const incomingQueueLength = 25
  30. // Broadcaster distributes event notifications among any number of watchers. Every event
  31. // is delivered to every watcher.
  32. type Broadcaster struct {
  33. watchers map[int64]*broadcasterWatcher
  34. nextWatcher int64
  35. distributing sync.WaitGroup
  36. incoming chan Event
  37. stopped chan struct{}
  38. // How large to make watcher's channel.
  39. watchQueueLength int
  40. // If one of the watch channels is full, don't wait for it to become empty.
  41. // Instead just deliver it to the watchers that do have space in their
  42. // channels and move on to the next event.
  43. // It's more fair to do this on a per-watcher basis than to do it on the
  44. // "incoming" channel, which would allow one slow watcher to prevent all
  45. // other watchers from getting new events.
  46. fullChannelBehavior FullChannelBehavior
  47. }
  48. // NewBroadcaster creates a new Broadcaster. queueLength is the maximum number of events to queue per watcher.
  49. // It is guaranteed that events will be distributed in the order in which they occur,
  50. // but the order in which a single event is distributed among all of the watchers is unspecified.
  51. func NewBroadcaster(queueLength int, fullChannelBehavior FullChannelBehavior) *Broadcaster {
  52. m := &Broadcaster{
  53. watchers: map[int64]*broadcasterWatcher{},
  54. incoming: make(chan Event, incomingQueueLength),
  55. stopped: make(chan struct{}),
  56. watchQueueLength: queueLength,
  57. fullChannelBehavior: fullChannelBehavior,
  58. }
  59. m.distributing.Add(1)
  60. go m.loop()
  61. return m
  62. }
  63. // NewLongQueueBroadcaster functions nearly identically to NewBroadcaster,
  64. // except that the incoming queue is the same size as the outgoing queues
  65. // (specified by queueLength).
  66. func NewLongQueueBroadcaster(queueLength int, fullChannelBehavior FullChannelBehavior) *Broadcaster {
  67. m := &Broadcaster{
  68. watchers: map[int64]*broadcasterWatcher{},
  69. incoming: make(chan Event, queueLength),
  70. stopped: make(chan struct{}),
  71. watchQueueLength: queueLength,
  72. fullChannelBehavior: fullChannelBehavior,
  73. }
  74. m.distributing.Add(1)
  75. go m.loop()
  76. return m
  77. }
  78. const internalRunFunctionMarker = "internal-do-function"
  79. // a function type we can shoehorn into the queue.
  80. type functionFakeRuntimeObject func()
  81. func (obj functionFakeRuntimeObject) GetObjectKind() schema.ObjectKind {
  82. return schema.EmptyObjectKind
  83. }
  84. func (obj functionFakeRuntimeObject) DeepCopyObject() runtime.Object {
  85. if obj == nil {
  86. return nil
  87. }
  88. // funcs are immutable. Hence, just return the original func.
  89. return obj
  90. }
  91. // Execute f, blocking the incoming queue (and waiting for it to drain first).
  92. // The purpose of this terrible hack is so that watchers added after an event
  93. // won't ever see that event, and will always see any event after they are
  94. // added.
  95. func (m *Broadcaster) blockQueue(f func()) {
  96. select {
  97. case <-m.stopped:
  98. return
  99. default:
  100. }
  101. var wg sync.WaitGroup
  102. wg.Add(1)
  103. m.incoming <- Event{
  104. Type: internalRunFunctionMarker,
  105. Object: functionFakeRuntimeObject(func() {
  106. defer wg.Done()
  107. f()
  108. }),
  109. }
  110. wg.Wait()
  111. }
  112. // Watch adds a new watcher to the list and returns an Interface for it.
  113. // Note: new watchers will only receive new events. They won't get an entire history
  114. // of previous events. It will block until the watcher is actually added to the
  115. // broadcaster.
  116. func (m *Broadcaster) Watch() Interface {
  117. var w *broadcasterWatcher
  118. m.blockQueue(func() {
  119. id := m.nextWatcher
  120. m.nextWatcher++
  121. w = &broadcasterWatcher{
  122. result: make(chan Event, m.watchQueueLength),
  123. stopped: make(chan struct{}),
  124. id: id,
  125. m: m,
  126. }
  127. m.watchers[id] = w
  128. })
  129. if w == nil {
  130. // The panic here is to be consistent with the previous interface behavior
  131. // we are willing to re-evaluate in the future.
  132. panic("broadcaster already stopped")
  133. }
  134. return w
  135. }
  136. // WatchWithPrefix adds a new watcher to the list and returns an Interface for it. It sends
  137. // queuedEvents down the new watch before beginning to send ordinary events from Broadcaster.
  138. // The returned watch will have a queue length that is at least large enough to accommodate
  139. // all of the items in queuedEvents. It will block until the watcher is actually added to
  140. // the broadcaster.
  141. func (m *Broadcaster) WatchWithPrefix(queuedEvents []Event) Interface {
  142. var w *broadcasterWatcher
  143. m.blockQueue(func() {
  144. id := m.nextWatcher
  145. m.nextWatcher++
  146. length := m.watchQueueLength
  147. if n := len(queuedEvents) + 1; n > length {
  148. length = n
  149. }
  150. w = &broadcasterWatcher{
  151. result: make(chan Event, length),
  152. stopped: make(chan struct{}),
  153. id: id,
  154. m: m,
  155. }
  156. m.watchers[id] = w
  157. for _, e := range queuedEvents {
  158. w.result <- e
  159. }
  160. })
  161. if w == nil {
  162. // The panic here is to be consistent with the previous interface behavior
  163. // we are willing to re-evaluate in the future.
  164. panic("broadcaster already stopped")
  165. }
  166. return w
  167. }
  168. // stopWatching stops the given watcher and removes it from the list.
  169. func (m *Broadcaster) stopWatching(id int64) {
  170. m.blockQueue(func() {
  171. w, ok := m.watchers[id]
  172. if !ok {
  173. // No need to do anything, it's already been removed from the list.
  174. return
  175. }
  176. delete(m.watchers, id)
  177. close(w.result)
  178. })
  179. }
  180. // closeAll disconnects all watchers (presumably in response to a Shutdown call).
  181. func (m *Broadcaster) closeAll() {
  182. for _, w := range m.watchers {
  183. close(w.result)
  184. }
  185. // Delete everything from the map, since presence/absence in the map is used
  186. // by stopWatching to avoid double-closing the channel.
  187. m.watchers = map[int64]*broadcasterWatcher{}
  188. }
  189. // Action distributes the given event among all watchers.
  190. func (m *Broadcaster) Action(action EventType, obj runtime.Object) {
  191. m.incoming <- Event{action, obj}
  192. }
  193. // Action distributes the given event among all watchers, or drops it on the floor
  194. // if too many incoming actions are queued up. Returns true if the action was sent,
  195. // false if dropped.
  196. func (m *Broadcaster) ActionOrDrop(action EventType, obj runtime.Object) bool {
  197. select {
  198. case m.incoming <- Event{action, obj}:
  199. return true
  200. default:
  201. return false
  202. }
  203. }
  204. // Shutdown disconnects all watchers (but any queued events will still be distributed).
  205. // You must not call Action or Watch* after calling Shutdown. This call blocks
  206. // until all events have been distributed through the outbound channels. Note
  207. // that since they can be buffered, this means that the watchers might not
  208. // have received the data yet as it can remain sitting in the buffered
  209. // channel. It will block until the broadcaster stop request is actually executed
  210. func (m *Broadcaster) Shutdown() {
  211. m.blockQueue(func() {
  212. close(m.stopped)
  213. close(m.incoming)
  214. })
  215. m.distributing.Wait()
  216. }
  217. // loop receives from m.incoming and distributes to all watchers.
  218. func (m *Broadcaster) loop() {
  219. // Deliberately not catching crashes here. Yes, bring down the process if there's a
  220. // bug in watch.Broadcaster.
  221. for event := range m.incoming {
  222. if event.Type == internalRunFunctionMarker {
  223. event.Object.(functionFakeRuntimeObject)()
  224. continue
  225. }
  226. m.distribute(event)
  227. }
  228. m.closeAll()
  229. m.distributing.Done()
  230. }
  231. // distribute sends event to all watchers. Blocking.
  232. func (m *Broadcaster) distribute(event Event) {
  233. if m.fullChannelBehavior == DropIfChannelFull {
  234. for _, w := range m.watchers {
  235. select {
  236. case w.result <- event:
  237. case <-w.stopped:
  238. default: // Don't block if the event can't be queued.
  239. }
  240. }
  241. } else {
  242. for _, w := range m.watchers {
  243. select {
  244. case w.result <- event:
  245. case <-w.stopped:
  246. }
  247. }
  248. }
  249. }
  250. // broadcasterWatcher handles a single watcher of a broadcaster
  251. type broadcasterWatcher struct {
  252. result chan Event
  253. stopped chan struct{}
  254. stop sync.Once
  255. id int64
  256. m *Broadcaster
  257. }
  258. // ResultChan returns a channel to use for waiting on events.
  259. func (mw *broadcasterWatcher) ResultChan() <-chan Event {
  260. return mw.result
  261. }
  262. // Stop stops watching and removes mw from its list.
  263. // It will block until the watcher stop request is actually executed
  264. func (mw *broadcasterWatcher) Stop() {
  265. mw.stop.Do(func() {
  266. close(mw.stopped)
  267. mw.m.stopWatching(mw.id)
  268. })
  269. }