talos
79 строк · 1.5 Кб
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5package nethelpers
6
7import (
8"bytes"
9"io"
10"os"
11"path/filepath"
12"strings"
13)
14
15// DeviceInfo contains device hardware information that can be read from /sys/.
16type DeviceInfo struct {
17BusPath string
18PCIID string
19Driver string
20}
21
22// GetDeviceInfo get additional device information by reading /sys/ directory.
23//
24//nolint:gocyclo
25func GetDeviceInfo(deviceName string) (*DeviceInfo, error) {
26path := filepath.Join("/sys/class/net/", deviceName, "/device/")
27
28readFile := func(path string) (string, error) {
29f, err := os.Open(path)
30if err != nil {
31return "", err
32}
33
34res, err := io.ReadAll(f)
35if err != nil {
36return "", err
37}
38
39return string(bytes.TrimSpace(res)), nil
40}
41
42_, err := os.Stat(path)
43if err != nil {
44if os.IsNotExist(err) {
45return &DeviceInfo{}, nil
46}
47
48return nil, err
49}
50
51ueventContents, err := readFile(filepath.Join(path, "uevent"))
52if err != nil {
53return nil, err
54}
55
56if ueventContents == "" {
57return &DeviceInfo{}, nil
58}
59
60device := &DeviceInfo{}
61
62for _, line := range strings.Split(ueventContents, "\n") {
63key, value, found := strings.Cut(line, "=")
64if !found {
65continue
66}
67
68switch key {
69case "DRIVER":
70device.Driver = value
71case "PCI_ID":
72device.PCIID = value
73case "PCI_SLOT_NAME":
74device.BusPath = value
75}
76}
77
78return device, nil
79}
80