1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
|
# Copyright DataStax, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from cassandra import OperationTimedOut, WriteTimeout
from cassandra.cluster import Cluster, ExecutionProfile, ResponseFuture, EXEC_PROFILE_DEFAULT, NoHostAvailable
from cassandra.query import SimpleStatement
from cassandra.policies import ConstantSpeculativeExecutionPolicy, RoundRobinPolicy, RetryPolicy, WriteType
from cassandra.protocol import OverloadedErrorMessage, IsBootstrappingErrorMessage, TruncateError, ServerError
from tests.integration import greaterthancass21, requiressimulacron, SIMULACRON_JAR, \
CASSANDRA_VERSION
from tests.integration.simulacron import PROTOCOL_VERSION
from tests.integration.simulacron.utils import start_and_prime_singledc, prime_query, \
stop_simulacron, NO_THEN, clear_queries
from itertools import count
from packaging.version import Version
class BadRoundRobinPolicy(RoundRobinPolicy):
def make_query_plan(self, working_keyspace=None, query=None):
pos = self._position
self._position += 1
hosts = []
for _ in range(10):
hosts.extend(self._live_hosts)
return hosts
# This doesn't work well with Windows clock granularity
@requiressimulacron
class SpecExecTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"):
return
start_and_prime_singledc()
cls.cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False)
cls.session = cls.cluster.connect(wait_for_all_pools=True)
spec_ep_brr = ExecutionProfile(load_balancing_policy=BadRoundRobinPolicy(),
speculative_execution_policy=ConstantSpeculativeExecutionPolicy(1, 6),
request_timeout=12)
spec_ep_rr = ExecutionProfile(speculative_execution_policy=ConstantSpeculativeExecutionPolicy(.5, 10),
request_timeout=12)
spec_ep_rr_lim = ExecutionProfile(load_balancing_policy=BadRoundRobinPolicy(),
speculative_execution_policy=ConstantSpeculativeExecutionPolicy(0.5, 1),
request_timeout=12)
spec_ep_brr_lim = ExecutionProfile(load_balancing_policy=BadRoundRobinPolicy(),
speculative_execution_policy=ConstantSpeculativeExecutionPolicy(4, 10))
cls.cluster.add_execution_profile("spec_ep_brr", spec_ep_brr)
cls.cluster.add_execution_profile("spec_ep_rr", spec_ep_rr)
cls.cluster.add_execution_profile("spec_ep_rr_lim", spec_ep_rr_lim)
cls.cluster.add_execution_profile("spec_ep_brr_lim", spec_ep_brr_lim)
@classmethod
def tearDownClass(cls):
if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"):
return
cls.cluster.shutdown()
stop_simulacron()
def tearDown(self):
clear_queries()
@greaterthancass21
def test_speculative_execution(self):
"""
Test to ensure that speculative execution honors LBP, and that they retry appropriately.
This test will use various LBP, and ConstantSpeculativeExecutionPolicy settings and ensure the proper number of hosts are queried
@since 3.7.0
@jira_ticket PYTHON-218
@expected_result speculative retries should honor max retries, idempotent state of queries, and underlying lbp.
@test_category metadata
"""
query_to_prime = "INSERT INTO test3rf.test (k, v) VALUES (0, 1);"
prime_query(query_to_prime, then={"delay_in_ms": 10000})
statement = SimpleStatement(query_to_prime, is_idempotent=True)
statement_non_idem = SimpleStatement(query_to_prime, is_idempotent=False)
# This LBP should repeat hosts up to around 30
result = self.session.execute(statement, execution_profile='spec_ep_brr')
self.assertEqual(7, len(result.response_future.attempted_hosts))
# This LBP should keep host list to 3
result = self.session.execute(statement, execution_profile='spec_ep_rr')
self.assertEqual(3, len(result.response_future.attempted_hosts))
# Spec_execution policy should limit retries to 1
result = self.session.execute(statement, execution_profile='spec_ep_rr_lim')
self.assertEqual(2, len(result.response_future.attempted_hosts))
# Spec_execution policy should not be used if the query is not idempotent
result = self.session.execute(statement_non_idem, execution_profile='spec_ep_brr')
self.assertEqual(1, len(result.response_future.attempted_hosts))
# Default policy with non_idem query
result = self.session.execute(statement_non_idem, timeout=12)
self.assertEqual(1, len(result.response_future.attempted_hosts))
# Should be able to run an idempotent query against default execution policy with no speculative_execution_policy
result = self.session.execute(statement, timeout=12)
self.assertEqual(1, len(result.response_future.attempted_hosts))
# Test timeout with spec_ex
with self.assertRaises(OperationTimedOut):
self.session.execute(statement, execution_profile='spec_ep_rr', timeout=.5)
prepared_query_to_prime = "SELECT * FROM test3rf.test where k = ?"
when = {"params": {"k": "0"}, "param_types": {"k": "ascii"}}
prime_query(prepared_query_to_prime, when=when, then={"delay_in_ms": 4000})
# PYTHON-736 Test speculation policy works with a prepared statement
prepared_statement = self.session.prepare(prepared_query_to_prime)
# non-idempotent
result = self.session.execute(prepared_statement, ("0",), execution_profile='spec_ep_brr')
self.assertEqual(1, len(result.response_future.attempted_hosts))
# idempotent
prepared_statement.is_idempotent = True
result = self.session.execute(prepared_statement, ("0",), execution_profile='spec_ep_brr')
self.assertLess(1, len(result.response_future.attempted_hosts))
def test_speculative_and_timeout(self):
"""
Test to ensure the timeout is honored when using speculative execution
@since 3.10
@jira_ticket PYTHON-750
@expected_result speculative retries be schedule every fixed period, during the maximum
period of the timeout.
@test_category metadata
"""
query_to_prime = "INSERT INTO testkeyspace.testtable (k, v) VALUES (0, 1);"
prime_query(query_to_prime, then=NO_THEN)
statement = SimpleStatement(query_to_prime, is_idempotent=True)
# An OperationTimedOut is placed here in response_future,
# that's why we can't call session.execute,which would raise it, but
# we have to directly wait for the event
response_future = self.session.execute_async(statement, execution_profile='spec_ep_brr_lim',
timeout=14)
response_future._event.wait(16)
self.assertIsInstance(response_future._final_exception, OperationTimedOut)
# This is because 14 / 4 + 1 = 4
self.assertEqual(len(response_future.attempted_hosts), 4)
def test_delay_can_be_0(self):
"""
Test to validate that the delay can be zero for the ConstantSpeculativeExecutionPolicy
@since 3.13
@jira_ticket PYTHON-836
@expected_result all the queries are executed immediately
@test_category policy
"""
query_to_prime = "INSERT INTO madeup_keyspace.madeup_table(k, v) VALUES (1, 2)"
prime_query(query_to_prime, then={"delay_in_ms": 5000})
number_of_requests = 4
spec = ExecutionProfile(load_balancing_policy=RoundRobinPolicy(),
speculative_execution_policy=ConstantSpeculativeExecutionPolicy(0, number_of_requests))
cluster = Cluster(protocol_version=PROTOCOL_VERSION, compression=False)
cluster.add_execution_profile("spec", spec)
session = cluster.connect(wait_for_all_pools=True)
self.addCleanup(cluster.shutdown)
counter = count()
def patch_and_count(f):
def patched(*args, **kwargs):
next(counter)
f(*args, **kwargs)
return patched
self.addCleanup(setattr, ResponseFuture, "send_request", ResponseFuture.send_request)
ResponseFuture.send_request = patch_and_count(ResponseFuture.send_request)
stmt = SimpleStatement(query_to_prime)
stmt.is_idempotent = True
results = session.execute(stmt, execution_profile="spec")
self.assertEqual(len(results.response_future.attempted_hosts), 3)
# send_request is called number_of_requests times for the speculative request
# plus one for the call from the main thread.
self.assertEqual(next(counter), number_of_requests + 1)
class CustomRetryPolicy(RetryPolicy):
def on_write_timeout(self, query, consistency, write_type,
required_responses, received_responses, retry_num):
if retry_num != 0:
return self.RETHROW, None
elif write_type == WriteType.SIMPLE:
return self.RETHROW, None
elif write_type == WriteType.CDC:
return self.IGNORE, None
class CounterRetryPolicy(RetryPolicy):
def __init__(self):
self.write_timeout = count()
self.read_timeout = count()
self.unavailable = count()
self.request_error = count()
def on_read_timeout(self, query, consistency, required_responses,
received_responses, data_retrieved, retry_num):
next(self.read_timeout)
return self.IGNORE, None
def on_write_timeout(self, query, consistency, write_type,
required_responses, received_responses, retry_num):
next(self.write_timeout)
return self.IGNORE, None
def on_unavailable(self, query, consistency, required_replicas, alive_replicas, retry_num):
next(self.unavailable)
return self.IGNORE, None
def on_request_error(self, query, consistency, error, retry_num):
next(self.request_error)
return self.RETHROW, None
def reset_counters(self):
self.write_timeout = count()
self.read_timeout = count()
self.unavailable = count()
self.request_error = count()
@requiressimulacron
class RetryPolicyTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"):
return
start_and_prime_singledc()
@classmethod
def tearDownClass(cls):
if SIMULACRON_JAR is None or CASSANDRA_VERSION < Version("2.1"):
return
stop_simulacron()
def tearDown(self):
clear_queries()
def set_cluster(self, retry_policy):
self.cluster = Cluster(
protocol_version=PROTOCOL_VERSION,
compression=False,
execution_profiles={
EXEC_PROFILE_DEFAULT: ExecutionProfile(retry_policy=retry_policy)
},
)
self.session = self.cluster.connect(wait_for_all_pools=True)
self.addCleanup(self.cluster.shutdown)
def test_retry_policy_ignores_and_rethrows(self):
"""
Test to verify :class:`~cassandra.protocol.WriteTimeoutErrorMessage` is decoded correctly and that
:attr:`.~cassandra.policies.RetryPolicy.RETHROW` and
:attr:`.~cassandra.policies.RetryPolicy.IGNORE` are respected
to localhost
@since 3.12
@jira_ticket PYTHON-812
@expected_result the retry policy functions as expected
@test_category connection
"""
self.set_cluster(CustomRetryPolicy())
query_to_prime_simple = "SELECT * from simulacron_keyspace.simple"
query_to_prime_cdc = "SELECT * from simulacron_keyspace.cdc"
then = {
"result": "write_timeout",
"delay_in_ms": 0,
"consistency_level": "LOCAL_QUORUM",
"received": 1,
"block_for": 2,
"write_type": "SIMPLE",
"ignore_on_prepare": True
}
prime_query(query_to_prime_simple, rows=None, column_types=None, then=then)
then["write_type"] = "CDC"
prime_query(query_to_prime_cdc, rows=None, column_types=None, then=then)
with self.assertRaises(WriteTimeout):
self.session.execute(query_to_prime_simple)
#CDC should be ignored
self.session.execute(query_to_prime_cdc)
def test_retry_policy_with_prepared(self):
"""
Test to verify that the retry policy is called as expected
for bound and prepared statements when set at the cluster level
@since 3.13
@jira_ticket PYTHON-861
@expected_result the appropriate retry policy is called
@test_category connection
"""
counter_policy = CounterRetryPolicy()
self.set_cluster(counter_policy)
query_to_prime = "SELECT * from simulacron_keyspace.simulacron_table"
then = {
"result": "write_timeout",
"delay_in_ms": 0,
"consistency_level": "LOCAL_QUORUM",
"received": 1,
"block_for": 2,
"write_type": "SIMPLE",
"ignore_on_prepare": True
}
prime_query(query_to_prime, then=then, rows=None, column_types=None)
self.session.execute(query_to_prime)
self.assertEqual(next(counter_policy.write_timeout), 1)
counter_policy.reset_counters()
query_to_prime_prepared = "SELECT * from simulacron_keyspace.simulacron_table WHERE key = :key"
when = {"params": {"key": "0"}, "param_types": {"key": "ascii"}}
prime_query(query_to_prime_prepared, when=when, then=then, rows=None, column_types=None)
prepared_stmt = self.session.prepare(query_to_prime_prepared)
bound_stm = prepared_stmt.bind({"key": "0"})
self.session.execute(bound_stm)
self.assertEqual(next(counter_policy.write_timeout), 1)
counter_policy.reset_counters()
self.session.execute(prepared_stmt, ("0",))
self.assertEqual(next(counter_policy.write_timeout), 1)
def test_setting_retry_policy_to_statement(self):
"""
Test to verify that the retry policy is called as expected
for bound and prepared statements when set to the prepared statement
@since 3.13
@jira_ticket PYTHON-861
@expected_result the appropriate retry policy is called
@test_category connection
"""
retry_policy = RetryPolicy()
self.set_cluster(retry_policy)
then = {
"result": "write_timeout",
"delay_in_ms": 0,
"consistency_level": "LOCAL_QUORUM",
"received": 1,
"block_for": 2,
"write_type": "SIMPLE",
"ignore_on_prepare": True
}
query_to_prime_prepared = "SELECT * from simulacron_keyspace.simulacron_table WHERE key = :key"
when = {"params": {"key": "0"}, "param_types": {"key": "ascii"}}
prime_query(query_to_prime_prepared, when=when, then=then, rows=None, column_types=None)
counter_policy = CounterRetryPolicy()
prepared_stmt = self.session.prepare(query_to_prime_prepared)
prepared_stmt.retry_policy = counter_policy
self.session.execute(prepared_stmt, ("0",))
self.assertEqual(next(counter_policy.write_timeout), 1)
counter_policy.reset_counters()
bound_stmt = prepared_stmt.bind({"key": "0"})
bound_stmt.retry_policy = counter_policy
self.session.execute(bound_stmt)
self.assertEqual(next(counter_policy.write_timeout), 1)
def test_retry_policy_on_request_error(self):
"""
Test to verify that on_request_error is called properly.
@since 3.18
@jira_ticket PYTHON-1064
@expected_result the appropriate retry policy is called
@test_category connection
"""
overloaded_error = {
"result": "overloaded",
"message": "overloaded"
}
bootstrapping_error = {
"result": "is_bootstrapping",
"message": "isbootstrapping"
}
truncate_error = {
"result": "truncate_error",
"message": "truncate_error"
}
server_error = {
"result": "server_error",
"message": "server_error"
}
# Test the on_request_error call
retry_policy = CounterRetryPolicy()
self.set_cluster(retry_policy)
for prime_error, exc in [
(overloaded_error, OverloadedErrorMessage),
(bootstrapping_error, IsBootstrappingErrorMessage),
(truncate_error, TruncateError),
(server_error, ServerError)]:
clear_queries()
query_to_prime = "SELECT * from simulacron_keyspace.simulacron_table;"
prime_query(query_to_prime, then=prime_error, rows=None, column_types=None)
rf = self.session.execute_async(query_to_prime)
with self.assertRaises(exc):
rf.result()
self.assertEqual(len(rf.attempted_hosts), 1) # no retry
self.assertEqual(next(retry_policy.request_error), 4)
# Test that by default, retry on next host
retry_policy = RetryPolicy()
self.set_cluster(retry_policy)
for e in [overloaded_error, bootstrapping_error, truncate_error, server_error]:
clear_queries()
query_to_prime = "SELECT * from simulacron_keyspace.simulacron_table;"
prime_query(query_to_prime, then=e, rows=None, column_types=None)
rf = self.session.execute_async(query_to_prime)
with self.assertRaises(NoHostAvailable):
rf.result()
self.assertEqual(len(rf.attempted_hosts), 3) # all 3 nodes failed
|