forked from AcalephStorage/consul-alerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
482 lines (402 loc) · 15.3 KB
/
client.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package consul
import (
"fmt"
"strconv"
"strings"
"time"
"encoding/json"
log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
consulapi "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/hashicorp/consul/api"
)
const (
ConfigTypeBool = iota
ConfigTypeString
ConfigTypeInt
ConfigTypeStrArray
)
type configType int
type ConsulAlertClient struct {
api *consulapi.Client
config *ConsulAlertConfig
}
func NewClient(address, dc, aclToken string) (*ConsulAlertClient, error) {
config := consulapi.DefaultConfig()
config.Address = address
config.Datacenter = dc
config.Token = aclToken
api, _ := consulapi.NewClient(config)
alertConfig := DefaultAlertConfig()
client := &ConsulAlertClient{
api: api,
config: alertConfig,
}
try := 1
for {
try += try
log.Println("Checking consul agent connection...")
_, err := client.api.Status().Leader()
if err != nil {
log.Println("Waiting for consul:", err)
if try > 10 {
return nil, err
}
time.Sleep(10000 * time.Millisecond)
} else {
break
}
}
client.LoadConfig()
client.UpdateCheckData()
return client, nil
}
func (c *ConsulAlertClient) LoadConfig() {
if kvPairs, _, err := c.api.KV().List("consul-alerts/config", nil); err == nil {
config := c.config
for _, kvPair := range kvPairs {
key := kvPair.Key
val := kvPair.Value
var valErr error
switch key {
// checks config
case "consul-alerts/config/checks/enabled":
valErr = loadCustomValue(&config.Checks.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/checks/change-threshold":
valErr = loadCustomValue(&config.Checks.ChangeThreshold, val, ConfigTypeInt)
// events config
case "consul-alerts/config/events/enabled":
valErr = loadCustomValue(&config.Events.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/events/handlers":
valErr = loadCustomValue(&config.Events.Handlers, val, ConfigTypeStrArray)
// notifiers config
case "consul-alerts/config/notifiers/custom":
valErr = loadCustomValue(&config.Notifiers.Custom, val, ConfigTypeStrArray)
// email notifier config
case "consul-alerts/config/notifiers/email/cluster-name":
valErr = loadCustomValue(&config.Notifiers.Email.ClusterName, val, ConfigTypeString)
case "consul-alerts/config/notifiers/email/template":
valErr = loadCustomValue(&config.Notifiers.Email.Template, val, ConfigTypeString)
case "consul-alerts/config/notifiers/email/enabled":
valErr = loadCustomValue(&config.Notifiers.Email.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/notifiers/email/password":
valErr = loadCustomValue(&config.Notifiers.Email.Password, val, ConfigTypeString)
case "consul-alerts/config/notifiers/email/port":
valErr = loadCustomValue(&config.Notifiers.Email.Port, val, ConfigTypeInt)
case "consul-alerts/config/notifiers/email/receivers":
valErr = loadCustomValue(&config.Notifiers.Email.Receivers, val, ConfigTypeStrArray)
case "consul-alerts/config/notifiers/email/sender-alias":
valErr = loadCustomValue(&config.Notifiers.Email.SenderAlias, val, ConfigTypeString)
case "consul-alerts/config/notifiers/email/sender-email":
valErr = loadCustomValue(&config.Notifiers.Email.SenderEmail, val, ConfigTypeString)
case "consul-alerts/config/notifiers/email/url":
valErr = loadCustomValue(&config.Notifiers.Email.Url, val, ConfigTypeString)
case "consul-alerts/config/notifiers/email/username":
valErr = loadCustomValue(&config.Notifiers.Email.Username, val, ConfigTypeString)
// log notifier config
case "consul-alerts/config/notifiers/log/enabled":
valErr = loadCustomValue(&config.Notifiers.Log.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/notifiers/log/path":
valErr = loadCustomValue(&config.Notifiers.Log.Path, val, ConfigTypeString)
// influxdb notifier config
case "consul-alerts/config/notifiers/influxdb/enabled":
valErr = loadCustomValue(&config.Notifiers.Influxdb.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/notifiers/influxdb/host":
valErr = loadCustomValue(&config.Notifiers.Influxdb.Host, val, ConfigTypeString)
case "consul-alerts/config/notifiers/influxdb/username":
valErr = loadCustomValue(&config.Notifiers.Influxdb.Username, val, ConfigTypeString)
case "consul-alerts/config/notifiers/influxdb/password":
valErr = loadCustomValue(&config.Notifiers.Influxdb.Password, val, ConfigTypeString)
case "consul-alerts/config/notifiers/influxdb/database":
valErr = loadCustomValue(&config.Notifiers.Influxdb.Database, val, ConfigTypeString)
case "consul-alerts/config/notifiers/influxdb/series-name":
valErr = loadCustomValue(&config.Notifiers.Influxdb.SeriesName, val, ConfigTypeString)
// slack notfier config
case "consul-alerts/config/notifiers/slack/enabled":
valErr = loadCustomValue(&config.Notifiers.Slack.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/notifiers/slack/cluster-name":
valErr = loadCustomValue(&config.Notifiers.Slack.ClusterName, val, ConfigTypeString)
case "consul-alerts/config/notifiers/slack/url":
valErr = loadCustomValue(&config.Notifiers.Slack.Url, val, ConfigTypeString)
case "consul-alerts/config/notifiers/slack/channel":
valErr = loadCustomValue(&config.Notifiers.Slack.Channel, val, ConfigTypeString)
case "consul-alerts/config/notifiers/slack/username":
valErr = loadCustomValue(&config.Notifiers.Slack.Username, val, ConfigTypeString)
case "consul-alerts/config/notifiers/slack/icon-url":
valErr = loadCustomValue(&config.Notifiers.Slack.IconUrl, val, ConfigTypeString)
case "consul-alerts/config/notifiers/slack/icon-emoji":
valErr = loadCustomValue(&config.Notifiers.Slack.IconEmoji, val, ConfigTypeString)
case "consul-alerts/config/notifiers/slack/detailed":
valErr = loadCustomValue(&config.Notifiers.Slack.Detailed, val, ConfigTypeBool)
// pager-duty notfier config
case "consul-alerts/config/notifiers/pagerduty/enabled":
valErr = loadCustomValue(&config.Notifiers.PagerDuty.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/notifiers/pagerduty/service-key":
valErr = loadCustomValue(&config.Notifiers.PagerDuty.ServiceKey, val, ConfigTypeString)
case "consul-alerts/config/notifiers/pagerduty/client-name":
valErr = loadCustomValue(&config.Notifiers.PagerDuty.ClientName, val, ConfigTypeString)
case "consul-alerts/config/notifiers/pagerduty/client-url":
valErr = loadCustomValue(&config.Notifiers.PagerDuty.ClientUrl, val, ConfigTypeString)
// hipchat notfier config
case "consul-alerts/config/notifiers/hipchat/enabled":
valErr = loadCustomValue(&config.Notifiers.HipChat.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/notifiers/hipchat/cluster-name":
valErr = loadCustomValue(&config.Notifiers.HipChat.ClusterName, val, ConfigTypeString)
case "consul-alerts/config/notifiers/hipchat/room-id":
valErr = loadCustomValue(&config.Notifiers.HipChat.RoomId, val, ConfigTypeString)
case "consul-alerts/config/notifiers/hipchat/auth-token":
valErr = loadCustomValue(&config.Notifiers.HipChat.AuthToken, val, ConfigTypeString)
case "consul-alerts/config/notifiers/hipchat/base-url":
valErr = loadCustomValue(&config.Notifiers.HipChat.BaseURL, val, ConfigTypeString)
// OpsGenie notifier config
case "consul-alerts/config/notifiers/opsgenie/enabled":
valErr = loadCustomValue(&config.Notifiers.OpsGenie.Enabled, val, ConfigTypeBool)
case "consul-alerts/config/notifiers/opsgenie/cluster-name":
valErr = loadCustomValue(&config.Notifiers.OpsGenie.ClusterName, val, ConfigTypeString)
case "consul-alerts/config/notifiers/opsgenie/api-key":
valErr = loadCustomValue(&config.Notifiers.OpsGenie.ApiKey, val, ConfigTypeString)
}
if valErr != nil {
log.Printf(`unable to load custom value for "%s". Using default instead. Error: %s`, key, valErr.Error())
}
}
} else {
log.Println("Unable to load custom config, using default instead:", err)
}
}
func loadCustomValue(configVariable interface{}, data []byte, cType configType) (err error) {
switch cType {
case ConfigTypeBool:
var val bool
if val, err = strconv.ParseBool(string(data)); err == nil {
boolConfig := configVariable.(*bool)
*boolConfig = val
}
case ConfigTypeString:
strConfig := configVariable.(*string)
*strConfig = string(data)
case ConfigTypeInt:
var val int
if val, err = strconv.Atoi(string(data)); err == nil {
intConfig := configVariable.(*int)
*intConfig = int(val)
}
case ConfigTypeStrArray:
arrConfig := configVariable.(*[]string)
err = json.Unmarshal(data, arrConfig)
}
return err
}
func (c *ConsulAlertClient) EventsEnabled() bool {
return c.config.Events.Enabled
}
func (c *ConsulAlertClient) ChecksEnabled() bool {
return c.config.Checks.Enabled
}
func (c *ConsulAlertClient) EventHandlers(eventName string) []string {
return c.config.Events.Handlers
}
func (c *ConsulAlertClient) CheckChangeThreshold() int {
return c.config.Checks.ChangeThreshold
}
func (c *ConsulAlertClient) UpdateCheckData() {
healthApi := c.api.Health()
kvApi := c.api.KV()
healths, _, _ := healthApi.State("any", nil)
for _, health := range healths {
node := health.Node
service := health.ServiceID
check := health.CheckID
if service == "" {
service = "_"
}
key := fmt.Sprintf("consul-alerts/checks/%s/%s/%s", node, service, check)
status, _, _ := kvApi.Get(key, nil)
existing := status != nil
localHealth := Check(*health)
if c.IsBlacklisted(&localHealth) {
log.Printf("%s:%s:%s is blacklisted.", node, service, check)
continue
}
if !existing {
c.registerHealthCheck(key, &localHealth)
} else {
c.updateHealthCheck(key, &localHealth)
}
}
}
func (c *ConsulAlertClient) NewAlerts() []Check {
allChecks, _, _ := c.api.KV().List("consul-alerts/checks", nil)
alerts := make([]Check, 0)
for _, kvpair := range allChecks {
key := kvpair.Key
if strings.HasSuffix(key, "/") {
continue
}
var status Status
json.Unmarshal(kvpair.Value, &status)
if status.ForNotification {
status.ForNotification = false
data, _ := json.Marshal(status)
c.api.KV().Put(&consulapi.KVPair{Key: key, Value: data}, nil)
// check if blacklisted
if !c.IsBlacklisted(status.HealthCheck) {
alerts = append(alerts, *status.HealthCheck)
}
}
}
return alerts
}
func (c *ConsulAlertClient) CustomNotifiers() []string {
return c.config.Notifiers.Custom
}
func (c *ConsulAlertClient) EmailConfig() *EmailNotifierConfig {
return c.config.Notifiers.Email
}
func (c *ConsulAlertClient) LogConfig() *LogNotifierConfig {
return c.config.Notifiers.Log
}
func (c *ConsulAlertClient) InfluxdbConfig() *InfluxdbNotifierConfig {
return c.config.Notifiers.Influxdb
}
func (c *ConsulAlertClient) SlackConfig() *SlackNotifierConfig {
return c.config.Notifiers.Slack
}
func (c *ConsulAlertClient) PagerDutyConfig() *PagerDutyNotifierConfig {
return c.config.Notifiers.PagerDuty
}
func (c *ConsulAlertClient) HipChatConfig() *HipChatNotifierConfig {
return c.config.Notifiers.HipChat
}
func (c *ConsulAlertClient) OpsGenieConfig() *OpsGenieNotifierConfig {
return c.config.Notifiers.OpsGenie
}
func (c *ConsulAlertClient) registerHealthCheck(key string, health *Check) {
log.Printf(
"Registering new health check: node=%s, service=%s, check=%s, status=%s",
health.Node,
health.ServiceName,
health.Name,
health.Status,
)
var newStatus Status
if health.Status == "passing" {
newStatus = Status{
Current: health.Status,
CurrentTimestamp: time.Now(),
HealthCheck: health,
}
} else {
newStatus = Status{
Pending: health.Status,
PendingTimestamp: time.Now(),
HealthCheck: health,
}
}
statusData, _ := json.Marshal(newStatus)
c.api.KV().Put(&consulapi.KVPair{Key: key, Value: statusData}, nil)
}
func (c *ConsulAlertClient) updateHealthCheck(key string, health *Check) {
kvpair, _, _ := c.api.KV().Get(key, nil)
val := kvpair.Value
var storedStatus Status
json.Unmarshal(val, &storedStatus)
// no status change if the stored status and latest status is the same
noStatusChange := storedStatus.Current == health.Status
// new pending status if it's a new status and it's not the same as the pending status
newPendingStatus := storedStatus.Current != health.Status && storedStatus.Pending != health.Status
// status is still pending for change. will change if it reaches threshold
stillPendingStatus := storedStatus.Current != health.Status && storedStatus.Pending == health.Status
switch {
case noStatusChange:
if storedStatus.Pending != "" {
storedStatus.Pending = ""
storedStatus.PendingTimestamp = time.Time{}
log.Printf(
"%s:%s:%s is now back to %s.",
health.Node,
health.ServiceName,
health.Name,
storedStatus.Current,
)
}
case newPendingStatus:
storedStatus.Pending = health.Status
storedStatus.PendingTimestamp = time.Now()
log.Printf(
"%s:%s:%s is now pending status change from %s to %s.",
health.Node,
health.ServiceName,
health.Name,
storedStatus.Current,
storedStatus.Pending,
)
case stillPendingStatus:
duration := time.Since(storedStatus.PendingTimestamp)
if int(duration.Seconds()) >= c.config.Checks.ChangeThreshold {
log.Printf(
"%s:%s:%s has changed status from %s to %s.",
health.Node,
health.ServiceName,
health.Name,
storedStatus.Current,
storedStatus.Pending,
)
storedStatus.Current = storedStatus.Pending
storedStatus.CurrentTimestamp = time.Now()
storedStatus.Pending = ""
storedStatus.PendingTimestamp = time.Time{}
storedStatus.ForNotification = true
} else {
log.Printf(
"%s:%s:%s is pending status change from %s to %s for %s.",
health.Node,
health.ServiceName,
health.Name,
storedStatus.Current,
storedStatus.Pending,
duration,
)
}
}
storedStatus.HealthCheck = health
data, _ := json.Marshal(storedStatus)
c.api.KV().Put(&consulapi.KVPair{Key: key, Value: data}, nil)
}
func (c *ConsulAlertClient) CheckStatus(node, serviceId, checkId string) (status, output string) {
if serviceId == "" {
serviceId = "_"
}
key := fmt.Sprintf("consul-alerts/checks/%s/%s/%s", node, serviceId, checkId)
kvPair, _, _ := c.api.KV().Get(key, nil)
if kvPair == nil {
status = ""
output = ""
return
}
var checkStatus Status
json.Unmarshal(kvPair.Value, &checkStatus)
status = checkStatus.Current
output = checkStatus.HealthCheck.Output
return
}
func (c *ConsulAlertClient) IsBlacklisted(check *Check) bool {
node := check.Node
nodeCheckKey := fmt.Sprintf("consul-alerts/config/checks/blacklist/nodes/%s", node)
nodeBlacklisted := c.CheckKeyExists(nodeCheckKey)
service := "_"
serviceBlacklisted := false
if check.ServiceID != "" {
service = check.ServiceID
serviceCheckKey := fmt.Sprintf("consul-alerts/config/checks/blacklist/services/%s", service)
serviceBlacklisted = c.CheckKeyExists(serviceCheckKey)
}
checkId := check.CheckID
checkCheckKey := fmt.Sprintf("consul-alerts/config/checks/blacklist/checks/%s", checkId)
checkBlacklisted := c.CheckKeyExists(checkCheckKey)
singleKey := fmt.Sprintf("consul-alerts/config/checks/blacklist/single/%s/%s/%s", node, service, checkId)
singleBlacklisted := c.CheckKeyExists(singleKey)
return nodeBlacklisted || serviceBlacklisted || checkBlacklisted || singleBlacklisted
}
func (c *ConsulAlertClient) CheckKeyExists(key string) bool {
kvpair, _, err := c.api.KV().Get(key, nil)
return kvpair != nil && err == nil
}