Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bandwidth throttling using Twisted

I'm trying to set speed limits on downloading/uploading files and found that twisted provides twisted.protocols.policies.ThrottlingFactory to handle this job, but I can't get it right. I set readLimit and writeLimit, but file is still downloading on a maximum speed. What am I doing wrong?

from twisted.protocols.basic import FileSender
from twisted.protocols.policies import ThrottlingFactory
from twisted.web import server, resource
from twisted.internet import reactor
import os

class DownloadPage(resource.Resource):
    isLeaf = True

    def __init__(self, producer):
        self.producer = producer

    def render(self, request):
        size = os.stat(somefile).st_size
        request.setHeader('Content-Type', 'application/octet-stream')
        request.setHeader('Content-Length', size)
        request.setHeader('Content-Disposition', 'attachment; filename="' + somefile + '"')
        request.setHeader('Accept-Ranges', 'bytes')

        fp = open(somefile, 'rb')
        d = self.producer.beginFileTransfer(fp, request)

        def err(error):
            print "error %s", error

        def cbFinished(ignored):
            fp.close()
            request.finish()
        d.addErrback(err).addCallback(cbFinished)

        return server.NOT_DONE_YET


producer = FileSender()
root_resource = resource.Resource()
root_resource.putChild('download', DownloadPage(producer))
site = server.Site(root_resource)
tsite = ThrottlingFactory(site, readLimit=10000, writeLimit=10000)
tsite.protocol.producer = producer
reactor.listenTCP(8080, tsite)
reactor.run()

UPDATE

So sometime after I run it:

2012-10-25 09:17:03+0600 [-] Unhandled Error
Traceback (most recent call last):
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/application/app.py", line 402, in startReactor
        self.config, oldstdout, oldstderr, self.profiler, reactor)
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/application/app.py", line 323, in runReactorWithLogging
        reactor.run()
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/internet/base.py", line 1169, in run
        self.mainLoop()
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/internet/base.py", line 1178, in mainLoop
        self.runUntilCurrent()
    --- <exception caught here> ---
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/internet/base.py", line 800, in runUntilCurrent
        call.func(*call.args, **call.kw)
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/protocols/policies.py", line 334, in unthrottleWrites
        p.unthrottleWrites()
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/protocols/policies.py", line 225, in unthrottleWrites
        self.producer.resumeProducing()
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/protocols/basic.py", line 919, in resumeProducing
        self.consumer.unregisterProducer()
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/web/http.py", line 811, in unregisterProducer
        self.transport.unregisterProducer()
      File "/home/chambylov/environments/transfer/local/lib/python2.7/site-packages/twisted/protocols/policies.py", line 209, in unregisterProducer
        del self.producer
    exceptions.AttributeError: ThrottlingProtocol instance has no attribute 'producer'

I see that I'm not supposed to assign producer like I do know tsite.protocol.producer = producer, I'm new to Twisted and I don't know how to do that another way.

like image 887
dan.ch Avatar asked Oct 24 '12 10:10

dan.ch


2 Answers

Every producer needs (eventually) to be registered with whatever you want to consume the data. I don't see registration happening anywhere here. Maybe that is the issue you are having?

Twisted has been used on some big-time projects like Friendster, but all the callbacks do not sit well with the usual way I write in python (and I have some experience with functional programming). I switched to gevent.

If you are working with gevent libraries, many of the details (callbacks/generators that provide the asynchronous functionality) are abstracted out, so that you can typically get away with just monkey patching your code and writing it in the usual object-oriented style you are used to. If you are working on a project with anyone unfamiliar with a callback-heavy language like js/lisp, I bet they will appreciate gevent over twisted.

like image 62
egbutter Avatar answered Nov 02 '22 04:11

egbutter


As egbutter said, you have to register a producer. So instead of this:

tsite.protocol.producer = producer

you have to call a registerProducer method explicitly:

tsite.protocol.registerProducer( ... )

or, if you're using FileSender as a producer, call its beginFileTransfer method, in our case:

file_to_send = open( ... )
producer.beginFileTransfer(file_to_send, tsite.protocol)
like image 29
Oleksandr Fedorov Avatar answered Nov 02 '22 03:11

Oleksandr Fedorov