Hello everyone! I wrote Twisted-based TCP server which is capable of running in several relatively different modes. When mode switch is needed, I would like the server to restart itself by some means, for it to read new mode from configuration file and create corresponding implementation. Also I wanted the restart to occur without re-running twistd process, because it seems to me more appropriate for Linux daemon.
So I organized code in the .tac file in the following way:
# imports...
CONFIG_FILE_NAME = "master.conf"
def main():
print("Entered main")
config = ConfigParser.RawConfigParser()
config.read(CONFIG_FILE_NAME)
context = MasterPlayerImplementationContext()
context.config_file_name = CONFIG_FILE_NAME
context.reactor = reactor
print("Creating internet.TCPServer...")
master_player_service = internet.TCPServer(config.getint(shared_types.CONFIG_SECTION_GENERAL,
shared_types.CONFIG_PARAMETER_SERVER_PORT),
pb.PBServerFactory(MasterPlayer(context)),
50, config.get(shared_types.CONFIG_SECTION_GENERAL,
shared_types.CONFIG_PARAMETER_SERVER_IP))
def stop_service_succeeded(arg):
print("Service stop succeeded! arg is {}. Restarting...".format(arg))
main()
def stop_service_failed(failure):
print("Service stop failed! failure is {}. Trying to restart nevertheless...".format(failure))
main()
def restart_callback():
print("Entered restart_callback")
deferred = defer.maybeDeferred(master_player_service.disownServiceParent)
deferred.addCallback(stop_service_succeeded).addErrback(stop_service_failed)
print("Leaving restart_callback")
context.restart_callback = restart_callback
master_player_service.setServiceParent(service_collection)
print("Exiting main")
application = service.Application("master_player")
service_collection = service.IServiceCollection(application)
main()
print("After main")
When the server is in need of restarting itself, it just calls the context.restart_callback function and restart occurs immediately.
My experience in Linux, Python and Twisted is rather modest, so I would like to consult here to determine whether solution chosen is the right one.