62 lines
1.5 KiB
Go
62 lines
1.5 KiB
Go
package hvpnnode3
|
|
|
|
import (
|
|
"fmt"
|
|
"log/slog"
|
|
"strings"
|
|
"time"
|
|
|
|
"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
|
|
)
|
|
|
|
var log slog.Logger
|
|
|
|
func StartMonitor(wg *WGLink, log slog.Logger) {
|
|
go monitor(wg, log)
|
|
}
|
|
|
|
func monitor(wg *WGLink, log slog.Logger) {
|
|
log.Info("[WGMonitor] Starting")
|
|
for {
|
|
time.Sleep(time.Second * 5)
|
|
peers, err := wg.GetAllPeers()
|
|
if err != nil {
|
|
log.Error("[WGMonitor] " + err.Error())
|
|
continue
|
|
}
|
|
|
|
activepeers, err := getActivePeers(peers)
|
|
if err != nil {
|
|
log.Error("[WGMonitor] " + err.Error())
|
|
continue
|
|
}
|
|
|
|
sb := strings.Builder{}
|
|
sb.WriteString(fmt.Sprintf("Peers: %d ", len(peers)))
|
|
sb.WriteString(fmt.Sprintf("Active peers: %d ", len(activepeers)))
|
|
|
|
var totalRx int64
|
|
var totalTx int64
|
|
for _, peer := range activepeers {
|
|
totalRx += peer.ReceiveBytes
|
|
totalTx += peer.TransmitBytes
|
|
}
|
|
sb.WriteString(fmt.Sprintf("TX: %d RX: %d", totalTx, totalRx))
|
|
|
|
log.Info("[WGMonitor] " + sb.String())
|
|
}
|
|
}
|
|
|
|
func getActivePeers(peers []wgtypes.Peer) ([]wgtypes.Peer, error) {
|
|
active := make([]wgtypes.Peer, 0)
|
|
for _, peer := range peers {
|
|
if peer.LastHandshakeTime.IsZero() {
|
|
continue
|
|
} else if time.Now().UTC().Sub(peer.LastHandshakeTime.UTC()) < time.Duration(4 * time.Minute) {
|
|
active = append(active, peer)
|
|
}
|
|
}
|
|
return active, nil
|
|
}
|
|
|