From 11017902be8bfb33d38c773f24bffe33cc741e7f Mon Sep 17 00:00:00 2001 From: Yun Xu Date: Mon, 15 Jan 2018 11:23:49 -0800 Subject: [PATCH] signal handling --- sanic/server.py | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/sanic/server.py b/sanic/server.py index e9790dae..2c549be2 100644 --- a/sanic/server.py +++ b/sanic/server.py @@ -20,9 +20,10 @@ from httptools import HttpRequestParser from httptools.parser.errors import HttpParserError try: - import uvloop as async_loop + import uvloop + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: - async_loop = asyncio + pass from sanic.log import logger, access_logger from sanic.response import HTTPResponse @@ -509,11 +510,11 @@ def serve(host, port, request_handler, error_handler, before_start=None, request_timeout=60, response_timeout=60, keep_alive_timeout=5, ssl=None, sock=None, request_max_size=None, reuse_port=False, loop=None, protocol=HttpProtocol, backlog=100, - register_sys_signals=True, run_async=False, connections=None, - signal=Signal(), request_class=None, access_log=True, - keep_alive=True, is_request_stream=False, router=None, - websocket_max_size=None, websocket_max_queue=None, state=None, - graceful_shutdown_timeout=15.0): + register_sys_signals=True, run_multiple=False, run_async=False, + connections=None, signal=Signal(), request_class=None, + access_log=True, keep_alive=True, is_request_stream=False, + router=None, websocket_max_size=None, websocket_max_queue=None, + state=None, graceful_shutdown_timeout=15.0): """Start asynchronous HTTP Server on an individual process. :param host: Address to host on @@ -547,7 +548,10 @@ def serve(host, port, request_handler, error_handler, before_start=None, :return: Nothing """ if not run_async: - loop = async_loop.new_event_loop() + # create new event_loop after fork + asyncio.get_event_loop().close() + + loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) if debug: @@ -605,7 +609,8 @@ def serve(host, port, request_handler, error_handler, before_start=None, # Register signals for graceful termination if register_sys_signals: - for _signal in (SIGINT, SIGTERM): + _singals = (SIGTERM,) if run_multiple else (SIGINT, SIGTERM) + for _signal in _singals: try: loop.add_signal_handler(_signal, loop.stop) except NotImplementedError: @@ -668,6 +673,7 @@ def serve_multiple(server_settings, workers): :return: """ server_settings['reuse_port'] = True + server_settings['run_multiple'] = True # Handling when custom socket is not provided. if server_settings.get('sock') is None: @@ -682,7 +688,7 @@ def serve_multiple(server_settings, workers): def sig_handler(signal, frame): logger.info("Received signal %s. Shutting down.", Signals(signal).name) for process in processes: - os.kill(process.pid, SIGINT) + os.kill(process.pid, SIGTERM) signal_func(SIGINT, lambda s, f: sig_handler(s, f)) signal_func(SIGTERM, lambda s, f: sig_handler(s, f))