forked from FXinnovation/alertmanager-webhook-servicenow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
473 lines (394 loc) · 13 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/prometheus/common/version"
"gopkg.in/alecthomas/kingpin.v2"
"gopkg.in/yaml.v2"
"github.com/prometheus/common/log"
"crypto/md5"
tmpltext "text/template"
)
var (
configFile = kingpin.Flag("config.file", "ServiceNow configuration file.").Default("config/servicenow.yml").String()
listenAddress = kingpin.Flag("web.listen-address", "The address to listen on for HTTP requests.").Default(":9877").String()
config Config
serviceNow ServiceNow
noUpdateStates map[json.Number]bool
incidentUpdateFields map[string]bool
webhookRequests = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "webhook_requests_total",
Help: "Total number of HTTP requests on /webhook.",
},
[]string{"code"},
)
webhookLastRequest = promauto.NewGauge(
prometheus.GaugeOpts{
Name: "webhook_last_request_time_seconds",
Help: "Unix/epoch time of the last HTTP request on /webhook.",
},
)
webhookIncidentValidationError = promauto.NewCounter(
prometheus.CounterOpts{
Name: "webhook_incident_validation_errors_total",
Help: "Total number of incident validation errors.",
},
)
webhookIncidentTemplateError = promauto.NewCounter(
prometheus.CounterOpts{
Name: "webhook_incident_template_errors_total",
Help: "Total number of incident template errors.",
},
)
serviceNowRequests = promauto.NewCounterVec(
prometheus.CounterOpts{
Name: "servicenow_requests_total",
Help: "Total number of HTTP requests to ServiceNow instance.",
},
[]string{"host", "method", "code"},
)
serviceNowLastRequest = promauto.NewGauge(
prometheus.GaugeOpts{
Name: "servicenow_last_request_time_seconds",
Help: "Unix/epoch time of the last HTTP request to ServiceNow instance.",
},
)
serviceNowError = promauto.NewCounter(
prometheus.CounterOpts{
Name: "servicenow_errors_total",
Help: "Total number of ServiceNow errors.",
},
)
)
// Config - ServiceNow webhook configuration
type Config struct {
ServiceNow ServiceNowConfig `yaml:"service_now"`
Workflow WorkflowConfig `yaml:"workflow"`
DefaultIncident map[string]string `yaml:"default_incident"`
}
// ServiceNowConfig - ServiceNow instance configuration
type ServiceNowConfig struct {
InstanceName string `yaml:"instance_name"`
UserName string `yaml:"user_name"`
Password string `yaml:"password"`
}
// WorkflowConfig - Incident workflow configuration
type WorkflowConfig struct {
IncidentGroupKeyField string `yaml:"incident_group_key_field"`
NoUpdateStates []json.Number `yaml:"no_update_states"`
IncidentUpdateFields []string `yaml:"incident_update_fields"`
}
// JSONResponse is the Webhook http response
type JSONResponse struct {
Status int
Message string
}
func init() {
prometheus.MustRegister(version.NewCollector("alertmanager_webhook_servicenow"))
}
func (c Config) validate() error {
var errs strings.Builder
if len(c.ServiceNow.InstanceName) == 0 {
errs.WriteString("instance_name is missing\n")
}
if len(c.ServiceNow.UserName) == 0 {
errs.WriteString("user_name is missing\n")
}
if len(c.ServiceNow.Password) == 0 {
errs.WriteString("password is missing\n")
}
if len(c.Workflow.IncidentGroupKeyField) == 0 {
errs.WriteString("incident_group_key_field is missing\n")
}
if errs.Len() > 0 {
return errors.New("Config file is invalid\n" + errs.String())
}
return nil
}
func webhook(w http.ResponseWriter, r *http.Request) {
data, err := readRequestBody(r)
if err != nil {
log.Errorf("Error reading request body : %v", err)
sendJSONResponse(w, http.StatusBadRequest, err.Error())
return
}
err = onAlertGroup(data)
if err != nil {
log.Errorf("Error managing incident from alert : %v", err)
sendJSONResponse(w, http.StatusInternalServerError, err.Error())
return
}
// Returns a 200 if everything went smoothly
sendJSONResponse(w, http.StatusOK, "Success")
}
func homepage(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>alertmanager-webhook-servicenow</title></head>
<body>
<h1>alertmanager-webhook-servicenow</h1>
<p><a href="/metrics">Metrics</a></p>
</body>
</html>`))
}
// Starts the following http handler:
// - basic home page on /
// - Alertmanager webhook entry point on /webhook
// - health metrics on /metrics
func main() {
kingpin.Version(version.Print("alertmanager-webhook-servicenow"))
kingpin.HelpFlag.Short('h')
kingpin.Parse()
_, err := loadConfig(*configFile)
if err != nil {
log.Fatalf("Error loading config file: %v", err)
}
_, err = loadSnClient()
if err != nil {
log.Fatalf("Error loading ServiceNow client: %v", err)
}
log.Info("Starting webhook", version.Info())
log.Info("Build context", version.BuildContext())
http.HandleFunc("/", homepage)
http.HandleFunc("/webhook", webhook)
http.Handle("/metrics", promhttp.Handler())
log.Infof("listening on: %v", *listenAddress)
log.Fatal(http.ListenAndServe(*listenAddress, nil))
}
func sendJSONResponse(w http.ResponseWriter, status int, message string) {
webhookRequests.WithLabelValues(strconv.Itoa(status)).Inc()
webhookLastRequest.SetToCurrentTime()
data := JSONResponse{
Status: status,
Message: message,
}
bytes, _ := json.Marshal(data)
w.WriteHeader(status)
_, err := w.Write(bytes)
if err != nil {
log.Errorf("Error writing JSON response: %s", err)
}
}
func readRequestBody(r *http.Request) (template.Data, error) {
// Do not forget to close the body at the end
defer r.Body.Close()
// Extract data from the body in the Data template provided by AlertManager
data := template.Data{}
err := json.NewDecoder(r.Body).Decode(&data)
return data, err
}
func loadConfigContent(configData []byte) (Config, error) {
config = Config{}
var err error
err = yaml.Unmarshal([]byte(configData), &config)
if err != nil {
return config, err
}
loadEnvVars(&config)
err = config.validate()
if err != nil {
return config, err
}
// Load internal state from config
noUpdateStates = make(map[json.Number]bool, len(config.Workflow.NoUpdateStates))
for _, s := range config.Workflow.NoUpdateStates {
noUpdateStates[s] = true
}
// Load internal incidents update fields from config
incidentUpdateFields = make(map[string]bool, len(config.Workflow.IncidentUpdateFields))
for _, f := range config.Workflow.IncidentUpdateFields {
incidentUpdateFields[f] = true
}
log.Info("ServiceNow config loaded")
return config, nil
}
func loadConfig(configFile string) (Config, error) {
// Load the config from the file
configData, err := ioutil.ReadFile(configFile)
if err != nil {
return Config{}, err
}
return loadConfigContent(configData)
}
func loadEnvVars(c *Config) {
if instanceName, ok := os.LookupEnv("SERVICENOW_INSTANCE_NAME"); ok {
(*c).ServiceNow.InstanceName = instanceName
}
if userName, ok := os.LookupEnv("SERVICENOW_USERNAME"); ok {
(*c).ServiceNow.UserName = userName
}
if password, ok := os.LookupEnv("SERVICENOW_PASSWORD"); ok {
(*c).ServiceNow.Password = password
}
if incidentField, ok := os.LookupEnv("SERVICENOW_INCIDENT_GROUP_KEY_FIELD"); ok {
(*c).Workflow.IncidentGroupKeyField = incidentField
}
}
func loadSnClient() (ServiceNow, error) {
var err error
serviceNow, err = NewServiceNowClient(config.ServiceNow.InstanceName, config.ServiceNow.UserName, config.ServiceNow.Password)
if err != nil {
return serviceNow, err
}
return serviceNow, nil
}
func onAlertGroup(data template.Data) error {
log.Infof("Received alert group: Status=%s, GroupLabels=%v, CommonLabels=%v, CommonAnnotations=%v",
data.Status, data.GroupLabels, data.CommonLabels, data.CommonAnnotations)
getParams := map[string]string{
config.Workflow.IncidentGroupKeyField: getGroupKey(data),
}
existingIncidents, err := serviceNow.GetIncidents(getParams)
if err != nil {
serviceNowError.Inc()
return err
}
log.Infof("Found %v existing incident(s) for alert group key: %s.", len(existingIncidents), getGroupKey(data))
updatableIncidents := filterUpdatableIncidents(existingIncidents)
log.Infof("Found %v updatable incident(s) for alert group key: %s.", len(updatableIncidents), getGroupKey(data))
var updatableIncident Incident
if len(updatableIncidents) > 0 {
updatableIncident = updatableIncidents[0]
if len(updatableIncidents) > 1 {
log.Warnf("As multiple updable incidents were found for alert group key: %s, first one will be used: %s", getGroupKey(data), updatableIncident.GetNumber())
}
}
if data.Status == "firing" {
return onFiringGroup(data, updatableIncident)
} else if data.Status == "resolved" {
return onResolvedGroup(data, updatableIncident)
} else {
log.Errorf("Unknown alert group status: %s", data.Status)
}
return nil
}
func onFiringGroup(data template.Data, updatableIncident Incident) error {
incidentCreateParam, err := alertGroupToIncident(data)
if err != nil {
return err
}
incidentUpdateParam := filterForUpdate(incidentCreateParam)
if updatableIncident == nil {
log.Infof("Found no updatable incident for firing alert group key: %s", getGroupKey(data))
if _, err := serviceNow.CreateIncident(incidentCreateParam); err != nil {
serviceNowError.Inc()
return err
}
} else {
log.Infof("Found updatable incident (%s), with state %s, for firing alert group key: %s", updatableIncident.GetNumber(), updatableIncident.GetState(), getGroupKey(data))
if _, err := serviceNow.UpdateIncident(incidentUpdateParam, updatableIncident.GetSysID()); err != nil {
serviceNowError.Inc()
return err
}
}
return nil
}
func onResolvedGroup(data template.Data, updatableIncident Incident) error {
incidentCreateParam, err := alertGroupToIncident(data)
if err != nil {
return err
}
incidentUpdateParam := filterForUpdate(incidentCreateParam)
if updatableIncident == nil {
log.Infof("Found no updatable incident for resolved alert group key: %s. No incident will be created/updated.", getGroupKey(data))
} else {
log.Infof("Found updatable incident (%s), with state %s, for resolved alert group key: %s", updatableIncident.GetNumber(), updatableIncident.GetState(), getGroupKey(data))
if _, err := serviceNow.UpdateIncident(incidentUpdateParam, updatableIncident.GetSysID()); err != nil {
serviceNowError.Inc()
return err
}
}
return nil
}
func alertGroupToIncident(data template.Data) (Incident, error) {
incident := Incident{
"caller_id": config.ServiceNow.UserName,
config.Workflow.IncidentGroupKeyField: getGroupKey(data),
}
for k, v := range config.DefaultIncident {
incident[k] = v
}
applyIncidentTemplate(incident, data)
err := validateIncident(incident)
if err != nil {
webhookIncidentValidationError.Inc()
log.Error(err)
}
return incident, nil
}
func filterForUpdate(incident Incident) Incident {
incidentUpdate := Incident{}
for field, value := range incident {
if incidentUpdateFields[field] {
incidentUpdate[field] = value
}
}
return incidentUpdate
}
func filterUpdatableIncidents(incidents []Incident) []Incident {
var updatableIncidents []Incident
for _, incident := range incidents {
if !noUpdateStates[incident.GetState()] {
updatableIncidents = append(updatableIncidents, incident)
}
}
return updatableIncidents
}
func getGroupKey(data template.Data) string {
hash := md5.Sum([]byte(fmt.Sprintf("%v", data.GroupLabels.SortedPairs())))
return fmt.Sprintf("%x", hash)
}
func applyIncidentTemplate(incident Incident, data template.Data) {
for key, val := range incident {
var err error
incident[key], err = applyTemplate(key, val.(string), data)
if err != nil {
webhookIncidentTemplateError.Inc()
log.Errorf("Error parsing default incident template for key:%s value:%s, error:%v", key, val.(string), err)
}
}
}
func applyTemplate(name string, text string, data template.Data) (string, error) {
tmpl, err := tmpltext.New(name).Parse(text)
if err != nil {
return "", err
}
var result bytes.Buffer
err = tmpl.Execute(&result, data)
if err != nil {
return "", err
}
return result.String(), nil
}
func validateIncident(incident Incident) error {
var str strings.Builder
if impact, ok := incident["impact"]; ok && impact != nil && len(impact.(string)) > 0 {
if _, err := strconv.Atoi(impact.(string)); err != nil {
str.WriteString("'impact' field value is ")
str.WriteString(impact.(string))
str.WriteString(" but should be an integer, please fix your configuration. Incident creation/update will proceed but this field will be missing. ")
}
}
if urgency, ok := incident["urgency"]; ok && urgency != nil && len(urgency.(string)) > 0 {
if _, err := strconv.Atoi(urgency.(string)); err != nil {
str.WriteString("'urgency' field value is ")
str.WriteString(urgency.(string))
str.WriteString(" but should be an integer, please fix your configuration. Incident creation/update will proceed but this field will be missing.")
}
}
if str.Len() > 0 {
return errors.New(str.String())
}
return nil
}