kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | b1d33724c50ee0572ea6e15d2f73992e94405a089722227d58e920b0cee05bb0 |
|---|---|
| Author | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-03-01 19:45 +01:00 |
| Committer | Olivier Michallat <olim7t@users.noreply.github.com> · 2016-03-01 19:45 +01:00 |
| Parents | 21416b606ef9, 197c1f67b775 |
28 files changed
modified changelog/README.md +1 −0
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | - [improvement] JAVA-1021: Improve error message when connect() is called with an invalid keyspace name. |
| 24 | 24 | - [improvement] JAVA-879: Mapper.map() accepts mapper-generated and user queries. |
| 25 | 25 | - [bug] JAVA-1100: Exception when connecting with shaded java driver in OSGI |
| 26 | +- [bug] JAVA-819: Expose more errors in RetryPolicy + provide idempotent-aware wrapper. | |
| 26 | 27 | |
| 27 | 28 | Merged from 2.0 branch: |
| 28 | 29 |
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +103 −7
| @@ -272,6 +272,7 @@ | ||
| 272 | 272 | private final Counter writeTimeouts = registry.counter("write-timeouts"); |
| 273 | 273 | private final Counter readTimeouts = registry.counter("read-timeouts"); |
| 274 | 274 | private final Counter unavailables = registry.counter("unavailables"); |
| 275 | + private final Counter clientTimeouts = registry.counter("client-timeouts"); | |
| 275 | 276 | |
| 276 | 277 | private final Counter otherErrors = registry.counter("other-errors"); |
| 277 | 278 | |
| @@ -279,10 +280,17 @@ | ||
| 279 | 280 | private final Counter retriesOnWriteTimeout = registry.counter("retries-on-write-timeout"); |
| 280 | 281 | private final Counter retriesOnReadTimeout = registry.counter("retries-on-read-timeout"); |
| 281 | 282 | private final Counter retriesOnUnavailable = registry.counter("retries-on-unavailable"); |
| 283 | + private final Counter retriesOnClientTimeout = registry.counter("retries-on-client-timeout"); | |
| 284 | + private final Counter retriesOnConnectionError = registry.counter("retries-on-connection-error"); | |
| 285 | + private final Counter retriesOnOtherErrors = registry.counter("retries-on-other-errors"); | |
| 286 | + | |
| 282 | 287 | private final Counter ignores = registry.counter("ignores"); |
| 283 | 288 | private final Counter ignoresOnWriteTimeout = registry.counter("ignores-on-write-timeout"); |
| 284 | 289 | private final Counter ignoresOnReadTimeout = registry.counter("ignores-on-read-timeout"); |
| 285 | 290 | private final Counter ignoresOnUnavailable = registry.counter("ignores-on-unavailable"); |
| 291 | + private final Counter ignoresOnClientTimeout = registry.counter("ignores-on-client-timeout"); | |
| 292 | + private final Counter ignoresOnConnectionError = registry.counter("ignores-on-connection-error"); | |
| 293 | + private final Counter ignoresOnOtherErrors = registry.counter("ignores-on-other-errors"); | |
| 286 | 294 | |
| 287 | 295 | private final Counter speculativeExecutions = registry.counter("speculative-executions"); |
| 288 | 296 | |
| @@ -334,6 +342,16 @@ | ||
| 334 | 342 | return unavailables; |
| 335 | 343 | } |
| 336 | 344 | |
| 345 | + /** | |
| 346 | + * Returns the number of requests that timed out before the driver | |
| 347 | + * received a response. | |
| 348 | + * | |
| 349 | + * @return the number of client timeouts. | |
| 350 | + */ | |
| 351 | + public Counter getClientTimeouts() { | |
| 352 | + return clientTimeouts; | |
| 353 | + } | |
| 354 | + | |
| 337 | 355 | /** |
| 338 | 356 | * Returns the number of requests that returned errors not accounted for by |
| 339 | 357 | * another metric. This includes all types of invalid requests. |
| @@ -349,7 +367,7 @@ | ||
| 349 | 367 | * Returns the number of times a request was retried due to the |
| 350 | 368 | * {@link com.datastax.driver.core.policies.RetryPolicy}. |
| 351 | 369 | * |
| 352 | - * @return the number of times a requests was retried due to the | |
| 370 | + * @return the number of times a request was retried due to the | |
| 353 | 371 | * {@link com.datastax.driver.core.policies.RetryPolicy}. |
| 354 | 372 | */ |
| 355 | 373 | public Counter getRetries() { |
| @@ -361,7 +379,7 @@ | ||
| 361 | 379 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 362 | 380 | * read timed out. |
| 363 | 381 | * |
| 364 | - * @return the number of times a requests was retried due to the | |
| 382 | + * @return the number of times a request was retried due to the | |
| 365 | 383 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 366 | 384 | * read timed out. |
| 367 | 385 | */ |
| @@ -374,7 +392,7 @@ | ||
| 374 | 392 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 375 | 393 | * write timed out. |
| 376 | 394 | * |
| 377 | - * @return the number of times a requests was retried due to the | |
| 395 | + * @return the number of times a request was retried due to the | |
| 378 | 396 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 379 | 397 | * write timed out. |
| 380 | 398 | */ |
| @@ -387,7 +405,7 @@ | ||
| 387 | 405 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after an |
| 388 | 406 | * unavailable exception. |
| 389 | 407 | * |
| 390 | - * @return the number of times a requests was retried due to the | |
| 408 | + * @return the number of times a request was retried due to the | |
| 391 | 409 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after an |
| 392 | 410 | * unavailable exception. |
| 393 | 411 | */ |
| @@ -395,6 +413,45 @@ | ||
| 395 | 413 | return retriesOnUnavailable; |
| 396 | 414 | } |
| 397 | 415 | |
| 416 | + /** | |
| 417 | + * Returns the number of times a request was retried due to the | |
| 418 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 419 | + * client timeout. | |
| 420 | + * | |
| 421 | + * @return the number of times a request was retried due to the | |
| 422 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 423 | + * client timeout. | |
| 424 | + */ | |
| 425 | + public Counter getRetriesOnClientTimeout() { | |
| 426 | + return retriesOnClientTimeout; | |
| 427 | + } | |
| 428 | + | |
| 429 | + /** | |
| 430 | + * Returns the number of times a request was retried due to the | |
| 431 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 432 | + * connection error. | |
| 433 | + * | |
| 434 | + * @return the number of times a request was retried due to the | |
| 435 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 436 | + * connection error. | |
| 437 | + */ | |
| 438 | + public Counter getRetriesOnConnectionError() { | |
| 439 | + return retriesOnConnectionError; | |
| 440 | + } | |
| 441 | + | |
| 442 | + /** | |
| 443 | + * Returns the number of times a request was retried due to the | |
| 444 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after an | |
| 445 | + * unexpected error. | |
| 446 | + * | |
| 447 | + * @return the number of times a request was retried due to the | |
| 448 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after an | |
| 449 | + * unexpected error. | |
| 450 | + */ | |
| 451 | + public Counter getRetriesOnOtherErrors() { | |
| 452 | + return retriesOnOtherErrors; | |
| 453 | + } | |
| 454 | + | |
| 398 | 455 | /** |
| 399 | 456 | * Returns the number of times a request was ignored |
| 400 | 457 | * due to the {@link com.datastax.driver.core.policies.RetryPolicy}, for |
| @@ -412,7 +469,7 @@ | ||
| 412 | 469 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 413 | 470 | * read timed out. |
| 414 | 471 | * |
| 415 | - * @return the number of times a requests was ignored due to the | |
| 472 | + * @return the number of times a request was ignored due to the | |
| 416 | 473 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 417 | 474 | * read timed out. |
| 418 | 475 | */ |
| @@ -425,7 +482,7 @@ | ||
| 425 | 482 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 426 | 483 | * write timed out. |
| 427 | 484 | * |
| 428 | - * @return the number of times a requests was ignored due to the | |
| 485 | + * @return the number of times a request was ignored due to the | |
| 429 | 486 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after a |
| 430 | 487 | * write timed out. |
| 431 | 488 | */ |
| @@ -438,7 +495,7 @@ | ||
| 438 | 495 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after an |
| 439 | 496 | * unavailable exception. |
| 440 | 497 | * |
| 441 | - * @return the number of times a requests was ignored due to the | |
| 498 | + * @return the number of times a request was ignored due to the | |
| 442 | 499 | * {@link com.datastax.driver.core.policies.RetryPolicy}, after an |
| 443 | 500 | * unavailable exception. |
| 444 | 501 | */ |
| @@ -446,6 +503,45 @@ | ||
| 446 | 503 | return ignoresOnUnavailable; |
| 447 | 504 | } |
| 448 | 505 | |
| 506 | + /** | |
| 507 | + * Returns the number of times a request was ignored due to the | |
| 508 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 509 | + * client timeout. | |
| 510 | + * | |
| 511 | + * @return the number of times a request was ignored due to the | |
| 512 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 513 | + * client timeout. | |
| 514 | + */ | |
| 515 | + public Counter getIgnoresOnClientTimeout() { | |
| 516 | + return ignoresOnClientTimeout; | |
| 517 | + } | |
| 518 | + | |
| 519 | + /** | |
| 520 | + * Returns the number of times a request was ignored due to the | |
| 521 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 522 | + * connection error. | |
| 523 | + * | |
| 524 | + * @return the number of times a request was ignored due to the | |
| 525 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after a | |
| 526 | + * connection error. | |
| 527 | + */ | |
| 528 | + public Counter getIgnoresOnConnectionError() { | |
| 529 | + return ignoresOnConnectionError; | |
| 530 | + } | |
| 531 | + | |
| 532 | + /** | |
| 533 | + * Returns the number of times a request was ignored due to the | |
| 534 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after an | |
| 535 | + * unexpected error. | |
| 536 | + * | |
| 537 | + * @return the number of times a request was ignored due to the | |
| 538 | + * {@link com.datastax.driver.core.policies.RetryPolicy}, after an | |
| 539 | + * unexpected error. | |
| 540 | + */ | |
| 541 | + public Counter getIgnoresOnOtherErrors() { | |
| 542 | + return ignoresOnOtherErrors; | |
| 543 | + } | |
| 544 | + | |
| 449 | 545 | /** |
| 450 | 546 | * Returns the number of times a speculative execution was started |
| 451 | 547 | * because a previous execution did not complete within the delay |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +125 −76
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.codahale.metrics.Timer; |
| 19 | 19 | import com.datastax.driver.core.exceptions.*; |
| 20 | +import com.datastax.driver.core.policies.ExtendedRetryPolicy; | |
| 20 | 21 | import com.datastax.driver.core.policies.RetryPolicy; |
| 21 | 22 | import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type; |
| 22 | 23 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan; |
| @@ -27,11 +28,11 @@ | ||
| 27 | 28 | import org.slf4j.LoggerFactory; |
| 28 | 29 | |
| 29 | 30 | import java.net.InetSocketAddress; |
| 30 | -import java.util.*; | |
| 31 | -import java.util.concurrent.ConcurrentHashMap; | |
| 32 | -import java.util.concurrent.CopyOnWriteArrayList; | |
| 33 | -import java.util.concurrent.TimeUnit; | |
| 34 | -import java.util.concurrent.TimeoutException; | |
| 31 | +import java.util.Collections; | |
| 32 | +import java.util.Iterator; | |
| 33 | +import java.util.List; | |
| 34 | +import java.util.Set; | |
| 35 | +import java.util.concurrent.*; | |
| 35 | 36 | import java.util.concurrent.atomic.AtomicBoolean; |
| 36 | 37 | import java.util.concurrent.atomic.AtomicInteger; |
| 37 | 38 | import java.util.concurrent.atomic.AtomicReference; |
| @@ -57,8 +58,7 @@ | ||
| 57 | 58 | private final io.netty.util.Timer scheduler; |
| 58 | 59 | |
| 59 | 60 | private volatile List<Host> triedHosts; |
| 60 | - | |
| 61 | - private volatile Map<InetSocketAddress, Throwable> errors; | |
| 61 | + private volatile ConcurrentMap<InetSocketAddress, Throwable> errors; | |
| 62 | 62 | |
| 63 | 63 | private final Timer.Context timerContext; |
| 64 | 64 | private final long startTime; |
| @@ -149,13 +149,6 @@ | ||
| 149 | 149 | execution.cancel(); |
| 150 | 150 | } |
| 151 | 151 | |
| 152 | - private void logError(InetSocketAddress address, Throwable exception) { | |
| 153 | - logger.debug("Error querying {}, trying next host (error is: {})", address, exception.toString()); | |
| 154 | - if (errors == null) | |
| 155 | - errors = new ConcurrentHashMap<InetSocketAddress, Throwable>(); | |
| 156 | - errors.put(address, exception); | |
| 157 | - } | |
| 158 | - | |
| 159 | 152 | private void setFinalResult(SpeculativeExecution execution, Connection connection, Message.Response response) { |
| 160 | 153 | if (!isDone.compareAndSet(false, true)) { |
| 161 | 154 | if (logger.isTraceEnabled()) |
| @@ -224,6 +217,12 @@ | ||
| 224 | 217 | return manager.cluster.manager.metrics; |
| 225 | 218 | } |
| 226 | 219 | |
| 220 | + private RetryPolicy retryPolicy() { | |
| 221 | + return statement.getRetryPolicy() == null | |
| 222 | + ? manager.configuration().getPolicies().getRetryPolicy() | |
| 223 | + : statement.getRetryPolicy(); | |
| 224 | + } | |
| 225 | + | |
| 227 | 226 | interface Callback extends Connection.ResponseCallback { |
| 228 | 227 | void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency); |
| 229 | 228 | |
| @@ -250,7 +249,7 @@ | ||
| 250 | 249 | |
| 251 | 250 | // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from |
| 252 | 251 | // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an |
| 253 | - // OVERLOADED error). | |
| 252 | + // UNPREPARED response). | |
| 254 | 253 | // This is incremented by one writer at a time, so volatile is good enough. |
| 255 | 254 | private volatile int retriesByPolicy; |
| 256 | 255 | |
| @@ -341,6 +340,7 @@ | ||
| 341 | 340 | break; |
| 342 | 341 | } |
| 343 | 342 | |
| 343 | + // set this flag to true before writing the request | |
| 344 | 344 | connectionHandler = connection.write(responseCallback, false); |
| 345 | 345 | // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered |
| 346 | 346 | // *before* the call to connection.write had returned. |
| @@ -356,6 +356,30 @@ | ||
| 356 | 356 | connection.release(); |
| 357 | 357 | } |
| 358 | 358 | |
| 359 | + private void processRetryDecision(RetryPolicy.RetryDecision retryDecision, Connection connection, Exception exceptionToReport) { | |
| 360 | + switch (retryDecision.getType()) { | |
| 361 | + case RETRY: | |
| 362 | + retriesByPolicy++; | |
| 363 | + if (logger.isDebugEnabled()) | |
| 364 | + logger.debug("[{}] Doing retry {} for query {} at consistency {}", id, retriesByPolicy, statement, retryDecision.getRetryConsistencyLevel()); | |
| 365 | + if (metricsEnabled()) | |
| 366 | + metrics().getErrorMetrics().getRetries().inc(); | |
| 367 | + // log error for the current host if we are switching to another one | |
| 368 | + if (!retryDecision.isRetryCurrent()) | |
| 369 | + logError(connection.address, exceptionToReport); | |
| 370 | + retry(retryDecision.isRetryCurrent(), retryDecision.getRetryConsistencyLevel()); | |
| 371 | + break; | |
| 372 | + case RETHROW: | |
| 373 | + setFinalException(connection, exceptionToReport); | |
| 374 | + break; | |
| 375 | + case IGNORE: | |
| 376 | + if (metricsEnabled()) | |
| 377 | + metrics().getErrorMetrics().getIgnores().inc(); | |
| 378 | + setFinalResult(connection, new Responses.Result.Void()); | |
| 379 | + break; | |
| 380 | + } | |
| 381 | + } | |
| 382 | + | |
| 359 | 383 | private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { |
| 360 | 384 | final Host h = current; |
| 361 | 385 | this.retryConsistencyLevel = newConsistencyLevel; |
| @@ -379,6 +403,18 @@ | ||
| 379 | 403 | }); |
| 380 | 404 | } |
| 381 | 405 | |
| 406 | + private void logError(InetSocketAddress address, Throwable exception) { | |
| 407 | + logger.debug("[{}] Error querying {} : {}", id, address, exception.toString()); | |
| 408 | + if (errors == null) { | |
| 409 | + synchronized (RequestHandler.this) { | |
| 410 | + if (errors == null) { | |
| 411 | + errors = new ConcurrentHashMap<InetSocketAddress, Throwable>(); | |
| 412 | + } | |
| 413 | + } | |
| 414 | + } | |
| 415 | + errors.put(address, exception); | |
| 416 | + } | |
| 417 | + | |
| 382 | 418 | void cancel() { |
| 383 | 419 | // Atomically set a special QueryState, that will cause any further operation to abort. |
| 384 | 420 | // We want to remember whether a request was in progress when we did this, so there are two cancel states. |
| @@ -432,16 +468,11 @@ | ||
| 432 | 468 | Responses.Error err = (Responses.Error) response; |
| 433 | 469 | exceptionToReport = err.asException(connection.address); |
| 434 | 470 | RetryPolicy.RetryDecision retry = null; |
| 435 | - RetryPolicy retryPolicy = statement.getRetryPolicy() == null | |
| 436 | - ? manager.configuration().getPolicies().getRetryPolicy() | |
| 437 | - : statement.getRetryPolicy(); | |
| 471 | + RetryPolicy retryPolicy = retryPolicy(); | |
| 438 | 472 | switch (err.code) { |
| 439 | 473 | case READ_TIMEOUT: |
| 440 | 474 | connection.release(); |
| 441 | 475 | assert err.infos instanceof ReadTimeoutException; |
| 442 | - if (metricsEnabled()) | |
| 443 | - metrics().getErrorMetrics().getReadTimeouts().inc(); | |
| 444 | - | |
| 445 | 476 | ReadTimeoutException rte = (ReadTimeoutException) err.infos; |
| 446 | 477 | retry = retryPolicy.onReadTimeout(statement, |
| 447 | 478 | rte.getConsistencyLevel(), |
| @@ -449,8 +480,8 @@ | ||
| 449 | 480 | rte.getReceivedAcknowledgements(), |
| 450 | 481 | rte.wasDataRetrieved(), |
| 451 | 482 | retriesByPolicy); |
| 452 | - | |
| 453 | 483 | if (metricsEnabled()) { |
| 484 | + metrics().getErrorMetrics().getReadTimeouts().inc(); | |
| 454 | 485 | if (retry.getType() == Type.RETRY) |
| 455 | 486 | metrics().getErrorMetrics().getRetriesOnReadTimeout().inc(); |
| 456 | 487 | if (retry.getType() == Type.IGNORE) |
| @@ -460,9 +491,6 @@ | ||
| 460 | 491 | case WRITE_TIMEOUT: |
| 461 | 492 | connection.release(); |
| 462 | 493 | assert err.infos instanceof WriteTimeoutException; |
| 463 | - if (metricsEnabled()) | |
| 464 | - metrics().getErrorMetrics().getWriteTimeouts().inc(); | |
| 465 | - | |
| 466 | 494 | WriteTimeoutException wte = (WriteTimeoutException) err.infos; |
| 467 | 495 | retry = retryPolicy.onWriteTimeout(statement, |
| 468 | 496 | wte.getConsistencyLevel(), |
| @@ -470,8 +498,8 @@ | ||
| 470 | 498 | wte.getRequiredAcknowledgements(), |
| 471 | 499 | wte.getReceivedAcknowledgements(), |
| 472 | 500 | retriesByPolicy); |
| 473 | - | |
| 474 | 501 | if (metricsEnabled()) { |
| 502 | + metrics().getErrorMetrics().getWriteTimeouts().inc(); | |
| 475 | 503 | if (retry.getType() == Type.RETRY) |
| 476 | 504 | metrics().getErrorMetrics().getRetriesOnWriteTimeout().inc(); |
| 477 | 505 | if (retry.getType() == Type.IGNORE) |
| @@ -481,17 +509,14 @@ | ||
| 481 | 509 | case UNAVAILABLE: |
| 482 | 510 | connection.release(); |
| 483 | 511 | assert err.infos instanceof UnavailableException; |
| 484 | - if (metricsEnabled()) | |
| 485 | - metrics().getErrorMetrics().getUnavailables().inc(); | |
| 486 | - | |
| 487 | 512 | UnavailableException ue = (UnavailableException) err.infos; |
| 488 | 513 | retry = retryPolicy.onUnavailable(statement, |
| 489 | 514 | ue.getConsistencyLevel(), |
| 490 | 515 | ue.getRequiredReplicas(), |
| 491 | 516 | ue.getAliveReplicas(), |
| 492 | 517 | retriesByPolicy); |
| 493 | - | |
| 494 | 518 | if (metricsEnabled()) { |
| 519 | + metrics().getErrorMetrics().getUnavailables().inc(); | |
| 495 | 520 | if (retry.getType() == Type.RETRY) |
| 496 | 521 | metrics().getErrorMetrics().getRetriesOnUnavailable().inc(); |
| 497 | 522 | if (retry.getType() == Type.IGNORE) |
| @@ -500,33 +525,51 @@ | ||
| 500 | 525 | break; |
| 501 | 526 | case OVERLOADED: |
| 502 | 527 | connection.release(); |
| 503 | - // Try another node | |
| 504 | - logger.warn("Host {} is overloaded, trying next host.", connection.address); | |
| 505 | - DriverException overloaded = new DriverException("Host overloaded"); | |
| 506 | - logError(connection.address, overloaded); | |
| 507 | - if (metricsEnabled()) | |
| 528 | + logger.warn("Host {} is overloaded.", connection.address); | |
| 529 | + if (metricsEnabled()) { | |
| 508 | 530 | metrics().getErrorMetrics().getOthers().inc(); |
| 509 | - retry(false, null); | |
| 510 | - return; | |
| 531 | + } | |
| 532 | + if (retryPolicy instanceof ExtendedRetryPolicy) { | |
| 533 | + retry = ((ExtendedRetryPolicy) retryPolicy).onRequestError(statement, | |
| 534 | + request().consistency(), exceptionToReport, retriesByPolicy); | |
| 535 | + if (metricsEnabled()) { | |
| 536 | + if (retry.getType() == Type.RETRY) | |
| 537 | + metrics().getErrorMetrics().getRetriesOnOtherErrors().inc(); | |
| 538 | + if (retry.getType() == Type.IGNORE) | |
| 539 | + metrics().getErrorMetrics().getIgnoresOnOtherErrors().inc(); | |
| 540 | + } | |
| 541 | + } else { | |
| 542 | + retry = RetryPolicy.RetryDecision.tryNextHost(request().consistency()); | |
| 543 | + } | |
| 544 | + break; | |
| 511 | 545 | case SERVER_ERROR: |
| 512 | 546 | connection.release(); |
| 513 | - // Defunct connection and try another node | |
| 514 | - logger.warn("{} replied with server error ({}), trying next host.", connection.address, err.message); | |
| 515 | - DriverException exception = new DriverException("Host replied with server error: " + err.message); | |
| 516 | - logError(connection.address, exception); | |
| 517 | - connection.defunct(exception); | |
| 518 | - if (metricsEnabled()) | |
| 547 | + logger.warn("{} replied with server error ({}), defuncting connection.", connection.address, err.message); | |
| 548 | + // Defunct connection | |
| 549 | + connection.defunct(exceptionToReport); | |
| 550 | + if (metricsEnabled()) { | |
| 519 | 551 | metrics().getErrorMetrics().getOthers().inc(); |
| 520 | - retry(false, null); | |
| 521 | - return; | |
| 552 | + } | |
| 553 | + if (retryPolicy instanceof ExtendedRetryPolicy) { | |
| 554 | + retry = ((ExtendedRetryPolicy) retryPolicy).onRequestError(statement, | |
| 555 | + request().consistency(), exceptionToReport, retriesByPolicy); | |
| 556 | + if (metricsEnabled()) { | |
| 557 | + if (retry.getType() == Type.RETRY) | |
| 558 | + metrics().getErrorMetrics().getRetriesOnOtherErrors().inc(); | |
| 559 | + if (retry.getType() == Type.IGNORE) | |
| 560 | + metrics().getErrorMetrics().getIgnoresOnOtherErrors().inc(); | |
| 561 | + } | |
| 562 | + } else { | |
| 563 | + retry = RetryPolicy.RetryDecision.tryNextHost(request().consistency()); | |
| 564 | + } | |
| 565 | + break; | |
| 522 | 566 | case IS_BOOTSTRAPPING: |
| 523 | 567 | connection.release(); |
| 524 | - // Try another node | |
| 525 | 568 | logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address); |
| 526 | - DriverException bootstrapping = new DriverException("Host is bootstrapping"); | |
| 527 | - logError(connection.address, bootstrapping); | |
| 528 | - if (metricsEnabled()) | |
| 569 | + if (metricsEnabled()) { | |
| 529 | 570 | metrics().getErrorMetrics().getOthers().inc(); |
| 571 | + } | |
| 572 | + logError(connection.address, exceptionToReport); | |
| 530 | 573 | retry(false, null); |
| 531 | 574 | return; |
| 532 | 575 | case UNPREPARED: |
| @@ -572,26 +615,7 @@ | ||
| 572 | 615 | if (retry == null) |
| 573 | 616 | setFinalResult(connection, response); |
| 574 | 617 | else { |
| 575 | - switch (retry.getType()) { | |
| 576 | - case RETRY: | |
| 577 | - ++retriesByPolicy; | |
| 578 | - if (logger.isDebugEnabled()) | |
| 579 | - logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel()); | |
| 580 | - if (metricsEnabled()) | |
| 581 | - metrics().getErrorMetrics().getRetries().inc(); | |
| 582 | - if (!retry.isRetryCurrent()) | |
| 583 | - logError(connection.address, exceptionToReport); | |
| 584 | - retry(retry.isRetryCurrent(), retry.getRetryConsistencyLevel()); | |
| 585 | - break; | |
| 586 | - case RETHROW: | |
| 587 | - setFinalResult(connection, response); | |
| 588 | - break; | |
| 589 | - case IGNORE: | |
| 590 | - if (metricsEnabled()) | |
| 591 | - metrics().getErrorMetrics().getIgnores().inc(); | |
| 592 | - setFinalResult(connection, new Responses.Result.Void()); | |
| 593 | - break; | |
| 594 | - } | |
| 618 | + processRetryDecision(retry, connection, exceptionToReport); | |
| 595 | 619 | } |
| 596 | 620 | break; |
| 597 | 621 | default: |
| @@ -609,6 +633,11 @@ | ||
| 609 | 633 | } |
| 610 | 634 | |
| 611 | 635 | private Connection.ResponseCallback prepareAndRetry(final String toPrepare) { |
| 636 | + // do not bother inspecting retry policy at this step, no other decision | |
| 637 | + // makes sense than retry on the same host if the query was prepared, | |
| 638 | + // or on another host, if an error/timeout occurred. | |
| 639 | + // The original request hasn't been executed so far, so there is no risk | |
| 640 | + // of re-executing non-idempotent statements. | |
| 612 | 641 | return new Connection.ResponseCallback() { |
| 613 | 642 | |
| 614 | 643 | @Override |
| @@ -633,7 +662,6 @@ | ||
| 633 | 662 | |
| 634 | 663 | connection.release(); |
| 635 | 664 | |
| 636 | - // TODO should we check the response ? | |
| 637 | 665 | switch (response.type) { |
| 638 | 666 | case RESULT: |
| 639 | 667 | if (((Responses.Result) response).kind == Responses.Result.Kind.PREPARED) { |
| @@ -694,11 +722,20 @@ | ||
| 694 | 722 | connection.release(); |
| 695 | 723 | |
| 696 | 724 | if (exception instanceof ConnectionException) { |
| 697 | - if (metricsEnabled()) | |
| 725 | + RetryPolicy retryPolicy = retryPolicy(); | |
| 726 | + RetryPolicy.RetryDecision decision; | |
| 727 | + if (retryPolicy instanceof ExtendedRetryPolicy) | |
| 728 | + decision = ((ExtendedRetryPolicy) retryPolicy).onRequestError(statement, request().consistency(), exception, retriesByPolicy); | |
| 729 | + else | |
| 730 | + decision = RetryPolicy.RetryDecision.tryNextHost(request().consistency()); | |
| 731 | + if (metricsEnabled()) { | |
| 698 | 732 | metrics().getErrorMetrics().getConnectionErrors().inc(); |
| 699 | - ConnectionException ce = (ConnectionException) exception; | |
| 700 | - logError(ce.address, ce); | |
| 701 | - retry(false, null); | |
| 733 | + if (decision.getType() == Type.RETRY) | |
| 734 | + metrics().getErrorMetrics().getRetriesOnConnectionError().inc(); | |
| 735 | + if (decision.getType() == Type.IGNORE) | |
| 736 | + metrics().getErrorMetrics().getIgnoresOnConnectionError().inc(); | |
| 737 | + } | |
| 738 | + processRetryDecision(decision, connection, exception); | |
| 702 | 739 | return; |
| 703 | 740 | } |
| 704 | 741 | setFinalException(connection, exception); |
| @@ -726,8 +763,20 @@ | ||
| 726 | 763 | try { |
| 727 | 764 | connection.release(); |
| 728 | 765 | |
| 729 | - logError(connection.address, timeoutException); | |
| 730 | - retry(false, null); | |
| 766 | + RetryPolicy retryPolicy = retryPolicy(); | |
| 767 | + RetryPolicy.RetryDecision decision; | |
| 768 | + if (retryPolicy instanceof ExtendedRetryPolicy) | |
| 769 | + decision = ((ExtendedRetryPolicy) retryPolicy).onRequestError(statement, request().consistency(), timeoutException, retriesByPolicy); | |
| 770 | + else | |
| 771 | + decision = RetryPolicy.RetryDecision.tryNextHost(request().consistency()); | |
| 772 | + if (metricsEnabled()) { | |
| 773 | + metrics().getErrorMetrics().getClientTimeouts().inc(); | |
| 774 | + if (decision.getType() == Type.RETRY) | |
| 775 | + metrics().getErrorMetrics().getRetriesOnClientTimeout().inc(); | |
| 776 | + if (decision.getType() == Type.IGNORE) | |
| 777 | + metrics().getErrorMetrics().getIgnoresOnClientTimeout().inc(); | |
| 778 | + } | |
| 779 | + processRetryDecision(decision, connection, timeoutException); | |
| 731 | 780 | } catch (Exception e) { |
| 732 | 781 | // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely |
| 733 | 782 | setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e)); |
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +3 −2
| @@ -87,8 +87,9 @@ | ||
| 87 | 87 | * answer a query. |
| 88 | 88 | * <p/> |
| 89 | 89 | * Please note that this is not the maximum time a call to {@link Session#execute} may block; |
| 90 | - * this is the maximum time that call will wait for one particular | |
| 91 | - * Cassandra host, but other hosts will be tried if one of them times out. In | |
| 90 | + * this is the maximum time that a call will wait for one particular | |
| 91 | + * Cassandra host, but other hosts could be tried if one of them times out, depending | |
| 92 | + * on the {@link com.datastax.driver.core.policies.RetryPolicy} in use. In | |
| 92 | 93 | * other words, a {@link Session#execute} call may theoretically wait up to |
| 93 | 94 | * {@code getReadTimeoutMillis() * <number_of_cassandra_hosts>} (though the |
| 94 | 95 | * total number of hosts tried for a given query also depends on the |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java +1 −5
| @@ -19,11 +19,7 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | |
| 21 | 21 | /** |
| 22 | - * Indicates that the contacted host was bootstrapping. | |
| 23 | - * This class is mainly intended for internal use; | |
| 24 | - * client applications are not expected to deal with this exception directly, | |
| 25 | - * because the driver would transparently retry the same query on another host; | |
| 26 | - * but such exceptions are likely to appear occasionally in the driver logs. | |
| 22 | + * Indicates that the contacted host was bootstrapping when it received a read query. | |
| 27 | 23 | */ |
| 28 | 24 | public class BootstrappingException extends DriverInternalError implements CoordinatorException { |
| 29 | 25 |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java +6 −6
| @@ -20,24 +20,24 @@ | ||
| 20 | 20 | |
| 21 | 21 | /** |
| 22 | 22 | * An interface for exceptions that are able to report the address of the coordinator host |
| 23 | - * that triggered the response error which caused the exception to be raised. | |
| 23 | + * that was contacted. | |
| 24 | 24 | */ |
| 25 | 25 | public interface CoordinatorException { |
| 26 | 26 | |
| 27 | 27 | /** |
| 28 | - * The coordinator host that caused this exception to be raised. | |
| 29 | - * <p/> | |
| 28 | + * The coordinator host that was contacted. | |
| 29 | + * <p> | |
| 30 | 30 | * This is a shortcut for {@link InetSocketAddress#getAddress() getAddress().getAddress()}. |
| 31 | 31 | * |
| 32 | - * @return The coordinator host that caused this exception to be raised; | |
| 32 | + * @return The coordinator host that was contacted; | |
| 33 | 33 | * may be {@code null} if the coordinator is not known. |
| 34 | 34 | */ |
| 35 | 35 | InetAddress getHost(); |
| 36 | 36 | |
| 37 | 37 | /** |
| 38 | - * The full address of the coordinator host that caused this exception to be raised. | |
| 38 | + * The full address of the coordinator host that was contacted. | |
| 39 | 39 | * |
| 40 | - * @return the full address of the coordinator host that caused this exception to be raised; | |
| 40 | + * @return the full address of the coordinator host that was contacted; | |
| 41 | 41 | * may be {@code null} if the coordinator is not known. |
| 42 | 42 | */ |
| 43 | 43 | InetSocketAddress getAddress(); |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java +1 −1
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | /** |
| 19 | 19 | * An unexpected error happened internally. |
| 20 | 20 | * <p/> |
| 21 | - * This should never be raise and indicates a bug (either in the driver or in | |
| 21 | + * This should never be raised and indicates a bug (either in the driver or in | |
| 22 | 22 | * Cassandra). |
| 23 | 23 | */ |
| 24 | 24 | public class DriverInternalError extends DriverException { |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +0 −4
| @@ -20,10 +20,6 @@ | ||
| 20 | 20 | |
| 21 | 21 | /** |
| 22 | 22 | * Indicates that the contacted host reported itself being overloaded. |
| 23 | - * This class is mainly intended for internal use; | |
| 24 | - * client applications are not expected to deal with this exception directly, | |
| 25 | - * because the driver would transparently retry the same query on another host; | |
| 26 | - * but such exceptions are likely to appear occasionally in the driver logs. | |
| 27 | 23 | */ |
| 28 | 24 | public class OverloadedException extends DriverInternalError implements CoordinatorException { |
| 29 | 25 |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ServerError.java +1 −0
| @@ -20,6 +20,7 @@ | ||
| 20 | 20 | |
| 21 | 21 | /** |
| 22 | 22 | * Indicates that the contacted host reported un expected error. |
| 23 | + * This should be considered as a bug in Cassandra and reported as such. | |
| 23 | 24 | */ |
| 24 | 25 | public class ServerError extends DriverInternalError implements CoordinatorException { |
| 25 | 26 |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +16 −1
| @@ -34,7 +34,7 @@ | ||
| 34 | 34 | * In some cases, it may be convenient to use a more aggressive retry policy |
| 35 | 35 | * like {@link DowngradingConsistencyRetryPolicy}. |
| 36 | 36 | */ |
| 37 | -public class DefaultRetryPolicy implements RetryPolicy { | |
| 37 | +public class DefaultRetryPolicy implements ExtendedRetryPolicy { | |
| 38 | 38 | |
| 39 | 39 | public static final DefaultRetryPolicy INSTANCE = new DefaultRetryPolicy(); |
| 40 | 40 | |
| @@ -136,4 +136,19 @@ | ||
| 136 | 136 | ? RetryDecision.tryNextHost(cl) |
| 137 | 137 | : RetryDecision.rethrow(); |
| 138 | 138 | } |
| 139 | + | |
| 140 | + /** | |
| 141 | + * {@inheritDoc} | |
| 142 | + * <p/> | |
| 143 | + * For historical reasons, this implementation triggers a retry on the next host in the query plan | |
| 144 | + * with the same consistency level, regardless of the statement's idempotence. | |
| 145 | + * Note that this breaks the general rule | |
| 146 | + * stated in {@link ExtendedRetryPolicy#onRequestError(Statement, ConsistencyLevel, Exception, int)}: | |
| 147 | + * "a retry should only be attempted if the request is known to be idempotent". | |
| 148 | + */ | |
| 149 | + @Override | |
| 150 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 151 | + return RetryDecision.tryNextHost(cl); | |
| 152 | + } | |
| 153 | + | |
| 139 | 154 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +15 −1
| @@ -66,7 +66,7 @@ | ||
| 66 | 66 | * to make sure the data is persisted, and that reading something is better |
| 67 | 67 | * than reading nothing, even if there is a risk of reading stale data. |
| 68 | 68 | */ |
| 69 | -public class DowngradingConsistencyRetryPolicy implements RetryPolicy { | |
| 69 | +public class DowngradingConsistencyRetryPolicy implements ExtendedRetryPolicy { | |
| 70 | 70 | |
| 71 | 71 | public static final DowngradingConsistencyRetryPolicy INSTANCE = new DowngradingConsistencyRetryPolicy(); |
| 72 | 72 | |
| @@ -195,4 +195,18 @@ | ||
| 195 | 195 | // Tries the biggest CL that is expected to work |
| 196 | 196 | return maxLikelyToWorkCL(aliveReplica); |
| 197 | 197 | } |
| 198 | + | |
| 199 | + /** | |
| 200 | + * {@inheritDoc} | |
| 201 | + * <p/> | |
| 202 | + * For historical reasons, this implementation triggers a retry on the next host in the query plan | |
| 203 | + * with the same consistency level, regardless of the statement's idempotence. | |
| 204 | + * Note that this breaks the general rule | |
| 205 | + * stated in {@link ExtendedRetryPolicy#onRequestError(Statement, ConsistencyLevel, Exception, int)}: | |
| 206 | + * "a retry should only be attempted if the request is known to be idempotent".` | |
| 207 | + */ | |
| 208 | + @Override | |
| 209 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 210 | + return RetryDecision.tryNextHost(cl); | |
| 211 | + } | |
| 198 | 212 | } |
added driver-core/src/main/java/com/datastax/driver/core/policies/ExtendedRetryPolicy.java +60 −0
| @@ -0,0 +1,60 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | +import com.datastax.driver.core.SocketOptions; | |
| 20 | +import com.datastax.driver.core.Statement; | |
| 21 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * A policy that defines a default behavior to adopt in the event of unexpected errors. | |
| 25 | + * <p> | |
| 26 | + * This interface exists only for backward compatibility reasons: its methods should really be | |
| 27 | + * defined by {@link RetryPolicy}, but adding it after the fact would break binary compatibility. | |
| 28 | + * It should be merged into {@link RetryPolicy} in the next major release. | |
| 29 | + * <p> | |
| 30 | + * All retry policies shipped with the driver implement this interface. | |
| 31 | + */ | |
| 32 | +public interface ExtendedRetryPolicy extends RetryPolicy { | |
| 33 | + | |
| 34 | + /** | |
| 35 | + * Defines whether to retry and at which consistency level on an | |
| 36 | + * unexpected error. | |
| 37 | + * <p/> | |
| 38 | + * This method might be invoked in the following situations: | |
| 39 | + * <ol> | |
| 40 | + * <li>On a client timeout, while waiting for the server response | |
| 41 | + * (see {@link SocketOptions#getReadTimeoutMillis()});</li> | |
| 42 | + * <li>On a connection error (socket closed, etc.);</li> | |
| 43 | + * <li>When the contacted host replies with an error, such as | |
| 44 | + * {@code OVERLOADED}, {@code IS_BOOTSTRAPPING}, {@code SERVER_ERROR}, etc.</li> | |
| 45 | + * </ol> | |
| 46 | + * <p/> | |
| 47 | + * Note that when this method is invoked, <em>the driver cannot guarantee that the mutation has | |
| 48 | + * been effectively applied server-side</em>; a retry should only be attempted if the request | |
| 49 | + * is known to be idempotent. | |
| 50 | + * | |
| 51 | + * @param statement the original query that failed. | |
| 52 | + * @param cl the original consistency level for the operation. | |
| 53 | + * @param e the exception that caused this request to fail. | |
| 54 | + * @param nbRetry the number of retries already performed for this operation. | |
| 55 | + * @return the retry decision. If {@code RetryDecision.RETHROW} is returned, | |
| 56 | + * the {@link DriverException} passed to this method will be thrown for the operation. | |
| 57 | + */ | |
| 58 | + RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry); | |
| 59 | + | |
| 60 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java +12 −1
| @@ -25,7 +25,7 @@ | ||
| 25 | 25 | * All of the methods of this retry policy unconditionally return {@link RetryPolicy.RetryDecision#rethrow}. |
| 26 | 26 | * If this policy is used, retry will have to be implemented in business code. |
| 27 | 27 | */ |
| 28 | -public class FallthroughRetryPolicy implements RetryPolicy { | |
| 28 | +public class FallthroughRetryPolicy implements ExtendedRetryPolicy { | |
| 29 | 29 | |
| 30 | 30 | public static final FallthroughRetryPolicy INSTANCE = new FallthroughRetryPolicy(); |
| 31 | 31 | |
| @@ -87,4 +87,15 @@ | ||
| 87 | 87 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { |
| 88 | 88 | return RetryDecision.rethrow(); |
| 89 | 89 | } |
| 90 | + | |
| 91 | + /** | |
| 92 | + * {@inheritDoc} | |
| 93 | + * <p/> | |
| 94 | + * This implementation always returns {@code RetryDecision.rethrow()}. | |
| 95 | + */ | |
| 96 | + @Override | |
| 97 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 98 | + return RetryDecision.rethrow(); | |
| 99 | + } | |
| 100 | + | |
| 90 | 101 | } |
added driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java +97 −0
| @@ -0,0 +1,97 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | +import com.datastax.driver.core.QueryOptions; | |
| 20 | +import com.datastax.driver.core.Statement; | |
| 21 | +import com.datastax.driver.core.WriteType; | |
| 22 | + | |
| 23 | +/** | |
| 24 | + * A retry policy that avoids retrying non-idempotent statements. | |
| 25 | + * <p/> | |
| 26 | + * In case of write timeouts or unexpected errors, this policy will always return {@link com.datastax.driver.core.policies.RetryPolicy.RetryDecision#rethrow()} | |
| 27 | + * if the statement is deemed non-idempotent (see {@link #isIdempotent(Statement)}). | |
| 28 | + * <p/> | |
| 29 | + * For all other cases, this policy delegates the decision to the child policy. | |
| 30 | + */ | |
| 31 | +public class IdempotenceAwareRetryPolicy implements ExtendedRetryPolicy { | |
| 32 | + | |
| 33 | + private final ExtendedRetryPolicy childPolicy; | |
| 34 | + | |
| 35 | + private final QueryOptions queryOptions; | |
| 36 | + | |
| 37 | + /** | |
| 38 | + * Creates a new instance. | |
| 39 | + * | |
| 40 | + * @param childPolicy the policy to wrap. | |
| 41 | + * @param queryOptions the cluster's {@link QueryOptions} object. | |
| 42 | + */ | |
| 43 | + public IdempotenceAwareRetryPolicy(ExtendedRetryPolicy childPolicy, QueryOptions queryOptions) { | |
| 44 | + this.childPolicy = childPolicy; | |
| 45 | + this.queryOptions = queryOptions; | |
| 46 | + } | |
| 47 | + | |
| 48 | + @Override | |
| 49 | + public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 50 | + return childPolicy.onReadTimeout(statement, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry); | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Override | |
| 54 | + public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 55 | + if(isIdempotent(statement)) | |
| 56 | + return childPolicy.onWriteTimeout(statement, cl, writeType, requiredAcks, receivedAcks, nbRetry); | |
| 57 | + else | |
| 58 | + return RetryDecision.rethrow(); | |
| 59 | + } | |
| 60 | + | |
| 61 | + @Override | |
| 62 | + public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 63 | + return childPolicy.onUnavailable(statement, cl, requiredReplica, aliveReplica, nbRetry); | |
| 64 | + } | |
| 65 | + | |
| 66 | + @Override | |
| 67 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 68 | + if(isIdempotent(statement)) | |
| 69 | + return childPolicy.onRequestError(statement, cl, e, nbRetry); | |
| 70 | + else | |
| 71 | + return RetryDecision.rethrow(); | |
| 72 | + } | |
| 73 | + | |
| 74 | + /** | |
| 75 | + * Determines whether the given statement is idempotent or not. | |
| 76 | + * <p/> | |
| 77 | + * The current implementation inspects the statement's | |
| 78 | + * {@link Statement#isIdempotent() idempotent flag}; | |
| 79 | + * if this flag is not set, then it inspects | |
| 80 | + * {@link QueryOptions#getDefaultIdempotence()}. | |
| 81 | + * <p/> | |
| 82 | + * Subclasses may override if they have better knowledge of | |
| 83 | + * the statement being executed. | |
| 84 | + * | |
| 85 | + * @param statement The statement to execute. | |
| 86 | + * @return {@code true} if the given statement is idempotent, | |
| 87 | + * {@code false} otherwise | |
| 88 | + */ | |
| 89 | + protected boolean isIdempotent(Statement statement) { | |
| 90 | + Boolean myValue = statement.isIdempotent(); | |
| 91 | + if (myValue != null) | |
| 92 | + return myValue; | |
| 93 | + else | |
| 94 | + return queryOptions.getDefaultIdempotence(); | |
| 95 | + } | |
| 96 | + | |
| 97 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +77 −13
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | 19 | import com.datastax.driver.core.Statement; |
| 20 | 20 | import com.datastax.driver.core.WriteType; |
| 21 | +import com.google.common.annotations.VisibleForTesting; | |
| 21 | 22 | import org.slf4j.Logger; |
| 22 | 23 | import org.slf4j.LoggerFactory; |
| 23 | 24 | |
| @@ -28,9 +29,42 @@ | ||
| 28 | 29 | * RETHROW decisions are just meant to propagate the cassandra exception). The |
| 29 | 30 | * logging is done at the INFO level. |
| 30 | 31 | */ |
| 31 | -public class LoggingRetryPolicy implements RetryPolicy { | |
| 32 | +public class LoggingRetryPolicy implements ExtendedRetryPolicy { | |
| 32 | 33 | |
| 33 | 34 | private static final Logger logger = LoggerFactory.getLogger(LoggingRetryPolicy.class); |
| 35 | + | |
| 36 | + @VisibleForTesting | |
| 37 | + static final String IGNORING_READ_TIMEOUT = | |
| 38 | + "Ignoring read timeout (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})"; | |
| 39 | + | |
| 40 | + @VisibleForTesting | |
| 41 | + static final String RETRYING_ON_READ_TIMEOUT = | |
| 42 | + "Retrying on read timeout on {} at consistency {} (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})"; | |
| 43 | + | |
| 44 | + @VisibleForTesting | |
| 45 | + static final String IGNORING_WRITE_TIMEOUT = | |
| 46 | + "Ignoring write timeout (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})"; | |
| 47 | + | |
| 48 | + @VisibleForTesting | |
| 49 | + static final String RETRYING_ON_WRITE_TIMEOUT = | |
| 50 | + "Retrying on write timeout on {} at consistency {} (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})"; | |
| 51 | + | |
| 52 | + @VisibleForTesting | |
| 53 | + static final String IGNORING_UNAVAILABLE = | |
| 54 | + "Ignoring unavailable exception (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})"; | |
| 55 | + | |
| 56 | + @VisibleForTesting | |
| 57 | + static final String RETRYING_ON_UNAVAILABLE = | |
| 58 | + "Retrying on unavailable exception on {} at consistency {} (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})"; | |
| 59 | + | |
| 60 | + @VisibleForTesting | |
| 61 | + static final String IGNORING_REQUEST_ERROR = | |
| 62 | + "Ignoring request error (initial consistency: {}, retries: {}, exception: {})"; | |
| 63 | + | |
| 64 | + @VisibleForTesting | |
| 65 | + static final String RETRYING_ON_REQUEST_ERROR = | |
| 66 | + "Retrying on request error on {} at consistency {} (initial consistency: {}, retries: {}, exception: {})"; | |
| 67 | + | |
| 34 | 68 | private final RetryPolicy policy; |
| 35 | 69 | |
| 36 | 70 | /** |
| @@ -47,17 +81,19 @@ | ||
| 47 | 81 | return decision.getRetryConsistencyLevel() == null ? cl : decision.getRetryConsistencyLevel(); |
| 48 | 82 | } |
| 49 | 83 | |
| 84 | + private static String host(RetryDecision decision) { | |
| 85 | + return decision.isRetryCurrent() ? "same host" : "next host"; | |
| 86 | + } | |
| 87 | + | |
| 50 | 88 | @Override |
| 51 | 89 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { |
| 52 | 90 | RetryDecision decision = policy.onReadTimeout(statement, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry); |
| 53 | 91 | switch (decision.getType()) { |
| 54 | 92 | case IGNORE: |
| 55 | - String f1 = "Ignoring read timeout (initial consistency: %s, required responses: %d, received responses: %d, data retrieved: %b, retries: %d)"; | |
| 56 | - logger.info(String.format(f1, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry)); | |
| 93 | + logDecision(IGNORING_READ_TIMEOUT, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry); | |
| 57 | 94 | break; |
| 58 | 95 | case RETRY: |
| 59 | - String f2 = "Retrying on read timeout at consistency %s (initial consistency: %s, required responses: %d, received responses: %d, data retrieved: %b, retries: %d)"; | |
| 60 | - logger.info(String.format(f2, cl(cl, decision), cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry)); | |
| 96 | + logDecision(RETRYING_ON_READ_TIMEOUT, host(decision), cl(cl, decision), cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry); | |
| 61 | 97 | break; |
| 62 | 98 | } |
| 63 | 99 | return decision; |
| @@ -68,12 +104,10 @@ | ||
| 68 | 104 | RetryDecision decision = policy.onWriteTimeout(statement, cl, writeType, requiredAcks, receivedAcks, nbRetry); |
| 69 | 105 | switch (decision.getType()) { |
| 70 | 106 | case IGNORE: |
| 71 | - String f1 = "Ignoring write timeout (initial consistency: %s, write type: %s, required acknowledgments: %d, received acknowledgments: %d, retries: %d)"; | |
| 72 | - logger.info(String.format(f1, cl, writeType, requiredAcks, receivedAcks, nbRetry)); | |
| 107 | + logDecision(IGNORING_WRITE_TIMEOUT, cl, writeType, requiredAcks, receivedAcks, nbRetry); | |
| 73 | 108 | break; |
| 74 | 109 | case RETRY: |
| 75 | - String f2 = "Retrying on write timeout at consistency %s(initial consistency: %s, write type: %s, required acknowledgments: %d, received acknowledgments: %d, retries: %d)"; | |
| 76 | - logger.info(String.format(f2, cl(cl, decision), cl, writeType, requiredAcks, receivedAcks, nbRetry)); | |
| 110 | + logDecision(RETRYING_ON_WRITE_TIMEOUT, host(decision), cl(cl, decision), cl, writeType, requiredAcks, receivedAcks, nbRetry); | |
| 77 | 111 | break; |
| 78 | 112 | } |
| 79 | 113 | return decision; |
| @@ -84,14 +118,44 @@ | ||
| 84 | 118 | RetryDecision decision = policy.onUnavailable(statement, cl, requiredReplica, aliveReplica, nbRetry); |
| 85 | 119 | switch (decision.getType()) { |
| 86 | 120 | case IGNORE: |
| 87 | - String f1 = "Ignoring unavailable exception (initial consistency: %s, required replica: %d, alive replica: %d, retries: %d)"; | |
| 88 | - logger.info(String.format(f1, cl, requiredReplica, aliveReplica, nbRetry)); | |
| 121 | + logDecision(IGNORING_UNAVAILABLE, cl, requiredReplica, aliveReplica, nbRetry); | |
| 122 | + break; | |
| 123 | + case RETRY: | |
| 124 | + logDecision(RETRYING_ON_UNAVAILABLE, host(decision), cl(cl, decision), cl, requiredReplica, aliveReplica, nbRetry); | |
| 125 | + break; | |
| 126 | + } | |
| 127 | + return decision; | |
| 128 | + } | |
| 129 | + | |
| 130 | + @Override | |
| 131 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 132 | + RetryDecision decision; | |
| 133 | + if (policy instanceof ExtendedRetryPolicy) | |
| 134 | + decision = ((ExtendedRetryPolicy) policy).onRequestError(statement, cl, e, nbRetry); | |
| 135 | + else | |
| 136 | + // old behavior for policies that do not implement ExtendedRetryPolicy | |
| 137 | + decision = RetryDecision.tryNextHost(cl); | |
| 138 | + switch (decision.getType()) { | |
| 139 | + case IGNORE: | |
| 140 | + logDecision(IGNORING_REQUEST_ERROR, cl, nbRetry, e); | |
| 89 | 141 | break; |
| 90 | 142 | case RETRY: |
| 91 | - String f2 = "Retrying on unavailable exception at consistency %s (initial consistency: %s, required replica: %d, alive replica: %d, retries: %d)"; | |
| 92 | - logger.info(String.format(f2, cl(cl, decision), cl, requiredReplica, aliveReplica, nbRetry)); | |
| 143 | + logDecision(RETRYING_ON_REQUEST_ERROR, host(decision), cl(cl, decision), cl, nbRetry, e); | |
| 93 | 144 | break; |
| 94 | 145 | } |
| 95 | 146 | return decision; |
| 96 | 147 | } |
| 148 | + | |
| 149 | + /** | |
| 150 | + * Logs the decision according to the given template and parameters. | |
| 151 | + * The log level is INFO, but subclasses may override. | |
| 152 | + * | |
| 153 | + * @param template The template to use; arguments must be specified in SLF4J style, i.e. {@code "{}"}. | |
| 154 | + * @param parameters The template parameters. | |
| 155 | + */ | |
| 156 | + protected void logDecision(String template, Object... parameters) { | |
| 157 | + logger.info(template, parameters); | |
| 158 | + } | |
| 159 | + | |
| 160 | + | |
| 97 | 161 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +31 −24
| @@ -20,8 +20,7 @@ | ||
| 20 | 20 | import com.datastax.driver.core.WriteType; |
| 21 | 21 | |
| 22 | 22 | /** |
| 23 | - * A policy that defines a default behavior to adopt when a request returns | |
| 24 | - * a TimeoutException or an UnavailableException. | |
| 23 | + * A policy that defines a default behavior to adopt when a request fails. | |
| 25 | 24 | * <p/> |
| 26 | 25 | * Such policy allows to centralize the handling of query retries, allowing to |
| 27 | 26 | * minimize the need for exception catching/handling in business code. |
| @@ -32,9 +31,9 @@ | ||
| 32 | 31 | * A retry decision to adopt on a Cassandra exception (read/write timeout |
| 33 | 32 | * or unavailable exception). |
| 34 | 33 | * <p/> |
| 35 | - * There is three possible decision: | |
| 34 | + * There are three possible decisions: | |
| 36 | 35 | * <ul> |
| 37 | - * <li>RETHROW: no retry should be attempted and an exception should be thrown</li> | |
| 36 | + * <li>RETHROW: no retry should be attempted and an exception should be thrown.</li> | |
| 38 | 37 | * <li>RETRY: the operation will be retried. The consistency level of the |
| 39 | 38 | * retry should be specified.</li> |
| 40 | 39 | * <li>IGNORE: no retry should be attempted and the exception should be |
| @@ -44,14 +43,12 @@ | ||
| 44 | 43 | */ |
| 45 | 44 | class RetryDecision { |
| 46 | 45 | /** |
| 47 | - * The type of retry decisions. | |
| 46 | + * The types of retry decisions. | |
| 48 | 47 | */ |
| 49 | 48 | public enum Type { |
| 50 | 49 | RETRY, RETHROW, IGNORE |
| 51 | 50 | } |
| 52 | 51 | |
| 53 | - ; | |
| 54 | - | |
| 55 | 52 | private final Type type; |
| 56 | 53 | private final ConsistencyLevel retryCL; |
| 57 | 54 | private final boolean retryCurrent; |
| @@ -72,57 +69,67 @@ | ||
| 72 | 69 | } |
| 73 | 70 | |
| 74 | 71 | /** |
| 75 | - * The consistency level for a retry decision. | |
| 72 | + * The consistency level for this retry decision. | |
| 73 | + * This is only meaningful for {@code RETRY} decisions. | |
| 74 | + * The consistency level is always {@code null} for an | |
| 75 | + * {@code IGNORE} or a {@code RETHROW} decision; | |
| 76 | + * for a {@code RETRY} decision, the consistency level can be {@code null}, | |
| 77 | + * in which case the retry is done at the same consistency level | |
| 78 | + * as in the original attempt. | |
| 76 | 79 | * |
| 77 | - * @return the consistency level for a retry decision or {@code null} | |
| 78 | - * if this retry decision is an {@code IGNORE} or a {@code RETHROW}. | |
| 80 | + * @return the consistency level for a retry decision. | |
| 79 | 81 | */ |
| 80 | 82 | public ConsistencyLevel getRetryConsistencyLevel() { |
| 81 | 83 | return retryCL; |
| 82 | 84 | } |
| 83 | 85 | |
| 84 | 86 | /** |
| 85 | - * Whether the retry policy uses the same host for retry decision. | |
| 87 | + * Whether this decision is to retry the same host. | |
| 88 | + * This is only meaningful for {@code RETRY} decisions. | |
| 86 | 89 | * |
| 87 | - * @return the retry on next host boolean. Default is false. | |
| 90 | + * @return {@code true} if the decision is to retry the same host, | |
| 91 | + * {@code false} otherwise. Default is {@code false}. | |
| 88 | 92 | */ |
| 89 | 93 | public boolean isRetryCurrent() { |
| 90 | 94 | return retryCurrent; |
| 91 | 95 | } |
| 92 | 96 | |
| 93 | 97 | /** |
| 94 | - * Creates a RETHROW retry decision. | |
| 98 | + * Creates a {@link RetryDecision.Type#RETHROW} retry decision. | |
| 95 | 99 | * |
| 96 | - * @return a RETHROW retry decision. | |
| 100 | + * @return a {@link RetryDecision.Type#RETHROW} retry decision. | |
| 97 | 101 | */ |
| 98 | 102 | public static RetryDecision rethrow() { |
| 99 | 103 | return new RetryDecision(Type.RETHROW, null, true); |
| 100 | 104 | } |
| 101 | 105 | |
| 102 | 106 | /** |
| 103 | - * Creates a RETRY retry decision using the provided consistency level. | |
| 107 | + * Creates a {@link RetryDecision.Type#RETRY} retry decision using | |
| 108 | + * the same host and the provided consistency level. | |
| 104 | 109 | * |
| 105 | 110 | * @param consistency the consistency level to use for the retry. |
| 106 | - * @return a RETRY with consistency level {@code consistency} retry decision. | |
| 111 | + * @return a {@link RetryDecision.Type#RETRY} decision using | |
| 112 | + * the same host and the provided consistency level | |
| 107 | 113 | */ |
| 108 | 114 | public static RetryDecision retry(ConsistencyLevel consistency) { |
| 109 | 115 | return new RetryDecision(Type.RETRY, consistency, true); |
| 110 | 116 | } |
| 111 | 117 | |
| 112 | 118 | /** |
| 113 | - * Creates an IGNORE retry decision. | |
| 119 | + * Creates an {@link RetryDecision.Type#IGNORE} retry decision. | |
| 114 | 120 | * |
| 115 | - * @return an IGNORE retry decision. | |
| 121 | + * @return an {@link RetryDecision.Type#IGNORE} retry decision. | |
| 116 | 122 | */ |
| 117 | 123 | public static RetryDecision ignore() { |
| 118 | 124 | return new RetryDecision(Type.IGNORE, null, true); |
| 119 | 125 | } |
| 120 | 126 | |
| 121 | 127 | /** |
| 122 | - * Creates a RETRY retry decision and indicates to retry on another host | |
| 123 | - * using the provided consistency level. | |
| 128 | + * Creates a {@link RetryDecision.Type#RETRY} retry decision using the next host | |
| 129 | + * in the query plan, and using the provided consistency level. | |
| 124 | 130 | * |
| 125 | - * @return a RETRY retry decision. | |
| 131 | + * @return a {@link RetryDecision.Type#RETRY} retry decision using the next host | |
| 132 | + * in the query plan, and using the provided consistency level. | |
| 126 | 133 | */ |
| 127 | 134 | public static RetryDecision tryNextHost(ConsistencyLevel retryCL) { |
| 128 | 135 | return new RetryDecision(Type.RETRY, retryCL, false); |
| @@ -163,7 +170,7 @@ | ||
| 163 | 170 | * a {@link com.datastax.driver.core.exceptions.ReadTimeoutException} will |
| 164 | 171 | * be thrown for the operation. |
| 165 | 172 | */ |
| 166 | - public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry); | |
| 173 | + RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry); | |
| 167 | 174 | |
| 168 | 175 | /** |
| 169 | 176 | * Defines whether to retry and at which consistency level on a write timeout. |
| @@ -180,7 +187,7 @@ | ||
| 180 | 187 | * a {@link com.datastax.driver.core.exceptions.WriteTimeoutException} will |
| 181 | 188 | * be thrown for the operation. |
| 182 | 189 | */ |
| 183 | - public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry); | |
| 190 | + RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry); | |
| 184 | 191 | |
| 185 | 192 | /** |
| 186 | 193 | * Defines whether to retry and at which consistency level on an |
| @@ -198,5 +205,5 @@ | ||
| 198 | 205 | * an {@link com.datastax.driver.core.exceptions.UnavailableException} will |
| 199 | 206 | * be thrown for the operation. |
| 200 | 207 | */ |
| 201 | - public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry); | |
| 208 | + RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry); | |
| 202 | 209 | } |
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +8 −2
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.Metrics.Errors; |
| 19 | -import com.datastax.driver.core.policies.RetryPolicy; | |
| 19 | +import com.datastax.driver.core.policies.ExtendedRetryPolicy; | |
| 20 | 20 | import com.datastax.driver.core.policies.RetryPolicy.RetryDecision; |
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| @@ -27,7 +27,7 @@ | ||
| 27 | 27 | |
| 28 | 28 | @Override |
| 29 | 29 | public Cluster.Builder createClusterBuilder() { |
| 30 | - return Cluster.builder().withRetryPolicy(new RetryPolicy() { | |
| 30 | + return Cluster.builder().withRetryPolicy(new ExtendedRetryPolicy() { | |
| 31 | 31 | @Override |
| 32 | 32 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { |
| 33 | 33 | return retryDecision; |
| @@ -42,6 +42,12 @@ | ||
| 42 | 42 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { |
| 43 | 43 | return retryDecision; |
| 44 | 44 | } |
| 45 | + | |
| 46 | + @Override | |
| 47 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 48 | + return retryDecision; | |
| 49 | + } | |
| 50 | + | |
| 45 | 51 | }); |
| 46 | 52 | } |
| 47 | 53 |
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +2 −8
| @@ -134,7 +134,7 @@ | ||
| 134 | 134 | .contains(ip) |
| 135 | 135 | .contains(Integer.toString(scassandra.getBinaryPort())) |
| 136 | 136 | .contains(query) |
| 137 | - .contains(OperationTimedOutException.class.getName()); | |
| 137 | + .contains("Operation timed out"); | |
| 138 | 138 | } |
| 139 | 139 | |
| 140 | 140 | @DataProvider(name = "errors") |
| @@ -177,14 +177,8 @@ | ||
| 177 | 177 | } catch (Exception e) { |
| 178 | 178 | if (e instanceof NoHostAvailableException) { |
| 179 | 179 | assertThat(expectedException).isEqualTo(NoHostAvailableException.class); |
| 180 | - // ok | |
| 181 | 180 | Throwable error = ((NoHostAvailableException) e).getErrors().get(hostAddress); |
| 182 | - assertThat(error).isNotNull(); | |
| 183 | - if (loggedException.getSuperclass() == DriverInternalError.class) { | |
| 184 | - assertThat(error).isOfAnyClassIn(DriverException.class); | |
| 185 | - } else { | |
| 186 | - assertThat(error).isOfAnyClassIn(loggedException); | |
| 187 | - } | |
| 181 | + assertThat(error).isNotNull().isInstanceOf(loggedException); | |
| 188 | 182 | } else { |
| 189 | 183 | assertThat(e).isInstanceOf(expectedException); |
| 190 | 184 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +11 −2
| @@ -16,7 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy; |
| 19 | -import com.datastax.driver.core.policies.RetryPolicy; | |
| 19 | +import com.datastax.driver.core.policies.ExtendedRetryPolicy; | |
| 20 | 20 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy; |
| 21 | 21 | import com.google.common.collect.ImmutableList; |
| 22 | 22 | import com.google.common.collect.ImmutableMap; |
| @@ -52,6 +52,7 @@ | ||
| 52 | 52 | cluster = Cluster.builder() |
| 53 | 53 | .addContactPoints(scassandras.address(2).getAddress()) |
| 54 | 54 | .withPort(scassandras.getBinaryPort()) |
| 55 | + .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet | |
| 55 | 56 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 56 | 57 | .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1)) |
| 57 | 58 | .withQueryOptions(new QueryOptions().setDefaultIdempotence(true)) |
| @@ -203,6 +204,8 @@ | ||
| 203 | 204 | Cluster cluster = Cluster.builder() |
| 204 | 205 | .addContactPoints(scassandras.address(2).getAddress()) |
| 205 | 206 | .withPort(scassandras.getBinaryPort()) |
| 207 | + // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash | |
| 208 | + .withProtocolVersion(ProtocolVersion.V2) | |
| 206 | 209 | .withSpeculativeExecutionPolicy(mockPolicy) |
| 207 | 210 | .build(); |
| 208 | 211 | |
| @@ -222,7 +225,7 @@ | ||
| 222 | 225 | * Custom retry policy that retries at ONE on read timeout. |
| 223 | 226 | * This deals with the fact that Scassandra only allows read timeouts with 0 replicas. |
| 224 | 227 | */ |
| 225 | - static class CustomRetryPolicy implements RetryPolicy { | |
| 228 | + static class CustomRetryPolicy implements ExtendedRetryPolicy { | |
| 226 | 229 | @Override |
| 227 | 230 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { |
| 228 | 231 | if (nbRetry != 0) |
| @@ -239,6 +242,12 @@ | ||
| 239 | 242 | public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { |
| 240 | 243 | return RetryDecision.rethrow(); |
| 241 | 244 | } |
| 245 | + | |
| 246 | + @Override | |
| 247 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 248 | + return RetryDecision.tryNextHost(cl); | |
| 249 | + } | |
| 250 | + | |
| 242 | 251 | } |
| 243 | 252 | |
| 244 | 253 | private static List<Map<String, ?>> row(String key, String value) { |
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +7 −1
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | /** |
| 126 | 126 | * A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors. |
| 127 | 127 | */ |
| 128 | - static class CustomRetryPolicy implements RetryPolicy { | |
| 128 | + static class CustomRetryPolicy implements ExtendedRetryPolicy { | |
| 129 | 129 | final AtomicInteger customStatementsHandled = new AtomicInteger(); |
| 130 | 130 | |
| 131 | 131 | @Override |
| @@ -144,5 +144,11 @@ | ||
| 144 | 144 | public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { |
| 145 | 145 | return RetryDecision.rethrow(); |
| 146 | 146 | } |
| 147 | + | |
| 148 | + @Override | |
| 149 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 150 | + return RetryDecision.tryNextHost(cl); | |
| 151 | + } | |
| 152 | + | |
| 147 | 153 | } |
| 148 | 154 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +57 −6
| @@ -16,13 +16,19 @@ | ||
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | +import com.datastax.driver.core.exceptions.OverloadedException; | |
| 20 | +import com.datastax.driver.core.exceptions.ServerError; | |
| 19 | 21 | import com.google.common.collect.ImmutableList; |
| 20 | 22 | import com.google.common.collect.ImmutableMap; |
| 21 | 23 | import org.mockito.Mockito; |
| 22 | 24 | import org.scassandra.Scassandra; |
| 25 | +import org.scassandra.http.client.ClosedConnectionConfig.CloseType; | |
| 26 | +import org.scassandra.http.client.Config; | |
| 23 | 27 | import org.scassandra.http.client.PrimingRequest; |
| 28 | +import org.scassandra.http.client.PrimingRequest.PrimingRequestBuilder; | |
| 24 | 29 | import org.testng.annotations.AfterMethod; |
| 25 | 30 | import org.testng.annotations.BeforeMethod; |
| 31 | +import org.testng.annotations.DataProvider; | |
| 26 | 32 | |
| 27 | 33 | import java.util.List; |
| 28 | 34 | import java.util.Map; |
| @@ -31,6 +37,8 @@ | ||
| 31 | 37 | import static org.assertj.core.api.Assertions.assertThat; |
| 32 | 38 | import static org.mockito.Matchers.*; |
| 33 | 39 | import static org.mockito.Mockito.times; |
| 40 | +import static org.scassandra.http.client.PrimingRequest.Result.overloaded; | |
| 41 | +import static org.scassandra.http.client.PrimingRequest.Result.server_error; | |
| 34 | 42 | |
| 35 | 43 | /** |
| 36 | 44 | * Base class for retry policy integration tests. |
| @@ -49,9 +57,16 @@ | ||
| 49 | 57 | protected Host host1, host2, host3; |
| 50 | 58 | protected Session session; |
| 51 | 59 | |
| 52 | - protected RetryPolicy retryPolicy; | |
| 60 | + protected ExtendedRetryPolicy retryPolicy; | |
| 53 | 61 | |
| 54 | - protected AbstractRetryPolicyIntegrationTest(RetryPolicy retryPolicy) { | |
| 62 | + protected AbstractRetryPolicyIntegrationTest() { | |
| 63 | + } | |
| 64 | + | |
| 65 | + protected AbstractRetryPolicyIntegrationTest(ExtendedRetryPolicy retryPolicy) { | |
| 66 | + setRetryPolicy(retryPolicy); | |
| 67 | + } | |
| 68 | + | |
| 69 | + protected final void setRetryPolicy(ExtendedRetryPolicy retryPolicy) { | |
| 55 | 70 | this.retryPolicy = Mockito.spy(retryPolicy); |
| 56 | 71 | } |
| 57 | 72 | |
| @@ -65,6 +80,12 @@ | ||
| 65 | 80 | .withPort(scassandras.getBinaryPort()) |
| 66 | 81 | .withRetryPolicy(retryPolicy) |
| 67 | 82 | .withLoadBalancingPolicy(new SortingLoadBalancingPolicy()) |
| 83 | + // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash | |
| 84 | + .withProtocolVersion(ProtocolVersion.V2) | |
| 85 | + .withPoolingOptions(new PoolingOptions() | |
| 86 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) | |
| 87 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, 1) | |
| 88 | + .setHeartbeatIntervalSeconds(0)) | |
| 68 | 89 | .withNettyOptions(nonQuietClusterCloseOptions) |
| 69 | 90 | .build(); |
| 70 | 91 | |
| @@ -84,10 +105,18 @@ | ||
| 84 | 105 | } |
| 85 | 106 | |
| 86 | 107 | protected void simulateError(int hostNumber, PrimingRequest.Result result) { |
| 87 | - scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder() | |
| 108 | + simulateError(hostNumber, result, null); | |
| 109 | + } | |
| 110 | + | |
| 111 | + protected void simulateError(int hostNumber, PrimingRequest.Result result, Config config) { | |
| 112 | + PrimingRequestBuilder builder = PrimingRequest.queryBuilder() | |
| 88 | 113 | .withQuery("mock query") |
| 89 | - .withResult(result) | |
| 90 | - .build()); | |
| 114 | + .withResult(result); | |
| 115 | + | |
| 116 | + if (config != null) | |
| 117 | + builder = builder.withConfig(config); | |
| 118 | + | |
| 119 | + scassandras.node(hostNumber).primingClient().prime(builder.build()); | |
| 91 | 120 | } |
| 92 | 121 | |
| 93 | 122 | protected void simulateNormalResponse(int hostNumber) { |
| @@ -97,7 +126,7 @@ | ||
| 97 | 126 | .build()); |
| 98 | 127 | } |
| 99 | 128 | |
| 100 | - private static List<Map<String, ?>> row(String key, String value) { | |
| 129 | + protected static List<Map<String, ?>> row(String key, String value) { | |
| 101 | 130 | return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value)); |
| 102 | 131 | } |
| 103 | 132 | |
| @@ -125,6 +154,11 @@ | ||
| 125 | 154 | any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt()); |
| 126 | 155 | } |
| 127 | 156 | |
| 157 | + protected void assertOnRequestErrorWasCalled(int times) { | |
| 158 | + Mockito.verify(retryPolicy, times(times)).onRequestError( | |
| 159 | + any(Statement.class), any(ConsistencyLevel.class), any(Exception.class), anyInt()); | |
| 160 | + } | |
| 161 | + | |
| 128 | 162 | protected void assertQueried(int hostNumber, int times) { |
| 129 | 163 | assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times); |
| 130 | 164 | } |
| @@ -136,4 +170,21 @@ | ||
| 136 | 170 | if (scassandras != null) |
| 137 | 171 | scassandras.stop(); |
| 138 | 172 | } |
| 173 | + | |
| 174 | + @DataProvider | |
| 175 | + public static Object[][] serverSideErrors() { | |
| 176 | + return new Object[][]{ | |
| 177 | + {server_error, ServerError.class}, | |
| 178 | + {overloaded, OverloadedException.class}, | |
| 179 | + }; | |
| 180 | + } | |
| 181 | + | |
| 182 | + @DataProvider | |
| 183 | + public static Object[][] connectionErrors() { | |
| 184 | + return new Object[][]{ | |
| 185 | + {CloseType.CLOSE}, | |
| 186 | + {CloseType.HALFCLOSE}, | |
| 187 | + {CloseType.RESET} | |
| 188 | + }; | |
| 189 | + } | |
| 139 | 190 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +91 −7
| @@ -15,17 +15,20 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | -import com.datastax.driver.core.ResultSet; | |
| 20 | -import com.datastax.driver.core.Statement; | |
| 21 | -import com.datastax.driver.core.WriteType; | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 20 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 22 | 21 | import com.datastax.driver.core.exceptions.UnavailableException; |
| 22 | +import org.scassandra.http.client.ClosedConnectionConfig; | |
| 23 | +import org.scassandra.http.client.ClosedConnectionConfig.CloseType; | |
| 24 | +import org.scassandra.http.client.PrimingRequest; | |
| 23 | 25 | import org.testng.annotations.Test; |
| 24 | 26 | |
| 25 | -import static org.assertj.core.api.Assertions.assertThat; | |
| 26 | -import static org.assertj.core.api.Assertions.fail; | |
| 27 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 28 | +import static org.assertj.core.api.Fail.fail; | |
| 27 | 29 | import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout; |
| 28 | 30 | import static org.scassandra.http.client.PrimingRequest.Result.unavailable; |
| 31 | +import static org.scassandra.http.client.PrimingRequest.then; | |
| 29 | 32 | |
| 30 | 33 | /** |
| 31 | 34 | * Integration test with a custom implementation, to test retry and ignore decisions. |
| @@ -43,6 +46,9 @@ | ||
| 43 | 46 | assertThat(rs.iterator().hasNext()).isFalse(); // ignore decisions produce empty result sets |
| 44 | 47 | |
| 45 | 48 | assertOnReadTimeoutWasCalled(1); |
| 49 | + assertThat(errors.getIgnores().getCount()).isEqualTo(1); | |
| 50 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 51 | + assertThat(errors.getIgnoresOnReadTimeout().getCount()).isEqualTo(1); | |
| 46 | 52 | assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0); |
| 47 | 53 | assertQueried(1, 1); |
| 48 | 54 | assertQueried(2, 0); |
| @@ -59,16 +65,89 @@ | ||
| 59 | 65 | } catch (UnavailableException e) {/*expected*/} |
| 60 | 66 | |
| 61 | 67 | assertOnUnavailableWasCalled(2); |
| 68 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 69 | + assertThat(errors.getUnavailables().getCount()).isEqualTo(2); | |
| 62 | 70 | assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); |
| 63 | 71 | assertQueried(1, 2); |
| 64 | 72 | assertQueried(2, 0); |
| 65 | 73 | assertQueried(3, 0); |
| 66 | 74 | } |
| 67 | 75 | |
| 76 | + @Test(groups = "short") | |
| 77 | + public void should_rethrow_on_client_timeouts() { | |
| 78 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1); | |
| 79 | + try { | |
| 80 | + scassandras | |
| 81 | + .node(1).primingClient().prime(PrimingRequest.queryBuilder() | |
| 82 | + .withQuery("mock query") | |
| 83 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1"))) | |
| 84 | + .build()); | |
| 85 | + try { | |
| 86 | + query(); | |
| 87 | + fail("expected a DriverInternalError"); | |
| 88 | + } catch (DriverInternalError e) { | |
| 89 | + assertThat(e.getCause().getMessage()).isEqualTo( | |
| 90 | + String.format("[%s] Operation timed out", host1.getSocketAddress()) | |
| 91 | + ); | |
| 92 | + } | |
| 93 | + assertOnRequestErrorWasCalled(1); | |
| 94 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 95 | + assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1); | |
| 96 | + assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(0); | |
| 97 | + assertQueried(1, 1); | |
| 98 | + assertQueried(2, 0); | |
| 99 | + assertQueried(3, 0); | |
| 100 | + } finally { | |
| 101 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 105 | + | |
| 106 | + @Test(groups = "short", dataProvider = "serverSideErrors") | |
| 107 | + public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 108 | + simulateError(1, error); | |
| 109 | + try { | |
| 110 | + query(); | |
| 111 | + fail("expected a DriverException"); | |
| 112 | + } catch (DriverException e) { | |
| 113 | + assertThat(e).isInstanceOf(exception); | |
| 114 | + } | |
| 115 | + assertOnRequestErrorWasCalled(1); | |
| 116 | + assertThat(errors.getOthers().getCount()).isEqualTo(1); | |
| 117 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 118 | + assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(0); | |
| 119 | + assertQueried(1, 1); | |
| 120 | + assertQueried(2, 0); | |
| 121 | + assertQueried(3, 0); | |
| 122 | + } | |
| 123 | + | |
| 124 | + | |
| 125 | + @Test(groups = "short", dataProvider = "connectionErrors") | |
| 126 | + public void should_rethrow_on_connection_error(CloseType closeType) { | |
| 127 | + simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 128 | + try { | |
| 129 | + query(); | |
| 130 | + fail("expected an error"); | |
| 131 | + } catch (DriverInternalError e) { | |
| 132 | + assertThat(e.getCause().getMessage()).isEqualTo( | |
| 133 | + String.format("[%s] Connection has been closed", host1.getSocketAddress()) | |
| 134 | + ); | |
| 135 | + } | |
| 136 | + assertOnRequestErrorWasCalled(1); | |
| 137 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 138 | + assertThat(errors.getConnectionErrors().getCount()).isEqualTo(1); | |
| 139 | + assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0); | |
| 140 | + assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(0); | |
| 141 | + assertQueried(1, 1); | |
| 142 | + assertQueried(2, 0); | |
| 143 | + assertQueried(3, 0); | |
| 144 | + } | |
| 145 | + | |
| 68 | 146 | /** |
| 69 | 147 | * Ignores read and write timeouts, and retries at most once on unavailable. |
| 148 | + * Rethrows for unexpected errors. | |
| 70 | 149 | */ |
| 71 | - static class CustomRetryPolicy implements RetryPolicy { | |
| 150 | + static class CustomRetryPolicy implements ExtendedRetryPolicy { | |
| 72 | 151 | |
| 73 | 152 | @Override |
| 74 | 153 | public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { |
| @@ -86,5 +165,10 @@ | ||
| 86 | 165 | ? RetryDecision.retry(cl) |
| 87 | 166 | : RetryDecision.rethrow(); |
| 88 | 167 | } |
| 168 | + | |
| 169 | + @Override | |
| 170 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 171 | + return RetryDecision.rethrow(); | |
| 172 | + } | |
| 89 | 173 | } |
| 90 | 174 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +117 −0
| @@ -18,18 +18,26 @@ | ||
| 18 | 18 | import com.datastax.driver.core.Cluster; |
| 19 | 19 | import com.datastax.driver.core.Metrics; |
| 20 | 20 | import com.datastax.driver.core.Session; |
| 21 | +import com.datastax.driver.core.SocketOptions; | |
| 21 | 22 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 22 | 23 | import com.datastax.driver.core.exceptions.ReadTimeoutException; |
| 23 | 24 | import com.datastax.driver.core.exceptions.UnavailableException; |
| 24 | 25 | import com.datastax.driver.core.exceptions.WriteTimeoutException; |
| 26 | +import com.google.common.base.Function; | |
| 27 | +import com.google.common.collect.Collections2; | |
| 28 | +import org.assertj.core.api.Fail; | |
| 25 | 29 | import org.scassandra.Scassandra; |
| 30 | +import org.scassandra.http.client.ClosedConnectionConfig; | |
| 31 | +import org.scassandra.http.client.PrimingRequest; | |
| 26 | 32 | import org.testng.annotations.Test; |
| 27 | 33 | |
| 34 | +import java.util.Collection; | |
| 28 | 35 | import java.util.Collections; |
| 29 | 36 | |
| 30 | 37 | import static org.assertj.core.api.Assertions.assertThat; |
| 31 | 38 | import static org.assertj.core.api.Assertions.fail; |
| 32 | 39 | import static org.scassandra.http.client.PrimingRequest.Result.*; |
| 40 | +import static org.scassandra.http.client.PrimingRequest.then; | |
| 33 | 41 | |
| 34 | 42 | public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { |
| 35 | 43 | public DefaultRetryPolicyIntegrationTest() { |
| @@ -46,6 +54,8 @@ | ||
| 46 | 54 | } catch (ReadTimeoutException e) {/*expected*/ } |
| 47 | 55 | |
| 48 | 56 | assertOnReadTimeoutWasCalled(1); |
| 57 | + assertThat(errors.getReadTimeouts().getCount()).isEqualTo(1); | |
| 58 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 49 | 59 | assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0); |
| 50 | 60 | assertQueried(1, 1); |
| 51 | 61 | assertQueried(2, 0); |
| @@ -62,6 +72,8 @@ | ||
| 62 | 72 | } catch (WriteTimeoutException e) {/*expected*/} |
| 63 | 73 | |
| 64 | 74 | assertOnWriteTimeoutWasCalled(1); |
| 75 | + assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1); | |
| 76 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 65 | 77 | assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0); |
| 66 | 78 | assertQueried(1, 1); |
| 67 | 79 | assertQueried(2, 0); |
| @@ -76,6 +88,8 @@ | ||
| 76 | 88 | query(); |
| 77 | 89 | |
| 78 | 90 | assertOnUnavailableWasCalled(1); |
| 91 | + assertThat(errors.getUnavailables().getCount()).isEqualTo(1); | |
| 92 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 79 | 93 | assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); |
| 80 | 94 | assertQueried(1, 1); |
| 81 | 95 | assertQueried(2, 1); |
| @@ -93,6 +107,8 @@ | ||
| 93 | 107 | } catch (UnavailableException e) {/*expected*/} |
| 94 | 108 | |
| 95 | 109 | assertOnUnavailableWasCalled(2); |
| 110 | + assertThat(errors.getUnavailables().getCount()).isEqualTo(2); | |
| 111 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 96 | 112 | assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); |
| 97 | 113 | assertQueried(1, 1); |
| 98 | 114 | assertQueried(2, 1); |
| @@ -142,4 +158,105 @@ | ||
| 142 | 158 | whiteListedCluster.close(); |
| 143 | 159 | } |
| 144 | 160 | } |
| 161 | + | |
| 162 | + @Test(groups = "short") | |
| 163 | + public void should_try_next_host_on_client_timeouts() { | |
| 164 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1); | |
| 165 | + try { | |
| 166 | + scassandras | |
| 167 | + .node(1).primingClient().prime(PrimingRequest.queryBuilder() | |
| 168 | + .withQuery("mock query") | |
| 169 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1"))) | |
| 170 | + .build()); | |
| 171 | + scassandras | |
| 172 | + .node(2).primingClient().prime(PrimingRequest.queryBuilder() | |
| 173 | + .withQuery("mock query") | |
| 174 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result2"))) | |
| 175 | + .build()); | |
| 176 | + scassandras | |
| 177 | + .node(3).primingClient().prime(PrimingRequest.queryBuilder() | |
| 178 | + .withQuery("mock query") | |
| 179 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result3"))) | |
| 180 | + .build()); | |
| 181 | + try { | |
| 182 | + query(); | |
| 183 | + fail("expected a NoHostAvailableException"); | |
| 184 | + } catch (NoHostAvailableException e) { | |
| 185 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 186 | + host1.getSocketAddress(), | |
| 187 | + host2.getSocketAddress(), | |
| 188 | + host3.getSocketAddress()); | |
| 189 | + Collection<String> messages = Collections2.transform(e.getErrors().values(), new Function<Throwable, String>() { | |
| 190 | + @Override | |
| 191 | + public String apply(Throwable input) { | |
| 192 | + return input.getMessage(); | |
| 193 | + } | |
| 194 | + }); | |
| 195 | + assertThat(messages).containsOnlyOnce( | |
| 196 | + String.format("[%s] Operation timed out", host1.getSocketAddress()), | |
| 197 | + String.format("[%s] Operation timed out", host2.getSocketAddress()), | |
| 198 | + String.format("[%s] Operation timed out", host3.getSocketAddress()) | |
| 199 | + ); | |
| 200 | + } | |
| 201 | + assertOnRequestErrorWasCalled(3); | |
| 202 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 203 | + assertThat(errors.getClientTimeouts().getCount()).isEqualTo(3); | |
| 204 | + assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(3); | |
| 205 | + assertQueried(1, 1); | |
| 206 | + assertQueried(2, 1); | |
| 207 | + assertQueried(3, 1); | |
| 208 | + } finally { | |
| 209 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); | |
| 210 | + } | |
| 211 | + } | |
| 212 | + | |
| 213 | + | |
| 214 | + @Test(groups = "short", dataProvider = "serverSideErrors") | |
| 215 | + public void should_try_next_host_on_server_side_error(PrimingRequest.Result error, Class<?> exception) { | |
| 216 | + simulateError(1, error); | |
| 217 | + simulateError(2, error); | |
| 218 | + simulateError(3, error); | |
| 219 | + try { | |
| 220 | + query(); | |
| 221 | + Fail.fail("expected a NoHostAvailableException"); | |
| 222 | + } catch (NoHostAvailableException e) { | |
| 223 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 224 | + host1.getSocketAddress(), | |
| 225 | + host2.getSocketAddress(), | |
| 226 | + host3.getSocketAddress()); | |
| 227 | + assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception); | |
| 228 | + } | |
| 229 | + assertOnRequestErrorWasCalled(3); | |
| 230 | + assertThat(errors.getOthers().getCount()).isEqualTo(3); | |
| 231 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 232 | + assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(3); | |
| 233 | + assertQueried(1, 1); | |
| 234 | + assertQueried(2, 1); | |
| 235 | + assertQueried(3, 1); | |
| 236 | + } | |
| 237 | + | |
| 238 | + | |
| 239 | + @Test(groups = "short", dataProvider = "connectionErrors") | |
| 240 | + public void should_try_next_host_on_connection_error(ClosedConnectionConfig.CloseType closeType) { | |
| 241 | + simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 242 | + simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 243 | + simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 244 | + try { | |
| 245 | + query(); | |
| 246 | + Fail.fail("expected a NoHostAvailableException"); | |
| 247 | + } catch (NoHostAvailableException e) { | |
| 248 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 249 | + host1.getSocketAddress(), | |
| 250 | + host2.getSocketAddress(), | |
| 251 | + host3.getSocketAddress()); | |
| 252 | + } | |
| 253 | + assertOnRequestErrorWasCalled(3); | |
| 254 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 255 | + assertThat(errors.getConnectionErrors().getCount()).isEqualTo(3); | |
| 256 | + assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0); | |
| 257 | + assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(3); | |
| 258 | + assertQueried(1, 1); | |
| 259 | + assertQueried(2, 1); | |
| 260 | + assertQueried(3, 1); | |
| 261 | + } | |
| 145 | 262 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +424 −91
| @@ -15,100 +15,433 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.*; | |
| 19 | -import com.google.common.base.Objects; | |
| 20 | -import org.mockito.Mockito; | |
| 21 | -import org.mockito.verification.VerificationMode; | |
| 18 | +import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | +import com.datastax.driver.core.SocketOptions; | |
| 20 | +import com.datastax.driver.core.WriteType; | |
| 21 | +import com.datastax.driver.core.exceptions.*; | |
| 22 | +import com.google.common.base.Function; | |
| 23 | +import com.google.common.collect.Collections2; | |
| 24 | +import org.assertj.core.api.Assertions; | |
| 25 | +import org.assertj.core.api.Fail; | |
| 26 | +import org.scassandra.http.client.*; | |
| 27 | +import org.testng.annotations.DataProvider; | |
| 22 | 28 | import org.testng.annotations.Test; |
| 23 | 29 | |
| 24 | -import static com.datastax.driver.core.ConsistencyLevel.*; | |
| 25 | -import static com.datastax.driver.core.TestUtils.ipOfNode; | |
| 30 | +import java.util.Collection; | |
| 31 | + | |
| 26 | 32 | import static org.assertj.core.api.Assertions.assertThat; |
| 27 | -import static org.mockito.Matchers.any; | |
| 28 | -import static org.mockito.Matchers.anyInt; | |
| 29 | -import static org.mockito.Mockito.never; | |
| 30 | -import static org.mockito.Mockito.times; | |
| 31 | - | |
| 32 | -/** | |
| 33 | - * Note: we can't extend {@link AbstractRetryPolicyIntegrationTest} here, because SCassandra doesn't allow custom values for | |
| 34 | - * receivedResponses in primed responses. | |
| 35 | - * If that becomes possible in the future, we could refactor this test. | |
| 36 | - */ | |
| 37 | -@CCMConfig( | |
| 38 | - dirtiesContext = true, | |
| 39 | - createCluster = false, | |
| 40 | - numberOfNodes = 3, | |
| 41 | - config = { | |
| 42 | - // tests fail often with write or read timeouts | |
| 43 | - "hinted_handoff_enabled:true", | |
| 44 | - "phi_convict_threshold:5", | |
| 45 | - "read_request_timeout_in_ms:100000", | |
| 46 | - "write_request_timeout_in_ms:100000" | |
| 33 | +import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 34 | +import static org.scassandra.http.client.PrimingRequest.then; | |
| 35 | +import static org.scassandra.http.client.WriteTypePrime.UNLOGGED_BATCH; | |
| 36 | +import static org.testng.Assert.fail; | |
| 37 | + | |
| 38 | +public class DowngradingConsistencyRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { | |
| 39 | + | |
| 40 | + public DowngradingConsistencyRetryPolicyIntegrationTest() { | |
| 41 | + super(DowngradingConsistencyRetryPolicy.INSTANCE); | |
| 42 | + } | |
| 43 | + | |
| 44 | + /** | |
| 45 | + * @return An array of pairs that match # of alive replicas with the expected downgraded CL used on read/write/unavailable. | |
| 46 | + */ | |
| 47 | + @DataProvider | |
| 48 | + public static Object[][] consistencyLevels() { | |
| 49 | + return new Object[][]{ | |
| 50 | + {4, ConsistencyLevel.THREE}, | |
| 51 | + {3, ConsistencyLevel.THREE}, | |
| 52 | + {2, ConsistencyLevel.TWO}, | |
| 53 | + {1, ConsistencyLevel.ONE} | |
| 54 | + }; | |
| 55 | + } | |
| 56 | + | |
| 57 | + | |
| 58 | + /** | |
| 59 | + * @return Write Types for which we expect a rethrow if used and there are no received acks. | |
| 60 | + */ | |
| 61 | + @DataProvider | |
| 62 | + public static Object[][] rethrowWriteTypes() { | |
| 63 | + return new Object[][]{ | |
| 64 | + {WriteTypePrime.SIMPLE}, | |
| 65 | + {WriteTypePrime.BATCH}, | |
| 66 | + {WriteTypePrime.COUNTER}, | |
| 67 | + {WriteTypePrime.CAS} | |
| 68 | + }; | |
| 69 | + } | |
| 70 | + | |
| 71 | + | |
| 72 | + /** | |
| 73 | + * @return Write Types for which we expect an ignore if used and there are received acks. | |
| 74 | + */ | |
| 75 | + @DataProvider | |
| 76 | + public static Object[][] ignoreWriteTypesWithReceivedAcks() { | |
| 77 | + return new Object[][]{ | |
| 78 | + {WriteTypePrime.SIMPLE}, | |
| 79 | + {WriteTypePrime.BATCH} | |
| 80 | + }; | |
| 81 | + } | |
| 82 | + | |
| 83 | + | |
| 84 | + /** | |
| 85 | + * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 86 | + * reattempted with a {@link ConsistencyLevel} that matches min(received acknowledgements, THREE) and is only | |
| 87 | + * retried once. | |
| 88 | + * | |
| 89 | + * @param received The number of received acknowledgements to use in read timeout. | |
| 90 | + * @param expectedDowngradedCL The consistency level that is expected to be used on the retry. | |
| 91 | + * @test_category retry_policy | |
| 92 | + */ | |
| 93 | + @Test(groups = "short", dataProvider = "consistencyLevels") | |
| 94 | + public void should_retry_once_on_same_host_with_reduced_consistency_level_on_read_timeout(int received, ConsistencyLevel expectedDowngradedCL) { | |
| 95 | + simulateError(1, read_request_timeout, new ReadTimeoutConfig(received, received + 1, true)); | |
| 96 | + | |
| 97 | + try { | |
| 98 | + query(); | |
| 99 | + fail("expected an ReadTimeoutException"); | |
| 100 | + } catch (ReadTimeoutException e) { | |
| 101 | + assertThat(e.getConsistencyLevel()).isEqualTo(expectedDowngradedCL); | |
| 102 | + } | |
| 103 | + | |
| 104 | + assertOnReadTimeoutWasCalled(2); | |
| 105 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 106 | + assertThat(errors.getReadTimeouts().getCount()).isEqualTo(2); | |
| 107 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(1); | |
| 108 | + assertQueried(1, 2); | |
| 109 | + assertQueried(2, 0); | |
| 110 | + assertQueried(3, 0); | |
| 111 | + } | |
| 112 | + | |
| 113 | + | |
| 114 | + /** | |
| 115 | + * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 116 | + * reattempted if data was not retrieved, but enough replicas were alive to handle the request. | |
| 117 | + * | |
| 118 | + * @test_category retry_policy | |
| 119 | + */ | |
| 120 | + @Test(groups = "short") | |
| 121 | + public void should_retry_once_if_not_data_was_retrieved_and_enough_replicas_alive() { | |
| 122 | + simulateError(1, read_request_timeout, new ReadTimeoutConfig(1, 1, false)); | |
| 123 | + | |
| 124 | + try { | |
| 125 | + query(); | |
| 126 | + fail("expected an ReadTimeoutException"); | |
| 127 | + } catch (ReadTimeoutException e) {/*expected*/} | |
| 128 | + | |
| 129 | + assertOnReadTimeoutWasCalled(2); | |
| 130 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 131 | + assertThat(errors.getReadTimeouts().getCount()).isEqualTo(2); | |
| 132 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(1); | |
| 133 | + assertQueried(1, 2); | |
| 134 | + assertQueried(2, 0); | |
| 135 | + assertQueried(3, 0); | |
| 136 | + } | |
| 137 | + | |
| 138 | + | |
| 139 | + /** | |
| 140 | + * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is not | |
| 141 | + * attempted if no replicas were alive. In a real scenario, this would not be expected as we'd anticipate an | |
| 142 | + * {@link UnavailableException} instead. | |
| 143 | + * | |
| 144 | + * @test_category retry_policy | |
| 145 | + */ | |
| 146 | + @Test(groups = "short") | |
| 147 | + public void should_rethrow_if_no_hosts_alive_on_read_timeout() { | |
| 148 | + simulateError(1, read_request_timeout); | |
| 149 | + | |
| 150 | + try { | |
| 151 | + query(); | |
| 152 | + fail("expected a ReadTimeoutException"); | |
| 153 | + } catch (ReadTimeoutException e) {/*expected*/ } | |
| 154 | + | |
| 155 | + assertOnReadTimeoutWasCalled(1); | |
| 156 | + assertThat(errors.getReadTimeouts().getCount()).isEqualTo(1); | |
| 157 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 158 | + assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0); | |
| 159 | + assertQueried(1, 1); | |
| 160 | + assertQueried(2, 0); | |
| 161 | + assertQueried(3, 0); | |
| 162 | + } | |
| 163 | + | |
| 164 | + | |
| 165 | + /** | |
| 166 | + * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that it rethrows | |
| 167 | + * the exception if the {@link WriteType} was any of {@link #rethrowWriteTypes}. | |
| 168 | + * | |
| 169 | + * @param writeType writeType communicated by {@link WriteTimeoutException}. | |
| 170 | + * @test_category retry_policy | |
| 171 | + */ | |
| 172 | + @Test(groups = "short", dataProvider = "rethrowWriteTypes") | |
| 173 | + public void should_rethrow_on_write_timeout_with_write_type(WriteTypePrime writeType) { | |
| 174 | + simulateError(1, write_request_timeout, new WriteTimeoutConfig(writeType, 0, 2)); | |
| 175 | + | |
| 176 | + try { | |
| 177 | + query(); | |
| 178 | + fail("expected a WriteTimeoutException"); | |
| 179 | + } catch (WriteTimeoutException e) {/*expected*/} | |
| 180 | + | |
| 181 | + assertOnWriteTimeoutWasCalled(1); | |
| 182 | + assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1); | |
| 183 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 184 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0); | |
| 185 | + assertQueried(1, 1); | |
| 186 | + assertQueried(2, 0); | |
| 187 | + assertQueried(3, 0); | |
| 188 | + } | |
| 189 | + | |
| 190 | + | |
| 191 | + /** | |
| 192 | + * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that it ignores | |
| 193 | + * the exception if the {@link WriteType} was any of {@link #ignoreWriteTypesWithReceivedAcks} and we received acks | |
| 194 | + * some at least one replica. | |
| 195 | + * | |
| 196 | + * @param writeType writeType communicated by {@link WriteTimeoutException}. | |
| 197 | + * @test_category retry_policy | |
| 198 | + */ | |
| 199 | + @Test(groups = "short", dataProvider = "ignoreWriteTypesWithReceivedAcks") | |
| 200 | + public void should_ignore_on_write_timeout_with_write_type_and_received_acks(WriteTypePrime writeType) { | |
| 201 | + simulateError(1, write_request_timeout, new WriteTimeoutConfig(writeType, 1, 2)); | |
| 202 | + | |
| 203 | + query(); | |
| 204 | + | |
| 205 | + assertOnWriteTimeoutWasCalled(1); | |
| 206 | + assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1); | |
| 207 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 208 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0); | |
| 209 | + assertThat(errors.getIgnoresOnWriteTimeout().getCount()).isEqualTo(1); | |
| 210 | + assertQueried(1, 1); | |
| 211 | + assertQueried(2, 0); | |
| 212 | + assertQueried(3, 0); | |
| 213 | + } | |
| 214 | + | |
| 215 | + | |
| 216 | + /** | |
| 217 | + * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 218 | + * attempted on the same host if the {@link WriteType} is {@link WriteType#BATCH_LOG}. | |
| 219 | + * | |
| 220 | + * @test_category retry_policy | |
| 221 | + */ | |
| 222 | + @Test(groups = "short") | |
| 223 | + public void should_retry_once_on_same_host_with_BATCH_LOG_write_type() { | |
| 224 | + simulateError(1, write_request_timeout, new WriteTimeoutConfig(WriteTypePrime.BATCH_LOG, 1, 2)); | |
| 225 | + | |
| 226 | + try { | |
| 227 | + query(); | |
| 228 | + fail("expected a WriteTimeoutException"); | |
| 229 | + } catch (WriteTimeoutException e) {/*expected*/} | |
| 230 | + | |
| 231 | + assertOnWriteTimeoutWasCalled(2); | |
| 232 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 233 | + assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(2); | |
| 234 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(1); | |
| 235 | + assertQueried(1, 2); | |
| 236 | + assertQueried(2, 0); | |
| 237 | + assertQueried(3, 0); | |
| 238 | + } | |
| 239 | + | |
| 240 | + | |
| 241 | + /** | |
| 242 | + * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 243 | + * attempted on the same host with a reduced consistency level that matches min(received acknowledgments, THREE) | |
| 244 | + * if the {@link WriteType} is {@link WriteType#UNLOGGED_BATCH} and is only retries once. | |
| 245 | + * | |
| 246 | + * @param alive The number of received acknowledgements to use in write timeout. | |
| 247 | + * @param expectedDowngradedCL The consistency level that is expected to be used on the retry. | |
| 248 | + * @test_category retry_policy | |
| 249 | + */ | |
| 250 | + @Test(groups = "short", dataProvider = "consistencyLevels") | |
| 251 | + public void should_retry_once_on_same_host_with_reduced_consistency_level_on_write_timeout(int alive, ConsistencyLevel expectedDowngradedCL) { | |
| 252 | + simulateError(1, write_request_timeout, new WriteTimeoutConfig(UNLOGGED_BATCH, alive, alive + 1)); | |
| 253 | + | |
| 254 | + try { | |
| 255 | + query(); | |
| 256 | + fail("expected a WriteTimeoutException"); | |
| 257 | + } catch (WriteTimeoutException e) { | |
| 258 | + assertThat(e.getConsistencyLevel()).isEqualTo(expectedDowngradedCL); | |
| 259 | + } | |
| 260 | + | |
| 261 | + assertOnWriteTimeoutWasCalled(2); | |
| 262 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 263 | + assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(2); | |
| 264 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(1); | |
| 265 | + assertQueried(1, 2); | |
| 266 | + assertQueried(2, 0); | |
| 267 | + assertQueried(3, 0); | |
| 268 | + } | |
| 269 | + | |
| 270 | + | |
| 271 | + /** | |
| 272 | + * Ensures that when handling an unavailable with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 273 | + * reattempted with a {@link ConsistencyLevel} that matches min(received acknowledgements, THREE) and is only | |
| 274 | + * retried once. | |
| 275 | + * | |
| 276 | + * @param alive The number of received acknowledgements to use in unavailable. | |
| 277 | + * @param expectedDowngradedCL The consistency level that is expected to be used on the retry. | |
| 278 | + * @test_category retry_policy | |
| 279 | + */ | |
| 280 | + @Test(groups = "short", dataProvider = "consistencyLevels") | |
| 281 | + public void should_retry_once_on_same_host_with_reduced_consistency_level_on_unavailable(int alive, ConsistencyLevel expectedDowngradedCL) { | |
| 282 | + simulateError(1, unavailable, new UnavailableConfig(alive + 1, alive)); | |
| 283 | + | |
| 284 | + try { | |
| 285 | + query(); | |
| 286 | + fail("expected an UnavailableException"); | |
| 287 | + } catch (UnavailableException e) { | |
| 288 | + assertThat(e.getConsistencyLevel()).isEqualTo(expectedDowngradedCL); | |
| 289 | + } | |
| 290 | + | |
| 291 | + assertOnUnavailableWasCalled(2); | |
| 292 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 293 | + assertThat(errors.getUnavailables().getCount()).isEqualTo(2); | |
| 294 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1); | |
| 295 | + assertQueried(1, 2); | |
| 296 | + assertQueried(2, 0); | |
| 297 | + assertQueried(3, 0); | |
| 298 | + } | |
| 299 | + | |
| 300 | + | |
| 301 | + /** | |
| 302 | + * Ensures that when handling an unavailable with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 303 | + * is not reattempted if no replicas are alive. | |
| 304 | + * | |
| 305 | + * @test_category retry_policy | |
| 306 | + */ | |
| 307 | + @Test(groups = "short") | |
| 308 | + public void should_rethrow_if_no_hosts_alive_on_unavailable() { | |
| 309 | + simulateError(1, unavailable, new UnavailableConfig(1, 0)); | |
| 310 | + | |
| 311 | + try { | |
| 312 | + query(); | |
| 313 | + fail("expected an UnavailableException"); | |
| 314 | + } catch (UnavailableException e) {/*expected*/} | |
| 315 | + | |
| 316 | + assertOnUnavailableWasCalled(1); | |
| 317 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 318 | + assertThat(errors.getUnavailables().getCount()).isEqualTo(1); | |
| 319 | + assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(0); | |
| 320 | + assertQueried(1, 1); | |
| 321 | + assertQueried(2, 0); | |
| 322 | + assertQueried(3, 0); | |
| 323 | + } | |
| 324 | + | |
| 325 | + /** | |
| 326 | + * Ensures that when handling a client timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is | |
| 327 | + * attempted on the next host until all hosts are tried at which point a {@link NoHostAvailableException} is | |
| 328 | + * returned. | |
| 329 | + * | |
| 330 | + * @test_category retry_policy | |
| 331 | + */ | |
| 332 | + @Test(groups = "short") | |
| 333 | + public void should_try_next_host_on_client_timeouts() { | |
| 334 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1); | |
| 335 | + try { | |
| 336 | + scassandras | |
| 337 | + .node(1).primingClient().prime(PrimingRequest.queryBuilder() | |
| 338 | + .withQuery("mock query") | |
| 339 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1"))) | |
| 340 | + .build()); | |
| 341 | + scassandras | |
| 342 | + .node(2).primingClient().prime(PrimingRequest.queryBuilder() | |
| 343 | + .withQuery("mock query") | |
| 344 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result2"))) | |
| 345 | + .build()); | |
| 346 | + scassandras | |
| 347 | + .node(3).primingClient().prime(PrimingRequest.queryBuilder() | |
| 348 | + .withQuery("mock query") | |
| 349 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result3"))) | |
| 350 | + .build()); | |
| 351 | + try { | |
| 352 | + query(); | |
| 353 | + Assertions.fail("expected a NoHostAvailableException"); | |
| 354 | + } catch (NoHostAvailableException e) { | |
| 355 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 356 | + host1.getSocketAddress(), | |
| 357 | + host2.getSocketAddress(), | |
| 358 | + host3.getSocketAddress()); | |
| 359 | + Collection<String> messages = Collections2.transform(e.getErrors().values(), new Function<Throwable, String>() { | |
| 360 | + @Override | |
| 361 | + public String apply(Throwable input) { | |
| 362 | + return input.getMessage(); | |
| 363 | + } | |
| 364 | + }); | |
| 365 | + assertThat(messages).containsOnlyOnce( | |
| 366 | + String.format("[%s] Operation timed out", host1.getSocketAddress()), | |
| 367 | + String.format("[%s] Operation timed out", host2.getSocketAddress()), | |
| 368 | + String.format("[%s] Operation timed out", host3.getSocketAddress()) | |
| 369 | + ); | |
| 370 | + } | |
| 371 | + assertOnRequestErrorWasCalled(3); | |
| 372 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 373 | + assertThat(errors.getClientTimeouts().getCount()).isEqualTo(3); | |
| 374 | + assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(3); | |
| 375 | + assertQueried(1, 1); | |
| 376 | + assertQueried(2, 1); | |
| 377 | + assertQueried(3, 1); | |
| 378 | + } finally { | |
| 379 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); | |
| 380 | + } | |
| 381 | + } | |
| 382 | + | |
| 383 | + | |
| 384 | + /** | |
| 385 | + * Ensures that when handling a server error defined in {@link #serverSideErrors} with | |
| 386 | + * {@link DowngradingConsistencyRetryPolicy} that a retry is attempted on the next host until all hosts are tried | |
| 387 | + * at which point a {@link NoHostAvailableException} is raised and it's errors include the expected exception. | |
| 388 | + * | |
| 389 | + * @param error Server side error to be produced. | |
| 390 | + * @param exception The exception we expect to be raised. | |
| 391 | + * @test_category retry_policy | |
| 392 | + */ | |
| 393 | + @Test(groups = "short", dataProvider = "serverSideErrors") | |
| 394 | + public void should_try_next_host_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 395 | + simulateError(1, error); | |
| 396 | + simulateError(2, error); | |
| 397 | + simulateError(3, error); | |
| 398 | + try { | |
| 399 | + query(); | |
| 400 | + Fail.fail("expected a NoHostAvailableException"); | |
| 401 | + } catch (NoHostAvailableException e) { | |
| 402 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 403 | + host1.getSocketAddress(), | |
| 404 | + host2.getSocketAddress(), | |
| 405 | + host3.getSocketAddress()); | |
| 406 | + assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception); | |
| 407 | + } | |
| 408 | + assertOnRequestErrorWasCalled(3); | |
| 409 | + assertThat(errors.getOthers().getCount()).isEqualTo(3); | |
| 410 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 411 | + assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(3); | |
| 412 | + assertQueried(1, 1); | |
| 413 | + assertQueried(2, 1); | |
| 414 | + assertQueried(3, 1); | |
| 415 | + } | |
| 416 | + | |
| 417 | + | |
| 418 | + /** | |
| 419 | + * Ensures that when handling a connection error caused by the connection closing during a request in a way | |
| 420 | + * described by {@link #connectionErrors} that the next host is tried. | |
| 421 | + * | |
| 422 | + * @param closeType The way the connection should be closed during the request. | |
| 423 | + */ | |
| 424 | + @Test(groups = "short", dataProvider = "connectionErrors") | |
| 425 | + public void should_try_next_host_on_connection_error(ClosedConnectionConfig.CloseType closeType) { | |
| 426 | + simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 427 | + simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 428 | + simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 429 | + try { | |
| 430 | + query(); | |
| 431 | + Fail.fail("expected a NoHostAvailableException"); | |
| 432 | + } catch (NoHostAvailableException e) { | |
| 433 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 434 | + host1.getSocketAddress(), | |
| 435 | + host2.getSocketAddress(), | |
| 436 | + host3.getSocketAddress()); | |
| 47 | 437 | } |
| 48 | -) | |
| 49 | -public class DowngradingConsistencyRetryPolicyIntegrationTest extends CCMTestsSupport { | |
| 50 | - | |
| 51 | - @Test(groups = "long") | |
| 52 | - public void should_downgrade_if_not_enough_replicas_for_requested_CL() { | |
| 53 | - Cluster cluster = register(Cluster.builder() | |
| 54 | - .addContactPoints(getContactPoints().get(0)) | |
| 55 | - .withPort(ccm().getBinaryPort()) | |
| 56 | - .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000)) | |
| 57 | - .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE)) | |
| 58 | - .build()); | |
| 59 | - Session session = cluster.connect(); | |
| 60 | - | |
| 61 | - String ks = TestUtils.generateIdentifier("ks_"); | |
| 62 | - session.execute(String.format("CREATE KEYSPACE %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}", ks)); | |
| 63 | - useKeyspace(session, ks); | |
| 64 | - session.execute("CREATE TABLE foo(k int primary key)"); | |
| 65 | - session.execute("INSERT INTO foo(k) VALUES (0)"); | |
| 66 | - | |
| 67 | - // All replicas up: should achieve all levels without downgrading | |
| 68 | - checkAchievedConsistency(ALL, ALL, session); | |
| 69 | - checkAchievedConsistency(QUORUM, QUORUM, session); | |
| 70 | - checkAchievedConsistency(ONE, ONE, session); | |
| 71 | - | |
| 72 | - stopAndWait(1, cluster); | |
| 73 | - // Two replicas remaining: should downgrade to 2 when CL > 2 | |
| 74 | - checkAchievedConsistency(ALL, TWO, session); | |
| 75 | - checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes | |
| 76 | - checkAchievedConsistency(TWO, TWO, session); | |
| 77 | - checkAchievedConsistency(ONE, ONE, session); | |
| 78 | - | |
| 79 | - stopAndWait(2, cluster); | |
| 80 | - // One replica remaining: should downgrade to 1 when CL > 1 | |
| 81 | - checkAchievedConsistency(ALL, ONE, session); | |
| 82 | - checkAchievedConsistency(QUORUM, ONE, session); | |
| 83 | - checkAchievedConsistency(TWO, ONE, session); | |
| 84 | - checkAchievedConsistency(ONE, ONE, session); | |
| 85 | - | |
| 86 | - } | |
| 87 | - | |
| 88 | - private void stopAndWait(int node, Cluster cluster) { | |
| 89 | - ccm().stop(node); | |
| 90 | - ccm().waitForDown(node);// this uses port ping | |
| 91 | - TestUtils.waitForDown(ipOfNode(node), cluster); // this uses UP/DOWN events | |
| 92 | - } | |
| 93 | - | |
| 94 | - private void checkAchievedConsistency(ConsistencyLevel requested, ConsistencyLevel expected, Session session) { | |
| 95 | - RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy(); | |
| 96 | - Mockito.reset(retryPolicy); | |
| 97 | - | |
| 98 | - Statement s = new SimpleStatement("SELECT * FROM foo WHERE k = 0") | |
| 99 | - .setConsistencyLevel(requested); | |
| 100 | - | |
| 101 | - ResultSet rs = session.execute(s); | |
| 102 | - | |
| 103 | - ConsistencyLevel achieved = rs.getExecutionInfo().getAchievedConsistencyLevel(); | |
| 104 | - // ExecutionInfo returns null when the requested level was met. | |
| 105 | - ConsistencyLevel actual = Objects.firstNonNull(achieved, requested); | |
| 106 | - | |
| 107 | - assertThat(actual).isEqualTo(expected); | |
| 108 | - | |
| 109 | - // If the level was downgraded the policy should have been invoked | |
| 110 | - VerificationMode expectedCallsToPolicy = (expected == requested) ? never() : times(1); | |
| 111 | - Mockito.verify(retryPolicy, expectedCallsToPolicy).onUnavailable( | |
| 112 | - any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt()); | |
| 438 | + assertOnRequestErrorWasCalled(3); | |
| 439 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 440 | + assertThat(errors.getConnectionErrors().getCount()).isEqualTo(3); | |
| 441 | + assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0); | |
| 442 | + assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(3); | |
| 443 | + assertQueried(1, 1); | |
| 444 | + assertQueried(2, 1); | |
| 445 | + assertQueried(3, 1); | |
| 113 | 446 | } |
| 114 | 447 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +76 −3
| @@ -15,14 +15,17 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.exceptions.ReadTimeoutException; | |
| 19 | -import com.datastax.driver.core.exceptions.UnavailableException; | |
| 20 | -import com.datastax.driver.core.exceptions.WriteTimeoutException; | |
| 18 | +import com.datastax.driver.core.SocketOptions; | |
| 19 | +import com.datastax.driver.core.exceptions.*; | |
| 20 | +import org.scassandra.http.client.ClosedConnectionConfig; | |
| 21 | +import org.scassandra.http.client.ClosedConnectionConfig.CloseType; | |
| 22 | +import org.scassandra.http.client.PrimingRequest; | |
| 21 | 23 | import org.testng.annotations.Test; |
| 22 | 24 | |
| 23 | 25 | import static org.assertj.core.api.Assertions.assertThat; |
| 24 | 26 | import static org.assertj.core.api.Assertions.fail; |
| 25 | 27 | import static org.scassandra.http.client.PrimingRequest.Result.*; |
| 28 | +import static org.scassandra.http.client.PrimingRequest.then; | |
| 26 | 29 | |
| 27 | 30 | public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { |
| 28 | 31 | public FallthroughRetryPolicyIntegrationTest() { |
| @@ -76,4 +79,74 @@ | ||
| 76 | 79 | assertQueried(2, 0); |
| 77 | 80 | assertQueried(3, 0); |
| 78 | 81 | } |
| 82 | + | |
| 83 | + @Test(groups = "short") | |
| 84 | + public void should_rethrow_on_client_timeouts() { | |
| 85 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1); | |
| 86 | + try { | |
| 87 | + scassandras | |
| 88 | + .node(1).primingClient().prime(PrimingRequest.queryBuilder() | |
| 89 | + .withQuery("mock query") | |
| 90 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1"))) | |
| 91 | + .build()); | |
| 92 | + try { | |
| 93 | + query(); | |
| 94 | + fail("expected a DriverInternalError"); | |
| 95 | + } catch (DriverInternalError e) { | |
| 96 | + assertThat(e.getCause().getMessage()).isEqualTo( | |
| 97 | + String.format("[%s] Operation timed out", host1.getSocketAddress()) | |
| 98 | + ); | |
| 99 | + } | |
| 100 | + assertOnRequestErrorWasCalled(1); | |
| 101 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 102 | + assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1); | |
| 103 | + assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(0); | |
| 104 | + assertQueried(1, 1); | |
| 105 | + assertQueried(2, 0); | |
| 106 | + assertQueried(3, 0); | |
| 107 | + } finally { | |
| 108 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); | |
| 109 | + } | |
| 110 | + } | |
| 111 | + | |
| 112 | + | |
| 113 | + @Test(groups = "short", dataProvider = "serverSideErrors") | |
| 114 | + public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 115 | + simulateError(1, error); | |
| 116 | + try { | |
| 117 | + query(); | |
| 118 | + fail("expected a DriverException"); | |
| 119 | + } catch (DriverException e) { | |
| 120 | + assertThat(e).isInstanceOf(exception); | |
| 121 | + } | |
| 122 | + assertOnRequestErrorWasCalled(1); | |
| 123 | + assertThat(errors.getOthers().getCount()).isEqualTo(1); | |
| 124 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 125 | + assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(0); | |
| 126 | + assertQueried(1, 1); | |
| 127 | + assertQueried(2, 0); | |
| 128 | + assertQueried(3, 0); | |
| 129 | + } | |
| 130 | + | |
| 131 | + | |
| 132 | + @Test(groups = "short", dataProvider = "connectionErrors") | |
| 133 | + public void should_rethrow_on_connection_error(CloseType closeType) { | |
| 134 | + simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 135 | + try { | |
| 136 | + query(); | |
| 137 | + fail("expected an error"); | |
| 138 | + } catch (DriverInternalError e) { | |
| 139 | + assertThat(e.getCause().getMessage()).isEqualTo( | |
| 140 | + String.format("[%s] Connection has been closed", host1.getSocketAddress()) | |
| 141 | + ); | |
| 142 | + } | |
| 143 | + assertOnRequestErrorWasCalled(1); | |
| 144 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 145 | + assertThat(errors.getConnectionErrors().getCount()).isEqualTo(1); | |
| 146 | + assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0); | |
| 147 | + assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(0); | |
| 148 | + assertQueried(1, 1); | |
| 149 | + assertQueried(2, 0); | |
| 150 | + assertQueried(3, 0); | |
| 151 | + } | |
| 79 | 152 | } |
added driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +242 −0
| @@ -0,0 +1,242 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.*; | |
| 19 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 20 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 21 | +import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 22 | +import com.datastax.driver.core.exceptions.WriteTimeoutException; | |
| 23 | +import org.assertj.core.api.Fail; | |
| 24 | +import org.scassandra.http.client.ClosedConnectionConfig; | |
| 25 | +import org.scassandra.http.client.PrimingRequest; | |
| 26 | +import org.testng.annotations.Test; | |
| 27 | + | |
| 28 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 29 | +import static org.assertj.core.api.Assertions.fail; | |
| 30 | +import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout; | |
| 31 | +import static org.scassandra.http.client.PrimingRequest.then; | |
| 32 | + | |
| 33 | +/** | |
| 34 | + * Integration test with an IdempotenceAwareRetryPolicy. | |
| 35 | + */ | |
| 36 | +public class IdempotenceAwareRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { | |
| 37 | + | |
| 38 | + public IdempotenceAwareRetryPolicyIntegrationTest() { | |
| 39 | + super(new IdempotenceAwareRetryPolicy(new CustomRetryPolicy(), new QueryOptions().setDefaultIdempotence(false))); | |
| 40 | + } | |
| 41 | + | |
| 42 | + @Test(groups = "short") | |
| 43 | + public void should_not_retry_on_write_timeout_if_statement_non_idempotent() { | |
| 44 | + simulateError(1, write_request_timeout); | |
| 45 | + try { | |
| 46 | + query(); | |
| 47 | + fail("expected an WriteTimeoutException"); | |
| 48 | + } catch (WriteTimeoutException e) {/* expected */} | |
| 49 | + assertOnWriteTimeoutWasCalled(1); | |
| 50 | + assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1); | |
| 51 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 52 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0); | |
| 53 | + assertQueried(1, 1); | |
| 54 | + assertQueried(2, 0); | |
| 55 | + assertQueried(3, 0); | |
| 56 | + } | |
| 57 | + | |
| 58 | + @Test(groups = "short") | |
| 59 | + public void should_retry_on_write_timeout_if_statement_idempotent() { | |
| 60 | + simulateError(1, write_request_timeout); | |
| 61 | + session.execute(new SimpleStatement("mock query").setIdempotent(true)); | |
| 62 | + assertOnWriteTimeoutWasCalled(1); | |
| 63 | + assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1); | |
| 64 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 65 | + assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(1); | |
| 66 | + assertQueried(1, 1); | |
| 67 | + assertQueried(2, 1); | |
| 68 | + assertQueried(3, 0); | |
| 69 | + } | |
| 70 | + | |
| 71 | + @Test(groups = "short") | |
| 72 | + public void should_not_retry_on_client_timeout_if_statement_non_idempotent() { | |
| 73 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1); | |
| 74 | + try { | |
| 75 | + scassandras | |
| 76 | + .node(1).primingClient().prime(PrimingRequest.queryBuilder() | |
| 77 | + .withQuery("mock query") | |
| 78 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1"))) | |
| 79 | + .build()); | |
| 80 | + try { | |
| 81 | + query(); | |
| 82 | + fail("expected a DriverInternalError"); | |
| 83 | + } catch (DriverInternalError e) { | |
| 84 | + assertThat(e.getCause().getMessage()).isEqualTo( | |
| 85 | + String.format("[%s] Operation timed out", host1.getSocketAddress()) | |
| 86 | + ); | |
| 87 | + } | |
| 88 | + assertOnRequestErrorWasCalled(1); | |
| 89 | + assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1); | |
| 90 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 91 | + assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(0); | |
| 92 | + assertQueried(1, 1); | |
| 93 | + assertQueried(2, 0); | |
| 94 | + assertQueried(3, 0); | |
| 95 | + } finally { | |
| 96 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); | |
| 97 | + } | |
| 98 | + } | |
| 99 | + | |
| 100 | + @Test(groups = "short") | |
| 101 | + public void should_retry_on_client_timeout_if_statement_idempotent() { | |
| 102 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1); | |
| 103 | + try { | |
| 104 | + scassandras | |
| 105 | + .node(1).primingClient().prime(PrimingRequest.queryBuilder() | |
| 106 | + .withQuery("mock query") | |
| 107 | + .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1"))) | |
| 108 | + .build()); | |
| 109 | + session.execute(new SimpleStatement("mock query").setIdempotent(true)); | |
| 110 | + assertOnRequestErrorWasCalled(1); | |
| 111 | + assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1); | |
| 112 | + assertThat(errors.getRetries().getCount()).isEqualTo(1); | |
| 113 | + assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(1); | |
| 114 | + assertQueried(1, 1); | |
| 115 | + assertQueried(2, 1); | |
| 116 | + assertQueried(3, 0); | |
| 117 | + } finally { | |
| 118 | + cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + | |
| 123 | + @Test(groups = "short", dataProvider = "serverSideErrors") | |
| 124 | + public void should_not_retry_on_server_error_if_statement_non_idempotent(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 125 | + simulateError(1, error); | |
| 126 | + try { | |
| 127 | + query(); | |
| 128 | + fail("expected " + exception); | |
| 129 | + } catch (DriverException e) { | |
| 130 | + assertThat(e).isInstanceOf(exception); | |
| 131 | + } | |
| 132 | + assertOnRequestErrorWasCalled(1); | |
| 133 | + assertThat(errors.getOthers().getCount()).isEqualTo(1); | |
| 134 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 135 | + assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(0); | |
| 136 | + assertQueried(1, 1); | |
| 137 | + assertQueried(2, 0); | |
| 138 | + assertQueried(3, 0); | |
| 139 | + } | |
| 140 | + | |
| 141 | + @SuppressWarnings("UnusedParameters") | |
| 142 | + @Test(groups = "short", dataProvider = "serverSideErrors") | |
| 143 | + public void should_retry_on_server_error_if_statement_idempotent(PrimingRequest.Result error, Class<? extends DriverException> exception) { | |
| 144 | + simulateError(1, error); | |
| 145 | + simulateError(2, error); | |
| 146 | + simulateError(3, error); | |
| 147 | + try { | |
| 148 | + session.execute(new SimpleStatement("mock query").setIdempotent(true)); | |
| 149 | + fail("expected a NoHostAvailableException"); | |
| 150 | + } catch (NoHostAvailableException e) { | |
| 151 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 152 | + host1.getSocketAddress(), | |
| 153 | + host2.getSocketAddress(), | |
| 154 | + host3.getSocketAddress()); | |
| 155 | + assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception); | |
| 156 | + } | |
| 157 | + assertOnRequestErrorWasCalled(3); | |
| 158 | + assertThat(errors.getOthers().getCount()).isEqualTo(3); | |
| 159 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 160 | + assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(3); | |
| 161 | + assertQueried(1, 1); | |
| 162 | + assertQueried(2, 1); | |
| 163 | + assertQueried(3, 1); | |
| 164 | + } | |
| 165 | + | |
| 166 | + | |
| 167 | + @Test(groups = "short", dataProvider = "connectionErrors") | |
| 168 | + public void should_not_retry_on_connection_error_if_statement_non_idempotent(ClosedConnectionConfig.CloseType closeType) { | |
| 169 | + simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 170 | + simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 171 | + simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 172 | + try { | |
| 173 | + query(); | |
| 174 | + Fail.fail("expected an error"); | |
| 175 | + } catch (DriverInternalError e) { | |
| 176 | + assertThat(e.getCause().getMessage()).isEqualTo( | |
| 177 | + String.format("[%s] Connection has been closed", host1.getSocketAddress()) | |
| 178 | + ); | |
| 179 | + } | |
| 180 | + assertOnRequestErrorWasCalled(1); | |
| 181 | + assertThat(errors.getRetries().getCount()).isEqualTo(0); | |
| 182 | + assertThat(errors.getConnectionErrors().getCount()).isEqualTo(1); | |
| 183 | + assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0); | |
| 184 | + assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(0); | |
| 185 | + assertQueried(1, 1); | |
| 186 | + assertQueried(2, 0); | |
| 187 | + assertQueried(3, 0); | |
| 188 | + } | |
| 189 | + | |
| 190 | + | |
| 191 | + @Test(groups = "short", dataProvider = "connectionErrors") | |
| 192 | + public void should_retry_on_connection_error_if_statement_idempotent(ClosedConnectionConfig.CloseType closeType) { | |
| 193 | + simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 194 | + simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 195 | + simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType)); | |
| 196 | + try { | |
| 197 | + session.execute(new SimpleStatement("mock query").setIdempotent(true)); | |
| 198 | + Fail.fail("expected a NoHostAvailableException"); | |
| 199 | + } catch (NoHostAvailableException e) { | |
| 200 | + assertThat(e.getErrors().keySet()).hasSize(3).containsOnly( | |
| 201 | + host1.getSocketAddress(), | |
| 202 | + host2.getSocketAddress(), | |
| 203 | + host3.getSocketAddress()); | |
| 204 | + } | |
| 205 | + assertOnRequestErrorWasCalled(3); | |
| 206 | + assertThat(errors.getRetries().getCount()).isEqualTo(3); | |
| 207 | + assertThat(errors.getConnectionErrors().getCount()).isEqualTo(3); | |
| 208 | + assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0); | |
| 209 | + assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(3); | |
| 210 | + assertQueried(1, 1); | |
| 211 | + assertQueried(2, 1); | |
| 212 | + assertQueried(3, 1); | |
| 213 | + } | |
| 214 | + | |
| 215 | + | |
| 216 | + /** | |
| 217 | + * Retries everything on the next host. | |
| 218 | + */ | |
| 219 | + static class CustomRetryPolicy implements ExtendedRetryPolicy { | |
| 220 | + | |
| 221 | + @Override | |
| 222 | + public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 223 | + return RetryDecision.tryNextHost(cl); | |
| 224 | + } | |
| 225 | + | |
| 226 | + @Override | |
| 227 | + public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 228 | + return RetryDecision.tryNextHost(cl); | |
| 229 | + } | |
| 230 | + | |
| 231 | + @Override | |
| 232 | + public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 233 | + return RetryDecision.tryNextHost(cl); | |
| 234 | + } | |
| 235 | + | |
| 236 | + @Override | |
| 237 | + public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 238 | + return RetryDecision.tryNextHost(cl); | |
| 239 | + } | |
| 240 | + | |
| 241 | + } | |
| 242 | +} |
added driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java +179 −0
| @@ -0,0 +1,179 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | +import com.datastax.driver.core.MemoryAppender; | |
| 20 | +import com.datastax.driver.core.Statement; | |
| 21 | +import com.datastax.driver.core.WriteType; | |
| 22 | +import com.datastax.driver.core.exceptions.ServerError; | |
| 23 | +import org.apache.log4j.Level; | |
| 24 | +import org.apache.log4j.Logger; | |
| 25 | +import org.slf4j.helpers.MessageFormatter; | |
| 26 | +import org.testng.annotations.AfterMethod; | |
| 27 | +import org.testng.annotations.BeforeClass; | |
| 28 | +import org.testng.annotations.BeforeMethod; | |
| 29 | +import org.testng.annotations.Test; | |
| 30 | + | |
| 31 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 32 | +import static com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE; | |
| 33 | +import static com.datastax.driver.core.WriteType.SIMPLE; | |
| 34 | +import static com.datastax.driver.core.policies.LoggingRetryPolicy.*; | |
| 35 | +import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.ignore; | |
| 36 | +import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.tryNextHost; | |
| 37 | +import static org.apache.log4j.Level.INFO; | |
| 38 | +import static org.scassandra.http.client.PrimingRequest.Result.*; | |
| 39 | + | |
| 40 | +/** | |
| 41 | + * Integration tests with LoggingRetryPolicy. | |
| 42 | + */ | |
| 43 | +public class LoggingRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest { | |
| 44 | + | |
| 45 | + private volatile RetryPolicy.RetryDecision retryDecision; | |
| 46 | + | |
| 47 | + private Logger logger = Logger.getLogger(LoggingRetryPolicy.class.getName()); | |
| 48 | + | |
| 49 | + private MemoryAppender appender; | |
| 50 | + | |
| 51 | + private Level originalLevel; | |
| 52 | + private ConsistencyLevel defaultCL; | |
| 53 | + | |
| 54 | + @BeforeClass(groups = {"short", "unit"}) | |
| 55 | + public void setUpRetryPolicy() { | |
| 56 | + setRetryPolicy(new LoggingRetryPolicy(new CustomRetryPolicy())); | |
| 57 | + } | |
| 58 | + | |
| 59 | + @BeforeMethod(groups = {"short", "unit"}) | |
| 60 | + public void storeDefaultCL() { | |
| 61 | + defaultCL = cluster.getConfiguration().getQueryOptions().getConsistencyLevel(); | |
| 62 | + } | |
| 63 | + | |
| 64 | + @BeforeMethod(groups = {"short", "unit"}) | |
| 65 | + public void startCapturingLogs() { | |
| 66 | + originalLevel = logger.getLevel(); | |
| 67 | + logger.setLevel(INFO); | |
| 68 | + logger.addAppender(appender = new MemoryAppender()); | |
| 69 | + } | |
| 70 | + | |
| 71 | + @AfterMethod(groups = {"short", "unit"}) | |
| 72 | + public void stopCapturingLogs() { | |
| 73 | + logger.setLevel(originalLevel); | |
| 74 | + logger.removeAppender(appender); | |
| 75 | + } | |
| 76 | + | |
| 77 | + @Test(groups = "short") | |
| 78 | + public void should_log_ignored_read_timeout() throws InterruptedException { | |
| 79 | + simulateError(1, read_request_timeout); | |
| 80 | + retryDecision = ignore(); | |
| 81 | + query(); | |
| 82 | + String line = appender.waitAndGet(5000); | |
| 83 | + assertThat(line.trim()).isEqualTo(expectedMessage(IGNORING_READ_TIMEOUT, defaultCL, 1, 0, false, 0)); | |
| 84 | + } | |
| 85 | + | |
| 86 | + @Test(groups = "short") | |
| 87 | + public void should_log_retried_read_timeout() throws InterruptedException { | |
| 88 | + simulateError(1, read_request_timeout); | |
| 89 | + retryDecision = tryNextHost(LOCAL_ONE); | |
| 90 | + query(); | |
| 91 | + String line = appender.waitAndGet(5000); | |
| 92 | + assertThat(line.trim()).isEqualTo(expectedMessage(RETRYING_ON_READ_TIMEOUT, "next host", LOCAL_ONE, defaultCL, 1, 0, false, 0)); | |
| 93 | + } | |
| 94 | + | |
| 95 | + @Test(groups = "short") | |
| 96 | + public void should_log_ignored_write_timeout() throws InterruptedException { | |
| 97 | + simulateError(1, write_request_timeout); | |
| 98 | + retryDecision = ignore(); | |
| 99 | + query(); | |
| 100 | + String line = appender.waitAndGet(5000); | |
| 101 | + assertThat(line.trim()).isEqualTo(expectedMessage(IGNORING_WRITE_TIMEOUT, defaultCL, SIMPLE, 1, 0, 0)); | |
| 102 | + } | |
| 103 | + | |
| 104 | + @Test(groups = "short") | |
| 105 | + public void should_log_retried_write_timeout() throws InterruptedException { | |
| 106 | + simulateError(1, write_request_timeout); | |
| 107 | + retryDecision = tryNextHost(LOCAL_ONE); | |
| 108 | + query(); | |
| 109 | + String line = appender.waitAndGet(5000); | |
| 110 | + assertThat(line.trim()).isEqualTo(expectedMessage(RETRYING_ON_WRITE_TIMEOUT, "next host", LOCAL_ONE, defaultCL, SIMPLE, 1, 0, 0)); | |
| 111 | + } | |
| 112 | + | |
| 113 | + @Test(groups = "short") | |
| 114 | + public void should_log_ignored_unavailabe() throws InterruptedException { | |
| 115 | + simulateError(1, unavailable); | |
| 116 | + retryDecision = ignore(); | |
| 117 | + query(); | |
| 118 | + String line = appender.waitAndGet(5000); | |
| 119 | + assertThat(line.trim()).isEqualTo(expectedMessage(IGNORING_UNAVAILABLE, defaultCL, 1, 0, 0)); | |
| 120 | + } | |
| 121 | + | |
| 122 | + @Test(groups = "short") | |
| 123 | + public void should_log_retried_unavailable() throws InterruptedException { | |
| 124 | + simulateError(1, unavailable); | |
| 125 | + retryDecision = tryNextHost(LOCAL_ONE); | |
| 126 | + query(); | |
| 127 | + String line = appender.waitAndGet(5000); | |
| 128 | + assertThat(line.trim()).isEqualTo(expectedMessage(RETRYING_ON_UNAVAILABLE, "next host", LOCAL_ONE, defaultCL, 1, 0, 0)); | |
| 129 | + } | |
| 130 | + | |
| 131 | + @Test(groups = "short") | |
| 132 | + public void should_log_ignored_request_error() throws InterruptedException { | |
| 133 | + simulateError(1, server_error); | |
| 134 | + retryDecision = ignore(); | |
| 135 | + query(); | |
| 136 | + String line = appender.waitAndGet(5000); | |
| 137 | + assertThat(line.trim()).isEqualTo(expectedMessage(IGNORING_REQUEST_ERROR, defaultCL, 0, new ServerError(host1.getSocketAddress(), "Server Error"))); | |
| 138 | + } | |
| 139 | + | |
| 140 | + @Test(groups = "short") | |
| 141 | + public void should_log_retried_request_error() throws InterruptedException { | |
| 142 | + simulateError(1, server_error); | |
| 143 | + retryDecision = tryNextHost(LOCAL_ONE); | |
| 144 | + query(); | |
| 145 | + String line = appender.waitAndGet(5000); | |
| 146 | + assertThat(line.trim()).isEqualTo(expectedMessage(RETRYING_ON_REQUEST_ERROR, "next host", LOCAL_ONE, defaultCL, 0, new ServerError(host1.getSocketAddress(), "Server Error"))); | |
| 147 | + } | |
| 148 | + | |
| 149 | + private String expectedMessage(String template, Object... args) { | |
| 150 | + return MessageFormatter.arrayFormat(template, args).getMessage(); | |
| 151 | + } | |
| 152 | + | |
| 153 | + /** | |
| 154 | + * Dynamically modifiable retry policy. | |
| 155 | + */ | |
| 156 | + class CustomRetryPolicy implements ExtendedRetryPolicy { | |
| 157 | + | |
| 158 | + @Override | |
| 159 | + public RetryPolicy.RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) { | |
| 160 | + return retryDecision; | |
| 161 | + } | |
| 162 | + | |
| 163 | + @Override | |
| 164 | + public RetryPolicy.RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) { | |
| 165 | + return retryDecision; | |
| 166 | + } | |
| 167 | + | |
| 168 | + @Override | |
| 169 | + public RetryPolicy.RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) { | |
| 170 | + return retryDecision; | |
| 171 | + } | |
| 172 | + | |
| 173 | + @Override | |
| 174 | + public RetryPolicy.RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) { | |
| 175 | + return retryDecision; | |
| 176 | + } | |
| 177 | + | |
| 178 | + } | |
| 179 | +} |
modified pom.xml +1 −1
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | <testng.version>6.8.8</testng.version> |
| 61 | 61 | <assertj.version>1.7.0</assertj.version> |
| 62 | 62 | <mockito.version>1.10.8</mockito.version> |
| 63 | - <scassandra.version>0.10.0</scassandra.version> | |
| 63 | + <scassandra.version>0.11.0</scassandra.version> | |
| 64 | 64 | <main.basedir>${project.basedir}</main.basedir> |
| 65 | 65 | </properties> |
| 66 | 66 |