forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alert.go
763 lines (691 loc) · 18.1 KB
/
alert.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
package kapacitor
import (
"bytes"
"encoding/json"
"errors"
"fmt"
html "html/template"
"log"
"net/http"
"os"
"os/exec"
"path"
text "text/template"
"time"
"github.com/influxdata/kapacitor/models"
"github.com/influxdata/kapacitor/pipeline"
"github.com/influxdata/kapacitor/tick"
"github.com/influxdb/influxdb/influxql"
imodels "github.com/influxdb/influxdb/models"
)
// The newest state change is weighted 'weightDiff' times more than oldest state change.
const weightDiff = 1.5
// Maximum weight applied to newest state change.
const maxWeight = 1.2
type AlertHandler func(ad *AlertData)
type AlertLevel int
const (
OKAlert AlertLevel = iota
InfoAlert
WarnAlert
CritAlert
)
func (l AlertLevel) String() string {
switch l {
case OKAlert:
return "OK"
case InfoAlert:
return "INFO"
case WarnAlert:
return "WARNING"
case CritAlert:
return "CRITICAL"
default:
panic("unknown AlertLevel")
}
}
func (l AlertLevel) MarshalText() ([]byte, error) {
return []byte(l.String()), nil
}
func (l *AlertLevel) UnmarshalText(text []byte) error {
s := string(text)
switch s {
case "OK":
*l = OKAlert
case "INFO":
*l = InfoAlert
case "WARNING":
*l = WarnAlert
case "CRITICAL":
*l = CritAlert
default:
return fmt.Errorf("unknown AlertLevel %s", s)
}
return nil
}
type AlertData struct {
ID string `json:"id"`
Message string `json:"message"`
Details string `json:"details"`
Time time.Time `json:"time"`
Level AlertLevel `json:"level"`
Data influxql.Result `json:"data"`
}
type AlertNode struct {
node
a *pipeline.AlertNode
endpoint string
handlers []AlertHandler
levels []*tick.StatefulExpr
states map[models.GroupID]*alertState
idTmpl *text.Template
messageTmpl *text.Template
detailsTmpl *html.Template
}
// Create a new AlertNode which caches the most recent item and exposes it over the HTTP API.
func newAlertNode(et *ExecutingTask, n *pipeline.AlertNode, l *log.Logger) (an *AlertNode, err error) {
an = &AlertNode{
node: node{Node: n, et: et, logger: l},
a: n,
}
an.node.runF = an.runAlert
// Parse templates
an.idTmpl, err = text.New("id").Parse(n.Id)
if err != nil {
return nil, err
}
an.messageTmpl, err = text.New("message").Parse(n.Message)
if err != nil {
return nil, err
}
an.detailsTmpl, err = html.New("details").Funcs(html.FuncMap{
"json": func(v interface{}) html.JS {
a, _ := json.Marshal(v)
return html.JS(a)
},
}).Parse(n.Details)
if err != nil {
return nil, err
}
// Construct alert handlers
an.handlers = make([]AlertHandler, 0)
for _, post := range n.PostHandlers {
post := post
an.handlers = append(an.handlers, func(ad *AlertData) { an.handlePost(post, ad) })
}
for _, email := range n.EmailHandlers {
email := email
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleEmail(email, ad) })
}
if len(n.EmailHandlers) == 0 && (et.tm.SMTPService != nil && et.tm.SMTPService.Global()) {
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleEmail(&pipeline.EmailHandler{}, ad) })
}
// If email has been configured globally only send state changes.
if et.tm.SMTPService != nil && et.tm.SMTPService.Global() {
n.IsStateChangesOnly = true
}
for _, exec := range n.ExecHandlers {
exec := exec
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleExec(exec, ad) })
}
for _, log := range n.LogHandlers {
log := log
if !path.IsAbs(log.FilePath) {
return nil, fmt.Errorf("alert log path must be absolute: %s is not absolute", log.FilePath)
}
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleLog(log, ad) })
}
for _, vo := range n.VictorOpsHandlers {
vo := vo
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleVictorOps(vo, ad) })
}
if len(n.VictorOpsHandlers) == 0 && (et.tm.VictorOpsService != nil && et.tm.VictorOpsService.Global()) {
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleVictorOps(&pipeline.VictorOpsHandler{}, ad) })
}
for _, pd := range n.PagerDutyHandlers {
pd := pd
an.handlers = append(an.handlers, func(ad *AlertData) { an.handlePagerDuty(pd, ad) })
}
if len(n.PagerDutyHandlers) == 0 && (et.tm.PagerDutyService != nil && et.tm.PagerDutyService.Global()) {
an.handlers = append(an.handlers, func(ad *AlertData) { an.handlePagerDuty(&pipeline.PagerDutyHandler{}, ad) })
}
for _, sensu := range n.SensuHandlers {
sensu := sensu
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleSensu(sensu, ad) })
}
for _, slack := range n.SlackHandlers {
slack := slack
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleSlack(slack, ad) })
}
if len(n.SlackHandlers) == 0 && (et.tm.SlackService != nil && et.tm.SlackService.Global()) {
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleSlack(&pipeline.SlackHandler{}, ad) })
}
// If slack has been configured globally only send state changes.
if et.tm.SlackService != nil && et.tm.SlackService.Global() {
n.IsStateChangesOnly = true
}
for _, hipchat := range n.HipChatHandlers {
hipchat := hipchat
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleHipChat(hipchat, ad) })
}
if len(n.HipChatHandlers) == 0 && (et.tm.HipChatService != nil && et.tm.HipChatService.Global()) {
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleHipChat(&pipeline.HipChatHandler{}, ad) })
}
// If HipChat has been configured globally only send state changes.
if et.tm.HipChatService != nil && et.tm.HipChatService.Global() {
n.IsStateChangesOnly = true
}
for _, alerta := range n.AlertaHandlers {
alerta := alerta
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleAlerta(alerta, ad) })
}
for _, og := range n.OpsGenieHandlers {
og := og
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleOpsGenie(og, ad) })
}
if len(n.OpsGenieHandlers) == 0 && (et.tm.OpsGenieService != nil && et.tm.OpsGenieService.Global()) {
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleOpsGenie(&pipeline.OpsGenieHandler{}, ad) })
}
for _, talk := range n.TalkHandlers {
talk := talk
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleTalk(talk, ad) })
}
// Parse level expressions
an.levels = make([]*tick.StatefulExpr, CritAlert+1)
if n.Info != nil {
an.levels[InfoAlert] = tick.NewStatefulExpr(n.Info)
}
if n.Warn != nil {
an.levels[WarnAlert] = tick.NewStatefulExpr(n.Warn)
}
if n.Crit != nil {
an.levels[CritAlert] = tick.NewStatefulExpr(n.Crit)
}
// Setup states
if n.History < 2 {
n.History = 2
}
an.states = make(map[models.GroupID]*alertState)
// Configure flapping
if n.UseFlapping {
if n.FlapLow > 1 || n.FlapHigh > 1 {
return nil, errors.New("alert flap thresholds are percentages and should be between 0 and 1")
}
}
return
}
func (a *AlertNode) runAlert([]byte) error {
switch a.Wants() {
case pipeline.StreamEdge:
for p, ok := a.ins[0].NextPoint(); ok; p, ok = a.ins[0].NextPoint() {
l := a.determineLevel(p.Time, p.Fields, p.Tags)
state := a.updateState(l, p.Group)
if (a.a.UseFlapping && state.flapping) || (a.a.IsStateChangesOnly && !state.changed) {
continue
}
// send alert if we are not OK or we are OK and state changed (i.e recovery)
if l != OKAlert || state.changed {
batch := models.Batch{
Name: p.Name,
Group: p.Group,
Tags: p.Tags,
Points: []models.BatchPoint{models.BatchPointFromPoint(p)},
}
ad, err := a.alertData(p.Name, p.Group, p.Tags, p.Fields, l, p.Time, batch)
if err != nil {
return err
}
for _, h := range a.handlers {
h(ad)
}
}
}
case pipeline.BatchEdge:
for b, ok := a.ins[0].NextBatch(); ok; b, ok = a.ins[0].NextBatch() {
triggered := false
for _, p := range b.Points {
l := a.determineLevel(p.Time, p.Fields, p.Tags)
if l > OKAlert {
triggered = true
state := a.updateState(l, b.Group)
if (a.a.UseFlapping && state.flapping) || (a.a.IsStateChangesOnly && !state.changed) {
break
}
ad, err := a.alertData(b.Name, b.Group, b.Tags, p.Fields, l, p.Time, b)
if err != nil {
return err
}
for _, h := range a.handlers {
h(ad)
}
break
}
}
if !triggered {
state := a.updateState(OKAlert, b.Group)
if state.changed {
var fields models.Fields
if l := len(b.Points); l > 0 {
fields = b.Points[l-1].Fields
}
ad, err := a.alertData(b.Name, b.Group, b.Tags, fields, OKAlert, b.TMax, b)
if err != nil {
return err
}
for _, h := range a.handlers {
h(ad)
}
}
}
}
}
return nil
}
func (a *AlertNode) determineLevel(now time.Time, fields models.Fields, tags map[string]string) (level AlertLevel) {
for l, se := range a.levels {
if se == nil {
continue
}
if pass, err := EvalPredicate(se, now, fields, tags); pass {
level = AlertLevel(l)
} else if err != nil {
a.logger.Println("E! error evaluating expression:", err)
return
} else {
return
}
}
return
}
func (a *AlertNode) batchToResult(b models.Batch) influxql.Result {
row := models.BatchToRow(b)
r := influxql.Result{
Series: imodels.Rows{row},
}
return r
}
func (a *AlertNode) alertData(
name string,
group models.GroupID,
tags models.Tags,
fields models.Fields,
level AlertLevel,
t time.Time,
b models.Batch,
) (*AlertData, error) {
id, err := a.renderID(name, group, tags)
if err != nil {
return nil, err
}
msg, details, err := a.renderMessageAndDetails(id, name, group, tags, fields, level)
if err != nil {
return nil, err
}
ad := &AlertData{
ID: id,
Message: msg,
Details: details,
Time: t,
Level: level,
Data: a.batchToResult(b),
}
return ad, nil
}
type alertState struct {
history []AlertLevel
idx int
flapping bool
changed bool
}
func (a *alertState) addEvent(level AlertLevel) {
a.changed = a.history[a.idx] != level
a.idx = (a.idx + 1) % len(a.history)
a.history[a.idx] = level
}
func (a *alertState) percentChange() float64 {
l := len(a.history)
changes := 0.0
weight := (maxWeight / weightDiff)
step := (maxWeight - weight) / float64(l-1)
for i := 0; i < l-1; i++ {
// get current index
c := (i + a.idx) % l
// get previous index
p := c - 1
// check for wrap around
if p < 0 {
p = l - 1
}
if a.history[c] != a.history[p] {
changes += weight
}
weight += step
}
p := changes / float64(l-1)
return p
}
func (a *AlertNode) updateState(level AlertLevel, group models.GroupID) *alertState {
state, ok := a.states[group]
if !ok {
state = &alertState{
history: make([]AlertLevel, a.a.History),
}
a.states[group] = state
}
state.addEvent(level)
if a.a.UseFlapping {
p := state.percentChange()
if state.flapping && p < a.a.FlapLow {
state.flapping = false
} else if !state.flapping && p > a.a.FlapHigh {
state.flapping = true
}
}
return state
}
// Type containing information available to ID template.
type idInfo struct {
// Measurement name
Name string
// Task name
TaskName string
// Concatenation of all group-by tags of the form [key=value,]+.
// If not groupBy is performed equal to literal 'nil'
Group string
// Map of tags
Tags map[string]string
}
type messageInfo struct {
idInfo
// The ID of the alert.
ID string
// Fields of alerting data point.
Fields map[string]interface{}
// Alert Level, one of: INFO, WARNING, CRITICAL.
Level string
}
type detailsInfo struct {
messageInfo
// The Message of the Alert
Message string
}
func (a *AlertNode) renderID(name string, group models.GroupID, tags models.Tags) (string, error) {
g := string(group)
if group == models.NilGroup {
g = "nil"
}
info := idInfo{
Name: name,
TaskName: a.et.Task.Name,
Group: g,
Tags: tags,
}
var id bytes.Buffer
err := a.idTmpl.Execute(&id, info)
if err != nil {
return "", err
}
return id.String(), nil
}
func (a *AlertNode) renderMessageAndDetails(id, name string, group models.GroupID, tags models.Tags, fields models.Fields, level AlertLevel) (string, string, error) {
g := string(group)
if group == models.NilGroup {
g = "nil"
}
minfo := messageInfo{
idInfo: idInfo{
Name: name,
TaskName: a.et.Task.Name,
Group: g,
Tags: tags,
},
ID: id,
Fields: fields,
Level: level.String(),
}
var msg bytes.Buffer
err := a.messageTmpl.Execute(&msg, minfo)
if err != nil {
return "", "", err
}
dinfo := detailsInfo{
messageInfo: minfo,
Message: msg.String(),
}
var details bytes.Buffer
err = a.detailsTmpl.Execute(&details, dinfo)
if err != nil {
return "", "", err
}
return msg.String(), details.String(), nil
}
//--------------------------------
// Alert handlers
func (a *AlertNode) handlePost(post *pipeline.PostHandler, ad *AlertData) {
b, err := json.Marshal(ad)
if err != nil {
a.logger.Println("E! failed to marshal alert data json", err)
return
}
buf := bytes.NewBuffer(b)
_, err = http.Post(post.URL, "application/json", buf)
if err != nil {
a.logger.Println("E! failed to POST batch", err)
}
}
func (a *AlertNode) handleEmail(email *pipeline.EmailHandler, ad *AlertData) {
if a.et.tm.SMTPService != nil {
err := a.et.tm.SMTPService.SendMail(email.ToList, ad.Message, ad.Details)
if err != nil {
a.logger.Println("E!", err)
}
} else {
a.logger.Println("E! smtp service not enabled, cannot send email.")
}
}
func (a *AlertNode) handleExec(ex *pipeline.ExecHandler, ad *AlertData) {
b, err := json.Marshal(ad)
if err != nil {
a.logger.Println("E! failed to marshal alert data json", err)
return
}
cmd := exec.Command(ex.Command[0], ex.Command[1:]...)
cmd.Stdin = bytes.NewBuffer(b)
var out bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &out
err = cmd.Run()
if err != nil {
a.logger.Println("E! error running alert command:", err, out.String())
return
}
}
func (a *AlertNode) handleLog(l *pipeline.LogHandler, ad *AlertData) {
b, err := json.Marshal(ad)
if err != nil {
a.logger.Println("E! failed to marshal alert data json", err)
return
}
f, err := os.OpenFile(l.FilePath, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
if err != nil {
a.logger.Println("E! failed to open file for alert logging", err)
return
}
defer f.Close()
n, err := f.Write(b)
if n != len(b) || err != nil {
a.logger.Println("E! failed to write to file", err)
}
n, err = f.Write([]byte("\n"))
if n != 1 || err != nil {
a.logger.Println("E! failed to write to file", err)
}
}
func (a *AlertNode) handleVictorOps(vo *pipeline.VictorOpsHandler, ad *AlertData) {
if a.et.tm.VictorOpsService == nil {
a.logger.Println("E! failed to send VictorOps alert. VictorOps is not enabled")
return
}
var messageType string
switch ad.Level {
case OKAlert:
messageType = "RECOVERY"
default:
messageType = ad.Level.String()
}
err := a.et.tm.VictorOpsService.Alert(
vo.RoutingKey,
messageType,
ad.Message,
ad.ID,
ad.Time,
ad.Data,
)
if err != nil {
a.logger.Println("E! failed to send alert data to VictorOps:", err)
return
}
}
func (a *AlertNode) handlePagerDuty(pd *pipeline.PagerDutyHandler, ad *AlertData) {
if a.et.tm.PagerDutyService == nil {
a.logger.Println("E! failed to send PagerDuty alert. PagerDuty is not enabled")
return
}
err := a.et.tm.PagerDutyService.Alert(
ad.ID,
ad.Message,
ad.Data,
)
if err != nil {
a.logger.Println("E! failed to send alert data to PagerDuty:", err)
return
}
}
func (a *AlertNode) handleSensu(sensu *pipeline.SensuHandler, ad *AlertData) {
if a.et.tm.SensuService == nil {
a.logger.Println("E! failed to send Sensu message. Sensu is not enabled")
return
}
err := a.et.tm.SensuService.Alert(
ad.ID,
ad.Message,
ad.Level,
)
if err != nil {
a.logger.Println("E! failed to send alert data to Sensu:", err)
return
}
}
func (a *AlertNode) handleSlack(slack *pipeline.SlackHandler, ad *AlertData) {
if a.et.tm.SlackService == nil {
a.logger.Println("E! failed to send Slack message. Slack is not enabled")
return
}
err := a.et.tm.SlackService.Alert(
slack.Channel,
ad.Message,
ad.Level,
)
if err != nil {
a.logger.Println("E! failed to send alert data to Slack:", err)
return
}
}
func (a *AlertNode) handleHipChat(hipchat *pipeline.HipChatHandler, ad *AlertData) {
if a.et.tm.HipChatService == nil {
a.logger.Println("E! failed to send HipChat message. HipChat is not enabled")
return
}
err := a.et.tm.HipChatService.Alert(
hipchat.Room,
hipchat.Token,
ad.Message,
ad.Level,
)
if err != nil {
a.logger.Println("E! failed to send alert data to HipChat:", err)
return
}
}
func (a *AlertNode) handleAlerta(alerta *pipeline.AlertaHandler, ad *AlertData) {
if a.et.tm.AlertaService == nil {
a.logger.Println("E! failed to send Alerta message. Alerta is not enabled")
return
}
var severity string
var status string
switch ad.Level {
case OKAlert:
severity = "ok"
status = "closed"
case InfoAlert:
severity = "informational"
status = "open"
case WarnAlert:
severity = "warning"
status = "open"
case CritAlert:
severity = "critical"
status = "open"
default:
severity = "unknown"
status = "unknown"
}
err := a.et.tm.AlertaService.Alert(
alerta.Token,
alerta.Resource,
alerta.Event,
alerta.Environment,
severity,
status,
alerta.Group,
alerta.Value,
ad.Message,
alerta.Origin,
ad.Data,
)
if err != nil {
a.logger.Println("E! failed to send alert data to Alerta:", err)
return
}
}
func (a *AlertNode) handleOpsGenie(og *pipeline.OpsGenieHandler, ad *AlertData) {
if a.et.tm.OpsGenieService == nil {
a.logger.Println("E! failed to send OpsGenie alert. OpsGenie is not enabled")
return
}
var messageType string
switch ad.Level {
case OKAlert:
messageType = "RECOVERY"
default:
messageType = ad.Level.String()
}
err := a.et.tm.OpsGenieService.Alert(
og.TeamsList,
og.RecipientsList,
messageType,
ad.Message,
ad.ID,
ad.Time,
ad.Data,
)
if err != nil {
a.logger.Println("E! failed to send alert data to OpsGenie:", err)
return
}
}
func (a *AlertNode) handleTalk(talk *pipeline.TalkHandler, ad *AlertData) {
if a.et.tm.TalkService == nil {
a.logger.Println("E! failed to send Talk message. Talk is not enabled")
return
}
err := a.et.tm.TalkService.Alert(
ad.ID,
ad.Message,
)
if err != nil {
a.logger.Println("E! failed to send alert data to Talk:", err)
return
}
}