| 1 |
# Copyright DataStax, Inc. |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
# you may not use this file except in compliance with the License. |
| 5 |
# You may obtain a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
# See the License for the specific language governing permissions and |
| 13 |
# limitations under the License. |
| 14 |
import atexit |
| 15 |
from collections import deque |
| 16 |
from functools import partial |
| 17 |
import logging |
| 18 |
import os |
| 19 |
import socket |
| 20 |
import ssl |
| 21 |
from threading import Lock, Thread |
| 22 |
import time |
| 23 |
|
| 24 |
from cassandra import DependencyException |
| 25 |
try: |
| 26 |
import cassandra.io.libevwrapper as libev |
| 27 |
except ImportError: |
| 28 |
raise DependencyException( |
| 29 |
"The C extension needed to use libev was not found. This " |
| 30 |
"probably means that you didn't have the required build dependencies " |
| 31 |
"when installing the driver. See " |
| 32 |
"http://datastax.github.io/python-driver/installation.html#c-extensions " |
| 33 |
"for instructions on installing build dependencies and building " |
| 34 |
"the C extension.") |
| 35 |
|
| 36 |
from cassandra.connection import (Connection, ConnectionShutdown, |
| 37 |
NONBLOCKING, Timer, TimerManager) |
| 38 |
|
| 39 |
|
| 40 |
log = logging.getLogger(__name__) |
| 41 |
|
| 42 |
|
| 43 |
def _cleanup(loop): |
| 44 |
if loop: |
| 45 |
loop._cleanup() |
| 46 |
|
| 47 |
|
| 48 |
class LibevLoop(object): |
| 49 |
|
| 50 |
def __init__(self): |
| 51 |
self._pid = os.getpid() |
| 52 |
self._loop = libev.Loop() |
| 53 |
self._notifier = libev.Async(self._loop) |
| 54 |
self._notifier.start() |
| 55 |
|
| 56 |
# prevent _notifier from keeping the loop from returning |
| 57 |
self._loop.unref() |
| 58 |
|
| 59 |
self._started = False |
| 60 |
self._shutdown = False |
| 61 |
self._lock = Lock() |
| 62 |
self._lock_thread = Lock() |
| 63 |
|
| 64 |
self._thread = None |
| 65 |
|
| 66 |
# set of all connections; only replaced with a new copy |
| 67 |
# while holding _conn_set_lock, never modified in place |
| 68 |
self._live_conns = set() |
| 69 |
# newly created connections that need their write/read watcher started |
| 70 |
self._new_conns = set() |
| 71 |
# recently closed connections that need their write/read watcher stopped |
| 72 |
self._closed_conns = set() |
| 73 |
self._conn_set_lock = Lock() |
| 74 |
|
| 75 |
self._preparer = libev.Prepare(self._loop, self._loop_will_run) |
| 76 |
# prevent _preparer from keeping the loop from returning |
| 77 |
self._loop.unref() |
| 78 |
self._preparer.start() |
| 79 |
|
| 80 |
self._timers = TimerManager() |
| 81 |
self._loop_timer = libev.Timer(self._loop, self._on_loop_timer) |
| 82 |
|
| 83 |
def maybe_start(self): |
| 84 |
should_start = False |
| 85 |
with self._lock: |
| 86 |
if not self._started: |
| 87 |
log.debug("Starting libev event loop") |
| 88 |
self._started = True |
| 89 |
should_start = True |
| 90 |
|
| 91 |
if should_start: |
| 92 |
with self._lock_thread: |
| 93 |
if not self._shutdown: |
| 94 |
self._thread = Thread(target=self._run_loop, name="event_loop") |
| 95 |
self._thread.daemon = True |
| 96 |
self._thread.start() |
| 97 |
|
| 98 |
self._notifier.send() |
| 99 |
|
| 100 |
def _run_loop(self): |
| 101 |
while True: |
| 102 |
self._loop.start() |
| 103 |
# there are still active watchers, no deadlock |
| 104 |
with self._lock: |
| 105 |
if not self._shutdown and self._live_conns: |
| 106 |
log.debug("Restarting event loop") |
| 107 |
continue |
| 108 |
else: |
| 109 |
# all Connections have been closed, no active watchers |
| 110 |
log.debug("All Connections currently closed, event loop ended") |
| 111 |
self._started = False |
| 112 |
break |
| 113 |
|
| 114 |
def _cleanup(self): |
| 115 |
self._shutdown = True |
| 116 |
if not self._thread: |
| 117 |
return |
| 118 |
|
| 119 |
for conn in self._live_conns | self._new_conns | self._closed_conns: |
| 120 |
conn.close() |
| 121 |
for watcher in (conn._write_watcher, conn._read_watcher): |
| 122 |
if watcher: |
| 123 |
watcher.stop() |
| 124 |
|
| 125 |
self.notify() # wake the timer watcher |
| 126 |
|
| 127 |
# PYTHON-752 Thread might have just been created and not started |
| 128 |
with self._lock_thread: |
| 129 |
self._thread.join(timeout=1.0) |
| 130 |
|
| 131 |
if self._thread.is_alive(): |
| 132 |
log.warning( |
| 133 |
"Event loop thread could not be joined, so shutdown may not be clean. " |
| 134 |
"Please call Cluster.shutdown() to avoid this.") |
| 135 |
|
| 136 |
log.debug("Event loop thread was joined") |
| 137 |
|
| 138 |
def add_timer(self, timer): |
| 139 |
self._timers.add_timer(timer) |
| 140 |
self._notifier.send() # wake up in case this timer is earlier |
| 141 |
|
| 142 |
def _update_timer(self): |
| 143 |
if not self._shutdown: |
| 144 |
next_end = self._timers.service_timeouts() |
| 145 |
if next_end: |
| 146 |
self._loop_timer.start(next_end - time.time()) # timer handles negative values |
| 147 |
else: |
| 148 |
self._loop_timer.stop() |
| 149 |
|
| 150 |
def _on_loop_timer(self): |
| 151 |
self._timers.service_timeouts() |
| 152 |
|
| 153 |
def notify(self): |
| 154 |
self._notifier.send() |
| 155 |
|
| 156 |
def connection_created(self, conn): |
| 157 |
with self._conn_set_lock: |
| 158 |
new_live_conns = self._live_conns.copy() |
| 159 |
new_live_conns.add(conn) |
| 160 |
self._live_conns = new_live_conns |
| 161 |
|
| 162 |
new_new_conns = self._new_conns.copy() |
| 163 |
new_new_conns.add(conn) |
| 164 |
self._new_conns = new_new_conns |
| 165 |
|
| 166 |
def connection_destroyed(self, conn): |
| 167 |
with self._conn_set_lock: |
| 168 |
new_live_conns = self._live_conns.copy() |
| 169 |
new_live_conns.discard(conn) |
| 170 |
self._live_conns = new_live_conns |
| 171 |
|
| 172 |
new_closed_conns = self._closed_conns.copy() |
| 173 |
new_closed_conns.add(conn) |
| 174 |
self._closed_conns = new_closed_conns |
| 175 |
|
| 176 |
self._notifier.send() |
| 177 |
|
| 178 |
def _loop_will_run(self, prepare): |
| 179 |
changed = False |
| 180 |
for conn in self._live_conns: |
| 181 |
if not conn.deque and conn._write_watcher_is_active: |
| 182 |
if conn._write_watcher: |
| 183 |
conn._write_watcher.stop() |
| 184 |
conn._write_watcher_is_active = False |
| 185 |
changed = True |
| 186 |
elif conn.deque and not conn._write_watcher_is_active: |
| 187 |
conn._write_watcher.start() |
| 188 |
conn._write_watcher_is_active = True |
| 189 |
changed = True |
| 190 |
|
| 191 |
if self._new_conns: |
| 192 |
with self._conn_set_lock: |
| 193 |
to_start = self._new_conns |
| 194 |
self._new_conns = set() |
| 195 |
|
| 196 |
for conn in to_start: |
| 197 |
conn._read_watcher.start() |
| 198 |
|
| 199 |
changed = True |
| 200 |
|
| 201 |
if self._closed_conns: |
| 202 |
with self._conn_set_lock: |
| 203 |
to_stop = self._closed_conns |
| 204 |
self._closed_conns = set() |
| 205 |
|
| 206 |
for conn in to_stop: |
| 207 |
if conn._write_watcher: |
| 208 |
conn._write_watcher.stop() |
| 209 |
# clear reference cycles from IO callback |
| 210 |
del conn._write_watcher |
| 211 |
if conn._read_watcher: |
| 212 |
conn._read_watcher.stop() |
| 213 |
# clear reference cycles from IO callback |
| 214 |
del conn._read_watcher |
| 215 |
|
| 216 |
changed = True |
| 217 |
|
| 218 |
# TODO: update to do connection management, timer updates through dedicated async 'notifier' callbacks |
| 219 |
self._update_timer() |
| 220 |
|
| 221 |
if changed: |
| 222 |
self._notifier.send() |
| 223 |
|
| 224 |
|
| 225 |
_global_loop = None |
| 226 |
atexit.register(partial(_cleanup, _global_loop)) |
| 227 |
|
| 228 |
|
| 229 |
class LibevConnection(Connection): |
| 230 |
""" |
| 231 |
An implementation of :class:`.Connection` that uses libev for its event loop. |
| 232 |
""" |
| 233 |
_write_watcher_is_active = False |
| 234 |
_read_watcher = None |
| 235 |
_write_watcher = None |
| 236 |
_socket = None |
| 237 |
|
| 238 |
@classmethod |
| 239 |
def initialize_reactor(cls): |
| 240 |
global _global_loop |
| 241 |
if not _global_loop: |
| 242 |
_global_loop = LibevLoop() |
| 243 |
else: |
| 244 |
if _global_loop._pid != os.getpid(): |
| 245 |
log.debug("Detected fork, clearing and reinitializing reactor state") |
| 246 |
cls.handle_fork() |
| 247 |
_global_loop = LibevLoop() |
| 248 |
|
| 249 |
@classmethod |
| 250 |
def handle_fork(cls): |
| 251 |
global _global_loop |
| 252 |
if _global_loop: |
| 253 |
_global_loop._cleanup() |
| 254 |
_global_loop = None |
| 255 |
|
| 256 |
@classmethod |
| 257 |
def create_timer(cls, timeout, callback): |
| 258 |
timer = Timer(timeout, callback) |
| 259 |
_global_loop.add_timer(timer) |
| 260 |
return timer |
| 261 |
|
| 262 |
def __init__(self, *args, **kwargs): |
| 263 |
Connection.__init__(self, *args, **kwargs) |
| 264 |
|
| 265 |
self.deque = deque() |
| 266 |
self._deque_lock = Lock() |
| 267 |
self._connect_socket() |
| 268 |
self._socket.setblocking(0) |
| 269 |
|
| 270 |
with _global_loop._lock: |
| 271 |
self._read_watcher = libev.IO(self._socket.fileno(), libev.EV_READ, _global_loop._loop, self.handle_read) |
| 272 |
self._write_watcher = libev.IO(self._socket.fileno(), libev.EV_WRITE, _global_loop._loop, self.handle_write) |
| 273 |
|
| 274 |
self._send_options_message() |
| 275 |
|
| 276 |
_global_loop.connection_created(self) |
| 277 |
|
| 278 |
# start the global event loop if needed |
| 279 |
_global_loop.maybe_start() |
| 280 |
|
| 281 |
def close(self): |
| 282 |
with self.lock: |
| 283 |
if self.is_closed: |
| 284 |
return |
| 285 |
self.is_closed = True |
| 286 |
|
| 287 |
log.debug("Closing connection (%s) to %s", id(self), self.endpoint) |
| 288 |
|
| 289 |
_global_loop.connection_destroyed(self) |
| 290 |
self._socket.close() |
| 291 |
log.debug("Closed socket to %s", self.endpoint) |
| 292 |
|
| 293 |
# don't leave in-progress operations hanging |
| 294 |
if not self.is_defunct: |
| 295 |
self.error_all_requests( |
| 296 |
ConnectionShutdown("Connection to %s was closed" % self.endpoint)) |
| 297 |
|
| 298 |
def handle_write(self, watcher, revents, errno=None): |
| 299 |
if revents & libev.EV_ERROR: |
| 300 |
if errno: |
| 301 |
exc = IOError(errno, os.strerror(errno)) |
| 302 |
else: |
| 303 |
exc = Exception("libev reported an error") |
| 304 |
|
| 305 |
self.defunct(exc) |
| 306 |
return |
| 307 |
|
| 308 |
while True: |
| 309 |
try: |
| 310 |
with self._deque_lock: |
| 311 |
next_msg = self.deque.popleft() |
| 312 |
except IndexError: |
| 313 |
if not self._socket_writable: |
| 314 |
self._socket_writable = True |
| 315 |
return |
| 316 |
|
| 317 |
try: |
| 318 |
sent = self._socket.send(next_msg) |
| 319 |
except socket.error as err: |
| 320 |
if (err.args[0] in NONBLOCKING or |
| 321 |
err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE)): |
| 322 |
if err.args[0] in NONBLOCKING: |
| 323 |
self._socket_writable = False |
| 324 |
with self._deque_lock: |
| 325 |
self.deque.appendleft(next_msg) |
| 326 |
else: |
| 327 |
self.defunct(err) |
| 328 |
return |
| 329 |
else: |
| 330 |
if sent < len(next_msg): |
| 331 |
with self._deque_lock: |
| 332 |
self.deque.appendleft(next_msg[sent:]) |
| 333 |
# we've seen some cases that 0 is returned instead of NONBLOCKING. But usually, |
| 334 |
# we don't expect this to happen. https://bugs.python.org/issue20951 |
| 335 |
if sent == 0: |
| 336 |
self._socket_writable = False |
| 337 |
return |
| 338 |
|
| 339 |
def handle_read(self, watcher, revents, errno=None): |
| 340 |
if revents & libev.EV_ERROR: |
| 341 |
if errno: |
| 342 |
exc = IOError(errno, os.strerror(errno)) |
| 343 |
else: |
| 344 |
exc = Exception("libev reported an error") |
| 345 |
|
| 346 |
self.defunct(exc) |
| 347 |
return |
| 348 |
try: |
| 349 |
while True: |
| 350 |
buf = self._socket.recv(self.in_buffer_size) |
| 351 |
self._iobuf.write(buf) |
| 352 |
if len(buf) < self.in_buffer_size: |
| 353 |
break |
| 354 |
except socket.error as err: |
| 355 |
if isinstance(err, ssl.SSLError): |
| 356 |
if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): |
| 357 |
if not self._iobuf.tell(): |
| 358 |
return |
| 359 |
else: |
| 360 |
self.defunct(err) |
| 361 |
return |
| 362 |
elif err.args[0] in NONBLOCKING: |
| 363 |
if not self._iobuf.tell(): |
| 364 |
return |
| 365 |
else: |
| 366 |
self.defunct(err) |
| 367 |
return |
| 368 |
|
| 369 |
if self._iobuf.tell(): |
| 370 |
self.process_io_buffer() |
| 371 |
else: |
| 372 |
log.debug("Connection %s closed by server", self) |
| 373 |
self.close() |
| 374 |
|
| 375 |
def push(self, data): |
| 376 |
sabs = self.out_buffer_size |
| 377 |
if len(data) > sabs: |
| 378 |
chunks = [] |
| 379 |
for i in range(0, len(data), sabs): |
| 380 |
chunks.append(data[i:i + sabs]) |
| 381 |
else: |
| 382 |
chunks = [data] |
| 383 |
|
| 384 |
with self._deque_lock: |
| 385 |
self.deque.extend(chunks) |
| 386 |
_global_loop.notify() |