2024-03-19 00:56:52 +01:00
|
|
|
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 {
|
2024-03-24 16:13:26 +01:00
|
|
|
time.Sleep(time.Second * 10)
|
2024-03-19 00:56:52 +01:00
|
|
|
peers, err := wg.GetAllPeers()
|
|
|
|
if err != nil {
|
|
|
|
log.Error("[WGMonitor] " + err.Error())
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
sb := strings.Builder{}
|
|
|
|
var totalRx int64
|
|
|
|
var totalTx int64
|
2024-03-24 16:13:26 +01:00
|
|
|
for _, peer := range peers {
|
2024-03-19 00:56:52 +01:00
|
|
|
totalRx += peer.ReceiveBytes
|
|
|
|
totalTx += peer.TransmitBytes
|
2024-03-27 23:22:29 +01:00
|
|
|
if !isActive(peer, wg) {
|
2024-03-24 16:26:48 +01:00
|
|
|
log.Info(
|
|
|
|
fmt.Sprintf("[WGMonitor] Evecting peer %s", peer.PublicKey.String()),
|
|
|
|
)
|
|
|
|
if err := wg.DeletePeer(peer.PublicKey.String()); err != nil {
|
|
|
|
log.Error(err.Error())
|
|
|
|
log.Warn("[WGMonitor] Could not evect peer")
|
|
|
|
}
|
2024-03-24 16:13:26 +01:00
|
|
|
}
|
2024-03-19 00:56:52 +01:00
|
|
|
}
|
2024-03-24 16:13:26 +01:00
|
|
|
sb.WriteString(fmt.Sprintf("Peers: %d ", len(peers)))
|
2024-03-19 00:56:52 +01:00
|
|
|
sb.WriteString(fmt.Sprintf("TX: %d RX: %d", totalTx, totalRx))
|
|
|
|
|
|
|
|
log.Info("[WGMonitor] " + sb.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-27 23:22:29 +01:00
|
|
|
func isActive(peer wgtypes.Peer, wg *WGLink) bool {
|
2024-03-24 16:13:26 +01:00
|
|
|
if peer.LastHandshakeTime.IsZero() {
|
2024-03-27 23:22:29 +01:00
|
|
|
if time.Since(wg.meta.TimeAdded(peer.PublicKey)) < time.Duration(4 * time.Minute) {
|
|
|
|
return true
|
|
|
|
}
|
2024-03-24 16:13:26 +01:00
|
|
|
return false
|
|
|
|
} else if time.Since(peer.LastHandshakeTime.UTC()) < time.Duration(4 * time.Minute) {
|
|
|
|
return true
|
2024-03-19 00:56:52 +01:00
|
|
|
}
|
2024-03-24 16:13:26 +01:00
|
|
|
return false
|
2024-03-19 00:56:52 +01:00
|
|
|
}
|
|
|
|
|