blob: ad08676f537d9acb86561c54cbd669166ae73b95 [file] [log] [blame]
Ved-vampirf2e13832015-03-17 13:24:18 +03001import os
2
koder aka kdanilovdda86d32015-03-16 11:20:04 +02003from collections import namedtuple
4
5SensorInfo = namedtuple("SensorInfo", ['value', 'is_accumulated'])
6
7
8def 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-vampirf2e13832015-03-17 13:24:18 +030022def 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):
Ved-vampir98a99172015-03-17 14:58:15 +030038 print name
Ved-vampirf2e13832015-03-17 13:24:18 +030039 # this is allowed pid?
40 result.append(pid)
41 return result
42
43
44def get_pid_name(pid):
45 """ Return name by pid """
46 try:
47 with open(os.path.join('/proc/', pid, 'cmdline'), 'r') as pidfile:
48 try:
49 cmd = pidfile.readline().split()[0]
50 return os.path.basename(cmd).rstrip('\x00')
51 except IndexError:
52 # no cmd returned
Ved-vampir0fc13672015-03-18 11:13:17 +030053 return "<NO NAME>"
Ved-vampirf2e13832015-03-17 13:24:18 +030054 except IOError:
Ved-vampirbb783a12015-03-18 11:21:48 +030055 # upstream wait any string, no matter if we couldn't read proc
Ved-vampirf2e13832015-03-17 13:24:18 +030056 return "no_such_process"
57
58
koder aka kdanilovdda86d32015-03-16 11:20:04 +020059def delta(func, only_upd=True):
60 prev = {}
61 while True:
62 for dev_name, vals in func():
63 if dev_name not in prev:
64 prev[dev_name] = {}
65 for name, (val, _) in vals.items():
66 prev[dev_name][name] = val
67 else:
68 dev_prev = prev[dev_name]
69 res = {}
70 for stat_name, (val, accum_val) in vals.items():
71 if accum_val:
72 if stat_name in dev_prev:
73 delta = int(val) - int(dev_prev[stat_name])
74 if not only_upd or 0 != delta:
75 res[stat_name] = str(delta)
76 dev_prev[stat_name] = val
77 elif not only_upd or '0' != val:
78 res[stat_name] = val
79
80 if only_upd and len(res) == 0:
81 continue
82 yield dev_name, res
83 yield None, None