tornado.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import asyncio
  2. import fnmatch
  3. import json
  4. import logging
  5. import os
  6. import threading
  7. import webbrowser
  8. from functools import partial
  9. from urllib.parse import urlparse
  10. import tornado
  11. import tornado.httpserver
  12. import tornado.ioloop
  13. from tornado.web import StaticFileHandler
  14. from tornado.websocket import WebSocketHandler
  15. from ..session import CoroutineBasedSession, ThreadBasedSession, ScriptModeSession, \
  16. register_session_implement_for_target, Session
  17. from ..session.base import get_session_info_from_headers
  18. from ..utils import get_free_port, wait_host_port, STATIC_PATH, iscoroutinefunction, isgeneratorfunction
  19. from .utils import make_applications
  20. logger = logging.getLogger(__name__)
  21. _ioloop = None
  22. def ioloop() -> tornado.ioloop.IOLoop:
  23. """获得运行Tornado server的IOLoop"""
  24. global _ioloop
  25. return _ioloop
  26. def _check_origin(origin, allowed_origins, handler: WebSocketHandler):
  27. if _is_same_site(origin, handler):
  28. return True
  29. return any(
  30. fnmatch.fnmatch(origin, patten)
  31. for patten in allowed_origins
  32. )
  33. def _is_same_site(origin, handler: WebSocketHandler):
  34. parsed_origin = urlparse(origin)
  35. origin = parsed_origin.netloc
  36. origin = origin.lower()
  37. host = handler.request.headers.get("Host")
  38. # Check to see that origin matches host directly, including ports
  39. return origin == host
  40. def _webio_handler(applications, check_origin_func=_is_same_site):
  41. """获取用于Tornado进行整合的RequestHandle类
  42. :param dict applications: 任务名->任务函数 的字典
  43. :param callable check_origin_func: check_origin_func(origin, handler) -> bool
  44. :return: Tornado RequestHandle类
  45. """
  46. class WSHandler(WebSocketHandler):
  47. def check_origin(self, origin):
  48. return check_origin_func(origin=origin, handler=self)
  49. def get_compression_options(self):
  50. # Non-None enables compression with default options.
  51. return {}
  52. def send_msg_to_client(self, session: Session):
  53. for msg in session.get_task_commands():
  54. self.write_message(json.dumps(msg))
  55. def open(self):
  56. logger.debug("WebSocket opened")
  57. # self.set_nodelay(True)
  58. self._close_from_session_tag = False # 由session主动关闭连接
  59. session_info = get_session_info_from_headers(self.request.headers)
  60. session_info['user_ip'] = self.request.remote_ip
  61. session_info['request'] = self.request
  62. session_info['backend'] = 'tornado'
  63. app_name = self.get_query_argument('app', 'index')
  64. application = applications.get(app_name) or applications['index']
  65. if iscoroutinefunction(application) or isgeneratorfunction(application):
  66. self.session = CoroutineBasedSession(application, session_info=session_info,
  67. on_task_command=self.send_msg_to_client,
  68. on_session_close=self.close_from_session)
  69. else:
  70. self.session = ThreadBasedSession(application, session_info=session_info,
  71. on_task_command=self.send_msg_to_client,
  72. on_session_close=self.close_from_session,
  73. loop=asyncio.get_event_loop())
  74. def on_message(self, message):
  75. data = json.loads(message)
  76. if data is not None:
  77. self.session.send_client_event(data)
  78. def close_from_session(self):
  79. self._close_from_session_tag = True
  80. self.close()
  81. def on_close(self):
  82. if not self._close_from_session_tag: # 只有在由客户端主动断开连接时,才调用 session.close()
  83. self.session.close()
  84. logger.debug("WebSocket closed")
  85. return WSHandler
  86. def webio_handler(applications, allowed_origins=None, check_origin=None):
  87. """获取在Tornado中运行PyWebIO任务的RequestHandle类。RequestHandle类基于WebSocket协议与浏览器进行通讯。
  88. :param callable/list/dict applications: PyWebIO应用
  89. :param list allowed_origins: 除当前域名外,服务器还允许的请求的来源列表。
  90. 来源包含协议和域名和端口部分,允许使用 Unix shell 风格的匹配模式:
  91. - ``*`` 为通配符
  92. - ``?`` 匹配单个字符
  93. - ``[seq]`` 匹配seq内的字符
  94. - ``[!seq]`` 匹配不在seq内的字符
  95. 比如 ``https://*.example.com`` 、 ``*://*.example.com`` 、
  96. :param callable check_origin: 请求来源检查函数。接收请求来源(包含协议和域名和端口部分)字符串,
  97. 返回 ``True/False`` 。若设置了 ``check_origin`` , ``allowed_origins`` 参数将被忽略
  98. :return: Tornado RequestHandle类
  99. """
  100. applications = make_applications(applications)
  101. for target in applications.values():
  102. register_session_implement_for_target(target)
  103. if check_origin is None:
  104. check_origin_func = partial(_check_origin, allowed_origins=allowed_origins or [])
  105. else:
  106. check_origin_func = lambda origin, handler: _is_same_site(origin, handler) or check_origin(origin)
  107. return _webio_handler(applications=applications, check_origin_func=check_origin_func)
  108. async def open_webbrowser_on_server_started(host, port):
  109. url = 'http://%s:%s' % (host, port)
  110. is_open = await wait_host_port(host, port, duration=5, delay=0.5)
  111. if is_open:
  112. logger.info('Openning %s' % url)
  113. webbrowser.open(url)
  114. else:
  115. logger.error('Open %s failed.' % url)
  116. def _setup_server(webio_handler, port=0, host='', **tornado_app_settings):
  117. if port == 0:
  118. port = get_free_port()
  119. print('Listen on %s:%s' % (host or '0.0.0.0', port))
  120. handlers = [(r"/io", webio_handler),
  121. (r"/(.*)", StaticFileHandler, {"path": STATIC_PATH, 'default_filename': 'index.html'})]
  122. app = tornado.web.Application(handlers=handlers, **tornado_app_settings)
  123. server = app.listen(port, address=host)
  124. return server, port
  125. def start_server(applications, port=0, host='', debug=False,
  126. allowed_origins=None, check_origin=None,
  127. auto_open_webbrowser=False,
  128. websocket_max_message_size=None,
  129. websocket_ping_interval=None,
  130. websocket_ping_timeout=None,
  131. **tornado_app_settings):
  132. """启动一个 Tornado server 将PyWebIO应用作为Web服务提供。
  133. :param list/dict/callable applications: PyWebIO应用. 可以是任务函数或者任务函数的字典或列表。
  134. 类型为字典时,字典键为任务名,可以通过 ``app`` URL参数选择要运行的任务函数,默认使用运行 ``index`` 任务函数,
  135. 当 ``index`` 键不存在时,PyWebIO会提供一个默认的索引页作为主页。
  136. 类型为列表时,函数名为任务名
  137. 任务函数为协程函数时,使用 :ref:`基于协程的会话实现 <coroutine_based_session>` ;任务函数为普通函数时,使用基于线程的会话实现。
  138. :param int port: server bind port. set ``0`` to find a free port number to use
  139. :param str host: server bind host. ``host`` may be either an IP address or hostname. If it's a hostname,
  140. the server will listen on all IP addresses associated with the name.
  141. set empty string or `None` to listen on all available interfaces.
  142. :param bool debug: Tornado debug mode
  143. :param list allowed_origins: 除当前域名外,服务器还允许的请求的来源列表。
  144. 来源包含协议和域名和端口部分,允许使用 Unix shell 风格的匹配模式:
  145. - ``*`` 为通配符
  146. - ``?`` 匹配单个字符
  147. - ``[seq]`` 匹配seq内的字符
  148. - ``[!seq]`` 匹配不在seq内的字符
  149. 比如 ``https://*.example.com`` 、 ``*://*.example.com``
  150. :param callable check_origin: 请求来源检查函数。接收请求来源(包含协议和域名和端口部分)字符串,
  151. 返回 ``True/False`` 。若设置了 ``check_origin`` , ``allowed_origins`` 参数将被忽略
  152. :param bool auto_open_webbrowser: Whether or not auto open web browser when server is started (if the operating system allows it) .
  153. :param int websocket_max_message_size: Max bytes of a message which Tornado can accept.
  154. Messages larger than the ``websocket_max_message_size`` (default 10MiB) will not be accepted.
  155. :param int websocket_ping_interval: If set to a number, all websockets will be pinged every n seconds.
  156. This can help keep the connection alive through certain proxy servers which close idle connections,
  157. and it can detect if the websocket has failed without being properly closed.
  158. :param int websocket_ping_timeout: If the ping interval is set, and the server doesn’t receive a ‘pong’
  159. in this many seconds, it will close the websocket. The default is three times the ping interval,
  160. with a minimum of 30 seconds. Ignored if ``websocket_ping_interval`` is not set.
  161. :param tornado_app_settings: Additional keyword arguments passed to the constructor of ``tornado.web.Application``.
  162. ref: https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings
  163. """
  164. kwargs = locals()
  165. global _ioloop
  166. _ioloop = tornado.ioloop.IOLoop.current()
  167. app_options = ['debug', 'websocket_max_message_size', 'websocket_ping_interval', 'websocket_ping_timeout']
  168. for opt in app_options:
  169. if kwargs[opt] is not None:
  170. tornado_app_settings[opt] = kwargs[opt]
  171. handler = webio_handler(applications, allowed_origins=allowed_origins, check_origin=check_origin)
  172. _, port = _setup_server(webio_handler=handler, port=port, host=host, **tornado_app_settings)
  173. if auto_open_webbrowser:
  174. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
  175. tornado.ioloop.IOLoop.current().start()
  176. def start_server_in_current_thread_session():
  177. """启动 script mode 的server,监听可用端口,并自动打开浏览器
  178. PYWEBIO_SCRIPT_MODE_PORT环境变量可以设置监听端口,并关闭自动打开浏览器,用于测试
  179. """
  180. websocket_conn_opened = threading.Event()
  181. thread = threading.current_thread()
  182. class SingleSessionWSHandler(_webio_handler(applications={})):
  183. session = None
  184. instance = None
  185. def open(self):
  186. self.main_session = False
  187. if SingleSessionWSHandler.session is None:
  188. self.main_session = True
  189. SingleSessionWSHandler.instance = self
  190. session_info = get_session_info_from_headers(self.request.headers)
  191. session_info['user_ip'] = self.request.remote_ip
  192. session_info['request'] = self.request
  193. session_info['backend'] = 'tornado'
  194. SingleSessionWSHandler.session = ScriptModeSession(thread, session_info=session_info,
  195. on_task_command=self.send_msg_to_client,
  196. loop=asyncio.get_event_loop())
  197. websocket_conn_opened.set()
  198. else:
  199. self.close()
  200. def on_close(self):
  201. if SingleSessionWSHandler.session is not None and self.main_session:
  202. self.session.close()
  203. logger.debug('ScriptModeSession closed')
  204. async def wait_to_stop_loop(server):
  205. """当只剩当前线程和Daemon线程运行时,关闭Server"""
  206. alive_none_daemonic_thread_cnt = None # 包括当前线程在内的非Daemon线程数
  207. while alive_none_daemonic_thread_cnt != 1:
  208. alive_none_daemonic_thread_cnt = sum(
  209. 1 for t in threading.enumerate() if t.is_alive() and not t.isDaemon()
  210. )
  211. await asyncio.sleep(1)
  212. # 关闭Websocket连接
  213. if SingleSessionWSHandler.instance:
  214. SingleSessionWSHandler.instance.close()
  215. server.stop()
  216. logger.debug('Closing tornado ioloop...')
  217. tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task() and not t.done()]
  218. for task in tasks: task.cancel()
  219. # 必须需要 await asyncio.sleep ,否则 t.cancel() 调用无法调度生效
  220. await asyncio.sleep(0)
  221. tornado.ioloop.IOLoop.current().stop()
  222. def server_thread():
  223. loop = asyncio.new_event_loop()
  224. asyncio.set_event_loop(loop)
  225. global _ioloop
  226. _ioloop = tornado.ioloop.IOLoop.current()
  227. port = 0
  228. if os.environ.get("PYWEBIO_SCRIPT_MODE_PORT"):
  229. port = int(os.environ.get("PYWEBIO_SCRIPT_MODE_PORT"))
  230. server, port = _setup_server(webio_handler=SingleSessionWSHandler, port=port, host='localhost')
  231. tornado.ioloop.IOLoop.current().spawn_callback(partial(wait_to_stop_loop, server=server))
  232. if "PYWEBIO_SCRIPT_MODE_PORT" not in os.environ:
  233. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, 'localhost', port)
  234. tornado.ioloop.IOLoop.current().start()
  235. logger.debug('Tornado server exit')
  236. t = threading.Thread(target=server_thread, name='Tornado-server')
  237. t.start()
  238. websocket_conn_opened.wait()