-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathmain.go
476 lines (424 loc) · 11.2 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
474
475
476
package main
import (
"bufio"
"bytes"
"crypto/tls"
"errors"
"fmt"
"github.com/Masterminds/sprig"
"github.com/google/uuid"
corev2 "github.com/sensu/sensu-go/api/core/v2"
"github.com/sensu/sensu-plugin-sdk/sensu"
htemplate "html/template"
"io"
"math"
"net"
"net/mail"
"net/smtp"
"os"
"strconv"
"strings"
ttemplate "text/template"
"time"
)
// HandlerConfig config options for email handler.
type HandlerConfig struct {
sensu.PluginConfig
SmtpHost string
SmtpUsername string
SmtpPassword string
SmtpPort uint64
ToEmail []string
FromEmail string
FromHeader string
AuthMethod string
TLSSkipVerify bool
Hookout bool
BodyTemplateFile string
SubjectTemplate string
// deprecated options
Insecure bool
LoginAuth bool
}
type loginAuth struct {
username, password string
}
type rcpts []string
// used to handle getting text/template or html/template
type templater interface {
Execute(wr io.Writer, data interface{}) error
}
const (
smtpHost = "smtpHost"
smtpUsername = "smtpUsername"
smtpPassword = "smtpPassword"
smtpPort = "smtpPort"
toEmail = "toEmail"
fromEmail = "fromEmail"
authMethod = "authMethod"
tlsSkipVerify = "tlsSkipVerify"
hookout = "hookout"
bodyTemplateFile = "bodyTemplateFile"
subjectTemplate = "subjectTemplate"
defaultSmtpPort = 587
// deprecated options
insecure = "insecure"
enableLoginAuth = "enableLoginAuth"
)
const (
AuthMethodNone = "none"
AuthMethodPlain = "plain"
AuthMethodLogin = "login"
)
// Email body content
const (
ContentHTML = "text/html"
ContentPlain = "text/plain"
)
var (
config = HandlerConfig{
PluginConfig: sensu.PluginConfig{
Name: "sensu-email-handler",
Short: "The Sensu Go Email handler for sending an email notification",
Keyspace: "sensu.io/plugins/email/config",
},
}
emailBodyTemplate = "{{.Check.Output}}"
emailConfigOptions = []*sensu.PluginConfigOption{
{
Path: smtpHost,
Argument: smtpHost,
Shorthand: "s",
Default: "",
Usage: "The SMTP host to use to send to send email",
Value: &config.SmtpHost,
},
{
Path: smtpUsername,
Env: "SMTP_USERNAME",
Argument: smtpUsername,
Shorthand: "u",
Default: "",
Usage: "The SMTP username, if not in env SMTP_USERNAME",
Value: &config.SmtpUsername,
},
{
Path: smtpPassword,
Env: "SMTP_PASSWORD",
Argument: smtpPassword,
Shorthand: "p",
Default: "",
Secret: true,
Usage: "The SMTP password, if not in env SMTP_PASSWORD",
Value: &config.SmtpPassword,
},
{
Path: smtpPort,
Argument: smtpPort,
Shorthand: "P",
Default: uint64(defaultSmtpPort),
Usage: "The SMTP server port",
Value: &config.SmtpPort,
},
{
Path: toEmail,
Argument: toEmail,
Shorthand: "t",
Default: []string{},
Usage: "The 'to' email address (accepts comma delimited and/or multiple flags)",
Value: &config.ToEmail,
},
{
Path: fromEmail,
Argument: fromEmail,
Shorthand: "f",
Default: "",
Usage: "The 'from' email address",
Value: &config.FromEmail,
},
{
Path: tlsSkipVerify,
Argument: tlsSkipVerify,
Shorthand: "k",
Default: false,
Usage: "Do not verify TLS certificates",
Value: &config.TLSSkipVerify,
},
{
Path: authMethod,
Argument: authMethod,
Shorthand: "a",
Default: AuthMethodPlain,
Usage: "The SMTP authentication method, one of 'none', 'plain', or 'login'",
Value: &config.AuthMethod,
},
{
Path: hookout,
Argument: hookout,
Shorthand: "H",
Default: false,
Usage: "Include output from check hook(s)",
Value: &config.Hookout,
},
{
Path: bodyTemplateFile,
Argument: bodyTemplateFile,
Shorthand: "T",
Default: "",
Usage: "A template file to use for the body",
Value: &config.BodyTemplateFile,
},
{
Path: subjectTemplate,
Argument: subjectTemplate,
Shorthand: "S",
Default: "Sensu Alert - {{.Entity.Name}}/{{.Check.Name}}: {{.Check.State}}",
Usage: "A template to use for the subject",
Value: &config.SubjectTemplate,
},
// deprecated options
{
Path: insecure,
Argument: insecure,
Shorthand: "i",
Default: false,
Usage: "[deprecated] Use an insecure connection (unauthenticated on port 25)",
Value: &config.Insecure,
},
{
Path: enableLoginAuth,
Argument: enableLoginAuth,
Shorthand: "l",
Default: false,
Usage: "[deprecated] Use \"login auth\" mechanisim",
Value: &config.LoginAuth,
},
}
)
func main() {
goHandler := sensu.NewGoHandler(&config.PluginConfig, emailConfigOptions, checkArgs, sendEmail)
goHandler.Execute()
}
func checkArgs(_ *corev2.Event) error {
if len(config.SmtpHost) == 0 {
return errors.New("missing smtp host")
}
if config.SmtpPort > math.MaxUint16 {
return errors.New("smtp port is out of range")
}
if len(config.ToEmail) == 0 {
return errors.New("missing destination email address")
}
if len(config.FromEmail) == 0 {
return errors.New("from email is empty")
}
// translate deprecated options to replacements
if config.LoginAuth {
config.AuthMethod = AuthMethodLogin
}
if config.Insecure {
config.SmtpPort = 25
config.AuthMethod = AuthMethodNone
config.TLSSkipVerify = true
}
switch config.AuthMethod {
case AuthMethodPlain, AuthMethodNone, AuthMethodLogin:
case "":
config.AuthMethod = AuthMethodPlain
default:
return fmt.Errorf("%s is not a valid auth method", config.AuthMethod)
}
if config.AuthMethod != AuthMethodNone {
if len(config.SmtpUsername) == 0 {
return errors.New("smtp username is empty")
}
if len(config.SmtpPassword) == 0 {
return errors.New("smtp password is empty")
}
}
if config.Hookout && len(config.BodyTemplateFile) > 0 {
return errors.New("--hookout (-H) and --bodyTemplateFile (-T) are mutually exclusive")
}
if config.Hookout {
emailBodyTemplate = "{{.Check.Output}}\n{{range .Check.Hooks}}Hook Name: {{.Name}}\nHook Command: {{.Command}}\n\n{{.Output}}\n\n{{end}}"
} else if len(config.BodyTemplateFile) > 0 {
templateBytes, fileErr := os.ReadFile(config.BodyTemplateFile)
if fileErr != nil {
return fmt.Errorf("failed to read specified template file %s", config.BodyTemplateFile)
}
emailBodyTemplate = string(templateBytes)
}
fromAddr, addrErr := mail.ParseAddress(config.FromEmail)
if addrErr != nil {
return addrErr
}
config.FromEmail = fromAddr.Address
config.FromHeader = fromAddr.String()
return nil
}
func sendEmail(event *corev2.Event) error {
var contentType string
smtpAddress := net.JoinHostPort(config.SmtpHost, strconv.FormatUint(config.SmtpPort, 10))
subject, subjectErr := resolveTemplate(config.SubjectTemplate, event, ContentPlain)
if subjectErr != nil {
return subjectErr
}
if strings.Contains(emailBodyTemplate, "<html") {
contentType = ContentHTML
} else {
contentType = ContentPlain
}
body, bodyErr := resolveTemplate(emailBodyTemplate, event, contentType)
if bodyErr != nil {
return bodyErr
}
recipients := newRcpts(config.ToEmail)
t := time.Now()
msg := []byte("From: " + config.FromHeader + "\r\n" +
"To: " + recipients.String() + "\r\n" +
"Subject: " + subject + "\r\n" +
"Date: " + t.Format(time.RFC1123Z) + "\r\n" +
"Content-Type: " + contentType + "\r\n" +
"\r\n" +
body + "\r\n")
var auth smtp.Auth
switch config.AuthMethod {
case AuthMethodPlain:
auth = smtp.PlainAuth("", config.SmtpUsername, config.SmtpPassword, config.SmtpHost)
case AuthMethodLogin:
auth = LoginAuth(config.SmtpUsername, config.SmtpPassword)
}
conn, err := smtp.Dial(smtpAddress)
if err != nil {
return err
}
defer conn.Close()
if ok, _ := conn.Extension("STARTTLS"); ok {
tlsConfig := &tls.Config{
ServerName: config.SmtpHost,
InsecureSkipVerify: config.TLSSkipVerify,
}
if err := conn.StartTLS(tlsConfig); err != nil {
return err
}
}
if ok, _ := conn.Extension("AUTH"); ok && auth != nil {
if err := conn.Auth(auth); err != nil {
return err
}
}
if err := conn.Mail(config.FromEmail); err != nil {
return err
}
if err := recipients.rcpt(conn); err != nil {
return err
}
data, err := conn.Data()
if err != nil {
return err
}
if _, err := data.Write(msg); err != nil {
return err
}
if err := data.Close(); err != nil {
return err
}
// FUTURE: send to AH
fmt.Printf("Email sent to %s\n", recipients.String())
return conn.Quit()
}
func StringLines(s string) ([]string, error) {
var lines []string
scanner := bufio.NewScanner(strings.NewReader(s))
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
err := scanner.Err()
return lines, err
}
func resolveTemplate(templateValue string, event *corev2.Event, contentType string) (string, error) {
var (
resolved bytes.Buffer
tmpl templater
err error
)
if contentType == ContentHTML {
// parse using html/template
tmpl, err = htemplate.New("test").Funcs(htemplate.FuncMap{
// function lets change text line breaks with html line breakss
// to ensure event Check.Output is ready
"StringLines": StringLines,
"UnixTime": func(i int64) time.Time { return time.Unix(i, 0) },
"UUIDFromBytes": uuid.FromBytes,
}).Funcs(sprig.HtmlFuncMap()).Parse(templateValue)
} else {
// default parse using text/template
tmpl, err = ttemplate.New("test").Funcs(ttemplate.FuncMap{
"StringLines": StringLines,
"UnixTime": func(i int64) time.Time { return time.Unix(i, 0) },
"UUIDFromBytes": uuid.FromBytes,
}).Funcs(sprig.TxtFuncMap()).Parse(templateValue)
}
if err != nil {
return "", err
}
err = tmpl.Execute(&resolved, *event)
if err != nil {
return "", err
}
return resolved.String(), nil
}
// newRcpts trims "spaces" and checks each toEmails for commas.
// Any additional rcpts via commas appends to the end.
func newRcpts(toEmails []string) rcpts {
tos := make([]string, len(toEmails))
var ntos []string
for i, t := range toEmails {
ts := strings.Split(t, ",")
tos[i] = strings.TrimSpace(ts[0])
if len(ts) == 1 {
continue
}
// first 1 already in slice
for _, tt := range ts[1:] {
ntos = append(ntos, strings.TrimSpace(tt))
}
}
if len(ntos) > 0 {
return rcpts(append(tos, ntos...))
}
return rcpts(tos)
}
func (r rcpts) rcpt(c *smtp.Client) error {
for _, to := range r {
if err := c.Rcpt(to); err != nil {
return err
}
}
return nil
}
func (r rcpts) String() string {
return strings.Join(r, ",")
}
// https://gist.github.com/homme/22b457eb054a07e7b2fb
// https://gist.github.com/andelf/5118732
// MIT license (c) andelf 2013
func LoginAuth(username, password string) smtp.Auth {
return &loginAuth{username, password}
}
func (a *loginAuth) Start(_ *smtp.ServerInfo) (string, []byte, error) {
return "LOGIN", []byte(a.username), nil
}
func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
if more {
switch string(fromServer) {
case "Username:":
return []byte(a.username), nil
case "Password:":
return []byte(a.password), nil
default:
return nil, fmt.Errorf("Unknown response (%s) from server when attempting to use loginAuth", string(fromServer))
}
}
return nil, nil
}