/
wireguard.go
112 lines (98 loc) · 2.73 KB
/
wireguard.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
package opnsense
import (
"github.com/go-kit/log"
"github.com/go-kit/log/level"
)
type wireguardClientsResponse struct {
Rows []struct {
IfId string `json:"if"`
IfType string `json:"type"`
LatestHandshake float64 `json:"latest-handshake"`
TransferRx float64 `json:"transfer-rx"`
TransferTx float64 `json:"transfer-tx"`
Status string `json:"status"`
Name string `json:"name"`
IfName string `json:"ifname"`
} `json:"rows"`
RowCount int `json:"rowCount"`
Total int `json:"total"`
Current int `json:"current"`
}
// WGInterfaceStatus is the custom type that represents the status of a Wireguard interface
type WGInterfaceStatus int
const (
WGInterfaceStatusDown WGInterfaceStatus = iota
WGInterfaceStatusUp
WGInterfaceStatusUnknown
)
type WireguardPeers struct {
Device string
DeviceName string
DeviceType string
LatestHandshake float64
TransferRx float64
TransferTx float64
Name string
}
type WireguardInterfaces struct {
Device string
DeviceType string
Status WGInterfaceStatus
Name string
DeviceName string
}
type WireguardClients struct {
Peers []WireguardPeers
Interfaces []WireguardInterfaces
}
// parseWGInterfaceStatus parses a string status to a WGInterfaceStatus type.
func parseWGInterfaceStatus(statusTranslated string, logger log.Logger, originalStatus string) WGInterfaceStatus {
switch statusTranslated {
case "up":
return WGInterfaceStatusUp
case "down":
return WGInterfaceStatusDown
default:
level.Warn(logger).
Log("msg", "unknown wireguard interface status detected", "status", originalStatus)
return WGInterfaceStatusUnknown
}
}
func (c *Client) FetchWireguardConfig() (WireguardClients, *APICallError) {
var response wireguardClientsResponse
var data WireguardClients
url, ok := c.endpoints["wireguardClients"]
if !ok {
return data, &APICallError{
Endpoint: string(url),
Message: "Unable to fetch Wireguard stats",
StatusCode: 0,
}
}
if err := c.do("GET", url, nil, &response); err != nil {
return data, err
}
for _, v := range response.Rows {
if v.IfType == "interface" {
data.Interfaces = append(data.Interfaces, WireguardInterfaces{
Device: v.IfId,
DeviceType: v.IfType,
Status: parseWGInterfaceStatus(v.Status, c.log, v.Status),
Name: v.Name,
DeviceName: v.IfName,
})
}
if v.IfType == "peer" {
data.Peers = append(data.Peers, WireguardPeers{
DeviceType: v.IfType,
LatestHandshake: v.LatestHandshake,
TransferRx: v.TransferRx,
TransferTx: v.TransferTx,
Name: v.Name,
DeviceName: v.IfName,
Device: v.IfId,
})
}
}
return data, nil
}