This repository has been archived by the owner on Apr 8, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathwebserver.go
249 lines (221 loc) · 5.18 KB
/
webserver.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
package main
import (
"encoding/json"
"errors"
"github.com/gorilla/websocket"
"net"
"net/http"
"sort"
"sync"
)
const (
apiMins = `/api/minutes`
apiHours = `/api/hours`
apiDays = `/api/days`
apiMonths = `/api/months`
apiLive = `/api/live`
apiIface = `/api/interfaces`
home = `/`
chanBufferSize = 8
minId setId = iota
hourId setId = iota
dayId setId = iota
monthId setId = iota
)
var (
errInvalidState = errors.New("Invalid state")
errInvalidType = errors.New("Invalid type")
)
type setId int
type webserver struct {
lst net.Listener
ifaces []ifstore
lf *LiveFeeder
root string
wg *sync.WaitGroup
mtx *sync.Mutex
running bool
err error
}
func NewWebserver(lst net.Listener, root string, lf *LiveFeeder, ifaces []ifstore) (*webserver, error) {
if lst == nil {
return nil, errors.New("invalid listener")
}
return &webserver{
lst: lst,
lf: lf,
ifaces: ifaces,
root: root,
wg: &sync.WaitGroup{},
mtx: &sync.Mutex{},
}, nil
}
func (w *webserver) Close() error {
w.mtx.Lock()
defer w.mtx.Unlock()
if w.lst == nil || w.wg == nil || !w.running {
return errInvalidState
}
if err := w.lst.Close(); err != nil {
return err
}
w.wg.Wait()
return w.err
}
func (w *webserver) Run() error {
w.mtx.Lock()
defer w.mtx.Unlock()
if w.lst == nil || w.wg == nil || w.running {
return errInvalidState
}
w.wg.Add(1)
w.running = true
go w.routine()
return nil
}
func (w *webserver) routine() {
defer w.wg.Done()
mux := http.NewServeMux()
mux.HandleFunc(apiMins, w.minutes)
mux.HandleFunc(apiHours, w.hours)
mux.HandleFunc(apiDays, w.days)
mux.HandleFunc(apiMonths, w.months)
mux.HandleFunc(apiIface, w.interfaces)
mux.HandleFunc(apiLive, w.live)
mux.Handle(home, http.FileServer(http.Dir(w.root)))
w.err = http.Serve(w.lst, mux)
w.running = false
}
type namedBwSample struct {
Name string
Data Sample
}
type liveWSFeeder struct {
ch chan namedBwSample
}
func (wsf *liveWSFeeder) Write(name string, s Sample) error {
bws, ok := s.(*BWSample)
if !ok {
//skip ip
return errInvalidType
}
//we don't want to ever block the DB, so if a write fails, bail
select {
case wsf.ch <- namedBwSample{name, bws}:
default:
return nil
}
return nil
}
func (wsf *liveWSFeeder) Close() error {
close(wsf.ch)
return nil
}
func (w *webserver) interfaces(resp http.ResponseWriter, req *http.Request) {
var ifaces []string
for i := range w.ifaces {
ifaces = append(ifaces, w.ifaces[i].iface.Name())
}
resp.Header().Set("Content-Type", "application/json")
jenc := json.NewEncoder(resp)
if err := jenc.Encode(ifaces); err != nil {
resp.WriteHeader(http.StatusInternalServerError)
}
}
func (w *webserver) live(resp http.ResponseWriter, req *http.Request) {
//get our feeder registered
wsf := &liveWSFeeder{
ch: make(chan namedBwSample, chanBufferSize),
}
id, err := w.lf.RegisterLiveFeeder(wsf)
if err != nil {
resp.WriteHeader(http.StatusInternalServerError)
return
}
defer w.lf.DeregisterLiveFeeder(id)
//upgrade to a websocket
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
conn, err := upgrader.Upgrade(resp, req, nil)
if err != nil {
return
}
defer conn.Close()
//start feeding and relaying
for s := range wsf.ch {
if err := websocket.WriteJSON(conn, s); err != nil {
break
}
}
}
type sample struct {
Name string
Samples []BWSample
}
func (w *webserver) sendSamples(req setId, resp http.ResponseWriter) error {
var smps []sample
for i := range w.ifaces {
var smp sample
var err error
var bws []BWSample
var s []Sample
smp.Name = w.ifaces[i].iface.Name()
switch req {
case minId:
s, err = w.ifaces[i].db.Minutes()
case hourId:
s, err = w.ifaces[i].db.Hours()
case dayId:
s, err = w.ifaces[i].db.Days()
case monthId:
s, err = w.ifaces[i].db.Months()
default:
err = errors.New("Invalid set")
}
if err != nil {
return err
}
for j := range s {
bw, ok := s[j].(*BWSample)
if !ok {
continue
}
bws = append(bws, *bw)
}
sort.Sort(sortSet(bws))
smp.Samples = bws
smps = append(smps, smp)
}
resp.Header().Set("Content-Type", "application/json")
jenc := json.NewEncoder(resp)
if err := jenc.Encode(smps); err != nil {
return err
}
return nil
}
func (w *webserver) minutes(resp http.ResponseWriter, req *http.Request) {
if err := w.sendSamples(minId, resp); err != nil {
resp.WriteHeader(http.StatusInternalServerError)
}
}
func (w *webserver) hours(resp http.ResponseWriter, req *http.Request) {
if err := w.sendSamples(hourId, resp); err != nil {
resp.WriteHeader(http.StatusInternalServerError)
}
}
func (w *webserver) days(resp http.ResponseWriter, req *http.Request) {
if err := w.sendSamples(dayId, resp); err != nil {
resp.WriteHeader(http.StatusInternalServerError)
}
}
func (w *webserver) months(resp http.ResponseWriter, req *http.Request) {
if err := w.sendSamples(monthId, resp); err != nil {
resp.WriteHeader(http.StatusInternalServerError)
}
}
type sortSet []BWSample
func (ss sortSet) Len() int { return len(ss) }
func (ss sortSet) Less(i, j int) bool { return ss[i].TS().Before(ss[j].TS()) }
func (ss sortSet) Swap(i, j int) { ss[i], ss[j] = ss[j], ss[i] }