twistedtwisted.internet

Getting ReactorNotRestartable error when though I am checking if the reactor is already running


Code:

def hook(ui, repo, hooktype, node=None, source=None, **kwargs):

    from buildbot.clients import sendchange
    from twisted.internet import defer, reactor

    for master in masters:
        s = sendchange.Sender(master, auth=(username, password))
        d = defer.Deferred()
        reactor.callLater(0, d.callback, None)

        for rev in range(start, end):
            # some code here
            d.addCallback(dummy, "calling dummy")

    def _printSuccess(res):
        pass

    def _printFailure(why):
        pass

    d.addCallbacks(_printSuccess, _printFailure)
    d.addBoth(lambda _: reactor.stop())
    try:
        logger.info("before starting reactor")
        if not reactor.running:
            reactor.run()
            logger.info("after reactor.run")
        else:
            logger.info("reactor is already running")

    except Exception as e:
        logger.info("in exception")
        logger.exception("exception occurred")
        if reactor.running:
            reactor.stop()


def dummy(content):
    with open("/home/rhodecode/hg_buildbot_hooks/dummy.txt", "w") as f:
        f.write("dummy" + "\n")
        f.write("{}".format(content))

Error:

File "/home/rhodecode/hg_buildbot_hooks/hooks.py", line 291, in hook
    reactor.run()
File "/home/rhodecode/buildbot_venv/lib/python2.7/site-packages/twisted/internet/base.py", line 1266, in run
    self.startRunning(installSignalHandlers=installSignalHandlers)
File "/home/rhodecode/buildbot_venv/lib/python2.7/site-packages/twisted/internet/base.py", line 1246, in startRunning
    ReactorBase.startRunning(self)
File "/home/rhodecode/buildbot_venv/lib/python2.7/site-packages/twisted/internet/base.py", line 754, in startRunning
    raise error.ReactorNotRestartable()
ReactorNotRestartable

Solution

  • I was facing this problem at two different places for two different reasons

    1. The reactor as getting started by python main thread but a non-main thread was calling reactor.stop(), and there was no reactor running to stop. ref: reactor.callFromThread(reactor.stop)

    2. Reactor as reactor.run() was getting called from non-main thread and it as not event getting started. ref: reactor.run(installSignalHandlers=False)