-
Notifications
You must be signed in to change notification settings - Fork 1
/
cluster.go
264 lines (216 loc) · 6.64 KB
/
cluster.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
package monitor
import (
"fmt"
"net"
"net/http"
"reflect"
"time"
"sync"
"math"
"encoding/json"
"code.cloudfoundry.org/lager"
"github.com/cloudfoundry-incubator/galera-healthcheck/api"
"github.com/cloudfoundry-incubator/switchboard/domain"
)
//go:generate counterfeiter . UrlGetter
type UrlGetter interface {
Get(url string) (*http.Response, error)
}
func HttpUrlGetterProvider(healthcheckTimeout time.Duration) UrlGetter {
return &http.Client{
Timeout: healthcheckTimeout,
}
}
var UrlGetterProvider = HttpUrlGetterProvider
type BackendStatus struct {
Index int
Healthy bool
Counters *DecisionCounters
}
type Cluster struct {
backends []*domain.Backend
logger lager.Logger
healthcheckTimeout time.Duration
arpEntryRemover ArpEntryRemover
activeBackendSubscribers []chan<- *domain.Backend
lookupIP func(string) ([]net.IP, error)
}
func NewCluster(
backends []*domain.Backend,
healthcheckTimeout time.Duration,
logger lager.Logger,
arpEntryRemover ArpEntryRemover,
activeBackendSubscribers []chan<- *domain.Backend,
lookupIP func(string) ([]net.IP, error),
) *Cluster {
return &Cluster{
backends: backends,
logger: logger,
healthcheckTimeout: healthcheckTimeout,
arpEntryRemover: arpEntryRemover,
activeBackendSubscribers: activeBackendSubscribers,
lookupIP: lookupIP,
}
}
func (c *Cluster) Monitor(stopChan <-chan interface{}) {
client := UrlGetterProvider(c.healthcheckTimeout)
backendHealthMap := make(map[*domain.Backend]*BackendStatus)
for i, backend := range c.backends {
backendHealthMap[backend] = &BackendStatus{
Index: i,
Counters: c.SetupCounters(),
}
}
go func() {
var activeBackend *domain.Backend
for {
select {
case <-time.After(c.healthcheckTimeout / 5):
var wg sync.WaitGroup
for backend, healthStatus := range backendHealthMap {
wg.Add(1)
go func(backend *domain.Backend, healthStatus *BackendStatus) {
defer wg.Done()
c.QueryBackendHealth(backend, healthStatus, client)
}(backend, healthStatus)
}
wg.Wait()
newActiveBackend := ChooseActiveBackend(backendHealthMap)
if newActiveBackend != activeBackend {
if newActiveBackend != nil {
c.logger.Info("New active backend", lager.Data{"backend": newActiveBackend.AsJSON()})
}
activeBackend = newActiveBackend
for _, s := range c.activeBackendSubscribers {
s <- activeBackend
}
}
case <-stopChan:
return
}
}
}()
}
func (c *Cluster) SetupCounters() *DecisionCounters {
counters := NewDecisionCounters()
logFreq := uint64(5)
clearArpFreq := uint64(5)
//used to make logs less noisy
counters.AddCondition("log", func() bool {
return (counters.GetCount("dial") % logFreq) == 0
})
//only clear ARP cache after X consecutive unhealthy dials
counters.AddCondition("clearArp", func() bool {
// golang makes it difficult to tell whether the value of an interface is nil
if reflect.ValueOf(c.arpEntryRemover).IsNil() {
return false
} else {
checks := counters.GetCount("consecutiveUnhealthyChecks")
return (checks > 0) && (checks%clearArpFreq) == 0
}
})
return counters
}
func ChooseActiveBackend(backendHealths map[*domain.Backend]*BackendStatus) *domain.Backend {
var lowestIndexedHealthyDomain *domain.Backend
lowestHealthyIndex := math.MaxUint32
for backend, backendStatus := range backendHealths {
if !backendStatus.Healthy || lowestHealthyIndex <= backendStatus.Index {
continue
}
lowestHealthyIndex = backendStatus.Index
lowestIndexedHealthyDomain = backend
}
return lowestIndexedHealthyDomain
}
func (c *Cluster) determineStateFromBackend(backend *domain.Backend, client UrlGetter, shouldLog bool) (bool, *int) {
j := backend.AsJSON()
url := fmt.Sprintf("http://%s:%d/api/v1/status", j.Host, j.StatusPort)
resp, err := client.Get(url)
/////////////////
// Determine health from either the v1 status endpoint
// or fallback to the v0 status endpoint
var healthy bool
var index *int
if err == nil {
if resp.StatusCode == http.StatusOK {
var v1StatusResponse api.V1StatusResponse
_ = json.NewDecoder(resp.Body).Decode(&v1StatusResponse)
healthy = v1StatusResponse.Healthy
indexVal := int(v1StatusResponse.WsrepLocalIndex)
index = &indexVal
} else if resp.StatusCode == http.StatusNotFound {
url = backend.HealthcheckUrl()
resp, err = client.Get(url)
healthy = (err == nil && resp.StatusCode == http.StatusOK)
}
}
if shouldLog {
if !healthy && err == nil {
c.logger.Error(
"Healthcheck failed on backend",
fmt.Errorf("Backend reported as unhealthy"),
lager.Data{
"backend": backend.AsJSON(),
"endpoint": url,
"resp": fmt.Sprintf("%#v", resp),
},
)
}
if err != nil {
c.logger.Error(
"Healthcheck failed on backend",
fmt.Errorf("Error during healthcheck http get"),
lager.Data{
"backend": backend.AsJSON(),
"endpoint": url,
"resp": fmt.Sprintf("%#v", resp),
"err": err,
},
)
}
if healthy {
c.logger.Debug("Healthcheck succeeded", lager.Data{"endpoint": url})
}
}
return healthy, index
}
func (c *Cluster) QueryBackendHealth(backend *domain.Backend, healthMonitor *BackendStatus, client UrlGetter) {
c.logger.Debug("Querying Backend", lager.Data{"backend": backend, "healthMonitor": healthMonitor})
healthMonitor.Counters.IncrementCount("dial")
shouldLog := healthMonitor.Counters.Should("log")
healthy, index := c.determineStateFromBackend(backend, client, shouldLog)
if index != nil {
healthMonitor.Index = *index
}
if healthy {
c.logger.Debug("Querying Backend: healthy", lager.Data{"backend": backend, "healthMonitor": healthMonitor})
backend.SetHealthy()
healthMonitor.Healthy = true
healthMonitor.Counters.ResetCount("consecutiveUnhealthyChecks")
} else {
c.logger.Debug("Querying Backend: unhealthy", lager.Data{"backend": backend, "healthMonitor": healthMonitor})
backend.SetUnhealthy()
healthMonitor.Healthy = false
healthMonitor.Counters.IncrementCount("consecutiveUnhealthyChecks")
}
if healthMonitor.Counters.Should("clearArp") {
c.logger.Debug("Querying Backend: clear arp", lager.Data{"backend": backend, "healthMonitor": healthMonitor})
backendHost := backend.AsJSON().Host
backendIp := net.ParseIP(backendHost)
if backendIp == nil {
var ips []net.IP
ips, err := c.lookupIP(backendHost)
if err != nil {
c.logger.Error("DNS lookup failed", err)
return
} else {
backendIp = ips[0]
}
}
err := c.arpEntryRemover.RemoveEntry(backendIp)
if err != nil {
c.logger.Error("Failed to clear arp cache", err)
}
}
}