* Changed variable names for clarity...and fixed a glaring syntax error.
[nodemanager.git] / bwmon.py
1 #!/usr/bin/python
2 #
3 # Average bandwidth monitoring script. Run periodically via cron(8) to
4 # enforce a soft limit on daily bandwidth usage for each slice. If a
5 # slice is found to have exceeded its daily bandwidth usage when the
6 # script is run, its instantaneous rate will be capped at the desired
7 # average rate. Thus, in the worst case, a slice will only be able to
8 # send a little more than twice its average daily limit.
9 #
10 # Two separate limits are enforced, one for destinations exempt from
11 # the node bandwidth cap, and the other for all other destinations.
12 #
13 # Mark Huang <mlhuang@cs.princeton.edu>
14 # Andy Bavier <acb@cs.princeton.edu>
15 # Faiyaz Ahmed <faiyaza@cs.princeton.edu>
16 # Copyright (C) 2004-2006 The Trustees of Princeton University
17 #
18 # $Id: bwmon.py,v 1.6 2007/02/12 23:05:58 faiyaza Exp $
19 #
20
21 import os
22 import sys
23 import time
24 import pickle
25 import database
26
27 import socket
28 #import xmlrpclib
29 import bwlimit
30 import logger
31
32 from sets import Set
33 try:
34     sys.path.append("/etc/planetlab")
35     from plc_config import *
36 except:
37     logger.log("bwmon:  Warning: Configuration file /etc/planetlab/plc_config.py not found")
38     PLC_NAME = "PlanetLab"
39     PLC_SLICE_PREFIX = "pl"
40     PLC_MAIL_SUPPORT_ADDRESS = "support@planet-lab.org"
41     PLC_MAIL_SLICE_ADDRESS = "SLICE@slices.planet-lab.org"
42
43
44 # Utility functions
45 #from pl_mom import *
46
47 # Constants
48 seconds_per_day = 24 * 60 * 60
49 bits_per_byte = 8
50
51 # Defaults
52 debug = False
53 verbose = 0
54 datafile = "/var/lib/misc/bwmon.dat"
55 #nm = None
56
57 # Burst to line rate (or node cap).  Set by NM. in KBit/s
58 default_MaxRate = int(bwlimit.get_bwcap() / 1000)
59 default_Maxi2Rate = int(bwlimit.bwmax / 1000)
60 # Min rate 8 bits/s 
61 default_MinRate = 0
62 default_Mini2Rate = 0
63 # 5.4 Gbyte per day. 5.4 * 1024 k * 1024M * 1024G 
64 # 5.4 Gbyte per day max allowed transfered per recording period
65 default_MaxKByte = 5662310
66 default_ThreshKByte = int(.8 * default_MaxKByte) 
67 # 16.4 Gbyte per day max allowed transfered per recording period to I2
68 default_Maxi2KByte = 17196646
69 default_Threshi2KByte = int(.8 * default_Maxi2KByte) 
70 # Default share quanta
71 default_Share = 1
72
73 # Average over 1 day
74 period = 1 * seconds_per_day
75
76 # Message template
77 template = \
78 """
79 The slice %(slice)s has transmitted more than %(bytes)s from
80 %(hostname)s to %(class)s destinations
81 since %(since)s.
82
83 Its maximum %(class)s burst rate will be capped at %(new_maxrate)s/s
84 until %(until)s.
85
86 Please reduce the average %(class)s transmission rate
87 of the slice to %(limit)s per %(period)s.
88
89 """.lstrip()
90
91 footer = \
92 """
93 %(date)s %(hostname)s bwcap %(slice)s
94 """.lstrip()
95
96 def format_bytes(bytes, si = True):
97     """
98     Formats bytes into a string
99     """
100     if si:
101         kilo = 1000.
102     else:
103         # Officially, a kibibyte
104         kilo = 1024.
105
106     if bytes >= (kilo * kilo * kilo):
107         return "%.1f GB" % (bytes / (kilo * kilo * kilo))
108     elif bytes >= 1000000:
109         return "%.1f MB" % (bytes / (kilo * kilo))
110     elif bytes >= 1000:
111         return "%.1f KB" % (bytes / kilo)
112     else:
113         return "%.0f bytes" % bytes
114
115 def format_period(seconds):
116     """
117     Formats a period in seconds into a string
118     """
119
120     if seconds == (24 * 60 * 60):
121         return "day"
122     elif seconds == (60 * 60):
123         return "hour"
124     elif seconds > (24 * 60 * 60):
125         return "%.1f days" % (seconds / 24. / 60. / 60.)
126     elif seconds > (60 * 60):
127         return "%.1f hours" % (seconds / 60. / 60.)
128     elif seconds > (60):
129         return "%.1f minutes" % (seconds / 60.)
130     else:
131         return "%.0f seconds" % seconds
132
133 def slicemail(slice, subject, body):
134     sendmail = os.popen("/usr/sbin/sendmail -N never -t -f%s" % PLC_MAIL_SUPPORT_ADDRESS, "w")
135
136     # PLC has a separate list for pl_mom messages
137     if PLC_MAIL_SUPPORT_ADDRESS == "support@planet-lab.org":
138         to = ["pl-mom@planet-lab.org"]
139     else:
140         to = [PLC_MAIL_SUPPORT_ADDRESS]
141
142     if slice is not None and slice != "root":
143         to.append(PLC_MAIL_SLICE_ADDRESS.replace("SLICE", slice))
144
145     header = {'from': "%s Support <%s>" % (PLC_NAME, PLC_MAIL_SUPPORT_ADDRESS),
146               'to': ", ".join(to),
147               'version': sys.version.split(" ")[0],
148               'subject': subject}
149
150     # Write headers
151     sendmail.write(
152 """
153 Content-type: text/plain
154 From: %(from)s
155 Reply-To: %(from)s
156 To: %(to)s
157 X-Mailer: Python/%(version)s
158 Subject: %(subject)s
159
160 """.lstrip() % header)
161
162     # Write body
163     sendmail.write(body)
164     # Done
165     sendmail.close()
166
167
168 class Slice:
169     """
170     Stores the last recorded bandwidth parameters of a slice.
171
172     xid - slice context/VServer ID
173     name - slice name
174     time - beginning of recording period in UNIX seconds
175     bytes - low bandwidth bytes transmitted at the beginning of the recording period
176     i2bytes - high bandwidth bytes transmitted at the beginning of the recording period (for I2 -F)
177     ByteMax - total volume of data allowed
178     ByteThresh - After thresh, cap node to (maxbyte - bytes)/(time left in period)
179     ExemptByteMax - Same as above, but for i2.
180     ExemptByteThresh - i2 ByteThresh
181     maxrate - max_rate slice attribute. 
182     maxexemptrate - max_exempt_rate slice attribute.
183     self.emailed = did we email during this recording period
184
185     """
186
187     def __init__(self, xid, name, data):
188         self.xid = xid
189         self.name = name
190         self.time = 0
191         self.bytes = 0
192         self.i2bytes = 0
193         self.MaxRate = default_MaxRate
194         self.MinRate = default_MinRate
195         self.Maxi2Rate = default_Maxi2Rate
196         self.Mini2Rate = default_Mini2Rate
197         self.MaxKByte = default_MaxKByte
198         self.ThreshKByte = default_ThreshKByte
199         self.Maxi2KByte = default_Maxi2KByte
200         self.Threshi2KByte = default_Threshi2KByte
201         self.Share = default_Share
202         self.emailed = False
203
204         self.updateSliceAttributes(data)
205         bwlimit.set(xid = self.xid, 
206                 minrate = self.MinRate, 
207                 maxrate = self.MaxRate, 
208                 maxexemptrate = self.Maxi2Rate,
209                 minexemptrate = self.Mini2Rate,
210                 share = self.Share)
211
212
213     def __repr__(self):
214         return self.name
215
216     @database.synchronized
217     def updateSliceAttributes(self, data):
218         for sliver in data['slivers']:
219             if sliver['name'] == self.name: 
220                 for attribute in sliver['attributes']:
221                     if attribute['name'] == 'net_min_rate':     
222                         self.MinRate = int(attribute['value'])
223                         logger.log("bwmon:  Updating %s. Min Rate - %s" \
224                           %(self.name, self.MinRate))
225                     elif attribute['name'] == 'net_max_rate':       
226                         self.MaxRate = int(attribute['value'])
227                         logger.log("bwmon:  Updating %s. Max Rate - %s" \
228                           %(self.name, self.MaxRate))
229                     elif attribute['name'] == 'net_i2_min_rate':
230                         self.Mini2Rate = int(attribute['value'])
231                         logger.log("bwmon:  Updating %s. Min i2 Rate - %s" \
232                           %(self.name, self.Mini2Rate))
233                     elif attribute['name'] == 'net_i2_max_rate':        
234                         self.Maxi2Rate = int(attribute['value'])
235                         logger.log("bwmon:  Updating %s. Max i2 Rate - %s" \
236                           %(self.name, self.Maxi2Rate))
237                     elif attribute['name'] == 'net_max_kbyte':      
238                         self.MaxKByte = int(attribute['value'])
239                         logger.log("bwmon:  Updating %s. Max KByte lim - %s" \
240                           %(self.name, self.MaxKByte))
241                     elif attribute['name'] == 'net_i2_max_kbyte':   
242                         self.Maxi2KByte = int(attribute['value'])
243                         logger.log("bwmon:  Updating %s. Max i2 KByte - %s" \
244                           %(self.name, self.Maxi2KByte))
245                     elif attribute['name'] == 'net_thresh_kbyte':   
246                         self.ThreshKByte = int(attribute['value'])
247                         logger.log("bwmon:  Updating %s. Thresh KByte - %s" \
248                           %(self.name, self.ThreshKByte))
249                     elif attribute['name'] == 'net_i2_thresh_kbyte':    
250                         self.Threshi2KByte = int(attribute['value'])
251                         logger.log("bwmon:  Updating %s. i2 Thresh KByte - %s" \
252                           %(self.name, self.Threshi2KByte))
253                     elif attribute['name'] == 'net_share':  
254                         self.Share = int(attribute['value'])
255                         logger.log("bwmon:  Updating %s. Net Share - %s" \
256                           %(self.name, self.Share))
257                     elif attribute['name'] == 'net_i2_share':   
258                         self.Sharei2 = int(attribute['value'])
259                         logger.log("bwmon:  Updating %s. Net i2 Share - %s" \
260                           %(self.name, self.i2Share))
261
262
263     def reset(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, data):
264         """
265         Begin a new recording period. Remove caps by restoring limits
266         to their default values.
267         """
268         
269         # Query Node Manager for max rate overrides
270         self.updateSliceAttributes(data)    
271
272         # Reset baseline time
273         self.time = time.time()
274
275         # Reset baseline byte coutns
276         self.bytes = usedbytes
277         self.i2bytes = usedi2bytes
278
279         # Reset email 
280         self.emailed = False
281         maxrate = self.MaxRate * 1000 
282         maxi2rate = self.Maxi2Rate * 1000 
283         # Reset rates.
284         if (self.MaxRate != runningmaxrate) or (self.Maxi2Rate != runningmaxi2rate):
285             logger.log("bwmon:  %s reset to %s/%s" % \
286                   (self.name,
287                    bwlimit.format_tc_rate(maxrate),
288                    bwlimit.format_tc_rate(maxi2rate)))
289             bwlimit.set(xid = self.xid, 
290                 minrate = self.MinRate * 1000, 
291                 maxrate = self.MaxRate * 1000, 
292                 maxexemptrate = self.Maxi2Rate * 1000,
293                 minexemptrate = self.Mini2Rate * 1000,
294                 share = self.Share)
295
296     def update(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, data):
297         """
298         Update byte counts and check if byte limits have been
299         exceeded. 
300         """
301     
302         # Query Node Manager for max rate overrides
303         self.updateSliceAttributes(data)    
304      
305         # Prepare message parameters from the template
306         message = ""
307         params = {'slice': self.name, 'hostname': socket.gethostname(),
308                   'since': time.asctime(time.gmtime(self.time)) + " GMT",
309                   'until': time.asctime(time.gmtime(self.time + period)) + " GMT",
310                   'date': time.asctime(time.gmtime()) + " GMT",
311                   'period': format_period(period)} 
312
313         if usedbytes >= (self.bytes + (self.ThreshKByte * 1024)):
314             maxbyte = self.MaxKByte * 1024
315             bytesused = usedbytes - self.bytes
316             timeused = int(time.time() - self.time)
317             new_maxrate = int(((maxbyte - bytesused) * 8)/(period - timeused))
318             if new_maxrate < self.MinRate:
319                 new_maxrate = self.MinRate
320         else:
321             new_maxrate = self.MaxRate * 1000 
322
323         # Format template parameters for low bandwidth message
324         params['class'] = "low bandwidth"
325         params['bytes'] = format_bytes(usedbytes - self.bytes)
326         params['maxrate'] = bwlimit.format_tc_rate(runningmaxrate)
327         params['limit'] = format_bytes(self.MaxKByte * 1024)
328         params['new_maxrate'] = bwlimit.format_tc_rate(new_maxrate)
329
330         if verbose:
331             logger.log("bwmon:  %(slice)s %(class)s " \
332                   "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % \
333                   params)
334
335         # Cap low bandwidth burst rate
336         if new_maxrate != runningmaxrate:
337             message += template % params
338             logger.log("bwmon:      %(slice)s %(class)s capped at %(new_maxrate)s/s " % params)
339     
340         if usedi2bytes >= (self.i2bytes + (self.Threshi2KByte * 1024)):
341             maxi2byte = self.Maxi2KByte * 1024
342             i2bytesused = usedi2bytes - self.i2bytes
343             timeused = int(time.time() - self.time)
344             new_maxi2rate = int(((maxi2byte - i2bytesused) * 8)/(period - timeused))
345             if new_maxi2rate < self.Mini2Rate:
346                 new_maxi2rate = self.Mini2Rate
347         else:
348             new_maxi2rate = self.Maxi2Rate * 1000
349
350         # Format template parameters for high bandwidth message
351         params['class'] = "high bandwidth"
352         params['bytes'] = format_bytes(usedi2bytes - self.i2bytes)
353         params['maxrate'] = bwlimit.format_tc_rate(runningmaxi2rate)
354         params['limit'] = format_bytes(self.Maxi2KByte * 1024)
355         params['new_maxexemptrate'] = bwlimit.format_tc_rate(new_maxi2rate)
356
357         if verbose:
358             logger.log("bwmon:  %(slice)s %(class)s " \
359                   "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % params)
360
361         # Cap high bandwidth burst rate
362         if new_maxi2rate != runningmaxi2rate:
363             message += template % params
364             logger.log("bwmon:  %(slice)s %(class)s capped at %(new_maxexemptrate)s/s" % params)
365
366         # Apply parameters
367         if new_maxrate != runningmaxrate or new_maxi2rate != runningmaxi2rate:
368             bwlimit.set(xid = self.xid, maxrate = new_maxrate, maxexemptrate = new_maxi2rate)
369
370         # Notify slice
371         if message and self.emailed == False:
372             subject = "pl_mom capped bandwidth of slice %(slice)s on %(hostname)s" % params
373             if debug:
374                 logger.log("bwmon:  "+ subject)
375                 logger.log("bwmon:  "+ message + (footer % params))
376             else:
377                 self.emailed = True
378                 slicemail(self.name, subject, message + (footer % params))
379
380 def GetSlivers(data):
381     # Defaults
382     global datafile, \
383         period, \
384         default_MaxRate, \
385         default_Maxi2Rate, \
386         default_MinRate, \
387         default_MaxKByte,\
388         default_ThreshKByte,\
389         default_Maxi2KByte,\
390         default_Threshi2KByte,\
391         default_Share,\
392         verbose
393
394     verbose = True
395     # All slices
396     names = []
397
398     try:
399         f = open(datafile, "r+")
400         if verbose:
401             logger.log("bwmon:  Loading %s" % datafile)
402         (version, slices) = pickle.load(f)
403         f.close()
404         # Check version of data file
405         if version != "$Id: bwmon.py,v 1.6 2007/02/12 23:05:58 faiyaza Exp $":
406             logger.log("bwmon:  Not using old version '%s' data file %s" % (version, datafile))
407             raise Exception
408     except Exception:
409         version = "$Id: bwmon.py,v 1.6 2007/02/12 23:05:58 faiyaza Exp $"
410         slices = {}
411
412     # Get/set special slice IDs
413     root_xid = bwlimit.get_xid("root")
414     default_xid = bwlimit.get_xid("default")
415
416     if root_xid not in slices.keys():
417         slices[root_xid] = Slice(root_xid, "root", data)
418         slices[root_xid].reset(0, 0, 0, 0, data)
419
420     if default_xid not in slices.keys():
421         slices[default_xid] = Slice(default_xid, "default", data)
422         slices[default_xid].reset(0, 0, 0, 0, data)
423
424     live = {}
425     # Get running slivers. {xid: name}
426     for sliver in data['slivers']:
427         live[bwlimit.get_xid(sliver['name'])] = sliver['name']
428
429
430     # Setup new slices.
431     newslicesxids = Set(live.keys()) - Set(slices.keys())
432     for newslicexid in newslicesxids:
433         logger.log("bwmon: New Slice %s" % live[newslicexid])
434         slices[newslicexid] = Slice(newslicexid, live[newslicexid], data)
435         slices[newslicexid].reset(0, 0, 0, 0, data)
436
437     # Get actual running values from tc.
438     # Update slice totals and bandwidth.
439     for params in bwlimit.get():
440         (xid, share,
441          minrate, maxrate,
442          minexemptrate, maxexemptrate,
443          usedbytes, usedi2bytes) = params
444         
445         # Ignore root and default buckets
446         if xid == root_xid or xid == default_xid:
447             continue
448
449         name = bwlimit.get_slice(xid)
450         if name is None:
451             # Orphaned (not associated with a slice) class
452             name = "%d?" % xid
453             bwlimit.off(xid)
454
455         # Monitor only the specified slices
456         if names and name not in names:
457             continue
458         #slices is populated from the pickle file
459         #xid is populated from bwlimit (read from /etc/passwd) 
460         if slices.has_key(xid):
461             slice = slices[xid]
462             if time.time() >= (slice.time + period) or \
463                usedbytes < slice.bytes or usedi2bytes < slice.i2bytes:
464                 # Reset to defaults every 24 hours or if it appears
465                 # that the byte counters have overflowed (or, more
466                 # likely, the node was restarted or the HTB buckets
467                 # were re-initialized).
468                 slice.reset(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
469             else:
470                 # Update byte counts
471                 slice.update(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
472         else:
473             # Just in case.  Probably (hopefully) this will never happen.
474             # New slice, initialize state
475             if verbose:
476                 logger.log("bwmon: New Slice %s" % name)
477             slice = slices[xid] = Slice(xid, name, data)
478             slice.reset(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
479
480     # Delete dead slices
481     dead = Set(slices.keys()) - Set(live.keys())
482     for xid in dead:
483         if xid == root_xid or xid == default_xid:
484             continue
485         del slices[xid]
486         bwlimit.off(xid)
487
488     logger.log("bwmon:  Saving %s" % datafile)
489     f = open(datafile, "w")
490     pickle.dump((version, slices), f)
491     f.close()
492
493
494 #def GetSlivers(data):
495 #   for sliver in data['slivers']:
496 #       if sliver.has_key('attributes'):
497 #          print sliver
498 #           for attribute in sliver['attributes']:
499 #               if attribute['name'] == "KByteThresh": print attribute['value']
500
501 def start(options, config):
502     pass
503