资讯专栏INFORMATION COLUMN

tornado 源码阅读-初步认识

2450184176 / 3319人阅读

摘要:序言最近闲暇无事阅读了一下的源码对整体的结构有了初步认识与大家分享不知道为什么右边的目录一直出不来非常不舒服不如移步到吧是的核心模块也是个调度模块各种异步事件都是由他调度的所以必须弄清他的执行逻辑源码分析而的核心部分则是这个循环内部的逻辑贴

序言

</>复制代码

  1. 最近闲暇无事,阅读了一下tornado的源码,对整体的结构有了初步认识,与大家分享
  2. 不知道为什么右边的目录一直出不来,非常不舒服.
  3. 不如移步到oschina吧....[http://my.oschina.net/abc2001x/blog/476349][1]
ioloop

</>复制代码

  1. `ioloop``tornado`的核心模块,也是个调度模块,各种异步事件都是由他调度的,所以必须弄清他的执行逻辑
源码分析

</>复制代码

  1. `ioloop`的核心部分则是 `while True`这个循环内部的逻辑,贴上他的代码如下

</>复制代码

  1. def start(self):
  2. if self._running:
  3. raise RuntimeError("IOLoop is already running")
  4. self._setup_logging()
  5. if self._stopped:
  6. self._stopped = False
  7. return
  8. old_current = getattr(IOLoop._current, "instance", None)
  9. IOLoop._current.instance = self
  10. self._thread_ident = thread.get_ident()
  11. self._running = True
  12. old_wakeup_fd = None
  13. if hasattr(signal, "set_wakeup_fd") and os.name == "posix":
  14. try:
  15. old_wakeup_fd = signal.set_wakeup_fd(self._waker.write_fileno())
  16. if old_wakeup_fd != -1:
  17. signal.set_wakeup_fd(old_wakeup_fd)
  18. old_wakeup_fd = None
  19. except ValueError:
  20. old_wakeup_fd = None
  21. try:
  22. while True:
  23. with self._callback_lock:
  24. callbacks = self._callbacks
  25. self._callbacks = []
  26. due_timeouts = []
  27. if self._timeouts:
  28. now = self.time()
  29. while self._timeouts:
  30. if self._timeouts[0].callback is None:
  31. heapq.heappop(self._timeouts)
  32. self._cancellations -= 1
  33. elif self._timeouts[0].deadline <= now:
  34. due_timeouts.append(heapq.heappop(self._timeouts))
  35. else:
  36. break
  37. if (self._cancellations > 512
  38. and self._cancellations > (len(self._timeouts) >> 1)):
  39. self._cancellations = 0
  40. self._timeouts = [x for x in self._timeouts
  41. if x.callback is not None]
  42. heapq.heapify(self._timeouts)
  43. for callback in callbacks:
  44. self._run_callback(callback)
  45. for timeout in due_timeouts:
  46. if timeout.callback is not None:
  47. self._run_callback(timeout.callback)
  48. callbacks = callback = due_timeouts = timeout = None
  49. if self._callbacks:
  50. poll_timeout = 0.0
  51. elif self._timeouts:
  52. poll_timeout = self._timeouts[0].deadline - self.time()
  53. poll_timeout = max(0, min(poll_timeout, _POLL_TIMEOUT))
  54. else:
  55. poll_timeout = _POLL_TIMEOUT
  56. if not self._running:
  57. break
  58. if self._blocking_signal_threshold is not None:
  59. signal.setitimer(signal.ITIMER_REAL, 0, 0)
  60. try:
  61. event_pairs = self._impl.poll(poll_timeout)
  62. except Exception as e:
  63. if errno_from_exception(e) == errno.EINTR:
  64. continue
  65. else:
  66. raise
  67. if self._blocking_signal_threshold is not None:
  68. signal.setitimer(signal.ITIMER_REAL,
  69. self._blocking_signal_threshold, 0)
  70. self._events.update(event_pairs)
  71. while self._events:
  72. fd, events = self._events.popitem()
  73. try:
  74. fd_obj, handler_func = self._handlers[fd]
  75. handler_func(fd_obj, events)
  76. except (OSError, IOError) as e:
  77. if errno_from_exception(e) == errno.EPIPE:
  78. pass
  79. else:
  80. self.handle_callback_exception(self._handlers.get(fd))
  81. except Exception:
  82. self.handle_callback_exception(self._handlers.get(fd))
  83. fd_obj = handler_func = None
  84. finally:
  85. self._stopped = False
  86. if self._blocking_signal_threshold is not None:
  87. signal.setitimer(signal.ITIMER_REAL, 0, 0)
  88. IOLoop._current.instance = old_current
  89. if old_wakeup_fd is not None:
  90. signal.set_wakeup_fd(old_wakeup_fd)

</>复制代码

  1. 除去注释,代码其实没多少行. 由while 内部代码可以看出ioloop主要由三部分组成:
1.回调 callbacks

他是ioloop回调的基础部分,通过IOLoop.instance().add_callback()添加到self._callbacks
他们将在每一次loop中被运行.

主要用途是将逻辑分块,在适合时机将包装好的callback添加到self._callbacks让其执行.

例如ioloop中的add_future

</>复制代码

  1. def add_future(self, future, callback):
  2. """Schedules a callback on the ``IOLoop`` when the given
  3. `.Future` is finished.
  4. The callback is invoked with one argument, the
  5. `.Future`.
  6. """
  7. assert is_future(future)
  8. callback = stack_context.wrap(callback)
  9. future.add_done_callback(
  10. lambda future: self.add_callback(callback, future))

future对象得到result的时候会调用future.add_done_callback添加的callback,再将其转至ioloop执行

2.定时器 due_timeouts

这是定时器,在指定的事件执行callback.
跟1中的callback类似,通过IOLoop.instance().add_callback

在每一次循环,会计算timeouts回调列表里的事件,运行已到期的callback.
当然不是无节操的循环.

因为poll操作会阻塞到有io操作发生,所以只要计算最近的timeout,
然后用这个时间作为self._impl.poll(poll_timeout)poll_timeout ,
就可以达到按时运行了

但是,假设poll_timeout的时间很大时,self._impl.poll一直在堵塞中(没有io事件,但在处理某一个io事件),
那添加刚才1中的callback不是要等很久才会被运行吗? 答案当然是不会.
ioloop中有个waker对象,他是由两个fd组成,一个读一个写.
ioloop在初始化的时候把waker绑定到epoll里了,add_callback时会触发waker的读写.
这样ioloop就会在poll中被唤醒了,接着就可以及时处理timeout callback

用这样的方式也可以自己封装一个小的定时器功能玩玩

3.io事件的event loop

处理epoll事件的功能
通过IOLoop.instance().add_handler(fd, handler, events)绑定fd event的处理事件
httpserver.listen的代码内,
netutil.py中的netutil.pyadd_accept_handler绑定accept handler处理客户端接入的逻辑

如法炮制,其他的io事件也这样绑定,业务逻辑的分块交由ioloopcallbackfuture处理

关于epoll的用法的内容.详情见我第一篇文章吧,哈哈

总结

ioloop由callback(业务分块), timeout callback(定时任务) io event(io传输和解析) 三块组成,互相配合完成异步的功能,构建gen,httpclient,iostream等功能

串联大致的流程是,tornado 绑定io event,处理io传输解析,传输完成后(结合Future)回调(callback)业务处理的逻辑和一些固定操作 . 定时器则是较为独立的模块

Futrue

个人认为Futuretornado仅此ioloop重要的模块,他贯穿全文,所有异步操作都有他的身影
顾名思义,他主要是关注日后要做的事,类似jqueryDeferred

一般的用法是通过ioloopadd_future定义futuredone callback,
futureset_result的时候,futuredone callback就会被调用.
从而完成Future的功能.

具体可以参考gen.coroutine的实现,本文后面也会讲到

他的组成不复杂,只有几个重要的方法
最重要的是 add_done_callback , set_result

tornadoFutureioloop,yield实现了gen.coroutine

1. add_done_callback

ioloopcallback类似 , 存储事件完成后的callbackself._callbacks

</>复制代码

  1. def add_done_callback(self, fn):
  2. if self._done:
  3. fn(self)
  4. else:
  5. self._callbacks.append(fn)
2.set_result

设置事件的结果,并运行之前存储好的callback

</>复制代码

  1. def set_result(self, result):
  2. self._result = result
  3. self._set_done()
  4. def _set_done(self):
  5. self._done = True
  6. for cb in self._callbacks:
  7. try:
  8. cb(self)
  9. except Exception:
  10. app_log.exception("Exception in callback %r for %r",
  11. cb, self)
  12. self._callbacks = None

为了验证之前所说的,上一段测试代码

</>复制代码

  1. #! /usr/bin/env python
  2. #coding=utf-8
  3. import tornado.web
  4. import tornado.ioloop
  5. from tornado.gen import coroutine
  6. from tornado.concurrent import Future
  7. def test():
  8. def pp(s):
  9. print s
  10. future = Future()
  11. iol = tornado.ioloop.IOLoop.instance()
  12. print "init future %s"%future
  13. iol.add_future(future, lambda f: pp("ioloop callback after future done,future is %s"%f))
  14. #模拟io延迟操作
  15. iol.add_timeout(iol.time()+5,lambda:future.set_result("set future is done"))
  16. print "init complete"
  17. tornado.ioloop.IOLoop.instance().start()
  18. if __name__ == "__main__":
  19. test()

运行结果:

gen.coroutine

接着继续延伸,看看coroutine的实现
gen.coroutine实现的功能其实是将原来的callback的写法,用yield的写法代替. 即以yield为分界,将代码分成两部分.
如:

</>复制代码

  1. #! /usr/bin/env python
  2. #coding=utf-8
  3. import tornado.ioloop
  4. from tornado.gen import coroutine
  5. from tornado.httpclient import AsyncHTTPClient
  6. @coroutine
  7. def cotest():
  8. client = AsyncHTTPClient()
  9. res = yield client.fetch("http://www.segmentfault.com/")
  10. print res
  11. if __name__ == "__main__":
  12. f = cotest()
  13. print f #这里返回了一个future哦
  14. tornado.ioloop.IOLoop.instance().start()

运行结果:

源码分析

接下来分析下coroutine的实现

</>复制代码

  1. def _make_coroutine_wrapper(func, replace_callback):
  2. @functools.wraps(func)
  3. def wrapper(*args, **kwargs):
  4. future = TracebackFuture()
  5. if replace_callback and "callback" in kwargs:
  6. callback = kwargs.pop("callback")
  7. IOLoop.current().add_future(
  8. future, lambda future: callback(future.result()))
  9. try:
  10. result = func(*args, **kwargs)
  11. except (Return, StopIteration) as e:
  12. result = getattr(e, "value", None)
  13. except Exception:
  14. future.set_exc_info(sys.exc_info())
  15. return future
  16. else:
  17. if isinstance(result, types.GeneratorType):
  18. try:
  19. orig_stack_contexts = stack_context._state.contexts
  20. yielded = next(result)
  21. if stack_context._state.contexts is not orig_stack_contexts:
  22. yielded = TracebackFuture()
  23. yielded.set_exception(
  24. stack_context.StackContextInconsistentError(
  25. "stack_context inconsistency (probably caused "
  26. "by yield within a "with StackContext" block)"))
  27. except (StopIteration, Return) as e:
  28. future.set_result(getattr(e, "value", None))
  29. except Exception:
  30. future.set_exc_info(sys.exc_info())
  31. else:
  32. Runner(result, future, yielded)
  33. try:
  34. return future
  35. finally:
  36. future = None
  37. future.set_result(result)
  38. return future
  39. return wrapper

如源码所示,func运行的结果是GeneratorType ,yielded = next(result),
运行至原函数的yield位置,返回的是原函数func内部 yield 右边返回的对象(必须是FutureFuturelist)给yielded.
经过Runner(result, future, yielded) 对yielded进行处理.
在此就 贴出Runner的代码了.
Runner初始化过程,调用handle_yield, 查看yielded是否已done了,否则add_future运行Runnerrun方法,
run方法中如果yielded对象已完成,用对它的gen调用send,发送完成的结果.
所以yielded在什么地方被set_result非常重要,
当被set_result的时候,才会send结果给原func,完成整个异步操作

详情可以查看tornado 中重要的对象 iostream,源码中iostream的 _handle_connect,如此设置了连接的result.

</>复制代码

  1. def _handle_connect(self):
  2. err = self.socket.getsockopt(socket.SOL_SOCKET, socket.SO_ERROR)
  3. if err != 0:
  4. self.error = socket.error(err, os.strerror(err))
  5. if self._connect_future is None:
  6. gen_log.warning("Connect error on fd %s: %s",
  7. self.socket.fileno(), errno.errorcode[err])
  8. self.close()
  9. return
  10. if self._connect_callback is not None:
  11. callback = self._connect_callback
  12. self._connect_callback = None
  13. self._run_callback(callback)
  14. if self._connect_future is not None:
  15. future = self._connect_future
  16. self._connect_future = None
  17. future.set_result(self)
  18. self._connecting = False

最后贴上一个简单的测试代码,演示coroutine,future的用法

</>复制代码

  1. import tornado.ioloop
  2. from tornado.gen import coroutine
  3. from tornado.concurrent import Future
  4. @coroutine
  5. def asyn_sum(a, b):
  6. print("begin calculate:sum %d+%d"%(a,b))
  7. future = Future()
  8. future2 = Future()
  9. iol = tornado.ioloop.IOLoop.instance()
  10. print future
  11. def callback(a, b):
  12. print("calculating the sum of %d+%d:"%(a,b))
  13. future.set_result(a+b)
  14. iol.add_timeout(iol.time()+3,lambda f:f.set_result(None),future2)
  15. iol.add_timeout(iol.time()+3,callback, a, b)
  16. result = yield future
  17. print("after yielded")
  18. print("the %d+%d=%d"%(a, b, result))
  19. yield future2
  20. print "after future2"
  21. def main():
  22. f = asyn_sum(2,3)
  23. print ""
  24. print f
  25. tornado.ioloop.IOLoop.instance().start()
  26. if __name__ == "__main__":
  27. main()

运行结果:

为什么代码中个yield都起作用了? 因为Runner.run里,最后继续用handle_yield处理了send后返回的yielded对象,意思是func里可以有n干个yield操作

</>复制代码

  1. if not self.handle_yield(yielded):
  2. return
总结

至此,已完成tornado中重要的几个模块的流程,其他模块也是由此而来.写了这么多,越写越卡,就到此为止先吧,

最后的最后的最后

啊~~~~~~好想有份工作女朋友啊~~~~~

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/37553.html

相关文章

  • SegmentFault 技术周刊 Vol.30 - 学习 Python 来做一些神奇好玩的事情吧

    摘要:学习笔记七数学形态学关注的是图像中的形状,它提供了一些方法用于检测形状和改变形状。学习笔记十一尺度不变特征变换,简称是图像局部特征提取的现代方法基于区域图像块的分析。本文的目的是简明扼要地说明的编码机制,并给出一些建议。 showImg(https://segmentfault.com/img/bVRJbz?w=900&h=385); 前言 开始之前,我们先来看这样一个提问: pyth...

    lifesimple 评论0 收藏0
  • [零基础学python]python开发框架

    摘要:软件开发者通常依据特定的框架实现更为复杂的商业运用和业务逻辑。所有,做开发,要用一个框架。的性能是相当优异的,因为它师徒解决一个被称之为问题,就是处理大于或等于一万的并发。 One does not live by bread alone,but by every word that comes from the mouth of God --(MATTHEW4:4) 不...

    lucas 评论0 收藏0
  • 记一次tornado QPS 优化

    摘要:初步分析提升可从两方面入手,一个是增加并发数,其二是减少平均响应时间。大部分的时间花在系统与数据库的交互上,到这,便有了一个优化的主题思路最大限度的降低平均响应时间。不要轻易否定一项公认的技术真理,要拿数据说话。 本文最早发表于个人博客:PylixmWiki 应项目的需求,我们使用tornado开发了一个api系统,系统开发完后,在8核16G的虚机上经过压测qps只有200+。与我们当...

    Doyle 评论0 收藏0
  • [零基础学python]探析get和post方法

    摘要:特别提醒,看官不要自宫,因为本教程不是辟邪剑谱,也不是葵花宝典,撰写本课程的人更是生理健全者。直到目前,科学上尚未有证实或证伪自宫和写程序之间是否存在某种因果关系。和是中用的最多的方法啦。 Do not store up for yourselves treasures on earth, where moth and rust consume and where thieves...

    AaronYuan 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<