tcpclient.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2014 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """A non-blocking TCP connection factory.
  17. """
  18. from __future__ import absolute_import, division, print_function, with_statement
  19. import functools
  20. import socket
  21. from tornado.concurrent import Future
  22. from tornado.ioloop import IOLoop
  23. from tornado.iostream import IOStream
  24. from tornado import gen
  25. from tornado.netutil import Resolver
  26. _INITIAL_CONNECT_TIMEOUT = 0.3
  27. class _Connector(object):
  28. """A stateless implementation of the "Happy Eyeballs" algorithm.
  29. "Happy Eyeballs" is documented in RFC6555 as the recommended practice
  30. for when both IPv4 and IPv6 addresses are available.
  31. In this implementation, we partition the addresses by family, and
  32. make the first connection attempt to whichever address was
  33. returned first by ``getaddrinfo``. If that connection fails or
  34. times out, we begin a connection in parallel to the first address
  35. of the other family. If there are additional failures we retry
  36. with other addresses, keeping one connection attempt per family
  37. in flight at a time.
  38. http://tools.ietf.org/html/rfc6555
  39. """
  40. def __init__(self, addrinfo, io_loop, connect):
  41. self.io_loop = io_loop
  42. self.connect = connect
  43. self.future = Future()
  44. self.timeout = None
  45. self.last_error = None
  46. self.remaining = len(addrinfo)
  47. self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
  48. @staticmethod
  49. def split(addrinfo):
  50. """Partition the ``addrinfo`` list by address family.
  51. Returns two lists. The first list contains the first entry from
  52. ``addrinfo`` and all others with the same family, and the
  53. second list contains all other addresses (normally one list will
  54. be AF_INET and the other AF_INET6, although non-standard resolvers
  55. may return additional families).
  56. """
  57. primary = []
  58. secondary = []
  59. primary_af = addrinfo[0][0]
  60. for af, addr in addrinfo:
  61. if af == primary_af:
  62. primary.append((af, addr))
  63. else:
  64. secondary.append((af, addr))
  65. return primary, secondary
  66. def start(self, timeout=_INITIAL_CONNECT_TIMEOUT):
  67. self.try_connect(iter(self.primary_addrs))
  68. self.set_timout(timeout)
  69. return self.future
  70. def try_connect(self, addrs):
  71. try:
  72. af, addr = next(addrs)
  73. except StopIteration:
  74. # We've reached the end of our queue, but the other queue
  75. # might still be working. Send a final error on the future
  76. # only when both queues are finished.
  77. if self.remaining == 0 and not self.future.done():
  78. self.future.set_exception(self.last_error or
  79. IOError("connection failed"))
  80. return
  81. future = self.connect(af, addr)
  82. future.add_done_callback(functools.partial(self.on_connect_done,
  83. addrs, af, addr))
  84. def on_connect_done(self, addrs, af, addr, future):
  85. self.remaining -= 1
  86. try:
  87. stream = future.result()
  88. except Exception as e:
  89. if self.future.done():
  90. return
  91. # Error: try again (but remember what happened so we have an
  92. # error to raise in the end)
  93. self.last_error = e
  94. self.try_connect(addrs)
  95. if self.timeout is not None:
  96. # If the first attempt failed, don't wait for the
  97. # timeout to try an address from the secondary queue.
  98. self.io_loop.remove_timeout(self.timeout)
  99. self.on_timeout()
  100. return
  101. self.clear_timeout()
  102. if self.future.done():
  103. # This is a late arrival; just drop it.
  104. stream.close()
  105. else:
  106. self.future.set_result((af, addr, stream))
  107. def set_timout(self, timeout):
  108. self.timeout = self.io_loop.add_timeout(self.io_loop.time() + timeout,
  109. self.on_timeout)
  110. def on_timeout(self):
  111. self.timeout = None
  112. self.try_connect(iter(self.secondary_addrs))
  113. def clear_timeout(self):
  114. if self.timeout is not None:
  115. self.io_loop.remove_timeout(self.timeout)
  116. class TCPClient(object):
  117. """A non-blocking TCP connection factory.
  118. .. versionchanged:: 4.1
  119. The ``io_loop`` argument is deprecated.
  120. """
  121. def __init__(self, resolver=None, io_loop=None):
  122. self.io_loop = io_loop or IOLoop.current()
  123. if resolver is not None:
  124. self.resolver = resolver
  125. self._own_resolver = False
  126. else:
  127. self.resolver = Resolver(io_loop=io_loop)
  128. self._own_resolver = True
  129. def close(self):
  130. if self._own_resolver:
  131. self.resolver.close()
  132. @gen.coroutine
  133. def connect(self, host, port, af=socket.AF_UNSPEC, ssl_options=None,
  134. max_buffer_size=None):
  135. """Connect to the given host and port.
  136. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if
  137. ``ssl_options`` is not None).
  138. """
  139. addrinfo = yield self.resolver.resolve(host, port, af)
  140. connector = _Connector(
  141. addrinfo, self.io_loop,
  142. functools.partial(self._create_stream, max_buffer_size))
  143. af, addr, stream = yield connector.start()
  144. # TODO: For better performance we could cache the (af, addr)
  145. # information here and re-use it on subsequent connections to
  146. # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)
  147. if ssl_options is not None:
  148. stream = yield stream.start_tls(False, ssl_options=ssl_options,
  149. server_hostname=host)
  150. raise gen.Return(stream)
  151. def _create_stream(self, max_buffer_size, af, addr):
  152. # Always connect in plaintext; we'll convert to ssl if necessary
  153. # after one connection has completed.
  154. stream = IOStream(socket.socket(af),
  155. io_loop=self.io_loop,
  156. max_buffer_size=max_buffer_size)
  157. return stream.connect(addr)