-
Notifications
You must be signed in to change notification settings - Fork 0
/
monitor.go
84 lines (77 loc) · 1.87 KB
/
monitor.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
package ping2ws
import (
"log"
"net/http"
"github.com/gorilla/websocket"
)
// Monitor provides the main entrypoint into the package.
type Monitor struct {
Broker Broker
Observers []Observer
Targets []string
}
// NewMonitor starts a new Broker and kicks off an Observer for each Target provided.
// Target should be a slice of strings of valid IPv4 addresses.
func NewMonitor(targets []string) *Monitor {
broker := NewBroker()
go broker.Start()
// Create observers
observers := make([]Observer, len(targets))
for i, target := range targets {
o, oErr := NewPingObserver(target, broker)
if oErr != nil {
log.Printf("Ignoring bad target: %s", target)
continue
}
go o.Start()
observers[i] = o
}
return &Monitor{
Broker: *broker,
Targets: targets,
Observers: observers,
}
}
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
// PingHandler is a pluggable websocket handler
// that subscribes to the Monitor's Broker
// and forwards published messages over the websocket connection.
func (m *Monitor) PingHandler(w http.ResponseWriter, r *http.Request) {
if !websocket.IsWebSocketUpgrade(r) {
log.Println("No upgrade requested")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Request websocket upgrade"))
return
}
conn, upgradeErr := upgrader.Upgrade(w, r, nil)
if upgradeErr != nil {
log.Print("Could not upgrade connection: ", upgradeErr)
return
}
defer conn.Close()
// Get pings
sub := m.Broker.Subscribe()
defer m.Broker.Unsubscribe(sub)
for {
// On receive, send on conn
select {
case update := <-sub:
// Publish to websocket connection
conn.WriteJSON(update)
default:
}
}
log.Print("Exit")
}
// Stop halts goroutines kicked off by the Monitor.
func (m *Monitor) Stop() {
m.Broker.Stop()
for _, observer := range m.Observers {
if observer != nil {
observer.Stop()
}
}
}