Skip to content

Commit

Permalink
add: monkey patch to resolve sanic-org/sanic#1471
Browse files Browse the repository at this point in the history
  • Loading branch information
cfhamlet committed Jan 16, 2019
1 parent 7502f89 commit b5c92e0
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
60 changes: 60 additions & 0 deletions src/os_sanic/monkey_patch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os
import signal
from contextlib import contextmanager
from time import sleep
from unittest import mock

from sanic import reloader_helpers
from sanic.reloader_helpers import (_iter_module_files, kill_process_children,
restart_with_reloader)


@contextmanager
def patch():
with mock.patch.object(reloader_helpers, 'watchdog', patch_reloader_helpers_watchdog):
yield


def patch_reloader_helpers_watchdog(sleep_interval):
mtimes = {}
worker_process = []
signal.signal(
signal.SIGTERM, lambda *args: kill_program_completly(
worker_process)
)
signal.signal(
signal.SIGINT, lambda *args: kill_program_completly(
worker_process)
)

worker_process.append(restart_with_reloader())
while True:
for filename in _iter_module_files():
try:
mtime = os.stat(filename).st_mtime
except OSError:
continue

old_time = mtimes.get(filename)
if old_time is None:
mtimes[filename] = mtime
continue
elif mtime > old_time:
wp = worker_process.pop()
kill_process_children(wp.pid)
wp.terminate()
worker_process.append(restart_with_reloader())
mtimes[filename] = mtime
break

sleep(sleep_interval)


def kill_program_completly(proc):
if not proc:
kill_process_children(os.getpid())
os._exit(0)
proc = proc.pop()
kill_process_children(proc.pid)
proc.terminate()
os._exit(0)
4 changes: 3 additions & 1 deletion src/os_sanic/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from os_sanic.config import SANIC_ENV_PREFIX, create_sanic_config
from os_sanic.log import LOGGING_CONFIG_PATCH, logger
from os_sanic.utils import deep_update
from os_sanic.monkey_patch import patch


class Server(object):
Expand Down Expand Up @@ -45,7 +46,8 @@ def _run_args(self):
return run_args

def run(self):
self.sanic.run(**self._run_args())
with patch():
self.sanic.run(**self._run_args())

@classmethod
def create(cls, app='os-sanic', config=None, env_prefix=SANIC_ENV_PREFIX, log_config=None):
Expand Down

0 comments on commit b5c92e0

Please sign in to comment.