Navigation

Source code for tornado.iostream

#!/usr/bin/env python## Copyright 2009 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 utility class to write to and read from a non-blocking socket."""from__future__importwith_statementimportcollectionsimporterrnoimportloggingimportsocketimportsysimportrefromtornadoimportioloopfromtornadoimportstack_contextfromtornado.utilimportb,bytes_typetry:importssl# Python 2.6+exceptImportError:ssl=None

[docs]classIOStream(object):r"""A utility class to write to and read from a non-blocking socket. We support a non-blocking ``write()`` and a family of ``read_*()`` methods. All of the methods take callbacks (since writing and reading are non-blocking and asynchronous). The socket parameter may either be connected or unconnected. For server operations the socket is the result of calling socket.accept(). For client operations the socket is created with socket.socket(), and may either be connected before passing it to the IOStream or connected with IOStream.connect. A very simple (and broken) HTTP client using this class:: from tornado import ioloop from tornado import iostream import socket def send_request(): stream.write("GET / HTTP/1.0\r\nHost: friendfeed.com\r\n\r\n") stream.read_until("\r\n\r\n", on_headers) def on_headers(data): headers = {} for line in data.split("\r\n"): parts = line.split(":") if len(parts) == 2: headers[parts[0].strip()] = parts[1].strip() stream.read_bytes(int(headers["Content-Length"]), on_body) def on_body(data): print data stream.close() ioloop.IOLoop.instance().stop() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) stream = iostream.IOStream(s) stream.connect(("friendfeed.com", 80), send_request) ioloop.IOLoop.instance().start() """def__init__(self,socket,io_loop=None,max_buffer_size=104857600,read_chunk_size=4096):self.socket=socketself.socket.setblocking(False)self.io_loop=io_looporioloop.IOLoop.instance()self.max_buffer_size=max_buffer_sizeself.read_chunk_size=read_chunk_sizeself._read_buffer=collections.deque()self._write_buffer=collections.deque()self._read_buffer_size=0self._write_buffer_frozen=Falseself._read_delimiter=Noneself._read_regex=Noneself._read_bytes=Noneself._read_until_close=Falseself._read_callback=Noneself._streaming_callback=Noneself._write_callback=Noneself._close_callback=Noneself._connect_callback=Noneself._connecting=Falseself._state=Noneself._pending_callbacks=0

[docs]defconnect(self,address,callback=None):"""Connects the socket to a remote address without blocking. May only be called if the socket passed to the constructor was not previously connected. The address parameter is in the same format as for socket.connect, i.e. a (host, port) tuple. If callback is specified, it will be called when the connection is completed. Note that it is safe to call IOStream.write while the connection is pending, in which case the data will be written as soon as the connection is ready. Calling IOStream read methods before the socket is connected works on some platforms but is non-portable. """self._connecting=Truetry:self.socket.connect(address)exceptsocket.error,e:# In non-blocking mode we expect connect() to raise an# exception with EINPROGRESS or EWOULDBLOCK.## On freebsd, other errors such as ECONNREFUSED may be# returned immediately when attempting to connect to# localhost, so handle them the same way as an error# reported later in _handle_connect.ife.args[0]notin(errno.EINPROGRESS,errno.EWOULDBLOCK):logging.warning("Connect error on fd %d: %s",self.socket.fileno(),e)self.close()returnself._connect_callback=stack_context.wrap(callback)self._add_io_state(self.io_loop.WRITE)

[docs]defread_until_regex(self,regex,callback):"""Call callback when we read the given regex pattern."""assertnotself._read_callback,"Already reading"self._read_regex=re.compile(regex)self._read_callback=stack_context.wrap(callback)whileTrue:# See if we've already got the data from a previous readifself._read_from_buffer():returnself._check_closed()ifself._read_to_buffer()==0:breakself._add_io_state(self.io_loop.READ)

[docs]defread_until(self,delimiter,callback):"""Call callback when we read the given delimiter."""assertnotself._read_callback,"Already reading"self._read_delimiter=delimiterself._read_callback=stack_context.wrap(callback)whileTrue:# See if we've already got the data from a previous readifself._read_from_buffer():returnself._check_closed()ifself._read_to_buffer()==0:breakself._add_io_state(self.io_loop.READ)

[docs]defread_bytes(self,num_bytes,callback,streaming_callback=None):"""Call callback when we read the given number of bytes. If a ``streaming_callback`` is given, it will be called with chunks of data as they become available, and the argument to the final ``callback`` will be empty. """assertnotself._read_callback,"Already reading"assertisinstance(num_bytes,(int,long))self._read_bytes=num_bytesself._read_callback=stack_context.wrap(callback)self._streaming_callback=stack_context.wrap(streaming_callback)whileTrue:ifself._read_from_buffer():returnself._check_closed()ifself._read_to_buffer()==0:breakself._add_io_state(self.io_loop.READ)

[docs]defread_until_close(self,callback,streaming_callback=None):"""Reads all data from the socket until it is closed. If a ``streaming_callback`` is given, it will be called with chunks of data as they become available, and the argument to the final ``callback`` will be empty. Subject to ``max_buffer_size`` limit from `IOStream` constructor if a ``streaming_callback`` is not used. """assertnotself._read_callback,"Already reading"ifself.closed():self._run_callback(callback,self._consume(self._read_buffer_size))returnself._read_until_close=Trueself._read_callback=stack_context.wrap(callback)self._streaming_callback=stack_context.wrap(streaming_callback)self._add_io_state(self.io_loop.READ)

[docs]defwrite(self,data,callback=None):"""Write the given data to this stream. If callback is given, we call it when all of the buffered write data has been successfully written to the stream. If there was previously buffered write data and an old write callback, that callback is simply overwritten with this new callback. """assertisinstance(data,bytes_type)self._check_closed()self._write_buffer.append(data)self._write_callback=stack_context.wrap(callback)self._handle_write()ifself._write_buffer:self._add_io_state(self.io_loop.WRITE)self._maybe_add_error_listener()

[docs]defset_close_callback(self,callback):"""Call the given callback when the stream is closed."""self._close_callback=stack_context.wrap(callback)

[docs]defclose(self):"""Close this stream."""ifself.socketisnotNone:ifself._read_until_close:callback=self._read_callbackself._read_callback=Noneself._read_until_close=Falseself._run_callback(callback,self._consume(self._read_buffer_size))ifself._stateisnotNone:self.io_loop.remove_handler(self.socket.fileno())self._state=Noneself.socket.close()self.socket=Noneifself._close_callbackandself._pending_callbacks==0:# if there are pending callbacks, don't run the close callback# until they're done (see _maybe_add_error_handler)cb=self._close_callbackself._close_callback=Noneself._run_callback(cb)

[docs]defreading(self):"""Returns true if we are currently reading from the stream."""returnself._read_callbackisnotNone

[docs]defwriting(self):"""Returns true if we are currently writing to the stream."""returnbool(self._write_buffer)

[docs]defclosed(self):"""Returns true if the stream has been closed."""returnself.socketisNone

def_handle_events(self,fd,events):ifnotself.socket:logging.warning("Got events for closed stream %d",fd)returntry:ifevents&self.io_loop.READ:self._handle_read()ifnotself.socket:returnifevents&self.io_loop.WRITE:ifself._connecting:self._handle_connect()self._handle_write()ifnotself.socket:returnifevents&self.io_loop.ERROR:# We may have queued up a user callback in _handle_read or# _handle_write, so don't close the IOStream until those# callbacks have had a chance to run.self.io_loop.add_callback(self.close)returnstate=self.io_loop.ERRORifself.reading():state|=self.io_loop.READifself.writing():state|=self.io_loop.WRITEifstate==self.io_loop.ERROR:state|=self.io_loop.READifstate!=self._state:assertself._stateisnotNone, \
"shouldn't happen: _handle_events without self._state"self._state=stateself.io_loop.update_handler(self.socket.fileno(),self._state)exceptException:logging.error("Uncaught exception, closing connection.",exc_info=True)self.close()raisedef_run_callback(self,callback,*args):defwrapper():self._pending_callbacks-=1try:callback(*args)exceptException:logging.error("Uncaught exception, closing connection.",exc_info=True)# Close the socket on an uncaught exception from a user callback# (It would eventually get closed when the socket object is# gc'd, but we don't want to rely on gc happening before we# run out of file descriptors)self.close()# Re-raise the exception so that IOLoop.handle_callback_exception# can see it and log the errorraiseself._maybe_add_error_listener()# We schedule callbacks to be run on the next IOLoop iteration# rather than running them directly for several reasons:# * Prevents unbounded stack growth when a callback calls an# IOLoop operation that immediately runs another callback# * Provides a predictable execution context for e.g.# non-reentrant mutexes# * Ensures that the try/except in wrapper() is run outside# of the application's StackContextswithstack_context.NullContext():# stack_context was already captured in callback, we don't need to# capture it again for IOStream's wrapper. This is especially# important if the callback was pre-wrapped before entry to# IOStream (as in HTTPConnection._header_callback), as we could# capture and leak the wrong context here.self._pending_callbacks+=1self.io_loop.add_callback(wrapper)def_handle_read(self):whileTrue:try:# Read from the socket until we get EWOULDBLOCK or equivalent.# SSL sockets do some internal buffering, and if the data is# sitting in the SSL object's buffer select() and friends# can't see it; the only way to find out if it's there is to# try to read it.result=self._read_to_buffer()exceptException:self.close()returnifresult==0:breakelse:ifself._read_from_buffer():returndef_read_from_socket(self):"""Attempts to read from the socket. Returns the data read or None if there is nothing to read. May be overridden in subclasses. """try:chunk=self.socket.recv(self.read_chunk_size)exceptsocket.error,e:ife.args[0]in(errno.EWOULDBLOCK,errno.EAGAIN):returnNoneelse:raiseifnotchunk:self.close()returnNonereturnchunkdef_read_to_buffer(self):"""Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception. """try:chunk=self._read_from_socket()exceptsocket.error,e:# ssl.SSLError is a subclass of socket.errorlogging.warning("Read error on %d: %s",self.socket.fileno(),e)self.close()raiseifchunkisNone:return0self._read_buffer.append(chunk)self._read_buffer_size+=len(chunk)ifself._read_buffer_size>=self.max_buffer_size:logging.error("Reached maximum read buffer size")self.close()raiseIOError("Reached maximum read buffer size")returnlen(chunk)def_read_from_buffer(self):"""Attempts to complete the currently-pending read from the buffer. Returns True if the read was completed. """ifself._read_bytesisnotNone:ifself._streaming_callbackisnotNoneandself._read_buffer_size:bytes_to_consume=min(self._read_bytes,self._read_buffer_size)self._read_bytes-=bytes_to_consumeself._run_callback(self._streaming_callback,self._consume(bytes_to_consume))ifself._read_buffer_size>=self._read_bytes:num_bytes=self._read_bytescallback=self._read_callbackself._read_callback=Noneself._streaming_callback=Noneself._read_bytes=Noneself._run_callback(callback,self._consume(num_bytes))returnTrueelifself._read_delimiterisnotNone:_merge_prefix(self._read_buffer,sys.maxint)loc=self._read_buffer[0].find(self._read_delimiter)ifloc!=-1:callback=self._read_callbackdelimiter_len=len(self._read_delimiter)self._read_callback=Noneself._streaming_callback=Noneself._read_delimiter=Noneself._run_callback(callback,self._consume(loc+delimiter_len))returnTrueelifself._read_regexisnotNone:_merge_prefix(self._read_buffer,sys.maxint)m=self._read_regex.search(self._read_buffer[0])ifm:callback=self._read_callbackself._read_callback=Noneself._streaming_callback=Noneself._read_regex=Noneself._run_callback(callback,self._consume(m.end()))returnTrueelifself._read_until_close:ifself._streaming_callbackisnotNoneandself._read_buffer_size:self._run_callback(self._streaming_callback,self._consume(self._read_buffer_size))returnFalsedef_handle_connect(self):err=self.socket.getsockopt(socket.SOL_SOCKET,socket.SO_ERROR)iferr!=0:# IOLoop implementations may vary: some of them return# an error state before the socket becomes writable, so# in that case a connection failure would be handled by the# error path in _handle_events instead of here.logging.warning("Connect error on fd %d: %s",self.socket.fileno(),errno.errorcode[err])self.close()returnifself._connect_callbackisnotNone:callback=self._connect_callbackself._connect_callback=Noneself._run_callback(callback)self._connecting=Falsedef_handle_write(self):whileself._write_buffer:try:ifnotself._write_buffer_frozen:# On windows, socket.send blows up if given a# write buffer that's too large, instead of just# returning the number of bytes it was able to# process. Therefore we must not call socket.send# with more than 128KB at a time._merge_prefix(self._write_buffer,128*1024)num_bytes=self.socket.send(self._write_buffer[0])ifnum_bytes==0:# With OpenSSL, if we couldn't write the entire buffer,# the very same string object must be used on the# next call to send. Therefore we suppress# merging the write buffer after an incomplete send.# A cleaner solution would be to set# SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER, but this is# not yet accessible from python# (http://bugs.python.org/issue8240)self._write_buffer_frozen=Truebreakself._write_buffer_frozen=False_merge_prefix(self._write_buffer,num_bytes)self._write_buffer.popleft()exceptsocket.error,e:ife.args[0]in(errno.EWOULDBLOCK,errno.EAGAIN):self._write_buffer_frozen=Truebreakelse:logging.warning("Write error on %d: %s",self.socket.fileno(),e)self.close()returnifnotself._write_bufferandself._write_callback:callback=self._write_callbackself._write_callback=Noneself._run_callback(callback)def_consume(self,loc):ifloc==0:returnb("")_merge_prefix(self._read_buffer,loc)self._read_buffer_size-=locreturnself._read_buffer.popleft()def_check_closed(self):ifnotself.socket:raiseIOError("Stream is closed")def_maybe_add_error_listener(self):ifself._stateisNoneandself._pending_callbacks==0:ifself.socketisNone:cb=self._close_callbackifcbisnotNone:self._close_callback=Noneself._run_callback(cb)else:self._add_io_state(ioloop.IOLoop.READ)def_add_io_state(self,state):"""Adds `state` (IOLoop.{READ,WRITE} flags) to our event handler. Implementation notes: Reads and writes have a fast path and a slow path. The fast path reads synchronously from socket buffers, while the slow path uses `_add_io_state` to schedule an IOLoop callback. Note that in both cases, the callback is run asynchronously with `_run_callback`. To detect closed connections, we must have called `_add_io_state` at some point, but we want to delay this as much as possible so we don't have to set an `IOLoop.ERROR` listener that will be overwritten by the next slow-path operation. As long as there are callbacks scheduled for fast-path ops, those callbacks may do more reads. If a sequence of fast-path ops do not end in a slow-path op, (e.g. for an @asynchronous long-poll request), we must add the error handler. This is done in `_run_callback` and `write` (since the write callback is optional so we can have a fast-path write with no `_run_callback`) """ifself.socketisNone:# connection has been closed, so there can be no future eventsreturnifself._stateisNone:self._state=ioloop.IOLoop.ERROR|statewithstack_context.NullContext():self.io_loop.add_handler(self.socket.fileno(),self._handle_events,self._state)elifnotself._state&state:self._state=self._state|stateself.io_loop.update_handler(self.socket.fileno(),self._state)

[docs]classSSLIOStream(IOStream):"""A utility class to write to and read from a non-blocking SSL socket. If the socket passed to the constructor is already connected, it should be wrapped with:: ssl.wrap_socket(sock, do_handshake_on_connect=False, **kwargs) before constructing the SSLIOStream. Unconnected sockets will be wrapped when IOStream.connect is finished. """def__init__(self,*args,**kwargs):"""Creates an SSLIOStream. If a dictionary is provided as keyword argument ssl_options, it will be used as additional keyword arguments to ssl.wrap_socket. """self._ssl_options=kwargs.pop('ssl_options',{})super(SSLIOStream,self).__init__(*args,**kwargs)self._ssl_accepting=Trueself._handshake_reading=Falseself._handshake_writing=Falsedefreading(self):returnself._handshake_readingorsuper(SSLIOStream,self).reading()defwriting(self):returnself._handshake_writingorsuper(SSLIOStream,self).writing()def_do_ssl_handshake(self):# Based on code from test_ssl.py in the python stdlibtry:self._handshake_reading=Falseself._handshake_writing=Falseself.socket.do_handshake()exceptssl.SSLError,err:iferr.args[0]==ssl.SSL_ERROR_WANT_READ:self._handshake_reading=Truereturneliferr.args[0]==ssl.SSL_ERROR_WANT_WRITE:self._handshake_writing=Truereturneliferr.args[0]in(ssl.SSL_ERROR_EOF,ssl.SSL_ERROR_ZERO_RETURN):returnself.close()eliferr.args[0]==ssl.SSL_ERROR_SSL:logging.warning("SSL Error on %d: %s",self.socket.fileno(),err)returnself.close()raiseexceptsocket.error,err:iferr.args[0]==errno.ECONNABORTED:returnself.close()else:self._ssl_accepting=Falsesuper(SSLIOStream,self)._handle_connect()def_handle_read(self):ifself._ssl_accepting:self._do_ssl_handshake()returnsuper(SSLIOStream,self)._handle_read()def_handle_write(self):ifself._ssl_accepting:self._do_ssl_handshake()returnsuper(SSLIOStream,self)._handle_write()def_handle_connect(self):self.socket=ssl.wrap_socket(self.socket,do_handshake_on_connect=False,**self._ssl_options)# Don't call the superclass's _handle_connect (which is responsible# for telling the application that the connection is complete)# until we've completed the SSL handshake (so certificates are# available, etc).def_read_from_socket(self):try:# SSLSocket objects have both a read() and recv() method,# while regular sockets only have recv().# The recv() method blocks (at least in python 2.6) if it is# called when there is nothing to read, so we have to use# read() instead.chunk=self.socket.read(self.read_chunk_size)exceptssl.SSLError,e:# SSLError is a subclass of socket.error, so this except# block must come first.ife.args[0]==ssl.SSL_ERROR_WANT_READ:returnNoneelse:raiseexceptsocket.error,e:ife.args[0]in(errno.EWOULDBLOCK,errno.EAGAIN):returnNoneelse:raiseifnotchunk:self.close()returnNonereturnchunk