* Sets up root slice / default slice HTBs.
[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.20 2007/01/10 16:51:04 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.
58 default_MaxRate = bwlimit.get_bwcap()
59 default_Maxi2Rate = bwlimit.bwmax
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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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
282         # Reset rates.
283         if (self.MaxRate != runningmaxrate) or (self.Maxi2Rate != runningmaxi2rate):
284             logger.log("bwmon:  %s reset to %s/%s" % \
285                   (self.name,
286                    bwlimit.format_tc_rate(self.MaxRate),
287                    bwlimit.format_tc_rate(self.Maxi2Rate)))
288             bwlimit.set(xid = self.xid, 
289                 minrate = self.MinRate, 
290                 maxrate = self.MaxRate, 
291                 maxexemptrate = self.Maxi2Rate,
292                 minexemptrate = self.Mini2Rate,
293                 share = self.Share)
294
295     def update(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, data):
296         """
297         Update byte counts and check if byte limits have been
298         exceeded. 
299         """
300     
301         # Query Node Manager for max rate overrides
302         self.updateSliceAttributes(data)    
303      
304         # Prepare message parameters from the template
305         message = ""
306         params = {'slice': self.name, 'hostname': socket.gethostname(),
307                   'since': time.asctime(time.gmtime(self.time)) + " GMT",
308                   'until': time.asctime(time.gmtime(self.time + period)) + " GMT",
309                   'date': time.asctime(time.gmtime()) + " GMT",
310                   'period': format_period(period)} 
311
312         if usedbytes >= (self.bytes + (self.ThreshKByte * 1024)):
313             maxbyte = self.MaxKByte * 1024
314             bytesused = bytes - self.bytes
315             timeused = int(time.time() - self.time)
316             new_maxrate = int(((maxbyte - bytesused) * 8)/(period - timeused))
317             if new_maxrate < self.MinRate:
318                 new_maxrate = self.MinRate
319         else:
320             new_maxrate = self.MaxRate 
321
322         # Format template parameters for low bandwidth message
323         params['class'] = "low bandwidth"
324         params['bytes'] = format_bytes(usedbytes - self.bytes)
325         params['maxrate'] = bwlimit.format_tc_rate(runningmaxrate)
326         params['limit'] = format_bytes(self.MaxKByte * 1024)
327         params['new_maxrate'] = bwlimit.format_tc_rate(new_maxrate)
328
329         if verbose:
330             logger.log("bwmon:  %(slice)s %(class)s " \
331                   "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % \
332                   params)
333
334         # Cap low bandwidth burst rate
335         if new_maxrate != runningmaxrate:
336             message += template % params
337             logger.log("bwmon:      %(slice)s %(class)s capped at %(new_maxrate)s/s " % params)
338     
339         if usedi2bytes >= (self.i2bytes + (self.Threshi2KByte * 1024)):
340             maxi2byte = self.Maxi2KByte * 1024
341             i2bytesused = i2bytes - self.i2bytes
342             timeused = int(time.time() - self.time)
343             new_maxi2rate = int(((maxi2byte - i2bytesused) * 8)/(period - timeused))
344             if new_maxi2rate < self.Mini2Rate:
345                 new_maxi2rate = self.Mini2Rate
346         else:
347             new_maxi2rate = self.Maxi2Rate 
348
349         # Format template parameters for high bandwidth message
350         params['class'] = "high bandwidth"
351         params['bytes'] = format_bytes(usedi2bytes - self.i2bytes)
352         params['maxrate'] = bwlimit.format_tc_rate(runningmaxi2rate)
353         params['limit'] = format_bytes(self.Maxi2KByte * 1024)
354         params['new_maxexemptrate'] = bwlimit.format_tc_rate(new_maxi2rate)
355
356         if verbose:
357             logger.log("bwmon:  %(slice)s %(class)s " \
358                   "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % params)
359
360         # Cap high bandwidth burst rate
361         if new_maxi2rate != runningmaxi2rate:
362             message += template % params
363             logger.log("bwmon:  %(slice)s %(class)s capped at %(new_maxexemptrate)s/s" % params)
364
365         # Apply parameters
366         if new_maxrate != runningmaxrate or new_maxi2rate != runningmaxi2rate:
367             bwlimit.set(xid = self.xid, maxrate = new_maxrate, maxexemptrate = new_maxi2rate)
368
369         # Notify slice
370         if message and self.emailed == False:
371             subject = "pl_mom capped bandwidth of slice %(slice)s on %(hostname)s" % params
372             if debug:
373                 logger.log("bwmon:  "+ subject)
374                 logger.log("bwmon:  "+ message + (footer % params))
375             else:
376                 self.emailed = True
377                 slicemail(self.name, subject, message + (footer % params))
378
379 def GetSlivers(data):
380     # Defaults
381     global datafile, \
382         period, \
383         default_MaxRate, \
384         default_Maxi2Rate, \
385         default_MinRate, \
386         default_MaxKByte,\
387         default_ThreshKByte,\
388         default_Maxi2KByte,\
389         default_Threshi2KByte,\
390         default_Share,\
391         verbose
392
393     verbose = True
394     # All slices
395     names = []
396
397     try:
398         f = open(datafile, "r+")
399         if verbose:
400             logger.log("bwmon:  Loading %s" % datafile)
401         (version, slices) = pickle.load(f)
402         f.close()
403         # Check version of data file
404         if version != "$Id: bwmon.py,v 1.20 2007/01/10 16:51:04 faiyaza Exp $":
405             logger.log("bwmon:  Not using old version '%s' data file %s" % (version, datafile))
406             raise Exception
407     except Exception:
408         version = "$Id: bwmon.py,v 1.20 2007/01/10 16:51:04 faiyaza Exp $"
409         slices = {}
410
411     # Get/set special slice IDs
412     root_xid = bwlimit.get_xid("root")
413     default_xid = bwlimit.get_xid("default")
414
415     if root_xid not in slices.keys():
416         slices[root_xid] = Slice(root_xid, "root", data)
417         slices[root_xid].reset(0, 0, 0, 0, data)
418
419     if default_xid not in slices.keys():
420         slices[default_xid] = Slice(default_xid, "default", data)
421         slices[default_xid].reset(0, 0, 0, 0, data)
422
423     live = {}
424     # Get running slivers. {xid: name}
425     for sliver in data['slivers']:
426         live[bwlimit.get_xid(sliver['name'])] = sliver['name']
427
428     # Setup new slices.
429     newslicesxids = Set(live.keys()) - Set(slices.keys())
430     for newslicexid in newslicesxids:
431         logger.log("bwmon: New Slice %s" % live[newslicexid])
432         slices[newslicexid] = Slice(newslicexid, live[newslicexid], data)
433         slices[newslicexid].reset(0, 0, 0, 0, data)
434
435     # Get actual running values from tc.
436     # Update slice totals and bandwidth.
437     for params in bwlimit.get():
438         (xid, share,
439          minrate, maxrate,
440          minexemptrate, maxexemptrate,
441          usedbytes, usedi2bytes) = params
442         
443         # Ignore root and default buckets
444         if xid == root_xid or xid == default_xid:
445             continue
446
447         name = bwlimit.get_slice(xid)
448         if name is None:
449             # Orphaned (not associated with a slice) class
450             name = "%d?" % xid
451             bwlimit.off(xid)
452
453         # Monitor only the specified slices
454         if names and name not in names:
455             continue
456         #slices is populated from the pickle file
457         #xid is populated from bwlimit (read from /etc/passwd) 
458         if slices.has_key(xid):
459             slice = slices[xid]
460             if time.time() >= (slice.time + period) or \
461                usedbytes < slice.bytes or usedi2bytes < slice.i2bytes:
462                 # Reset to defaults every 24 hours or if it appears
463                 # that the byte counters have overflowed (or, more
464                 # likely, the node was restarted or the HTB buckets
465                 # were re-initialized).
466                 slice.reset(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
467             else:
468                 # Update byte counts
469                 slice.update(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
470         else:
471             # Just in case.  Probably (hopefully) this will never happen.
472             # New slice, initialize state
473             if verbose:
474                 logger.log("bwmon: New Slice %s" % name)
475             slice = slices[xid] = Slice(xid, name, data)
476             slice.reset(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
477
478     # Delete dead slices
479     dead = Set(slices.keys()) - Set(live.keys())
480     for xid in dead:
481         del slices[xid]
482         bwlimit.off(xid)
483
484     logger.log("bwmon:  Saving %s" % datafile)
485     f = open(datafile, "w")
486     pickle.dump((version, slices), f)
487     f.close()
488
489
490 #def GetSlivers(data):
491 #   for sliver in data['slivers']:
492 #       if sliver.has_key('attributes'):
493 #          print sliver
494 #           for attribute in sliver['attributes']:
495 #               if attribute['name'] == "KByteThresh": print attribute['value']
496
497 def start(options, config):
498     pass
499