3 # Bandwidth limit module for PlanetLab nodes. The intent is to use the
4 # Hierarchical Token Bucket (HTB) queueing discipline (qdisc) to allow
5 # slices to fairly share access to available node bandwidth. We
6 # currently define three classes of "available node bandwidth":
8 # 1. Available hardware bandwidth (bwmax): The maximum rate of the
11 # 2. Available capped bandwidth (bwcap): The maximum rate allowed to
12 # non-exempt destinations. By default, equal to bwmax, but may be
15 # 3. Available uncapped ("exempt") bandwidth: The difference between
16 # bwmax and what is currently being used of bwcap, or the maximum rate
17 # allowed to destinations exempt from caps (e.g., Internet2).
19 # All three classes of bandwidth are fairly shared according to the
20 # notion of "shares". For instance, if the node is capped at 5 Mbps,
21 # there are N slices, and each slice has 1 share, then each slice
22 # should get at least 5/N Mbps of bandwidth. How HTB is implemented
23 # makes this statement a little too simplistic. What it really means
24 # is that during any single time period, only a certain number of
25 # bytes can be sent onto the wire. Each slice is guaranteed that at
26 # least some small number of its bytes will be sent. Whatever is left
27 # over from the budget, is split in proportion to the number of shares
30 # Even if the node is not capped at a particular limit (bwcap ==
31 # bwmax), this module enforces fair share access to bwmax. Also, if
32 # the node is capped at a particular limit, rules may optionally be
33 # defined that classify certain packets into the "exempt" class. This
34 # class receives whatever bandwidth is leftover between bwcap and
35 # bwmax; slices fairly share this bandwidth as well.
37 # The root context is exempt from sharing and can send as much as it
42 # 1. http://lartc.org/howto for how to use tc
43 # 2. http://luxik.cdi.cz/~devik/qos/htb/ for info on HTB
45 # Andy Bavier <acb@cs.princeton.edu>
46 # Mark Huang <mlhuang@cs.princeton.edu>
47 # Copyright (C) 2006 The Trustees of Princeton University
49 # $Id: bwlimit.py,v 1.15 2007/02/07 04:21:11 mlhuang Exp $
52 import sys, os, re, getopt
57 # Where the tc binary lives
66 # bwmin should be small enough that it can be considered negligibly
67 # slow compared to the hardware. 8 bits/second appears to be the
68 # smallest value supported by tc.
71 # bwmax should be large enough that it can be considered at least as
72 # fast as the hardware.
73 bwmax = 1000*1000*1000
75 # quantum is the maximum number of bytes that can be borrowed by a
76 # share (or slice, if each slice gets 1 share) in one time period
77 # (with HZ=1000, 1 ms). If multiple slices are competing for bandwidth
78 # above their guarantees, and each is attempting to borrow up to the
79 # node bandwidth cap, quantums control how the excess bandwidth is
80 # distributed. Slices with 2 shares will borrow twice the amount in
81 # one time period as slices with 1 share, so averaged over time, they
82 # will get twice as much of the excess bandwidth. The value should be
83 # as small as possible and at least 1 MTU. By default, it would be
84 # calculated as bwmin/10, but since we use such small a value for
85 # bwmin, it's better to just set it to a value safely above 1 Ethernet
89 # cburst is the maximum number of bytes that can be burst onto the
90 # wire in one time period (with HZ=1000, 1 ms). If multiple slices
91 # have data queued for transmission, cbursts control how long each
92 # slice can have the wire for. If not specified, it is set to the
93 # smallest possible value that would enable the slice's "ceil" rate
94 # (usually the node bandwidth cap), to be reached if a slice was able
95 # to borrow enough bandwidth to do so. For now, it's unclear how or if
96 # to relate this to the notion of shares, so just let tc set the
100 # There is another parameter that controls how bandwidth is allocated
101 # between slices on nodes that is outside the scope of HTB. We enforce
102 # a 16 GByte/day total limit on each slice, which works out to about
103 # 1.5mbit. If a slice exceeds this byte limit before the day finishes,
104 # it is capped at (i.e., its "ceil" rate is set to) the smaller of the
105 # node bandwidth cap or 1.5mbit. pl_mom is in charge of enforcing this
106 # rule and executes this script to override "ceil".
108 # We support multiple bandwidth limits, by reserving the top nibble of
109 # the minor classid to be the "subclassid". Theoretically, we could
110 # support up to 15 subclasses, but for now, we only define two: the
111 # "default" subclass 1:10 that is capped at the node bandwidth cap (in
112 # this example, 5mbit) and the "exempt" subclass 1:20 that is capped
113 # at bwmax (i.e., not capped). The 1:1 parent class exists only to
114 # make the borrowing model work. All bandwidth above minimum
115 # guarantees is fairly shared (in this example, slice 2 is guaranteed
116 # at least 1mbit in addition to fair access to the rest), subject to
117 # the restrictions of the class hierarchy: namely, that the total
118 # bandwidth to non-exempt destinations should not exceed the node
124 # ______________|_____________
126 # 1:10 (8bit, 5mbit) 1:20 (8bit, 1gbit)
128 # 1:1000 (8bit, 5mbit), 1:2000 (8bit, 1gbit),
129 # 1:1001 (8bit, 5mbit), 1:2001 (8bit, 1gbit),
130 # 1:1002 (1mbit, 5mbit), 1:2002 (1mbit, 1gbit),
132 # 1:1FFF (8bit, 5mbit) 1:2FFF (8bit, 1gbit)
134 default_minor = 0x1000
135 exempt_minor = 0x2000
137 # root_xid is for the root context. The root context is exempt from
138 # fair sharing in both the default and exempt subclasses. The root
139 # context gets 5 shares by default.
143 # default_xid is for unclassifiable packets. Packets should not be
144 # classified here very often. They can be if a slice's HTB classes are
145 # deleted before its processes are. Each slice gets 1 share by
150 # See tc_util.c and http://physics.nist.gov/cuu/Units/binary.html. Be
151 # warned that older versions of tc interpret "kbps", "mbps", "mbit",
152 # and "kbit" to mean (in this system) "kibps", "mibps", "mibit", and
153 # "kibit" and that if an older version is installed, all rates will
154 # be off by a small fraction.
162 "gibit": 1024*1024*1024,
164 "tibit": 1024*1024*1024*1024,
165 "tbit": 1000000000000,
169 "mibps": 8*1024*1024,
171 "gibps": 8*1024*1024*1024,
173 "tibps": 8*1024*1024*1024*1024,
174 "tbps": 8000000000000
180 Parses an integer or a tc rate string (e.g., 1.5mbit) into bits/second
185 m = re.match(r"([0-9.]+)(\D*)", s)
188 suffix = m.group(2).lower()
189 if suffixes.has_key(suffix):
190 return int(float(m.group(1)) * suffixes[suffix])
194 def format_bytes(bytes, si = True):
196 Formats bytes into a string
201 # Officially, a kibibyte
204 if bytes >= (kilo * kilo * kilo):
205 return "%.1f GB" % (bytes / (kilo * kilo * kilo))
206 elif bytes >= 1000000:
207 return "%.1f MB" % (bytes / (kilo * kilo))
209 return "%.1f KB" % (bytes / kilo)
211 return "%.0f bytes" % bytes
213 def format_tc_rate(rate):
215 Formats a bits/second rate into a tc rate string
218 if rate >= 1000000000 and (rate % 1000000000) == 0:
219 return "%.0fgbit" % (rate / 1000000000.)
220 elif rate >= 1000000 and (rate % 1000000) == 0:
221 return "%.0fmbit" % (rate / 1000000.)
223 return "%.0fkbit" % (rate / 1000.)
225 return "%.0fbit" % rate
228 # Parse /etc/planetlab/bwcap (or equivalent)
229 def read_bwcap(bwcap_file):
232 fp = open(bwcap_file, "r")
233 line = fp.readline().strip()
235 bwcap = get_tc_rate(line)
243 def get_bwcap(dev = dev):
245 Get the current (live) value of the node bandwidth cap
248 state = tc("-d class show dev %s" % dev)
249 base_re = re.compile(r"class htb 1:10 parent 1:1 .*ceil ([^ ]+) .*")
250 base_classes = filter(None, map(base_re.match, state))
253 if len(base_classes) > 1:
254 raise Exception, "unable to get current bwcap"
255 return get_tc_rate(base_classes[0].group(1))
260 Get slice name ("princeton_mlh") from slice xid (500)
265 if xid == default_xid:
268 return pwd.getpwuid(xid).pw_name
276 Get slice xid ("princeton_mlh") from slice name ("500" or "princeton_mlh")
281 if slice == "default":
288 return pwd.getpwnam(slice).pw_uid
294 def run(cmd, input = None):
296 Shortcut for running a shell command
301 sys.stderr.write("Executing: " + cmd + "\n")
303 fileobj = os.popen(cmd, "r")
304 output = fileobj.readlines()
306 fileobj = os.popen(cmd, "w")
309 if fileobj.close() is None:
318 Shortcut for running a tc command
321 return run(TC + " " + cmd)
326 Turn off all queing. Stops all slice HTBS and reverts to pfifo_fast (the default).
328 tc("qdisc del dev %s root" % dev)
331 def init(dev = dev, bwcap = bwmax):
333 (Re)initialize the bandwidth limits on this node
336 # Load the module used to manage exempt classes
337 run("/sbin/modprobe ip_set_iphash")
339 # Save current settings
340 paramslist = get(None, dev)
342 # Delete root qdisc 1: if it exists. This will also automatically
343 # delete any child classes.
344 for line in tc("qdisc show dev %s" % dev):
345 # Search for the root qdisc 1:
346 m = re.match(r"qdisc htb 1:", line)
348 tc("qdisc del dev %s root handle 1:" % dev)
351 # Initialize HTB. The "default" clause specifies that if a packet
352 # fails classification, it should go into the class with handle
354 tc("qdisc add dev %s root handle 1: htb default %x" % \
355 (dev, default_minor | default_xid))
357 # Set up a parent class from which all subclasses borrow.
358 tc("class add dev %s parent 1: classid 1:1 htb rate %dbit" % \
361 # Set up a subclass that represents the node bandwidth cap. We
362 # allow each slice to borrow up to this rate, so it is also
363 # usually the "ceil" rate for each slice.
364 tc("class add dev %s parent 1:1 classid 1:10 htb rate %dbit ceil %dbit" % \
367 # Set up a subclass that represents "exemption" from the node
368 # bandwidth cap. Once the node bandwidth cap is reached, bandwidth
369 # to exempt destinations can still be fairly shared up to bwmax.
370 tc("class add dev %s parent 1:1 classid 1:20 htb rate %dbit ceil %dbit" % \
373 # Set up the root class (and tell VNET what it is). Packets sent
374 # by root end up here and are capped at the node bandwidth
376 #on(root_xid, dev, share = root_share)
378 # file("/proc/sys/vnet/root_class", "w").write("%d" % ((1 << 16) | default_minor | root_xid))
382 # Set up the default class. Packets that fail classification end
384 on(default_xid, dev, share = default_share)
386 # Restore old settings
389 minexemptrate, maxexemptrate,
390 bytes, exemptbytes) in paramslist:
391 if xid not in (root_xid, default_xid):
392 on(xid, dev, share, minrate, maxrate, minexemptrate, maxexemptrate)
395 def get(xid = None, dev = dev):
397 Get the bandwidth limits and current byte totals for a
398 particular slice xid as a tuple (xid, share, minrate, maxrate,
399 minexemptrate, maxexemptrate, bytes, exemptbytes), or all classes
400 as a list of such tuples.
412 # class htb 1:1000 parent 1:10 leaf 1000: prio 0 quantum 8000 rate 8bit ceil 10000Kbit ...
413 # Sent 6851486 bytes 49244 pkt (dropped 0, overlimits 0 requeues 0)
415 # class htb 1:2000 parent 1:20 leaf 2000: prio 0 quantum 8000 rate 8bit ceil 1000Mbit ...
416 # Sent 0 bytes 0 pkt (dropped 0, overlimits 0 requeues 0)
418 for line in tc("-s -d class show dev %s" % dev):
419 # Rate parameter line
420 params = re.match(r"class htb 1:([0-9a-f]+) parent 1:(10|20)", line)
422 stats = re.match(r".* Sent ([0-9]+) bytes", line)
424 ignore = re.match(r"class htb", line)
426 if params is not None:
428 if params.group(2) == "10":
435 bytes = 'exemptbytes'
438 id = int(params.group(1), 16) & 0x0FFF;
440 if rates.has_key(id):
447 m = re.search(r"quantum (\d+)", line)
449 rate['share'] = int(m.group(1)) / quantum
453 m = re.search(r"rate (\w+)", line)
455 rate[min] = get_tc_rate(m.group(1))
459 m = re.search(r"ceil (\w+)", line)
461 rate[max] = get_tc_rate(m.group(1))
463 # Which statistics to parse
464 rate['stats'] = bytes
468 elif stats is not None:
470 rate[rate['stats']] = int(stats.group(1))
472 elif ignore is not None:
475 # Keep parsing until we get everything
476 if rate is not None and \
477 rate.has_key('min') and rate.has_key('minexempt') and \
478 rate.has_key('max') and rate.has_key('maxexempt') and \
479 rate.has_key('bytes') and rate.has_key('exemptbytes'):
480 params = (rate['id'], rate['share'],
481 rate['min'], rate['max'],
482 rate['minexempt'], rate['maxexempt'],
483 rate['bytes'], rate['exemptbytes'])
485 # Return a list of parameters
488 elif xid == rate['id']:
489 # Return the parameters for this class
496 def on(xid, dev = dev, share = None, minrate = None, maxrate = None, minexemptrate = None, maxexemptrate = None):
498 Apply specified bandwidth limit to the specified slice xid
501 # Get defaults from current state if available
510 if minexemptrate is None:
511 minexemptrate = cap[4]
512 if maxexemptrate is None:
513 maxexemptrate = cap[5]
515 # Figure out what the current node bandwidth cap is
520 share = default_share
524 minrate = get_tc_rate(minrate)
528 maxrate = get_tc_rate(maxrate)
529 if minexemptrate is None:
530 minexemptrate = minrate
532 minexemptrate = get_tc_rate(minexemptrate)
533 if maxexemptrate is None:
534 maxexemptrate = bwmax
536 maxexemptrate = get_tc_rate(maxexemptrate)
545 if minrate > maxrate:
547 if maxexemptrate < bwmin:
548 maxexemptrate = bwmin
549 if maxexemptrate > bwmax:
550 maxexemptrate = bwmax
551 if minexemptrate < bwmin:
552 minexemptrate = bwmin
553 if minexemptrate > maxexemptrate:
554 minexemptrate = maxexemptrate
556 # Set up subclasses for the slice
557 tc("class replace dev %s parent 1:10 classid 1:%x htb rate %dbit ceil %dbit quantum %d" % \
558 (dev, default_minor | xid, minrate, maxrate, share * quantum))
560 tc("class replace dev %s parent 1:20 classid 1:%x htb rate %dbit ceil %dbit quantum %d" % \
561 (dev, exempt_minor | xid, minexemptrate, maxexemptrate, share * quantum))
563 # Attach a FIFO to each subclass, which helps to throttle back
564 # processes that are sending faster than the token buckets can
566 tc("qdisc replace dev %s parent 1:%x handle %x pfifo" % \
567 (dev, default_minor | xid, default_minor | xid))
569 tc("qdisc replace dev %s parent 1:%x handle %x pfifo" % \
570 (dev, exempt_minor | xid, exempt_minor | xid))
573 def set(xid, share = None, minrate = None, maxrate = None, minexemptrate = None, maxexemptrate = None):
574 on(xid = xid, share = share,
575 minrate = minrate, maxrate = maxrate,
576 minexemptrate = minexemptrate, maxexemptrate = maxexemptrate)
579 # Remove class associated with specified slice xid. If further packets
580 # are seen from this slice, they will be classified into the default
582 def off(xid, dev = dev):
584 Remove class associated with specified slice xid. If further
585 packets are seen from this slice, they will be classified into the
586 default class 1:1FFF.
591 tc("class del dev %s classid 1:%x" % (dev, default_minor | xid))
592 tc("class del dev %s classid 1:%x" % (dev, exempt_minor | xid))
595 def exempt_init(group_name, node_ips):
597 Initialize the list of destinations exempt from the node bandwidth
601 # Check of set exists
602 set = run("/sbin/ipset -S " + group_name)
604 # Create a hashed IP set of all of these destinations
605 lines = ["-N %s iphash" % group_name]
606 add_cmd = "-A %s " % group_name
607 lines += [(add_cmd + ip) for ip in node_ips]
609 restore = "\n".join(lines) + "\n"
610 run("/sbin/ipset -R", restore)
612 # Check all hosts and add missing.
613 for nodeip in node_ips:
614 if not run("/sbin/ipset -T %s %s" % (group_name, nodeip)):
615 run("/sbin/ipset -A %s %s" % (group_name, nodeip))
619 bwcap_description = format_tc_rate(get_bwcap())
624 %s [OPTION]... [COMMAND] [ARGUMENT]...
627 -d device Network interface (default: %s)
628 -r rate Node bandwidth cap (default: %s)
629 -q quantum Share multiplier (default: %d bytes)
630 -n Print rates in numeric bits per second
631 -v Enable verbose debug messages
636 (Re)initialize all bandwidth parameters
637 on slice [share|-] [minrate|-] [maxrate|-] [minexemptrate|-] [maxexemptrate|-]
638 Set bandwidth parameter(s) for the specified slice
640 Remove all bandwidth parameters for the specified slice
642 Get all bandwidth parameters for all slices
644 Get bandwidth parameters for the specified slice
645 """ % (sys.argv[0], dev, bwcap_description, quantum)
650 global dev, quantum, verbose
656 (opts, argv) = getopt.getopt(sys.argv[1:], "d:nr:q:vh")
657 for (opt, optval) in opts:
663 bwcap = get_tc_rate(optval)
665 quantum = int(optval)
672 if argv[0] == "init" or (argv[0] == "on" and len(argv) == 1):
674 init(dev, get_tc_rate(bwcap))
676 elif argv[0] == "get" or argv[0] == "show":
679 # Show a particular slice
680 xid = get_xid(argv[1])
682 sys.stderr.write("Error: Invalid slice name or context '%s'\n" % argv[1])
684 params = get(xid, dev)
688 paramslist = [params]
691 paramslist = get(None, dev)
695 minexemptrate, maxexemptrate,
696 bytes, exemptbytes) in paramslist:
697 slice = get_slice(xid)
699 # Orphaned (not associated with a slice) class
702 print "%s %d %d %d %d %d %d %d" % \
705 minexemptrate, maxexemptrate,
708 print "%s %d %s %s %s %s %s %s" % \
710 format_tc_rate(minrate), format_tc_rate(maxrate),
711 format_tc_rate(minexemptrate), format_tc_rate(maxexemptrate),
712 format_bytes(bytes), format_bytes(exemptbytes))
716 xid = get_xid(argv[1])
718 sys.stderr.write("Error: Invalid slice name or context '%s'\n" % argv[1])
721 if argv[0] == "on" or argv[0] == "add" or argv[0] == "replace" or argv[0] == "set":
725 # ... share, minrate, maxrate, minexemptrate, maxexemptrate
726 casts = [int, get_tc_rate, get_tc_rate, get_tc_rate, get_tc_rate]
727 for i, arg in enumerate(argv[2:]):
733 args.append(casts[i](arg))
736 elif argv[0] == "off" or argv[0] == "del":
747 if __name__ == '__main__':