package resources import ( "time" "github.com/shirou/gopsutil/net" ) type HostNetIOUsage net.IOCountersStat type HostNetIOCountersStatWrap struct { IOStat []net.IOCountersStat Ts int64 } func GetHostNetIOUsageWithInterval(d time.Duration) ([]HostNetIOUsage, error) { usages := make([]HostNetIOUsage, 0) pre, err := net.IOCounters(false) if err != nil { return usages, err } preWrap := HostNetIOCountersStatWrap{IOStat: pre, Ts: time.Now().Unix()} time.Sleep(d) now, err := net.IOCounters(false) if err != nil { return usages, err } nowWrap := HostNetIOCountersStatWrap{IOStat: now, Ts: time.Now().Unix()} return calculateNetIOUsage(&preWrap, &nowWrap), nil } func GetHostNetIOUsageWithPre(preWrap *HostNetIOCountersStatWrap) ( []HostNetIOUsage, *HostNetIOCountersStatWrap, error) { usages := make([]HostNetIOUsage, 0) now, err := net.IOCounters(false) if err != nil { return usages, nil, err } nowWrap := HostNetIOCountersStatWrap{IOStat: now, Ts: time.Now().Unix()} if preWrap == nil { return calculateNetIOUsage(&nowWrap, &nowWrap), &nowWrap, nil } return calculateNetIOUsage(preWrap, &nowWrap), &nowWrap, nil } func calculateNetIOUsage(preWrap, nowWrap *HostNetIOCountersStatWrap) []HostNetIOUsage { usages := make([]HostNetIOUsage, 0) duration := nowWrap.Ts - preWrap.Ts for _, nowStat := range nowWrap.IOStat { usage := HostNetIOUsage{ Name: nowStat.Name, } for _, preStat := range preWrap.IOStat { if preStat.Name == nowStat.Name { usage.BytesSent = iops(preStat.BytesSent, nowStat.BytesSent, uint64(duration)) usage.BytesRecv = iops(preStat.BytesRecv, nowStat.BytesRecv, uint64(duration)) usage.PacketsSent = iops(preStat.PacketsSent, nowStat.PacketsSent, uint64(duration)) usage.PacketsRecv = iops(preStat.PacketsRecv, nowStat.PacketsRecv, uint64(duration)) usage.Errin = iops(preStat.Errin, nowStat.Errin, uint64(duration)) usage.Errout = iops(preStat.Errout, nowStat.Errout, uint64(duration)) usage.Dropin = iops(preStat.Dropin, nowStat.Dropin, uint64(duration)) usage.Dropout = iops(preStat.Dropout, nowStat.Dropout, uint64(duration)) usage.Fifoin = iops(preStat.Fifoin, nowStat.Fifoin, uint64(duration)) usage.Fifoout = iops(preStat.Fifoout, nowStat.Fifoout, uint64(duration)) break } } usages = append(usages, usage) } return usages } func iops(pre, now, duration uint64) uint64 { diff := (now - pre) if diff > 0 && duration > 0 { return diff / duration } return 0 }