-
Notifications
You must be signed in to change notification settings - Fork 13
/
net_darwin.go
85 lines (76 loc) · 2.41 KB
/
net_darwin.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
package main
import (
"errors"
"os/exec"
"regexp"
"strconv"
)
const NET = "net"
func init() {
parser.Add(NET, "true", "Collect network metrics")
}
var mapStatMapping = map[string]string{
"total packets received": "ip.TotalPacketsReceived",
"forwarded": "ip.Forwarded",
"incoming packets discarded": "ip.IncomingPacketsDiscarded",
"incoming packets delivered": "ip.IncomingPacketsDelivered",
"requests sent out": "ip.RequestsSentOut",
"active connections openings": "tcp.ActiveConnectionsOpenings",
"passive connection openings": "tcp.PassiveConnectionsOpenings",
"failed connection attempts": "tcp.FailedConnectionAttempts",
"connection resets received": "tcp.ConnectionResetsReceived",
"connections established": "tcp.ConnectionsEstablished",
"segments received": "tcp.SegmentsReceived",
"segments send out": "tcp.SegmentsSendOut",
"segments retransmited": "tcp.SegmentsTransmitted",
"bad segments received.": "tcp.BadSegmentsReceived",
"resets sent": "tcp.ResetsSent",
"packets received": "udp.PacketsReceived",
"packets to unknown port received.": "udp.PacketsToUnknownPortRecived",
"packet receive errors": "udp.PacketReceiveErrors",
"packets sent": "udp.PacketsSent",
}
type Net struct {
RawStatus []byte
}
func (self *Net) fetch() (b []byte, e error) {
if len(self.RawStatus) == 0 {
self.RawStatus, _ = exec.Command("netstat", "-s").Output()
if len(self.RawStatus) == 0 {
e = errors.New("netstat returned empty output")
return
}
}
b = self.RawStatus
return
}
func (self *Net) Prefix() string {
return "net"
}
func (self *Net) Collect(c *MetricsCollection) (e error) {
s, e := self.fetch()
if e != nil {
return
}
raw := string(s)
re := regexp.MustCompile("(\\d+) ([\\w\\ \\.]+)")
for _, v := range re.FindAllStringSubmatch(raw, -1) {
if value, e := strconv.ParseInt(v[1], 10, 64); e == nil {
if k, ok := mapStatMapping[v[2]]; ok {
c.Add(k, value)
}
}
}
re = regexp.MustCompile("(\\w+): (\\d+)")
for _, v := range re.FindAllStringSubmatch(raw, -1) {
if value, e := strconv.ParseInt(v[2], 10, 64); e == nil {
switch v[1] {
case "InOctets":
c.Add("ip.InOctets", value)
case "OutOctets":
c.Add("ip.OutOctets", value)
}
}
}
return
}