Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 79 additions & 3 deletions cassandra/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@
from cassandra.connection import (ClientRoutesEndPointFactory, ConnectionException, ConnectionShutdown,
ConnectionHeartbeat, ProtocolVersionUnsupported,
EndPoint, DefaultEndPoint, DefaultEndPointFactory,
SniEndPointFactory, ConnectionBusy, locally_supported_compressions)
SniEndPointFactory, ConnectionBusy, locally_supported_compressions,
SSLSessionCache)
from cassandra.cqltypes import UserType
import cassandra.cqltypes as types
from cassandra.encoder import Encoder
Expand Down Expand Up @@ -916,6 +917,45 @@ def default_retry_policy(self, policy):
.. versionadded:: 3.17.0
"""

ssl_session_cache = None
"""
An optional :class:`~cassandra.connection.SSLSessionCache` instance used to
enable TLS session resumption (via session tickets or PSK) for all
connections managed by this cluster.

When :attr:`~Cluster.ssl_context` is set, a cache is created automatically
so that reconnections to the same host can skip the full TLS handshake.
Set this to :const:`None` explicitly to disable session caching.

Note: automatic caching is **not** enabled for the legacy
:attr:`~Cluster.ssl_options` path because each connection builds a fresh
``SSLContext``, making session reuse impossible. If you migrate to
``ssl_context``, the cache will be created automatically.

You may also pass a custom :class:`~cassandra.connection.SSLSessionCache`
instance with specific ``max_size`` and ``ttl`` parameters::

from cassandra.connection import SSLSessionCache

cluster = Cluster(
ssl_context=ssl_context,
ssl_session_cache=SSLSessionCache(max_size=200, ttl=7200),
)

Note: TLS 1.2 sessions are cached immediately after connect. TLS 1.3
sessions are cached after the CQL handshake completes (Ready / AuthSuccess),
because session tickets are sent asynchronously by the server.

Works with stdlib ``ssl`` (asyncore, libev, gevent) and PyOpenSSL
(Twisted, Eventlet).

Note: the ``asyncio`` event loop (``EVENT_LOOP_MANAGER=asyncio``) is **not**
supported. ``AsyncioConnection`` performs the TLS handshake via
``loop.create_connection(..., ssl=...)``, which offers no hook to restore a
cached session before the handshake, so the cache is neither populated nor
used on that reactor.
"""

sockopts = None
"""
An optional list of tuples which will be used as arguments to
Expand Down Expand Up @@ -1268,7 +1308,8 @@ def __init__(self,
column_encryption_policy=None,
application_info:Optional[ApplicationInfoBase]=None,
client_routes_config:Optional[ClientRoutesConfig]=None,
allow_control_connection_query_fallback:Optional[ControlConnectionQueryFallback]=ControlConnectionQueryFallback.Disabled
allow_control_connection_query_fallback:Optional[ControlConnectionQueryFallback]=ControlConnectionQueryFallback.Disabled,
ssl_session_cache=_NOT_SET
):
"""
``executor_threads`` defines the number of threads in a pool for handling asynchronous tasks such as
Expand Down Expand Up @@ -1517,6 +1558,23 @@ def __init__(self,

self.ssl_options = ssl_options
self.ssl_context = ssl_context

# Auto-create a session cache when TLS is enabled via ssl_context,
# unless the caller explicitly passed ssl_session_cache (including None
# to opt out). The legacy ssl_options-only path is excluded because it
# builds a fresh SSLContext per connection, making session reuse
# impossible. The asyncio reactor is also skipped because
# AsyncioConnection establishes TLS via loop.create_connection(...,
# ssl=...) and offers no hook to restore/store sessions, so an
# auto-created cache would stay empty.
if ssl_session_cache is _NOT_SET:
if ssl_context is not None and self._connection_class_supports_tls_resumption():
self.ssl_session_cache = SSLSessionCache()
else:
self.ssl_session_cache = None
else:
self.ssl_session_cache = ssl_session_cache

self.sockopts = sockopts
self.cql_version = cql_version
self.max_schema_agreement_wait = max_schema_agreement_wait
Expand Down Expand Up @@ -1751,6 +1809,23 @@ def connection_factory(self, endpoint, host_conn = None, *args, **kwargs):
kwargs = self._make_connection_kwargs(endpoint, kwargs)
return self.connection_class.factory(endpoint, self.connect_timeout, host_conn, *args, **kwargs)

def _connection_class_supports_tls_resumption(self):
"""
Return ``False`` for reactors that cannot restore/store TLS sessions,
so a session cache is not auto-created where it would stay empty.

Currently only the asyncio reactor is unsupported: it establishes TLS
via ``loop.create_connection(..., ssl=...)`` with no hook to restore a
cached session before the handshake.
"""
try:
from cassandra.io.asyncioreactor import AsyncioConnection
except (ImportError, DependencyException):
# asyncio not available at all; treat as "supported" since the
# AsyncioConnection class cannot be selected in that environment.
return True
return not issubclass(self.connection_class, AsyncioConnection)

def _make_connection_factory(self, host, *args, **kwargs):
kwargs = self._make_connection_kwargs(host.endpoint, kwargs)
return partial(self.connection_class.factory, host.endpoint, self.connect_timeout, *args, **kwargs)
Expand All @@ -1764,6 +1839,7 @@ def _make_connection_kwargs(self, endpoint, kwargs_dict):
kwargs_dict.setdefault('sockopts', self.sockopts)
kwargs_dict.setdefault('ssl_options', self.ssl_options)
kwargs_dict.setdefault('ssl_context', self.ssl_context)
kwargs_dict.setdefault('ssl_session_cache', self.ssl_session_cache)
kwargs_dict.setdefault('cql_version', self.cql_version)
kwargs_dict.setdefault('protocol_version', self.protocol_version)
kwargs_dict.setdefault('user_type_map', self._user_types)
Expand Down Expand Up @@ -5329,7 +5405,7 @@ def _execute_after_prepare(self, host, connection, pool, response):
new_metadata_id = response.result_metadata_id
if new_metadata_id is not None:
self.prepared_statement.result_metadata_id = new_metadata_id

# use self._query to re-use the same host and
# at the same time properly borrow the connection
if pool is None and connection is not None and connection.is_control_connection:
Expand Down
Loading
Loading