forked from dynport/metrix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocesses.go
101 lines (89 loc) · 1.91 KB
/
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
94
95
96
97
98
99
100
101
package main
import (
"io/ioutil"
"os"
"regexp"
"strconv"
"strings"
)
const PROCESSES = "processes"
func init() {
parser.Add(PROCESSES, "true", "Collect metrics for processes")
}
var procStatsMapping = map[int]string{
13: "Utime",
14: "Stime",
15: "Cutime",
16: "Sctime",
17: "Priority",
18: "Nice",
19: "NumThreads",
20: "Itrealvalue",
21: "Starttime",
22: "Vsize",
23: "RSS",
24: "RSSlim",
27: "Startstac",
42: "GuestTime",
43: "CguestTime",
}
type Processes struct {
}
func (self *Processes) Prefix() string {
return "processes"
}
var matchBrackets = regexp.MustCompile("(^\\(|\\)$)")
func NormalizeProcessName(comm string) string {
withoutBrackes := matchBrackets.ReplaceAllString(comm, "")
return strings.Split(withoutBrackes, "/")[0]
}
var matchNums = regexp.MustCompile("[0-9]+")
func generateProcfiles() (matches chan string, e error) {
procmount := ProcRoot() + "/proc"
d, e := os.Open(procmount)
if e != nil {
return nil, e
}
matches = make(chan string, 100)
go func(dir *os.File) {
for e := error(nil); e == error(nil); {
names, e := dir.Readdirnames(100)
if e != nil {
break
}
for _, name := range names {
if matchNums.MatchString(name) {
matches <- procmount + "/" + name + "/stat"
}
}
}
close(matches)
}(d)
return matches, nil
}
func (self *Processes) Collect(c *MetricsCollection) (e error) {
matches, e := generateProcfiles()
if e != nil {
return
}
for path := range matches {
if data, e := ioutil.ReadFile(path); e == nil {
chunks := strings.Split(string(data), " ")
tags := map[string]string{
"pid": chunks[0],
"ppid": chunks[3],
"comm": chunks[1],
"name": NormalizeProcessName(chunks[1]),
"state": chunks[2],
}
for idx, v := range chunks {
if i, e := strconv.ParseInt(v, 10, 64); e == nil {
if k, ok := procStatsMapping[idx]; ok {
c.AddWithTags(k, i, tags)
}
}
}
}
}
return
}