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.6 2007/02/12 23:05:58 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. in KBit/s
58 default_MaxRate = int(bwlimit.get_bwcap() / 1000)
59 default_Maxi2Rate = int(bwlimit.bwmax / 1000)
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 = 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))
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
281 maxrate = self.MaxRate * 1000
282 maxi2rate = self.Maxi2Rate * 1000
284 if (self.MaxRate != runningmaxrate) or (self.Maxi2Rate != runningmaxi2rate):
285 logger.log("bwmon: %s reset to %s/%s" % \
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,
296 def update(self, runningmaxrate, runningmaxi2rate, usedbytes, usedi2bytes, data):
298 Update byte counts and check if byte limits have been
302 # Query Node Manager for max rate overrides
303 self.updateSliceAttributes(data)
305 # Prepare message parameters from the template
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)}
313 if usedbytes >= (self.bytes + (self.ThreshKByte * 1024)):
314 maxbyte = self.MaxKByte * 1024
315 bytesused = bytes - 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
321 new_maxrate = self.MaxRate * 1000
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)
331 logger.log("bwmon: %(slice)s %(class)s " \
332 "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % \
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)
340 if usedi2bytes >= (self.i2bytes + (self.Threshi2KByte * 1024)):
341 maxi2byte = self.Maxi2KByte * 1024
342 i2bytesused = i2bytes - 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
348 new_maxi2rate = self.Maxi2Rate * 1000
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)
358 logger.log("bwmon: %(slice)s %(class)s " \
359 "%(bytes)s of %(limit)s (%(new_maxrate)s/s maxrate)" % params)
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)
367 if new_maxrate != runningmaxrate or new_maxi2rate != runningmaxi2rate:
368 bwlimit.set(xid = self.xid, maxrate = new_maxrate, maxexemptrate = new_maxi2rate)
371 if message and self.emailed == False:
372 subject = "pl_mom capped bandwidth of slice %(slice)s on %(hostname)s" % params
374 logger.log("bwmon: "+ subject)
375 logger.log("bwmon: "+ message + (footer % params))
378 slicemail(self.name, subject, message + (footer % params))
380 def GetSlivers(data):
388 default_ThreshKByte,\
390 default_Threshi2KByte,\
399 f = open(datafile, "r+")
401 logger.log("bwmon: Loading %s" % datafile)
402 (version, slices) = pickle.load(f)
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))
409 version = "$Id: bwmon.py,v 1.6 2007/02/12 23:05:58 faiyaza Exp $"
412 # Get/set special slice IDs
413 root_xid = bwlimit.get_xid("root")
414 default_xid = bwlimit.get_xid("default")
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)
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)
425 # Get running slivers. {xid: name}
426 for sliver in data['slivers']:
427 live[bwlimit.get_xid(sliver['name'])] = sliver['name']
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)
437 # Get actual running values from tc.
438 # Update slice totals and bandwidth.
439 for params in bwlimit.get():
442 minexemptrate, maxexemptrate,
443 usedbytes, usedi2bytes) = params
445 # Ignore root and default buckets
446 if xid == root_xid or xid == default_xid:
449 name = bwlimit.get_slice(xid)
451 # Orphaned (not associated with a slice) class
455 # Monitor only the specified slices
456 if names and name not in names:
458 #slices is populated from the pickle file
459 #xid is populated from bwlimit (read from /etc/passwd)
460 if slices.has_key(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)
471 slice.update(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
473 # Just in case. Probably (hopefully) this will never happen.
474 # New slice, initialize state
476 logger.log("bwmon: New Slice %s" % name)
477 slice = slices[xid] = Slice(xid, name, data)
478 slice.reset(maxrate, maxexemptrate, usedbytes, usedi2bytes, data)
481 dead = Set(slices.keys()) - Set(live.keys())
483 if xid == root_xid or xid == default_xid:
488 logger.log("bwmon: Saving %s" % datafile)
489 f = open(datafile, "w")
490 pickle.dump((version, slices), f)
494 #def GetSlivers(data):
495 # for sliver in data['slivers']:
496 # if sliver.has_key('attributes'):
498 # for attribute in sliver['attributes']:
499 # if attribute['name'] == "KByteThresh": print attribute['value']
501 def start(options, config):