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 * 10) peers, err := wg.GetAllPeers() if err != nil { log.Error("[WGMonitor] " + err.Error()) continue } sb := strings.Builder{} var totalRx int64 var totalTx int64 for _, peer := range peers { totalRx += peer.ReceiveBytes totalTx += peer.TransmitBytes if !isActive(peer, wg) { 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") } } } sb.WriteString(fmt.Sprintf("Peers: %d ", len(peers))) sb.WriteString(fmt.Sprintf("TX: %d RX: %d", totalTx, totalRx)) log.Info("[WGMonitor] " + sb.String()) } } func isActive(peer wgtypes.Peer, wg *WGLink) bool { if peer.LastHandshakeTime.IsZero() { if time.Since(wg.meta.TimeAdded(peer.PublicKey)) < time.Duration(4 * time.Minute) { return true } return false } else if time.Since(peer.LastHandshakeTime.UTC()) < time.Duration(4 * time.Minute) { return true } return false }