Skip to content

Commit

Permalink
Get NIC Speed and Duplex from SysFs if ethtool is not available.
Browse files Browse the repository at this point in the history
Update ParseBool to return `false` for empty strings.

Signed-off-by: Jacob Young <jacoby@nvidia.com>
  • Loading branch information
Jacob Young committed May 11, 2023
1 parent d0b5715 commit 53f9704
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
34 changes: 34 additions & 0 deletions pkg/net/net_linux.go
Expand Up @@ -71,6 +71,8 @@ func nics(ctx *context.Context) []*NIC {
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)
Expand Down Expand Up @@ -248,6 +250,38 @@ func netDevicePCIAddress(netDevDir, netDevName string) *string {
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 := ioutil.ReadFile(path)
if err != nil {
return ""
}
return strings.TrimSpace(string(contents))
}

func (nic *NIC) setNicAttrEthtool(ctx *context.Context, dev string) error {
path, _ := exec.LookPath("ethtool")
cmd := exec.Command(path, dev)
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
msg := fmt.Sprintf("could not grab NIC link info for %s: %s", dev, err)
ctx.Warn(msg)
return err
}

m := parseNicAttrEthtool(&out)
nic.updateNicAttrEthtool(m)

return nil
}

func autoNegCap(m map[string][]string) *NICCapability {
autoNegotiation := NICCapability{Name: "auto-negotiation", IsEnabled: false, CanEnable: false}

Expand Down
3 changes: 3 additions & 0 deletions pkg/util/util.go
Expand Up @@ -71,6 +71,9 @@ func ParseBool(str string) (bool, error) {
"off": false,
"yes": true,
"no": false,
// Return false instead of an error on empty strings
// For example from empty files in SysClassNet/Device
"": false,
}
if b, ok := ExtraBools[strings.ToLower(str)]; ok {
return b, nil
Expand Down
4 changes: 4 additions & 0 deletions pkg/util/util_test.go
Expand Up @@ -75,6 +75,10 @@ func TestParseBool(t *testing.T) {
item: "1",
expected: true,
},
{
item: "",
expected: false,
},
{
item: "on",
expected: true,
Expand Down

0 comments on commit 53f9704

Please sign in to comment.