forked from krlc/bravo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
statsStore.go
101 lines (82 loc) · 2.05 KB
/
statsStore.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
package main
import (
"log"
"os/exec"
"strconv"
"github.com/mdlayher/wireguardctrl"
)
type StatsStore struct {
w *wireguardctrl.Client
Alive bool
Endpoint string
Received string
Sent string
}
func toReadable(bytes int64) string {
const (
KB = 1024 << (10 * iota) // 2^20
MB
GB
TB
)
num := float64(bytes)
switch {
case bytes >= TB:
return strconv.FormatFloat(num / TB, 'f', 2, 64) + " TiB"
case bytes >= GB:
return strconv.FormatFloat(num / GB, 'f', 2, 64) + " GiB"
case bytes >= MB:
return strconv.FormatFloat(num / MB, 'f', 2, 64) + " MiB"
case bytes >= KB:
return strconv.FormatFloat(num / KB, 'f', 2, 64) + " KiB"
default:
return strconv.FormatFloat(num, 'f', 2, 64) + " bytes"
}
}
func (d *StatsStore) Update() *StatsStore {
// init client
if d.w == nil {
c, err := wireguardctrl.New()
if err != nil {
log.Fatalf("Failed to open wireguardctrl: %v", err)
}
d.w = c
}
devs, err := d.w.Devices()
if err != nil {
log.Fatalf("Failed to get devices: %v", err)
}
if devs == nil {
d.Alive = false
return d
}
// TODO: to be rewritten:
peers := devs[0].Peers // we only expect 1 wireguard connection
if peers == nil {
d.Alive = false
return d
}
peer := peers[0] // and only one vpn server
d.Alive = true
d.Endpoint = peer.Endpoint.IP.String()
d.Received = toReadable(peer.ReceiveBytes)
d.Sent = toReadable(peer.TransmitBytes)
return d
}
func (d *StatsStore) Close() {
if err := d.w.Close(); err != nil {
log.Println("Error closing wireguardctrl watcher:", err)
}
}
// TODO: Buggy
func toggleConnection(disconnect bool) {
var arg string
if disconnect {
arg = "down"
} else {
arg = "up"
}
if err := exec.Command("wg-quick", arg, conf.WgConfig).Run(); err != nil {
log.Println("Error running wg-quick:", err)
}
}