forked from AcalephStorage/consul-alerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend-notifs.go
104 lines (92 loc) · 2.39 KB
/
send-notifs.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
package main
import (
"bytes"
"encoding/json"
"os/exec"
log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
"github.com/AcalephStorage/consul-alerts/notifier"
)
// NotifEngine handles notifications.
//
// To start NotifEngine:
// notifEngine := startNotifEngine()
//
// Tp stop NotifEngine (for cleanup):
// notifEngine.stop()
//
type NotifEngine struct {
inChan chan notifier.Messages
closeChan chan struct{}
}
func (n *NotifEngine) start() {
cleanup := false
for !cleanup {
select {
case messages := <-n.inChan:
n.sendBuiltin(messages)
n.sendCustom(messages)
case <-n.closeChan:
cleanup = true
}
}
}
func (n *NotifEngine) stop() {
close(n.closeChan)
}
func (n *NotifEngine) queueMessages(messages notifier.Messages) {
n.inChan <- messages
log.Println("messages sent for notification")
}
func (n *NotifEngine) sendBuiltin(messages notifier.Messages) {
log.Println("sendBuiltin running")
for _, n := range builtinNotifiers() {
filteredMessages := make(notifier.Messages, 0)
notifName := n.NotifierName()
for _, m := range messages {
if boolVal, exists := m.NotifList[notifName]; (exists && boolVal) || len(m.NotifList) == 0 {
filteredMessages = append(filteredMessages, m)
}
}
if len(filteredMessages) > 0 {
n.Notify(filteredMessages)
}
}
}
func (n *NotifEngine) sendCustom(messages notifier.Messages) {
for notifName, notifCmd := range consulClient.CustomNotifiers() {
filteredMessages := make(notifier.Messages, 0)
for _, m := range messages {
if boolVal, exists := m.NotifList[notifName]; (exists && boolVal) || len(m.NotifList) == 0 {
filteredMessages = append(filteredMessages, m)
}
}
if len(filteredMessages) == 0 {
continue
}
data, err := json.Marshal(&filteredMessages)
if err != nil {
log.Println("Unable to read messages: ", err)
return
}
input := bytes.NewReader(data)
output := new(bytes.Buffer)
cmd := exec.Command(notifCmd)
cmd.Stdin = input
cmd.Stdout = output
cmd.Stderr = output
if err := cmd.Run(); err != nil {
log.Println("error running notifier: ", err)
} else {
log.Println(">>> notification sent to:", notifCmd)
}
log.Println(output)
}
}
func startNotifEngine() *NotifEngine {
notifEngine := &NotifEngine{
inChan: make(chan notifier.Messages),
closeChan: make(chan struct{}),
}
go notifEngine.start()
return notifEngine
}