-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathi_processes.go
93 lines (78 loc) · 2.07 KB
/
i_processes.go
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package main
import (
"log"
"os/exec"
"strings"
)
type Processes struct {
}
func (p *Processes) Description() string {
return "Get the number of processes and group them by status"
}
func (p *Processes) SampleConfig() string { return "" }
func (p *Processes) Gather(acc Accumulator) error {
// Get an empty map of metric fields
fields := getEmptyFields()
if err := p.gatherFromPS(fields); err != nil {
return err
}
acc.AddFields("processes", fields, nil)
return nil
}
// TODO: total_threads needs to be implemented
// Gets empty fields of metrics based on the OS
func getEmptyFields() map[string]interface{} {
fields := map[string]interface{}{
"blocked": int64(0),
"zombies": int64(0),
"stopped": int64(0),
"running": int64(0),
"sleeping": int64(0),
"total": int64(0),
"unknown": int64(0),
"total_threads": int64(0),
"wait": int64(0),
}
return fields
}
// exec `ps` to get all process states
func (p *Processes) gatherFromPS(fields map[string]interface{}) error {
out, err := execPS()
if err != nil {
return err
}
rows := strings.Split(string(out), "\n")
for _, line := range rows[1:len(rows)-1] {
stats := strings.Fields(line)
switch stats[1] {
case "W":
fields["wait"] = fields["wait"].(int64) + int64(1)
case "Z":
fields["zombies"] = fields["zombies"].(int64) + int64(1)
case "X":
fields["dead"] = fields["dead"].(int64) + int64(1)
case "T":
fields["stopped"] = fields["stopped"].(int64) + int64(1)
case "O":
fields["running"] = fields["running"].(int64) + int64(1)
case "S":
fields["sleeping"] = fields["sleeping"].(int64) + int64(1)
case "I":
fields["idle"] = fields["idle"].(int64) + int64(1)
case "?":
fields["unknown"] = fields["unknown"].(int64) + int64(1)
default:
log.Printf("I! processes: Unknown state [ %s ] from ps",
string(stats[1]))
}
fields["total"] = fields["total"].(int64) + int64(1)
}
return nil
}
func execPS() ([]byte, error) {
out, err := exec.Command("ps", "-el").Output()
if err != nil {
return nil, err
}
return out, err
}