procstat plugin, consolidate PID-getting

This commit is contained in:
Cameron Sparr 2015-10-07 14:13:33 -06:00
parent 9221f93be9
commit d620651ef6
1 changed files with 30 additions and 20 deletions

View File

@ -54,7 +54,7 @@ func (p *Procstat) Gather(acc plugins.Accumulator) error {
defer wg.Done() defer wg.Done()
procs, err := spec.createProcesses() procs, err := spec.createProcesses()
if err != nil { if err != nil {
log.Printf("Error: procstat getting process, exe: %s, pidfile: %s, %s", log.Printf("Error: procstat getting process, exe: [%s] pidfile: [%s] %s",
spec.Exe, spec.PidFile, err.Error()) spec.Exe, spec.PidFile, err.Error())
} else { } else {
for _, proc := range procs { for _, proc := range procs {
@ -73,23 +73,10 @@ func (spec *Specification) createProcesses() ([]*process.Process, error) {
var out []*process.Process var out []*process.Process
var errstring string var errstring string
var outerr error var outerr error
var pids []int32
if spec.PidFile != "" { pids, err := spec.getAllPids()
pid, err := pidFromFile(spec.PidFile) if err != nil {
if err != nil { errstring += err.Error() + " "
errstring += err.Error() + " "
} else {
pids = append(pids, int32(pid))
}
} else if spec.Exe != "" {
exepids, err := pidsFromExe(spec.Exe)
if err != nil {
errstring += err.Error() + " "
}
pids = append(pids, exepids...)
} else {
errstring += fmt.Sprintf("Either exe or pid_file has to be specified")
} }
for _, pid := range pids { for _, pid := range pids {
@ -108,13 +95,36 @@ func (spec *Specification) createProcesses() ([]*process.Process, error) {
return out, outerr return out, outerr
} }
func pidFromFile(file string) (int, error) { func (spec *Specification) getAllPids() ([]int32, error) {
var pids []int32
var err error
if spec.PidFile != "" {
pids, err = pidsFromFile(spec.PidFile)
} else if spec.Exe != "" {
pids, err = pidsFromExe(spec.Exe)
} else {
err = fmt.Errorf("Either exe or pid_file has to be specified")
}
return pids, err
}
func pidsFromFile(file string) ([]int32, error) {
var out []int32
var outerr error
pidString, err := ioutil.ReadFile(file) pidString, err := ioutil.ReadFile(file)
if err != nil { if err != nil {
return -1, fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'", file, err) outerr = fmt.Errorf("Failed to read pidfile '%s'. Error: '%s'", file, err)
} else { } else {
return strconv.Atoi(strings.TrimSpace(string(pidString))) pid, err := strconv.Atoi(strings.TrimSpace(string(pidString)))
if err != nil {
outerr = err
} else {
out = append(out, int32(pid))
}
} }
return out, outerr
} }
func pidsFromExe(exe string) ([]int32, error) { func pidsFromExe(exe string) ([]int32, error) {