From 777b751f9038547ee2367bf145603a8f44967145 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=A7=8B=E8=91=89?= Date: Mon, 8 Jul 2019 21:53:14 +0800 Subject: [PATCH] read /proc/net files with a single read syscall (#1380) Signed-off-by: Hanaasagi --- collector/tcpstat_linux.go | 22 ++++++++++------------ collector/tcpstat_linux_test.go | 2 +- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/collector/tcpstat_linux.go b/collector/tcpstat_linux.go index da652f97..cc4e960b 100644 --- a/collector/tcpstat_linux.go +++ b/collector/tcpstat_linux.go @@ -16,9 +16,9 @@ package collector import ( - "bufio" "fmt" "io" + "io/ioutil" "os" "strconv" "strings" @@ -108,23 +108,21 @@ func getTCPStats(statsFile string) (map[tcpConnectionState]float64, error) { } func parseTCPStats(r io.Reader) (map[tcpConnectionState]float64, error) { - var ( - tcpStats = map[tcpConnectionState]float64{} - scanner = bufio.NewScanner(r) - ) + tcpStats := map[tcpConnectionState]float64{} + contents, err := ioutil.ReadAll(r) + if err != nil { + return nil, err + } - for scanner.Scan() { - parts := strings.Fields(scanner.Text()) + for _, line := range strings.Split(string(contents), "\n")[1:] { + parts := strings.Fields(line) if len(parts) == 0 { continue } if len(parts) < 4 { - return nil, fmt.Errorf("invalid TCP stats line: %q", scanner.Text()) + return nil, fmt.Errorf("invalid TCP stats line: %q", line) } - if strings.HasPrefix(parts[0], "sl") { - continue - } st, err := strconv.ParseInt(parts[3], 16, 8) if err != nil { return nil, err @@ -133,7 +131,7 @@ func parseTCPStats(r io.Reader) (map[tcpConnectionState]float64, error) { tcpStats[tcpConnectionState(st)]++ } - return tcpStats, scanner.Err() + return tcpStats, nil } func (st tcpConnectionState) String() string { diff --git a/collector/tcpstat_linux_test.go b/collector/tcpstat_linux_test.go index ca9d9944..f4c3b36c 100644 --- a/collector/tcpstat_linux_test.go +++ b/collector/tcpstat_linux_test.go @@ -26,7 +26,7 @@ func Test_parseTCPStatsError(t *testing.T) { }{ { name: "too few fields", - in: "hello world", + in: "sl local_address\n 0: 00000000:0016", }, }