python-esmonitor/pymonitor/monitors/procs.py

79 lines
1.9 KiB
Python
Raw Normal View History

2018-10-04 18:50:34 -07:00
from pymonitor import Metric
2015-12-05 16:46:45 -08:00
from glob import glob
import re
2017-05-15 17:29:20 -07:00
2015-12-05 16:46:45 -08:00
KTHREADD_PID = 2
PAT_REMOVE_PROC_SPACES = re.compile(r'(\([^\)]+\))')
2015-12-05 16:46:45 -08:00
2017-05-15 17:29:20 -07:00
2015-12-05 16:46:45 -08:00
def procs():
# Get uid->name mapping
users = {}
with open('/etc/passwd', 'r') as passwd:
while True:
line = passwd.readline()
if not line:
break
2017-05-15 17:29:20 -07:00
uname, _, uid, gid, opts, home, shell = line.split(":")
users[int(uid)] = uname
2015-12-05 16:46:45 -08:00
# Get gid->groupname mapping
groups = {}
with open('/etc/group', 'r') as group:
while True:
line = group.readline()
if not line:
break
2017-05-15 17:29:20 -07:00
gname, _, gid, y = line.split(":")
groups[int(gid)] = gname
2015-12-05 16:46:45 -08:00
num_procs = 0
num_threads = 0
num_kthreads = 0
2017-05-15 17:29:20 -07:00
2015-12-05 16:46:45 -08:00
for f in glob('/proc/[0-9]*/stat'):
try:
with open(f, "r") as statfile:
2015-12-06 15:36:58 -08:00
# Read stat info
stat = statfile.read().strip()
# Fix spaces in process names
stat = PAT_REMOVE_PROC_SPACES.sub("PROCNAME", stat)
stat = stat.split(" ")
2017-05-15 17:29:20 -07:00
2015-12-06 15:36:58 -08:00
proc_parent = int(stat[3])
2017-05-15 17:29:20 -07:00
2015-12-06 15:36:58 -08:00
if proc_parent == KTHREADD_PID:
2017-05-15 17:29:20 -07:00
num_kthreads += 1
2015-12-06 15:36:58 -08:00
else:
2017-05-15 17:29:20 -07:00
num_procs += 1
2015-12-06 15:36:58 -08:00
num_threads += int(stat[19])
2017-05-15 17:29:20 -07:00
2015-12-05 16:46:45 -08:00
except Exception as e:
print(e)
print("Failed to open %s" % f)
2017-05-15 17:29:20 -07:00
2018-10-04 18:50:34 -07:00
yield Metric({"procs": num_procs, "threads": num_threads, "kthreads": num_kthreads})
2017-05-15 17:29:20 -07:00
2015-12-05 16:46:45 -08:00
mapping = {
"procs": {
"properties": {
"procs": {
"type": "integer"
},
"threads": {
"type": "integer"
},
"kthreads": {
"type": "integer"
}
}
}
}
2017-05-15 17:29:20 -07:00
2015-12-05 16:46:45 -08:00
if __name__ == '__main__':
2016-01-28 22:18:56 -08:00
for item in procs():
print(item)