-
Notifications
You must be signed in to change notification settings - Fork 115
/
monit_retry_strategy.go
76 lines (61 loc) · 1.85 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
package monit
import (
"strings"
"time"
boshhttp "github.com/cloudfoundry/bosh-utils/http"
boshretry "github.com/cloudfoundry/bosh-utils/retrystrategy"
"github.com/pivotal-golang/clock"
)
type monitRetryStrategy struct {
retryable boshhttp.RequestRetryable
maxUnavailableAttempts uint
maxOtherAttempts uint
delay time.Duration
timeService clock.Clock
unavailableAttempts uint
otherAttempts uint
}
func NewMonitRetryStrategy(
retryable boshhttp.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 isRetryable bool
for m.hasMoreAttempts() {
isRetryable, err = m.retryable.Attempt()
if !isRetryable {
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
}