-
Notifications
You must be signed in to change notification settings - Fork 0
/
alert_handler.go
82 lines (71 loc) · 2.17 KB
/
alert_handler.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
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
"text/template"
"time"
promTemplate "github.com/prometheus/alertmanager/template"
)
type alertHandler struct {
sender Sender
firingTemplate *template.Template
resolvedTemplate *template.Template
timeLoc *time.Location
format Format
}
// NewAlertHandler create an HTTP handler to receive prometheus webhook alerts
func NewAlertHandler(config *Config, sender Sender) http.Handler {
return &alertHandler{
sender: sender,
firingTemplate: config.Firing.ToTemplate(),
resolvedTemplate: config.Resolved.ToTemplate(),
timeLoc: config.TimeZone.ToLocation(),
format: config.Format,
}
}
func (a *alertHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
// https://godoc.org/github.com/prometheus/alertmanager/template#Data
promAlert := promTemplate.Data{}
if err := json.NewDecoder(r.Body).Decode(&promAlert); err != nil {
a.handleError(w, http.StatusBadRequest, err, "Cannot decode payload")
return
}
promAlertTriggeredMetric.Inc()
a.instantiateTemplate(a.firingTemplate, promAlert.Alerts.Firing())
a.instantiateTemplate(a.resolvedTemplate, promAlert.Alerts.Resolved())
}
func (a *alertHandler) handleError(w http.ResponseWriter, statusCode int, err error, message string) {
w.WriteHeader(statusCode)
w.Write([]byte("Error: "))
w.Write([]byte(err.Error()))
if message != "" {
w.Write([]byte("\n"))
w.Write([]byte(message))
}
}
func (a *alertHandler) instantiateTemplate(tmpl *template.Template, alerts []promTemplate.Alert) {
if tmpl == nil {
return
}
for _, alert := range alerts {
if a.timeLoc != nil {
alert.StartsAt = alert.StartsAt.In(a.timeLoc)
alert.EndsAt = alert.EndsAt.In(a.timeLoc)
}
if message := a.generateString(tmpl, &alert); message != "" {
promAlertsProcessedMetric.Inc()
a.sender.Send(message, a.format)
}
}
}
func (a *alertHandler) generateString(tmpl *template.Template, alert *promTemplate.Alert) string {
buf := bytes.Buffer{}
if err := tmpl.Execute(&buf, alert); err != nil {
log.Printf("Could not instantiate template :%s\n", err)
return ""
}
return buf.String()
}