host_net.go 2.45 KB
Newer Older
Lei Li's avatar
Lei Li committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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
}