implement aggregator stub
[bwmon.git] / bwmon / aggregator.py
blob7a8080c99aeb64f2270313b9d68a2fa618f04eec
1 from subprocess import Popen, PIPE
2 from datetime import datetime
3 import re
4 import collections
7 class Aggregator():
9 def __init__(self, args):
10 self.args = args
12 def run(self):
13 line_regex = re.compile('\s*(?P<in>\d+)\s*/\s*(?P<out>\d+)\s*--\s*(?P<proc>.*)')
15 proc = Popen(self.args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=1)
16 records = collections.defaultdict(list)
18 for line in proc.stdout:
20 record = self.get_record(line)
22 if not record:
23 continue
25 records[process].append(record)
27 if len(records[process]) > 1:
28 prev_record = records[process][-2]
29 bw = self.get_bandwidth(prev_record, record)
30 # process bandwidth
33 def get_record(line):
34 match = line_regex.match(line)
36 if not match:
37 return None
39 process = match.group('proc').strip()
40 bytes_in = int(match.group('in'))
41 bytes_out = int(match.group('out'))
42 record = {'timestamp': datetime.now(), 'in': bytes_in, 'out': bytes_out}
45 def get_bandwidth(rec1, rec2):
46 """
47 returns the mean incoming and outgoing bandwidth used between
48 the two given records.
50 rec1 represents the earlier, rec2 the later record
51 """
52 date_diff = rec2['timestamp'] - rec1['timestamp']
53 in_diff = rec2['in'] - rec1['diff']
54 out_diff = rec2['out'] - rec1['out']
56 in_bw = in_diff / date_diff.seconds
57 out_bw = out_diff / date_diff.seconds
59 return (in_bw, out_bw)