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.
10 # Two separate limits are enforced, one for destinations exempt from
11 # the node bandwidth cap, and the other for all other destinations.
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
18 # $Id: bwmon.py,v 1.12 2007/03/06 20:46:54 faiyaza Exp $
33 sys.path.append("/etc/planetlab")
34 from plc_config import *
36 logger.log("bwmon: Warning: Configuration file /etc/planetlab/plc_config.py not found")
37 PLC_NAME = "PlanetLab"
38 PLC_SLICE_PREFIX = "pl"
39 PLC_MAIL_SUPPORT_ADDRESS = "support@planet-lab.org"
40 PLC_MAIL_SLICE_ADDRESS = "SLICE@slices.planet-lab.org"
43 seconds_per_day = 24 * 60 * 60
49 datafile = "/var/lib/misc/bwmon.dat"
52 # Burst to line rate (or node cap). Set by NM. in KBit/s
53 default_MaxRate = int(bwlimit.get_bwcap() / 1000)
54 default_Maxi2Rate = int(bwlimit.bwmax / 1000)
58 # 5.4 Gbyte per day. 5.4 * 1024 k * 1024M * 1024G
59 # 5.4 Gbyte per day max allowed transfered per recording period
60 default_MaxKByte = 5662310
61 default_ThreshKByte = int(.8 * default_MaxKByte)
62 # 16.4 Gbyte per day max allowed transfered per recording period to I2
63 default_Maxi2KByte = 17196646
64 default_Threshi2KByte = int(.8 * default_Maxi2KByte)
65 # Default share quanta
69 period = 1 * seconds_per_day
74 The slice %(slice)s has transmitted more than %(bytes)s from
75 %(hostname)s to %(class)s destinations
78 Its maximum %(class)s burst rate will be capped at %(new_maxrate)s/s
81 Please reduce the average %(class)s transmission rate
82 of the slice to %(limit)s per %(period)s.
88 %(date)s %(hostname)s bwcap %(slice)s
91 def format_bytes(bytes, si = True):
93 Formats bytes into a string
98 # Officially, a kibibyte
101 if bytes >= (kilo * kilo * kilo):
102 return "%.1f GB" % (bytes / (kilo * kilo * kilo))
103 elif bytes >= 1000000:
104 return "%.1f MB" % (bytes / (kilo * kilo))
106 return "%.1f KB" % (bytes / kilo)
108 return "%.0f bytes" % bytes
110 def format_period(seconds):
112 Formats a period in seconds into a string
115 if seconds == (24 * 60 * 60):
117 elif seconds == (60 * 60):
119 elif seconds > (24 * 60 * 60):
120 return "%.1f days" % (seconds / 24. / 60. / 60.)
121 elif seconds > (60 * 60):
122 return "%.1f hours" % (seconds / 60. / 60.)
124 return "%.1f minutes" % (seconds / 60.)
126 return "%.0f seconds" % seconds
128 def slicemail(slice, subject, body):
129 sendmail = os.popen("/usr/sbin/sendmail -N never -t -f%s" % PLC_MAIL_SUPPORT_ADDRESS, "w")
131 # PLC has a separate list for pl_mom messages
132 if PLC_MAIL_SUPPORT_ADDRESS == "support@planet-lab.org":
133 to = ["pl-mom@planet-lab.org"]
135 to = [PLC_MAIL_SUPPORT_ADDRESS]
137 if slice is not None and slice != "root":
138 to.append(PLC_MAIL_SLICE_ADDRESS.replace("SLICE", slice))
140 header = {'from': "%s Support <%s>" % (PLC_NAME, PLC_MAIL_SUPPORT_ADDRESS),
142 'version': sys.version.split(" ")[0],
148 Content-type: text/plain
152 X-Mailer: Python/%(version)s
155 """.lstrip() % header)
165 Stores the last recorded bandwidth parameters of a slice.
167 xid - slice context/VServer ID
169 time - beginning of recording period in UNIX seconds
170 bytes - low bandwidth bytes transmitted at the beginning of the recording period
171 i2bytes - high bandwidth bytes transmitted at the beginning of the recording period (for I2 -F)
172 ByteMax - total volume of data allowed
173 ByteThresh - After thresh, cap node to (maxbyte - bytes)/(time left in period)
174 ExemptByteMax - Same as above, but for i2.
175 ExemptByteThresh - i2 ByteThresh
176 maxrate - max_rate slice attribute.
177 maxexemptrate - max_exempt_rate slice attribute.
178 self.emailed = did we email during this recording period
182 def __init__(self, xid, name, rspec):
188 self.MaxRate = default_MaxRate
189 self.MinRate = default_MinRate
190 self.Maxi2Rate = default_Maxi2Rate
191 self.Mini2Rate = default_Mini2Rate
192 self.MaxKByte = default_MaxKByte
193 self.ThreshKByte = default_ThreshKByte
194 self.Maxi2KByte = default_Maxi2KByte
195 self.Threshi2KByte = default_Threshi2KByte
196 self.Share = default_Share
197 self.Sharei2 = default_Share
200 self.updateSliceAttributes(rspec)
201 bwlimit.set(xid = self.xid,
202 minrate = self.MinRate * 1000,
203 maxrate = self.MaxRate * 1000,
204 maxexemptrate = self.Maxi2Rate * 1000,
205 minexemptrate = self.Mini2Rate * 1000,
211 def updateSliceAttributes(self, rspec):
212 # Incase the limits have changed.
213 if (self.MaxRate != default_MaxRate) or \
214 (self.Maxi2Rate != default_Maxi2Rate):
215 self.MaxRate = int(bwlimit.get_bwcap() / 1000)
216 self.Maxi2Rate = int(bwlimit.bwmax / 1000)
219 if rspec.has_key('net_min_rate'):
220 logger.log("bwmon: Updating %s. Min Rate = %s" %(self.name, self.MinRate))
221 # To ensure min does not go above 25% of nodecap.
222 if int(rspec['net_min_rate']) > int(.25 * default_MaxRate):
223 self.MinRate = int(.25 * default_MaxRate)
225 self.MinRate = int(rspec['net_min_rate'])
227 MaxRate = int(rspec.get('net_max_rate', bwlimit.get_bwcap() / 1000))
228 if MaxRate != self.MaxRate:
229 self.MaxRate = MaxRate
230 logger.log("bwmon: Updating %s. Max Rate = %s" %(self.name, self.MaxRate))
232 Mini2Rate = int(rspec.get('net_i2_min_rate', default_Mini2Rate))
233 if Mini2Rate != self.Mini2Rate:
234 self.Mini2Rate = Mini2Rate
235 logger.log("bwmon: Updating %s. Min i2 Rate = %s" %(self.name, self.Mini2Rate))
237 Maxi2Rate = int(rspec.get('net_i2_max_rate', bwlimit.bwmax / 1000))
238 if Maxi2Rate != self.Maxi2Rate:
239 self.Maxi2Rate = Maxi2Rate
240 logger.log("bwmon: Updating %s. Max i2 Rate = %s" %(self.name, self.Maxi2Rate))
242 MaxKByte = int(rspec.get('net_max_kbyte', default_MaxKByte))
243 if MaxKByte != self.MaxKByte:
244 self.MaxKByte = MaxKByte
245 logger.log("bwmon: Updating %s. Max KByte lim = %s" %(self.name, self.MaxKByte))
247 Maxi2KByte = int(rspec.get('net_i2_max_kbyte', default_Maxi2KByte))
248 if Maxi2KByte != self.Maxi2KByte:
249 self.Maxi2KByte = Maxi2KByte
250 logger.log("bwmon: Updating %s. Max i2 KByte = %s" %(self.name, self.Maxi2KByte))
252 ThreshKByte = int(rspec.get('net_thresh_kbyte', default_ThreshKByte))
253 if ThreshKByte != self.ThreshKByte:
254 self.ThreshKByte = ThreshKByte
255 logger.log("bwmon: Updating %s. Thresh KByte = %s" %(self.name, self.ThreshKByte))
257 Threshi2KByte = int(rspec.get('net_i2_thresh_kbyte', default_Threshi2KByte))
258 if Threshi2KByte != self.Threshi2KByte:
259 self.Threshi2KByte = Threshi2KByte
260 logger.log("bwmon: Updating %s. i2 Thresh KByte = %s" %(self.name, self.Threshi2KByte))
262 Share = int(rspec.get('net_share', default_Share))
263 if Share != self.Share:
265 logger.log("bwmon: Updating %s. Net Share = %s" %(self.name, self.Share))
267 Sharei2 = int(rspec.get('net_i2_share', default_Share))
268 if Sharei2 != self.Sharei2:
269 self.Sharei2 = Sharei2
270 logger.log("bwmon: Updating %s. Net i2 Share = %s" %(self.name, self.i2Share))
273 def reset(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, rspec):
275 Begin a new recording period. Remove caps by restoring limits
276 to their default values.
279 # Query Node Manager for max rate overrides
280 self.updateSliceAttributes(rspec)
282 # Reset baseline time
283 self.time = time.time()
285 # Reset baseline byte coutns
286 self.bytes = usedbytes
287 self.i2bytes = usedi2bytes
291 maxrate = self.MaxRate * 1000
292 maxi2rate = self.Maxi2Rate * 1000
294 if (self.MaxRate != runningmaxrate) or (self.Maxi2Rate != runningmaxi2rate):
295 logger.log("bwmon: %s reset to %s/%s" % \
297 bwlimit.format_tc_rate(maxrate),
298 bwlimit.format_tc_rate(maxi2rate)))
299 bwlimit.set(xid = self.xid,
300 minrate = self.MinRate * 1000,
301 maxrate = self.MaxRate * 1000,
302 maxexemptrate = self.Maxi2Rate * 1000,
303 minexemptrate = self.Mini2Rate * 1000,
306 def update(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, rspec):
308 Update byte counts and check if byte limits have been
312 # Query Node Manager for max rate overrides
313 self.updateSliceAttributes(rspec)
315 # Prepare message parameters from the template
317 params = {'slice': self.name, 'hostname': socket.gethostname(),
318 'since': time.asctime(time.gmtime(self.time)) + " GMT",
319 'until': time.asctime(time.gmtime(self.time + period)) + " GMT",
320 'date': time.asctime(time.gmtime()) + " GMT",
321 'period': format_period(period)}
323 if usedbytes >= (self.bytes + (self.ThreshKByte * 1024)):
324 sum = self.bytes + (self.ThreshKByte * 1024)
325 maxbyte = self.MaxKByte * 1024
326 bytesused = usedbytes - self.bytes
327 timeused = int(time.time() - self.time)
328 new_maxrate = int(((maxbyte - bytesused) * 8)/(period - timeused))
329 if new_maxrate < (self.MinRate * 1000):
330 new_maxrate = self.MinRate * 1000
332 new_maxrate = self.MaxRate * 1000
334 # Format template parameters for low bandwidth message
335 params['class'] = "low bandwidth"
336 params['bytes'] = format_bytes(usedbytes - self.bytes)
337 params['limit'] = format_bytes(self.MaxKByte * 1024)
338 params['new_maxrate'] = bwlimit.format_tc_rate(new_maxrate)
341 logger.log("bwmon: %(slice)s %(class)s " \
342 "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % \
345 # Cap low bandwidth burst rate
346 if new_maxrate != runningmaxrate:
347 message += template % params
348 logger.log("bwmon: ** %(slice)s %(class)s capped at %(new_maxrate)s/s " % params)
350 if usedi2bytes >= (self.i2bytes + (self.Threshi2KByte * 1024)):
351 maxi2byte = self.Maxi2KByte * 1024
352 i2bytesused = usedi2bytes - self.i2bytes
353 timeused = int(time.time() - self.time)
354 new_maxi2rate = int(((maxi2byte - i2bytesused) * 8)/(period - timeused))
355 if new_maxi2rate < (self.Mini2Rate * 1000):
356 new_maxi2rate = self.Mini2Rate * 1000
358 new_maxi2rate = self.Maxi2Rate * 1000
360 # Format template parameters for high bandwidth message
361 params['class'] = "high bandwidth"
362 params['bytes'] = format_bytes(usedi2bytes - self.i2bytes)
363 params['limit'] = format_bytes(self.Maxi2KByte * 1024)
364 params['new_maxexemptrate'] = bwlimit.format_tc_rate(new_maxi2rate)
367 logger.log("bwmon: %(slice)s %(class)s " \
368 "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % params)
370 # Cap high bandwidth burst rate
371 if new_maxi2rate != runningmaxi2rate:
372 message += template % params
373 logger.log("bwmon: %(slice)s %(class)s capped at %(new_maxexemptrate)s/s" % params)
376 if new_maxrate != runningmaxrate or new_maxi2rate != runningmaxi2rate:
377 bwlimit.set(xid = self.xid, maxrate = new_maxrate, maxexemptrate = new_maxi2rate)
380 if message and self.emailed == False:
381 subject = "pl_mom capped bandwidth of slice %(slice)s on %(hostname)s" % params
383 logger.log("bwmon: "+ subject)
384 logger.log("bwmon: "+ message + (footer % params))
387 slicemail(self.name, subject, message + (footer % params))
397 default_ThreshKByte,\
399 default_Threshi2KByte,\
406 # Incase the limits have changed.
407 default_MaxRate = int(bwlimit.get_bwcap() / 1000)
408 default_Maxi2Rate = int(bwlimit.bwmax / 1000)
410 # Incase default isn't set yet.
411 if default_MaxRate == -1:
412 default_MaxRate = 1000000
415 f = open(datafile, "r+")
416 logger.log("bwmon: Loading %s" % datafile)
417 (version, slices) = pickle.load(f)
419 # Check version of data file
420 if version != "$Id: bwmon.py,v 1.12 2007/03/06 20:46:54 faiyaza Exp $":
421 logger.log("bwmon: Not using old version '%s' data file %s" % (version, datafile))
424 version = "$Id: bwmon.py,v 1.12 2007/03/06 20:46:54 faiyaza Exp $"
427 # Get/set special slice IDs
428 root_xid = bwlimit.get_xid("root")
429 default_xid = bwlimit.get_xid("default")
431 if root_xid not in slices.keys():
432 slices[root_xid] = Slice(root_xid, "root", {})
433 slices[root_xid].reset(0, 0, 0, 0, {})
435 if default_xid not in slices.keys():
436 slices[default_xid] = Slice(default_xid, "default", {})
437 slices[default_xid].reset(0, 0, 0, 0, {})
440 # Get running slivers that should be on this node (from plc). {xid: name}
441 for sliver in db.keys():
442 live[bwlimit.get_xid(sliver)] = sliver
445 # live.xids - runing.xids = new.xids
446 newslicesxids = Set(live.keys()) - Set(slices.keys())
447 for newslicexid in newslicesxids:
448 if newslicexid != None or db[live[newslicexid]].has_key('_rspec') != True:
449 logger.log("bwmon: New Slice %s" % live[newslicexid])
450 rspec = db[live[newslicexid]]['_rspec']
451 slices[newslicexid] = Slice(newslicexid, live[newslicexid], rspec)
452 slices[newslicexid].reset(0, 0, 0, 0, rspec)
454 logger.log("bwmon Slice %s doesn't have xid. Must be delegated. Skipping." % live[newslicexid])
455 # Get actual running values from tc.
456 # Update slice totals and bandwidth.
457 for params in bwlimit.get():
460 minexemptrate, maxexemptrate,
461 usedbytes, usedi2bytes) = params
463 # Ignore root and default buckets
464 if xid == root_xid or xid == default_xid:
467 name = bwlimit.get_slice(xid)
469 # Orphaned (not associated with a slice) class
473 # Monitor only the specified slices
474 if names and name not in names:
476 #slices is populated from the pickle file
477 #xid is populated from bwlimit (read from /etc/passwd)
478 if slices.has_key(xid):
480 if time.time() >= (slice.time + period) or \
481 usedbytes < slice.bytes or usedi2bytes < slice.i2bytes:
482 # Reset to defaults every 24 hours or if it appears
483 # that the byte counters have overflowed (or, more
484 # likely, the node was restarted or the HTB buckets
485 # were re-initialized).
486 slice.reset(maxrate, \
490 db[slice.name]['_rspec'])
493 slice.update(maxrate, \
497 db[slice.name]['_rspec'])
499 # Just in case. Probably (hopefully) this will never happen.
500 # New slice, initialize state
501 logger.log("bwmon: New Slice %s" % name)
502 slice = slices[xid] = Slice(xid, name, db[slice.name]['_rspec'])
503 slice.reset(maxrate, \
507 db[slice.name]['_rspec'])
510 dead = Set(slices.keys()) - Set(live.keys())
512 if xid == root_xid or xid == default_xid:
517 logger.log("bwmon: Saving %s" % datafile)
518 f = open(datafile, "w")
519 pickle.dump((version, slices), f)
523 #def GetSlivers(data):
524 # for sliver in data['slivers']:
525 # if sliver.has_key('attributes'):
527 # for attribute in sliver['attributes']:
528 # if attribute['name'] == "KByteThresh": print attribute['value']
530 #def start(options, config):