tcpclient.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. import functools
  18. import socket
  19. import numbers
  20. import datetime
  21. import ssl
  22. import typing
  23. from tornado.concurrent import Future, future_add_done_callback
  24. from tornado.ioloop import IOLoop
  25. from tornado.iostream import IOStream
  26. from tornado import gen
  27. from tornado.netutil import Resolver
  28. from tornado.gen import TimeoutError
  29. from typing import Any, Union, Dict, Tuple, List, Callable, Iterator, Optional
  30. if typing.TYPE_CHECKING:
  31. from typing import Set # noqa(F401)
  32. _INITIAL_CONNECT_TIMEOUT = 0.3
  33. class _Connector:
  34. """A stateless implementation of the "Happy Eyeballs" algorithm.
  35. "Happy Eyeballs" is documented in RFC6555 as the recommended practice
  36. for when both IPv4 and IPv6 addresses are available.
  37. In this implementation, we partition the addresses by family, and
  38. make the first connection attempt to whichever address was
  39. returned first by ``getaddrinfo``. If that connection fails or
  40. times out, we begin a connection in parallel to the first address
  41. of the other family. If there are additional failures we retry
  42. with other addresses, keeping one connection attempt per family
  43. in flight at a time.
  44. http://tools.ietf.org/html/rfc6555
  45. """
  46. def __init__(
  47. self,
  48. addrinfo: List[Tuple],
  49. connect: Callable[
  50. [socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
  51. ],
  52. ) -> None:
  53. self.io_loop = IOLoop.current()
  54. self.connect = connect
  55. self.future = (
  56. Future()
  57. ) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
  58. self.timeout = None # type: Optional[object]
  59. self.connect_timeout = None # type: Optional[object]
  60. self.last_error = None # type: Optional[Exception]
  61. self.remaining = len(addrinfo)
  62. self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
  63. self.streams = set() # type: Set[IOStream]
  64. @staticmethod
  65. def split(
  66. addrinfo: List[Tuple],
  67. ) -> Tuple[
  68. List[Tuple[socket.AddressFamily, Tuple]],
  69. List[Tuple[socket.AddressFamily, Tuple]],
  70. ]:
  71. """Partition the ``addrinfo`` list by address family.
  72. Returns two lists. The first list contains the first entry from
  73. ``addrinfo`` and all others with the same family, and the
  74. second list contains all other addresses (normally one list will
  75. be AF_INET and the other AF_INET6, although non-standard resolvers
  76. may return additional families).
  77. """
  78. primary = []
  79. secondary = []
  80. primary_af = addrinfo[0][0]
  81. for af, addr in addrinfo:
  82. if af == primary_af:
  83. primary.append((af, addr))
  84. else:
  85. secondary.append((af, addr))
  86. return primary, secondary
  87. def start(
  88. self,
  89. timeout: float = _INITIAL_CONNECT_TIMEOUT,
  90. connect_timeout: Optional[Union[float, datetime.timedelta]] = None,
  91. ) -> "Future[Tuple[socket.AddressFamily, Any, IOStream]]":
  92. self.try_connect(iter(self.primary_addrs))
  93. self.set_timeout(timeout)
  94. if connect_timeout is not None:
  95. self.set_connect_timeout(connect_timeout)
  96. return self.future
  97. def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None:
  98. try:
  99. af, addr = next(addrs)
  100. except StopIteration:
  101. # We've reached the end of our queue, but the other queue
  102. # might still be working. Send a final error on the future
  103. # only when both queues are finished.
  104. if self.remaining == 0 and not self.future.done():
  105. self.future.set_exception(
  106. self.last_error or IOError("connection failed")
  107. )
  108. return
  109. stream, future = self.connect(af, addr)
  110. self.streams.add(stream)
  111. future_add_done_callback(
  112. future, functools.partial(self.on_connect_done, addrs, af, addr)
  113. )
  114. def on_connect_done(
  115. self,
  116. addrs: Iterator[Tuple[socket.AddressFamily, Tuple]],
  117. af: socket.AddressFamily,
  118. addr: Tuple,
  119. future: "Future[IOStream]",
  120. ) -> None:
  121. self.remaining -= 1
  122. try:
  123. stream = future.result()
  124. except Exception as e:
  125. if self.future.done():
  126. return
  127. # Error: try again (but remember what happened so we have an
  128. # error to raise in the end)
  129. self.last_error = e
  130. self.try_connect(addrs)
  131. if self.timeout is not None:
  132. # If the first attempt failed, don't wait for the
  133. # timeout to try an address from the secondary queue.
  134. self.io_loop.remove_timeout(self.timeout)
  135. self.on_timeout()
  136. return
  137. self.clear_timeouts()
  138. if self.future.done():
  139. # This is a late arrival; just drop it.
  140. stream.close()
  141. else:
  142. self.streams.discard(stream)
  143. self.future.set_result((af, addr, stream))
  144. self.close_streams()
  145. def set_timeout(self, timeout: float) -> None:
  146. self.timeout = self.io_loop.add_timeout(
  147. self.io_loop.time() + timeout, self.on_timeout
  148. )
  149. def on_timeout(self) -> None:
  150. self.timeout = None
  151. if not self.future.done():
  152. self.try_connect(iter(self.secondary_addrs))
  153. def clear_timeout(self) -> None:
  154. if self.timeout is not None:
  155. self.io_loop.remove_timeout(self.timeout)
  156. def set_connect_timeout(
  157. self, connect_timeout: Union[float, datetime.timedelta]
  158. ) -> None:
  159. self.connect_timeout = self.io_loop.add_timeout(
  160. connect_timeout, self.on_connect_timeout
  161. )
  162. def on_connect_timeout(self) -> None:
  163. if not self.future.done():
  164. self.future.set_exception(TimeoutError())
  165. self.close_streams()
  166. def clear_timeouts(self) -> None:
  167. if self.timeout is not None:
  168. self.io_loop.remove_timeout(self.timeout)
  169. if self.connect_timeout is not None:
  170. self.io_loop.remove_timeout(self.connect_timeout)
  171. def close_streams(self) -> None:
  172. for stream in self.streams:
  173. stream.close()
  174. class TCPClient:
  175. """A non-blocking TCP connection factory.
  176. .. versionchanged:: 5.0
  177. The ``io_loop`` argument (deprecated since version 4.1) has been removed.
  178. """
  179. def __init__(self, resolver: Optional[Resolver] = None) -> None:
  180. if resolver is not None:
  181. self.resolver = resolver
  182. self._own_resolver = False
  183. else:
  184. self.resolver = Resolver()
  185. self._own_resolver = True
  186. def close(self) -> None:
  187. if self._own_resolver:
  188. self.resolver.close()
  189. async def connect(
  190. self,
  191. host: str,
  192. port: int,
  193. af: socket.AddressFamily = socket.AF_UNSPEC,
  194. ssl_options: Optional[Union[Dict[str, Any], ssl.SSLContext]] = None,
  195. max_buffer_size: Optional[int] = None,
  196. source_ip: Optional[str] = None,
  197. source_port: Optional[int] = None,
  198. timeout: Optional[Union[float, datetime.timedelta]] = None,
  199. ) -> IOStream:
  200. """Connect to the given host and port.
  201. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if
  202. ``ssl_options`` is not None).
  203. Using the ``source_ip`` kwarg, one can specify the source
  204. IP address to use when establishing the connection.
  205. In case the user needs to resolve and
  206. use a specific interface, it has to be handled outside
  207. of Tornado as this depends very much on the platform.
  208. Raises `TimeoutError` if the input future does not complete before
  209. ``timeout``, which may be specified in any form allowed by
  210. `.IOLoop.add_timeout` (i.e. a `datetime.timedelta` or an absolute time
  211. relative to `.IOLoop.time`)
  212. Similarly, when the user requires a certain source port, it can
  213. be specified using the ``source_port`` arg.
  214. .. versionchanged:: 4.5
  215. Added the ``source_ip`` and ``source_port`` arguments.
  216. .. versionchanged:: 5.0
  217. Added the ``timeout`` argument.
  218. """
  219. if timeout is not None:
  220. if isinstance(timeout, numbers.Real):
  221. timeout = IOLoop.current().time() + timeout
  222. elif isinstance(timeout, datetime.timedelta):
  223. timeout = IOLoop.current().time() + timeout.total_seconds()
  224. else:
  225. raise TypeError("Unsupported timeout %r" % timeout)
  226. if timeout is not None:
  227. addrinfo = await gen.with_timeout(
  228. timeout, self.resolver.resolve(host, port, af)
  229. )
  230. else:
  231. addrinfo = await self.resolver.resolve(host, port, af)
  232. connector = _Connector(
  233. addrinfo,
  234. functools.partial(
  235. self._create_stream,
  236. max_buffer_size,
  237. source_ip=source_ip,
  238. source_port=source_port,
  239. ),
  240. )
  241. af, addr, stream = await connector.start(connect_timeout=timeout)
  242. # TODO: For better performance we could cache the (af, addr)
  243. # information here and re-use it on subsequent connections to
  244. # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)
  245. if ssl_options is not None:
  246. if timeout is not None:
  247. stream = await gen.with_timeout(
  248. timeout,
  249. stream.start_tls(
  250. False, ssl_options=ssl_options, server_hostname=host
  251. ),
  252. )
  253. else:
  254. stream = await stream.start_tls(
  255. False, ssl_options=ssl_options, server_hostname=host
  256. )
  257. return stream
  258. def _create_stream(
  259. self,
  260. max_buffer_size: int,
  261. af: socket.AddressFamily,
  262. addr: Tuple,
  263. source_ip: Optional[str] = None,
  264. source_port: Optional[int] = None,
  265. ) -> Tuple[IOStream, "Future[IOStream]"]:
  266. # Always connect in plaintext; we'll convert to ssl if necessary
  267. # after one connection has completed.
  268. source_port_bind = source_port if isinstance(source_port, int) else 0
  269. source_ip_bind = source_ip
  270. if source_port_bind and not source_ip:
  271. # User required a specific port, but did not specify
  272. # a certain source IP, will bind to the default loopback.
  273. source_ip_bind = "::1" if af == socket.AF_INET6 else "127.0.0.1"
  274. # Trying to use the same address family as the requested af socket:
  275. # - 127.0.0.1 for IPv4
  276. # - ::1 for IPv6
  277. socket_obj = socket.socket(af)
  278. if source_port_bind or source_ip_bind:
  279. # If the user requires binding also to a specific IP/port.
  280. try:
  281. socket_obj.bind((source_ip_bind, source_port_bind))
  282. except OSError:
  283. socket_obj.close()
  284. # Fail loudly if unable to use the IP/port.
  285. raise
  286. try:
  287. stream = IOStream(socket_obj, max_buffer_size=max_buffer_size)
  288. except OSError as e:
  289. fu = Future() # type: Future[IOStream]
  290. fu.set_exception(e)
  291. return stream, fu
  292. else:
  293. return stream, stream.connect(addr)