blob: f7c2d206fea91e032f20a2126594f756aaa351c3 [file] [log] [blame]
Ved-vampirf2e13832015-03-17 13:24:18 +03001import os
Ved-vampirf2e13832015-03-17 13:24:18 +03002
3from discover import provides
4from utils import SensorInfo, get_pid_name, get_pid_list
5
6
7
8@provides("perprocess-cpu")
9def pscpu_stat(disallowed_prefixes=None, allowed_prefixes=None):
10 results = {}
Ved-vampirf2e13832015-03-17 13:24:18 +030011 pid_list = get_pid_list(disallowed_prefixes, allowed_prefixes)
12
13 for pid in pid_list:
14 try:
Ved-vampirf2e13832015-03-17 13:24:18 +030015 dev_name = get_pid_name(pid)
16
17 pid_stat1 = pid_stat(pid)
Ved-vampirf2e13832015-03-17 13:24:18 +030018
19 sensor_name = "{0}.{1}".format(dev_name, pid)
Ved-vampirbb783a12015-03-18 11:21:48 +030020 results[sensor_name] = SensorInfo(pid_stat1, True)
Ved-vampirf2e13832015-03-17 13:24:18 +030021 except IOError:
Ved-vampirbb783a12015-03-18 11:21:48 +030022 # may be, proc has already terminated, skip it
Ved-vampirf2e13832015-03-17 13:24:18 +030023 continue
24 return results
25
26
27def pid_stat(pid):
28 """ Return total cpu usage time from process"""
29 # read /proc/pid/stat
30 with open(os.path.join('/proc/', pid, 'stat'), 'r') as pidfile:
31 proctimes = pidfile.readline().split()
Ved-vampir0fc13672015-03-18 11:13:17 +030032 # get utime from /proc/<pid>/stat, 14 item
33 utime = proctimes[13]
34 # get stime from proc/<pid>/stat, 15 item
35 stime = proctimes[14]
36 # count total process used time
37 proctotal = int(utime) + int(stime)
38 return float(proctotal)