forked from hailocab/go-hostpool
-
Notifications
You must be signed in to change notification settings - Fork 3
/
standard_hostpool.go
298 lines (259 loc) · 6.31 KB
/
standard_hostpool.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
package hostpool
import (
"sync"
"time"
)
// standardHostPoolResponse implements HostPoolResponse
type standardHostPoolResponse struct {
host string
sync.Once
pool HostPool
}
func (r *standardHostPoolResponse) Host() string {
return r.host
}
func (r *standardHostPoolResponse) hostPool() HostPool {
return r.pool
}
func (r *standardHostPoolResponse) Mark(err error) {
r.Do(func() {
doMark(err, r)
})
}
func doMark(err error, r HostPoolResponse) {
if err == nil {
r.hostPool().markSuccess(r)
} else {
r.hostPool().markFailed(r)
}
}
// standardHostPool implements HostPool
type standardHostPool struct {
sync.RWMutex
hosts map[string]*hostEntry
hostList []*hostEntry
returnUnhealthy bool
nextHostIndex int
logger Logger
// Host retry parameters
initialRetryDelay time.Duration
maxRetryInterval time.Duration
// Error budget config
maxFailures int
failureWindow time.Duration
}
type StandardHostPoolOptions struct {
Logger Logger
// Host retry parameters
InitialRetryDelay time.Duration
MaxRetryInterval time.Duration
// Error budget config
MaxFailures int
FailureWindow time.Duration
}
// ------ constants -------------------
const initialRetryDelay = time.Duration(30) * time.Second
const maxRetryInterval = time.Duration(900) * time.Second
const defaultFailureWindow = time.Duration(60) * time.Second
// Construct a basic HostPool using the hostnames provided
func New(hosts []string) HostPool {
p := &standardHostPool{
returnUnhealthy: true,
hosts: make(map[string]*hostEntry, len(hosts)),
hostList: make([]*hostEntry, len(hosts)),
logger: DefaultLogger{},
initialRetryDelay: initialRetryDelay,
maxRetryInterval: maxRetryInterval,
}
for i, h := range hosts {
e := &hostEntry{
host: h,
retryDelay: p.initialRetryDelay,
}
p.hosts[h] = e
p.hostList[i] = e
}
return p
}
func NewWithOptions(hosts []string, options StandardHostPoolOptions) HostPool {
// Initialise with defaults, override from options
p := &standardHostPool{
returnUnhealthy: true,
hosts: make(map[string]*hostEntry, len(hosts)),
hostList: make([]*hostEntry, len(hosts)),
logger: DefaultLogger{},
initialRetryDelay: initialRetryDelay,
maxRetryInterval: maxRetryInterval,
failureWindow: defaultFailureWindow,
}
if options.Logger != nil {
p.logger = options.Logger
}
if options.InitialRetryDelay > 0 {
p.initialRetryDelay = options.InitialRetryDelay
}
if options.MaxRetryInterval > 0 {
p.maxRetryInterval = options.MaxRetryInterval
}
if options.MaxFailures > 0 {
p.maxFailures = options.MaxFailures
}
if options.FailureWindow > 0 {
p.failureWindow = options.FailureWindow
}
for i, h := range hosts {
e := &hostEntry{
host: h,
retryDelay: p.initialRetryDelay,
}
if p.maxFailures > 0 {
// We test for failures > maxFailures, so need an extra slot in the buffer.
e.failures = NewRingBuffer(p.maxFailures + 1)
}
p.hosts[h] = e
p.hostList[i] = e
}
return p
}
// return an entry from the HostPool
func (p *standardHostPool) Get() HostPoolResponse {
p.Lock()
defer p.Unlock()
host := p.getRoundRobin()
if host == "" {
return nil
}
return &standardHostPoolResponse{host: host, pool: p}
}
func (p *standardHostPool) getRoundRobin() string {
now := time.Now()
hostCount := len(p.hostList)
for i := range p.hostList {
// iterate via sequenece from where we last iterated
currentIndex := (i + p.nextHostIndex) % hostCount
h := p.hostList[currentIndex]
if !h.dead {
p.nextHostIndex = currentIndex + 1
return h.host
}
if h.nextRetry.Before(now) {
h.willRetryHost(p.maxRetryInterval)
p.nextHostIndex = currentIndex + 1
return h.host
}
}
// all hosts are down and returnUnhealhy is false then return no host
if !p.returnUnhealthy {
return ""
}
// all hosts are down. re-add them
p.doResetAll()
p.nextHostIndex = 0
return p.hostList[0].host
}
func (p *standardHostPool) ResetAll() {
p.Lock()
defer p.Unlock()
p.doResetAll()
}
func (p *standardHostPool) SetHosts(hosts []string) {
p.Lock()
defer p.Unlock()
p.setHosts(hosts)
}
func (p *standardHostPool) ReturnUnhealthy(v bool) {
p.Lock()
defer p.Unlock()
p.returnUnhealthy = v
}
func (p *standardHostPool) setHosts(hosts []string) {
p.hosts = make(map[string]*hostEntry, len(hosts))
p.hostList = make([]*hostEntry, len(hosts))
for i, h := range hosts {
e := &hostEntry{
host: h,
retryDelay: p.initialRetryDelay,
}
if p.maxFailures > 0 {
// We test for failures > maxFailures, so need an extra slot in the buffer.
e.failures = NewRingBuffer(p.maxFailures + 1)
}
p.hosts[h] = e
p.hostList[i] = e
}
}
// this actually performs the logic to reset,
// and should only be called when the lock has
// already been acquired
func (p *standardHostPool) doResetAll() {
for _, h := range p.hosts {
h.dead = false
}
}
func (p *standardHostPool) Close() {
p.Lock()
defer p.Unlock()
for _, h := range p.hosts {
h.dead = true
}
}
func (p *standardHostPool) markSuccess(hostR HostPoolResponse) {
host := hostR.Host()
p.Lock()
defer p.Unlock()
h, ok := p.hosts[host]
if !ok {
p.logger.Fatalf("host %s not in HostPool %v", host, p.Hosts())
}
h.dead = false
}
func (p *standardHostPool) markFailed(hostR HostPoolResponse) {
host := hostR.Host()
p.Lock()
defer p.Unlock()
h, ok := p.hosts[host]
if !ok {
p.logger.Fatalf("host %s not in HostPool %v", host, p.Hosts())
}
if !h.dead {
if h.failures != nil {
ts := time.Now()
h.failures.insert(ts)
if h.failures.since(ts.Add(-p.failureWindow)) > p.maxFailures {
p.logger.Printf("host %s exceeded %d failures in %s", h.host, p.maxFailures, p.failureWindow)
h.markDead(p.initialRetryDelay)
}
} else {
h.markDead(p.initialRetryDelay)
}
}
}
func (p *standardHostPool) Hosts() []string {
hosts := make([]string, 0, len(p.hosts))
for host := range p.hosts {
hosts = append(hosts, host)
}
return hosts
}
func (p *standardHostPool) Statistics() HostPoolStatistics {
p.RLock()
defer p.RUnlock()
var alive int64 = 0
for _, host := range p.hosts {
if !host.dead {
alive += 1
}
}
return HostPoolStatistics{
Gauges: []Gauge{
{
Name: HostPoolGaugeNumberOfHosts,
Value: int64(len(p.hosts)),
},
{
Name: HostPoolGaugeNumberOfLiveHosts,
Value: alive,
},
},
}
}