move pre-compiled regex to correct method
[bwmon.git] / bwmon / __init__.py
blob4adc1083b4e4cc215abedd7b121c32f82f833368
1 # -*- coding: utf-8 -*-
3 from __future__ import absolute_import
5 from bwmon import proc
7 import collections
8 import time
9 import sys
10 import curses
11 import copy
13 def clear():
14 curses.setupterm()
15 sys.stdout.write(curses.tigetstr("clear"))
16 sys.stdout.flush()
18 class Monitor(object):
19 def __init__(self):
20 self.fd_map = {}
21 self.conntrack = {}
22 self.last_conntrack = {}
23 self.connections = {}
24 self.tracking = {}
26 def update(self):
27 self.fd_map.update(proc.get_fd_map())
28 self.last_conntrack = copy.deepcopy(self.conntrack)
29 self.conntrack.update(proc.parse_ip_conntrack())
30 self.connections.update(proc.get_connections())
32 def convert(self):
33 for con in self.connections.itervalues():
34 inode = con.get('inode', None)
35 process = self.fd_map.get(inode, None)
37 if process is None:
38 continue
40 key_in = proc.ip_hash(con['remote'], con['local'])
41 key_out = proc.ip_hash(con['local'], con['remote'])
42 keys = {'in': key_in, 'out': key_out}
43 new_byte = {'in': 0, 'out': 0}
45 for direction in ('in', 'out'):
46 k = keys[direction]
47 if k in self.conntrack:
48 if key_in in self.last_conntrack:
49 new_byte[direction] = int(self.conntrack[k]['bytes']) - int(self.last_conntrack[k]['bytes'])
50 else:
51 new_byte[direction] = int(self.conntrack[k]['bytes'])
53 if process['cmd'] in self.tracking:
54 old_in, old_out = self.tracking[process['cmd']]
55 else:
56 old_in = 0
57 old_out = 0
59 self.tracking[process['cmd']] = (old_in + new_byte['in'], old_out + new_byte['out'])
61 def output(self):
62 def compare(a, b):
63 return cmp(a[1], b[1])
65 clear()
66 for cmd, bytes in sorted(self.tracking.iteritems(), cmp=compare):
67 if len(cmd) > 60:
68 cmd = cmd[:57] + '...'
69 print '%10d / %10d -- %s' % (bytes[0], bytes[1], cmd)
71 def loop(self):
72 while True:
73 self.update()
74 self.convert()
75 self.output()
76 time.sleep(1)
78 #def loop():
79 # """
80 # prints a list of processes
81 # """
83 # while True:
84 # for con in connections.itervalues():
86 # if not con['inode']:
87 # continue
89 # if not con['inode'] in fd_map:
90 # print 'inode %s not im map' % con['inode']
91 # continue
93 # process = fd_map[con['inode']]
96 # key1 = proc.ip_hash(con['local'], con['remote'])
97 # key2 = proc.ip_hash(con['remote'], con['local'])
98 # key = None
100 # if key1 in conntrack:
101 # key = key1
102 # elif key2 in conntrack:
103 # key = key2
105 # if key and 'bytes' in conntrack[key]:
106 # byte_count = conntrack[key]['bytes']
107 # else:
108 # byte_count = '?'
110 # print '%d: %s: %s -> %s (%s Bytes)' % (process['pid'], process['cmd'], con['local'], con['remote'], byte_count)
111 # time.sleep(1)