forked from influxdata/kapacitor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
alert.go
1113 lines (1000 loc) · 27.4 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
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kapacitor
import (
"bytes"
"encoding/json"
"errors"
"fmt"
html "html/template"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"sync"
text "text/template"
"time"
"github.com/influxdata/influxdb/influxql"
imodels "github.com/influxdata/influxdb/models"
"github.com/influxdata/kapacitor/expvar"
"github.com/influxdata/kapacitor/models"
"github.com/influxdata/kapacitor/pipeline"
"github.com/influxdata/kapacitor/tick/stateful"
)
const (
statsAlertsTriggered = "alerts_triggered"
statsOKsTriggered = "oks_triggered"
statsInfosTriggered = "infos_triggered"
statsWarnsTriggered = "warns_triggered"
statsCritsTriggered = "crits_triggered"
)
// 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"`
Duration time.Duration `json:"duration"`
Level AlertLevel `json:"level"`
Data influxql.Result `json:"data"`
// Info for custom templates
info detailsInfo
}
type AlertNode struct {
node
a *pipeline.AlertNode
endpoint string
handlers []AlertHandler
levels []stateful.Expression
scopePools []stateful.ScopePool
states map[models.GroupID]*alertState
idTmpl *text.Template
messageTmpl *text.Template
detailsTmpl *html.Template
alertsTriggered *expvar.Int
oksTriggered *expvar.Int
infosTriggered *expvar.Int
warnsTriggered *expvar.Int
critsTriggered *expvar.Int
bufPool sync.Pool
}
// 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
// Create buffer pool for the templates
an.bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
// 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 {
tmpBuffer := an.bufPool.Get().(*bytes.Buffer)
defer func() {
tmpBuffer.Reset()
an.bufPool.Put(tmpBuffer)
}()
json.NewEncoder(tmpBuffer).Encode(v)
return html.JS(tmpBuffer.String())
},
}).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 with state changes only set it.
if et.tm.SMTPService != nil &&
et.tm.SMTPService.Global() &&
et.tm.SMTPService.StateChangesOnly() {
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 !filepath.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 with state changes only set it.
if et.tm.SlackService != nil &&
et.tm.SlackService.Global() &&
et.tm.SlackService.StateChangesOnly() {
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 with state changes only set it.
if et.tm.HipChatService != nil &&
et.tm.HipChatService.Global() &&
et.tm.HipChatService.StateChangesOnly() {
n.IsStateChangesOnly = true
}
for _, alerta := range n.AlertaHandlers {
// Validate alerta templates
rtmpl, err := text.New("resource").Parse(alerta.Resource)
if err != nil {
return nil, err
}
evtmpl, err := text.New("event").Parse(alerta.Event)
if err != nil {
return nil, err
}
etmpl, err := text.New("environment").Parse(alerta.Environment)
if err != nil {
return nil, err
}
gtmpl, err := text.New("group").Parse(alerta.Group)
if err != nil {
return nil, err
}
vtmpl, err := text.New("value").Parse(alerta.Value)
if err != nil {
return nil, err
}
ai := alertaHandler{
AlertaHandler: alerta,
resourceTmpl: rtmpl,
eventTmpl: evtmpl,
environmentTmpl: etmpl,
groupTmpl: gtmpl,
valueTmpl: vtmpl,
}
an.handlers = append(an.handlers, func(ad *AlertData) { an.handleAlerta(ai, 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([]stateful.Expression, CritAlert+1)
an.scopePools = make([]stateful.ScopePool, CritAlert+1)
if n.Info != nil {
statefulExpression, expressionCompileError := stateful.NewExpression(n.Info.Expression)
if expressionCompileError != nil {
return nil, fmt.Errorf("Failed to compile stateful expression for info: %s", expressionCompileError)
}
an.levels[InfoAlert] = statefulExpression
an.scopePools[InfoAlert] = stateful.NewScopePool(stateful.FindReferenceVariables(n.Info.Expression))
}
if n.Warn != nil {
statefulExpression, expressionCompileError := stateful.NewExpression(n.Warn.Expression)
if expressionCompileError != nil {
return nil, fmt.Errorf("Failed to compile stateful expression for warn: %s", expressionCompileError)
}
an.levels[WarnAlert] = statefulExpression
an.scopePools[WarnAlert] = stateful.NewScopePool(stateful.FindReferenceVariables(n.Warn.Expression))
}
if n.Crit != nil {
statefulExpression, expressionCompileError := stateful.NewExpression(n.Crit.Expression)
if expressionCompileError != nil {
return nil, fmt.Errorf("Failed to compile stateful expression for crit: %s", expressionCompileError)
}
an.levels[CritAlert] = statefulExpression
an.scopePools[CritAlert] = stateful.NewScopePool(stateful.FindReferenceVariables(n.Crit.Expression))
}
// 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 {
a.alertsTriggered = &expvar.Int{}
a.statMap.Set(statsAlertsTriggered, a.alertsTriggered)
a.oksTriggered = &expvar.Int{}
a.statMap.Set(statsOKsTriggered, a.oksTriggered)
a.infosTriggered = &expvar.Int{}
a.statMap.Set(statsInfosTriggered, a.infosTriggered)
a.warnsTriggered = &expvar.Int{}
a.statMap.Set(statsWarnsTriggered, a.warnsTriggered)
a.critsTriggered = &expvar.Int{}
a.statMap.Set(statsCritsTriggered, a.critsTriggered)
switch a.Wants() {
case pipeline.StreamEdge:
for p, ok := a.ins[0].NextPoint(); ok; p, ok = a.ins[0].NextPoint() {
a.timer.Start()
l := a.determineLevel(p.Time, p.Fields, p.Tags)
state := a.updateState(p.Time, l, p.Group)
if (a.a.UseFlapping && state.flapping) || (a.a.IsStateChangesOnly && !state.changed && !state.expired) {
a.timer.Stop()
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)},
}
state.triggered(p.Time)
duration := state.duration()
ad, err := a.alertData(p.Name, p.Group, p.Tags, p.Fields, l, p.Time, duration, batch)
if err != nil {
return err
}
a.handleAlert(ad)
if a.a.LevelTag != "" || a.a.IdTag != "" {
p.Tags = p.Tags.Copy()
if a.a.LevelTag != "" {
p.Tags[a.a.LevelTag] = l.String()
}
if a.a.IdTag != "" {
p.Tags[a.a.IdTag] = ad.ID
}
}
if a.a.LevelField != "" || a.a.IdField != "" || a.a.DurationField != "" {
p.Fields = p.Fields.Copy()
if a.a.LevelField != "" {
p.Fields[a.a.LevelField] = l.String()
}
if a.a.IdField != "" {
p.Fields[a.a.IdField] = ad.ID
}
if a.a.DurationField != "" {
p.Fields[a.a.DurationField] = int64(duration)
}
}
a.timer.Pause()
for _, child := range a.outs {
err := child.CollectPoint(p)
if err != nil {
return err
}
}
a.timer.Resume()
}
a.timer.Stop()
}
case pipeline.BatchEdge:
for b, ok := a.ins[0].NextBatch(); ok; b, ok = a.ins[0].NextBatch() {
a.timer.Start()
if len(b.Points) == 0 {
a.timer.Stop()
continue
}
// Keep track of lowest level for any point
lowestLevel := CritAlert
// Keep track of highest level and point
highestLevel := OKAlert
var highestPoint *models.BatchPoint
for i, p := range b.Points {
l := a.determineLevel(p.Time, p.Fields, p.Tags)
if l < lowestLevel {
lowestLevel = l
}
if l > highestLevel || highestPoint == nil {
highestLevel = l
highestPoint = &b.Points[i]
}
}
// Default the determined level to lowest.
l := lowestLevel
// Update determined level to highest if we don't care about all
if !a.a.AllFlag {
l = highestLevel
}
// Create alert Data
t := highestPoint.Time
if a.a.AllFlag || l == OKAlert {
t = b.TMax
}
// Update state
state := a.updateState(t, l, b.Group)
// Trigger alert if:
// l == OK and state.changed (aka recovery)
// OR
// l != OK and flapping/statechanges checkout
if state.changed && l == OKAlert ||
(l != OKAlert &&
!((a.a.UseFlapping && state.flapping) ||
(a.a.IsStateChangesOnly && !state.changed && !state.expired))) {
state.triggered(t)
duration := state.duration()
ad, err := a.alertData(b.Name, b.Group, b.Tags, highestPoint.Fields, l, t, duration, b)
if err != nil {
return err
}
a.handleAlert(ad)
// Update tags or fields for Level property
if a.a.LevelTag != "" ||
a.a.LevelField != "" ||
a.a.IdTag != "" ||
a.a.IdField != "" ||
a.a.DurationField != "" {
for i := range b.Points {
if a.a.LevelTag != "" || a.a.IdTag != "" {
b.Points[i].Tags = b.Points[i].Tags.Copy()
if a.a.LevelTag != "" {
b.Points[i].Tags[a.a.LevelTag] = l.String()
}
if a.a.IdTag != "" {
b.Points[i].Tags[a.a.IdTag] = ad.ID
}
}
if a.a.LevelField != "" || a.a.IdField != "" || a.a.DurationField != "" {
b.Points[i].Fields = b.Points[i].Fields.Copy()
if a.a.LevelField != "" {
b.Points[i].Fields[a.a.LevelField] = l.String()
}
if a.a.IdField != "" {
b.Points[i].Fields[a.a.IdField] = ad.ID
}
if a.a.DurationField != "" {
b.Points[i].Fields[a.a.DurationField] = int64(duration)
}
}
}
if a.a.LevelTag != "" || a.a.IdTag != "" {
b.Tags = b.Tags.Copy()
if a.a.LevelTag != "" {
b.Tags[a.a.LevelTag] = l.String()
}
if a.a.IdTag != "" {
b.Tags[a.a.IdTag] = ad.ID
}
}
}
a.timer.Pause()
for _, child := range a.outs {
err := child.CollectBatch(b)
if err != nil {
return err
}
}
a.timer.Resume()
}
a.timer.Stop()
}
}
return nil
}
func (a *AlertNode) handleAlert(ad *AlertData) {
a.alertsTriggered.Add(1)
switch ad.Level {
case OKAlert:
a.oksTriggered.Add(1)
case InfoAlert:
a.infosTriggered.Add(1)
case WarnAlert:
a.warnsTriggered.Add(1)
case CritAlert:
a.critsTriggered.Add(1)
}
a.logger.Printf("D! %v alert triggered id:%s msg:%s data:%v", ad.Level, ad.ID, ad.Message, ad.Data.Series[0])
for _, h := range a.handlers {
h(ad)
}
}
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, a.scopePools[l], 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,
d time.Duration,
b models.Batch,
) (*AlertData, error) {
id, err := a.renderID(name, group, tags)
if err != nil {
return nil, err
}
msg, details, info, err := a.renderMessageAndDetails(id, name, t, group, tags, fields, level)
if err != nil {
return nil, err
}
ad := &AlertData{
ID: id,
Message: msg,
Details: details,
Time: t,
Duration: d,
Level: level,
Data: a.batchToResult(b),
info: info,
}
return ad, nil
}
type alertState struct {
history []AlertLevel
idx int
flapping bool
changed bool
// Time when first alert was triggered
firstTriggered time.Time
// Time when last alert was triggered.
// Note: Alerts are not triggered for every event.
lastTriggered time.Time
expired bool
}
// Return the duration of the current alert state.
func (a *alertState) duration() time.Duration {
return a.lastTriggered.Sub(a.firstTriggered)
}
// Record that the alert was triggered at time t.
func (a *alertState) triggered(t time.Time) {
a.lastTriggered = t
// Check if we are being triggered for first time since an OKAlert
// If so reset firstTriggered time
p := a.idx - 1
if p == -1 {
p = len(a.history) - 1
}
if a.history[p] == OKAlert {
a.firstTriggered = t
}
}
// Record an event in the alert history.
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
}
// Compute the percentage change in the alert history.
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(t time.Time, 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
}
}
state.expired = !state.changed && a.a.StateChangesOnlyDuration != 0 && t.Sub(state.lastTriggered) >= a.a.StateChangesOnlyDuration
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
// Time
Time time.Time
}
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.ID,
Group: g,
Tags: tags,
}
id := a.bufPool.Get().(*bytes.Buffer)
defer func() {
id.Reset()
a.bufPool.Put(id)
}()
err := a.idTmpl.Execute(id, info)
if err != nil {
return "", err
}
return id.String(), nil
}
func (a *AlertNode) renderMessageAndDetails(id, name string, t time.Time, group models.GroupID, tags models.Tags, fields models.Fields, level AlertLevel) (string, string, detailsInfo, error) {
g := string(group)
if group == models.NilGroup {
g = "nil"
}
minfo := messageInfo{
idInfo: idInfo{
Name: name,
TaskName: a.et.Task.ID,
Group: g,
Tags: tags,
},
ID: id,
Fields: fields,
Level: level.String(),
Time: t,
}
// Grab a buffer for the message template and the details template
tmpBuffer := a.bufPool.Get().(*bytes.Buffer)
defer func() {
tmpBuffer.Reset()
a.bufPool.Put(tmpBuffer)
}()
tmpBuffer.Reset()
err := a.messageTmpl.Execute(tmpBuffer, minfo)
if err != nil {
return "", "", detailsInfo{}, err
}
msg := tmpBuffer.String()
dinfo := detailsInfo{
messageInfo: minfo,
Message: msg,
}
// Reuse the buffer, for the details template
tmpBuffer.Reset()
err = a.detailsTmpl.Execute(tmpBuffer, dinfo)
if err != nil {
return "", "", dinfo, err
}
details := tmpBuffer.String()
return msg, details, dinfo, nil
}
//--------------------------------
// Alert handlers
func (a *AlertNode) handlePost(post *pipeline.PostHandler, ad *AlertData) {
bodyBuffer := a.bufPool.Get().(*bytes.Buffer)
defer func() {
bodyBuffer.Reset()
a.bufPool.Put(bodyBuffer)
}()
err := json.NewEncoder(bodyBuffer).Encode(ad)
if err != nil {
a.logger.Println("E! failed to marshal alert data json", err)
return
}
resp, err := http.Post(post.URL, "application/json", bodyBuffer)
if err != nil {
a.logger.Println("E! failed to POST batch", err)
return
}
if resp == nil {
a.logger.Println("E! failed to POST batch response is nil")
return
}
// close http response otherwise tcp socket will be 'ESTABLISHED' in a long time
defer resp.Body.Close()
return
}
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, os.FileMode(l.Mode))
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(
pd.ServiceKey,
ad.ID,
ad.Message,
ad.Level,
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
}
}
type alertaHandler struct {
*pipeline.AlertaHandler
resourceTmpl *text.Template
eventTmpl *text.Template
environmentTmpl *text.Template
valueTmpl *text.Template
groupTmpl *text.Template
}
func (a *AlertNode) handleAlerta(alerta 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
switch ad.Level {
case OKAlert:
severity = "ok"
case InfoAlert:
severity = "informational"
case WarnAlert:
severity = "warning"
case CritAlert:
severity = "critical"
default:
severity = "indeterminate"
}
var buf bytes.Buffer
err := alerta.resourceTmpl.Execute(&buf, ad.info)