-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
473 lines (404 loc) · 10.6 KB
/
main.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
package main
import (
"flag"
"fmt"
"net/http"
"os"
"os/exec"
"os/signal"
"strconv"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/net/websocket"
)
var (
port = flag.Int("port", 8080, "listen port")
config = flag.String("config", "", "config file")
configDark = flag.String("config-dark", "", "config file for dark theme")
)
var (
lock = &sync.Mutex{}
mapConn map[string][]LiveEntry = make(map[string][]LiveEntry)
)
type LiveEntry struct {
Conn *websocket.Conn
Ch chan bool
}
func main() {
flag.Usage = func() {
flag.PrintDefaults()
}
flag.Parse()
fmt.Println("port: " + strconv.Itoa(*port))
fmt.Println("config: " + *config)
fmt.Println("config-dark: " + *configDark)
go startServer(*port)
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
s := <-sig
fmt.Printf("Signal (%s) received, stopping\n", s)
}
func startServer(port int) {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/summary.png", summaryHandler)
http.HandleFunc("/vsummary.png", vsummaryHandler)
http.HandleFunc("/hsummary.png", hsummaryHandler)
http.HandleFunc("/top.png", topHandler)
http.HandleFunc("/years.png", yearHandler)
http.HandleFunc("/months.png", monthHandler)
http.HandleFunc("/days.png", dayHandler)
http.HandleFunc("/hours.png", hourHandler)
http.HandleFunc("/hoursgraph.png", hourgraphHandler)
http.HandleFunc("/five.png", fiveHandler)
http.HandleFunc("/fivegraph.png", fivegraphHandler)
http.HandleFunc("/summary", summaryPageHandler)
http.HandleFunc("/top", topPageHandler)
http.HandleFunc("/years", yearPageHandler)
http.HandleFunc("/months", monthPageHandler)
http.HandleFunc("/days", dayPageHandler)
http.HandleFunc("/hours", hourPageHandler)
http.HandleFunc("/five", fivePageHandler)
http.Handle("/live", websocket.Handler(liveHandler))
http.ListenAndServe("[::]:"+strconv.Itoa(port), nil)
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/summary", http.StatusMovedPermanently)
}
func pageHandler(w http.ResponseWriter, r *http.Request, images ...string) {
iface := r.URL.Query().Get("iface")
query := "?"
if len(iface) > 0 {
query += "iface=" + iface
}
ifList := getIfList()
// check iface safe
if !checkIface(iface, ifList) {
fmt.Fprintf(w, "Interface does not exist: "+iface)
return
}
printPageHeader(w)
printNav(w, r, ifList)
fmt.Fprintf(w, "<div class=\"content\">")
fmt.Fprintf(w, "<div id=\"live\"></div>")
for _, image := range images {
fmt.Fprintf(w, "<picture>")
fmt.Fprintf(w, "<source srcset=\""+image+".png"+query+"&dark=1\" media=\"(prefers-color-scheme: dark)\">")
fmt.Fprintf(w, "<source srcset=\""+image+".png"+query+"&dark=0\">")
fmt.Fprintf(w, "<img class=\"light\" src=\""+image+".png"+query+"\" alt=\""+image+".png\">")
fmt.Fprintf(w, "</picture>")
}
fmt.Fprintf(w, "<div>")
printPageFooter(w)
}
func summaryPageHandler(w http.ResponseWriter, r *http.Request) {
pageHandler(w, r, "vsummary")
}
func topPageHandler(w http.ResponseWriter, r *http.Request) {
pageHandler(w, r, "top")
}
func yearPageHandler(w http.ResponseWriter, r *http.Request) {
pageHandler(w, r, "years")
}
func monthPageHandler(w http.ResponseWriter, r *http.Request) {
pageHandler(w, r, "months")
}
func dayPageHandler(w http.ResponseWriter, r *http.Request) {
pageHandler(w, r, "days")
}
func hourPageHandler(w http.ResponseWriter, r *http.Request) {
pageHandler(w, r, "hours", "hoursgraph")
}
func fivePageHandler(w http.ResponseWriter, r *http.Request) {
pageHandler(w, r, "five", "fivegraph")
}
func printPageHeader(w http.ResponseWriter) {
w.Header().Add("Content-Type", "text/html")
w.Header().Add("Expires", "0")
w.Header().Add("Refresh", "300")
fmt.Fprintf(w, "<!DOCTYPE html><html><head>")
printCss(w)
fmt.Fprintf(w, "</head><body>")
}
func printPageFooter(w http.ResponseWriter) {
printScript(w)
fmt.Fprintf(w, "</body></html>")
}
func printNav(w http.ResponseWriter, r *http.Request, ifList []string) {
fmt.Fprintf(w, "<ul class=\"nav\">")
// interface select
selectedIface := r.URL.Query().Get("iface")
fmt.Fprintf(w, "<select onchange=\"location.replace(location.pathname+'?iface='+encodeURIComponent(this.value))\" style=\"width: 120px\">")
fmt.Fprintf(w, "<option value=\"\">default interface</option>")
for _, iface := range ifList {
if len(iface) > 0 {
iface = strings.TrimSpace(iface)
if iface == selectedIface {
fmt.Fprintf(w, "<option selected>"+iface+"</option>")
} else {
fmt.Fprintf(w, "<option>"+iface+"</option>")
}
}
}
fmt.Fprintf(w, "</select>")
query := ""
if len(selectedIface) > 0 {
query = "?iface=" + selectedIface
}
fmt.Fprint(w, "<li><a href=\"summary"+query+"\">Summary</a></li>")
fmt.Fprint(w, "<li><a href=\"top"+query+"\">Top</a></li>")
fmt.Fprint(w, "<li><a href=\"years"+query+"\">Years</a></li>")
fmt.Fprint(w, "<li><a href=\"months"+query+"\">Months</a></li>")
fmt.Fprint(w, "<li><a href=\"days"+query+"\">Days</a></li>")
fmt.Fprint(w, "<li><a href=\"hours"+query+"\">Hours</a></li>")
fmt.Fprint(w, "<li><a href=\"five"+query+"\">Five Minutes</a></li>")
fmt.Fprintf(w, "</ul>")
}
func printCss(w http.ResponseWriter) {
fmt.Fprint(w, `<style>
body, input, select {
color: #222;
background: #fff;
font: 100% system-ui;
}
a {
color: #0033cc;
}
@media (prefers-color-scheme: dark) {
body, input, select {
color: #eee;
background: #121212;
}
a {
color: #809fff;
}
}
.nav {
display: inline-block;
margin-right: 42px;
}
.content {
display: inline-block;
vertical-align: top;
}
.content img {
margin-top: 16px;
display: block;
}
#live {
font-family: Courier, monospace;
}
</style>`)
}
func printScript(w http.ResponseWriter) {
fmt.Fprint(w, `<script>
(function connect() {
const socket = new WebSocket("ws://"+location.host+"/live"+location.search);
socket.addEventListener("open", function (event) {
socket.send("Hello!");
});
socket.addEventListener("message", function (event) {
document.getElementById("live").innerText = event.data;
});
socket.addEventListener("close", function (event) {
console.log('Socket is closed. Reconnect will be attempted in 10 second.', event.reason);
document.getElementById("live").innerText = "";
delete socket;
setTimeout(function() {
connect();
}, 10000);
});
})();
</script>`)
}
func imageHandler(w http.ResponseWriter, r *http.Request, args ...string) {
iface := r.URL.Query().Get("iface")
// check iface safe
if !checkIface(iface, nil) {
fmt.Fprintf(w, "Interface does not exist: "+iface)
return
}
dark := r.URL.Query().Get("dark")
if len(iface) > 0 {
args = append(args, "-i", iface)
}
if dark == "1" && len(*configDark) > 0 {
args = append(args, "--config", *configDark)
} else if len(*config) > 0 {
args = append(args, "--config", *config)
}
args = append(args, "-o", "-")
cmd := exec.Command("vnstati", args...)
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
return
}
w.Write(stdout)
}
func summaryHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-s")
}
func vsummaryHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-vs")
}
func hsummaryHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-hs")
}
func topHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-t")
}
func yearHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-y")
}
func monthHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-m")
}
func dayHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-d")
}
func hourHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-h")
}
func hourgraphHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-hg")
}
func fiveHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-5")
}
func fivegraphHandler(w http.ResponseWriter, r *http.Request) {
imageHandler(w, r, "-5g")
}
func getIfList() []string {
cmd := exec.Command("vnstat", "--iflist", "1")
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
return nil
}
iflist := strings.Split(string(stdout), "\n")
var result []string
for _, str := range iflist {
if len(str) > 0 {
result = append(result, str)
}
}
return result
}
func checkIface(iface string, ifList []string) bool {
if len(iface) == 0 {
return true
}
if ifList == nil {
ifList = getIfList()
}
for _, a := range ifList {
if a == iface {
return true
}
}
return false
}
func liveHandler(ws *websocket.Conn) {
var err error
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("receive failed:", err)
return
}
fmt.Println("reveived from client: " + reply)
iface := ws.Request().URL.Query().Get("iface")
if !checkIface(iface, nil) {
fmt.Println("Interface does not exist: ", iface)
return
}
startLive(iface, ws)
}
func startLive(iface string, ws *websocket.Conn) {
entry := LiveEntry{
Conn: ws,
Ch: make(chan bool),
}
if appendOrCreateEntry(iface, entry) {
go liveProcess(iface)
}
<-entry.Ch
}
func appendOrCreateEntry(iface string, entry LiveEntry) bool {
lock.Lock()
defer lock.Unlock()
if list, ok := mapConn[iface]; ok {
mapConn[iface] = append(list, entry)
return false
} else {
mapConn[iface] = []LiveEntry{entry}
return true
}
}
func liveProcess(iface string) {
args := []string{"-l"}
if len(iface) > 0 {
args = append(args, "-i", iface)
}
if len(*config) > 0 {
args = append(args, "--config", *config)
}
cmd := exec.Command("vnstat", args...)
stdout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println(err.Error())
return
}
defer stdout.Close()
err = cmd.Start()
if err != nil {
fmt.Println(err.Error())
return
}
defer func() {
cmd.Process.Signal(syscall.SIGINT)
cmd.Wait()
}()
buf := make([]byte, 1024)
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
<-ticker.C
read, err := stdout.Read(buf)
if err != nil {
fmt.Println(err.Error())
return
}
str := string(buf[:read])
// str := "rx:" + strconv.Itoa(time.Now().Nanosecond()) // test
i := strings.Index(str, "rx:")
if i != -1 {
lock.Lock()
message := str[i:]
list := mapConn[iface]
removeList := []int{}
for i, en := range list {
if err = websocket.Message.Send(en.Conn, message); err != nil {
en.Ch <- true
fmt.Println("send failed:", err)
removeList = append(removeList, i)
}
}
if len(removeList) > 0 {
for j, i := range removeList {
list = append(list[:i-j], list[i-j+1:]...)
}
if len(list) == 0 {
ticker.Stop()
delete(mapConn, iface)
lock.Unlock()
break
} else {
mapConn[iface] = list
}
}
lock.Unlock()
}
}
}