mon cycle and uptime

This commit is contained in:
HeshamTB 2024-03-24 18:13:26 +03:00
parent ed0fcb59eb
commit a9c728355b
5 changed files with 25 additions and 22 deletions

View File

@ -55,6 +55,8 @@ func main() {
func run(ctx *cli.Context) {
slog.Debug("Starting run()")
wgLink.StartedAT = time.Now().UTC()
slog.Info(fmt.Sprintf("Started at %s", wgLink.StartedAT))
hvpnnode3.StartMonitor(wgLink, *slog.Default())
apiMux := http.NewServeMux()

View File

@ -8,6 +8,7 @@ import (
"log/slog"
"net/http"
"net/url"
"time"
"github.com/felixge/httpsnoop"
"github.com/google/uuid"
@ -34,7 +35,8 @@ func HandleGetNodeInfo(wgLink *WGLink) http.HandlerFunc {
UDPPort: dev.ListenPort,
Endpoint: wgLink.Endpoint,
Type: dev.Type.String(),
// TODO: Send endpoint for clients to connect
StartedAt: wgLink.StartedAT,
Uptime: time.Since(wgLink.StartedAT),
},
)
}

View File

@ -20,6 +20,7 @@ type WGLink struct {
*wgctrl.Client
IPPool
Endpoint string // Endpoint for clients to use when connecting to this link. Has no effect.
StartedAT time.Time
lock *sync.Mutex
}

View File

@ -18,44 +18,38 @@ func StartMonitor(wg *WGLink, log slog.Logger) {
func monitor(wg *WGLink, log slog.Logger) {
log.Info("[WGMonitor] Starting")
for {
time.Sleep(time.Second * 5)
time.Sleep(time.Second * 10)
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 activePeers int
var totalRx int64
var totalTx int64
for _, peer := range activepeers {
for _, peer := range peers {
totalRx += peer.ReceiveBytes
totalTx += peer.TransmitBytes
if isActive(peer) {
activePeers += 1
}
}
sb.WriteString(fmt.Sprintf("Peers: %d ", len(peers)))
sb.WriteString(fmt.Sprintf("Active peers: %d ", activePeers))
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 {
func isActive(peer wgtypes.Peer) bool {
if peer.LastHandshakeTime.IsZero() {
continue
} else if time.Now().UTC().Sub(peer.LastHandshakeTime.UTC()) < time.Duration(4 * time.Minute) {
active = append(active, peer)
return false
} else if time.Since(peer.LastHandshakeTime.UTC()) < time.Duration(4 * time.Minute) {
return true
}
}
return active, nil
return false
}

View File

@ -1,8 +1,12 @@
package proto
import "time"
type NodePublicInfo struct {
PublicKey string `json:"public_key"`
UDPPort int `json:"udp_port"`
Endpoint string `json:"endpoint"`
Type string
Type string `json:"type"`
StartedAt time.Time `json:"started_at"`
Uptime time.Duration `json:"uptime"`
}