tornado.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import asyncio
  2. import fnmatch
  3. import json
  4. import logging
  5. import threading
  6. import webbrowser
  7. from functools import partial
  8. from urllib.parse import urlparse
  9. import tornado
  10. import tornado.httpserver
  11. import tornado.ioloop
  12. import tornado.websocket
  13. from tornado.web import StaticFileHandler
  14. from tornado.websocket import WebSocketHandler
  15. from ..session import CoroutineBasedSession, ThreadBasedSession, get_session_implement, ScriptModeSession, \
  16. set_session_implement, get_session_implement_for_target, SCRIPT_MODE
  17. from ..utils import get_free_port, wait_host_port, STATIC_PATH
  18. logger = logging.getLogger(__name__)
  19. def _check_origin(origin, allowed_origins, handler: WebSocketHandler):
  20. if _is_same_site(origin, handler):
  21. return True
  22. return any(
  23. fnmatch.fnmatch(origin, patten)
  24. for patten in allowed_origins
  25. )
  26. def _is_same_site(origin, handler: WebSocketHandler):
  27. parsed_origin = urlparse(origin)
  28. origin = parsed_origin.netloc
  29. origin = origin.lower()
  30. host = handler.request.headers.get("Host")
  31. # Check to see that origin matches host directly, including ports
  32. return origin == host
  33. def webio_handler(target, session_type=None, allowed_origins=None, check_origin=None):
  34. if not session_type:
  35. session_type = get_session_implement_for_target(target)
  36. set_session_implement(session_type)
  37. if check_origin is None:
  38. check_origin_func = _is_same_site
  39. if allowed_origins:
  40. check_origin_func = partial(_check_origin, allowed_origins=allowed_origins)
  41. else:
  42. check_origin_func = lambda origin, handler: check_origin(origin)
  43. class WSHandler(WebSocketHandler):
  44. def check_origin(self, origin):
  45. return check_origin_func(origin=origin, handler=self)
  46. def get_compression_options(self):
  47. # Non-None enables compression with default options.
  48. return {}
  49. def send_msg_to_client(self, session: CoroutineBasedSession):
  50. for msg in session.get_task_commands():
  51. self.write_message(json.dumps(msg))
  52. def open(self):
  53. logger.debug("WebSocket opened")
  54. self.set_nodelay(True)
  55. self._close_from_session_tag = False # 由session主动关闭连接
  56. if get_session_implement() is CoroutineBasedSession:
  57. self.session = CoroutineBasedSession(target, on_task_command=self.send_msg_to_client,
  58. on_session_close=self.close_from_session)
  59. else:
  60. self.session = ThreadBasedSession(target, on_task_command=self.send_msg_to_client,
  61. on_session_close=self.close_from_session,
  62. loop=asyncio.get_event_loop())
  63. def on_message(self, message):
  64. data = json.loads(message)
  65. self.session.send_client_event(data)
  66. def close_from_session(self):
  67. self._close_from_session_tag = True
  68. self.close()
  69. def on_close(self):
  70. if not self._close_from_session_tag: # 只有在由客户端主动断开连接时,才调用 session.close()
  71. self.session.close()
  72. logger.debug("WebSocket closed")
  73. return WSHandler
  74. async def open_webbrowser_on_server_started(host, port):
  75. url = 'http://%s:%s' % (host, port)
  76. is_open = await wait_host_port(host, port, duration=5, delay=0.5)
  77. if is_open:
  78. logger.info('Openning %s' % url)
  79. webbrowser.open(url)
  80. else:
  81. logger.error('Open %s failed.' % url)
  82. def _setup_server(webio_handler, port=0, host='', **tornado_app_settings):
  83. if port == 0:
  84. port = get_free_port()
  85. print('Listen on %s:%s' % (host or '0.0.0.0', port))
  86. handlers = [(r"/io", webio_handler),
  87. (r"/(.*)", StaticFileHandler, {"path": STATIC_PATH, 'default_filename': 'index.html'})]
  88. app = tornado.web.Application(handlers=handlers, **tornado_app_settings)
  89. server = app.listen(port, address=host)
  90. return server, port
  91. def start_server(target, port=0, host='', debug=False,
  92. allowed_origins=None, check_origin=None,
  93. auto_open_webbrowser=False,
  94. session_type=None,
  95. websocket_max_message_size=None,
  96. websocket_ping_interval=None,
  97. websocket_ping_timeout=None,
  98. **tornado_app_settings):
  99. """Start a Tornado server to serve `target` function
  100. :param target: task function. It's a coroutine function is use CoroutineBasedSession or
  101. a simple function is use ThreadBasedSession.
  102. :param port: server bind port. set ``0`` to find a free port number to use
  103. :param host: server bind host. ``host`` may be either an IP address or hostname. If it's a hostname,
  104. the server will listen on all IP addresses associated with the name.
  105. set empty string or to listen on all available interfaces.
  106. :param bool debug: Tornado debug mode
  107. :param list allowed_origins: 除当前域名外,服务器还允许的请求的来源列表。
  108. 来源包含协议和域名和端口部分,允许使用 ``*`` 作为通配符。 比如 ``https://*.example.com`` 、 ``*://*.example.com`` 、
  109. :param callable check_origin: 请求来源检查函数。接收请求来源(包含协议和域名和端口部分)字符串,
  110. 返回 ``True/False`` 。若设置了 ``check_origin`` , ``allowed_origins`` 参数将被忽律
  111. :param bool auto_open_webbrowser: Whether or not auto open web browser when server is started.
  112. :param str session_type: 指定 `Session <pywebio.session.AbstractSession>` 的实现。未设置则根据 ``target`` 类型选择合适的实现。
  113. 接受的值为 `pywebio.session.THREAD_BASED` 和 `pywebio.session.COROUTINE_BASED`
  114. :param int websocket_max_message_size: Max bytes of a message which Tornado can accept.
  115. Messages larger than the ``websocket_max_message_size`` (default 10MiB) will not be accepted.
  116. :param int websocket_ping_interval: If set to a number, all websockets will be pinged every n seconds.
  117. This can help keep the connection alive through certain proxy servers which close idle connections,
  118. and it can detect if the websocket has failed without being properly closed.
  119. :param int websocket_ping_timeout: If the ping interval is set, and the server doesn’t receive a ‘pong’
  120. in this many seconds, it will close the websocket. The default is three times the ping interval,
  121. with a minimum of 30 seconds. Ignored if ``websocket_ping_interval`` is not set.
  122. :param tornado_app_settings: Additional keyword arguments passed to the constructor of ``tornado.web.Application``.
  123. ref: https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings
  124. :return:
  125. """
  126. kwargs = locals()
  127. app_options = ['debug', 'websocket_max_message_size', 'websocket_ping_interval', 'websocket_ping_timeout']
  128. for opt in app_options:
  129. if kwargs[opt] is not None:
  130. tornado_app_settings[opt] = kwargs[opt]
  131. handler = webio_handler(target, session_type=session_type, allowed_origins=allowed_origins, check_origin=check_origin)
  132. _, port = _setup_server(webio_handler=handler, port=port, host=host, **tornado_app_settings)
  133. if auto_open_webbrowser:
  134. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
  135. tornado.ioloop.IOLoop.current().start()
  136. def start_server_in_current_thread_session():
  137. """启动 script mode 的server"""
  138. websocket_conn_opened = threading.Event()
  139. thread = threading.current_thread()
  140. class SingleSessionWSHandler(webio_handler(None, session_type=SCRIPT_MODE)):
  141. session = None
  142. def open(self):
  143. self.main_sessin = False
  144. if SingleSessionWSHandler.session is None:
  145. self.main_sessin = True
  146. SingleSessionWSHandler.session = ScriptModeSession(thread,
  147. on_task_command=self.send_msg_to_client,
  148. loop=asyncio.get_event_loop())
  149. websocket_conn_opened.set()
  150. else:
  151. self.close()
  152. def on_close(self):
  153. if SingleSessionWSHandler.session is not None and self.main_sessin:
  154. self.session.close()
  155. logger.debug('ScriptModeSession closed')
  156. async def wait_to_stop_loop():
  157. """当只剩当前线程和Daemon线程运行时,关闭Server"""
  158. alive_none_daemonic_thread_cnt = None
  159. while alive_none_daemonic_thread_cnt != 1:
  160. alive_none_daemonic_thread_cnt = sum(
  161. 1 for t in threading.enumerate() if t.is_alive() and not t.isDaemon()
  162. )
  163. await asyncio.sleep(1)
  164. # Current thread is only one none-daemonic-thread, so exit
  165. logger.debug('Closing tornado ioloop...')
  166. tornado.ioloop.IOLoop.current().stop()
  167. def server_thread():
  168. loop = asyncio.new_event_loop()
  169. asyncio.set_event_loop(loop)
  170. server, port = _setup_server(webio_handler=SingleSessionWSHandler, host='localhost')
  171. tornado.ioloop.IOLoop.current().spawn_callback(wait_to_stop_loop)
  172. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, 'localhost', port)
  173. tornado.ioloop.IOLoop.current().start()
  174. logger.debug('Tornado server exit')
  175. t = threading.Thread(target=server_thread, name='Tornado-server')
  176. t.start()
  177. websocket_conn_opened.wait()