forked from sensu/sensu-slack-handler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
275 lines (239 loc) · 6.39 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"path"
"strings"
"github.com/bluele/slack"
"github.com/sensu/sensu-go/types"
"github.com/spf13/cobra"
)
type HandlerConfigOption struct {
Value string
Path string
Env string
}
type HandlerConfig struct {
SlackWebhookUrl HandlerConfigOption
SlackChannel HandlerConfigOption
SlackUsername HandlerConfigOption
SlackIconUrl HandlerConfigOption
Timeout int
Keyspace string
}
var (
stdin *os.File
config = HandlerConfig{
// default values
SlackWebhookUrl: HandlerConfigOption{Path: "webhook-url", Env: "SENSU_SLACK_WEHBOOK_URL"},
SlackChannel: HandlerConfigOption{Path: "channel", Env: "SENSU_SLACK_CHANNEL"},
SlackUsername: HandlerConfigOption{Path: "username", Env: "SENSU_SLACK_USERNAME"},
SlackIconUrl: HandlerConfigOption{Path: "icon-url", Env: "SENSU_SLACK_ICON_URL"},
Timeout: 10,
Keyspace: "sensu.io/plugins/slack/config",
}
options = []*HandlerConfigOption{
// iterable slice of user-overridable configuration options
&config.SlackWebhookUrl,
&config.SlackChannel,
&config.SlackUsername,
&config.SlackIconUrl,
}
)
func main() {
rootCmd := configureRootCommand()
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
func configureRootCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "sensu-slack-handler",
Short: "The Sensu Go Slack handler for notifying a channel",
RunE: run,
}
/*
Sensitive flags
default to using envvar value
do not mark as required
manually test for empty value
*/
cmd.Flags().StringVarP(&config.SlackWebhookUrl.Value,
"webhook-url",
"w",
os.Getenv("SLACK_WEBHOOK_URL"),
"The webhook url to send messages to, defaults to value of SLACK_WEBHOOK_URL env variable")
cmd.Flags().StringVarP(&config.SlackChannel.Value,
"channel",
"c",
"#general",
"The channel to post messages to")
cmd.Flags().StringVarP(&config.SlackUsername.Value,
"username",
"u",
"sensu",
"The username that messages will be sent as")
cmd.Flags().StringVarP(&config.SlackIconUrl.Value,
"icon-url",
"i",
"http://s3-us-west-2.amazonaws.com/sensuapp.org/sensu.png",
"A URL to an image to use as the user avatar")
cmd.Flags().IntVarP(&config.Timeout,
"timeout",
"t",
10,
"The amount of seconds to wait before terminating the handler")
return cmd
}
func run(cmd *cobra.Command, args []string) error {
if len(args) != 0 {
_ = cmd.Help()
return errors.New("invalid argument(s) received")
}
// load & parse stdin
if stdin == nil {
stdin = os.Stdin
}
eventJSON, err := ioutil.ReadAll(stdin)
if err != nil {
return fmt.Errorf("failed to read stdin: %s", err.Error())
}
event := &types.Event{}
err = json.Unmarshal(eventJSON, event)
if err != nil {
return fmt.Errorf("failed to unmarshal stdin data: %s", eventJSON)
}
// configuration validation & overrides
if config.SlackWebhookUrl.Value == "" {
_ = cmd.Help()
return fmt.Errorf("webhook url is empty")
}
configurationOverrides(&config, options, event)
if err = validateEvent(event); err != nil {
return errors.New(err.Error())
}
if err = sendMessage(event); err != nil {
return errors.New(err.Error())
}
return nil
}
func configurationOverrides(config *HandlerConfig, options []*HandlerConfigOption, event *types.Event) {
if config.Keyspace == "" {
return
}
for _, opt := range options {
if opt.Path != "" {
// compile the Annotation keyspace to look for configuration overrides
k := path.Join(config.Keyspace, opt.Path)
switch {
case event.Check.Annotations[k] != "":
opt.Value = event.Check.Annotations[k]
log.Printf("Overriding default handler configuration with value of \"Check.Annotations.%s\" (\"%s\")\n", k, event.Check.Annotations[k])
case event.Entity.Annotations[k] != "":
opt.Value = event.Entity.Annotations[k]
log.Printf("Overriding default handler configuration with value of \"Entity.Annotations.%s\" (\"%s\")\n", k, event.Entity.Annotations[k])
}
}
}
}
func formattedEventAction(event *types.Event) string {
switch event.Check.Status {
case 0:
return "RESOLVED"
default:
return "ALERT"
}
}
func chomp(s string) string {
return strings.Trim(strings.Trim(strings.Trim(s, "\n"), "\r"), "\r\n")
}
func eventKey(event *types.Event) string {
return fmt.Sprintf("%s/%s", event.Entity.Name, event.Check.Name)
}
func eventSummary(event *types.Event, maxLength int) string {
output := chomp(event.Check.Output)
if len(event.Check.Output) > maxLength {
output = output[0:maxLength] + "..."
}
return fmt.Sprintf("%s:%s", eventKey(event), output)
}
func formattedMessage(event *types.Event) string {
return fmt.Sprintf("%s - %s", formattedEventAction(event), eventSummary(event, 100))
}
func messageColor(event *types.Event) string {
switch event.Check.Status {
case 0:
return "good"
case 2:
return "danger"
default:
return "warning"
}
}
func messageStatus(event *types.Event) string {
switch event.Check.Status {
case 0:
return "Resolved"
case 2:
return "Critical"
default:
return "Warning"
}
}
func messageAttachment(event *types.Event) *slack.Attachment {
attachment := &slack.Attachment{
Title: "Description",
Text: event.Check.Output,
Fallback: formattedMessage(event),
Color: messageColor(event),
Fields: []*slack.AttachmentField{
&slack.AttachmentField{
Title: "Status",
Value: messageStatus(event),
Short: false,
},
&slack.AttachmentField{
Title: "Entity",
Value: event.Entity.Name,
Short: true,
},
&slack.AttachmentField{
Title: "Check",
Value: event.Check.Name,
Short: true,
},
},
}
return attachment
}
func sendMessage(event *types.Event) error {
hook := slack.NewWebHook(config.SlackWebhookUrl.Value)
return hook.PostMessage(&slack.WebHookPostPayload{
Attachments: []*slack.Attachment{messageAttachment(event)},
Channel: config.SlackChannel.Value,
IconUrl: config.SlackIconUrl.Value,
Username: config.SlackUsername.Value,
})
}
func validateEvent(event *types.Event) error {
if event.Timestamp <= 0 {
return errors.New("timestamp is missing or must be greater than zero")
}
if event.Entity == nil {
return errors.New("entity is missing from event")
}
if !event.HasCheck() {
return errors.New("check is missing from event")
}
if err := event.Entity.Validate(); err != nil {
return err
}
if err := event.Check.Validate(); err != nil {
return err
}
return nil
}