-
Notifications
You must be signed in to change notification settings - Fork 2
/
host_availabler.go
188 lines (173 loc) · 4.89 KB
/
host_availabler.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
package core
import (
"fmt"
"sort"
"strings"
"time"
"github.com/byteplus-sdk/sdk-go/core/logs"
"github.com/valyala/fasthttp"
)
const (
pingUrlFormat = "{}://%s/predict/api/ping"
pingInterval = time.Second
windowSize = 60
failureRateThreshold = 0.1
pingTimeout = 200 * time.Millisecond
)
func NewHostAvailabler(urlCenter URLCenter, context *Context) *HostAvailabler {
availabler := &HostAvailabler{
context: context,
urlCenter: urlCenter,
}
availabler.pingUrlFormat = strings.ReplaceAll(pingUrlFormat, "{}", context.Schema())
if len(context.hosts) <= 1 {
return availabler
}
availabler.currentHost = context.hosts[0]
availabler.availableHosts = context.hosts
hostWindowMap := make(map[string]*window, len(context.hosts))
hostHttpCliMap := make(map[string]*fasthttp.HostClient, len(context.hosts))
for _, host := range context.hosts {
hostWindowMap[host] = newWindow(windowSize)
hostHttpCliMap[host] = &fasthttp.HostClient{Addr: host}
}
availabler.hostWindowMap = hostWindowMap
availabler.hostHTTPCliMap = hostHttpCliMap
AsyncExecute(availabler.scheduleFunc())
return availabler
}
type HostAvailabler struct {
abort bool
context *Context
urlCenter URLCenter
currentHost string
availableHosts []string
hostWindowMap map[string]*window
hostHTTPCliMap map[string]*fasthttp.HostClient
pingUrlFormat string
}
func (receiver *HostAvailabler) Shutdown() {
receiver.abort = true
}
func (receiver *HostAvailabler) scheduleFunc() func() {
return func() {
ticker := time.NewTicker(pingInterval)
for true {
if receiver.abort {
ticker.Stop()
return
}
receiver.checkHost()
receiver.switchHost()
<-ticker.C
}
}
}
func (receiver *HostAvailabler) checkHost() {
availableHosts := make([]string, 0, len(receiver.context.hosts))
for _, host := range receiver.context.hosts {
winObj := receiver.hostWindowMap[host]
winObj.put(receiver.ping(host))
if winObj.failureRate() < failureRateThreshold {
availableHosts = append(availableHosts, host)
}
}
receiver.availableHosts = availableHosts
if len(availableHosts) <= 1 {
return
}
sort.Slice(availableHosts, func(i, j int) bool {
failureRateI := receiver.hostWindowMap[availableHosts[i]].failureRate()
failureRateJ := receiver.hostWindowMap[availableHosts[j]].failureRate()
return failureRateI < failureRateJ
})
}
func (receiver *HostAvailabler) ping(host string) bool {
start := time.Now()
request := fasthttp.AcquireRequest()
response := fasthttp.AcquireResponse()
defer func() {
fasthttp.ReleaseRequest(request)
fasthttp.ReleaseResponse(response)
}()
url := fmt.Sprintf(receiver.pingUrlFormat, host)
request.SetRequestURI(url)
request.Header.SetMethod(fasthttp.MethodGet)
for k, v := range receiver.context.CustomerHeaders() {
request.Header.Set(k, v)
}
if len(receiver.context.hostHeader) > 0 {
request.SetHost(receiver.context.hostHeader)
}
httpCli := receiver.hostHTTPCliMap[host]
err := httpCli.DoTimeout(request, response, pingTimeout)
cost := time.Now().Sub(start)
if err == nil && response.StatusCode() == fasthttp.StatusOK {
ReportRequestSuccess(metricsKeyPingSuccess, url, start)
logs.Trace("ping success host:'%s' cost:'%s'", host, cost)
return true
}
if err != nil {
ReportRequestException(metricsKeyPingError, url, start, err)
} else {
ReportRequestError(metricsKeyPingError, url, start, response.StatusCode(), "ping-fail")
}
logs.Warn("ping fail, host:%s cost:%s status:%d err:%v",
host, cost, response.StatusCode(), err)
return false
}
func (receiver *HostAvailabler) switchHost() {
var newHost string
if len(receiver.availableHosts) == 0 {
newHost = receiver.context.hosts[0]
} else {
newHost = receiver.availableHosts[0]
}
if newHost != receiver.currentHost {
logs.Warn("switch host to '%s', origin is '%s'",
newHost, receiver.currentHost)
receiver.currentHost = newHost
receiver.urlCenter.Refresh(newHost)
if receiver.context.hostHeader != "" {
receiver.context.hostHTTPCli = &fasthttp.HostClient{Addr: newHost}
}
}
}
func newWindow(size int) *window {
result := &window{
size: size,
items: make([]bool, size),
head: size - 1,
tail: 0,
failureCount: 0,
}
for i := range result.items {
result.items[i] = true
}
return result
}
type window struct {
size int
items []bool
head int
tail int
failureCount float64
}
func (receiver *window) put(success bool) {
if !success {
receiver.failureCount++
}
receiver.head = (receiver.head + 1) % receiver.size
receiver.items[receiver.head] = success
receiver.tail = (receiver.tail + 1) % receiver.size
removingItem := receiver.items[receiver.tail]
if !removingItem {
receiver.failureCount--
}
}
func (receiver *window) failureRate() float64 {
return receiver.failureCount / float64(receiver.size)
}
func (receiver *window) String() string {
return fmt.Sprintf("%+v", *receiver)
}