~justin-fathomdb/nova/justinsb-openstack-api-volumes

« back to all changes in this revision

Viewing changes to vendor/Twisted-10.0.0/doc/core/examples/shaper.py

  • Committer: Jesse Andrews
  • Date: 2010-05-28 06:05:26 UTC
  • Revision ID: git-v1:bf6e6e718cdc7488e2da87b21e258ccc065fe499
initial commit

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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
from twisted.protocols import htb
 
14
# for picklability
 
15
import shaper
 
16
 
 
17
serverFilter = htb.HierarchicalBucketFilter()
 
18
serverBucket = htb.Bucket()
 
19
 
 
20
# Cap total server traffic at 20 kB/s
 
21
serverBucket.maxburst = 20000
 
22
serverBucket.rate = 20000
 
23
 
 
24
serverFilter.buckets[None] = serverBucket
 
25
 
 
26
# Web service is also limited per-host:
 
27
class WebClientBucket(htb.Bucket):
 
28
    # Your first 10k is free
 
29
    maxburst = 10000
 
30
    # One kB/s thereafter.
 
31
    rate = 1000
 
32
 
 
33
webFilter = htb.FilterByHost(serverFilter)
 
34
webFilter.bucketFactory = shaper.WebClientBucket
 
35
 
 
36
servertype = "web" # "chargen"
 
37
 
 
38
if servertype == "web":
 
39
    from twisted.web import server, static
 
40
    site = server.Site(static.File("/var/www"))
 
41
    site.protocol = htb.ShapedProtocolFactory(site.protocol, webFilter)
 
42
elif servertype == "chargen":
 
43
    from twisted.protocols import wire
 
44
    from twisted.internet import protocol
 
45
 
 
46
    site = protocol.ServerFactory()
 
47
    site.protocol = htb.ShapedProtocolFactory(wire.Chargen, webFilter)
 
48
    #site.protocol = wire.Chargen
 
49
 
 
50
from twisted.internet import reactor
 
51
reactor.listenTCP(8000, site)
 
52
reactor.run()