tornado.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import asyncio
  2. import fnmatch
  3. import json
  4. import logging
  5. import os
  6. import threading
  7. import time
  8. import webbrowser
  9. from functools import partial
  10. from typing import Dict
  11. from urllib.parse import urlparse
  12. import tornado
  13. import tornado.httpserver
  14. import tornado.ioloop
  15. from tornado.web import StaticFileHandler
  16. from tornado.websocket import WebSocketHandler
  17. from . import page
  18. from .remote_access import start_remote_access_service
  19. from .page import make_applications, render_page
  20. from .utils import cdn_validation, deserialize_binary_event, print_listen_address
  21. from ..session import CoroutineBasedSession, ThreadBasedSession, ScriptModeSession, \
  22. register_session_implement_for_target, Session
  23. from ..session.base import get_session_info_from_headers
  24. from ..utils import get_free_port, wait_host_port, STATIC_PATH, iscoroutinefunction, isgeneratorfunction, \
  25. check_webio_js, parse_file_size, random_str, LRUDict
  26. logger = logging.getLogger(__name__)
  27. _ioloop = None
  28. def set_ioloop(loop):
  29. global _ioloop
  30. _ioloop = loop
  31. def ioloop() -> tornado.ioloop.IOLoop:
  32. """获得运行Tornado server的IOLoop
  33. 本方法当前仅在显示boken app时使用
  34. This method is currently only used when displaying boken app"""
  35. global _ioloop
  36. return _ioloop
  37. def _check_origin(origin, allowed_origins, handler: WebSocketHandler):
  38. if _is_same_site(origin, handler):
  39. return True
  40. return any(
  41. fnmatch.fnmatch(origin, pattern)
  42. for pattern in allowed_origins
  43. )
  44. def _is_same_site(origin, handler: WebSocketHandler):
  45. parsed_origin = urlparse(origin)
  46. origin = parsed_origin.netloc
  47. origin = origin.lower()
  48. host = handler.request.headers.get("Host")
  49. # Check to see that origin matches host directly, including ports
  50. return origin == host
  51. def _webio_handler(applications=None, cdn=True, reconnect_timeout=0, check_origin_func=_is_same_site): # noqa: C901
  52. """
  53. :param dict applications: dict of `name -> task function`
  54. :param bool/str cdn: Whether to load front-end static resources from CDN
  55. :param callable check_origin_func: check_origin_func(origin, handler) -> bool
  56. :return: Tornado RequestHandler class
  57. """
  58. check_webio_js()
  59. if applications is None:
  60. applications = dict(index=lambda: None) # mock PyWebIO app
  61. class WSHandler(WebSocketHandler):
  62. def __init__(self, *args, **kwargs):
  63. super().__init__(*args, **kwargs)
  64. self._close_from_session = False
  65. self.session_id = None
  66. self.session = None # type: Session
  67. if reconnect_timeout and not type(self)._started_clean_task:
  68. type(self)._started_clean_task = True
  69. tornado.ioloop.IOLoop.current().call_later(reconnect_timeout // 2, type(self).clean_expired_sessions)
  70. logger.debug("Started session clean task")
  71. def get_app(self):
  72. app_name = self.get_query_argument('app', 'index')
  73. app = applications.get(app_name) or applications['index']
  74. return app
  75. def get_cdn(self):
  76. if cdn is True and self.get_query_argument('_pywebio_cdn', '') == 'false':
  77. return False
  78. return cdn
  79. async def get(self, *args, **kwargs) -> None:
  80. # It's a simple http GET request
  81. if self.request.headers.get("Upgrade", "").lower() != "websocket":
  82. # Backward compatible
  83. # Frontend detect whether the backend is http server
  84. if self.get_query_argument('test', ''):
  85. return self.write('')
  86. app = self.get_app()
  87. html = render_page(app, protocol='ws', cdn=self.get_cdn())
  88. return self.write(html)
  89. else:
  90. await super().get()
  91. def check_origin(self, origin):
  92. return check_origin_func(origin=origin, handler=self)
  93. def get_compression_options(self):
  94. # Non-None enables compression with default options.
  95. return {}
  96. @classmethod
  97. def clean_expired_sessions(cls):
  98. tornado.ioloop.IOLoop.current().call_later(reconnect_timeout // 2, cls.clean_expired_sessions)
  99. while cls._session_expire:
  100. session_id, expire_ts = cls._session_expire.popitem(last=False) # 弹出最早过期的session
  101. if time.time() < expire_ts:
  102. # this session is not expired
  103. cls._session_expire[session_id] = expire_ts # restore this item
  104. cls._session_expire.move_to_end(session_id, last=False) # move to front
  105. break
  106. # clean this session
  107. logger.debug("session %s expired" % session_id)
  108. cls._connections.pop(session_id, None)
  109. session = cls._webio_sessions.pop(session_id, None)
  110. if session:
  111. session.close(nonblock=True)
  112. @classmethod
  113. def send_msg_to_client(cls, _, session_id=None):
  114. conn = cls._connections.get(session_id)
  115. session = cls._webio_sessions[session_id]
  116. if not conn or not conn.ws_connection:
  117. return
  118. for msg in session.get_task_commands():
  119. try:
  120. conn.write_message(json.dumps(msg))
  121. except TypeError as e:
  122. logger.exception('Data serialization error: %s\n'
  123. 'This may be because you pass the wrong type of parameter to the function'
  124. ' of PyWebIO.\nData content: %s', e, msg)
  125. @classmethod
  126. def close_from_session(cls, session_id=None):
  127. cls.send_msg_to_client(None, session_id=session_id)
  128. conn = cls._connections.pop(session_id, None)
  129. cls._webio_sessions.pop(session_id, None)
  130. if conn and conn.ws_connection:
  131. conn._close_from_session = True
  132. conn.close()
  133. _started_clean_task = False
  134. _session_expire = LRUDict() # session_id -> expire timestamp. In increasing order of expire time
  135. _webio_sessions = {} # type: Dict[str, Session] # session_id -> session
  136. _connections = {} # type: Dict[str, WSHandler] # session_id -> WSHandler
  137. def open(self):
  138. logger.debug("WebSocket opened")
  139. cls = type(self)
  140. self.session_id = self.get_query_argument('session', None)
  141. if self.session_id in ('NEW', None): # 初始请求,创建新 Session
  142. session_info = get_session_info_from_headers(self.request.headers)
  143. session_info['user_ip'] = self.request.remote_ip
  144. session_info['request'] = self.request
  145. session_info['backend'] = 'tornado'
  146. session_info['protocol'] = 'websocket'
  147. application = self.get_app()
  148. self.session_id = random_str(24)
  149. cls._connections[self.session_id] = self
  150. if iscoroutinefunction(application) or isgeneratorfunction(application):
  151. self.session = CoroutineBasedSession(
  152. application, session_info=session_info,
  153. on_task_command=partial(self.send_msg_to_client, session_id=self.session_id),
  154. on_session_close=partial(self.close_from_session, session_id=self.session_id))
  155. else:
  156. self.session = ThreadBasedSession(
  157. application, session_info=session_info,
  158. on_task_command=partial(self.send_msg_to_client, session_id=self.session_id),
  159. on_session_close=partial(self.close_from_session, session_id=self.session_id),
  160. loop=asyncio.get_event_loop())
  161. cls._webio_sessions[self.session_id] = self.session
  162. if reconnect_timeout:
  163. self.write_message(json.dumps(dict(command='set_session_id', spec=self.session_id)))
  164. elif self.session_id not in cls._webio_sessions: # WebIOSession deleted
  165. self.write_message(json.dumps(dict(command='close_session')))
  166. else:
  167. self.session = cls._webio_sessions[self.session_id]
  168. cls._session_expire.pop(self.session_id, None)
  169. cls._connections[self.session_id] = self
  170. cls.send_msg_to_client(self.session, self.session_id)
  171. logger.debug('session id: %s' % self.session_id)
  172. def on_message(self, message):
  173. if isinstance(message, bytes):
  174. event = deserialize_binary_event(message)
  175. else:
  176. event = json.loads(message)
  177. if event is None:
  178. return
  179. self.session.send_client_event(event)
  180. def on_close(self):
  181. cls = type(self)
  182. cls._connections.pop(self.session_id, None)
  183. if not reconnect_timeout and not self._close_from_session:
  184. self.session.close(nonblock=True)
  185. elif reconnect_timeout:
  186. if self._close_from_session:
  187. cls._webio_sessions.pop(self.session_id, None)
  188. elif self.session:
  189. cls._session_expire[self.session_id] = time.time() + reconnect_timeout
  190. logger.debug("WebSocket closed")
  191. return WSHandler
  192. def webio_handler(applications, cdn=True, reconnect_timeout=0, allowed_origins=None, check_origin=None):
  193. """Get the ``RequestHandler`` class for running PyWebIO applications in Tornado.
  194. The ``RequestHandler`` communicates with the browser by WebSocket protocol.
  195. The arguments of ``webio_handler()`` have the same meaning as for :func:`pywebio.platform.tornado.start_server`
  196. """
  197. applications = make_applications(applications)
  198. for target in applications.values():
  199. register_session_implement_for_target(target)
  200. cdn = cdn_validation(cdn, 'error') # if CDN is not available, raise error
  201. if check_origin is None:
  202. check_origin_func = partial(_check_origin, allowed_origins=allowed_origins or [])
  203. else:
  204. check_origin_func = lambda origin, handler: _is_same_site(origin, handler) or check_origin(origin)
  205. return _webio_handler(applications=applications, cdn=cdn, check_origin_func=check_origin_func,
  206. reconnect_timeout=reconnect_timeout)
  207. async def open_webbrowser_on_server_started(host, port):
  208. url = 'http://%s:%s' % (host, port)
  209. is_open = await wait_host_port(host, port, duration=20)
  210. if is_open:
  211. logger.info('Try open %s in web browser' % url)
  212. # webbrowser.open() may block, so invoke it in thread
  213. threading.Thread(target=webbrowser.open, args=(url,), daemon=True).start()
  214. else:
  215. logger.error('Open %s in web browser failed.' % url)
  216. def _setup_server(webio_handler, port=0, host='', static_dir=None, max_buffer_size=2 ** 20 * 200,
  217. **tornado_app_settings):
  218. if port == 0:
  219. port = get_free_port()
  220. handlers = [(r"/", webio_handler)]
  221. if static_dir is not None:
  222. handlers.append((r"/static/(.*)", StaticFileHandler, {"path": static_dir}))
  223. handlers.append((r"/(.*)", StaticFileHandler, {"path": STATIC_PATH, 'default_filename': 'index.html'}))
  224. app = tornado.web.Application(handlers=handlers, **tornado_app_settings)
  225. # Credit: https://stackoverflow.com/questions/19074972/content-length-too-long-when-uploading-file-using-tornado
  226. server = app.listen(port, address=host, max_buffer_size=max_buffer_size)
  227. return server, port
  228. def start_server(applications, port=0, host='',
  229. debug=False, cdn=True, static_dir=None,
  230. remote_access=False,
  231. reconnect_timeout=0,
  232. allowed_origins=None, check_origin=None,
  233. auto_open_webbrowser=False,
  234. max_payload_size='200M',
  235. **tornado_app_settings):
  236. """Start a Tornado server to provide the PyWebIO application as a web service.
  237. The Tornado server communicates with the browser by WebSocket protocol.
  238. Tornado is the default backend server for PyWebIO applications,
  239. and ``start_server`` can be imported directly using ``from pywebio import start_server``.
  240. :param list/dict/callable applications: PyWebIO application.
  241. Can be a task function, a list of functions, or a dictionary.
  242. Refer to :ref:`Advanced topic: Multiple applications in start_server() <multiple_app>` for more information.
  243. When the task function is a coroutine function, use :ref:`Coroutine-based session <coroutine_based_session>` implementation,
  244. otherwise, use thread-based session implementation.
  245. :param int port: The port the server listens on.
  246. When set to ``0``, the server will automatically select a available port.
  247. :param str host: The host the server listens on. ``host`` may be either an IP address or hostname.
  248. If it’s a hostname, the server will listen on all IP addresses associated with the name.
  249. ``host`` may be an empty string or None to listen on all available interfaces.
  250. :param bool debug: Tornado Server's debug mode. If enabled, the server will automatically reload for code changes.
  251. See `tornado doc <https://www.tornadoweb.org/en/stable/guide/running.html#debug-mode>`_ for more detail.
  252. :param bool/str cdn: Whether to load front-end static resources from CDN, the default is ``True``.
  253. Can also use a string to directly set the url of PyWebIO static resources.
  254. :param str static_dir: The directory to store the application static files.
  255. The files in this directory can be accessed via ``http://<host>:<port>/static/files``.
  256. For example, if there is a ``A/B.jpg`` file in ``static_dir`` path,
  257. it can be accessed via ``http://<host>:<port>/static/A/B.jpg``.
  258. :param bool remote_access: Whether to enable remote access, when enabled,
  259. you can get a temporary public network access address for the current application,
  260. others can access your application via this address.
  261. :param bool auto_open_webbrowser: Whether or not auto open web browser when server is started (if the operating system allows it) .
  262. :param int reconnect_timeout: The client can reconnect to server within ``reconnect_timeout`` seconds after an unexpected disconnection.
  263. If set to 0 (default), once the client disconnects, the server session will be closed.
  264. :param list allowed_origins: The allowed request source list. (The current server host is always allowed)
  265. The source contains the protocol, domain name, and port part.
  266. Can use Unix shell-style wildcards:
  267. - ``*`` matches everything
  268. - ``?`` matches any single character
  269. - ``[seq]`` matches any character in *seq*
  270. - ``[!seq]`` matches any character not in *seq*
  271. Such as: ``https://*.example.com`` 、 ``*://*.example.com``
  272. For detail, see `Python Doc <https://docs.python.org/zh-tw/3/library/fnmatch.html>`_
  273. :param callable check_origin: The validation function for request source.
  274. It receives the source string (which contains protocol, host, and port parts) as parameter and
  275. return ``True/False`` to indicate that the server accepts/rejects the request.
  276. If ``check_origin`` is set, the ``allowed_origins`` parameter will be ignored.
  277. :param bool auto_open_webbrowser: Whether or not auto open web browser when server is started (if the operating system allows it) .
  278. :param int/str max_payload_size: Max size of a websocket message which Tornado can accept.
  279. Messages larger than the ``max_payload_size`` (default 200MB) will not be accepted.
  280. ``max_payload_size`` can be a integer indicating the number of bytes, or a string ending with `K` / `M` / `G`
  281. (representing kilobytes, megabytes, and gigabytes, respectively).
  282. E.g: ``500``, ``'40K'``, ``'3M'``
  283. :param tornado_app_settings: Additional keyword arguments passed to the constructor of ``tornado.web.Application``.
  284. For details, please refer: https://www.tornadoweb.org/en/stable/web.html#tornado.web.Application.settings
  285. """
  286. set_ioloop(tornado.ioloop.IOLoop.current()) # to enable bokeh app
  287. cdn = cdn_validation(cdn, 'warn') # if CDN is not available, warn user and disable CDN
  288. page.MAX_PAYLOAD_SIZE = max_payload_size = parse_file_size(max_payload_size)
  289. debug = Session.debug = os.environ.get('PYWEBIO_DEBUG', debug)
  290. # Since some cloud server may close idle connections (such as heroku),
  291. # use `websocket_ping_interval` to keep the connection alive
  292. tornado_app_settings.setdefault('websocket_ping_interval', 30)
  293. tornado_app_settings.setdefault('websocket_max_message_size', max_payload_size) # Backward compatible
  294. tornado_app_settings['websocket_max_message_size'] = parse_file_size(
  295. tornado_app_settings['websocket_max_message_size'])
  296. tornado_app_settings['debug'] = debug
  297. handler = webio_handler(applications, cdn, allowed_origins=allowed_origins, check_origin=check_origin,
  298. reconnect_timeout=reconnect_timeout)
  299. _, port = _setup_server(webio_handler=handler, port=port, host=host, static_dir=static_dir,
  300. max_buffer_size=max_payload_size, **tornado_app_settings)
  301. print_listen_address(host, port)
  302. if auto_open_webbrowser:
  303. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, host or 'localhost', port)
  304. if remote_access:
  305. start_remote_access_service(local_port=port)
  306. tornado.ioloop.IOLoop.current().start()
  307. def start_server_in_current_thread_session():
  308. """启动 script mode 的server,监听可用端口,并自动打开浏览器
  309. Start the server for script mode, and automatically open the browser when the server port is available.
  310. PYWEBIO_SCRIPT_MODE_PORT环境变量可以设置监听端口,并关闭自动打开浏览器,用于测试
  311. The PYWEBIO_SCRIPT_MODE_PORT environment variable can set the listening port, just used in testing.
  312. """
  313. websocket_conn_opened = threading.Event()
  314. thread = threading.current_thread()
  315. class SingleSessionWSHandler(_webio_handler(cdn=False)):
  316. session = None
  317. instance = None
  318. closed = False
  319. def open(self):
  320. self.main_session = False
  321. cls = type(self)
  322. if SingleSessionWSHandler.session is None:
  323. self.main_session = True
  324. SingleSessionWSHandler.instance = self
  325. self.session_id = 'main'
  326. cls._connections[self.session_id] = self
  327. session_info = get_session_info_from_headers(self.request.headers)
  328. session_info['user_ip'] = self.request.remote_ip
  329. session_info['request'] = self.request
  330. session_info['backend'] = 'tornado'
  331. session_info['protocol'] = 'websocket'
  332. self.session = SingleSessionWSHandler.session = ScriptModeSession(
  333. thread, session_info=session_info,
  334. on_task_command=partial(self.send_msg_to_client, session_id=self.session_id),
  335. loop=asyncio.get_event_loop())
  336. websocket_conn_opened.set()
  337. cls._webio_sessions[self.session_id] = self.session
  338. else:
  339. self.close()
  340. def on_close(self):
  341. if SingleSessionWSHandler.session is not None and self.main_session:
  342. self.session.close()
  343. self.closed = True
  344. logger.debug('ScriptModeSession closed')
  345. async def wait_to_stop_loop(server):
  346. """当只剩当前线程和Daemon线程运行时,关闭Server
  347. When only the current thread and Daemon thread are running, close the Server"""
  348. # 包括当前线程在内的非Daemon线程数
  349. # The number of non-Daemon threads(including the current thread)
  350. alive_none_daemonic_thread_cnt = None
  351. while alive_none_daemonic_thread_cnt != 1:
  352. alive_none_daemonic_thread_cnt = sum(
  353. 1 for t in threading.enumerate() if t.is_alive() and not t.isDaemon()
  354. )
  355. await asyncio.sleep(0.5)
  356. if SingleSessionWSHandler.instance.session.need_keep_alive():
  357. while not SingleSessionWSHandler.instance.closed:
  358. await asyncio.sleep(0.5)
  359. # 关闭Websocket连接
  360. # Close the Websocket connection
  361. if SingleSessionWSHandler.instance:
  362. SingleSessionWSHandler.instance.close()
  363. server.stop()
  364. logger.debug('Closing tornado ioloop...')
  365. tasks = [t for t in asyncio.all_tasks() if t is not asyncio.current_task() and not t.done()]
  366. for task in tasks:
  367. task.cancel()
  368. # 必须需要 await asyncio.sleep ,否则上方 task.cancel() 调用无法调度生效
  369. # This line must be required, otherwise the `task.cancel()` call cannot be scheduled to take effect
  370. await asyncio.sleep(0)
  371. tornado.ioloop.IOLoop.current().stop()
  372. def server_thread():
  373. from tornado.log import access_log, app_log, gen_log
  374. access_log.setLevel(logging.ERROR)
  375. app_log.setLevel(logging.ERROR)
  376. gen_log.setLevel(logging.ERROR)
  377. loop = asyncio.new_event_loop()
  378. asyncio.set_event_loop(loop)
  379. set_ioloop(tornado.ioloop.IOLoop.current()) # to enable bokeh app
  380. port = 0
  381. if os.environ.get("PYWEBIO_SCRIPT_MODE_PORT"):
  382. port = int(os.environ.get("PYWEBIO_SCRIPT_MODE_PORT"))
  383. server, port = _setup_server(webio_handler=SingleSessionWSHandler, port=port, host='localhost',
  384. websocket_max_message_size=parse_file_size('200M'))
  385. tornado.ioloop.IOLoop.current().spawn_callback(partial(wait_to_stop_loop, server=server))
  386. if "PYWEBIO_SCRIPT_MODE_PORT" not in os.environ:
  387. tornado.ioloop.IOLoop.current().spawn_callback(open_webbrowser_on_server_started, 'localhost', port)
  388. tornado.ioloop.IOLoop.current().start()
  389. logger.debug('Tornado server exit')
  390. t = threading.Thread(target=server_thread, name='Tornado-server')
  391. t.start()
  392. websocket_conn_opened.wait()