forked from betorvs/sensu-opsgenie-handler
-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
472 lines (432 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
package main
import (
"context"
"encoding/json"
"fmt"
"strings"
"time"
"github.com/opsgenie/opsgenie-go-sdk-v2/alert"
"github.com/opsgenie/opsgenie-go-sdk-v2/client"
"github.com/sensu-community/sensu-plugin-sdk/sensu"
"github.com/sensu-community/sensu-plugin-sdk/templates"
"github.com/sensu/sensu-go/types"
)
const (
notFound = "NOT FOUND"
source = "Sensu Go"
)
// Config represents the handler plugin config.
type Config struct {
sensu.PluginConfig
IncludeEventInNote bool
FullDetails bool
WithAnnotations bool
WithLabels bool
MessageLimit int
DescriptionLimit int
APIRegion string
AuthToken string
Team string
Priority string
SensuDashboard string
MessageTemplate string
DescriptionTemplate string
Actions []string
TagsTemplates []string
}
var (
plugin = Config{
PluginConfig: sensu.PluginConfig{
Name: "sensu-opsgenie-handler",
Short: "The Sensu Go OpsGenie handler for incident management",
Keyspace: "sensu.io/plugins/sensu-opsgenie-handler/config",
},
}
options = []*sensu.PluginConfigOption{
{
Path: "region",
Env: "OPSGENIE_REGION",
Argument: "region",
Shorthand: "r",
Default: "us",
Usage: "The OpsGenie API Region (us or eu), use default from OPSGENIE_REGION env var",
Value: &plugin.APIRegion,
},
{
Path: "auth",
Env: "OPSGENIE_AUTHTOKEN",
Argument: "auth",
Shorthand: "a",
Default: "",
Secret: true,
Usage: "The OpsGenie V2 API authentication token, use default from OPSGENIE_AUTHTOKEN env var",
Value: &plugin.AuthToken,
},
{
Path: "team",
Env: "OPSGENIE_TEAM",
Argument: "team",
Shorthand: "t",
Default: "",
Usage: "The OpsGenie V2 API Team, use default from OPSGENIE_TEAM env var",
Value: &plugin.Team,
},
{
Path: "sensuDashboard",
Env: "OPSGENIE_SENSU_DASHBOARD",
Argument: "sensuDashboard",
Shorthand: "s",
Default: "",
Usage: "The OpsGenie Handler will use it to create a source Sensu Dashboard URL. Use OPSGENIE_SENSU_DASHBOARD. Example: http://sensu-dashboard.example.local/c/~/n",
Value: &plugin.SensuDashboard,
},
{
Path: "messageTemplate",
Env: "OPSGENIE_MESSAGE_TEMPLATE",
Argument: "messageTemplate",
Shorthand: "m",
Default: "{{.Entity.Name}}/{{.Check.Name}}",
Usage: "The template for the message to be sent",
Value: &plugin.MessageTemplate,
},
{
Path: "messageLimit",
Env: "OPSGENIE_MESSAGE_LIMIT",
Argument: "messageLimit",
Shorthand: "l",
Default: 130,
Usage: "The maximum length of the message field",
Value: &plugin.MessageLimit,
},
{
Path: "descriptionTemplate",
Env: "OPSGENIE_DESCRIPTION_TEMPLATE",
Argument: "descriptionTemplate",
Shorthand: "d",
Default: "{{.Check.Output}}",
Usage: "The template for the description to be sent",
Value: &plugin.DescriptionTemplate,
},
{
Path: "descriptionLimit",
Env: "OPSGENIE_DESCRIPTION_LIMIT",
Argument: "descriptionLimit",
Shorthand: "L",
Default: 15000,
Usage: "The maximum length of the description field",
Value: &plugin.DescriptionLimit,
},
{
Path: "includeEventInNote",
Env: "",
Argument: "includeEventInNote",
Shorthand: "i",
Default: false,
Usage: "Include the event JSON in the payload sent to OpsGenie",
Value: &plugin.IncludeEventInNote,
},
{
Path: "priority",
Env: "OPSGENIE_PRIORITY",
Argument: "priority",
Shorthand: "p",
Default: "P3",
Usage: "The OpsGenie Alert Priority, use default from OPSGENIE_PRIORITY env var",
Value: &plugin.Priority,
},
{
Path: "actions",
Env: "",
Argument: "actions",
Shorthand: "A",
Default: []string{},
Usage: "The OpsGenie custom actions to assign to the event",
Value: &plugin.Actions,
},
{
Path: "withAnnotations",
Env: "",
Argument: "withAnnotations",
Shorthand: "w",
Default: false,
Usage: "Include the event.metadata.Annotations in details to send to OpsGenie",
Value: &plugin.WithAnnotations,
},
{
Path: "withLabels",
Env: "",
Argument: "withLabels",
Shorthand: "W",
Default: false,
Usage: "Include the event.metadata.Labels in details to send to OpsGenie",
Value: &plugin.WithLabels,
},
{
Path: "fullDetails",
Env: "",
Argument: "fullDetails",
Shorthand: "F",
Default: false,
Usage: "Include the more details to send to OpsGenie like proxy_entity_name, occurrences and agent details arch and os",
Value: &plugin.FullDetails,
},
{
Path: "tagTemplate",
Env: "",
Argument: "tagTemplate",
Shorthand: "T",
Default: []string{"{{.Entity.Name}}", "{{.Check.Name}}", "{{.Entity.Namespace}}", "{{.Entity.EntityClass}}"},
Usage: "The template to assign for the incident in OpsGenie",
Value: &plugin.TagsTemplates,
},
}
)
func main() {
handler := sensu.NewGoHandler(&plugin.PluginConfig, options, checkArgs, executeHandler)
handler.Execute()
}
func checkArgs(_ *types.Event) error {
if len(plugin.AuthToken) == 0 {
return fmt.Errorf("authentication token is empty")
}
if len(plugin.Team) == 0 {
return fmt.Errorf("team is empty")
}
return nil
}
// parseEventKeyTags func returns string, string, and []string with event data
// fist string contains custom template string to use in message
// second string contains Entity.Name/Check.Name to use in alias
// []string contains Entity.Name Check.Name Entity.Namespace, event.Entity.EntityClass to use as tags in Opsgenie
func parseEventKeyTags(event *types.Event) (title string, alias string, tags []string) {
alias = fmt.Sprintf("%s/%s", event.Entity.Name, event.Check.Name)
title, err := templates.EvalTemplate("title", plugin.MessageTemplate, event)
if err != nil {
return "", "", []string{}
}
for _, v := range plugin.TagsTemplates {
tag, err := templates.EvalTemplate("tags", v, event)
if err != nil {
return "", "", []string{}
}
tags = append(tags, tag)
}
return trim(title, plugin.MessageLimit), alias, tags
}
// parseDescription func returns string with custom template string to use in description
func parseDescription(event *types.Event) (description string) {
description, err := templates.EvalTemplate("description", plugin.DescriptionTemplate, event)
if err != nil {
return ""
}
// allow newlines to get expanded
description = strings.Replace(description, `\n`, "\n", -1)
return trim(description, plugin.DescriptionLimit)
}
// parseDetails func returns a map of string string with check information for the details field
func parseDetails(event *types.Event) map[string]string {
details := make(map[string]string)
details["output"] = event.Check.Output
details["command"] = event.Check.Command
details["proxy_entity_name"] = event.Check.ProxyEntityName
details["state"] = event.Check.State
details["status"] = fmt.Sprintf("%d", event.Check.Status)
details["occurrences"] = fmt.Sprintf("%d", event.Check.Occurrences)
details["occurrences_watermark"] = fmt.Sprintf("%d", event.Check.OccurrencesWatermark)
if plugin.FullDetails {
details["ttl"] = fmt.Sprintf("%d", event.Check.Ttl)
details["interval"] = fmt.Sprintf("%d", event.Check.Interval)
details["subscriptions"] = fmt.Sprintf("%v", event.Check.Subscriptions)
details["handlers"] = fmt.Sprintf("%v", event.Check.Handlers)
if event.Entity.EntityClass == "agent" {
details["arch"] = event.Entity.System.GetArch()
details["os"] = event.Entity.System.GetOS()
details["platform"] = event.Entity.System.GetPlatform()
details["platform_family"] = event.Entity.System.GetPlatformFamily()
details["platform_version"] = event.Entity.System.GetPlatformVersion()
}
}
if plugin.WithAnnotations {
if event.Check.Annotations != nil {
for key, value := range event.Check.Annotations {
if !strings.Contains(key, plugin.PluginConfig.Keyspace) {
checkKey := fmt.Sprintf("%s_annotation_%s", "check", key)
details[checkKey] = value
}
}
}
if event.Entity.Annotations != nil {
for key, value := range event.Entity.Annotations {
if !strings.Contains(key, plugin.PluginConfig.Keyspace) {
entityKey := fmt.Sprintf("%s_annotation_%s", "entity", key)
details[entityKey] = value
}
}
}
}
if plugin.WithLabels {
if event.Check.Labels != nil {
for key, value := range event.Check.Labels {
checkKey := fmt.Sprintf("%s_label_%s", "check", key)
details[checkKey] = value
}
}
if event.Entity.Labels != nil {
for key, value := range event.Entity.Labels {
entityKey := fmt.Sprintf("%s_label_%s", "entity", key)
details[entityKey] = value
}
}
}
if len(plugin.SensuDashboard) > 0 {
details["sensuDashboard"] = fmt.Sprintf("source: %s/%s/events/%s/%s \n", plugin.SensuDashboard, event.Entity.Namespace, event.Entity.Name, event.Check.Name)
}
return details
}
// eventPriority func read priority in the event and return alert.PX
// check.Annotations override Entity.Annotations
func eventPriority() alert.Priority {
switch plugin.Priority {
case "P5":
return alert.P5
case "P4":
return alert.P4
case "P3":
return alert.P3
case "P2":
return alert.P2
case "P1":
return alert.P1
default:
return alert.P3
}
}
// stringInSlice checks if a slice contains a specific string
func stringInSlice(a string, list []string) bool {
for _, b := range list {
if b == a {
return true
}
}
return false
}
// switchOpsgenieRegion func
func switchOpsgenieRegion() client.ApiUrl {
var region client.ApiUrl
apiRegionLowCase := strings.ToLower(plugin.APIRegion)
switch apiRegionLowCase {
case "eu":
region = client.API_URL_EU
case "us":
region = client.API_URL
default:
region = client.API_URL
}
return region
}
func executeHandler(event *types.Event) error {
alertClient, err := alert.NewClient(&client.Config{
ApiKey: plugin.AuthToken,
OpsGenieAPIURL: switchOpsgenieRegion(),
})
if err != nil {
return fmt.Errorf("failed to create opsgenie client: %s", err)
}
if event.Check.Status != 0 {
return createIncident(alertClient, event)
}
// check if event has a alert
hasAlert, _ := getAlert(alertClient, event)
// close incident if status == 0
if hasAlert != notFound && event.Check.Status == 0 {
return closeAlert(alertClient, event, hasAlert)
}
return nil
}
// createIncident func create an alert in OpsGenie
func createIncident(alertClient *alert.Client, event *types.Event) error {
var (
note string
err error
)
if plugin.IncludeEventInNote {
note, err = getNote(event)
if err != nil {
return err
}
}
teams := []alert.Responder{
{Type: alert.EscalationResponder, Name: plugin.Team},
{Type: alert.ScheduleResponder, Name: plugin.Team},
}
title, alias, tags := parseEventKeyTags(event)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
createResult, err := alertClient.Create(ctx, &alert.CreateAlertRequest{
Message: title,
Alias: alias,
Description: parseDescription(event),
Responders: teams,
Actions: plugin.Actions,
Tags: tags,
Details: parseDetails(event),
Entity: event.Entity.Name,
Source: source,
Priority: eventPriority(),
Note: note,
})
if err != nil {
fmt.Println(err.Error())
} else {
// FUTURE: send to AH
fmt.Println("Create request ID: " + createResult.RequestId)
}
return nil
}
// getAlert func get a alert using an alias.
func getAlert(alertClient *alert.Client, event *types.Event) (string, error) {
_, alias, _ := parseEventKeyTags(event)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
getResult, err := alertClient.Get(ctx, &alert.GetAlertRequest{
IdentifierType: alert.ALIAS,
IdentifierValue: alias,
})
if err != nil {
return notFound, nil
}
fmt.Printf("ID: %s, Message: %s, Count: %d \n", getResult.Id, getResult.Message, getResult.Count)
return getResult.Id, nil
}
// closeAlert func close an alert if status == 0
func closeAlert(alertClient *alert.Client, event *types.Event, alertid string) error {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
closeResult, err := alertClient.Close(ctx, &alert.CloseAlertRequest{
IdentifierType: alert.ALERTID,
IdentifierValue: alertid,
Source: source,
Note: "Closed Automatically",
})
if err != nil {
fmt.Printf("[ERROR] Not Closed: %s\n", err)
}
// FUTURE: send to AH
fmt.Printf("RequestID %s to Close %s\n", alertid, closeResult.RequestId)
return nil
}
// getNote func creates a note with whole event in json format
func getNote(event *types.Event) (string, error) {
eventJSON, err := json.Marshal(event)
if err != nil {
return "", err
}
return fmt.Sprintf("Event data update:\n\n%s", eventJSON), nil
}
// time func returns only the first n bytes of a string
func trim(s string, n int) string {
if len(s) > n {
return s[:n]
}
return s
}