| 1 |
# -*- Python -*- |
| 2 |
|
| 3 |
"""Example of rate-limiting your web server. |
| 4 |
|
| 5 |
Caveat emptor: While the transfer rates imposed by this mechanism will |
| 6 |
look accurate with wget's rate-meter, don't forget to examine your network |
| 7 |
interface's traffic statistics as well. The current implementation tends |
| 8 |
to create lots of small packets in some conditions, and each packet carries |
| 9 |
with it some bytes of overhead. Check to make sure this overhead is not |
| 10 |
costing you more bandwidth than you are saving by limiting the rate! |
| 11 |
""" |
| 12 |
|
| 13 |
# for picklability |
| 14 |
import shaper |
| 15 |
|
| 16 |
from twisted.protocols import htb |
| 17 |
|
| 18 |
serverFilter = htb.HierarchicalBucketFilter() |
| 19 |
serverBucket = htb.Bucket() |
| 20 |
|
| 21 |
# Cap total server traffic at 20 kB/s |
| 22 |
serverBucket.maxburst = 20000 |
| 23 |
serverBucket.rate = 20000 |
| 24 |
|
| 25 |
serverFilter.buckets[None] = serverBucket |
| 26 |
|
| 27 |
# Web service is also limited per-host: |
| 28 |
|
| 29 |
|
| 30 |
class WebClientBucket(htb.Bucket): |
| 31 |
# Your first 10k is free |
| 32 |
maxburst = 10000 |
| 33 |
# One kB/s thereafter. |
| 34 |
rate = 1000 |
| 35 |
|
| 36 |
|
| 37 |
webFilter = htb.FilterByHost(serverFilter) |
| 38 |
webFilter.bucketFactory = shaper.WebClientBucket |
| 39 |
|
| 40 |
servertype = "web" # "chargen" |
| 41 |
|
| 42 |
if servertype == "web": |
| 43 |
from twisted.web import server, static |
| 44 |
|
| 45 |
site = server.Site(static.File("/var/www")) |
| 46 |
site.protocol = htb.ShapedProtocolFactory(site.protocol, webFilter) |
| 47 |
elif servertype == "chargen": |
| 48 |
from twisted.internet import protocol |
| 49 |
from twisted.protocols import wire |
| 50 |
|
| 51 |
site = protocol.ServerFactory() |
| 52 |
site.protocol = htb.ShapedProtocolFactory(wire.Chargen, webFilter) |
| 53 |
# site.protocol = wire.Chargen |
| 54 |
|
| 55 |
from twisted.internet import reactor |
| 56 |
|
| 57 |
reactor.listenTCP(8000, site) |
| 58 |
reactor.run() |