mirror of
https://github.com/ceph/ceph-csi.git
synced 2025-06-13 10:33:35 +00:00
vendor files
This commit is contained in:
38
vendor/k8s.io/apimachinery/pkg/util/wait/BUILD
generated
vendored
Normal file
38
vendor/k8s.io/apimachinery/pkg/util/wait/BUILD
generated
vendored
Normal file
@ -0,0 +1,38 @@
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
load(
|
||||
"@io_bazel_rules_go//go:def.bzl",
|
||||
"go_library",
|
||||
"go_test",
|
||||
)
|
||||
|
||||
go_test(
|
||||
name = "go_default_test",
|
||||
srcs = ["wait_test.go"],
|
||||
importpath = "k8s.io/apimachinery/pkg/util/wait",
|
||||
library = ":go_default_library",
|
||||
deps = ["//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library"],
|
||||
)
|
||||
|
||||
go_library(
|
||||
name = "go_default_library",
|
||||
srcs = [
|
||||
"doc.go",
|
||||
"wait.go",
|
||||
],
|
||||
importpath = "k8s.io/apimachinery/pkg/util/wait",
|
||||
deps = ["//vendor/k8s.io/apimachinery/pkg/util/runtime:go_default_library"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "package-srcs",
|
||||
srcs = glob(["**"]),
|
||||
tags = ["automanaged"],
|
||||
visibility = ["//visibility:private"],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "all-srcs",
|
||||
srcs = [":package-srcs"],
|
||||
tags = ["automanaged"],
|
||||
)
|
19
vendor/k8s.io/apimachinery/pkg/util/wait/doc.go
generated
vendored
Normal file
19
vendor/k8s.io/apimachinery/pkg/util/wait/doc.go
generated
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package wait provides tools for polling or listening for changes
|
||||
// to a condition.
|
||||
package wait // import "k8s.io/apimachinery/pkg/util/wait"
|
385
vendor/k8s.io/apimachinery/pkg/util/wait/wait.go
generated
vendored
Normal file
385
vendor/k8s.io/apimachinery/pkg/util/wait/wait.go
generated
vendored
Normal file
@ -0,0 +1,385 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package wait
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/runtime"
|
||||
)
|
||||
|
||||
// For any test of the style:
|
||||
// ...
|
||||
// <- time.After(timeout):
|
||||
// t.Errorf("Timed out")
|
||||
// The value for timeout should effectively be "forever." Obviously we don't want our tests to truly lock up forever, but 30s
|
||||
// is long enough that it is effectively forever for the things that can slow down a run on a heavily contended machine
|
||||
// (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.
|
||||
var ForeverTestTimeout = time.Second * 30
|
||||
|
||||
// NeverStop may be passed to Until to make it never stop.
|
||||
var NeverStop <-chan struct{} = make(chan struct{})
|
||||
|
||||
// Group allows to start a group of goroutines and wait for their completion.
|
||||
type Group struct {
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func (g *Group) Wait() {
|
||||
g.wg.Wait()
|
||||
}
|
||||
|
||||
// StartWithChannel starts f in a new goroutine in the group.
|
||||
// stopCh is passed to f as an argument. f should stop when stopCh is available.
|
||||
func (g *Group) StartWithChannel(stopCh <-chan struct{}, f func(stopCh <-chan struct{})) {
|
||||
g.Start(func() {
|
||||
f(stopCh)
|
||||
})
|
||||
}
|
||||
|
||||
// StartWithContext starts f in a new goroutine in the group.
|
||||
// ctx is passed to f as an argument. f should stop when ctx.Done() is available.
|
||||
func (g *Group) StartWithContext(ctx context.Context, f func(context.Context)) {
|
||||
g.Start(func() {
|
||||
f(ctx)
|
||||
})
|
||||
}
|
||||
|
||||
// Start starts f in a new goroutine in the group.
|
||||
func (g *Group) Start(f func()) {
|
||||
g.wg.Add(1)
|
||||
go func() {
|
||||
defer g.wg.Done()
|
||||
f()
|
||||
}()
|
||||
}
|
||||
|
||||
// Forever calls f every period for ever.
|
||||
//
|
||||
// Forever is syntactic sugar on top of Until.
|
||||
func Forever(f func(), period time.Duration) {
|
||||
Until(f, period, NeverStop)
|
||||
}
|
||||
|
||||
// Until loops until stop channel is closed, running f every period.
|
||||
//
|
||||
// Until is syntactic sugar on top of JitterUntil with zero jitter factor and
|
||||
// with sliding = true (which means the timer for period starts after the f
|
||||
// completes).
|
||||
func Until(f func(), period time.Duration, stopCh <-chan struct{}) {
|
||||
JitterUntil(f, period, 0.0, true, stopCh)
|
||||
}
|
||||
|
||||
// NonSlidingUntil loops until stop channel is closed, running f every
|
||||
// period.
|
||||
//
|
||||
// NonSlidingUntil is syntactic sugar on top of JitterUntil with zero jitter
|
||||
// factor, with sliding = false (meaning the timer for period starts at the same
|
||||
// time as the function starts).
|
||||
func NonSlidingUntil(f func(), period time.Duration, stopCh <-chan struct{}) {
|
||||
JitterUntil(f, period, 0.0, false, stopCh)
|
||||
}
|
||||
|
||||
// JitterUntil loops until stop channel is closed, running f every period.
|
||||
//
|
||||
// If jitterFactor is positive, the period is jittered before every run of f.
|
||||
// If jitterFactor is not positive, the period is unchanged and not jittered.
|
||||
//
|
||||
// If sliding is true, the period is computed after f runs. If it is false then
|
||||
// period includes the runtime for f.
|
||||
//
|
||||
// Close stopCh to stop. f may not be invoked if stop channel is already
|
||||
// closed. Pass NeverStop to if you don't want it stop.
|
||||
func JitterUntil(f func(), period time.Duration, jitterFactor float64, sliding bool, stopCh <-chan struct{}) {
|
||||
var t *time.Timer
|
||||
var sawTimeout bool
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-stopCh:
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
jitteredPeriod := period
|
||||
if jitterFactor > 0.0 {
|
||||
jitteredPeriod = Jitter(period, jitterFactor)
|
||||
}
|
||||
|
||||
if !sliding {
|
||||
t = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)
|
||||
}
|
||||
|
||||
func() {
|
||||
defer runtime.HandleCrash()
|
||||
f()
|
||||
}()
|
||||
|
||||
if sliding {
|
||||
t = resetOrReuseTimer(t, jitteredPeriod, sawTimeout)
|
||||
}
|
||||
|
||||
// NOTE: b/c there is no priority selection in golang
|
||||
// it is possible for this to race, meaning we could
|
||||
// trigger t.C and stopCh, and t.C select falls through.
|
||||
// In order to mitigate we re-check stopCh at the beginning
|
||||
// of every loop to prevent extra executions of f().
|
||||
select {
|
||||
case <-stopCh:
|
||||
return
|
||||
case <-t.C:
|
||||
sawTimeout = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Jitter returns a time.Duration between duration and duration + maxFactor *
|
||||
// duration.
|
||||
//
|
||||
// This allows clients to avoid converging on periodic behavior. If maxFactor
|
||||
// is 0.0, a suggested default value will be chosen.
|
||||
func Jitter(duration time.Duration, maxFactor float64) time.Duration {
|
||||
if maxFactor <= 0.0 {
|
||||
maxFactor = 1.0
|
||||
}
|
||||
wait := duration + time.Duration(rand.Float64()*maxFactor*float64(duration))
|
||||
return wait
|
||||
}
|
||||
|
||||
// ErrWaitTimeout is returned when the condition exited without success.
|
||||
var ErrWaitTimeout = errors.New("timed out waiting for the condition")
|
||||
|
||||
// ConditionFunc returns true if the condition is satisfied, or an error
|
||||
// if the loop should be aborted.
|
||||
type ConditionFunc func() (done bool, err error)
|
||||
|
||||
// Backoff holds parameters applied to a Backoff function.
|
||||
type Backoff struct {
|
||||
Duration time.Duration // the base duration
|
||||
Factor float64 // Duration is multiplied by factor each iteration
|
||||
Jitter float64 // The amount of jitter applied each iteration
|
||||
Steps int // Exit with error after this many steps
|
||||
}
|
||||
|
||||
// ExponentialBackoff repeats a condition check with exponential backoff.
|
||||
//
|
||||
// It checks the condition up to Steps times, increasing the wait by multiplying
|
||||
// the previous duration by Factor.
|
||||
//
|
||||
// If Jitter is greater than zero, a random amount of each duration is added
|
||||
// (between duration and duration*(1+jitter)).
|
||||
//
|
||||
// If the condition never returns true, ErrWaitTimeout is returned. All other
|
||||
// errors terminate immediately.
|
||||
func ExponentialBackoff(backoff Backoff, condition ConditionFunc) error {
|
||||
duration := backoff.Duration
|
||||
for i := 0; i < backoff.Steps; i++ {
|
||||
if i != 0 {
|
||||
adjusted := duration
|
||||
if backoff.Jitter > 0.0 {
|
||||
adjusted = Jitter(duration, backoff.Jitter)
|
||||
}
|
||||
time.Sleep(adjusted)
|
||||
duration = time.Duration(float64(duration) * backoff.Factor)
|
||||
}
|
||||
if ok, err := condition(); err != nil || ok {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return ErrWaitTimeout
|
||||
}
|
||||
|
||||
// Poll tries a condition func until it returns true, an error, or the timeout
|
||||
// is reached.
|
||||
//
|
||||
// Poll always waits the interval before the run of 'condition'.
|
||||
// 'condition' will always be invoked at least once.
|
||||
//
|
||||
// Some intervals may be missed if the condition takes too long or the time
|
||||
// window is too short.
|
||||
//
|
||||
// If you want to Poll something forever, see PollInfinite.
|
||||
func Poll(interval, timeout time.Duration, condition ConditionFunc) error {
|
||||
return pollInternal(poller(interval, timeout), condition)
|
||||
}
|
||||
|
||||
func pollInternal(wait WaitFunc, condition ConditionFunc) error {
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
return WaitFor(wait, condition, done)
|
||||
}
|
||||
|
||||
// PollImmediate tries a condition func until it returns true, an error, or the timeout
|
||||
// is reached.
|
||||
//
|
||||
// Poll always checks 'condition' before waiting for the interval. 'condition'
|
||||
// will always be invoked at least once.
|
||||
//
|
||||
// Some intervals may be missed if the condition takes too long or the time
|
||||
// window is too short.
|
||||
//
|
||||
// If you want to Poll something forever, see PollInfinite.
|
||||
func PollImmediate(interval, timeout time.Duration, condition ConditionFunc) error {
|
||||
return pollImmediateInternal(poller(interval, timeout), condition)
|
||||
}
|
||||
|
||||
func pollImmediateInternal(wait WaitFunc, condition ConditionFunc) error {
|
||||
done, err := condition()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
return pollInternal(wait, condition)
|
||||
}
|
||||
|
||||
// PollInfinite tries a condition func until it returns true or an error
|
||||
//
|
||||
// PollInfinite always waits the interval before the run of 'condition'.
|
||||
//
|
||||
// Some intervals may be missed if the condition takes too long or the time
|
||||
// window is too short.
|
||||
func PollInfinite(interval time.Duration, condition ConditionFunc) error {
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
return PollUntil(interval, condition, done)
|
||||
}
|
||||
|
||||
// PollImmediateInfinite tries a condition func until it returns true or an error
|
||||
//
|
||||
// PollImmediateInfinite runs the 'condition' before waiting for the interval.
|
||||
//
|
||||
// Some intervals may be missed if the condition takes too long or the time
|
||||
// window is too short.
|
||||
func PollImmediateInfinite(interval time.Duration, condition ConditionFunc) error {
|
||||
done, err := condition()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
return PollInfinite(interval, condition)
|
||||
}
|
||||
|
||||
// PollUntil tries a condition func until it returns true, an error or stopCh is
|
||||
// closed.
|
||||
//
|
||||
// PolUntil always waits interval before the first run of 'condition'.
|
||||
// 'condition' will always be invoked at least once.
|
||||
func PollUntil(interval time.Duration, condition ConditionFunc, stopCh <-chan struct{}) error {
|
||||
return WaitFor(poller(interval, 0), condition, stopCh)
|
||||
}
|
||||
|
||||
// WaitFunc creates a channel that receives an item every time a test
|
||||
// should be executed and is closed when the last test should be invoked.
|
||||
type WaitFunc func(done <-chan struct{}) <-chan struct{}
|
||||
|
||||
// WaitFor continually checks 'fn' as driven by 'wait'.
|
||||
//
|
||||
// WaitFor gets a channel from 'wait()'', and then invokes 'fn' once for every value
|
||||
// placed on the channel and once more when the channel is closed.
|
||||
//
|
||||
// If 'fn' returns an error the loop ends and that error is returned, and if
|
||||
// 'fn' returns true the loop ends and nil is returned.
|
||||
//
|
||||
// ErrWaitTimeout will be returned if the channel is closed without fn ever
|
||||
// returning true.
|
||||
func WaitFor(wait WaitFunc, fn ConditionFunc, done <-chan struct{}) error {
|
||||
c := wait(done)
|
||||
for {
|
||||
_, open := <-c
|
||||
ok, err := fn()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ok {
|
||||
return nil
|
||||
}
|
||||
if !open {
|
||||
break
|
||||
}
|
||||
}
|
||||
return ErrWaitTimeout
|
||||
}
|
||||
|
||||
// poller returns a WaitFunc that will send to the channel every interval until
|
||||
// timeout has elapsed and then closes the channel.
|
||||
//
|
||||
// Over very short intervals you may receive no ticks before the channel is
|
||||
// closed. A timeout of 0 is interpreted as an infinity.
|
||||
//
|
||||
// Output ticks are not buffered. If the channel is not ready to receive an
|
||||
// item, the tick is skipped.
|
||||
func poller(interval, timeout time.Duration) WaitFunc {
|
||||
return WaitFunc(func(done <-chan struct{}) <-chan struct{} {
|
||||
ch := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
defer close(ch)
|
||||
|
||||
tick := time.NewTicker(interval)
|
||||
defer tick.Stop()
|
||||
|
||||
var after <-chan time.Time
|
||||
if timeout != 0 {
|
||||
// time.After is more convenient, but it
|
||||
// potentially leaves timers around much longer
|
||||
// than necessary if we exit early.
|
||||
timer := time.NewTimer(timeout)
|
||||
after = timer.C
|
||||
defer timer.Stop()
|
||||
}
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-tick.C:
|
||||
// If the consumer isn't ready for this signal drop it and
|
||||
// check the other channels.
|
||||
select {
|
||||
case ch <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
case <-after:
|
||||
return
|
||||
case <-done:
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
return ch
|
||||
})
|
||||
}
|
||||
|
||||
// resetOrReuseTimer avoids allocating a new timer if one is already in use.
|
||||
// Not safe for multiple threads.
|
||||
func resetOrReuseTimer(t *time.Timer, d time.Duration, sawTimeout bool) *time.Timer {
|
||||
if t == nil {
|
||||
return time.NewTimer(d)
|
||||
}
|
||||
if !t.Stop() && !sawTimeout {
|
||||
<-t.C
|
||||
}
|
||||
t.Reset(d)
|
||||
return t
|
||||
}
|
501
vendor/k8s.io/apimachinery/pkg/util/wait/wait_test.go
generated
vendored
Normal file
501
vendor/k8s.io/apimachinery/pkg/util/wait/wait_test.go
generated
vendored
Normal file
@ -0,0 +1,501 @@
|
||||
/*
|
||||
Copyright 2014 The Kubernetes Authors.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package wait
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"k8s.io/apimachinery/pkg/util/runtime"
|
||||
)
|
||||
|
||||
func TestUntil(t *testing.T) {
|
||||
ch := make(chan struct{})
|
||||
close(ch)
|
||||
Until(func() {
|
||||
t.Fatal("should not have been invoked")
|
||||
}, 0, ch)
|
||||
|
||||
ch = make(chan struct{})
|
||||
called := make(chan struct{})
|
||||
go func() {
|
||||
Until(func() {
|
||||
called <- struct{}{}
|
||||
}, 0, ch)
|
||||
close(called)
|
||||
}()
|
||||
<-called
|
||||
close(ch)
|
||||
<-called
|
||||
}
|
||||
|
||||
func TestNonSlidingUntil(t *testing.T) {
|
||||
ch := make(chan struct{})
|
||||
close(ch)
|
||||
NonSlidingUntil(func() {
|
||||
t.Fatal("should not have been invoked")
|
||||
}, 0, ch)
|
||||
|
||||
ch = make(chan struct{})
|
||||
called := make(chan struct{})
|
||||
go func() {
|
||||
NonSlidingUntil(func() {
|
||||
called <- struct{}{}
|
||||
}, 0, ch)
|
||||
close(called)
|
||||
}()
|
||||
<-called
|
||||
close(ch)
|
||||
<-called
|
||||
}
|
||||
|
||||
func TestUntilReturnsImmediately(t *testing.T) {
|
||||
now := time.Now()
|
||||
ch := make(chan struct{})
|
||||
Until(func() {
|
||||
close(ch)
|
||||
}, 30*time.Second, ch)
|
||||
if now.Add(25 * time.Second).Before(time.Now()) {
|
||||
t.Errorf("Until did not return immediately when the stop chan was closed inside the func")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJitterUntil(t *testing.T) {
|
||||
ch := make(chan struct{})
|
||||
// if a channel is closed JitterUntil never calls function f
|
||||
// and returns immediately
|
||||
close(ch)
|
||||
JitterUntil(func() {
|
||||
t.Fatal("should not have been invoked")
|
||||
}, 0, 1.0, true, ch)
|
||||
|
||||
ch = make(chan struct{})
|
||||
called := make(chan struct{})
|
||||
go func() {
|
||||
JitterUntil(func() {
|
||||
called <- struct{}{}
|
||||
}, 0, 1.0, true, ch)
|
||||
close(called)
|
||||
}()
|
||||
<-called
|
||||
close(ch)
|
||||
<-called
|
||||
}
|
||||
|
||||
func TestJitterUntilReturnsImmediately(t *testing.T) {
|
||||
now := time.Now()
|
||||
ch := make(chan struct{})
|
||||
JitterUntil(func() {
|
||||
close(ch)
|
||||
}, 30*time.Second, 1.0, true, ch)
|
||||
if now.Add(25 * time.Second).Before(time.Now()) {
|
||||
t.Errorf("JitterUntil did not return immediately when the stop chan was closed inside the func")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJitterUntilRecoversPanic(t *testing.T) {
|
||||
// Save and restore crash handlers
|
||||
originalReallyCrash := runtime.ReallyCrash
|
||||
originalHandlers := runtime.PanicHandlers
|
||||
defer func() {
|
||||
runtime.ReallyCrash = originalReallyCrash
|
||||
runtime.PanicHandlers = originalHandlers
|
||||
}()
|
||||
|
||||
called := 0
|
||||
handled := 0
|
||||
|
||||
// Hook up a custom crash handler to ensure it is called when a jitter function panics
|
||||
runtime.ReallyCrash = false
|
||||
runtime.PanicHandlers = []func(interface{}){
|
||||
func(p interface{}) {
|
||||
handled++
|
||||
},
|
||||
}
|
||||
|
||||
ch := make(chan struct{})
|
||||
JitterUntil(func() {
|
||||
called++
|
||||
if called > 2 {
|
||||
close(ch)
|
||||
return
|
||||
}
|
||||
panic("TestJitterUntilRecoversPanic")
|
||||
}, time.Millisecond, 1.0, true, ch)
|
||||
|
||||
if called != 3 {
|
||||
t.Errorf("Expected panic recovers")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJitterUntilNegativeFactor(t *testing.T) {
|
||||
now := time.Now()
|
||||
ch := make(chan struct{})
|
||||
called := make(chan struct{})
|
||||
received := make(chan struct{})
|
||||
go func() {
|
||||
JitterUntil(func() {
|
||||
called <- struct{}{}
|
||||
<-received
|
||||
}, time.Second, -30.0, true, ch)
|
||||
}()
|
||||
// first loop
|
||||
<-called
|
||||
received <- struct{}{}
|
||||
// second loop
|
||||
<-called
|
||||
close(ch)
|
||||
received <- struct{}{}
|
||||
|
||||
// it should take at most 2 seconds + some overhead, not 3
|
||||
if now.Add(3 * time.Second).Before(time.Now()) {
|
||||
t.Errorf("JitterUntil did not returned after predefined period with negative jitter factor when the stop chan was closed inside the func")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestExponentialBackoff(t *testing.T) {
|
||||
opts := Backoff{Factor: 1.0, Steps: 3}
|
||||
|
||||
// waits up to steps
|
||||
i := 0
|
||||
err := ExponentialBackoff(opts, func() (bool, error) {
|
||||
i++
|
||||
return false, nil
|
||||
})
|
||||
if err != ErrWaitTimeout || i != opts.Steps {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// returns immediately
|
||||
i = 0
|
||||
err = ExponentialBackoff(opts, func() (bool, error) {
|
||||
i++
|
||||
return true, nil
|
||||
})
|
||||
if err != nil || i != 1 {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// returns immediately on error
|
||||
testErr := fmt.Errorf("some other error")
|
||||
err = ExponentialBackoff(opts, func() (bool, error) {
|
||||
return false, testErr
|
||||
})
|
||||
if err != testErr {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
// invoked multiple times
|
||||
i = 1
|
||||
err = ExponentialBackoff(opts, func() (bool, error) {
|
||||
if i < opts.Steps {
|
||||
i++
|
||||
return false, nil
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
if err != nil || i != opts.Steps {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoller(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
w := poller(time.Millisecond, 2*time.Millisecond)
|
||||
ch := w(done)
|
||||
count := 0
|
||||
DRAIN:
|
||||
for {
|
||||
select {
|
||||
case _, open := <-ch:
|
||||
if !open {
|
||||
break DRAIN
|
||||
}
|
||||
count++
|
||||
case <-time.After(ForeverTestTimeout):
|
||||
t.Errorf("unexpected timeout after poll")
|
||||
}
|
||||
}
|
||||
if count > 3 {
|
||||
t.Errorf("expected up to three values, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
type fakePoller struct {
|
||||
max int
|
||||
used int32 // accessed with atomics
|
||||
wg sync.WaitGroup
|
||||
}
|
||||
|
||||
func fakeTicker(max int, used *int32, doneFunc func()) WaitFunc {
|
||||
return func(done <-chan struct{}) <-chan struct{} {
|
||||
ch := make(chan struct{})
|
||||
go func() {
|
||||
defer doneFunc()
|
||||
defer close(ch)
|
||||
for i := 0; i < max; i++ {
|
||||
select {
|
||||
case ch <- struct{}{}:
|
||||
case <-done:
|
||||
return
|
||||
}
|
||||
if used != nil {
|
||||
atomic.AddInt32(used, 1)
|
||||
}
|
||||
}
|
||||
}()
|
||||
return ch
|
||||
}
|
||||
}
|
||||
|
||||
func (fp *fakePoller) GetWaitFunc() WaitFunc {
|
||||
fp.wg.Add(1)
|
||||
return fakeTicker(fp.max, &fp.used, fp.wg.Done)
|
||||
}
|
||||
|
||||
func TestPoll(t *testing.T) {
|
||||
invocations := 0
|
||||
f := ConditionFunc(func() (bool, error) {
|
||||
invocations++
|
||||
return true, nil
|
||||
})
|
||||
fp := fakePoller{max: 1}
|
||||
if err := pollInternal(fp.GetWaitFunc(), f); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
fp.wg.Wait()
|
||||
if invocations != 1 {
|
||||
t.Errorf("Expected exactly one invocation, got %d", invocations)
|
||||
}
|
||||
used := atomic.LoadInt32(&fp.used)
|
||||
if used != 1 {
|
||||
t.Errorf("Expected exactly one tick, got %d", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollError(t *testing.T) {
|
||||
expectedError := errors.New("Expected error")
|
||||
f := ConditionFunc(func() (bool, error) {
|
||||
return false, expectedError
|
||||
})
|
||||
fp := fakePoller{max: 1}
|
||||
if err := pollInternal(fp.GetWaitFunc(), f); err == nil || err != expectedError {
|
||||
t.Fatalf("Expected error %v, got none %v", expectedError, err)
|
||||
}
|
||||
fp.wg.Wait()
|
||||
used := atomic.LoadInt32(&fp.used)
|
||||
if used != 1 {
|
||||
t.Errorf("Expected exactly one tick, got %d", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollImmediate(t *testing.T) {
|
||||
invocations := 0
|
||||
f := ConditionFunc(func() (bool, error) {
|
||||
invocations++
|
||||
return true, nil
|
||||
})
|
||||
fp := fakePoller{max: 0}
|
||||
if err := pollImmediateInternal(fp.GetWaitFunc(), f); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
// We don't need to wait for fp.wg, as pollImmediate shouldn't call WaitFunc at all.
|
||||
if invocations != 1 {
|
||||
t.Errorf("Expected exactly one invocation, got %d", invocations)
|
||||
}
|
||||
used := atomic.LoadInt32(&fp.used)
|
||||
if used != 0 {
|
||||
t.Errorf("Expected exactly zero ticks, got %d", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollImmediateError(t *testing.T) {
|
||||
expectedError := errors.New("Expected error")
|
||||
f := ConditionFunc(func() (bool, error) {
|
||||
return false, expectedError
|
||||
})
|
||||
fp := fakePoller{max: 0}
|
||||
if err := pollImmediateInternal(fp.GetWaitFunc(), f); err == nil || err != expectedError {
|
||||
t.Fatalf("Expected error %v, got none %v", expectedError, err)
|
||||
}
|
||||
// We don't need to wait for fp.wg, as pollImmediate shouldn't call WaitFunc at all.
|
||||
used := atomic.LoadInt32(&fp.used)
|
||||
if used != 0 {
|
||||
t.Errorf("Expected exactly zero ticks, got %d", used)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollForever(t *testing.T) {
|
||||
ch := make(chan struct{})
|
||||
done := make(chan struct{}, 1)
|
||||
complete := make(chan struct{})
|
||||
go func() {
|
||||
f := ConditionFunc(func() (bool, error) {
|
||||
ch <- struct{}{}
|
||||
select {
|
||||
case <-done:
|
||||
return true, nil
|
||||
default:
|
||||
}
|
||||
return false, nil
|
||||
})
|
||||
|
||||
if err := PollInfinite(time.Microsecond, f); err != nil {
|
||||
t.Fatalf("unexpected error %v", err)
|
||||
}
|
||||
|
||||
close(ch)
|
||||
complete <- struct{}{}
|
||||
}()
|
||||
|
||||
// ensure the condition is opened
|
||||
<-ch
|
||||
|
||||
// ensure channel sends events
|
||||
for i := 0; i < 10; i++ {
|
||||
select {
|
||||
case _, open := <-ch:
|
||||
if !open {
|
||||
t.Fatalf("did not expect channel to be closed")
|
||||
}
|
||||
case <-time.After(ForeverTestTimeout):
|
||||
t.Fatalf("channel did not return at least once within the poll interval")
|
||||
}
|
||||
}
|
||||
|
||||
// at most one poll notification should be sent once we return from the condition
|
||||
done <- struct{}{}
|
||||
go func() {
|
||||
for i := 0; i < 2; i++ {
|
||||
_, open := <-ch
|
||||
if !open {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("expected closed channel after two iterations")
|
||||
}()
|
||||
<-complete
|
||||
}
|
||||
|
||||
func TestWaitFor(t *testing.T) {
|
||||
var invocations int
|
||||
testCases := map[string]struct {
|
||||
F ConditionFunc
|
||||
Ticks int
|
||||
Invoked int
|
||||
Err bool
|
||||
}{
|
||||
"invoked once": {
|
||||
ConditionFunc(func() (bool, error) {
|
||||
invocations++
|
||||
return true, nil
|
||||
}),
|
||||
2,
|
||||
1,
|
||||
false,
|
||||
},
|
||||
"invoked and returns a timeout": {
|
||||
ConditionFunc(func() (bool, error) {
|
||||
invocations++
|
||||
return false, nil
|
||||
}),
|
||||
2,
|
||||
3, // the contract of WaitFor() says the func is called once more at the end of the wait
|
||||
true,
|
||||
},
|
||||
"returns immediately on error": {
|
||||
ConditionFunc(func() (bool, error) {
|
||||
invocations++
|
||||
return false, errors.New("test")
|
||||
}),
|
||||
2,
|
||||
1,
|
||||
true,
|
||||
},
|
||||
}
|
||||
for k, c := range testCases {
|
||||
invocations = 0
|
||||
ticker := fakeTicker(c.Ticks, nil, func() {})
|
||||
err := func() error {
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
return WaitFor(ticker, c.F, done)
|
||||
}()
|
||||
switch {
|
||||
case c.Err && err == nil:
|
||||
t.Errorf("%s: Expected error, got nil", k)
|
||||
continue
|
||||
case !c.Err && err != nil:
|
||||
t.Errorf("%s: Expected no error, got: %#v", k, err)
|
||||
continue
|
||||
}
|
||||
if invocations != c.Invoked {
|
||||
t.Errorf("%s: Expected %d invocations, got %d", k, c.Invoked, invocations)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForWithDelay(t *testing.T) {
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
WaitFor(poller(time.Millisecond, ForeverTestTimeout), func() (bool, error) {
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
return true, nil
|
||||
}, done)
|
||||
// If polling goroutine doesn't see the done signal it will leak timers.
|
||||
select {
|
||||
case done <- struct{}{}:
|
||||
case <-time.After(ForeverTestTimeout):
|
||||
t.Errorf("expected an ack of the done signal.")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPollUntil(t *testing.T) {
|
||||
stopCh := make(chan struct{})
|
||||
called := make(chan bool)
|
||||
pollDone := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
PollUntil(time.Microsecond, ConditionFunc(func() (bool, error) {
|
||||
called <- true
|
||||
return false, nil
|
||||
}), stopCh)
|
||||
|
||||
close(pollDone)
|
||||
}()
|
||||
|
||||
// make sure we're called once
|
||||
<-called
|
||||
// this should trigger a "done"
|
||||
close(stopCh)
|
||||
|
||||
go func() {
|
||||
// release the condition func if needed
|
||||
for {
|
||||
<-called
|
||||
}
|
||||
}()
|
||||
|
||||
// make sure we finished the poll
|
||||
<-pollDone
|
||||
}
|
Reference in New Issue
Block a user