forked from bitly/go-hostpool
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcachedpool.go
More file actions
278 lines (241 loc) · 6.54 KB
/
cachedpool.go
File metadata and controls
278 lines (241 loc) · 6.54 KB
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
package hostpool
import (
"bytes"
"encoding/gob"
"fmt"
"log"
"math"
"math/rand"
"net"
"os"
"strings"
"time"
)
type cachedResponse struct {
standardHostPoolResponse
started time.Time
ended time.Time
}
func (r *cachedResponse) Mark(err error) {
r.Do(func() {
r.ended = time.Now()
doMark(err, r)
})
}
type cached interface {
Save(fname string) error
Load(fname string) error
}
type cachedHostPool struct {
standardHostPool
cache []int64
responseValue int64
responseCount int64
index int
clusterLoad float64
maxResponse float64
maxLifespan time.Duration
}
// make sure cachedHostPool implements interface
var _ cached = &cachedHostPool{}
/* Cached hostpool keeps a rolling weighted average of
* cluster response time. Compare this response time
* to a max response time to obtain a "load score". The load
* score is then optimized towards a target load.
*/
func NewCached(hosts []string, fname string, targetLoad float64, maxResponse float64, tickerDuration time.Duration, maxLifespan time.Duration) (HostPool, error) {
stdHP := New(hosts).(*standardHostPool)
p := &cachedHostPool{
standardHostPool: *stdHP,
cache: make([]int64, epsilonBuckets),
index: 0,
clusterLoad: 0,
maxResponse: maxResponse,
maxLifespan: maxLifespan,
}
err := p.Load(fname)
// spawn off goroutine to check cluster health
// see function comment for detail
go p.checkHostHealth()
go func() {
// obtain per bucket duration
durationPerBucket := tickerDuration / epsilonBuckets
ticker := time.Tick(durationPerBucket)
for {
<-ticker
// ignore zero values
if p.responseCount == 0 || p.responseValue == 0 {
continue
}
// calculate the average response time of cluster
p.cache[p.index] = p.responseValue / p.responseCount
// cache to disk every so often
if p.index%10 == 0 {
err := p.Save(fname)
if err != nil {
log.Println("cached hostpool encode error:", err)
}
}
// recalculate the weighted cluster average and load score
p.clusterLoad = p.getClusterResponseTime() / p.maxResponse
// simple function to optimize the clusterLoad towards the
// target load specified. See comment for ShouldPassthru for detail
// set the max rejection at 80% of the traffic to avoid
// blocking all traffic
p.clusterLoad = math.Min(2*p.clusterLoad-targetLoad, 0.80)
// TODO: If the load function is > 1
// should enter an exploration phase for the targetload
// and dynamically modify it
fmt.Printf("Pool debug: Index %d calculated load %f with %d responses\n", p.index, p.clusterLoad, p.responseCount)
// rotate the bucket and reset values
p.index++
p.index = p.index % epsilonBuckets
p.cache[p.index] = 0
p.responseCount = 0
p.responseValue = 0
}
}()
return p, err
}
// Function to ping the cluster every 20s to make sure the
// hosts are alive. Unless a host is dead, it shouldn't
// be taken out of the rotation. A non responding webserver can
// be quickly restarted, a dead machine is more difficult to handle.
// Code modified from http://golang.org/src/pkg/net/ipraw_test.go
func (p *cachedHostPool) checkHostHealth() {
typ := icmpv4EchoRequest
xid, xseq := rand.Intn(0xffff), rand.Intn(0xffff)
wb, _ := (&icmpMessage{
Type: typ, Code: 0,
Body: &icmpEcho{
ID: xid, Seq: xseq,
Data: bytes.Repeat([]byte("ping!"), 3),
},
}).Marshal()
rb := make([]byte, 20+len(wb))
ticker := time.Tick(20 * time.Second)
for {
<-ticker
for _, h := range p.hostList {
c, err := net.Dial("ip4:icmp", strings.Split(h.host, ":")[0])
if err != nil {
continue
}
c.SetDeadline(time.Now().Add(10 * time.Millisecond))
if _, err := c.Write(wb); err != nil {
continue
}
if _, err := c.Read(rb); err != nil {
if err.(net.Error).Timeout() {
// timedout, mark remote as dead
p.Lock()
if !h.dead {
h.dead = true
h.retryCount = 0
h.retryDelay = p.initialRetryDelay
h.nextRetry = time.Now().Add(h.retryDelay)
}
p.Unlock()
}
log.Printf("Conn.Read failed for bidder %s: %v", h.host, err)
}
c.Close()
}
}
}
// weighted average of clustser response time
func (p *cachedHostPool) getClusterResponseTime() float64 {
var bucketCount float64
var value float64
for i := 1; i <= epsilonBuckets; i++ {
pos := (p.index + i) % epsilonBuckets
bucketValue := float64(p.cache[pos])
weight := float64(i) / float64(epsilonBuckets)
if bucketValue > 0 {
value += bucketValue * weight
bucketCount++
}
}
if bucketCount == 0 {
return 0.0
}
return value / bucketCount
}
func ShouldPassthru(h *HostPool) bool {
// We check if clusterLoad is on target. There are some special cases:
// 1. 2*clusterLoad - target < 0: we never reject.
// 2. clusterLoad = target: normal linear operation
// 3. 2*clusterLoad - target > target: we penelize extra based on the difference
if passPct, p := rand.Float64(), (*h).(*cachedHostPool); p.clusterLoad > 0 && passPct < p.clusterLoad {
return false
}
return true
}
func (p *cachedHostPool) Get() HostPoolResponse {
p.Lock()
defer p.Unlock()
host := p.getRoundRobin()
started := time.Now()
return &cachedResponse{
standardHostPoolResponse: standardHostPoolResponse{host: host, pool: p},
started: started,
}
}
func (p *cachedHostPool) markSuccess(resp HostPoolResponse) {
p.standardHostPool.markSuccess(resp)
cResp, _ := resp.(*cachedResponse)
host := cResp.host
duration := cResp.ended.Sub(cResp.started)
p.Lock()
defer p.Unlock()
_, ok := p.hosts[host]
if !ok {
log.Println("host %s not in HostPool %v", host, p.Hosts())
return
}
p.responseCount++
p.responseValue += int64(duration.Seconds() * 1000) // in milli
}
func (p *cachedHostPool) Save(fname string) (err error) {
fp, err := os.Create(fname)
if err != nil {
return
}
defer fp.Close()
enc := gob.NewEncoder(fp)
err = enc.Encode(p.cache)
if err != nil {
return err
}
err = enc.Encode(p.index)
if err != nil {
return err
}
return enc.Encode(p.nextHostIndex)
}
func (p *cachedHostPool) Load(fname string) (err error) {
finfo, err := os.Stat(fname)
if err != nil {
return
}
fileAge := time.Duration(time.Now().Unix()-finfo.ModTime().Unix()) * time.Second
if fileAge >= p.maxLifespan {
fmt.Println("Cache file is too old. It's okay, we will just leave cache empty.")
return
}
fp, err := os.Open(fname)
if err != nil {
return
}
defer fp.Close()
dec := gob.NewDecoder(fp)
err = dec.Decode(&p.cache)
if err != nil {
return
}
err = dec.Decode(&p.index)
if err != nil {
return
}
return dec.Decode(&p.nextHostIndex)
}