Search code examples
pythontwistedtwisted.application

Wait for a twisted service to start before starting another


I have written a proxy server that uses twisted's application framework. At it's core there it uses a DHT to resolve things. The DHT client takes a few seconds to start, so i want to make sure that the proxy only accepts connections after the DHT is ready.

# there is a class like 
class EntangledDHT(object):
    # connects to the dht

# create the client
dht = EntangledDHT.from_config(config)

# when it can be used this deferred fires
# i want to wait for this before creating the "real" application
dht.ready


# the proxy server, it uses the dht client
port = config.getint(section, 'port')

p = CosipProxy(host=config.get(section, 'listen'),
               port=port,
               dht=dht,
               domain=config.get(section, 'domain'))


## for twistd
application = service.Application('cosip')

serv = internet.UDPServer(port, p)
serv.setServiceParent(service.IService(application))

How do I turn the EntangledDHT into some kind of service that Twisted will wait for before starting the CosipProxy service? Is there any mechanism in twisted that does this for me? Or do I have to add a callback to dht.ready that creates the rest of the application? Thanks


Solution

  • Don't call serv.setServiceParent(service.IService(application)) right away. Instead, wait to call it in your callback to dht.ready. This will cause it to be started if the application service is already running.

    Also, it doesn't look like dht itself is an IService. It should be; or rather, the thing that calls from_config should be a service, since apparently from_config is going to kick off some connections (at least, that's what it looks like, if dht.ready is ever going to fire, in this example). Your plugin or tac file should be constructing a service, not starting a service. Nothing should happen until that first startService is called.