| 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 sys |
| 21 |
from threading import Lock, Thread, Event |
| 22 |
import time |
| 23 |
import weakref |
| 24 |
import sys |
| 25 |
import ssl |
| 26 |
|
| 27 |
try: |
| 28 |
from weakref import WeakSet |
| 29 |
except ImportError: |
| 30 |
from cassandra.util import WeakSet # noqa |
| 31 |
|
| 32 |
from cassandra import DependencyException |
| 33 |
try: |
| 34 |
import asyncore |
| 35 |
except ModuleNotFoundError: |
| 36 |
raise DependencyException( |
| 37 |
"Unable to import asyncore module. Note that this module has been removed in Python 3.12 " |
| 38 |
"so when using the driver with this version (or anything newer) you will need to use one of the " |
| 39 |
"other event loop implementations." |
| 40 |
) |
| 41 |
|
| 42 |
from cassandra.connection import Connection, ConnectionShutdown, NONBLOCKING, Timer, TimerManager |
| 43 |
|
| 44 |
|
| 45 |
log = logging.getLogger(__name__) |
| 46 |
|
| 47 |
_dispatcher_map = {} |
| 48 |
|
| 49 |
def _cleanup(loop): |
| 50 |
if loop: |
| 51 |
loop._cleanup() |
| 52 |
|
| 53 |
|
| 54 |
class WaitableTimer(Timer): |
| 55 |
def __init__(self, timeout, callback): |
| 56 |
Timer.__init__(self, timeout, callback) |
| 57 |
self.callback = callback |
| 58 |
self.event = Event() |
| 59 |
|
| 60 |
self.final_exception = None |
| 61 |
|
| 62 |
def finish(self, time_now): |
| 63 |
try: |
| 64 |
finished = Timer.finish(self, time_now) |
| 65 |
if finished: |
| 66 |
self.event.set() |
| 67 |
return True |
| 68 |
return False |
| 69 |
|
| 70 |
except Exception as e: |
| 71 |
self.final_exception = e |
| 72 |
self.event.set() |
| 73 |
return True |
| 74 |
|
| 75 |
def wait(self, timeout=None): |
| 76 |
self.event.wait(timeout) |
| 77 |
if self.final_exception: |
| 78 |
raise self.final_exception |
| 79 |
|
| 80 |
|
| 81 |
class _PipeWrapper(object): |
| 82 |
|
| 83 |
def __init__(self, fd): |
| 84 |
self.fd = fd |
| 85 |
|
| 86 |
def fileno(self): |
| 87 |
return self.fd |
| 88 |
|
| 89 |
def close(self): |
| 90 |
os.close(self.fd) |
| 91 |
|
| 92 |
def getsockopt(self, level, optname, buflen=None): |
| 93 |
# act like an unerrored socket for the asyncore error handling |
| 94 |
if level == socket.SOL_SOCKET and optname == socket.SO_ERROR and not buflen: |
| 95 |
return 0 |
| 96 |
raise NotImplementedError() |
| 97 |
|
| 98 |
|
| 99 |
class _AsyncoreDispatcher(asyncore.dispatcher): |
| 100 |
|
| 101 |
def __init__(self, socket): |
| 102 |
asyncore.dispatcher.__init__(self, map=_dispatcher_map) |
| 103 |
# inject after to avoid base class validation |
| 104 |
self.set_socket(socket) |
| 105 |
self._notified = False |
| 106 |
|
| 107 |
def writable(self): |
| 108 |
return False |
| 109 |
|
| 110 |
def validate(self): |
| 111 |
assert not self._notified |
| 112 |
self.notify_loop() |
| 113 |
assert self._notified |
| 114 |
self.loop(0.1) |
| 115 |
assert not self._notified |
| 116 |
|
| 117 |
def loop(self, timeout): |
| 118 |
asyncore.loop(timeout=timeout, use_poll=True, map=_dispatcher_map, count=1) |
| 119 |
|
| 120 |
|
| 121 |
class _AsyncorePipeDispatcher(_AsyncoreDispatcher): |
| 122 |
|
| 123 |
def __init__(self): |
| 124 |
self.read_fd, self.write_fd = os.pipe() |
| 125 |
_AsyncoreDispatcher.__init__(self, _PipeWrapper(self.read_fd)) |
| 126 |
|
| 127 |
def writable(self): |
| 128 |
return False |
| 129 |
|
| 130 |
def handle_read(self): |
| 131 |
while len(os.read(self.read_fd, 4096)) == 4096: |
| 132 |
pass |
| 133 |
self._notified = False |
| 134 |
|
| 135 |
def notify_loop(self): |
| 136 |
if not self._notified: |
| 137 |
self._notified = True |
| 138 |
os.write(self.write_fd, b'x') |
| 139 |
|
| 140 |
|
| 141 |
class _AsyncoreUDPDispatcher(_AsyncoreDispatcher): |
| 142 |
""" |
| 143 |
Experimental alternate dispatcher for avoiding busy wait in the asyncore loop. It is not used by default because |
| 144 |
it relies on local port binding. |
| 145 |
Port scanning is not implemented, so multiple clients on one host will collide. This address would need to be set per |
| 146 |
instance, or this could be specialized to scan until an address is found. |
| 147 |
|
| 148 |
To use:: |
| 149 |
|
| 150 |
from cassandra.io.asyncorereactor import _AsyncoreUDPDispatcher, AsyncoreLoop |
| 151 |
AsyncoreLoop._loop_dispatch_class = _AsyncoreUDPDispatcher |
| 152 |
|
| 153 |
""" |
| 154 |
bind_address = ('localhost', 10000) |
| 155 |
|
| 156 |
def __init__(self): |
| 157 |
self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) |
| 158 |
self._socket.bind(self.bind_address) |
| 159 |
self._socket.setblocking(0) |
| 160 |
_AsyncoreDispatcher.__init__(self, self._socket) |
| 161 |
|
| 162 |
def handle_read(self): |
| 163 |
try: |
| 164 |
d = self._socket.recvfrom(1) |
| 165 |
while d and d[1]: |
| 166 |
d = self._socket.recvfrom(1) |
| 167 |
except socket.error as e: |
| 168 |
pass |
| 169 |
self._notified = False |
| 170 |
|
| 171 |
def notify_loop(self): |
| 172 |
if not self._notified: |
| 173 |
self._notified = True |
| 174 |
self._socket.sendto(b'', self.bind_address) |
| 175 |
|
| 176 |
def loop(self, timeout): |
| 177 |
asyncore.loop(timeout=timeout, use_poll=False, map=_dispatcher_map, count=1) |
| 178 |
|
| 179 |
|
| 180 |
class _BusyWaitDispatcher(object): |
| 181 |
|
| 182 |
max_write_latency = 0.001 |
| 183 |
""" |
| 184 |
Timeout pushed down to asyncore select/poll. Dictates the amount of time it will sleep before coming back to check |
| 185 |
if anything is writable. |
| 186 |
""" |
| 187 |
|
| 188 |
def notify_loop(self): |
| 189 |
pass |
| 190 |
|
| 191 |
def loop(self, timeout): |
| 192 |
if not _dispatcher_map: |
| 193 |
time.sleep(0.005) |
| 194 |
count = timeout // self.max_write_latency |
| 195 |
asyncore.loop(timeout=self.max_write_latency, use_poll=True, map=_dispatcher_map, count=count) |
| 196 |
|
| 197 |
def validate(self): |
| 198 |
pass |
| 199 |
|
| 200 |
def close(self): |
| 201 |
pass |
| 202 |
|
| 203 |
|
| 204 |
class AsyncoreLoop(object): |
| 205 |
|
| 206 |
timer_resolution = 0.1 # used as the max interval to be in the io loop before returning to service timeouts |
| 207 |
|
| 208 |
_loop_dispatch_class = _AsyncorePipeDispatcher if os.name != 'nt' else _BusyWaitDispatcher |
| 209 |
|
| 210 |
def __init__(self): |
| 211 |
self._pid = os.getpid() |
| 212 |
self._loop_lock = Lock() |
| 213 |
self._started = False |
| 214 |
self._shutdown = False |
| 215 |
|
| 216 |
self._thread = None |
| 217 |
|
| 218 |
self._timers = TimerManager() |
| 219 |
|
| 220 |
try: |
| 221 |
dispatcher = self._loop_dispatch_class() |
| 222 |
dispatcher.validate() |
| 223 |
log.debug("Validated loop dispatch with %s", self._loop_dispatch_class) |
| 224 |
except Exception: |
| 225 |
log.exception("Failed validating loop dispatch with %s. Using busy wait execution instead.", self._loop_dispatch_class) |
| 226 |
dispatcher.close() |
| 227 |
dispatcher = _BusyWaitDispatcher() |
| 228 |
self._loop_dispatcher = dispatcher |
| 229 |
|
| 230 |
def maybe_start(self): |
| 231 |
should_start = False |
| 232 |
did_acquire = False |
| 233 |
try: |
| 234 |
did_acquire = self._loop_lock.acquire(False) |
| 235 |
if did_acquire and not self._started: |
| 236 |
self._started = True |
| 237 |
should_start = True |
| 238 |
finally: |
| 239 |
if did_acquire: |
| 240 |
self._loop_lock.release() |
| 241 |
|
| 242 |
if should_start: |
| 243 |
self._thread = Thread(target=self._run_loop, name="asyncore_cassandra_driver_event_loop") |
| 244 |
self._thread.daemon = True |
| 245 |
self._thread.start() |
| 246 |
|
| 247 |
def wake_loop(self): |
| 248 |
self._loop_dispatcher.notify_loop() |
| 249 |
|
| 250 |
def _run_loop(self): |
| 251 |
log.debug("Starting asyncore event loop") |
| 252 |
with self._loop_lock: |
| 253 |
while not self._shutdown: |
| 254 |
try: |
| 255 |
self._loop_dispatcher.loop(self.timer_resolution) |
| 256 |
self._timers.service_timeouts() |
| 257 |
except Exception as exc: |
| 258 |
self._maybe_log_debug("Asyncore event loop stopped unexpectedly", exc_info=exc) |
| 259 |
break |
| 260 |
self._started = False |
| 261 |
|
| 262 |
self._maybe_log_debug("Asyncore event loop ended") |
| 263 |
|
| 264 |
def _maybe_log_debug(self, *args, **kwargs): |
| 265 |
try: |
| 266 |
log.debug(*args, **kwargs) |
| 267 |
except Exception: |
| 268 |
# TODO: Remove when Python 2 support is removed |
| 269 |
# PYTHON-1266. If our logger has disappeared, there's nothing we |
| 270 |
# can do, so just log nothing. |
| 271 |
pass |
| 272 |
|
| 273 |
def add_timer(self, timer): |
| 274 |
self._timers.add_timer(timer) |
| 275 |
|
| 276 |
# This function is called from a different thread than the event loop |
| 277 |
# thread, so for this call to be thread safe, we must wake up the loop |
| 278 |
# in case it's stuck at a select |
| 279 |
self.wake_loop() |
| 280 |
|
| 281 |
def _cleanup(self): |
| 282 |
global _dispatcher_map |
| 283 |
|
| 284 |
self._shutdown = True |
| 285 |
if not self._thread: |
| 286 |
return |
| 287 |
|
| 288 |
log.debug("Waiting for event loop thread to join...") |
| 289 |
self._thread.join(timeout=1.0) |
| 290 |
if self._thread.is_alive(): |
| 291 |
log.warning( |
| 292 |
"Event loop thread could not be joined, so shutdown may not be clean. " |
| 293 |
"Please call Cluster.shutdown() to avoid this.") |
| 294 |
|
| 295 |
log.debug("Event loop thread was joined") |
| 296 |
|
| 297 |
# Ensure all connections are closed and in-flight requests cancelled |
| 298 |
for conn in tuple(_dispatcher_map.values()): |
| 299 |
if conn is not self._loop_dispatcher: |
| 300 |
conn.close() |
| 301 |
self._timers.service_timeouts() |
| 302 |
# Once all the connections are closed, close the dispatcher |
| 303 |
self._loop_dispatcher.close() |
| 304 |
|
| 305 |
log.debug("Dispatchers were closed") |
| 306 |
|
| 307 |
|
| 308 |
_global_loop = None |
| 309 |
atexit.register(partial(_cleanup, _global_loop)) |
| 310 |
|
| 311 |
|
| 312 |
class AsyncoreConnection(Connection, asyncore.dispatcher): |
| 313 |
""" |
| 314 |
An implementation of :class:`.Connection` that uses the ``asyncore`` |
| 315 |
module in the Python standard library for its event loop. |
| 316 |
""" |
| 317 |
|
| 318 |
_writable = False |
| 319 |
_readable = False |
| 320 |
|
| 321 |
@classmethod |
| 322 |
def initialize_reactor(cls): |
| 323 |
global _global_loop |
| 324 |
if not _global_loop: |
| 325 |
_global_loop = AsyncoreLoop() |
| 326 |
else: |
| 327 |
current_pid = os.getpid() |
| 328 |
if _global_loop._pid != current_pid: |
| 329 |
log.debug("Detected fork, clearing and reinitializing reactor state") |
| 330 |
cls.handle_fork() |
| 331 |
_global_loop = AsyncoreLoop() |
| 332 |
|
| 333 |
@classmethod |
| 334 |
def handle_fork(cls): |
| 335 |
global _dispatcher_map, _global_loop |
| 336 |
_dispatcher_map = {} |
| 337 |
if _global_loop: |
| 338 |
_global_loop._cleanup() |
| 339 |
_global_loop = None |
| 340 |
|
| 341 |
@classmethod |
| 342 |
def create_timer(cls, timeout, callback): |
| 343 |
timer = Timer(timeout, callback) |
| 344 |
_global_loop.add_timer(timer) |
| 345 |
return timer |
| 346 |
|
| 347 |
def __init__(self, *args, **kwargs): |
| 348 |
Connection.__init__(self, *args, **kwargs) |
| 349 |
|
| 350 |
self.deque = deque() |
| 351 |
self.deque_lock = Lock() |
| 352 |
|
| 353 |
self._connect_socket() |
| 354 |
|
| 355 |
# start the event loop if needed |
| 356 |
_global_loop.maybe_start() |
| 357 |
|
| 358 |
init_handler = WaitableTimer( |
| 359 |
timeout=0, |
| 360 |
callback=partial(asyncore.dispatcher.__init__, |
| 361 |
self, self._socket, _dispatcher_map) |
| 362 |
) |
| 363 |
_global_loop.add_timer(init_handler) |
| 364 |
init_handler.wait(kwargs["connect_timeout"]) |
| 365 |
|
| 366 |
self._writable = True |
| 367 |
self._readable = True |
| 368 |
|
| 369 |
self._send_options_message() |
| 370 |
|
| 371 |
def close(self): |
| 372 |
with self.lock: |
| 373 |
if self.is_closed: |
| 374 |
return |
| 375 |
self.is_closed = True |
| 376 |
|
| 377 |
log.debug("Closing connection (%s) to %s", id(self), self.endpoint) |
| 378 |
self._writable = False |
| 379 |
self._readable = False |
| 380 |
|
| 381 |
# We don't have to wait for this to be closed, we can just schedule it |
| 382 |
self.create_timer(0, partial(asyncore.dispatcher.close, self)) |
| 383 |
|
| 384 |
log.debug("Closed socket to %s", self.endpoint) |
| 385 |
|
| 386 |
if not self.is_defunct: |
| 387 |
self.error_all_requests( |
| 388 |
ConnectionShutdown("Connection to %s was closed" % self.endpoint)) |
| 389 |
|
| 390 |
#This happens when the connection is shutdown while waiting for the ReadyMessage |
| 391 |
if not self.connected_event.is_set(): |
| 392 |
self.last_error = ConnectionShutdown("Connection to %s was closed" % self.endpoint) |
| 393 |
|
| 394 |
# don't leave in-progress operations hanging |
| 395 |
self.connected_event.set() |
| 396 |
|
| 397 |
def handle_error(self): |
| 398 |
self.defunct(sys.exc_info()[1]) |
| 399 |
|
| 400 |
def handle_close(self): |
| 401 |
log.debug("Connection %s closed by server", self) |
| 402 |
self.close() |
| 403 |
|
| 404 |
def handle_write(self): |
| 405 |
while True: |
| 406 |
with self.deque_lock: |
| 407 |
try: |
| 408 |
next_msg = self.deque.popleft() |
| 409 |
except IndexError: |
| 410 |
self._writable = False |
| 411 |
return |
| 412 |
|
| 413 |
try: |
| 414 |
sent = self.send(next_msg) |
| 415 |
self._readable = True |
| 416 |
except socket.error as err: |
| 417 |
if (err.args[0] in NONBLOCKING or |
| 418 |
err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE)): |
| 419 |
with self.deque_lock: |
| 420 |
self.deque.appendleft(next_msg) |
| 421 |
else: |
| 422 |
self.defunct(err) |
| 423 |
return |
| 424 |
else: |
| 425 |
if sent < len(next_msg): |
| 426 |
with self.deque_lock: |
| 427 |
self.deque.appendleft(next_msg[sent:]) |
| 428 |
if sent == 0: |
| 429 |
return |
| 430 |
|
| 431 |
def handle_read(self): |
| 432 |
try: |
| 433 |
while True: |
| 434 |
buf = self.recv(self.in_buffer_size) |
| 435 |
self._iobuf.write(buf) |
| 436 |
if len(buf) < self.in_buffer_size: |
| 437 |
break |
| 438 |
except socket.error as err: |
| 439 |
if isinstance(err, ssl.SSLError): |
| 440 |
if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): |
| 441 |
if not self._iobuf.tell(): |
| 442 |
return |
| 443 |
else: |
| 444 |
self.defunct(err) |
| 445 |
return |
| 446 |
elif err.args[0] in NONBLOCKING: |
| 447 |
if not self._iobuf.tell(): |
| 448 |
return |
| 449 |
else: |
| 450 |
self.defunct(err) |
| 451 |
return |
| 452 |
|
| 453 |
if self._iobuf.tell(): |
| 454 |
self.process_io_buffer() |
| 455 |
if not self._requests and not self.is_control_connection: |
| 456 |
self._readable = False |
| 457 |
|
| 458 |
def push(self, data): |
| 459 |
sabs = self.out_buffer_size |
| 460 |
if len(data) > sabs: |
| 461 |
chunks = [] |
| 462 |
for i in range(0, len(data), sabs): |
| 463 |
chunks.append(data[i:i + sabs]) |
| 464 |
else: |
| 465 |
chunks = [data] |
| 466 |
|
| 467 |
with self.deque_lock: |
| 468 |
self.deque.extend(chunks) |
| 469 |
self._writable = True |
| 470 |
_global_loop.wake_loop() |
| 471 |
|
| 472 |
def writable(self): |
| 473 |
return self._writable |
| 474 |
|
| 475 |
def readable(self): |
| 476 |
return self._readable or ((self.is_control_connection or self._continuous_paging_sessions) and not (self.is_defunct or self.is_closed)) |