blob: 546dee76c7e23151f56e110055b09915ed7b5745 [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
53 return "no_name"
54 except IOError:
55 return "no_such_process"
56
57
koder aka kdanilovdda86d32015-03-16 11:20:04 +020058def delta(func, only_upd=True):
59 prev = {}
60 while True:
61 for dev_name, vals in func():
62 if dev_name not in prev:
63 prev[dev_name] = {}
64 for name, (val, _) in vals.items():
65 prev[dev_name][name] = val
66 else:
67 dev_prev = prev[dev_name]
68 res = {}
69 for stat_name, (val, accum_val) in vals.items():
70 if accum_val:
71 if stat_name in dev_prev:
72 delta = int(val) - int(dev_prev[stat_name])
73 if not only_upd or 0 != delta:
74 res[stat_name] = str(delta)
75 dev_prev[stat_name] = val
76 elif not only_upd or '0' != val:
77 res[stat_name] = val
78
79 if only_upd and len(res) == 0:
80 continue
81 yield dev_name, res
82 yield None, None