Skip to content

Commit

Permalink
Merge pull request open-falcon-archive#15 from mdh67899/nic-stat
Browse files Browse the repository at this point in the history
修复内核版本低于2.6.33时取不到net.if.speed.bits值的问题
  • Loading branch information
UlricQin authored Dec 20, 2018
2 parents 3bba579 + b3f8177 commit 7494d04
Showing 1 changed file with 43 additions and 4 deletions.
47 changes: 43 additions & 4 deletions ifstat.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ import (
"bufio"
"bytes"
"fmt"
"github.com/toolkits/file"
"io"
"io/ioutil"
"strconv"
"strings"

"github.com/toolkits/file"
"github.com/toolkits/sys"
)

const (
Expand Down Expand Up @@ -143,9 +145,46 @@ func NetIfs(onlyPrefix []string) ([]*NetIf, error) {
netIf.OutPercent = float64(netIf.OutBytes*BITS_PER_BYTE) * 100.0 / float64(netIf.SpeedBits)
}
} else {
netIf.SpeedBits = int64(0)
netIf.InPercent = float64(0)
netIf.OutPercent = float64(0)
if content, err := sys.CmdOutBytes("ethtool", netIf.Iface); err == nil {
var speed int64
var speedStr string

contentReader := bufio.NewReader(bytes.NewBuffer(content))
for {
line, err := file.ReadLine(contentReader)

if err == io.EOF {
err = nil
break
}

if err != nil {
break
}

line = bytes.Trim(line, "\t")

if bytes.HasPrefix(line, []byte("Speed:")) && bytes.HasSuffix(line, []byte("Mb/s")) {
speedStr = string(line[7 : len(line)-4])
break
}
}

speed, err = strconv.ParseInt(strings.TrimSpace(speedStr), 10, 64)
if speedStr == "" || err != nil || speed == 0 {
netIf.SpeedBits = int64(0)
netIf.InPercent = float64(0)
netIf.OutPercent = float64(0)
} else {
netIf.SpeedBits = speed * MILLION_BIT
netIf.InPercent = float64(netIf.InBytes*BITS_PER_BYTE) * 100.0 / float64(netIf.SpeedBits)
netIf.OutPercent = float64(netIf.OutBytes*BITS_PER_BYTE) * 100.0 / float64(netIf.SpeedBits)
}
} else {
netIf.SpeedBits = int64(0)
netIf.InPercent = float64(0)
netIf.OutPercent = float64(0)
}
}

ret = append(ret, &netIf)
Expand Down

0 comments on commit 7494d04

Please sign in to comment.