forked from shirou/gopsutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
net_darwin.go
267 lines (235 loc) · 6.83 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
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// +build darwin
package net
import (
"errors"
"fmt"
"os/exec"
"regexp"
"strconv"
"strings"
)
var (
errNetstatHeader = errors.New("Can't parse header of netstat output")
netstatLinkRegexp = regexp.MustCompile(`^<Link#(\d+)>$`)
)
const endOfLine = "\n"
func parseNetstatLine(line string) (stat *IOCountersStat, linkId *uint, err error) {
var (
numericValue uint64
columns = strings.Fields(line)
)
if columns[0] == "Name" {
err = errNetstatHeader
return
}
// try to extract the numeric value from <Link#123>
if subMatch := netstatLinkRegexp.FindStringSubmatch(columns[2]); len(subMatch) == 2 {
numericValue, err = strconv.ParseUint(subMatch[1], 10, 64)
if err != nil {
return
}
linkIdUint := uint(numericValue)
linkId = &linkIdUint
}
base := 1
numberColumns := len(columns)
// sometimes Address is ommitted
if numberColumns < 12 {
base = 0
}
if numberColumns < 11 || numberColumns > 13 {
err = fmt.Errorf("Line %q do have an invalid number of columns %d", line, numberColumns)
return
}
parsed := make([]uint64, 0, 7)
vv := []string{
columns[base+3], // Ipkts == PacketsRecv
columns[base+4], // Ierrs == Errin
columns[base+5], // Ibytes == BytesRecv
columns[base+6], // Opkts == PacketsSent
columns[base+7], // Oerrs == Errout
columns[base+8], // Obytes == BytesSent
}
if len(columns) == 12 {
vv = append(vv, columns[base+10])
}
for _, target := range vv {
if target == "-" {
parsed = append(parsed, 0)
continue
}
if numericValue, err = strconv.ParseUint(target, 10, 64); err != nil {
return
}
parsed = append(parsed, numericValue)
}
stat = &IOCountersStat{
Name: strings.Trim(columns[0], "*"), // remove the * that sometimes is on right on interface
PacketsRecv: parsed[0],
Errin: parsed[1],
BytesRecv: parsed[2],
PacketsSent: parsed[3],
Errout: parsed[4],
BytesSent: parsed[5],
}
if len(parsed) == 7 {
stat.Dropout = parsed[6]
}
return
}
type netstatInterface struct {
linkId *uint
stat *IOCountersStat
}
func parseNetstatOutput(output string) ([]netstatInterface, error) {
var (
err error
lines = strings.Split(strings.Trim(output, endOfLine), endOfLine)
)
// number of interfaces is number of lines less one for the header
numberInterfaces := len(lines) - 1
interfaces := make([]netstatInterface, numberInterfaces)
// no output beside header
if numberInterfaces == 0 {
return interfaces, nil
}
for index := 0; index < numberInterfaces; index++ {
nsIface := netstatInterface{}
if nsIface.stat, nsIface.linkId, err = parseNetstatLine(lines[index+1]); err != nil {
return nil, err
}
interfaces[index] = nsIface
}
return interfaces, nil
}
// map that hold the name of a network interface and the number of usage
type mapInterfaceNameUsage map[string]uint
func newMapInterfaceNameUsage(ifaces []netstatInterface) mapInterfaceNameUsage {
output := make(mapInterfaceNameUsage)
for index := range ifaces {
if ifaces[index].linkId != nil {
ifaceName := ifaces[index].stat.Name
usage, ok := output[ifaceName]
if ok {
output[ifaceName] = usage + 1
} else {
output[ifaceName] = 1
}
}
}
return output
}
func (min mapInterfaceNameUsage) isTruncated() bool {
for _, usage := range min {
if usage > 1 {
return true
}
}
return false
}
func (min mapInterfaceNameUsage) notTruncated() []string {
output := make([]string, 0)
for ifaceName, usage := range min {
if usage == 1 {
output = append(output, ifaceName)
}
}
return output
}
// example of `netstat -ibdnW` output on yosemite
// Name Mtu Network Address Ipkts Ierrs Ibytes Opkts Oerrs Obytes Coll Drop
// lo0 16384 <Link#1> 869107 0 169411755 869107 0 169411755 0 0
// lo0 16384 ::1/128 ::1 869107 - 169411755 869107 - 169411755 - -
// lo0 16384 127 127.0.0.1 869107 - 169411755 869107 - 169411755 - -
func IOCounters(pernic bool) ([]IOCountersStat, error) {
var (
ret []IOCountersStat
retIndex int
)
netstat, err := exec.LookPath("/usr/sbin/netstat")
if err != nil {
return nil, err
}
// try to get all interface metrics, and hope there won't be any truncated
out, err := invoke.Command(netstat, "-ibdnW")
if err != nil {
return nil, err
}
nsInterfaces, err := parseNetstatOutput(string(out))
if err != nil {
return nil, err
}
ifaceUsage := newMapInterfaceNameUsage(nsInterfaces)
notTruncated := ifaceUsage.notTruncated()
ret = make([]IOCountersStat, len(notTruncated))
if !ifaceUsage.isTruncated() {
// no truncated interface name, return stats of all interface with <Link#...>
for index := range nsInterfaces {
if nsInterfaces[index].linkId != nil {
ret[retIndex] = *nsInterfaces[index].stat
retIndex++
}
}
} else {
// duplicated interface, list all interfaces
ifconfig, err := exec.LookPath("/sbin/ifconfig")
if err != nil {
return nil, err
}
if out, err = invoke.Command(ifconfig, "-l"); err != nil {
return nil, err
}
interfaceNames := strings.Fields(strings.TrimRight(string(out), endOfLine))
// for each of the interface name, run netstat if we don't have any stats yet
for _, interfaceName := range interfaceNames {
truncated := true
for index := range nsInterfaces {
if nsInterfaces[index].linkId != nil && nsInterfaces[index].stat.Name == interfaceName {
// handle the non truncated name to avoid execute netstat for them again
ret[retIndex] = *nsInterfaces[index].stat
retIndex++
truncated = false
break
}
}
if truncated {
// run netstat with -I$ifacename
if out, err = invoke.Command(netstat, "-ibdnWI" + interfaceName);err != nil {
return nil, err
}
parsedIfaces, err := parseNetstatOutput(string(out))
if err != nil {
return nil, err
}
if len(parsedIfaces) == 0 {
// interface had been removed since `ifconfig -l` had been executed
continue
}
for index := range parsedIfaces {
if parsedIfaces[index].linkId != nil {
ret = append(ret, *parsedIfaces[index].stat)
break
}
}
}
}
}
if pernic == false {
return getIOCountersAll(ret)
}
return ret, nil
}
// NetIOCountersByFile is an method which is added just a compatibility for linux.
func IOCountersByFile(pernic bool, filename string) ([]IOCountersStat, error) {
return IOCounters(pernic)
}
func FilterCounters() ([]FilterStat, error) {
return nil, errors.New("NetFilterCounters not implemented for darwin")
}
// NetProtoCounters returns network statistics for the entire system
// If protocols is empty then all protocols are returned, otherwise
// just the protocols in the list are returned.
// Not Implemented for Darwin
func ProtoCounters(protocols []string) ([]ProtoCountersStat, error) {
return nil, errors.New("NetProtoCounters not implemented for darwin")
}