-
Notifications
You must be signed in to change notification settings - Fork 115
/
monit_retry_strategy.go
83 lines (66 loc) · 1.93 KB
/
monit_retry_strategy.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
package monit
import (
"net/http"
"strings"
"time"
"code.cloudfoundry.org/clock"
boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy"
)
//go:generate counterfeiter . RequestRetryable
type RequestRetryable interface {
Attempt() (bool, error)
Response() *http.Response
}
type monitRetryStrategy struct {
retryable RequestRetryable
maxUnavailableAttempts uint
maxOtherAttempts uint
delay time.Duration
timeService clock.Clock
unavailableAttempts uint
otherAttempts uint
}
func NewMonitRetryStrategy(
retryable RequestRetryable,
maxUnavailableAttempts uint,
maxOtherAttempts uint,
delay time.Duration,
timeService clock.Clock,
) boshretry.RetryStrategy {
return &monitRetryStrategy{
retryable: retryable,
maxUnavailableAttempts: maxUnavailableAttempts,
maxOtherAttempts: maxOtherAttempts,
unavailableAttempts: 0,
otherAttempts: 0,
delay: delay,
timeService: timeService,
}
}
func (m *monitRetryStrategy) Try() error {
var err error
var shouldRetry bool
for m.hasMoreAttempts() {
shouldRetry, err = m.retryable.Attempt()
if !shouldRetry {
break
}
is503 := m.retryable.Response() != nil && m.retryable.Response().StatusCode == 503
isCanceled := err != nil && strings.Contains(err.Error(), "request canceled")
if (is503 || isCanceled) && m.unavailableAttempts < m.maxUnavailableAttempts {
m.unavailableAttempts = m.unavailableAttempts + 1
} else {
// once a non-503 error is received, all errors count as 'other' errors
m.unavailableAttempts = m.maxUnavailableAttempts + 1
m.otherAttempts = m.otherAttempts + 1
}
m.timeService.Sleep(m.delay)
}
if err != nil && m.retryable.Response() != nil {
_ = m.retryable.Response().Body.Close()
}
return err
}
func (m *monitRetryStrategy) hasMoreAttempts() bool {
return m.unavailableAttempts < m.maxUnavailableAttempts || m.otherAttempts < m.maxOtherAttempts
}