Ved-vampir | f2e1383 | 2015-03-17 13:24:18 +0300 | [diff] [blame^] | 1 | import os |
| 2 | |
koder aka kdanilov | dda86d3 | 2015-03-16 11:20:04 +0200 | [diff] [blame] | 3 | from collections import namedtuple |
| 4 | |
| 5 | SensorInfo = namedtuple("SensorInfo", ['value', 'is_accumulated']) |
| 6 | |
| 7 | |
| 8 | def is_dev_accepted(name, disallowed_prefixes, allowed_prefixes): |
| 9 | dev_ok = True |
| 10 | |
| 11 | if disallowed_prefixes is not None: |
| 12 | dev_ok = all(not name.startswith(prefix) |
| 13 | for prefix in disallowed_prefixes) |
| 14 | |
| 15 | if dev_ok and allowed_prefixes is not None: |
| 16 | dev_ok = any(name.startswith(prefix) |
| 17 | for prefix in allowed_prefixes) |
| 18 | |
| 19 | return dev_ok |
| 20 | |
| 21 | |
Ved-vampir | f2e1383 | 2015-03-17 13:24:18 +0300 | [diff] [blame^] | 22 | def get_pid_list(disallowed_prefixes, allowed_prefixes): |
| 23 | """ Return pid list from list of pids and names """ |
| 24 | # exceptions |
| 25 | but = disallowed_prefixes if disallowed_prefixes is not None else [] |
| 26 | if allowed_prefixes is None: |
| 27 | # if nothing setted - all ps will be returned except setted |
| 28 | result = [pid |
| 29 | for pid in os.listdir('/proc') |
| 30 | if pid.isdigit() and pid not in but] |
| 31 | else: |
| 32 | result = [] |
| 33 | for pid in os.listdir('/proc'): |
| 34 | if pid.isdigit() and pid not in but: |
| 35 | name = get_pid_name(pid) |
| 36 | if pid in allowed_prefixes or \ |
| 37 | any(name.startswith(val) for val in allowed_prefixes): |
| 38 | # this is allowed pid? |
| 39 | result.append(pid) |
| 40 | return result |
| 41 | |
| 42 | |
| 43 | def get_pid_name(pid): |
| 44 | """ Return name by pid """ |
| 45 | try: |
| 46 | with open(os.path.join('/proc/', pid, 'cmdline'), 'r') as pidfile: |
| 47 | try: |
| 48 | cmd = pidfile.readline().split()[0] |
| 49 | return os.path.basename(cmd).rstrip('\x00') |
| 50 | except IndexError: |
| 51 | # no cmd returned |
| 52 | return "no_name" |
| 53 | except IOError: |
| 54 | return "no_such_process" |
| 55 | |
| 56 | |
koder aka kdanilov | dda86d3 | 2015-03-16 11:20:04 +0200 | [diff] [blame] | 57 | def delta(func, only_upd=True): |
| 58 | prev = {} |
| 59 | while True: |
| 60 | for dev_name, vals in func(): |
| 61 | if dev_name not in prev: |
| 62 | prev[dev_name] = {} |
| 63 | for name, (val, _) in vals.items(): |
| 64 | prev[dev_name][name] = val |
| 65 | else: |
| 66 | dev_prev = prev[dev_name] |
| 67 | res = {} |
| 68 | for stat_name, (val, accum_val) in vals.items(): |
| 69 | if accum_val: |
| 70 | if stat_name in dev_prev: |
| 71 | delta = int(val) - int(dev_prev[stat_name]) |
| 72 | if not only_upd or 0 != delta: |
| 73 | res[stat_name] = str(delta) |
| 74 | dev_prev[stat_name] = val |
| 75 | elif not only_upd or '0' != val: |
| 76 | res[stat_name] = val |
| 77 | |
| 78 | if only_upd and len(res) == 0: |
| 79 | continue |
| 80 | yield dev_name, res |
| 81 | yield None, None |