Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ProcState parsing for process names with parantheses #86

Merged
merged 2 commits into from
Nov 28, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).

### Changed
- OpenBSD returns `ErrNotImplemented` for `ProcTime.Get` instead of `nil`. #83
- Fixed `ProcState` on Linux and FreeBSD when process names contain parentheses. #81

### Deprecated

Expand Down
63 changes: 38 additions & 25 deletions sigar_linux_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ package gosigar
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
Expand Down Expand Up @@ -181,44 +180,58 @@ func (self *ProcList) Get() error {
}

func (self *ProcState) Get(pid int) error {
contents, err := readProcFile(pid, "stat")
data, err := readProcFile(pid, "stat")
if err != nil {
return err
}

headerAndStats := strings.SplitAfterN(string(contents), ")", 2)
pidAndName := headerAndStats[0]
fields := strings.Fields(headerAndStats[1])

name := strings.SplitAfterN(pidAndName, " ", 2)[1]
if name[0] == '(' && name[len(name)-1] == ')' {
self.Name = name[1 : len(name)-1] // strip ()'s
} else {
return errors.New(fmt.Sprintf("Malformed process stats for pid %d", pid))
// Extract the comm value with is surrounded by parentheses.
lIdx := bytes.Index(data, []byte("("))
rIdx := bytes.LastIndex(data, []byte(")"))
if lIdx < 0 || rIdx < 0 || lIdx >= rIdx || rIdx+2 >= len(data) {
return fmt.Errorf("failed to extract comm for pid %d from '%v'", pid, string(data))
}
self.Name = string(data[lIdx+1 : rIdx])

self.State = RunState(fields[0][0])

self.Ppid, _ = strconv.Atoi(fields[1])

self.Pgid, _ = strconv.Atoi(fields[2])

self.Tty, _ = strconv.Atoi(fields[4])

self.Priority, _ = strconv.Atoi(fields[15])

self.Nice, _ = strconv.Atoi(fields[16])
// Extract the rest of the fields that we are interested in.
fields := bytes.Fields(data[rIdx+2:])
if len(fields) <= 36 {
return fmt.Errorf("expected more stat fields for pid %d from '%v'", pid, string(data))
}

self.Processor, _ = strconv.Atoi(fields[36])
interests := bytes.Join([][]byte{
fields[0], // state
fields[1], // ppid
fields[2], // pgrp
fields[4], // tty_nr
fields[15], // priority
fields[16], // nice
fields[36], // processor (last processor executed on)
}, []byte(" "))

var state string
_, err = fmt.Fscan(bytes.NewBuffer(interests),
&state,
&self.Ppid,
&self.Pgid,
&self.Tty,
&self.Priority,
&self.Nice,
&self.Processor,
)
if err != nil {
return fmt.Errorf("failed to parse stat fields for pid %d from '%v': %v", pid, string(data), err)
}
self.State = RunState(state[0])

// Read /proc/[pid]/status to get the uid, then lookup uid to get username.
status, err := getProcStatus(pid)
if err != nil {
return fmt.Errorf("failed to read process status for pid %d. %v", pid, err)
return fmt.Errorf("failed to read process status for pid %d: %v", pid, err)
}
uids, err := getUIDs(status)
if err != nil {
return fmt.Errorf("failed to read process status for pid %d. %v", pid, err)
return fmt.Errorf("failed to read process status for pid %d: %v", pid, err)
}
user, err := user.LookupId(uids[0])
if err == nil {
Expand Down
20 changes: 16 additions & 4 deletions sigar_linux_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ func TestLinuxProcState(t *testing.T) {
var procNames = []string{
"cron",
"a very long process name",
"(sd-pam)",
"]",
"(",
}

for _, n := range procNames {
Expand All @@ -66,9 +69,18 @@ func TestLinuxProcState(t *testing.T) {

state := sigar.ProcState{}
if assert.NoError(t, state.Get(pid)) {
assert.Equal(t, n, state.Name)
assert.Equal(t, 2, state.Pgid)
assert.Equal(t, strconv.Itoa(uid), state.Username)
expected := sigar.ProcState{
Name: n,
Username: strconv.Itoa(uid),
State: 'S',
Ppid: 1,
Pgid: 2,
Tty: 4,
Priority: 15,
Nice: 16,
Processor: 36,
}
assert.Equal(t, expected, state)
}
}()
}
Expand Down Expand Up @@ -539,7 +551,7 @@ func writeFDs(pid int, count int) error {
}

func writePidStats(pid int, procName string, path string) error {
stats := "S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 " +
stats := "S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 " +
"20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 " +
"35 36 37 38 39"

Expand Down