| 1 |
from cassandra.connection import Connection, ConnectionShutdown |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import logging |
| 5 |
import os |
| 6 |
import socket |
| 7 |
import ssl |
| 8 |
from threading import Lock, Thread, get_ident |
| 9 |
|
| 10 |
|
| 11 |
log = logging.getLogger(__name__) |
| 12 |
|
| 13 |
|
| 14 |
# This module uses ``yield from`` and ``@asyncio.coroutine`` over ``await`` and |
| 15 |
# ``async def`` for pre-Python-3.5 compatibility, so keep in mind that the |
| 16 |
# managed coroutines are generator-based, not native coroutines. See PEP 492: |
| 17 |
# https://www.python.org/dev/peps/pep-0492/#coroutine-objects |
| 18 |
|
| 19 |
|
| 20 |
try: |
| 21 |
asyncio.run_coroutine_threadsafe |
| 22 |
except AttributeError: |
| 23 |
raise ImportError( |
| 24 |
'Cannot use asyncioreactor without access to ' |
| 25 |
'asyncio.run_coroutine_threadsafe (added in 3.4.6 and 3.5.1)' |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
class AsyncioTimer(object): |
| 30 |
""" |
| 31 |
An ``asyncioreactor``-specific Timer. Similar to :class:`.connection.Timer, |
| 32 |
but with a slightly different API due to limitations in the underlying |
| 33 |
``call_later`` interface. Not meant to be used with a |
| 34 |
:class:`.connection.TimerManager`. |
| 35 |
""" |
| 36 |
|
| 37 |
@property |
| 38 |
def end(self): |
| 39 |
raise NotImplementedError('{} is not compatible with TimerManager and ' |
| 40 |
'does not implement .end()') |
| 41 |
|
| 42 |
def __init__(self, timeout, callback, loop): |
| 43 |
delayed = self._call_delayed_coro(timeout=timeout, |
| 44 |
callback=callback) |
| 45 |
self._handle = asyncio.run_coroutine_threadsafe(delayed, loop=loop) |
| 46 |
|
| 47 |
@staticmethod |
| 48 |
async def _call_delayed_coro(timeout, callback): |
| 49 |
await asyncio.sleep(timeout) |
| 50 |
return callback() |
| 51 |
|
| 52 |
def __lt__(self, other): |
| 53 |
try: |
| 54 |
return self._handle < other._handle |
| 55 |
except AttributeError: |
| 56 |
raise NotImplemented |
| 57 |
|
| 58 |
def cancel(self): |
| 59 |
self._handle.cancel() |
| 60 |
|
| 61 |
def finish(self): |
| 62 |
# connection.Timer method not implemented here because we can't inspect |
| 63 |
# the Handle returned from call_later |
| 64 |
raise NotImplementedError('{} is not compatible with TimerManager and ' |
| 65 |
'does not implement .finish()') |
| 66 |
|
| 67 |
|
| 68 |
class AsyncioConnection(Connection): |
| 69 |
""" |
| 70 |
An experimental implementation of :class:`.Connection` that uses the |
| 71 |
``asyncio`` module in the Python standard library for its event loop. |
| 72 |
|
| 73 |
Note that it requires ``asyncio`` features that were only introduced in the |
| 74 |
3.4 line in 3.4.6, and in the 3.5 line in 3.5.1. |
| 75 |
""" |
| 76 |
|
| 77 |
_loop = None |
| 78 |
_pid = os.getpid() |
| 79 |
|
| 80 |
_lock = Lock() |
| 81 |
_loop_thread = None |
| 82 |
|
| 83 |
_write_queue = None |
| 84 |
_write_queue_lock = None |
| 85 |
|
| 86 |
def __init__(self, *args, **kwargs): |
| 87 |
Connection.__init__(self, *args, **kwargs) |
| 88 |
|
| 89 |
self._connect_socket() |
| 90 |
self._socket.setblocking(0) |
| 91 |
|
| 92 |
self._write_queue = asyncio.Queue() |
| 93 |
self._write_queue_lock = asyncio.Lock() |
| 94 |
|
| 95 |
# see initialize_reactor -- loop is running in a separate thread, so we |
| 96 |
# have to use a threadsafe call |
| 97 |
self._read_watcher = asyncio.run_coroutine_threadsafe( |
| 98 |
self.handle_read(), loop=self._loop |
| 99 |
) |
| 100 |
self._write_watcher = asyncio.run_coroutine_threadsafe( |
| 101 |
self.handle_write(), loop=self._loop |
| 102 |
) |
| 103 |
self._send_options_message() |
| 104 |
|
| 105 |
@classmethod |
| 106 |
def initialize_reactor(cls): |
| 107 |
with cls._lock: |
| 108 |
if cls._pid != os.getpid(): |
| 109 |
cls._loop = None |
| 110 |
if cls._loop is None: |
| 111 |
cls._loop = asyncio.new_event_loop() |
| 112 |
asyncio.set_event_loop(cls._loop) |
| 113 |
|
| 114 |
if not cls._loop_thread: |
| 115 |
# daemonize so the loop will be shut down on interpreter |
| 116 |
# shutdown |
| 117 |
cls._loop_thread = Thread(target=cls._loop.run_forever, |
| 118 |
daemon=True, name="asyncio_thread") |
| 119 |
cls._loop_thread.start() |
| 120 |
|
| 121 |
@classmethod |
| 122 |
def create_timer(cls, timeout, callback): |
| 123 |
return AsyncioTimer(timeout, callback, loop=cls._loop) |
| 124 |
|
| 125 |
def close(self): |
| 126 |
with self.lock: |
| 127 |
if self.is_closed: |
| 128 |
return |
| 129 |
self.is_closed = True |
| 130 |
|
| 131 |
# close from the loop thread to avoid races when removing file |
| 132 |
# descriptors |
| 133 |
asyncio.run_coroutine_threadsafe( |
| 134 |
self._close(), loop=self._loop |
| 135 |
) |
| 136 |
|
| 137 |
async def _close(self): |
| 138 |
log.debug("Closing connection (%s) to %s" % (id(self), self.endpoint)) |
| 139 |
if self._write_watcher: |
| 140 |
self._write_watcher.cancel() |
| 141 |
if self._read_watcher: |
| 142 |
self._read_watcher.cancel() |
| 143 |
if self._socket: |
| 144 |
self._loop.remove_writer(self._socket.fileno()) |
| 145 |
self._loop.remove_reader(self._socket.fileno()) |
| 146 |
self._socket.close() |
| 147 |
|
| 148 |
log.debug("Closed socket to %s" % (self.endpoint,)) |
| 149 |
|
| 150 |
if not self.is_defunct: |
| 151 |
self.error_all_requests( |
| 152 |
ConnectionShutdown("Connection to %s was closed" % self.endpoint)) |
| 153 |
# don't leave in-progress operations hanging |
| 154 |
self.connected_event.set() |
| 155 |
|
| 156 |
def push(self, data): |
| 157 |
buff_size = self.out_buffer_size |
| 158 |
if len(data) > buff_size: |
| 159 |
chunks = [] |
| 160 |
for i in range(0, len(data), buff_size): |
| 161 |
chunks.append(data[i:i + buff_size]) |
| 162 |
else: |
| 163 |
chunks = [data] |
| 164 |
|
| 165 |
if self._loop_thread.ident != get_ident(): |
| 166 |
asyncio.run_coroutine_threadsafe( |
| 167 |
self._push_msg(chunks), |
| 168 |
loop=self._loop |
| 169 |
) |
| 170 |
else: |
| 171 |
# avoid races/hangs by just scheduling this, not using threadsafe |
| 172 |
self._loop.create_task(self._push_msg(chunks)) |
| 173 |
|
| 174 |
async def _push_msg(self, chunks): |
| 175 |
# This lock ensures all chunks of a message are sequential in the Queue |
| 176 |
with await self._write_queue_lock: |
| 177 |
for chunk in chunks: |
| 178 |
self._write_queue.put_nowait(chunk) |
| 179 |
|
| 180 |
|
| 181 |
async def handle_write(self): |
| 182 |
while True: |
| 183 |
try: |
| 184 |
next_msg = await self._write_queue.get() |
| 185 |
if next_msg: |
| 186 |
await self._loop.sock_sendall(self._socket, next_msg) |
| 187 |
except socket.error as err: |
| 188 |
log.debug("Exception in send for %s: %s", self, err) |
| 189 |
self.defunct(err) |
| 190 |
return |
| 191 |
except asyncio.CancelledError: |
| 192 |
return |
| 193 |
|
| 194 |
async def handle_read(self): |
| 195 |
while True: |
| 196 |
try: |
| 197 |
buf = await self._loop.sock_recv(self._socket, self.in_buffer_size) |
| 198 |
self._iobuf.write(buf) |
| 199 |
# sock_recv expects EWOULDBLOCK if socket provides no data, but |
| 200 |
# nonblocking ssl sockets raise these instead, so we handle them |
| 201 |
# ourselves by yielding to the event loop, where the socket will |
| 202 |
# get the reading/writing it "wants" before retrying |
| 203 |
except (ssl.SSLWantWriteError, ssl.SSLWantReadError): |
| 204 |
# Apparently the preferred way to yield to the event loop from within |
| 205 |
# a native coroutine based on https://github.com/python/asyncio/issues/284 |
| 206 |
await asyncio.sleep(0) |
| 207 |
continue |
| 208 |
except socket.error as err: |
| 209 |
log.debug("Exception during socket recv for %s: %s", |
| 210 |
self, err) |
| 211 |
self.defunct(err) |
| 212 |
return # leave the read loop |
| 213 |
except asyncio.CancelledError: |
| 214 |
return |
| 215 |
|
| 216 |
if buf and self._iobuf.tell(): |
| 217 |
self.process_io_buffer() |
| 218 |
else: |
| 219 |
log.debug("Connection %s closed by server", self) |
| 220 |
self.close() |
| 221 |
return |