-
Notifications
You must be signed in to change notification settings - Fork 2
/
controller.go
316 lines (260 loc) · 9.86 KB
/
controller.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package main
import (
"context"
"fmt"
"sort"
"sync"
"time"
fthealth "github.com/Financial-Times/go-fthealth/v1_1"
log "github.com/Financial-Times/go-logger"
)
type healthCheckController struct {
healthCheckService healthcheckService
environment string
measuredServices map[string]measuredService
stickyCategoriesFailedServices map[string]int
}
type controller interface {
buildServicesHealthResult(context.Context, []string, bool) (fthealth.HealthResult, map[string]category, error)
runServiceChecksByServiceNames(context.Context, map[string]service, map[string]category) ([]fthealth.CheckResult, error)
runServiceChecksFor(context.Context, map[string]category) ([]fthealth.CheckResult, error)
buildPodsHealthResult(context.Context, string) (fthealth.HealthResult, error)
runPodChecksFor(context.Context, string) ([]fthealth.CheckResult, error)
collectChecksFromCachesFor(context.Context, map[string]category) ([]fthealth.CheckResult, error)
updateCachedHealth(context.Context, map[string]service, map[string]category)
scheduleCheck(measuredService, time.Duration, *time.Timer)
getIndividualPodHealth(context.Context, string) ([]byte, string, error)
addAck(context.Context, string, string) error
updateStickyCategory(context.Context, string, bool) error
removeAck(context.Context, string) error
getEnvironment() string
getSeverityForService(context.Context, string, int32) uint8
getSeverityForPod(context.Context, string, int32) uint8
getMeasuredServices() map[string]measuredService
}
func initializeController(environment string) *healthCheckController {
service := initializeHealthCheckService()
measuredServices := make(map[string]measuredService)
stickyCategoriesFailedServices := make(map[string]int)
return &healthCheckController{
healthCheckService: service,
environment: environment,
measuredServices: measuredServices,
stickyCategoriesFailedServices: stickyCategoriesFailedServices,
}
}
func (c *healthCheckController) getEnvironment() string {
return c.environment
}
func (c *healthCheckController) updateStickyCategory(ctx context.Context, categoryName string, isEnabled bool) error {
return c.healthCheckService.updateCategory(ctx, categoryName, isEnabled)
}
func (c *healthCheckController) removeAck(ctx context.Context, serviceName string) error {
if !c.healthCheckService.isServicePresent(serviceName) {
return fmt.Errorf("cannot find service with name %s", serviceName)
}
err := c.healthCheckService.removeAck(ctx, serviceName)
if err != nil {
return fmt.Errorf("failed to remove ack for service %s: %s", serviceName, err.Error())
}
return nil
}
func (c *healthCheckController) addAck(ctx context.Context, serviceName, ackMessage string) error {
if !c.healthCheckService.isServicePresent(serviceName) {
return fmt.Errorf("cannot find service with name %s", serviceName)
}
err := c.healthCheckService.addAck(ctx, serviceName, ackMessage)
if err != nil {
return fmt.Errorf("failed to add ack message [%s] for service %s: %s", ackMessage, serviceName, err.Error())
}
return nil
}
func (c *healthCheckController) buildServicesHealthResult(ctx context.Context, providedCategories []string, useCache bool) (fthealth.HealthResult, map[string]category, error) {
var checkResults []fthealth.CheckResult
desc := "Health of the whole cluster of the moment served without cache."
availableCategories, err := c.healthCheckService.getCategories(ctx)
if err != nil {
return fthealth.HealthResult{}, nil, fmt.Errorf("cannot build health check result for services: %v", err.Error())
}
matchingCategories := getMatchingCategories(providedCategories, availableCategories)
if useCache {
desc = "Health of the whole cluster served from cache."
checkResults, err = c.collectChecksFromCachesFor(ctx, matchingCategories)
} else {
checkResults, err = c.runServiceChecksFor(ctx, matchingCategories)
}
if err != nil {
return fthealth.HealthResult{}, nil, fmt.Errorf("cannot build health check result for services: %v", err.Error())
}
c.disableStickyFailingCategories(ctx, matchingCategories, checkResults)
finalOk, finalSeverity := getFinalResult(checkResults, matchingCategories)
health := fthealth.HealthResult{
SystemCode: c.environment,
Checks: checkResults,
Description: desc,
Name: c.environment + " cluster health",
SchemaVersion: 1,
Ok: finalOk,
Severity: finalSeverity,
}
sort.Sort(byNameComparator(health.Checks))
return health, matchingCategories, nil
}
func (c *healthCheckController) runServiceChecksByServiceNames(ctx context.Context, services map[string]service, categories map[string]category) ([]fthealth.CheckResult, error) {
deployments, err := c.healthCheckService.getDeployments(ctx)
if err != nil {
return nil, err
}
checks := make([]fthealth.Check, 0, len(services))
for _, service := range services {
check := newServiceHealthCheck(ctx, service, deployments, c.healthCheckService)
checks = append(checks, check)
}
healthChecks := fthealth.RunCheck(fthealth.HealthCheck{
SystemCode: "aggregate-healthcheck",
Name: "Aggregate Healthcheck",
Description: "Forced check run",
Checks: checks,
}).Checks
wg := sync.WaitGroup{}
tempCtx, cancel := context.WithCancel(context.Background())
defer cancel()
for i := range healthChecks {
wg.Add(1)
go func(context context.Context, i int) {
healthCheck := healthChecks[i]
if !healthCheck.Ok {
if unhealthyService, ok := services[healthCheck.Name]; ok {
severity := c.getSeverityForService(context, healthCheck.Name, unhealthyService.appPort)
healthChecks[i].Severity = severity
} else {
log.Warnf("Cannot compute severity for service with name %s because it was not found. Using default value.", healthCheck.Name)
}
}
wg.Done()
}(tempCtx, i)
}
wg.Wait()
for _, service := range services {
if service.ack != "" {
updateHealthCheckWithAckMsg(healthChecks, service.name, service.ack)
}
}
c.updateCachedHealth(tempCtx, services, categories)
return healthChecks, nil
}
func (c *healthCheckController) runServiceChecksFor(ctx context.Context, categories map[string]category) (healthChecks []fthealth.CheckResult, err error) {
serviceNames := getServiceNamesFromCategories(categories)
services := c.healthCheckService.getServicesMapByNames(serviceNames)
healthChecks, err = c.runServiceChecksByServiceNames(ctx, services, categories)
if err != nil {
return nil, err
}
return healthChecks, err
}
//nolint:gocognit
func (c *healthCheckController) disableStickyFailingCategories(ctx context.Context, categories map[string]category, healthChecks []fthealth.CheckResult) {
for catIndex, category := range categories {
if !isEnabledAndSticky(category) {
continue
}
for _, serviceName := range category.services {
for _, healthCheck := range healthChecks {
if healthCheck.Name == serviceName && !healthCheck.Ok {
c.stickyCategoriesFailedServices[serviceName]++
log.Infof("Sticky category [%s] is unhealthy -- check %v/%v.", category.name, c.stickyCategoriesFailedServices[serviceName], category.failureThreshold)
if c.isCategoryThresholdExceeded(serviceName, category.failureThreshold) {
log.Infof("Sticky category [%s] is unhealthy, disabling it.", category.name)
category.isEnabled = false
categories[catIndex] = category
err := c.healthCheckService.updateCategory(ctx, category.name, false)
if err != nil {
log.WithError(err).Errorf("Cannot disable sticky category with name %s.", category.name)
} else {
log.Infof("Category [%s] disabled", category.name)
c.stickyCategoriesFailedServices[serviceName] = 0
}
}
}
}
}
}
}
func (c *healthCheckController) isCategoryThresholdExceeded(serviceName string, failureThreshold int) bool {
return c.stickyCategoriesFailedServices[serviceName] >= failureThreshold
}
func isEnabledAndSticky(category category) bool {
return category.isSticky && category.isEnabled
}
func updateHealthCheckWithAckMsg(healthChecks []fthealth.CheckResult, name string, ackMsg string) {
for i, healthCheck := range healthChecks {
if healthCheck.Name == name {
healthChecks[i].Ack = ackMsg
return
}
}
}
func getFinalResult(checkResults []fthealth.CheckResult, categories map[string]category) (bool, uint8) {
finalOk := true
finalSeverity := defaultSeverity
if len(checkResults) == 0 {
return false, finalSeverity
}
for _, category := range categories {
if !category.isEnabled {
finalOk = false
}
}
for _, checkResult := range checkResults {
if !checkResult.Ok && checkResult.Ack == "" {
finalOk = false
if checkResult.Severity < finalSeverity {
finalSeverity = checkResult.Severity
}
}
}
return finalOk, finalSeverity
}
func getMatchingCategories(providedCategories []string, availableCategories map[string]category) map[string]category {
result := make(map[string]category)
for _, providedCat := range providedCategories {
if _, ok := availableCategories[providedCat]; ok {
result[providedCat] = availableCategories[providedCat]
}
}
return result
}
func getServiceNamesFromCategories(categories map[string]category) []string {
var services []string
if _, ok := categories["default"]; ok {
return services
}
for categoryName := range categories {
servicesForCategory := categories[categoryName].services
for _, service := range servicesForCategory {
if !isStringInSlice(service, services) {
services = append(services, service)
}
}
}
return services
}
func isStringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
//used for sorting checks
type byNameComparator []fthealth.CheckResult
func (s byNameComparator) Less(i, j int) bool {
return s[i].Name < s[j].Name
}
func (s byNameComparator) Len() int {
return len(s)
}
func (s byNameComparator) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}