-
Notifications
You must be signed in to change notification settings - Fork 457
/
device.go
79 lines (64 loc) · 1.5 KB
/
device.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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
package nethelpers
import (
"bytes"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
// DeviceInfo contains device hardware information that can be read from /sys/.
type DeviceInfo struct {
BusPath string
PCIID string
Driver string
}
// GetDeviceInfo get additional device information by reading /sys/ directory.
//
//nolint:gocyclo
func GetDeviceInfo(deviceName string) (*DeviceInfo, error) {
path := filepath.Join("/sys/class/net/", deviceName, "/device/")
readFile := func(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
res, err := ioutil.ReadAll(f)
if err != nil {
return "", err
}
return string(bytes.TrimSpace(res)), nil
}
_, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return &DeviceInfo{}, nil
}
return nil, err
}
ueventContents, err := readFile(filepath.Join(path, "uevent"))
if err != nil {
return nil, err
}
if ueventContents == "" {
return &DeviceInfo{}, nil
}
device := &DeviceInfo{}
for _, line := range strings.Split(ueventContents, "\n") {
key, value, found := strings.Cut(line, "=")
if !found {
continue
}
switch key {
case "DRIVER":
device.Driver = value
case "PCI_ID":
device.PCIID = value
case "PCI_SLOT_NAME":
device.BusPath = value
}
}
return device, nil
}