wait.go 14 KB

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