queue.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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 workqueue
  14. import (
  15. "sync"
  16. "time"
  17. "k8s.io/utils/clock"
  18. )
  19. type Interface interface {
  20. Add(item interface{})
  21. Len() int
  22. Get() (item interface{}, shutdown bool)
  23. Done(item interface{})
  24. ShutDown()
  25. ShutDownWithDrain()
  26. ShuttingDown() bool
  27. }
  28. // New constructs a new work queue (see the package comment).
  29. func New() *Type {
  30. return NewNamed("")
  31. }
  32. func NewNamed(name string) *Type {
  33. rc := clock.RealClock{}
  34. return newQueue(
  35. rc,
  36. globalMetricsFactory.newQueueMetrics(name, rc),
  37. defaultUnfinishedWorkUpdatePeriod,
  38. )
  39. }
  40. func newQueue(c clock.WithTicker, metrics queueMetrics, updatePeriod time.Duration) *Type {
  41. t := &Type{
  42. clock: c,
  43. dirty: set{},
  44. processing: set{},
  45. cond: sync.NewCond(&sync.Mutex{}),
  46. metrics: metrics,
  47. unfinishedWorkUpdatePeriod: updatePeriod,
  48. }
  49. // Don't start the goroutine for a type of noMetrics so we don't consume
  50. // resources unnecessarily
  51. if _, ok := metrics.(noMetrics); !ok {
  52. go t.updateUnfinishedWorkLoop()
  53. }
  54. return t
  55. }
  56. const defaultUnfinishedWorkUpdatePeriod = 500 * time.Millisecond
  57. // Type is a work queue (see the package comment).
  58. type Type struct {
  59. // queue defines the order in which we will work on items. Every
  60. // element of queue should be in the dirty set and not in the
  61. // processing set.
  62. queue []t
  63. // dirty defines all of the items that need to be processed.
  64. dirty set
  65. // Things that are currently being processed are in the processing set.
  66. // These things may be simultaneously in the dirty set. When we finish
  67. // processing something and remove it from this set, we'll check if
  68. // it's in the dirty set, and if so, add it to the queue.
  69. processing set
  70. cond *sync.Cond
  71. shuttingDown bool
  72. drain bool
  73. metrics queueMetrics
  74. unfinishedWorkUpdatePeriod time.Duration
  75. clock clock.WithTicker
  76. }
  77. type empty struct{}
  78. type t interface{}
  79. type set map[t]empty
  80. func (s set) has(item t) bool {
  81. _, exists := s[item]
  82. return exists
  83. }
  84. func (s set) insert(item t) {
  85. s[item] = empty{}
  86. }
  87. func (s set) delete(item t) {
  88. delete(s, item)
  89. }
  90. func (s set) len() int {
  91. return len(s)
  92. }
  93. // Add marks item as needing processing.
  94. func (q *Type) Add(item interface{}) {
  95. q.cond.L.Lock()
  96. defer q.cond.L.Unlock()
  97. if q.shuttingDown {
  98. return
  99. }
  100. if q.dirty.has(item) {
  101. return
  102. }
  103. q.metrics.add(item)
  104. q.dirty.insert(item)
  105. if q.processing.has(item) {
  106. return
  107. }
  108. q.queue = append(q.queue, item)
  109. q.cond.Signal()
  110. }
  111. // Len returns the current queue length, for informational purposes only. You
  112. // shouldn't e.g. gate a call to Add() or Get() on Len() being a particular
  113. // value, that can't be synchronized properly.
  114. func (q *Type) Len() int {
  115. q.cond.L.Lock()
  116. defer q.cond.L.Unlock()
  117. return len(q.queue)
  118. }
  119. // Get blocks until it can return an item to be processed. If shutdown = true,
  120. // the caller should end their goroutine. You must call Done with item when you
  121. // have finished processing it.
  122. func (q *Type) Get() (item interface{}, shutdown bool) {
  123. q.cond.L.Lock()
  124. defer q.cond.L.Unlock()
  125. for len(q.queue) == 0 && !q.shuttingDown {
  126. q.cond.Wait()
  127. }
  128. if len(q.queue) == 0 {
  129. // We must be shutting down.
  130. return nil, true
  131. }
  132. item = q.queue[0]
  133. // The underlying array still exists and reference this object, so the object will not be garbage collected.
  134. q.queue[0] = nil
  135. q.queue = q.queue[1:]
  136. q.metrics.get(item)
  137. q.processing.insert(item)
  138. q.dirty.delete(item)
  139. return item, false
  140. }
  141. // Done marks item as done processing, and if it has been marked as dirty again
  142. // while it was being processed, it will be re-added to the queue for
  143. // re-processing.
  144. func (q *Type) Done(item interface{}) {
  145. q.cond.L.Lock()
  146. defer q.cond.L.Unlock()
  147. q.metrics.done(item)
  148. q.processing.delete(item)
  149. if q.dirty.has(item) {
  150. q.queue = append(q.queue, item)
  151. q.cond.Signal()
  152. } else if q.processing.len() == 0 {
  153. q.cond.Signal()
  154. }
  155. }
  156. // ShutDown will cause q to ignore all new items added to it and
  157. // immediately instruct the worker goroutines to exit.
  158. func (q *Type) ShutDown() {
  159. q.setDrain(false)
  160. q.shutdown()
  161. }
  162. // ShutDownWithDrain will cause q to ignore all new items added to it. As soon
  163. // as the worker goroutines have "drained", i.e: finished processing and called
  164. // Done on all existing items in the queue; they will be instructed to exit and
  165. // ShutDownWithDrain will return. Hence: a strict requirement for using this is;
  166. // your workers must ensure that Done is called on all items in the queue once
  167. // the shut down has been initiated, if that is not the case: this will block
  168. // indefinitely. It is, however, safe to call ShutDown after having called
  169. // ShutDownWithDrain, as to force the queue shut down to terminate immediately
  170. // without waiting for the drainage.
  171. func (q *Type) ShutDownWithDrain() {
  172. q.setDrain(true)
  173. q.shutdown()
  174. for q.isProcessing() && q.shouldDrain() {
  175. q.waitForProcessing()
  176. }
  177. }
  178. // isProcessing indicates if there are still items on the work queue being
  179. // processed. It's used to drain the work queue on an eventual shutdown.
  180. func (q *Type) isProcessing() bool {
  181. q.cond.L.Lock()
  182. defer q.cond.L.Unlock()
  183. return q.processing.len() != 0
  184. }
  185. // waitForProcessing waits for the worker goroutines to finish processing items
  186. // and call Done on them.
  187. func (q *Type) waitForProcessing() {
  188. q.cond.L.Lock()
  189. defer q.cond.L.Unlock()
  190. // Ensure that we do not wait on a queue which is already empty, as that
  191. // could result in waiting for Done to be called on items in an empty queue
  192. // which has already been shut down, which will result in waiting
  193. // indefinitely.
  194. if q.processing.len() == 0 {
  195. return
  196. }
  197. q.cond.Wait()
  198. }
  199. func (q *Type) setDrain(shouldDrain bool) {
  200. q.cond.L.Lock()
  201. defer q.cond.L.Unlock()
  202. q.drain = shouldDrain
  203. }
  204. func (q *Type) shouldDrain() bool {
  205. q.cond.L.Lock()
  206. defer q.cond.L.Unlock()
  207. return q.drain
  208. }
  209. func (q *Type) shutdown() {
  210. q.cond.L.Lock()
  211. defer q.cond.L.Unlock()
  212. q.shuttingDown = true
  213. q.cond.Broadcast()
  214. }
  215. func (q *Type) ShuttingDown() bool {
  216. q.cond.L.Lock()
  217. defer q.cond.L.Unlock()
  218. return q.shuttingDown
  219. }
  220. func (q *Type) updateUnfinishedWorkLoop() {
  221. t := q.clock.NewTicker(q.unfinishedWorkUpdatePeriod)
  222. defer t.Stop()
  223. for range t.C() {
  224. if !func() bool {
  225. q.cond.L.Lock()
  226. defer q.cond.L.Unlock()
  227. if !q.shuttingDown {
  228. q.metrics.updateUnfinishedWork()
  229. return true
  230. }
  231. return false
  232. }() {
  233. return
  234. }
  235. }
  236. }