Skip to content

Commit

Permalink
Monkey patching tornado to backport tornadoweb/tornado#1290
Browse files Browse the repository at this point in the history
Should hopefully help with freezing/blocking issues upon first connect with the net on the Pi, more tests needed.
  • Loading branch information
foosel committed Mar 16, 2015
1 parent 1f55904 commit 57de36a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
9 changes: 2 additions & 7 deletions src/octoprint/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
import octoprint.slicing

from . import util
util.tornado.fix_ioloop_scheduling()


UI_API_KEY = ''.join('%02X' % ord(z) for z in uuid.uuid4().bytes)
Expand Down Expand Up @@ -656,13 +657,7 @@ def settings_plugin_inject_factory(name, implementation):

## Tornado initialization starts here

try:
import monotime
import time
ioloop = IOLoop(time_func=time.monotonic)
except:
import time
ioloop = IOLoop(time_func=time.time)
ioloop = IOLoop()
ioloop.install()

self._router = SockJSRouter(self._createSocketConnection, "/sockjs")
Expand Down
30 changes: 30 additions & 0 deletions src/octoprint/server/util/tornado.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,36 @@
import octoprint.util


#~~ Monkey patching


def fix_ioloop_scheduling():
"""
This monkey patches tornado's :meth:`tornado.ioloop.PeriodicCallback._schedule_next` method so it no longer
blocks for long times on slow machines (RPi) when the system time happens to change by a large amount (e.g. due to
the first ever contact to an NTP server).
Patch by @nosyjoe on Github. See this PR against tornado: https://github.com/tornadoweb/tornado/pull/1290
"""

import math

# patched implementation taken from PR
def _schedule_next(self):
if self._running:
current_time = self.io_loop.time()

if self._next_timeout <= current_time:
callback_time_sec = self.callback_time / 1000.0
self._next_timeout += (math.floor((current_time - self._next_timeout) / callback_time_sec) + 1) * callback_time_sec

self._timeout = self.io_loop.add_timeout(self._next_timeout, self._run)

# replace original implementation with patched version
import tornado.ioloop
tornado.ioloop.PeriodicCallback._schedule_next = _schedule_next


#~~ WSGI middleware


Expand Down

0 comments on commit 57de36a

Please sign in to comment.