-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathnet_linux.go
More file actions
359 lines (318 loc) · 10.5 KB
/
net_linux.go
File metadata and controls
359 lines (318 loc) · 10.5 KB
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Use and distribution licensed under the Apache license version 2.
//
// See the COPYING file in the root project directory for full text.
//
package net
import (
"bufio"
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/jaypipes/ghw/internal/config"
"github.com/jaypipes/ghw/internal/log"
"github.com/jaypipes/ghw/pkg/linuxpath"
"github.com/jaypipes/ghw/pkg/util"
)
const (
warnEthtoolNotInstalled = `ethtool not installed. Cannot grab NIC capabilities`
)
func (i *Info) load(ctx context.Context) error {
i.NICs = nics(ctx)
return nil
}
func nics(ctx context.Context) []*NIC {
nics := make([]*NIC, 0)
paths := linuxpath.New(ctx)
files, err := os.ReadDir(paths.SysClassNet)
if err != nil {
return nics
}
etAvailable := config.ToolsEnabled(ctx)
if etAvailable {
if etInstalled := ethtoolInstalled(); !etInstalled {
log.Warn(ctx, warnEthtoolNotInstalled)
etAvailable = false
}
}
for _, file := range files {
filename := file.Name()
// Ignore loopback and bonding_masters
if filename == "lo" || filename == "bonding_masters" {
continue
}
netPath := filepath.Join(paths.SysClassNet, filename)
dest, _ := os.Readlink(netPath)
isVirtual := false
if strings.Contains(dest, "devices/virtual/net") {
isVirtual = true
}
nic := &NIC{
Name: filename,
IsVirtual: isVirtual,
}
mac := netDeviceMacAddress(paths, filename)
nic.MacAddress = mac
nic.MACAddress = mac
if etAvailable {
nic.netDeviceParseEthtool(ctx, filename)
} else {
nic.Capabilities = []*NICCapability{}
// Sets NIC struct fields from data in SysFs
nic.setNicAttrSysFs(paths, filename)
}
nic.PCIAddress = netDevicePCIAddress(paths.SysClassNet, filename)
nics = append(nics, nic)
}
return nics
}
func netDeviceMacAddress(paths *linuxpath.Paths, dev string) string {
// Instead of use udevadm, we can get the device's MAC address by examing
// the /sys/class/net/$DEVICE/address file in sysfs. However, for devices
// that have addr_assign_type != 0, return None since the MAC address is
// random.
aatPath := filepath.Join(paths.SysClassNet, dev, "addr_assign_type")
contents, err := os.ReadFile(aatPath)
if err != nil {
return ""
}
if strings.TrimSpace(string(contents)) != "0" {
return ""
}
addrPath := filepath.Join(paths.SysClassNet, dev, "address")
contents, err = os.ReadFile(addrPath)
if err != nil {
return ""
}
return strings.TrimSpace(string(contents))
}
func ethtoolInstalled() bool {
_, err := exec.LookPath("ethtool")
return err == nil
}
func (n *NIC) netDeviceParseEthtool(ctx context.Context, dev string) {
var out bytes.Buffer
path, _ := exec.LookPath("ethtool")
// Get auto-negotiation and pause-frame-use capabilities from "ethtool" (with no options)
// Populate Speed, Duplex, SupportedLinkModes, SupportedPorts, SupportedFECModes,
// AdvertisedLinkModes, and AdvertisedFECModes attributes from "ethtool" output.
cmd := exec.Command(path, dev)
cmd.Stdout = &out
err := cmd.Run()
if err == nil {
m := parseNicAttrEthtool(&out)
n.Capabilities = append(n.Capabilities, autoNegCap(m))
n.Capabilities = append(n.Capabilities, pauseFrameUseCap(m))
// Update NIC Attributes with ethtool output
n.Speed = strings.Join(m["Speed"], "")
n.Duplex = strings.Join(m["Duplex"], "")
n.SupportedLinkModes = m["Supported link modes"]
n.SupportedPorts = m["Supported ports"]
n.SupportedFECModes = m["Supported FEC modes"]
n.AdvertisedLinkModes = m["Advertised link modes"]
n.AdvertisedFECModes = m["Advertised FEC modes"]
} else {
msg := fmt.Sprintf("could not grab NIC link info for %s: %s", dev, err)
log.Warn(ctx, msg)
}
// Get all other capabilities from "ethtool -k"
cmd = exec.Command(path, "-k", dev)
cmd.Stdout = &out
err = cmd.Run()
if err == nil {
// The out variable will now contain something that looks like the
// following.
//
// Features for enp58s0f1:
// rx-checksumming: on
// tx-checksumming: off
// tx-checksum-ipv4: off
// tx-checksum-ip-generic: off [fixed]
// tx-checksum-ipv6: off
// tx-checksum-fcoe-crc: off [fixed]
// tx-checksum-sctp: off [fixed]
// scatter-gather: off
// tx-scatter-gather: off
// tx-scatter-gather-fraglist: off [fixed]
// tcp-segmentation-offload: off
// tx-tcp-segmentation: off
// tx-tcp-ecn-segmentation: off [fixed]
// tx-tcp-mangleid-segmentation: off
// tx-tcp6-segmentation: off
// < snipped >
scanner := bufio.NewScanner(&out)
// Skip the first line...
scanner.Scan()
for scanner.Scan() {
line := strings.TrimPrefix(scanner.Text(), "\t")
n.Capabilities = append(n.Capabilities, netParseEthtoolFeature(line))
}
} else {
msg := fmt.Sprintf("could not grab NIC capabilities for %s: %s", dev, err)
log.Warn(ctx, msg)
}
}
// netParseEthtoolFeature parses a line from the ethtool -k output and returns
// a NICCapability.
//
// The supplied line will look like the following:
//
// tx-checksum-ip-generic: off [fixed]
//
// [fixed] indicates that the feature may not be turned on/off. Note: it makes
// no difference whether a privileged user runs `ethtool -k` when determining
// whether [fixed] appears for a feature.
func netParseEthtoolFeature(line string) *NICCapability {
parts := strings.Fields(line)
cap := strings.TrimSuffix(parts[0], ":")
enabled := parts[1] == "on"
fixed := len(parts) == 3 && parts[2] == "[fixed]"
return &NICCapability{
Name: cap,
IsEnabled: enabled,
CanEnable: !fixed,
}
}
func netDevicePCIAddress(netDevDir, netDevName string) *string {
// what we do here is not that hard in the end: we need to navigate the sysfs
// up to the directory belonging to the device backing the network interface.
// we can make few relatively safe assumptions, but the safest way is follow
// the right links. And so we go.
// First of all, knowing the network device name we need to resolve the backing
// device path to its full sysfs path.
// say we start with netDevDir="/sys/class/net" and netDevName="enp0s31f6"
netPath := filepath.Join(netDevDir, netDevName)
dest, err := os.Readlink(netPath)
if err != nil {
// bail out with empty value
return nil
}
// now we have something like dest="../../devices/pci0000:00/0000:00:1f.6/net/enp0s31f6"
// remember the path is relative to netDevDir="/sys/class/net"
netDev := filepath.Clean(filepath.Join(netDevDir, dest))
// so we clean "/sys/class/net/../../devices/pci0000:00/0000:00:1f.6/net/enp0s31f6"
// leading to "/sys/devices/pci0000:00/0000:00:1f.6/net/enp0s31f6"
// still not there. We need to access the data of the pci device. So we jump into the path
// linked to the "device" pseudofile
dest, err = os.Readlink(filepath.Join(netDev, "device"))
if err != nil {
// bail out with empty value
return nil
}
// we expect something like="../../../0000:00:1f.6"
devPath := filepath.Clean(filepath.Join(netDev, dest))
// so we clean "/sys/devices/pci0000:00/0000:00:1f.6/net/enp0s31f6/../../../0000:00:1f.6"
// leading to "/sys/devices/pci0000:00/0000:00:1f.6/"
// finally here!
// to which bus is this device connected to?
dest, err = os.Readlink(filepath.Join(devPath, "subsystem"))
if err != nil {
// bail out with empty value
return nil
}
// ok, this is hacky, but since we need the last *two* path components and we know we
// are running on linux...
if !strings.HasSuffix(dest, "/bus/pci") {
// unsupported and unexpected bus!
return nil
}
pciAddr := filepath.Base(devPath)
return &pciAddr
}
func (nic *NIC) setNicAttrSysFs(paths *linuxpath.Paths, dev string) {
// Get speed and duplex from /sys/class/net/$DEVICE/ directory
nic.Speed = readFile(filepath.Join(paths.SysClassNet, dev, "speed"))
nic.Duplex = readFile(filepath.Join(paths.SysClassNet, dev, "duplex"))
}
func readFile(path string) string {
contents, err := os.ReadFile(path)
if err != nil {
return ""
}
return strings.TrimSpace(string(contents))
}
func autoNegCap(m map[string][]string) *NICCapability {
autoNegotiation := NICCapability{Name: "auto-negotiation", IsEnabled: false, CanEnable: false}
an, anErr := util.ParseBool(strings.Join(m["Auto-negotiation"], ""))
aan, aanErr := util.ParseBool(strings.Join(m["Advertised auto-negotiation"], ""))
if an && aan && aanErr == nil && anErr == nil {
autoNegotiation.IsEnabled = true
}
san, err := util.ParseBool(strings.Join(m["Supports auto-negotiation"], ""))
if san && err == nil {
autoNegotiation.CanEnable = true
}
return &autoNegotiation
}
func pauseFrameUseCap(m map[string][]string) *NICCapability {
pauseFrameUse := NICCapability{Name: "pause-frame-use", IsEnabled: false, CanEnable: false}
apfu, err := util.ParseBool(strings.Join(m["Advertised pause frame use"], ""))
if apfu && err == nil {
pauseFrameUse.IsEnabled = true
}
spfu, err := util.ParseBool(strings.Join(m["Supports pause frame use"], ""))
if spfu && err == nil {
pauseFrameUse.CanEnable = true
}
return &pauseFrameUse
}
func parseNicAttrEthtool(out *bytes.Buffer) map[string][]string {
// The out variable will now contain something that looks like the
// following.
//
//Settings for eth0:
// Supported ports: [ TP ]
// Supported link modes: 10baseT/Half 10baseT/Full
// 100baseT/Half 100baseT/Full
// 1000baseT/Full
// Supported pause frame use: No
// Supports auto-negotiation: Yes
// Supported FEC modes: Not reported
// Advertised link modes: 10baseT/Half 10baseT/Full
// 100baseT/Half 100baseT/Full
// 1000baseT/Full
// Advertised pause frame use: No
// Advertised auto-negotiation: Yes
// Advertised FEC modes: Not reported
// Speed: 1000Mb/s
// Duplex: Full
// Auto-negotiation: on
// Port: Twisted Pair
// PHYAD: 1
// Transceiver: internal
// MDI-X: off (auto)
// Supports Wake-on: pumbg
// Wake-on: d
// Current message level: 0x00000007 (7)
// drv probe link
// Link detected: yes
scanner := bufio.NewScanner(out)
// Skip the first line
scanner.Scan()
m := make(map[string][]string)
var name string
for scanner.Scan() {
var fields []string
if strings.Contains(scanner.Text(), ":") {
line := strings.Split(scanner.Text(), ":")
name = strings.TrimSpace(line[0])
str := strings.Trim(strings.TrimSpace(line[1]), "[]")
switch str {
case
"Not reported",
"Unknown":
continue
}
fields = strings.Fields(str)
} else {
fields = strings.Fields(strings.Trim(strings.TrimSpace(scanner.Text()), "[]"))
}
for _, f := range fields {
m[name] = append(m[name], strings.TrimSpace(f))
}
}
return m
}