forked from flashcatcloud/categraf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net.go
118 lines (94 loc) · 2.15 KB
/
net.go
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package net
import (
"fmt"
"log"
"net"
"flashcat.cloud/categraf/config"
"flashcat.cloud/categraf/inputs"
"flashcat.cloud/categraf/inputs/system"
"flashcat.cloud/categraf/pkg/filter"
"github.com/toolkits/pkg/container/list"
)
const inputName = "net"
type NetIOStats struct {
ps system.PS
config.Interval
CollectProtocolStats bool `toml:"collect_protocol_stats"`
Interfaces []string `toml:"interfaces"`
interfaceFilters filter.Filter
}
func init() {
ps := system.NewSystemPS()
inputs.Add(inputName, func() inputs.Input {
return &NetIOStats{
ps: ps,
}
})
}
func (s *NetIOStats) Prefix() string {
return inputName
}
func (s *NetIOStats) Drop() {}
func (s *NetIOStats) Init() error {
var err error
if len(s.Interfaces) > 0 {
s.interfaceFilters, err = filter.Compile(s.Interfaces)
if err != nil {
return fmt.Errorf("error compiling interfaces filter: %s", err)
}
}
return nil
}
func (s *NetIOStats) Gather(slist *list.SafeList) {
netio, err := s.ps.NetIO()
if err != nil {
log.Println("E! failed to get net io metrics:", err)
return
}
interfaces, err := net.Interfaces()
if err != nil {
log.Println("E! failed to list interfaces:", err)
return
}
interfacesByName := map[string]net.Interface{}
for _, iface := range interfaces {
interfacesByName[iface.Name] = iface
}
for _, io := range netio {
if len(s.Interfaces) > 0 {
var found bool
if s.interfaceFilters.Match(io.Name) {
found = true
}
if !found {
continue
}
}
iface, ok := interfacesByName[io.Name]
if !ok {
continue
}
if iface.Flags&net.FlagLoopback == net.FlagLoopback {
continue
}
if iface.Flags&net.FlagUp == 0 {
continue
}
tags := map[string]string{
"interface": io.Name,
}
fields := map[string]interface{}{
"bytes_sent": io.BytesSent,
"bits_sent": io.BytesSent * 8,
"bytes_recv": io.BytesRecv,
"bits_recv": io.BytesRecv * 8,
"packets_sent": io.PacketsSent,
"packets_recv": io.PacketsRecv,
"err_in": io.Errin,
"err_out": io.Errout,
"drop_in": io.Dropin,
"drop_out": io.Dropout,
}
inputs.PushSamples(slist, fields, tags)
}
}