wait.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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"
  18. "math/rand"
  19. "sync"
  20. "time"
  21. "k8s.io/apimachinery/pkg/util/runtime"
  22. "k8s.io/utils/clock"
  23. )
  24. // For any test of the style:
  25. // ...
  26. // <- time.After(timeout):
  27. // t.Errorf("Timed out")
  28. // The value for timeout should effectively be "forever." Obviously we don't want our tests to truly lock up forever, but 30s
  29. // is long enough that it is effectively forever for the things that can slow down a run on a heavily contended machine
  30. // (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.
  31. var ForeverTestTimeout = time.Second * 30
  32. // NeverStop may be passed to Until to make it never stop.
  33. var NeverStop <-chan struct{} = make(chan struct{})
  34. // Group allows to start a group of goroutines and wait for their completion.
  35. type Group struct {
  36. wg sync.WaitGroup
  37. }
  38. func (g *Group) Wait() {
  39. g.wg.Wait()
  40. }
  41. // StartWithChannel starts f in a new goroutine in the group.
  42. // stopCh is passed to f as an argument. f should stop when stopCh is available.
  43. func (g *Group) StartWithChannel(stopCh <-chan struct{}, f func(stopCh <-chan struct{})) {
  44. g.Start(func() {
  45. f(stopCh)
  46. })
  47. }
  48. // StartWithContext starts f in a new goroutine in the group.
  49. // ctx is passed to f as an argument. f should stop when ctx.Done() is available.
  50. func (g *Group) StartWithContext(ctx context.Context, f func(context.Context)) {
  51. g.Start(func() {
  52. f(ctx)
  53. })
  54. }
  55. // Start starts f in a new goroutine in the group.
  56. func (g *Group) Start(f func()) {
  57. g.wg.Add(1)
  58. go func() {
  59. defer g.wg.Done()
  60. f()
  61. }()
  62. }
  63. // Forever calls f every period for ever.
  64. //
  65. // Forever is syntactic sugar on top of Until.
  66. func Forever(f func(), period time.Duration) {
  67. Until(f, period, NeverStop)
  68. }
  69. // Until loops until stop channel is closed, running f every period.
  70. //
  71. // Until is syntactic sugar on top of JitterUntil with zero jitter factor and
  72. // with sliding = true (which means the timer for period starts after the f
  73. // completes).
  74. func Until(f func(), period time.Duration, stopCh <-chan struct{}) {
  75. JitterUntil(f, period, 0.0, true, stopCh)
  76. }
  77. // UntilWithContext loops until context is done, running f every period.
  78. //
  79. // UntilWithContext is syntactic sugar on top of JitterUntilWithContext
  80. // with zero jitter factor and with sliding = true (which means the timer
  81. // for period starts after the f completes).
  82. func UntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) {
  83. JitterUntilWithContext(ctx, f, period, 0.0, true)
  84. }
  85. // NonSlidingUntil loops until stop channel is closed, running f every
  86. // period.
  87. //
  88. // NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter
  89. // factor, with sliding = false (meaning the timer for period starts at the same
  90. // time as the function starts).
  91. func NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) {
  92. JitterUntil(f, period, 0.0, false, stopCh)
  93. }
  94. // NonSlidingUntilWithContext loops until context is done, running f every
  95. // period.
  96. //
  97. // NonSlidingUntilWithContext is syntactic sugar on top of JitterUntilWithContext
  98. // with zero jitter factor, with sliding = false (meaning the timer for period
  99. // starts at the same time as the function starts).
  100. func NonSlidingUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration) {
  101. JitterUntilWithContext(ctx, f, period, 0.0, false)
  102. }
  103. // JitterUntil loops until stop channel is closed, running f every period.
  104. //
  105. // If jitterFactor is positive, the period is jittered before every run of f.
  106. // If jitterFactor is not positive, the period is unchanged and not jittered.
  107. //
  108. // If sliding is true, the period is computed after f runs. If it is false then
  109. // period includes the runtime for f.
  110. //
  111. // Close stopCh to stop. f may not be invoked if stop channel is already
  112. // closed. Pass NeverStop to if you don't want it stop.
  113. func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) {
  114. BackoffUntil(f, NewJitteredBackoffManager(period, jitterFactor, &clock.RealClock{}), sliding, stopCh)
  115. }
  116. // BackoffUntil loops until stop channel is closed, run f every duration given by BackoffManager.
  117. //
  118. // If sliding is true, the period is computed after f runs. If it is false then
  119. // period includes the runtime for f.
  120. func BackoffUntil(f func(), backoff BackoffManager, sliding bool, stopCh <-chan struct{}) {
  121. var t clock.Timer
  122. for {
  123. select {
  124. case <-stopCh:
  125. return
  126. default:
  127. }
  128. if !sliding {
  129. t = backoff.Backoff()
  130. }
  131. func() {
  132. defer runtime.HandleCrash()
  133. f()
  134. }()
  135. if sliding {
  136. t = backoff.Backoff()
  137. }
  138. // NOTE: b/c there is no priority selection in golang
  139. // it is possible for this to race, meaning we could
  140. // trigger t.C and stopCh, and t.C select falls through.
  141. // In order to mitigate we re-check stopCh at the beginning
  142. // of every loop to prevent extra executions of f().
  143. select {
  144. case <-stopCh:
  145. if !t.Stop() {
  146. <-t.C()
  147. }
  148. return
  149. case <-t.C():
  150. }
  151. }
  152. }
  153. // JitterUntilWithContext loops until context is done, running f every period.
  154. //
  155. // If jitterFactor is positive, the period is jittered before every run of f.
  156. // If jitterFactor is not positive, the period is unchanged and not jittered.
  157. //
  158. // If sliding is true, the period is computed after f runs. If it is false then
  159. // period includes the runtime for f.
  160. //
  161. // Cancel context to stop. f may not be invoked if context is already expired.
  162. func JitterUntilWithContext(ctx context.Context, f func(context.Context), period time.Duration, jitterFactor float64, sliding bool) {
  163. JitterUntil(func() { f(ctx) }, period, jitterFactor, sliding, ctx.Done())
  164. }
  165. // Jitter returns a time.Duration between duration and duration + maxFactor *
  166. // duration.
  167. //
  168. // This allows clients to avoid converging on periodic behavior. If maxFactor
  169. // is 0.0, a suggested default value will be chosen.
  170. func Jitter(duration time.Duration, maxFactor float64) time.Duration {
  171. if maxFactor <= 0.0 {
  172. maxFactor = 1.0
  173. }
  174. wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))
  175. return wait
  176. }
  177. // ErrWaitTimeout is returned when the condition exited without success.
  178. var ErrWaitTimeout = errors.New("timed out waiting for the condition")
  179. // ConditionFunc returns true if the condition is satisfied, or an error
  180. // if the loop should be aborted.
  181. type ConditionFunc func() (done bool, err error)
  182. // ConditionWithContextFunc returns true if the condition is satisfied, or an error
  183. // if the loop should be aborted.
  184. //
  185. // The caller passes along a context that can be used by the condition function.
  186. type ConditionWithContextFunc func(context.Context) (done bool, err error)
  187. // WithContext converts a ConditionFunc into a ConditionWithContextFunc
  188. func (cf ConditionFunc) WithContext() ConditionWithContextFunc {
  189. return func(context.Context) (done bool, err error) {
  190. return cf()
  191. }
  192. }
  193. // runConditionWithCrashProtection runs a ConditionFunc with crash protection
  194. func runConditionWithCrashProtection(condition ConditionFunc) (bool, error) {
  195. return runConditionWithCrashProtectionWithContext(context.TODO(), condition.WithContext())
  196. }
  197. // runConditionWithCrashProtectionWithContext runs a
  198. // ConditionWithContextFunc with crash protection.
  199. func runConditionWithCrashProtectionWithContext(ctx context.Context, condition ConditionWithContextFunc) (bool, error) {
  200. defer runtime.HandleCrash()
  201. return condition(ctx)
  202. }
  203. // Backoff holds parameters applied to a Backoff function.
  204. type Backoff struct {
  205. // The initial duration.
  206. Duration time.Duration
  207. // Duration is multiplied by factor each iteration, if factor is not zero
  208. // and the limits imposed by Steps and Cap have not been reached.
  209. // Should not be negative.
  210. // The jitter does not contribute to the updates to the duration parameter.
  211. Factor float64
  212. // The sleep at each iteration is the duration plus an additional
  213. // amount chosen uniformly at random from the interval between
  214. // zero and `jitter*duration`.
  215. Jitter float64
  216. // The remaining number of iterations in which the duration
  217. // parameter may change (but progress can be stopped earlier by
  218. // hitting the cap). If not positive, the duration is not
  219. // changed. Used for exponential backoff in combination with
  220. // Factor and Cap.
  221. Steps int
  222. // A limit on revised values of the duration parameter. If a
  223. // multiplication by the factor parameter would make the duration
  224. // exceed the cap then the duration is set to the cap and the
  225. // steps parameter is set to zero.
  226. Cap time.Duration
  227. }
  228. // Step (1) returns an amount of time to sleep determined by the
  229. // original Duration and Jitter and (2) mutates the provided Backoff
  230. // to update its Steps and Duration.
  231. func (b *Backoff) Step() time.Duration {
  232. if b.Steps < 1 {
  233. if b.Jitter > 0 {
  234. return Jitter(b.Duration, b.Jitter)
  235. }
  236. return b.Duration
  237. }
  238. b.Steps--
  239. duration := b.Duration
  240. // calculate the next step
  241. if b.Factor != 0 {
  242. b.Duration = time.Duration(float64(b.Duration) * b.Factor)
  243. if b.Cap > 0 && b.Duration > b.Cap {
  244. b.Duration = b.Cap
  245. b.Steps = 0
  246. }
  247. }
  248. if b.Jitter > 0 {
  249. duration = Jitter(duration, b.Jitter)
  250. }
  251. return duration
  252. }
  253. // contextForChannel derives a child context from a parent channel.
  254. //
  255. // The derived context's Done channel is closed when the returned cancel function
  256. // is called or when the parent channel is closed, whichever happens first.
  257. //
  258. // Note the caller must *always* call the CancelFunc, otherwise resources may be leaked.
  259. func contextForChannel(parentCh <-chan struct{}) (context.Context, context.CancelFunc) {
  260. ctx, cancel := context.WithCancel(context.Background())
  261. go func() {
  262. select {
  263. case <-parentCh:
  264. cancel()
  265. case <-ctx.Done():
  266. }
  267. }()
  268. return ctx, cancel
  269. }
  270. // BackoffManager manages backoff with a particular scheme based on its underlying implementation. It provides
  271. // an interface to return a timer for backoff, and caller shall backoff until Timer.C() drains. If the second Backoff()
  272. // is called before the timer from the first Backoff() call finishes, the first timer will NOT be drained and result in
  273. // undetermined behavior.
  274. // The BackoffManager is supposed to be called in a single-threaded environment.
  275. type BackoffManager interface {
  276. Backoff() clock.Timer
  277. }
  278. type exponentialBackoffManagerImpl struct {
  279. backoff *Backoff
  280. backoffTimer clock.Timer
  281. lastBackoffStart time.Time
  282. initialBackoff time.Duration
  283. backoffResetDuration time.Duration
  284. clock clock.Clock
  285. }
  286. // NewExponentialBackoffManager returns a manager for managing exponential backoff. Each backoff is jittered and
  287. // backoff will not exceed the given max. If the backoff is not called within resetDuration, the backoff is reset.
  288. // This backoff manager is used to reduce load during upstream unhealthiness.
  289. func NewExponentialBackoffManager(initBackoff, maxBackoff, resetDuration time.Duration, backoffFactor, jitter float64, c clock.Clock) BackoffManager {
  290. return &exponentialBackoffManagerImpl{
  291. backoff: &Backoff{
  292. Duration: initBackoff,
  293. Factor: backoffFactor,
  294. Jitter: jitter,
  295. // the current impl of wait.Backoff returns Backoff.Duration once steps are used up, which is not
  296. // what we ideally need here, we set it to max int and assume we will never use up the steps
  297. Steps: math.MaxInt32,
  298. Cap: maxBackoff,
  299. },
  300. backoffTimer: nil,
  301. initialBackoff: initBackoff,
  302. lastBackoffStart: c.Now(),
  303. backoffResetDuration: resetDuration,
  304. clock: c,
  305. }
  306. }
  307. func (b *exponentialBackoffManagerImpl) getNextBackoff() time.Duration {
  308. if b.clock.Now().Sub(b.lastBackoffStart) > b.backoffResetDuration {
  309. b.backoff.Steps = math.MaxInt32
  310. b.backoff.Duration = b.initialBackoff
  311. }
  312. b.lastBackoffStart = b.clock.Now()
  313. return b.backoff.Step()
  314. }
  315. // Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for exponential backoff.
  316. // The returned timer must be drained before calling Backoff() the second time
  317. func (b *exponentialBackoffManagerImpl) Backoff() clock.Timer {
  318. if b.backoffTimer == nil {
  319. b.backoffTimer = b.clock.NewTimer(b.getNextBackoff())
  320. } else {
  321. b.backoffTimer.Reset(b.getNextBackoff())
  322. }
  323. return b.backoffTimer
  324. }
  325. type jitteredBackoffManagerImpl struct {
  326. clock clock.Clock
  327. duration time.Duration
  328. jitter float64
  329. backoffTimer clock.Timer
  330. }
  331. // NewJitteredBackoffManager returns a BackoffManager that backoffs with given duration plus given jitter. If the jitter
  332. // is negative, backoff will not be jittered.
  333. func NewJitteredBackoffManager(duration time.Duration, jitter float64, c clock.Clock) BackoffManager {
  334. return &jitteredBackoffManagerImpl{
  335. clock: c,
  336. duration: duration,
  337. jitter: jitter,
  338. backoffTimer: nil,
  339. }
  340. }
  341. func (j *jitteredBackoffManagerImpl) getNextBackoff() time.Duration {
  342. jitteredPeriod := j.duration
  343. if j.jitter > 0.0 {
  344. jitteredPeriod = Jitter(j.duration, j.jitter)
  345. }
  346. return jitteredPeriod
  347. }
  348. // Backoff implements BackoffManager.Backoff, it returns a timer so caller can block on the timer for jittered backoff.
  349. // The returned timer must be drained before calling Backoff() the second time
  350. func (j *jitteredBackoffManagerImpl) Backoff() clock.Timer {
  351. backoff := j.getNextBackoff()
  352. if j.backoffTimer == nil {
  353. j.backoffTimer = j.clock.NewTimer(backoff)
  354. } else {
  355. j.backoffTimer.Reset(backoff)
  356. }
  357. return j.backoffTimer
  358. }
  359. // ExponentialBackoff repeats a condition check with exponential backoff.
  360. //
  361. // It repeatedly checks the condition and then sleeps, using `backoff.Step()`
  362. // to determine the length of the sleep and adjust Duration and Steps.
  363. // Stops and returns as soon as:
  364. // 1. the condition check returns true or an error,
  365. // 2. `backoff.Steps` checks of the condition have been done, or
  366. // 3. a sleep truncated by the cap on duration has been completed.
  367. // In case (1) the returned error is what the condition function returned.
  368. // In all other cases, ErrWaitTimeout is returned.
  369. func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {
  370. for backoff.Steps > 0 {
  371. if ok, err := runConditionWithCrashProtection(condition); err != nil || ok {
  372. return err
  373. }
  374. if backoff.Steps == 1 {
  375. break
  376. }
  377. time.Sleep(backoff.Step())
  378. }
  379. return ErrWaitTimeout
  380. }
  381. // Poll tries a condition func until it returns true, an error, or the timeout
  382. // is reached.
  383. //
  384. // Poll always waits the interval before the run of 'condition'.
  385. // 'condition' will always be invoked at least once.
  386. //
  387. // Some intervals may be missed if the condition takes too long or the time
  388. // window is too short.
  389. //
  390. // If you want to Poll something forever, see PollInfinite.
  391. func Poll(interval, timeout time.Duration, condition ConditionFunc) error {
  392. return PollWithContext(context.Background(), interval, timeout, condition.WithContext())
  393. }
  394. // PollWithContext tries a condition func until it returns true, an error,
  395. // or when the context expires or the timeout is reached, whichever
  396. // happens first.
  397. //
  398. // PollWithContext always waits the interval before the run of 'condition'.
  399. // 'condition' will always be invoked at least once.
  400. //
  401. // Some intervals may be missed if the condition takes too long or the time
  402. // window is too short.
  403. //
  404. // If you want to Poll something forever, see PollInfinite.
  405. func PollWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error {
  406. return poll(ctx, false, poller(interval, timeout), condition)
  407. }
  408. // PollUntil tries a condition func until it returns true, an error or stopCh is
  409. // closed.
  410. //
  411. // PollUntil always waits interval before the first run of 'condition'.
  412. // 'condition' will always be invoked at least once.
  413. func PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
  414. ctx, cancel := contextForChannel(stopCh)
  415. defer cancel()
  416. return PollUntilWithContext(ctx, interval, condition.WithContext())
  417. }
  418. // PollUntilWithContext tries a condition func until it returns true,
  419. // an error or the specified context is cancelled or expired.
  420. //
  421. // PollUntilWithContext always waits interval before the first run of 'condition'.
  422. // 'condition' will always be invoked at least once.
  423. func PollUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
  424. return poll(ctx, false, poller(interval, 0), condition)
  425. }
  426. // PollInfinite tries a condition func until it returns true or an error
  427. //
  428. // PollInfinite always waits the interval before the run of 'condition'.
  429. //
  430. // Some intervals may be missed if the condition takes too long or the time
  431. // window is too short.
  432. func PollInfinite(interval time.Duration, condition ConditionFunc) error {
  433. return PollInfiniteWithContext(context.Background(), interval, condition.WithContext())
  434. }
  435. // PollInfiniteWithContext tries a condition func until it returns true or an error
  436. //
  437. // PollInfiniteWithContext always waits the interval before the run of 'condition'.
  438. //
  439. // Some intervals may be missed if the condition takes too long or the time
  440. // window is too short.
  441. func PollInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
  442. return poll(ctx, false, poller(interval, 0), condition)
  443. }
  444. // PollImmediate tries a condition func until it returns true, an error, or the timeout
  445. // is reached.
  446. //
  447. // PollImmediate always checks 'condition' before waiting for the interval. 'condition'
  448. // will always be invoked at least once.
  449. //
  450. // Some intervals may be missed if the condition takes too long or the time
  451. // window is too short.
  452. //
  453. // If you want to immediately Poll something forever, see PollImmediateInfinite.
  454. func PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error {
  455. return PollImmediateWithContext(context.Background(), interval, timeout, condition.WithContext())
  456. }
  457. // PollImmediateWithContext tries a condition func until it returns true, an error,
  458. // or the timeout is reached or the specified context expires, whichever happens first.
  459. //
  460. // PollImmediateWithContext always checks 'condition' before waiting for the interval.
  461. // 'condition' will always be invoked at least once.
  462. //
  463. // Some intervals may be missed if the condition takes too long or the time
  464. // window is too short.
  465. //
  466. // If you want to immediately Poll something forever, see PollImmediateInfinite.
  467. func PollImmediateWithContext(ctx context.Context, interval, timeout time.Duration, condition ConditionWithContextFunc) error {
  468. return poll(ctx, true, poller(interval, timeout), condition)
  469. }
  470. // PollImmediateUntil tries a condition func until it returns true, an error or stopCh is closed.
  471. //
  472. // PollImmediateUntil runs the 'condition' before waiting for the interval.
  473. // 'condition' will always be invoked at least once.
  474. func PollImmediateUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
  475. ctx, cancel := contextForChannel(stopCh)
  476. defer cancel()
  477. return PollImmediateUntilWithContext(ctx, interval, condition.WithContext())
  478. }
  479. // PollImmediateUntilWithContext tries a condition func until it returns true,
  480. // an error or the specified context is cancelled or expired.
  481. //
  482. // PollImmediateUntilWithContext runs the 'condition' before waiting for the interval.
  483. // 'condition' will always be invoked at least once.
  484. func PollImmediateUntilWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
  485. return poll(ctx, true, poller(interval, 0), condition)
  486. }
  487. // PollImmediateInfinite tries a condition func until it returns true or an error
  488. //
  489. // PollImmediateInfinite runs the 'condition' before waiting for the interval.
  490. //
  491. // Some intervals may be missed if the condition takes too long or the time
  492. // window is too short.
  493. func PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error {
  494. return PollImmediateInfiniteWithContext(context.Background(), interval, condition.WithContext())
  495. }
  496. // PollImmediateInfiniteWithContext tries a condition func until it returns true
  497. // or an error or the specified context gets cancelled or expired.
  498. //
  499. // PollImmediateInfiniteWithContext runs the 'condition' before waiting for the interval.
  500. //
  501. // Some intervals may be missed if the condition takes too long or the time
  502. // window is too short.
  503. func PollImmediateInfiniteWithContext(ctx context.Context, interval time.Duration, condition ConditionWithContextFunc) error {
  504. return poll(ctx, true, poller(interval, 0), condition)
  505. }
  506. // Internally used, each of the the public 'Poll*' function defined in this
  507. // package should invoke this internal function with appropriate parameters.
  508. // ctx: the context specified by the caller, for infinite polling pass
  509. // a context that never gets cancelled or expired.
  510. // immediate: if true, the 'condition' will be invoked before waiting for the interval,
  511. // in this case 'condition' will always be invoked at least once.
  512. // wait: user specified WaitFunc function that controls at what interval the condition
  513. // function should be invoked periodically and whether it is bound by a timeout.
  514. // condition: user specified ConditionWithContextFunc function.
  515. func poll(ctx context.Context, immediate bool, wait WaitWithContextFunc, condition ConditionWithContextFunc) error {
  516. if immediate {
  517. done, err := runConditionWithCrashProtectionWithContext(ctx, condition)
  518. if err != nil {
  519. return err
  520. }
  521. if done {
  522. return nil
  523. }
  524. }
  525. select {
  526. case <-ctx.Done():
  527. // returning ctx.Err() will break backward compatibility
  528. return ErrWaitTimeout
  529. default:
  530. return WaitForWithContext(ctx, wait, condition)
  531. }
  532. }
  533. // WaitFunc creates a channel that receives an item every time a test
  534. // should be executed and is closed when the last test should be invoked.
  535. type WaitFunc func(done <-chan struct{}) <-chan struct{}
  536. // WithContext converts the WaitFunc to an equivalent WaitWithContextFunc
  537. func (w WaitFunc) WithContext() WaitWithContextFunc {
  538. return func(ctx context.Context) <-chan struct{} {
  539. return w(ctx.Done())
  540. }
  541. }
  542. // WaitWithContextFunc creates a channel that receives an item every time a test
  543. // should be executed and is closed when the last test should be invoked.
  544. //
  545. // When the specified context gets cancelled or expires the function
  546. // stops sending item and returns immediately.
  547. type WaitWithContextFunc func(ctx context.Context) <-chan struct{}
  548. // WaitFor continually checks 'fn' as driven by 'wait'.
  549. //
  550. // WaitFor gets a channel from 'wait()'', and then invokes 'fn' once for every value
  551. // placed on the channel and once more when the channel is closed. If the channel is closed
  552. // and 'fn' returns false without error, WaitFor returns ErrWaitTimeout.
  553. //
  554. // If 'fn' returns an error the loop ends and that error is returned. If
  555. // 'fn' returns true the loop ends and nil is returned.
  556. //
  557. // ErrWaitTimeout will be returned if the 'done' channel is closed without fn ever
  558. // returning true.
  559. //
  560. // When the done channel is closed, because the golang `select` statement is
  561. // "uniform pseudo-random", the `fn` might still run one or multiple time,
  562. // though eventually `WaitFor` will return.
  563. func WaitFor(wait WaitFunc, fn ConditionFunc, done <-chan struct{}) error {
  564. ctx, cancel := contextForChannel(done)
  565. defer cancel()
  566. return WaitForWithContext(ctx, wait.WithContext(), fn.WithContext())
  567. }
  568. // WaitForWithContext continually checks 'fn' as driven by 'wait'.
  569. //
  570. // WaitForWithContext gets a channel from 'wait()'', and then invokes 'fn'
  571. // once for every value placed on the channel and once more when the
  572. // channel is closed. If the channel is closed and 'fn'
  573. // returns false without error, WaitForWithContext returns ErrWaitTimeout.
  574. //
  575. // If 'fn' returns an error the loop ends and that error is returned. If
  576. // 'fn' returns true the loop ends and nil is returned.
  577. //
  578. // context.Canceled will be returned if the ctx.Done() channel is closed
  579. // without fn ever returning true.
  580. //
  581. // When the ctx.Done() channel is closed, because the golang `select` statement is
  582. // "uniform pseudo-random", the `fn` might still run one or multiple times,
  583. // though eventually `WaitForWithContext` will return.
  584. func WaitForWithContext(ctx context.Context, wait WaitWithContextFunc, fn ConditionWithContextFunc) error {
  585. waitCtx, cancel := context.WithCancel(context.Background())
  586. defer cancel()
  587. c := wait(waitCtx)
  588. for {
  589. select {
  590. case _, open := <-c:
  591. ok, err := runConditionWithCrashProtectionWithContext(ctx, fn)
  592. if err != nil {
  593. return err
  594. }
  595. if ok {
  596. return nil
  597. }
  598. if !open {
  599. return ErrWaitTimeout
  600. }
  601. case <-ctx.Done():
  602. // returning ctx.Err() will break backward compatibility
  603. return ErrWaitTimeout
  604. }
  605. }
  606. }
  607. // poller returns a WaitFunc that will send to the channel every interval until
  608. // timeout has elapsed and then closes the channel.
  609. //
  610. // Over very short intervals you may receive no ticks before the channel is
  611. // closed. A timeout of 0 is interpreted as an infinity, and in such a case
  612. // it would be the caller's responsibility to close the done channel.
  613. // Failure to do so would result in a leaked goroutine.
  614. //
  615. // Output ticks are not buffered. If the channel is not ready to receive an
  616. // item, the tick is skipped.
  617. func poller(interval, timeout time.Duration) WaitWithContextFunc {
  618. return WaitWithContextFunc(func(ctx context.Context) <-chan struct{} {
  619. ch := make(chan struct{})
  620. go func() {
  621. defer close(ch)
  622. tick := time.NewTicker(interval)
  623. defer tick.Stop()
  624. var after <-chan time.Time
  625. if timeout != 0 {
  626. // time.After is more convenient, but it
  627. // potentially leaves timers around much longer
  628. // than necessary if we exit early.
  629. timer := time.NewTimer(timeout)
  630. after = timer.C
  631. defer timer.Stop()
  632. }
  633. for {
  634. select {
  635. case <-tick.C:
  636. // If the consumer isn't ready for this signal drop it and
  637. // check the other channels.
  638. select {
  639. case ch <- struct{}{}:
  640. default:
  641. }
  642. case <-after:
  643. return
  644. case <-ctx.Done():
  645. return
  646. }
  647. }
  648. }()
  649. return ch
  650. })
  651. }
  652. // ExponentialBackoffWithContext works with a request context and a Backoff. It ensures that the retry wait never
  653. // exceeds the deadline specified by the request context.
  654. func ExponentialBackoffWithContext(ctx context.Context, backoff Backoff, condition ConditionFunc) error {
  655. for backoff.Steps > 0 {
  656. select {
  657. case <-ctx.Done():
  658. return ctx.Err()
  659. default:
  660. }
  661. if ok, err := runConditionWithCrashProtection(condition); err != nil || ok {
  662. return err
  663. }
  664. if backoff.Steps == 1 {
  665. break
  666. }
  667. waitBeforeRetry := backoff.Step()
  668. select {
  669. case <-ctx.Done():
  670. return ctx.Err()
  671. case <-time.After(waitBeforeRetry):
  672. }
  673. }
  674. return ErrWaitTimeout
  675. }