This repository has been archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
cluster_monitor.go
229 lines (186 loc) · 5.64 KB
/
cluster_monitor.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
package monitor
import (
"fmt"
"net/http"
"time"
"sync"
"math"
"encoding/json"
"code.cloudfoundry.org/lager"
"github.com/cloudfoundry-incubator/galera-healthcheck/api"
"github.com/cloudfoundry-incubator/switchboard/domain"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . 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 ClusterMonitor struct {
backends []*domain.Backend
logger lager.Logger
healthcheckTimeout time.Duration
backendSubscribers []chan<- *domain.Backend
useLowestIndex bool
}
func NewClusterMonitor(
backends []*domain.Backend,
healthcheckTimeout time.Duration,
logger lager.Logger,
useLowestIndex bool,
) *ClusterMonitor {
return &ClusterMonitor{
backends: backends,
logger: logger,
healthcheckTimeout: healthcheckTimeout,
useLowestIndex: useLowestIndex,
}
}
func (c *ClusterMonitor) Monitor(stopChan <-chan interface{}) {
client := UrlGetterProvider(c.healthcheckTimeout)
backendHealthMap := make(map[*domain.Backend]*BackendStatus)
for _, backend := range c.backends {
backendHealthMap[backend] = &BackendStatus{
Index: -1,
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, c.useLowestIndex)
if newActiveBackend != activeBackend {
if newActiveBackend != nil {
c.logger.Info("New active backend", lager.Data{"backend": newActiveBackend.AsJSON()})
}
activeBackend = newActiveBackend
for _, s := range c.backendSubscribers {
s <- activeBackend
}
}
case <-stopChan:
return
}
}
}()
}
func (c *ClusterMonitor) RegisterBackendSubscriber(newSubscriber chan<- *domain.Backend) {
c.backendSubscribers = append(c.backendSubscribers, newSubscriber)
}
func (c *ClusterMonitor) SetupCounters() *DecisionCounters {
counters := NewDecisionCounters()
logFreq := uint64(5)
//used to make logs less noisy
counters.AddCondition("log", func() bool {
return (counters.GetCount("dial") % logFreq) == 0
})
return counters
}
func ChooseActiveBackend(backendHealths map[*domain.Backend]*BackendStatus, useLowestIndex bool) *domain.Backend {
var lowestIndexedHealthyBackend, highestIndexedHealthyBackend *domain.Backend
lowestHealthyIndex := math.MaxUint32
highestHealthyIndex := -1
for backend, backendStatus := range backendHealths {
if !backendStatus.Healthy {
continue
}
if backendStatus.Index <= lowestHealthyIndex {
lowestHealthyIndex = backendStatus.Index
lowestIndexedHealthyBackend = backend
}
if backendStatus.Index >= highestHealthyIndex {
highestHealthyIndex = backendStatus.Index
highestIndexedHealthyBackend = backend
}
}
if useLowestIndex {
return lowestIndexedHealthyBackend
} else {
return highestIndexedHealthyBackend
}
}
func (c *ClusterMonitor) 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)
healthy := false
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
}
}
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.Error(),
},
)
}
if healthy {
c.logger.Debug("Healthcheck succeeded", lager.Data{"endpoint": url})
}
}
return healthy, index
}
func (c *ClusterMonitor) QueryBackendHealth(backend *domain.Backend, healthMonitor *BackendStatus, client UrlGetter) {
c.logger.Debug("Querying Backend", lager.Data{"backend": backend.AsJSON(), "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.AsJSON(), "healthMonitor": healthMonitor})
backend.SetHealthy()
healthMonitor.Healthy = true
healthMonitor.Counters.ResetCount("consecutiveUnhealthyChecks")
} else {
c.logger.Debug("Querying Backend: unhealthy", lager.Data{"backend": backend.AsJSON(), "healthMonitor": healthMonitor})
backend.SetUnhealthy()
healthMonitor.Healthy = false
healthMonitor.Counters.IncrementCount("consecutiveUnhealthyChecks")
}
}