Skip to content

Commit

Permalink
Fix bug when /proc/net/dev contains unexpected line (prometheus#421)
Browse files Browse the repository at this point in the history
* fix bug when /proc/net/dev contains unexpected line

Signed-off-by: 吴家榜 <[email protected]>

* modifying netDev.parseLine due to odd interface name

Signed-off-by: 吴家榜 <[email protected]>

* adding testing case for net device that has colon in its name

Signed-off-by: 吴家榜 <[email protected]>

Co-authored-by: wujiabang <[email protected]>
Co-authored-by: 吴家榜 <[email protected]>
  • Loading branch information
3 people authored Nov 24, 2021
1 parent 4f613c6 commit 081c329
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
8 changes: 4 additions & 4 deletions net_dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,17 +87,17 @@ func newNetDev(file string) (NetDev, error) {
// parseLine parses a single line from the /proc/net/dev file. Header lines
// must be filtered prior to calling this method.
func (netDev NetDev) parseLine(rawLine string) (*NetDevLine, error) {
parts := strings.SplitN(rawLine, ":", 2)
if len(parts) != 2 {
idx := strings.LastIndex(rawLine, ":")
if idx == -1 {
return nil, errors.New("invalid net/dev line, missing colon")
}
fields := strings.Fields(strings.TrimSpace(parts[1]))
fields := strings.Fields(strings.TrimSpace(rawLine[idx+1:]))

var err error
line := &NetDevLine{}

// Interface Name
line.Name = strings.TrimSpace(parts[0])
line.Name = strings.TrimSpace(rawLine[:idx])
if line.Name == "" {
return nil, errors.New("invalid net/dev line, empty interface name")
}
Expand Down
21 changes: 12 additions & 9 deletions net_dev_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,24 @@
package procfs

import (
"fmt"
"testing"
)

func TestNetDevParseLine(t *testing.T) {
const rawLine = ` eth0: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16`

have, err := NetDev{}.parseLine(rawLine)
if err != nil {
t.Fatal(err)
tc := []string{"eth0", "eth0:1"}
for i := range tc {
rawLine := fmt.Sprintf(` %v: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16`, tc[i])
have, err := NetDev{}.parseLine(rawLine)
if err != nil {
t.Fatal(err)
}
want := NetDevLine{tc[i], 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
if want != *have {
t.Errorf("want %v, have %v", want, have)
}
}

want := NetDevLine{"eth0", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}
if want != *have {
t.Errorf("want %v, have %v", want, have)
}
}

func TestNetDev(t *testing.T) {
Expand Down

0 comments on commit 081c329

Please sign in to comment.