wait.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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 wait
  14. import (
  15. "context"
  16. "errors"
  17. "math/rand"
  18. "sync"
  19. "time"
  20. "k8s.io/apimachinery/pkg/util/runtime"
  21. )
  22. // For any test of the style:
  23. // ...
  24. // <- time.After(timeout):
  25. // t.Errorf("Timed out")
  26. // The value for timeout should effectively be "forever." Obviously we don't want our tests to truly lock up forever, but 30s
  27. // is long enough that it is effectively forever for the things that can slow down a run on a heavily contended machine
  28. // (GC, seeks, etc), but not so long as to make a developer ctrl-c a test run if they do happen to break that test.
  29. var ForeverTestTimeout = time.Second * 30
  30. // NeverStop may be passed to Until to make it never stop.
  31. var NeverStop <-chan struct{} = make(chan struct{})
  32. // Group allows to start a group of goroutines and wait for their completion.
  33. type Group struct {
  34. wg sync.WaitGroup
  35. }
  36. func (g *Group) Wait() {
  37. g.wg.Wait()
  38. }
  39. // StartWithChannel starts f in a new goroutine in the group.
  40. // stopCh is passed to f as an argument. f should stop when stopCh is available.
  41. func (g *Group) StartWithChannel(stopCh <-chan struct{}, f func(stopCh <-chan struct{})) {
  42. g.Start(func() {
  43. f(stopCh)
  44. })
  45. }
  46. // StartWithContext starts f in a new goroutine in the group.
  47. // ctx is passed to f as an argument. f should stop when ctx.Done() is available.
  48. func (g *Group) StartWithContext(ctx context.Context, f func(context.Context)) {
  49. g.Start(func() {
  50. f(ctx)
  51. })
  52. }
  53. // Start starts f in a new goroutine in the group.
  54. func (g *Group) Start(f func()) {
  55. g.wg.Add(1)
  56. go func() {
  57. defer g.wg.Done()
  58. f()
  59. }()
  60. }
  61. // Forever calls f every period for ever.
  62. //
  63. // Forever is syntactic sugar on top of Until.
  64. func Forever(f func(), period time.Duration) {
  65. Until(f, period, NeverStop)
  66. }
  67. // Until loops until stop channel is closed, running f every period.
  68. //
  69. // Until is syntactic sugar on top of JitterUntil with zero jitter factor and
  70. // with sliding = true (which means the timer for period starts after the f
  71. // completes).
  72. func Until(f func(), period time.Duration, stopCh <-chan struct{}) {
  73. JitterUntil(f, period, 0.0, true, stopCh)
  74. }
  75. // UntilWithContext loops until context is done, running f every period.
  76. //
  77. // UntilWithContext is syntactic sugar on top of JitterUntilWithContext
  78. // with zero jitter factor and with sliding = true (which means the timer
  79. // for period starts after the f completes).
  80. func UntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) {
  81. JitterUntilWithContext(ctx, f, period, 0.0, true)
  82. }
  83. // NonSlidingUntil loops until stop channel is closed, running f every
  84. // period.
  85. //
  86. // NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter
  87. // factor, with sliding = false (meaning the timer for period starts at the same
  88. // time as the function starts).
  89. func NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) {
  90. JitterUntil(f, period, 0.0, false, stopCh)
  91. }
  92. // NonSlidingUntilWithContext loops until context is done, running f every
  93. // period.
  94. //
  95. // NonSlidingUntilWithContext is syntactic sugar on top of JitterUntilWithContext
  96. // with zero jitter factor, with sliding = false (meaning the timer for period
  97. // starts at the same time as the function starts).
  98. func NonSlidingUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) {
  99. JitterUntilWithContext(ctx, f, period, 0.0, false)
  100. }
  101. // JitterUntil loops until stop channel is closed, running f every period.
  102. //
  103. // If jitterFactor is positive, the period is jittered before every run of f.
  104. // If jitterFactor is not positive, the period is unchanged and not jittered.
  105. //
  106. // If sliding is true, the period is computed after f runs. If it is false then
  107. // period includes the runtime for f.
  108. //
  109. // Close stopCh to stop. f may not be invoked if stop channel is already
  110. // closed. Pass NeverStop to if you don't want it stop.
  111. func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) {
  112. var t *time.Timer
  113. var sawTimeout bool
  114. for {
  115. select {
  116. case <-stopCh:
  117. return
  118. default:
  119. }
  120. jitteredPeriod := period
  121. if jitterFactor > 0.0 {
  122. jitteredPeriod = Jitter(period, jitterFactor)
  123. }
  124. if !sliding {
  125. t = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)
  126. }
  127. func() {
  128. defer runtime.HandleCrash()
  129. f()
  130. }()
  131. if sliding {
  132. t = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)
  133. }
  134. // NOTE: b/c there is no priority selection in golang
  135. // it is possible for this to race, meaning we could
  136. // trigger t.C and stopCh, and t.C select falls through.
  137. // In order to mitigate we re-check stopCh at the beginning
  138. // of every loop to prevent extra executions of f().
  139. select {
  140. case <-stopCh:
  141. return
  142. case <-t.C:
  143. sawTimeout = true
  144. }
  145. }
  146. }
  147. // JitterUntilWithContext loops until context is done, running f every period.
  148. //
  149. // If jitterFactor is positive, the period is jittered before every run of f.
  150. // If jitterFactor is not positive, the period is unchanged and not jittered.
  151. //
  152. // If sliding is true, the period is computed after f runs. If it is false then
  153. // period includes the runtime for f.
  154. //
  155. // Cancel context to stop. f may not be invoked if context is already expired.
  156. func JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool) {
  157. JitterUntil(func() { f(ctx) }, period, jitterFactor, sliding, ctx.Done())
  158. }
  159. // Jitter returns a time.Duration between duration and duration + maxFactor *
  160. // duration.
  161. //
  162. // This allows clients to avoid converging on periodic behavior. If maxFactor
  163. // is 0.0, a suggested default value will be chosen.
  164. func Jitter(duration time.Duration, maxFactor float64) time.Duration {
  165. if maxFactor <= 0.0 {
  166. maxFactor = 1.0
  167. }
  168. wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))
  169. return wait
  170. }
  171. // ErrWaitTimeout is returned when the condition exited without success.
  172. var ErrWaitTimeout = errors.New("timed out waiting for the condition")
  173. // ConditionFunc returns true if the condition is satisfied, or an error
  174. // if the loop should be aborted.
  175. type ConditionFunc func() (done bool, err error)
  176. // Backoff holds parameters applied to a Backoff function.
  177. type Backoff struct {
  178. // The initial duration.
  179. Duration time.Duration
  180. // Duration is multiplied by factor each iteration. Must be greater
  181. // than or equal to zero.
  182. Factor float64
  183. // The amount of jitter applied each iteration. Jitter is applied after
  184. // cap.
  185. Jitter float64
  186. // The number of steps before duration stops changing. If zero, initial
  187. // duration is always used. Used for exponential backoff in combination
  188. // with Factor.
  189. Steps int
  190. // The returned duration will never be greater than cap *before* jitter
  191. // is applied. The actual maximum cap is `cap * (1.0 + jitter)`.
  192. Cap time.Duration
  193. }
  194. // Step returns the next interval in the exponential backoff. This method
  195. // will mutate the provided backoff.
  196. func (b *Backoff) Step() time.Duration {
  197. if b.Steps < 1 {
  198. if b.Jitter > 0 {
  199. return Jitter(b.Duration, b.Jitter)
  200. }
  201. return b.Duration
  202. }
  203. b.Steps--
  204. duration := b.Duration
  205. // calculate the next step
  206. if b.Factor != 0 {
  207. b.Duration = time.Duration(float64(b.Duration) * b.Factor)
  208. if b.Cap > 0 && b.Duration > b.Cap {
  209. b.Duration = b.Cap
  210. b.Steps = 0
  211. }
  212. }
  213. if b.Jitter > 0 {
  214. duration = Jitter(duration, b.Jitter)
  215. }
  216. return duration
  217. }
  218. // ExponentialBackoff repeats a condition check with exponential backoff.
  219. //
  220. // It checks the condition up to Steps times, increasing the wait by multiplying
  221. // the previous duration by Factor.
  222. //
  223. // If Jitter is greater than zero, a random amount of each duration is added
  224. // (between duration and duration*(1+jitter)).
  225. //
  226. // If the condition never returns true, ErrWaitTimeout is returned. All other
  227. // errors terminate immediately.
  228. func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {
  229. for backoff.Steps > 0 {
  230. if ok, err := condition(); err != nil || ok {
  231. return err
  232. }
  233. if backoff.Steps == 1 {
  234. break
  235. }
  236. time.Sleep(backoff.Step())
  237. }
  238. return ErrWaitTimeout
  239. }
  240. // Poll tries a condition func until it returns true, an error, or the timeout
  241. // is reached.
  242. //
  243. // Poll always waits the interval before the run of 'condition'.
  244. // 'condition' will always be invoked at least once.
  245. //
  246. // Some intervals may be missed if the condition takes too long or the time
  247. // window is too short.
  248. //
  249. // If you want to Poll something forever, see PollInfinite.
  250. func Poll(interval, timeout time.Duration, condition ConditionFunc) error {
  251. return pollInternal(poller(interval, timeout), condition)
  252. }
  253. func pollInternal(wait WaitFunc, condition ConditionFunc) error {
  254. done := make(chan struct{})
  255. defer close(done)
  256. return WaitFor(wait, condition, done)
  257. }
  258. // PollImmediate tries a condition func until it returns true, an error, or the timeout
  259. // is reached.
  260. //
  261. // PollImmediate always checks 'condition' before waiting for the interval. 'condition'
  262. // will always be invoked at least once.
  263. //
  264. // Some intervals may be missed if the condition takes too long or the time
  265. // window is too short.
  266. //
  267. // If you want to immediately Poll something forever, see PollImmediateInfinite.
  268. func PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error {
  269. return pollImmediateInternal(poller(interval, timeout), condition)
  270. }
  271. func pollImmediateInternal(wait WaitFunc, condition ConditionFunc) error {
  272. done, err := condition()
  273. if err != nil {
  274. return err
  275. }
  276. if done {
  277. return nil
  278. }
  279. return pollInternal(wait, condition)
  280. }
  281. // PollInfinite tries a condition func until it returns true or an error
  282. //
  283. // PollInfinite always waits the interval before the run of 'condition'.
  284. //
  285. // Some intervals may be missed if the condition takes too long or the time
  286. // window is too short.
  287. func PollInfinite(interval time.Duration, condition ConditionFunc) error {
  288. done := make(chan struct{})
  289. defer close(done)
  290. return PollUntil(interval, condition, done)
  291. }
  292. // PollImmediateInfinite tries a condition func until it returns true or an error
  293. //
  294. // PollImmediateInfinite runs the 'condition' before waiting for the interval.
  295. //
  296. // Some intervals may be missed if the condition takes too long or the time
  297. // window is too short.
  298. func PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error {
  299. done, err := condition()
  300. if err != nil {
  301. return err
  302. }
  303. if done {
  304. return nil
  305. }
  306. return PollInfinite(interval, condition)
  307. }
  308. // PollUntil tries a condition func until it returns true, an error or stopCh is
  309. // closed.
  310. //
  311. // PollUntil always waits interval before the first run of 'condition'.
  312. // 'condition' will always be invoked at least once.
  313. func PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
  314. return WaitFor(poller(interval, 0), condition, stopCh)
  315. }
  316. // PollImmediateUntil tries a condition func until it returns true, an error or stopCh is closed.
  317. //
  318. // PollImmediateUntil runs the 'condition' before waiting for the interval.
  319. // 'condition' will always be invoked at least once.
  320. func PollImmediateUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
  321. done, err := condition()
  322. if err != nil {
  323. return err
  324. }
  325. if done {
  326. return nil
  327. }
  328. select {
  329. case <-stopCh:
  330. return ErrWaitTimeout
  331. default:
  332. return PollUntil(interval, condition, stopCh)
  333. }
  334. }
  335. // WaitFunc creates a channel that receives an item every time a test
  336. // should be executed and is closed when the last test should be invoked.
  337. type WaitFunc func(done <-chan struct{}) <-chan struct{}
  338. // WaitFor continually checks 'fn' as driven by 'wait'.
  339. //
  340. // WaitFor gets a channel from 'wait()'', and then invokes 'fn' once for every value
  341. // placed on the channel and once more when the channel is closed. If the channel is closed
  342. // and 'fn' returns false without error, WaitFor returns ErrWaitTimeout.
  343. //
  344. // If 'fn' returns an error the loop ends and that error is returned. If
  345. // 'fn' returns true the loop ends and nil is returned.
  346. //
  347. // ErrWaitTimeout will be returned if the 'done' channel is closed without fn ever
  348. // returning true.
  349. //
  350. // When the done channel is closed, because the golang `select` statement is
  351. // "uniform pseudo-random", the `fn` might still run one or multiple time,
  352. // though eventually `WaitFor` will return.
  353. func WaitFor(wait WaitFunc, fn ConditionFunc, done <-chan struct{}) error {
  354. stopCh := make(chan struct{})
  355. defer close(stopCh)
  356. c := wait(stopCh)
  357. for {
  358. select {
  359. case _, open := <-c:
  360. ok, err := fn()
  361. if err != nil {
  362. return err
  363. }
  364. if ok {
  365. return nil
  366. }
  367. if !open {
  368. return ErrWaitTimeout
  369. }
  370. case <-done:
  371. return ErrWaitTimeout
  372. }
  373. }
  374. }
  375. // poller returns a WaitFunc that will send to the channel every interval until
  376. // timeout has elapsed and then closes the channel.
  377. //
  378. // Over very short intervals you may receive no ticks before the channel is
  379. // closed. A timeout of 0 is interpreted as an infinity.
  380. //
  381. // Output ticks are not buffered. If the channel is not ready to receive an
  382. // item, the tick is skipped.
  383. func poller(interval, timeout time.Duration) WaitFunc {
  384. return WaitFunc(func(done <-chan struct{}) <-chan struct{} {
  385. ch := make(chan struct{})
  386. go func() {
  387. defer close(ch)
  388. tick := time.NewTicker(interval)
  389. defer tick.Stop()
  390. var after <-chan time.Time
  391. if timeout != 0 {
  392. // time.After is more convenient, but it
  393. // potentially leaves timers around much longer
  394. // than necessary if we exit early.
  395. timer := time.NewTimer(timeout)
  396. after = timer.C
  397. defer timer.Stop()
  398. }
  399. for {
  400. select {
  401. case <-tick.C:
  402. // If the consumer isn't ready for this signal drop it and
  403. // check the other channels.
  404. select {
  405. case ch <- struct{}{}:
  406. default:
  407. }
  408. case <-after:
  409. return
  410. case <-done:
  411. return
  412. }
  413. }
  414. }()
  415. return ch
  416. })
  417. }
  418. // resetOrReuseTimer avoids allocating a new timer if one is already in use.
  419. // Not safe for multiple threads.
  420. func resetOrReuseTimer(t *time.Timer, d time.Duration, sawTimeout bool) *time.Timer {
  421. if t == nil {
  422. return time.NewTimer(d)
  423. }
  424. if !t.Stop() && !sawTimeout {
  425. <-t.C
  426. }
  427. t.Reset(d)
  428. return t
  429. }