Ved-vampir | f2e1383 | 2015-03-17 13:24:18 +0300 | [diff] [blame] | 1 | import os |
| 2 | import time |
| 3 | |
| 4 | from discover import provides |
| 5 | from utils import SensorInfo, get_pid_name, get_pid_list |
| 6 | |
| 7 | |
| 8 | |
| 9 | @provides("perprocess-cpu") |
| 10 | def pscpu_stat(disallowed_prefixes=None, allowed_prefixes=None): |
| 11 | results = {} |
| 12 | pid_stat0 = {} |
| 13 | sys_stat0 = {} |
| 14 | pid_list = get_pid_list(disallowed_prefixes, allowed_prefixes) |
| 15 | |
| 16 | for pid in pid_list: |
| 17 | try: |
| 18 | pid_stat0[pid] = pid_stat(pid) |
| 19 | sys_stat0[pid] = sys_stat() |
| 20 | except IOError: |
| 21 | # may be, proc has already terminated |
| 22 | continue |
| 23 | |
| 24 | time.sleep(1) |
| 25 | |
| 26 | for pid in pid_list: |
| 27 | try: |
| 28 | dev_name = get_pid_name(pid) |
| 29 | |
| 30 | pid_stat1 = pid_stat(pid) |
| 31 | sys_stat1 = sys_stat() |
| 32 | cpu = (pid_stat1 - pid_stat0[pid]) / (sys_stat1 - sys_stat0[pid]) |
| 33 | |
| 34 | sensor_name = "{0}.{1}".format(dev_name, pid) |
| 35 | results[sensor_name] = SensorInfo(cpu*100, False) |
| 36 | except IOError: |
| 37 | # may be, proc has already terminated |
| 38 | continue |
| 39 | return results |
| 40 | |
| 41 | |
| 42 | def pid_stat(pid): |
| 43 | """ Return total cpu usage time from process""" |
| 44 | # read /proc/pid/stat |
| 45 | with open(os.path.join('/proc/', pid, 'stat'), 'r') as pidfile: |
| 46 | proctimes = pidfile.readline().split() |
| 47 | # get utime from /proc/<pid>/stat, 14 item |
| 48 | utime = proctimes[13] |
| 49 | # get stime from proc/<pid>/stat, 15 item |
| 50 | stime = proctimes[14] |
| 51 | # count total process used time |
| 52 | proctotal = int(utime) + int(stime) |
| 53 | return float(proctotal) |
| 54 | |
| 55 | |
| 56 | def sys_stat(): |
| 57 | """ Return total system cpu usage time""" |
| 58 | with open('/proc/stat', 'r') as procfile: |
| 59 | cputimes = procfile.readline().split()[1:] |
| 60 | cputotal = 0 |
| 61 | # count from /proc/stat sum |
| 62 | for i in cputimes: |
| 63 | cputotal = cputotal + int(i) |
| 64 | return float(cputotal) |