| 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 |
|
| 15 |
from collections import defaultdict |
| 16 |
import logging |
| 17 |
import threading |
| 18 |
|
| 19 |
from cassandra.cluster import Cluster, _ConfigMode, _NOT_SET, NoHostAvailable, UserTypeDoesNotExist, ConsistencyLevel |
| 20 |
from cassandra.query import SimpleStatement, dict_factory |
| 21 |
|
| 22 |
from cassandra.cqlengine import CQLEngineException |
| 23 |
from cassandra.cqlengine.statements import BaseCQLStatement |
| 24 |
|
| 25 |
|
| 26 |
log = logging.getLogger(__name__) |
| 27 |
|
| 28 |
NOT_SET = _NOT_SET # required for passing timeout to Session.execute |
| 29 |
|
| 30 |
cluster = None |
| 31 |
session = None |
| 32 |
|
| 33 |
# connections registry |
| 34 |
DEFAULT_CONNECTION = object() |
| 35 |
_connections = {} |
| 36 |
|
| 37 |
# Because type models may be registered before a connection is present, |
| 38 |
# and because sessions may be replaced, we must register UDTs here, in order |
| 39 |
# to have them registered when a new session is established. |
| 40 |
udt_by_keyspace = defaultdict(dict) |
| 41 |
|
| 42 |
|
| 43 |
def format_log_context(msg, connection=None, keyspace=None): |
| 44 |
"""Format log message to add keyspace and connection context""" |
| 45 |
connection_info = connection or 'DEFAULT_CONNECTION' |
| 46 |
|
| 47 |
if keyspace: |
| 48 |
msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg) |
| 49 |
else: |
| 50 |
msg = '[Connection: {0}] {1}'.format(connection_info, msg) |
| 51 |
return msg |
| 52 |
|
| 53 |
|
| 54 |
class UndefinedKeyspaceException(CQLEngineException): |
| 55 |
pass |
| 56 |
|
| 57 |
|
| 58 |
class Connection(object): |
| 59 |
"""CQLEngine Connection""" |
| 60 |
|
| 61 |
name = None |
| 62 |
hosts = None |
| 63 |
|
| 64 |
consistency = None |
| 65 |
retry_connect = False |
| 66 |
lazy_connect = False |
| 67 |
lazy_connect_lock = None |
| 68 |
cluster_options = None |
| 69 |
|
| 70 |
cluster = None |
| 71 |
session = None |
| 72 |
|
| 73 |
def __init__(self, name, hosts, consistency=None, |
| 74 |
lazy_connect=False, retry_connect=False, cluster_options=None): |
| 75 |
self.hosts = hosts |
| 76 |
self.name = name |
| 77 |
self.consistency = consistency |
| 78 |
self.lazy_connect = lazy_connect |
| 79 |
self.retry_connect = retry_connect |
| 80 |
self.cluster_options = cluster_options if cluster_options else {} |
| 81 |
self.lazy_connect_lock = threading.RLock() |
| 82 |
|
| 83 |
@classmethod |
| 84 |
def from_session(cls, name, session): |
| 85 |
instance = cls(name=name, hosts=session.hosts) |
| 86 |
instance.cluster, instance.session = session.cluster, session |
| 87 |
instance.setup_session() |
| 88 |
return instance |
| 89 |
|
| 90 |
def setup(self): |
| 91 |
"""Setup the connection""" |
| 92 |
global cluster, session |
| 93 |
|
| 94 |
if 'username' in self.cluster_options or 'password' in self.cluster_options: |
| 95 |
raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider") |
| 96 |
|
| 97 |
if self.lazy_connect: |
| 98 |
return |
| 99 |
|
| 100 |
if 'cloud' in self.cluster_options: |
| 101 |
if self.hosts: |
| 102 |
log.warning("Ignoring hosts %s because a cloud config was provided.", self.hosts) |
| 103 |
self.cluster = Cluster(**self.cluster_options) |
| 104 |
else: |
| 105 |
self.cluster = Cluster(self.hosts, **self.cluster_options) |
| 106 |
|
| 107 |
try: |
| 108 |
self.session = self.cluster.connect() |
| 109 |
log.debug(format_log_context("connection initialized with internally created session", connection=self.name)) |
| 110 |
except NoHostAvailable: |
| 111 |
if self.retry_connect: |
| 112 |
log.warning(format_log_context("connect failed, setting up for re-attempt on first use", connection=self.name)) |
| 113 |
self.lazy_connect = True |
| 114 |
raise |
| 115 |
|
| 116 |
if DEFAULT_CONNECTION in _connections and _connections[DEFAULT_CONNECTION] == self: |
| 117 |
cluster = _connections[DEFAULT_CONNECTION].cluster |
| 118 |
session = _connections[DEFAULT_CONNECTION].session |
| 119 |
|
| 120 |
self.setup_session() |
| 121 |
|
| 122 |
def setup_session(self): |
| 123 |
if self.cluster._config_mode == _ConfigMode.PROFILES: |
| 124 |
self.cluster.profile_manager.default.row_factory = dict_factory |
| 125 |
if self.consistency is not None: |
| 126 |
self.cluster.profile_manager.default.consistency_level = self.consistency |
| 127 |
else: |
| 128 |
self.session.row_factory = dict_factory |
| 129 |
if self.consistency is not None: |
| 130 |
self.session.default_consistency_level = self.consistency |
| 131 |
enc = self.session.encoder |
| 132 |
enc.mapping[tuple] = enc.cql_encode_tuple |
| 133 |
_register_known_types(self.session.cluster) |
| 134 |
|
| 135 |
def handle_lazy_connect(self): |
| 136 |
|
| 137 |
# if lazy_connect is False, it means the cluster is setup and ready |
| 138 |
# No need to acquire the lock |
| 139 |
if not self.lazy_connect: |
| 140 |
return |
| 141 |
|
| 142 |
with self.lazy_connect_lock: |
| 143 |
# lazy_connect might have been set to False by another thread while waiting the lock |
| 144 |
# In this case, do nothing. |
| 145 |
if self.lazy_connect: |
| 146 |
log.debug(format_log_context("Lazy connect enabled", connection=self.name)) |
| 147 |
self.lazy_connect = False |
| 148 |
self.setup() |
| 149 |
|
| 150 |
|
| 151 |
def register_connection(name, hosts=None, consistency=None, lazy_connect=False, |
| 152 |
retry_connect=False, cluster_options=None, default=False, |
| 153 |
session=None): |
| 154 |
""" |
| 155 |
Add a connection to the connection registry. ``hosts`` and ``session`` are |
| 156 |
mutually exclusive, and ``consistency``, ``lazy_connect``, |
| 157 |
``retry_connect``, and ``cluster_options`` only work with ``hosts``. Using |
| 158 |
``hosts`` will create a new :class:`cassandra.cluster.Cluster` and |
| 159 |
:class:`cassandra.cluster.Session`. |
| 160 |
|
| 161 |
:param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`). |
| 162 |
:param int consistency: The default :class:`~.ConsistencyLevel` for the |
| 163 |
registered connection's new session. Default is the same as |
| 164 |
:attr:`.Session.default_consistency_level`. For use with ``hosts`` only; |
| 165 |
will fail when used with ``session``. |
| 166 |
:param bool lazy_connect: True if should not connect until first use. For |
| 167 |
use with ``hosts`` only; will fail when used with ``session``. |
| 168 |
:param bool retry_connect: True if we should retry to connect even if there |
| 169 |
was a connection failure initially. For use with ``hosts`` only; will |
| 170 |
fail when used with ``session``. |
| 171 |
:param dict cluster_options: A dict of options to be used as keyword |
| 172 |
arguments to :class:`cassandra.cluster.Cluster`. For use with ``hosts`` |
| 173 |
only; will fail when used with ``session``. |
| 174 |
:param bool default: If True, set the new connection as the cqlengine |
| 175 |
default |
| 176 |
:param Session session: A :class:`cassandra.cluster.Session` to be used in |
| 177 |
the created connection. |
| 178 |
""" |
| 179 |
|
| 180 |
if name in _connections: |
| 181 |
log.warning("Registering connection '{0}' when it already exists.".format(name)) |
| 182 |
|
| 183 |
if session is not None: |
| 184 |
invalid_config_args = (hosts is not None or |
| 185 |
consistency is not None or |
| 186 |
lazy_connect is not False or |
| 187 |
retry_connect is not False or |
| 188 |
cluster_options is not None) |
| 189 |
if invalid_config_args: |
| 190 |
raise CQLEngineException( |
| 191 |
"Session configuration arguments and 'session' argument are mutually exclusive" |
| 192 |
) |
| 193 |
conn = Connection.from_session(name, session=session) |
| 194 |
else: # use hosts argument |
| 195 |
conn = Connection( |
| 196 |
name, hosts=hosts, |
| 197 |
consistency=consistency, lazy_connect=lazy_connect, |
| 198 |
retry_connect=retry_connect, cluster_options=cluster_options |
| 199 |
) |
| 200 |
conn.setup() |
| 201 |
|
| 202 |
_connections[name] = conn |
| 203 |
|
| 204 |
if default: |
| 205 |
set_default_connection(name) |
| 206 |
|
| 207 |
return conn |
| 208 |
|
| 209 |
|
| 210 |
def unregister_connection(name): |
| 211 |
global cluster, session |
| 212 |
|
| 213 |
if name not in _connections: |
| 214 |
return |
| 215 |
|
| 216 |
if DEFAULT_CONNECTION in _connections and _connections[name] == _connections[DEFAULT_CONNECTION]: |
| 217 |
del _connections[DEFAULT_CONNECTION] |
| 218 |
cluster = None |
| 219 |
session = None |
| 220 |
|
| 221 |
conn = _connections[name] |
| 222 |
if conn.cluster: |
| 223 |
conn.cluster.shutdown() |
| 224 |
del _connections[name] |
| 225 |
log.debug("Connection '{0}' has been removed from the registry.".format(name)) |
| 226 |
|
| 227 |
|
| 228 |
def set_default_connection(name): |
| 229 |
global cluster, session |
| 230 |
|
| 231 |
if name not in _connections: |
| 232 |
raise CQLEngineException("Connection '{0}' doesn't exist.".format(name)) |
| 233 |
|
| 234 |
log.debug("Connection '{0}' has been set as default.".format(name)) |
| 235 |
_connections[DEFAULT_CONNECTION] = _connections[name] |
| 236 |
cluster = _connections[name].cluster |
| 237 |
session = _connections[name].session |
| 238 |
|
| 239 |
|
| 240 |
def get_connection(name=None): |
| 241 |
|
| 242 |
if not name: |
| 243 |
name = DEFAULT_CONNECTION |
| 244 |
|
| 245 |
if name not in _connections: |
| 246 |
raise CQLEngineException("Connection name '{0}' doesn't exist in the registry.".format(name)) |
| 247 |
|
| 248 |
conn = _connections[name] |
| 249 |
conn.handle_lazy_connect() |
| 250 |
|
| 251 |
return conn |
| 252 |
|
| 253 |
|
| 254 |
def default(): |
| 255 |
""" |
| 256 |
Configures the default connection to localhost, using the driver defaults |
| 257 |
(except for row_factory) |
| 258 |
""" |
| 259 |
|
| 260 |
try: |
| 261 |
conn = get_connection() |
| 262 |
if conn.session: |
| 263 |
log.warning("configuring new default connection for cqlengine when one was already set") |
| 264 |
except: |
| 265 |
pass |
| 266 |
|
| 267 |
register_connection('default', hosts=None, default=True) |
| 268 |
|
| 269 |
log.debug("cqlengine connection initialized with default session to localhost") |
| 270 |
|
| 271 |
|
| 272 |
def set_session(s): |
| 273 |
""" |
| 274 |
Configures the default connection with a preexisting :class:`cassandra.cluster.Session` |
| 275 |
|
| 276 |
Note: the mapper presently requires a Session :attr:`~.row_factory` set to ``dict_factory``. |
| 277 |
This may be relaxed in the future |
| 278 |
""" |
| 279 |
|
| 280 |
try: |
| 281 |
conn = get_connection() |
| 282 |
except CQLEngineException: |
| 283 |
# no default connection set; initalize one |
| 284 |
register_connection('default', session=s, default=True) |
| 285 |
conn = get_connection() |
| 286 |
else: |
| 287 |
if conn.session: |
| 288 |
log.warning("configuring new default session for cqlengine when one was already set") |
| 289 |
|
| 290 |
if not any([ |
| 291 |
s.cluster.profile_manager.default.row_factory is dict_factory and s.cluster._config_mode in [_ConfigMode.PROFILES, _ConfigMode.UNCOMMITTED], |
| 292 |
s.row_factory is dict_factory and s.cluster._config_mode in [_ConfigMode.LEGACY, _ConfigMode.UNCOMMITTED], |
| 293 |
]): |
| 294 |
raise CQLEngineException("Failed to initialize: row_factory must be 'dict_factory'") |
| 295 |
|
| 296 |
conn.session = s |
| 297 |
conn.cluster = s.cluster |
| 298 |
|
| 299 |
# Set default keyspace from given session's keyspace |
| 300 |
if conn.session.keyspace: |
| 301 |
from cassandra.cqlengine import models |
| 302 |
models.DEFAULT_KEYSPACE = conn.session.keyspace |
| 303 |
|
| 304 |
conn.setup_session() |
| 305 |
|
| 306 |
log.debug("cqlengine default connection initialized with %s", s) |
| 307 |
|
| 308 |
|
| 309 |
# TODO next major: if a cloud config is specified in kwargs, hosts will be ignored. |
| 310 |
# This function should be refactored to reflect this change. PYTHON-1265 |
| 311 |
def setup( |
| 312 |
hosts, |
| 313 |
default_keyspace, |
| 314 |
consistency=None, |
| 315 |
lazy_connect=False, |
| 316 |
retry_connect=False, |
| 317 |
**kwargs): |
| 318 |
""" |
| 319 |
Setup a the driver connection used by the mapper |
| 320 |
|
| 321 |
:param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`) |
| 322 |
:param str default_keyspace: The default keyspace to use |
| 323 |
:param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Session.default_consistency_level` |
| 324 |
:param bool lazy_connect: True if should not connect until first use |
| 325 |
:param bool retry_connect: True if we should retry to connect even if there was a connection failure initially |
| 326 |
:param kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster` |
| 327 |
""" |
| 328 |
|
| 329 |
from cassandra.cqlengine import models |
| 330 |
models.DEFAULT_KEYSPACE = default_keyspace |
| 331 |
|
| 332 |
register_connection('default', hosts=hosts, consistency=consistency, lazy_connect=lazy_connect, |
| 333 |
retry_connect=retry_connect, cluster_options=kwargs, default=True) |
| 334 |
|
| 335 |
|
| 336 |
def execute(query, params=None, consistency_level=None, timeout=NOT_SET, connection=None): |
| 337 |
|
| 338 |
conn = get_connection(connection) |
| 339 |
|
| 340 |
if not conn.session: |
| 341 |
raise CQLEngineException("It is required to setup() cqlengine before executing queries") |
| 342 |
|
| 343 |
if isinstance(query, SimpleStatement): |
| 344 |
pass # |
| 345 |
elif isinstance(query, BaseCQLStatement): |
| 346 |
params = query.get_context() |
| 347 |
query = SimpleStatement(str(query), consistency_level=consistency_level, fetch_size=query.fetch_size) |
| 348 |
elif isinstance(query, str): |
| 349 |
query = SimpleStatement(query, consistency_level=consistency_level) |
| 350 |
log.debug(format_log_context('Query: {}, Params: {}'.format(query.query_string, params), connection=connection)) |
| 351 |
|
| 352 |
result = conn.session.execute(query, params, timeout=timeout) |
| 353 |
|
| 354 |
return result |
| 355 |
|
| 356 |
|
| 357 |
def get_session(connection=None): |
| 358 |
conn = get_connection(connection) |
| 359 |
return conn.session |
| 360 |
|
| 361 |
|
| 362 |
def get_cluster(connection=None): |
| 363 |
conn = get_connection(connection) |
| 364 |
if not conn.cluster: |
| 365 |
raise CQLEngineException("%s.cluster is not configured. Call one of the setup or default functions first." % __name__) |
| 366 |
return conn.cluster |
| 367 |
|
| 368 |
|
| 369 |
def register_udt(keyspace, type_name, klass, connection=None): |
| 370 |
udt_by_keyspace[keyspace][type_name] = klass |
| 371 |
|
| 372 |
try: |
| 373 |
cluster = get_cluster(connection) |
| 374 |
except CQLEngineException: |
| 375 |
cluster = None |
| 376 |
|
| 377 |
if cluster: |
| 378 |
try: |
| 379 |
cluster.register_user_type(keyspace, type_name, klass) |
| 380 |
except UserTypeDoesNotExist: |
| 381 |
pass # new types are covered in management sync functions |
| 382 |
|
| 383 |
|
| 384 |
def _register_known_types(cluster): |
| 385 |
from cassandra.cqlengine import models |
| 386 |
for ks_name, name_type_map in udt_by_keyspace.items(): |
| 387 |
for type_name, klass in name_type_map.items(): |
| 388 |
try: |
| 389 |
cluster.register_user_type(ks_name or models.DEFAULT_KEYSPACE, type_name, klass) |
| 390 |
except UserTypeDoesNotExist: |
| 391 |
pass # new types are covered in management sync functions |