-
Notifications
You must be signed in to change notification settings - Fork 191
/
mattermost-notifier.go
602 lines (485 loc) · 14.8 KB
/
mattermost-notifier.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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package notifier
import (
"bytes"
"encoding/json"
"fmt"
log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
"net/http"
"strconv"
"strings"
)
type StringMap map[string]string
type MattermostLoginInfo struct {
LoginID string `json:"login_id"`
Password string `json:"password"`
}
type MattermostAuthInfo struct {
UserID string `json:"id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt int64 `json:"delete_at"`
UserName string `json:"username"`
AuthData string `json:"auth_data"`
AuthService string `json:"auth_service"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
NickName string `json:"nickname"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Roles string `json:"roles"`
AllowMarketing bool `json:"allow_marketing"`
NotifyProps StringMap `json:"notify_props"`
Props StringMap `json:"props"`
LastPasswordUpdate int64 `json:"last_password_update"`
LastPictureUpdate int64 `json:"last_picture_update"`
}
type MattermostUserInfo struct {
UserID string `json:"id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt int64 `json:"delete_at"`
Username string `json:"username"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Nickname string `json:"nickname"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Password string `json:"password"`
AuthData *string `json:"auth_data"`
AuthService string `json:"auth_service"`
Roles string `json:"roles"`
NotifyProps StringMap `json:"notify_props"`
Props StringMap `json:"props,omitempty"`
LastPasswordUpdate int64 `json:"last_password_update"`
LastPictureUpdate int64 `json:"last_picture_update"`
FailedAttempts int `json:"failed_attempts"`
MfaActive bool `json:"mfa_active"`
MfaSecret string `json:"mfa_secret"`
}
type MattermostTeamInfo struct {
TeamID string `json:"id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt int64 `json:"delete_at"`
DisplayName string `json:"display_name"`
Name string `json:"name"`
Email string `json:"email"`
Type string `json:"type"`
AllowedDomains string `json:"allowed_domains"`
InviteID string `json:"invite_id"`
AllowOpenInvite bool `json:"allow_open_invite"`
}
type MattermostChannelInfo struct {
ChannelID string `json:"id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt int64 `json:"delete_at"`
TeamID string `json:"team_id"`
Type string `json:"type"`
DisplayName string `json:"display_name"`
Name string `json:"name"`
Header string `json:"header"`
Purpose string `json:"purpose"`
LastPostAt int64 `json:"last_post_at"`
TotalMsgCount int64 `json:"total_msg_count"`
ExtraUpdateAt int64 `json:"extra_update_at"`
CreatorID string `json:"creator_id"`
}
type MattermostChannelList struct {
Channels []MattermostChannelInfo
}
type MattermostPostInfo struct {
PostID string `json:"id"`
CreateAt int64 `json:"create_at"`
UpdateAt int64 `json:"update_at"`
DeleteAt int64 `json:"delete_at"`
UserID string `json:"user_id"`
ChannelID string `json:"channel_id"`
RootID string `json:"root_id"`
ParentID string `json:"parent_id"`
OriginalID string `json:"original_id"`
Message string `json:"message"`
Type string `json:"type"`
Props StringMap `json:"props"`
Hashtags string `json:"hashtags"`
Filenames StringMap `json:"filenames"`
PendingPostID string `json:"pending_post_id"`
}
type MattermostNotifier struct {
ClusterName string
Url string
UserName string
Password string
Team string
Channel string
Detailed bool
NotifName string
Enabled bool
/* Filled in after authentication */
Initialized bool
Token string
TeamID string
UserID string
ChannelID string
Text string
}
func (mattermost *MattermostNotifier) GetURL() string {
proto := "http"
u := strings.TrimSpace(strings.ToLower(mattermost.Url))
if u[:5] == "https" && u[5] == ':' {
proto = "https"
}
host := ""
port := 0
buf := strings.Split(u, ":")
if (u[:4] == "http" && u[4] == ':') ||
(u[:5] == "https" && u[5] == ':') {
host = strings.Trim(buf[1], "/")
if len(buf) == 3 {
port, _ = strconv.Atoi(strings.TrimSpace(buf[2]))
}
} else if len(buf) == 2 {
host = strings.Trim(buf[0], "/")
port, _ = strconv.Atoi(strings.TrimSpace(buf[1]))
} else {
host = strings.TrimSpace(buf[0])
}
portstr := ""
if port > 0 {
portstr = fmt.Sprintf(":%d", port)
}
return fmt.Sprintf("%s://%s%s/api/v3", proto, host, portstr)
}
func (mattermost *MattermostNotifier) Authenticate() bool {
loginURL := fmt.Sprintf("%s/users/login", mattermost.GetURL())
loginInfo := MattermostLoginInfo{LoginID: mattermost.UserName,
Password: mattermost.Password}
buf := new(bytes.Buffer)
json.NewEncoder(buf).Encode(loginInfo)
req, err := http.NewRequest("POST", loginURL, buf)
if err != nil {
log.Error("NewRequest: ", err)
return false
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return false
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var a MattermostAuthInfo
err = decoder.Decode(&a)
if err != nil {
log.Error("Decode: ", err)
return false
}
if buf, ok := resp.Header["Token"]; ok {
if len(buf) > 0 {
mattermost.Token = buf[0]
return true
}
}
return false
}
func (mattermost *MattermostNotifier) GetAllTeams(teams *[]MattermostTeamInfo) bool {
teamURL := fmt.Sprintf("%s/teams/all", mattermost.GetURL())
req, err := http.NewRequest("GET", teamURL, nil)
if err != nil {
log.Error("NewRequest: ", err)
return false
}
authorization := fmt.Sprintf("Bearer %s", mattermost.Token)
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return false
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var buf map[string]*MattermostTeamInfo
err = decoder.Decode(&buf)
if err != nil {
log.Error("Decode: ", err)
return false
}
if len(buf) > 0 {
for _, value := range buf {
*teams = append(*teams, *value)
}
return true
}
return false
}
func (mattermost *MattermostNotifier) GetUser(userID string, userInfo *MattermostUserInfo) bool {
if userID == "" || userInfo == nil {
return false
}
userURL := fmt.Sprintf("%s/users/%s/get", mattermost.GetURL(), userID)
req, err := http.NewRequest("GET", userURL, nil)
if err != nil {
log.Error("NewRequest: ", err)
return false
}
authorization := fmt.Sprintf("Bearer %s", mattermost.Token)
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return false
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(userInfo)
if err != nil {
log.Error("Decode: ", err)
return false
}
return true
}
func (mattermost *MattermostNotifier) GetMe(me *MattermostUserInfo) bool {
if me == nil {
return false
}
userURL := fmt.Sprintf("%s/users/me", mattermost.GetURL())
req, err := http.NewRequest("GET", userURL, nil)
if err != nil {
log.Error("NewRequest: ", err)
return false
}
authorization := fmt.Sprintf("Bearer %s", mattermost.Token)
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return false
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(me)
if err != nil {
log.Error("Decode: ", err)
return false
}
return true
}
func (mattermost *MattermostNotifier) GetTeam(teamID string, teamInfo *MattermostTeamInfo) bool {
if teamID == "" || teamInfo == nil {
return false
}
teamURL := fmt.Sprintf("%s/teams/%s/me", mattermost.GetURL(), teamID)
req, err := http.NewRequest("GET", teamURL, nil)
if err != nil {
log.Error("NewRequest: ", err)
return false
}
authorization := fmt.Sprintf("Bearer %s", mattermost.Token)
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return false
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(teamInfo)
if err != nil {
log.Error("Decode: ", err)
return false
}
return true
}
func (mattermost *MattermostNotifier) GetChannels(teamID string, channels *[]MattermostChannelInfo) bool {
if teamID == "" || channels == nil {
return false
}
channelURL := fmt.Sprintf("%s/teams/%s/channels/", mattermost.GetURL(), teamID)
req, err := http.NewRequest("GET", channelURL, nil)
if err != nil {
log.Error("NewRequest: ", err)
return false
}
authorization := fmt.Sprintf("Bearer %s", mattermost.Token)
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return false
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
fc := &MattermostChannelList{}
err = decoder.Decode(&fc)
if err != nil {
log.Error("Decode: ", err)
return false
}
*channels = fc.Channels
return true
}
func (mattermost *MattermostNotifier) PostMessage(teamID string, channelID string, postInfo *MattermostPostInfo) bool {
if teamID == "" || channelID == "" || postInfo == nil {
return false
}
postURL := fmt.Sprintf("%s/teams/%s/channels/%s/posts/create",
mattermost.GetURL(), teamID, channelID)
buf := new(bytes.Buffer)
encoder := json.NewEncoder(buf)
err := encoder.Encode(*postInfo)
req, err := http.NewRequest("POST", postURL, buf)
if err != nil {
log.Error("NewRequest: ", err)
return false
}
authorization := fmt.Sprintf("Bearer %s", mattermost.Token)
req.Header.Set("Authorization", authorization)
req.Header.Set("Content-Type", "application/json; charset=utf-8")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Error("Do: ", err)
return false
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
var p MattermostPostInfo
err = decoder.Decode(&p)
if err != nil {
log.Error("Decode: ", err)
return false
}
*postInfo = p
return false
}
func (mattermost *MattermostNotifier) Init() bool {
if mattermost.Initialized == true {
return true
}
if mattermost.Token == "" && !mattermost.Authenticate() {
log.Println("Mattermost: Unable to authenticate!")
return false
}
if mattermost.TeamID == "" {
var teams []MattermostTeamInfo
if !mattermost.GetAllTeams(&teams) {
log.Println("Mattermost: Unable to get teams!")
return false
}
for i := 0; i < len(teams); i++ {
if teams[i].Name == mattermost.Team {
mattermost.TeamID = teams[i].TeamID
break
}
}
if mattermost.TeamID == "" {
log.Println("Mattermost: Unable to find team!")
return false
}
}
if mattermost.UserID == "" {
var me MattermostUserInfo
if !mattermost.GetMe(&me) {
log.Println("Mattermost: Unable to get user!")
return false
}
if me.UserID == "" {
log.Println("Mattermost: Unable to get user ID!")
return false
}
mattermost.UserID = me.UserID
}
if mattermost.ChannelID == "" {
var channels []MattermostChannelInfo
if !mattermost.GetChannels(mattermost.TeamID, &channels) {
log.Println("Mattermost: Unable to get channels!")
return false
}
for i := 0; i < len(channels); i++ {
if channels[i].Name == mattermost.Channel {
mattermost.ChannelID = channels[i].ChannelID
break
}
}
if mattermost.ChannelID == "" {
log.Println("Mattermost: Unable to find channel!")
return false
}
}
mattermost.Initialized = true
return true
}
// NotifierName provides name for notifier selection
func (mattermost *MattermostNotifier) NotifierName() string {
return "mattermost"
}
func (mattermost *MattermostNotifier) Copy() Notifier {
notifier := *mattermost
return ¬ifier
}
//Notify sends messages to the endpoint notifier
func (mattermost *MattermostNotifier) Notify(messages Messages) bool {
if !mattermost.Init() {
return false
}
if mattermost.Detailed {
return mattermost.notifyDetailed(messages)
}
return mattermost.notifySimple(messages)
}
func (mattermost *MattermostNotifier) notifySimple(messages Messages) bool {
overallStatus, pass, warn, fail := messages.Summary()
text := fmt.Sprintf(header, mattermost.ClusterName, overallStatus, fail, warn, pass)
for _, message := range messages {
text += fmt.Sprintf("\n%s:%s:%s is %s.",
message.Node, message.Service, message.Check, message.Status)
text += fmt.Sprintf("\n%s\n\n", message.Output)
}
mattermost.Text = text
return mattermost.postToMattermost()
}
func (mattermost *MattermostNotifier) notifyDetailed(messages Messages) bool {
overallStatus, pass, warn, fail := messages.Summary()
var emoji string
switch overallStatus {
case SYSTEM_HEALTHY:
emoji = ":white_check_mark:"
case SYSTEM_UNSTABLE:
emoji = ":question:"
case SYSTEM_CRITICAL:
emoji = ":x:"
default:
emoji = ":question:"
}
title := "Consul monitoring report"
pretext := fmt.Sprintf("%s %s is *%s*", emoji, mattermost.ClusterName, overallStatus)
detailedBody := ""
detailedBody += fmt.Sprintf("*Changes:* Fail = %d, Warn = %d, Pass = %d",
fail, warn, pass)
detailedBody += fmt.Sprintf("\n")
for _, message := range messages {
detailedBody += fmt.Sprintf("\n*[%s:%s]* %s is *%s.*",
message.Node, message.Service, message.Check, message.Status)
detailedBody += fmt.Sprintf("\n`%s`", strings.TrimSpace(message.Output))
}
mattermost.Text = fmt.Sprintf("%s\n%s\n%s\n\n", title, pretext, detailedBody)
return mattermost.postToMattermost()
}
func (mattermost *MattermostNotifier) postToMattermost() bool {
var postInfo = MattermostPostInfo{
ChannelID: mattermost.ChannelID,
Message: mattermost.Text}
return mattermost.PostMessage(mattermost.TeamID, mattermost.ChannelID, &postInfo)
}