forked from weaveworks/common
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackoff.go
97 lines (82 loc) · 1.98 KB
/
backoff.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package backoff
import (
"time"
log "github.com/sirupsen/logrus"
)
type backoff struct {
f func() (bool, error)
quit, done chan struct{}
msg string
initialBackoff, maxBackoff time.Duration
}
// Interface does f in a loop, sleeping for initialBackoff between
// each iterations. If it hits an error, it exponentially backs
// off to maxBackoff. Backoff will log when it backs off, but
// will stop logging when it reaches maxBackoff. It will also
// log on first success in the beginning and after errors.
type Interface interface {
Start()
Stop()
SetInitialBackoff(time.Duration)
SetMaxBackoff(time.Duration)
}
// New makes a new Interface
func New(f func() (bool, error), msg string) Interface {
return &backoff{
f: f,
quit: make(chan struct{}),
done: make(chan struct{}),
msg: msg,
initialBackoff: 10 * time.Second,
maxBackoff: 60 * time.Second,
}
}
func (b *backoff) SetInitialBackoff(d time.Duration) {
b.initialBackoff = d
}
func (b *backoff) SetMaxBackoff(d time.Duration) {
b.maxBackoff = d
}
// Stop the backoff, and waits for it to stop.
func (b *backoff) Stop() {
close(b.quit)
<-b.done
}
// Start the backoff. Can only be called once.
func (b *backoff) Start() {
defer close(b.done)
backoff := b.initialBackoff
shouldLog := true
for {
done, err := b.f()
if done {
return
}
if err != nil {
backoff *= 2
shouldLog = true
if backoff > b.maxBackoff {
backoff = b.maxBackoff
shouldLog = false
}
} else {
backoff = b.initialBackoff
}
if shouldLog {
if err != nil {
log.Warnf("Error %s, backing off %s: %s",
b.msg, backoff, err)
} else {
log.Infof("Success %s", b.msg)
}
}
// Re-enable logging if we came from an error (suppressed or not)
// since we want to log in case a success follows.
shouldLog = err != nil
select {
case <-time.After(backoff):
case <-b.quit:
return
}
}
}