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.20 2007/01/10 16:51:04 faiyaza Exp $
34 sys.path.append("/etc/planetlab")
35 from plc_config import *
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"
48 seconds_per_day = 24 * 60 * 60
54 datafile = "/var/lib/misc/bwmon.dat"
57 # Burst to line rate (or node cap). Set by NM.
58 default_MaxRate = bwlimit.get_bwcap()
59 default_Maxi2Rate = bwlimit.bwmax
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
74 period = 1 * seconds_per_day
79 The slice %(slice)s has transmitted more than %(bytes)s from
80 %(hostname)s to %(class)s destinations
83 Its maximum %(class)s burst rate will be capped at %(new_maxrate)s/s
86 Please reduce the average %(class)s transmission rate
87 of the slice to %(limit)s per %(period)s.
93 %(date)s %(hostname)s bwcap %(slice)s
96 def format_bytes(bytes, si = True):
98 Formats bytes into a string
103 # Officially, a kibibyte
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))
111 return "%.1f KB" % (bytes / kilo)
113 return "%.0f bytes" % bytes
115 def format_period(seconds):
117 Formats a period in seconds into a string
120 if seconds == (24 * 60 * 60):
122 elif seconds == (60 * 60):
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.)
129 return "%.1f minutes" % (seconds / 60.)
131 return "%.0f seconds" % seconds
133 def slicemail(slice, subject, body):
134 sendmail = os.popen("/usr/sbin/sendmail -N never -t -f%s" % PLC_MAIL_SUPPORT_ADDRESS, "w")
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"]
140 to = [PLC_MAIL_SUPPORT_ADDRESS]
142 if slice is not None and slice != "root":
143 to.append(PLC_MAIL_SLICE_ADDRESS.replace("SLICE", slice))
145 header = {'from': "%s Support <%s>" % (PLC_NAME, PLC_MAIL_SUPPORT_ADDRESS),
147 'version': sys.version.split(" ")[0],
153 Content-type: text/plain
157 X-Mailer: Python/%(version)s
160 """.lstrip() % header)
170 Stores the last recorded bandwidth parameters of a slice.
172 xid - slice context/VServer ID
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
187 def __init__(self, xid, name, data):
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
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,
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))
263 def reset(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, data):
265 Begin a new recording period. Remove caps by restoring limits
266 to their default values.
269 # Query Node Manager for max rate overrides
270 self.updateSliceAttributes(data)
272 # Reset baseline time
273 self.time = time.time()
275 # Reset baseline byte coutns
276 self.bytes = usedbytes
277 self.i2bytes = usedi2bytes
283 if (self.MaxRate != runningmaxrate) or (self.Maxi2Rate != runningmaxi2rate):
284 logger.log("bwmon: %s reset to %s/%s" % \
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,
295 def update(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, data):
297 Update byte counts and check if byte limits have been
301 # Query Node Manager for max rate overrides
302 self.updateSliceAttributes(data)
304 # Prepare message parameters from the template
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)}
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
320 new_maxrate = self.MaxRate
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)
330 logger.log("bwmon: %(slice)s %(class)s " \
331 "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % \
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)
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
347 new_maxi2rate = self.Maxi2Rate
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)
357 logger.log("bwmon: %(slice)s %(class)s " \
358 "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % params)
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)
366 if new_maxrate != runningmaxrate or new_maxi2rate != runningmaxi2rate:
367 bwlimit.set(xid = self.xid, maxrate = new_maxrate, maxexemptrate = new_maxi2rate)
370 if message and self.emailed == False:
371 subject = "pl_mom capped bandwidth of slice %(slice)s on %(hostname)s" % params
373 logger.log("bwmon: "+ subject)
374 logger.log("bwmon: "+ message + (footer % params))
377 slicemail(self.name, subject, message + (footer % params))
379 def GetSlivers(data):
387 default_ThreshKByte,\
389 default_Threshi2KByte,\
398 f = open(datafile, "r+")
400 logger.log("bwmon: Loading %s" % datafile)
401 (version, slices) = pickle.load(f)
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))
408 version = "$Id: bwmon.py,v 1.20 2007/01/10 16:51:04 faiyaza Exp $"
411 # Get/set special slice IDs
412 root_xid = bwlimit.get_xid("root")
413 default_xid = bwlimit.get_xid("default")
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)
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)
424 # Get running slivers. {xid: name}
425 for sliver in data['slivers']:
426 live[bwlimit.get_xid(sliver['name'])] = sliver['name']
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)
435 # Get actual running values from tc.
436 # Update slice totals and bandwidth.
437 for params in bwlimit.get():
440 minexemptrate, maxexemptrate,
441 usedbytes, usedi2bytes) = params
443 # Ignore root and default buckets
444 if xid == root_xid or xid == default_xid:
447 name = bwlimit.get_slice(xid)
449 # Orphaned (not associated with a slice) class
453 # Monitor only the specified slices
454 if names and name not in names:
456 #slices is populated from the pickle file
457 #xid is populated from bwlimit (read from /etc/passwd)
458 if slices.has_key(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)
469 slice.update(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
471 # Just in case. Probably (hopefully) this will never happen.
472 # New slice, initialize state
474 logger.log("bwmon: New Slice %s" % name)
475 slice = slices[xid] = Slice(xid, name, data)
476 slice.reset(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
479 dead = Set(slices.keys()) - Set(live.keys())
484 logger.log("bwmon: Saving %s" % datafile)
485 f = open(datafile, "w")
486 pickle.dump((version, slices), f)
490 #def GetSlivers(data):
491 # for sliver in data['slivers']:
492 # if sliver.has_key('attributes'):
494 # for attribute in sliver['attributes']:
495 # if attribute['name'] == "KByteThresh": print attribute['value']
497 def start(options, config):