forked from AcalephStorage/consul-alerts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event-handler.go
97 lines (82 loc) · 2.06 KB
/
event-handler.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
package main
import (
"bytes"
"encoding/json"
"net/http"
"os/exec"
"github.com/AcalephStorage/consul-alerts/consul"
log "github.com/AcalephStorage/consul-alerts/Godeps/_workspace/src/github.com/Sirupsen/logrus"
)
type EventProcessor struct {
inChan chan []consul.Event
closeChan chan struct{}
firstRun bool
}
func (ep *EventProcessor) start() {
cleanup := false
for !cleanup {
select {
case events := <-ep.inChan:
ep.handleEvents(events)
case <-ep.closeChan:
cleanup = true
}
}
}
func (ep *EventProcessor) stop() {
close(ep.closeChan)
}
func (ep *EventProcessor) handleEvents(events []consul.Event) {
for _, event := range events {
log.Println("----------------------------------------")
log.Printf("Processing event %s:\n", event.ID)
log.Println("----------------------------------------")
eventHandlers := consulClient.EventHandlers(event.Name)
for _, eventHandler := range eventHandlers {
data, err := json.Marshal(&event)
if err != nil {
log.Println("Unable to read event: ", event)
// then what?
}
input := bytes.NewReader(data)
output := new(bytes.Buffer)
cmd := exec.Command(eventHandler)
cmd.Stdin = input
cmd.Stdout = output
cmd.Stderr = output
if err := cmd.Run(); err != nil {
log.Println("error running handler: ", err)
} else {
log.Printf(">>> \n%s -> %s:\n %s\n", event.ID, eventHandler, output)
}
}
log.Printf("Event Processed.\n\n")
}
}
func (ep *EventProcessor) eventHandler(w http.ResponseWriter, r *http.Request) {
consulClient.LoadConfig()
if ep.firstRun {
log.Println("Now watching for events.")
ep.firstRun = false
// set status to OK
return
}
if !consulClient.EventsEnabled() {
log.Println("Event handling disabled. Event ignored.")
// set to OK?
return
}
var events []consul.Event
toWatchObject(r.Body, &events)
ep.inChan <- events
// set status to OK
}
func startEventProcessor() *EventProcessor {
ep := &EventProcessor{
inChan: make(chan []consul.Event, 1),
closeChan: make(chan struct{}),
firstRun: true,
}
go ep.start()
return ep
}