Adding pgrep user support

This commit is contained in:
Aurélien DEHAY 2016-02-19 19:25:17 +01:00
parent 3179829fa5
commit 7a8f0bee47
1 changed files with 31 additions and 2 deletions

View File

@ -19,6 +19,7 @@ type Procstat struct {
Exe string Exe string
Pattern string Pattern string
Prefix string Prefix string
User string
pidmap map[int32]*process.Process pidmap map[int32]*process.Process
} }
@ -37,6 +38,8 @@ var sampleConfig = `
# exe = "nginx" # exe = "nginx"
## pattern as argument for pgrep (ie, pgrep -f <pattern>) ## pattern as argument for pgrep (ie, pgrep -f <pattern>)
# pattern = "nginx" # pattern = "nginx"
## user as argument for pgrep (ie, pgrep -u <user>)
# user = "nginx"
## Field name prefix ## Field name prefix
prefix = "" prefix = ""
@ -53,8 +56,8 @@ func (_ *Procstat) Description() string {
func (p *Procstat) Gather(acc telegraf.Accumulator) error { func (p *Procstat) Gather(acc telegraf.Accumulator) error {
err := p.createProcesses() err := p.createProcesses()
if err != nil { if err != nil {
log.Printf("Error: procstat getting process, exe: [%s] pidfile: [%s] pattern: [%s] %s", log.Printf("Error: procstat getting process, exe: [%s] pidfile: [%s] pattern: [%s] user: [%s] %s",
p.Exe, p.PidFile, p.Pattern, err.Error()) p.Exe, p.PidFile, p.Pattern, p.User, err.Error())
} else { } else {
for _, proc := range p.pidmap { for _, proc := range p.pidmap {
p := NewSpecProcessor(p.Prefix, acc, proc) p := NewSpecProcessor(p.Prefix, acc, proc)
@ -103,6 +106,8 @@ func (p *Procstat) getAllPids() ([]int32, error) {
pids, err = pidsFromExe(p.Exe) pids, err = pidsFromExe(p.Exe)
} else if p.Pattern != "" { } else if p.Pattern != "" {
pids, err = pidsFromPattern(p.Pattern) pids, err = pidsFromPattern(p.Pattern)
} else if p.User != "" {
pids, err = pidsFromUser(p.User)
} else { } else {
err = fmt.Errorf("Either exe, pid_file or pattern has to be specified") err = fmt.Errorf("Either exe, pid_file or pattern has to be specified")
} }
@ -175,6 +180,30 @@ func pidsFromPattern(pattern string) ([]int32, error) {
return out, outerr return out, outerr
} }
func pidsFromUser(user string) ([]int32, error) {
var out []int32
var outerr error
bin, err := exec.LookPath("pgrep")
if err != nil {
return out, fmt.Errorf("Couldn't find pgrep binary: %s", err)
}
pgrep, err := exec.Command(bin, "-u", user).Output()
if err != nil {
return out, fmt.Errorf("Failed to execute %s. Error: '%s'", bin, err)
} else {
pids := strings.Fields(string(pgrep))
for _, pid := range pids {
ipid, err := strconv.Atoi(pid)
if err == nil {
out = append(out, int32(ipid))
} else {
outerr = err
}
}
}
return out, outerr
}
func init() { func init() {
inputs.Add("procstat", func() telegraf.Input { inputs.Add("procstat", func() telegraf.Input {
return NewProcstat() return NewProcstat()