Source code for tornado.tcpclient

#!/usr/bin/env python## Copyright 2014 Facebook## Licensed under the Apache License, Version 2.0 (the "License"); you may# not use this file except in compliance with the License. You may obtain# a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the# License for the specific language governing permissions and limitations# under the License."""A non-blocking TCP connection factory."""from__future__importabsolute_import,division,print_function,with_statementimportfunctoolsimportsocketfromtornado.concurrentimportFuturefromtornado.ioloopimportIOLoopfromtornado.iostreamimportIOStreamfromtornadoimportgenfromtornado.netutilimportResolver_INITIAL_CONNECT_TIMEOUT=0.3class_Connector(object):"""A stateless implementation of the "Happy Eyeballs" algorithm. "Happy Eyeballs" is documented in RFC6555 as the recommended practice for when both IPv4 and IPv6 addresses are available. In this implementation, we partition the addresses by family, and make the first connection attempt to whichever address was returned first by ``getaddrinfo``. If that connection fails or times out, we begin a connection in parallel to the first address of the other family. If there are additional failures we retry with other addresses, keeping one connection attempt per family in flight at a time. http://tools.ietf.org/html/rfc6555 """def__init__(self,addrinfo,io_loop,connect):self.io_loop=io_loopself.connect=connectself.future=Future()self.timeout=Noneself.last_error=Noneself.remaining=len(addrinfo)self.primary_addrs,self.secondary_addrs=self.split(addrinfo)@staticmethoddefsplit(addrinfo):"""Partition the ``addrinfo`` list by address family. Returns two lists. The first list contains the first entry from ``addrinfo`` and all others with the same family, and the second list contains all other addresses (normally one list will be AF_INET and the other AF_INET6, although non-standard resolvers may return additional families). """primary=[]secondary=[]primary_af=addrinfo[0][0]foraf,addrinaddrinfo:ifaf==primary_af:primary.append((af,addr))else:secondary.append((af,addr))returnprimary,secondarydefstart(self,timeout=_INITIAL_CONNECT_TIMEOUT):self.try_connect(iter(self.primary_addrs))self.set_timout(timeout)returnself.futuredeftry_connect(self,addrs):try:af,addr=next(addrs)exceptStopIteration:# We've reached the end of our queue, but the other queue# might still be working. Send a final error on the future# only when both queues are finished.ifself.remaining==0andnotself.future.done():self.future.set_exception(self.last_errororIOError("connection failed"))returnfuture=self.connect(af,addr)future.add_done_callback(functools.partial(self.on_connect_done,addrs,af,addr))defon_connect_done(self,addrs,af,addr,future):self.remaining-=1try:stream=future.result()exceptExceptionase:ifself.future.done():return# Error: try again (but remember what happened so we have an# error to raise in the end)self.last_error=eself.try_connect(addrs)ifself.timeoutisnotNone:# If the first attempt failed, don't wait for the# timeout to try an address from the secondary queue.self.io_loop.remove_timeout(self.timeout)self.on_timeout()returnself.clear_timeout()ifself.future.done():# This is a late arrival; just drop it.stream.close()else:self.future.set_result((af,addr,stream))defset_timout(self,timeout):self.timeout=self.io_loop.add_timeout(self.io_loop.time()+timeout,self.on_timeout)defon_timeout(self):self.timeout=Noneself.try_connect(iter(self.secondary_addrs))defclear_timeout(self):ifself.timeoutisnotNone:self.io_loop.remove_timeout(self.timeout)

[docs]defconnect(self,host,port,af=socket.AF_UNSPEC,ssl_options=None,max_buffer_size=None):"""Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). """addrinfo=yieldself.resolver.resolve(host,port,af)connector=_Connector(addrinfo,self.io_loop,functools.partial(self._create_stream,max_buffer_size))af,addr,stream=yieldconnector.start()# TODO: For better performance we could cache the (af, addr)# information here and re-use it on subsequent connections to# the same host. (http://tools.ietf.org/html/rfc6555#section-4.2)ifssl_optionsisnotNone:stream=yieldstream.start_tls(False,ssl_options=ssl_options,server_hostname=host)raisegen.Return(stream)

def_create_stream(self,max_buffer_size,af,addr):# Always connect in plaintext; we'll convert to ssl if necessary# after one connection has completed.stream=IOStream(socket.socket(af),io_loop=self.io_loop,max_buffer_size=max_buffer_size)returnstream.connect(addr)