Version 1.1 with conntrack-tools support
[bwmon.git] / bwmon / util.py
blob35abe91613efc3f3c204ba4a84ff5b8845b87d7f
1 # -*- coding: utf-8 -*-
3 # Copyright 2010 Thomas Perl and Stefan Kögl. All rights reserved.
5 # Developed for a practical course (Large-scaled distributed computing) at the
6 # University of Technology Vienna in the 2010 summer term.
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions are met:
11 # 1. Redistributions of source code must retain the above copyright notice,
12 # this list of conditions and the following disclaimer.
14 # 2. Redistributions in binary form must reproduce the above copyright notice,
15 # this list of conditions and the following disclaimer in the documentation
16 # and/or other materials provided with the distribution.
18 # THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR IMPLIED
19 # WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20 # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21 # EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
24 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
25 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
26 # OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
27 # ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 import curses
31 import sys
32 import ConfigParser
34 def clear():
35 """Clear the console using curses
37 This utility function empties the console ("clear").
38 """
39 curses.setupterm()
40 sys.stdout.write(curses.tigetstr("clear"))
41 sys.stdout.flush()
43 def read_monitor_config(configfile):
44 """Reads the monitor configuration file for the Aggregator
46 @param configfile: path of the config file
47 @return: a list of Monitor or PipeMonitor objects
48 """
49 config = ConfigParser.ConfigParser()
50 config.read(configfile)
51 for section in config.sections():
52 c = dict(config.items(section))
54 if c['type'] == 'monitor':
55 ignorelocal = parse_bool(c.get('ignorelocal', False))
56 import monitor
57 mon = monitor.Monitor(ignorelocal=ignorelocal)
58 inc = [c.get('include', '')]
59 exc = [c.get('exclude', '')]
60 mon.set_filter(inc, exc)
62 elif c['type'] == 'pipe':
63 import pipe
64 port = int(c['port'])
65 newhost = c['newhost']
66 newport = int(c['newport'])
68 mon = pipe.PipeMonitor(pipe.Pipe(port, newhost, newport))
69 #mon.set_shape(c.get('shape_threshold', 0))
71 else:
72 mon = None
73 print 'unknown monitor type %s' % c['type']
75 if mon:
76 yield mon
79 def parse_bool(val):
80 """Convert a string to a boolean value
82 @param val: The string value (or boolean)
83 @return: True or False, depending on "val"
84 """
85 if isinstance(val, bool):
86 return val
88 if string.lower() == 'true':
89 return True
91 return False
94 def read_notification_config(configfile):
95 """Reads the notification config file for the Aggregator
97 @param configfile: path to the config file
98 @return: a list of tuples representing the notification settings (process_regex, in_threshold, out_threshold, interval, command)
99 """
100 config = ConfigParser.ConfigParser()
101 config.read(configfile)
102 for section in config.sections():
103 c = dict(config.items(section))
104 yield ( c['process_filter'], int(c.get('in_threshold', 0)), int(c.get('out_threshold', 0)), int(c.get('interval', 1)), c.get('notification_command', '') )
107 class RingBuffer:
108 """A ringbuffer
111 def __init__(self,size_max):
112 """Initiates a new ringbuffer with the given size
114 @param size_max: maximum number of entries
116 self.max = size_max
117 self.data = []
119 def append(self,x):
120 """Append an element at the end of the buffer
122 @param x: The element to append
124 self.data.append(x)
125 if len(self.data) == self.max:
126 self.cur=0
127 self.__class__ = RingBufferFull
129 def get(self):
130 """Get a list of contained elements
132 @return: A list of ements from oldest to newesta
134 return self.data
137 class RingBufferFull:
138 """A full ringbuffer - not initialized directly
141 def __init__(self, n):
142 """Don't initialize this object directly!"""
143 raise "don't initialize FullRingBuffer directly"
145 def append(self,x):
146 """Append an element at the end of the buffer
148 @param x: The element to append
150 self.data[self.cur]=x
151 self.cur=(self.cur+1) % self.max
153 def get(self):
154 """Get a list of contained elements
156 @return: A list of ements from oldest to newesta
158 return self.data[self.cur:]+self.data[:self.cur]