From 3a8a09a60675db42dba05830f8e14f4e88c3887e Mon Sep 17 00:00:00 2001 From: Alban Crequy Date: Tue, 25 Apr 2017 12:05:29 +0200 Subject: [PATCH] proc walker: optimize readLimits --- probe/process/walker_linux.go | 35 ++++++++++++++++++++---------- probe/process/walker_linux_test.go | 2 +- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/probe/process/walker_linux.go b/probe/process/walker_linux.go index a28ea9e66..4e9e2a9aa 100644 --- a/probe/process/walker_linux.go +++ b/probe/process/walker_linux.go @@ -2,7 +2,6 @@ package process import ( "bytes" - "fmt" "os" "path" "strconv" @@ -99,17 +98,31 @@ func readLimits(path string) (openFilesLimit uint64, err error) { if err != nil { return 0, err } - for _, line := range strings.Split(string(buf), "\n") { - if strings.HasPrefix(line, "Max open files") { - splits := strings.Fields(line) - if len(splits) < 6 { - return 0, fmt.Errorf("Invalid /proc/PID/limits") - } - openFilesLimit, err := strconv.Atoi(splits[3]) - return uint64(openFilesLimit), err - } + content := string(buf) + + // File format: one line header + one line per limit + // + // Limit Soft Limit Hard Limit Units + // ... + // Max open files 1024 4096 files + // ... + delim := "\nMax open files" + pos := strings.Index(content, delim) + + if pos < 0 { + // Tests such as TestWalker can synthetise empty files + return 0, nil } - return 0, nil + pos += len(delim) + + for pos < len(content) && content[pos] == ' ' { + pos++ + } + + var softLimit uint64 + softLimit = parseUint64WithSpaces(&buf, &pos) + + return softLimit, nil } // Walk walks the supplied directory (expecting it to look like /proc) diff --git a/probe/process/walker_linux_test.go b/probe/process/walker_linux_test.go index 68912aed0..1da50deb7 100644 --- a/probe/process/walker_linux_test.go +++ b/probe/process/walker_linux_test.go @@ -23,7 +23,7 @@ var mockFS = fs.Dir("", }, fs.File{ FName: "limits", - FContents: `Max open files 32768 65536 files`, + FContents: "Limit Soft-Limit Hard-Limit Units\nMax open files 32768 65536 files", }, fs.Dir("fd", fs.File{FName: "0"}, fs.File{FName: "1"}, fs.File{FName: "2"}), ),