tcpclient.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. #
  2. # Copyright 2014 Facebook
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. """A non-blocking TCP connection factory.
  16. """
  17. from __future__ import absolute_import, division, print_function
  18. import functools
  19. import socket
  20. import numbers
  21. import datetime
  22. from tornado.concurrent import Future, future_add_done_callback
  23. from tornado.ioloop import IOLoop
  24. from tornado.iostream import IOStream
  25. from tornado import gen
  26. from tornado.netutil import Resolver
  27. from tornado.platform.auto import set_close_exec
  28. from tornado.gen import TimeoutError
  29. from tornado.util import timedelta_to_seconds
  30. _INITIAL_CONNECT_TIMEOUT = 0.3
  31. class _Connector(object):
  32. """A stateless implementation of the "Happy Eyeballs" algorithm.
  33. "Happy Eyeballs" is documented in RFC6555 as the recommended practice
  34. for when both IPv4 and IPv6 addresses are available.
  35. In this implementation, we partition the addresses by family, and
  36. make the first connection attempt to whichever address was
  37. returned first by ``getaddrinfo``. If that connection fails or
  38. times out, we begin a connection in parallel to the first address
  39. of the other family. If there are additional failures we retry
  40. with other addresses, keeping one connection attempt per family
  41. in flight at a time.
  42. http://tools.ietf.org/html/rfc6555
  43. """
  44. def __init__(self, addrinfo, connect):
  45. self.io_loop = IOLoop.current()
  46. self.connect = connect
  47. self.future = Future()
  48. self.timeout = None
  49. self.connect_timeout = None
  50. self.last_error = None
  51. self.remaining = len(addrinfo)
  52. self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
  53. self.streams = set()
  54. @staticmethod
  55. def split(addrinfo):
  56. """Partition the ``addrinfo`` list by address family.
  57. Returns two lists. The first list contains the first entry from
  58. ``addrinfo`` and all others with the same family, and the
  59. second list contains all other addresses (normally one list will
  60. be AF_INET and the other AF_INET6, although non-standard resolvers
  61. may return additional families).
  62. """
  63. primary = []
  64. secondary = []
  65. primary_af = addrinfo[0][0]
  66. for af, addr in addrinfo:
  67. if af == primary_af:
  68. primary.append((af, addr))
  69. else:
  70. secondary.append((af, addr))
  71. return primary, secondary
  72. def start(self, timeout=_INITIAL_CONNECT_TIMEOUT, connect_timeout=None):
  73. self.try_connect(iter(self.primary_addrs))
  74. self.set_timeout(timeout)
  75. if connect_timeout is not None:
  76. self.set_connect_timeout(connect_timeout)
  77. return self.future
  78. def try_connect(self, addrs):
  79. try:
  80. af, addr = next(addrs)
  81. except StopIteration:
  82. # We've reached the end of our queue, but the other queue
  83. # might still be working. Send a final error on the future
  84. # only when both queues are finished.
  85. if self.remaining == 0 and not self.future.done():
  86. self.future.set_exception(self.last_error or
  87. IOError("connection failed"))
  88. return
  89. stream, future = self.connect(af, addr)
  90. self.streams.add(stream)
  91. future_add_done_callback(
  92. future, functools.partial(self.on_connect_done, addrs, af, addr))
  93. def on_connect_done(self, addrs, af, addr, future):
  94. self.remaining -= 1
  95. try:
  96. stream = future.result()
  97. except Exception as e:
  98. if self.future.done():
  99. return
  100. # Error: try again (but remember what happened so we have an
  101. # error to raise in the end)
  102. self.last_error = e
  103. self.try_connect(addrs)
  104. if self.timeout is not None:
  105. # If the first attempt failed, don't wait for the
  106. # timeout to try an address from the secondary queue.
  107. self.io_loop.remove_timeout(self.timeout)
  108. self.on_timeout()
  109. return
  110. self.clear_timeouts()
  111. if self.future.done():
  112. # This is a late arrival; just drop it.
  113. stream.close()
  114. else:
  115. self.streams.discard(stream)
  116. self.future.set_result((af, addr, stream))
  117. self.close_streams()
  118. def set_timeout(self, timeout):
  119. self.timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,
  120. self.on_timeout)
  121. def on_timeout(self):
  122. self.timeout = None
  123. if not self.future.done():
  124. self.try_connect(iter(self.secondary_addrs))
  125. def clear_timeout(self):
  126. if self.timeout is not None:
  127. self.io_loop.remove_timeout(self.timeout)
  128. def set_connect_timeout(self, connect_timeout):
  129. self.connect_timeout = self.io_loop.add_timeout(
  130. connect_timeout, self.on_connect_timeout)
  131. def on_connect_timeout(self):
  132. if not self.future.done():
  133. self.future.set_exception(TimeoutError())
  134. self.close_streams()
  135. def clear_timeouts(self):
  136. if self.timeout is not None:
  137. self.io_loop.remove_timeout(self.timeout)
  138. if self.connect_timeout is not None:
  139. self.io_loop.remove_timeout(self.connect_timeout)
  140. def close_streams(self):
  141. for stream in self.streams:
  142. stream.close()
  143. class TCPClient(object):
  144. """A non-blocking TCP connection factory.
  145. .. versionchanged:: 5.0
  146. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  147. """
  148. def __init__(self, resolver=None):
  149. if resolver is not None:
  150. self.resolver = resolver
  151. self._own_resolver = False
  152. else:
  153. self.resolver = Resolver()
  154. self._own_resolver = True
  155. def close(self):
  156. if self._own_resolver:
  157. self.resolver.close()
  158. @gen.coroutine
  159. def connect(self, host, port, af=socket.AF_UNSPEC, ssl_options=None,
  160. max_buffer_size=None, source_ip=None, source_port=None,
  161. timeout=None):
  162. """Connect to the given host and port.
  163. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if
  164. ``ssl_options`` is not None).
  165. Using the ``source_ip`` kwarg, one can specify the source
  166. IP address to use when establishing the connection.
  167. In case the user needs to resolve and
  168. use a specific interface, it has to be handled outside
  169. of Tornado as this depends very much on the platform.
  170. Raises `TimeoutError` if the input future does not complete before
  171. ``timeout``, which may be specified in any form allowed by
  172. `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
  173. relative to `.IOLoop.time`)
  174. Similarly, when the user requires a certain source port, it can
  175. be specified using the ``source_port`` arg.
  176. .. versionchanged:: 4.5
  177. Added the ``source_ip`` and ``source_port`` arguments.
  178. .. versionchanged:: 5.0
  179. Added the ``timeout`` argument.
  180. """
  181. if timeout is not None:
  182. if isinstance(timeout, numbers.Real):
  183. timeout = IOLoop.current().time() + timeout
  184. elif isinstance(timeout, datetime.timedelta):
  185. timeout = IOLoop.current().time() + timedelta_to_seconds(timeout)
  186. else:
  187. raise TypeError("Unsupported timeout %r" % timeout)
  188. if timeout is not None:
  189. addrinfo = yield gen.with_timeout(
  190. timeout, self.resolver.resolve(host, port, af))
  191. else:
  192. addrinfo = yield self.resolver.resolve(host, port, af)
  193. connector = _Connector(
  194. addrinfo,
  195. functools.partial(self._create_stream, max_buffer_size,
  196. source_ip=source_ip, source_port=source_port)
  197. )
  198. af, addr, stream = yield connector.start(connect_timeout=timeout)
  199. # TODO: For better performance we could cache the (af, addr)
  200. # information here and re-use it on subsequent connections to
  201. # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)
  202. if ssl_options is not None:
  203. if timeout is not None:
  204. stream = yield gen.with_timeout(timeout, stream.start_tls(
  205. False, ssl_options=ssl_options, server_hostname=host))
  206. else:
  207. stream = yield stream.start_tls(False, ssl_options=ssl_options,
  208. server_hostname=host)
  209. raise gen.Return(stream)
  210. def _create_stream(self, max_buffer_size, af, addr, source_ip=None,
  211. source_port=None):
  212. # Always connect in plaintext; we'll convert to ssl if necessary
  213. # after one connection has completed.
  214. source_port_bind = source_port if isinstance(source_port, int) else 0
  215. source_ip_bind = source_ip
  216. if source_port_bind and not source_ip:
  217. # User required a specific port, but did not specify
  218. # a certain source IP, will bind to the default loopback.
  219. source_ip_bind = '::1' if af == socket.AF_INET6 else '127.0.0.1'
  220. # Trying to use the same address family as the requested af socket:
  221. # - 127.0.0.1 for IPv4
  222. # - ::1 for IPv6
  223. socket_obj = socket.socket(af)
  224. set_close_exec(socket_obj.fileno())
  225. if source_port_bind or source_ip_bind:
  226. # If the user requires binding also to a specific IP/port.
  227. try:
  228. socket_obj.bind((source_ip_bind, source_port_bind))
  229. except socket.error:
  230. socket_obj.close()
  231. # Fail loudly if unable to use the IP/port.
  232. raise
  233. try:
  234. stream = IOStream(socket_obj,
  235. max_buffer_size=max_buffer_size)
  236. except socket.error as e:
  237. fu = Future()
  238. fu.set_exception(e)
  239. return fu
  240. else:
  241. return stream, stream.connect(addr)