pythontwisteddaemontwistd

twisted python daemonization and port bindings


I am using the following script from the Twisted tutorial (with slight modification):

from twisted.application import internet, service
from twisted.internet import reactor, protocol, defer
from twisted.protocols import basic
from twisted.web import client

class FingerProtocol(basic.LineReceiver):

    def lineReceived(self, user):
        d = self.factory.getUser(user)

        def onError(err):
            return "Internal server error"
        d.addErrback(onError)

        def writeResponse(message):
            self.transport.write(message + "\r\n")
            self.transport.loseConnection()
        d.addCallback(writeResponse)

class FingerFactory(protocol.ServerFactory):
    protocol = FingerProtocol

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

    def getUser(self, user):
        return client.getPage(self.prefix + user)

application = service.Application('finger', uid=1, gid=1)
factory = FingerFactory(prefix="http://livejournal.com/~")
internet.TCPServer(7979, factory).setServiceParent(
    service.IServiceCollection(application))

which I save as finger_daemon.tac and run with

twistd -y finger_daemon.tac \ 
    -l /home/me/twisted/finger.log \
    --pidfile=/home/me/twisted/finger.pid

but of course it won't bind to 79, since it's a privileged port. I tried also running with sudo, no difference there.

I then tried changing the TCPServer port to 7979 and then connecting to the daemon once running with

telnet 127.0.0.1 7979

and I get Connection Refused error. What's going on here specifically? How is daemonizing supposed to work in Twisted?


Solution

  • When I run this code, I see the following log message:

    2013-10-02 23:50:34-0700 [-] failed to set uid/gid 1/1 (are you root?) -- exiting.
    

    and then twistd exits. So you'd need to do sudo twistd and then that adds a whole bunch of python path management problems...

    Why are you setting the uid and gid arguments? You're trying to run it as the daemon user? You don't need to do that in order to daemonize. Just removing the uid=1, gid=1 arguments to Application makes it work for me.