forked from cloudradar-monitoring/cagent
/
processes_notwindows.go
418 lines (357 loc) · 11.3 KB
/
processes_notwindows.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
// +build !windows
package processes
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"syscall"
"time"
"github.com/shirou/gopsutil/process"
"github.com/4S7xfPcbp1Hfayz/cagent/pkg/common"
"github.com/4S7xfPcbp1Hfayz/cagent/pkg/monitoring/docker"
)
var errorProcessTerminated = fmt.Errorf("Process was terminated")
type procStatus struct {
PPID int
State string
}
var dockerContainerIDRE = regexp.MustCompile(`(?m)/docker/([a-f0-9]*)$`)
var monitoredProcessCache = make(map[int]*process.Process)
func processes(systemMemorySize uint64) ([]*ProcStat, error) {
if runtime.GOOS == "linux" {
return processesFromProc(systemMemorySize)
}
return processesFromPS(systemMemorySize)
}
func getProcLongState(shortState byte) string {
switch shortState {
case 'R':
return "running"
case 'S':
return "sleeping"
case 'D':
return "blocked"
case 'Z':
return "zombie"
case 'X':
return "dead"
case 'T', 't':
return "stopped"
case 'W':
return "paging"
case 'I':
return "idle"
default:
return fmt.Sprintf("unknown(%s)", string(shortState))
}
}
// get process states from /proc/(pid)/stat
func processesFromProc(systemMemorySize uint64) ([]*ProcStat, error) {
filepaths, err := filepath.Glob(common.HostProc() + "/[0-9]*/status")
if err != nil {
return nil, err
}
var procs []*ProcStat
var updatedProcessCache = make(map[int]*process.Process)
for _, statusFilepath := range filepaths {
statusFile, err := readProcFile(statusFilepath)
if err != nil {
if err != errorProcessTerminated {
log.WithError(err).Error("readProcFile error")
}
continue
}
parsedProcStatus := parseProcStatusFile(statusFile)
stat := &ProcStat{ParentPID: parsedProcStatus.PPID, State: parsedProcStatus.State}
// get the PID from the filepath(/proc/<pid>/status) itself
pathParts := strings.Split(statusFilepath, string(filepath.Separator))
pidString := pathParts[len(pathParts)-2]
stat.PID, err = strconv.Atoi(pidString)
if err != nil {
log.WithError(err).Errorf("proc/status: failed to convert PID(%s) to int", pidString)
}
commFilepath := common.HostProc() + "/" + pidString + "/comm"
comm, err := readProcFile(commFilepath)
if err != nil && err != errorProcessTerminated {
log.WithError(err).Errorf("failed to read comm(%s)", commFilepath)
} else if err == nil {
stat.Name = string(bytes.TrimRight(comm, "\n"))
}
cmdLineFilepath := common.HostProc() + "/" + pidString + "/cmdline"
cmdline, err := readProcFile(cmdLineFilepath)
if err != nil && err != errorProcessTerminated {
log.WithError(err).Errorf("failed to read cmdline(%s)", cmdLineFilepath)
} else if err == nil {
stat.Cmdline = strings.Replace(string(bytes.TrimRight(cmdline, "\x00")), "\x00", " ", -1)
}
cgroupFilepath := common.HostProc() + "/" + pidString + "/cgroup"
cgroup, err := readProcFile(cgroupFilepath)
if err != nil && err != errorProcessTerminated {
log.WithError(err).Errorf("failed to read cgroup(%s)", cgroupFilepath)
} else if err == nil {
reParts := dockerContainerIDRE.FindStringSubmatch(string(cgroup))
if len(reParts) > 0 {
containerID := reParts[1]
containerName, err := docker.ContainerNameByID(containerID)
if err != nil {
if err != docker.ErrorNotImplementedForOS && err != docker.ErrorDockerNotAvailable {
log.WithError(err).Errorf("failed to read docker container name by id(%s)", containerID)
}
} else {
stat.Container = containerName
}
}
}
statFilepath := common.HostProc() + "/" + pidString + "/stat"
statFileContent, err := readProcFile(statFilepath)
if err != nil && err != errorProcessTerminated {
log.WithError(err).Errorf("failed to read stat (%s)", statFilepath)
} else if err == nil {
stat.ProcessGID = parseProcessGroupIDFromStatFile(statFileContent)
}
if stat.PID > 0 {
p := getProcessByPID(stat.PID)
stat.RSS, stat.VMS, stat.MemoryUsagePercent, stat.CPUAverageUsagePercent = gatherProcessResourceUsage(p, systemMemorySize)
updatedProcessCache[stat.PID] = p
}
procs = append(procs, stat)
}
monitoredProcessCache = updatedProcessCache
return procs, nil
}
func parseProcStatusFile(b []byte) procStatus {
// fill default value
// we need non-zero values in order to check if we set them, because PPID can be 0
status := procStatus{
PPID: -1,
}
scanner := bufio.NewScanner(bytes.NewReader(b))
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
switch strings.ToLower(fields[0]) {
case "ppid:":
var err error
status.PPID, err = strconv.Atoi(fields[1])
if err != nil {
log.WithError(err).Errorf("proc/status: failed to convert PPID(%s) to int", fields[1])
}
case "state:":
// extract raw long state
// eg "State: S (sleeping)"
if len(fields) >= 3 {
status.State = strings.ToLower(strings.Trim(fields[2], "()"))
break
}
if len(fields) < 2 {
break
}
// determine long state from the short one in case long one is not available
// eg "State: S"
status.State = getProcLongState(fields[1][0])
}
if status.PPID >= 0 && status.State != "" {
// we found all fields we want to
// we can break and return
break
}
}
return status
}
func parseProcessGroupIDFromStatFile(b []byte) int {
statFields := procPidStatSplit(string(b))
resultStr := statFields[4]
if resultStr == "" {
log.Warnf("proc/stat: could not parse stat file: %s", string(b))
return -1
}
pgrp, err := strconv.ParseInt(resultStr, 10, 32)
if err != nil {
log.WithError(err).Warnf("proc/stat: failed to convert PGRP (%s) to int. Stat file: %s", resultStr, string(b))
return -1
}
return int(pgrp)
}
// procPidStatSplit tries to parse /proc/<pid>/stat file
// from uber-archive/cpustat
// You might think that we could split on space, but due to what can at best be called
// a shortcoming of the /proc/pid/stat format, the comm field can have unescaped spaces, parens, etc.
// This may be a bit paranoid, because even many common tools like htop do not handle this case well.
func procPidStatSplit(b string) []string {
line := strings.TrimSpace(b)
var splitParts = make([]string, 52)
partnum := 0
strpos := 0
start := 0
inword := false
space := " "[0]
openParen := "("[0]
closeParen := ")"[0]
groupchar := space
for ; strpos < len(line); strpos++ {
if inword {
if line[strpos] == space && (groupchar == space || line[strpos-1] == groupchar) {
splitParts[partnum] = line[start:strpos]
partnum++
start = strpos
inword = false
}
} else {
if line[strpos] == openParen {
groupchar = closeParen
inword = true
start = strpos
strpos = strings.LastIndex(line, ")") - 1
if strpos <= start { // if we can't parse this insane field, skip to the end
strpos = len(line)
inword = false
}
} else if line[strpos] != space {
groupchar = space
inword = true
start = strpos
}
}
}
if inword {
splitParts[partnum] = line[start:strpos]
partnum++
}
for ; partnum < 52; partnum++ {
splitParts[partnum] = ""
}
return splitParts
}
func readProcFile(filename string) ([]byte, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
// if file doesn't exists it means that process was closed after we got the directory listing
if os.IsNotExist(err) {
return nil, errorProcessTerminated
}
// Reading from /proc/<PID> fails with ESRCH if the process has
// been terminated between open() and read().
if perr, ok := err.(*os.PathError); ok && perr.Err == syscall.ESRCH {
return nil, errorProcessTerminated
}
return nil, err
}
return data, nil
}
func execPS() ([]byte, error) {
bin, err := exec.LookPath("ps")
if err != nil {
return nil, err
}
out, _ := exec.Command(bin, "axwwo", "pid,ppid,pgrp,state,command").Output()
return out, nil
}
func processesFromPS(systemMemorySize uint64) ([]*ProcStat, error) {
out, err := execPS()
if err != nil {
return nil, err
}
lines := strings.Split(string(out), "\n")
var procs []*ProcStat
var updatedProcessCache = make(map[int]*process.Process)
var columnsIndex = map[string]int{}
for i, line := range lines {
parts := strings.Fields(line)
if i == 0 {
// parse the header
for colIndex, colName := range parts {
columnsIndex[strings.ToUpper(colName)] = colIndex
}
continue
}
if len(parts) < 3 {
continue
}
stat := &ProcStat{}
if pidIndex, exists := columnsIndex["PID"]; exists {
pidString := parts[pidIndex]
stat.PID, err = strconv.Atoi(pidString)
if err != nil {
log.WithError(err).Errorf("ps: failed to convert PID(%s) to int", pidString)
}
} else {
// we can't set PID set to default 0 if it is unavailable for some reason, because 0 PID means the kernel(Swapper) process
stat.PID = -1
}
if ppidIndex, exists := columnsIndex["PPID"]; exists {
ppidString := parts[ppidIndex]
stat.ParentPID, err = strconv.Atoi(ppidString)
if err != nil {
log.WithError(err).Errorf("ps: failed to convert PPID(%s) to int", ppidString)
}
} else {
// we can't left ParentPID set to default 0 if it is unavailable for some reason, because 0 PID means the kernel task process
stat.ParentPID = -1
}
if pgidIndex, exists := columnsIndex["PGRP"]; exists {
pgidString := parts[pgidIndex]
stat.ProcessGID, err = strconv.Atoi(pgidString)
if err != nil {
log.WithError(err).Errorf("ps: failed to convert PGID(%s) to int", pgidString)
}
} else {
// we can't left ProcessGID set to default 0 if it is unavailable for some reason, because 0 PGID means the kernel task group
stat.ProcessGID = -1
}
if statIndex, exists := columnsIndex["STAT"]; exists {
stat.State = getProcLongState(parts[statIndex][0])
}
// COMMAND must be the last column otherwise we can't parse it because it can contains spaces
if commandIndex, exists := columnsIndex["COMMAND"]; exists && commandIndex == (len(columnsIndex)-1) {
stat.Cmdline = strings.Join(parts[commandIndex:], " ")
// extract the executable name without the arguments
fileBaseWithArgs := filepath.Base(stat.Cmdline)
fileBaseParts := strings.Fields(fileBaseWithArgs)
stat.Name = fileBaseParts[0]
}
if stat.PID > 0 {
p := getProcessByPID(stat.PID)
stat.RSS, stat.VMS, stat.MemoryUsagePercent, stat.CPUAverageUsagePercent = gatherProcessResourceUsage(p, systemMemorySize)
updatedProcessCache[stat.PID] = p
}
procs = append(procs, stat)
}
monitoredProcessCache = updatedProcessCache
return procs, nil
}
func getProcessByPID(pid int) *process.Process {
p, exists := monitoredProcessCache[pid]
if !exists {
p = &process.Process{
Pid: int32(pid),
}
}
return p
}
func gatherProcessResourceUsage(proc *process.Process, systemMemorySize uint64) (uint64, uint64, float32, float32) {
memoryInfo, err := proc.MemoryInfo()
if err != nil {
log.WithError(err).Error("failed to get memory info")
return 0, 0, 0.0, 0.0
}
memUsagePercent := 0.0
if systemMemorySize > 0 {
memUsagePercent = (float64(memoryInfo.RSS) / float64(systemMemorySize)) * 100
}
// side effect: p.Percent() call update process internally
cpuUsagePercent, err := proc.Percent(time.Duration(0))
if err != nil {
log.WithError(err).Error("failed to get CPU usage")
}
return memoryInfo.RSS, memoryInfo.VMS, float32(common.RoundToTwoDecimalPlaces(memUsagePercent)), float32(common.RoundToTwoDecimalPlaces(cpuUsagePercent))
}
func isKernelTask(procStat *ProcStat) bool {
return procStat.ParentPID == 0 || procStat.ProcessGID == 0
}