Elffuss BraidHub

kikocis/java-driver public

Merge pull request #587 from datastax/java1050

JAVA-1050: Backport JAVA-819 to 2.1
Changesetb1d33724c50ee0572ea6e15d2f73992e94405a089722227d58e920b0cee05bb0
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-01 19:45 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2016-03-01 19:45 +01:00
Parents21416b606ef9, 197c1f67b775

Browse the files at this changeset

28 files changed

modified changelog/README.md +1 −0
@@ -23,6 +23,7 @@
2323 - [improvement] JAVA-1021: Improve error message when connect() is called with an invalid keyspace name.
2424 - [improvement] JAVA-879: Mapper.map() accepts mapper-generated and user queries.
2525 - [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.
2627
2728 Merged from 2.0 branch:
2829
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +103 −7
@@ -272,6 +272,7 @@
272272 private final Counter writeTimeouts = registry.counter("write-timeouts");
273273 private final Counter readTimeouts = registry.counter("read-timeouts");
274274 private final Counter unavailables = registry.counter("unavailables");
275+ private final Counter clientTimeouts = registry.counter("client-timeouts");
275276
276277 private final Counter otherErrors = registry.counter("other-errors");
277278
@@ -279,10 +280,17 @@
279280 private final Counter retriesOnWriteTimeout = registry.counter("retries-on-write-timeout");
280281 private final Counter retriesOnReadTimeout = registry.counter("retries-on-read-timeout");
281282 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+
282287 private final Counter ignores = registry.counter("ignores");
283288 private final Counter ignoresOnWriteTimeout = registry.counter("ignores-on-write-timeout");
284289 private final Counter ignoresOnReadTimeout = registry.counter("ignores-on-read-timeout");
285290 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");
286294
287295 private final Counter speculativeExecutions = registry.counter("speculative-executions");
288296
@@ -334,6 +342,16 @@
334342 return unavailables;
335343 }
336344
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+
337355 /**
338356 * Returns the number of requests that returned errors not accounted for by
339357 * another metric. This includes all types of invalid requests.
@@ -349,7 +367,7 @@
349367 * Returns the number of times a request was retried due to the
350368 * {@link com.datastax.driver.core.policies.RetryPolicy}.
351369 *
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
353371 * {@link com.datastax.driver.core.policies.RetryPolicy}.
354372 */
355373 public Counter getRetries() {
@@ -361,7 +379,7 @@
361379 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
362380 * read timed out.
363381 *
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
365383 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
366384 * read timed out.
367385 */
@@ -374,7 +392,7 @@
374392 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
375393 * write timed out.
376394 *
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
378396 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
379397 * write timed out.
380398 */
@@ -387,7 +405,7 @@
387405 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
388406 * unavailable exception.
389407 *
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
391409 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
392410 * unavailable exception.
393411 */
@@ -395,6 +413,45 @@
395413 return retriesOnUnavailable;
396414 }
397415
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+
398455 /**
399456 * Returns the number of times a request was ignored
400457 * due to the {@link com.datastax.driver.core.policies.RetryPolicy}, for
@@ -412,7 +469,7 @@
412469 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
413470 * read timed out.
414471 *
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
416473 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
417474 * read timed out.
418475 */
@@ -425,7 +482,7 @@
425482 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
426483 * write timed out.
427484 *
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
429486 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
430487 * write timed out.
431488 */
@@ -438,7 +495,7 @@
438495 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
439496 * unavailable exception.
440497 *
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
442499 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
443500 * unavailable exception.
444501 */
@@ -446,6 +503,45 @@
446503 return ignoresOnUnavailable;
447504 }
448505
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+
449545 /**
450546 * Returns the number of times a speculative execution was started
451547 * 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 @@
1717
1818 import com.codahale.metrics.Timer;
1919 import com.datastax.driver.core.exceptions.*;
20+import com.datastax.driver.core.policies.ExtendedRetryPolicy;
2021 import com.datastax.driver.core.policies.RetryPolicy;
2122 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type;
2223 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan;
@@ -27,11 +28,11 @@
2728 import org.slf4j.LoggerFactory;
2829
2930 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.*;
3536 import java.util.concurrent.atomic.AtomicBoolean;
3637 import java.util.concurrent.atomic.AtomicInteger;
3738 import java.util.concurrent.atomic.AtomicReference;
@@ -57,8 +58,7 @@
5758 private final io.netty.util.Timer scheduler;
5859
5960 private volatile List<Host> triedHosts;
60-
61- private volatile Map<InetSocketAddress, Throwable> errors;
61+ private volatile ConcurrentMap<InetSocketAddress, Throwable> errors;
6262
6363 private final Timer.Context timerContext;
6464 private final long startTime;
@@ -149,13 +149,6 @@
149149 execution.cancel();
150150 }
151151
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-
159152 private void setFinalResult(SpeculativeExecution execution, Connection connection, Message.Response response) {
160153 if (!isDone.compareAndSet(false, true)) {
161154 if (logger.isTraceEnabled())
@@ -224,6 +217,12 @@
224217 return manager.cluster.manager.metrics;
225218 }
226219
220+ private RetryPolicy retryPolicy() {
221+ return statement.getRetryPolicy() == null
222+ ? manager.configuration().getPolicies().getRetryPolicy()
223+ : statement.getRetryPolicy();
224+ }
225+
227226 interface Callback extends Connection.ResponseCallback {
228227 void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
229228
@@ -250,7 +249,7 @@
250249
251250 // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from
252251 // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an
253- // OVERLOADED error).
252+ // UNPREPARED response).
254253 // This is incremented by one writer at a time, so volatile is good enough.
255254 private volatile int retriesByPolicy;
256255
@@ -341,6 +340,7 @@
341340 break;
342341 }
343342
343+ // set this flag to true before writing the request
344344 connectionHandler = connection.write(responseCallback, false);
345345 // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered
346346 // *before* the call to connection.write had returned.
@@ -356,6 +356,30 @@
356356 connection.release();
357357 }
358358
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+
359383 private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
360384 final Host h = current;
361385 this.retryConsistencyLevel = newConsistencyLevel;
@@ -379,6 +403,18 @@
379403 });
380404 }
381405
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+
382418 void cancel() {
383419 // Atomically set a special QueryState, that will cause any further operation to abort.
384420 // We want to remember whether a request was in progress when we did this, so there are two cancel states.
@@ -432,16 +468,11 @@
432468 Responses.Error err = (Responses.Error) response;
433469 exceptionToReport = err.asException(connection.address);
434470 RetryPolicy.RetryDecision retry = null;
435- RetryPolicy retryPolicy = statement.getRetryPolicy() == null
436- ? manager.configuration().getPolicies().getRetryPolicy()
437- : statement.getRetryPolicy();
471+ RetryPolicy retryPolicy = retryPolicy();
438472 switch (err.code) {
439473 case READ_TIMEOUT:
440474 connection.release();
441475 assert err.infos instanceof ReadTimeoutException;
442- if (metricsEnabled())
443- metrics().getErrorMetrics().getReadTimeouts().inc();
444-
445476 ReadTimeoutException rte = (ReadTimeoutException) err.infos;
446477 retry = retryPolicy.onReadTimeout(statement,
447478 rte.getConsistencyLevel(),
@@ -449,8 +480,8 @@
449480 rte.getReceivedAcknowledgements(),
450481 rte.wasDataRetrieved(),
451482 retriesByPolicy);
452-
453483 if (metricsEnabled()) {
484+ metrics().getErrorMetrics().getReadTimeouts().inc();
454485 if (retry.getType() == Type.RETRY)
455486 metrics().getErrorMetrics().getRetriesOnReadTimeout().inc();
456487 if (retry.getType() == Type.IGNORE)
@@ -460,9 +491,6 @@
460491 case WRITE_TIMEOUT:
461492 connection.release();
462493 assert err.infos instanceof WriteTimeoutException;
463- if (metricsEnabled())
464- metrics().getErrorMetrics().getWriteTimeouts().inc();
465-
466494 WriteTimeoutException wte = (WriteTimeoutException) err.infos;
467495 retry = retryPolicy.onWriteTimeout(statement,
468496 wte.getConsistencyLevel(),
@@ -470,8 +498,8 @@
470498 wte.getRequiredAcknowledgements(),
471499 wte.getReceivedAcknowledgements(),
472500 retriesByPolicy);
473-
474501 if (metricsEnabled()) {
502+ metrics().getErrorMetrics().getWriteTimeouts().inc();
475503 if (retry.getType() == Type.RETRY)
476504 metrics().getErrorMetrics().getRetriesOnWriteTimeout().inc();
477505 if (retry.getType() == Type.IGNORE)
@@ -481,17 +509,14 @@
481509 case UNAVAILABLE:
482510 connection.release();
483511 assert err.infos instanceof UnavailableException;
484- if (metricsEnabled())
485- metrics().getErrorMetrics().getUnavailables().inc();
486-
487512 UnavailableException ue = (UnavailableException) err.infos;
488513 retry = retryPolicy.onUnavailable(statement,
489514 ue.getConsistencyLevel(),
490515 ue.getRequiredReplicas(),
491516 ue.getAliveReplicas(),
492517 retriesByPolicy);
493-
494518 if (metricsEnabled()) {
519+ metrics().getErrorMetrics().getUnavailables().inc();
495520 if (retry.getType() == Type.RETRY)
496521 metrics().getErrorMetrics().getRetriesOnUnavailable().inc();
497522 if (retry.getType() == Type.IGNORE)
@@ -500,33 +525,51 @@
500525 break;
501526 case OVERLOADED:
502527 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()) {
508530 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;
511545 case SERVER_ERROR:
512546 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()) {
519551 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;
522566 case IS_BOOTSTRAPPING:
523567 connection.release();
524- // Try another node
525568 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()) {
529570 metrics().getErrorMetrics().getOthers().inc();
571+ }
572+ logError(connection.address, exceptionToReport);
530573 retry(false, null);
531574 return;
532575 case UNPREPARED:
@@ -572,26 +615,7 @@
572615 if (retry == null)
573616 setFinalResult(connection, response);
574617 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);
595619 }
596620 break;
597621 default:
@@ -609,6 +633,11 @@
609633 }
610634
611635 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.
612641 return new Connection.ResponseCallback() {
613642
614643 @Override
@@ -633,7 +662,6 @@
633662
634663 connection.release();
635664
636- // TODO should we check the response ?
637665 switch (response.type) {
638666 case RESULT:
639667 if (((Responses.Result) response).kind == Responses.Result.Kind.PREPARED) {
@@ -694,11 +722,20 @@
694722 connection.release();
695723
696724 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()) {
698732 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);
702739 return;
703740 }
704741 setFinalException(connection, exception);
@@ -726,8 +763,20 @@
726763 try {
727764 connection.release();
728765
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);
731780 } catch (Exception e) {
732781 // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely
733782 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 @@
8787 * answer a query.
8888 * <p/>
8989 * 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
9293 * other words, a {@link Session#execute} call may theoretically wait up to
9394 * {@code getReadTimeoutMillis() * <number_of_cassandra_hosts>} (though the
9495 * 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 @@
1919 import java.net.InetSocketAddress;
2020
2121 /**
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.
2723 */
2824 public class BootstrappingException extends DriverInternalError implements CoordinatorException {
2925
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java +6 −6
@@ -20,24 +20,24 @@
2020
2121 /**
2222 * 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.
2424 */
2525 public interface CoordinatorException {
2626
2727 /**
28- * The coordinator host that caused this exception to be raised.
29- * <p/>
28+ * The coordinator host that was contacted.
29+ * <p>
3030 * This is a shortcut for {@link InetSocketAddress#getAddress() getAddress().getAddress()}.
3131 *
32- * @return The coordinator host that caused this exception to be raised;
32+ * @return The coordinator host that was contacted;
3333 * may be {@code null} if the coordinator is not known.
3434 */
3535 InetAddress getHost();
3636
3737 /**
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.
3939 *
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;
4141 * may be {@code null} if the coordinator is not known.
4242 */
4343 InetSocketAddress getAddress();
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverInternalError.java +1 −1
@@ -18,7 +18,7 @@
1818 /**
1919 * An unexpected error happened internally.
2020 * <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
2222 * Cassandra).
2323 */
2424 public class DriverInternalError extends DriverException {
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +0 −4
@@ -20,10 +20,6 @@
2020
2121 /**
2222 * 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.
2723 */
2824 public class OverloadedException extends DriverInternalError implements CoordinatorException {
2925
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ServerError.java +1 −0
@@ -20,6 +20,7 @@
2020
2121 /**
2222 * Indicates that the contacted host reported un expected error.
23+ * This should be considered as a bug in Cassandra and reported as such.
2324 */
2425 public class ServerError extends DriverInternalError implements CoordinatorException {
2526
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +16 −1
@@ -34,7 +34,7 @@
3434 * In some cases, it may be convenient to use a more aggressive retry policy
3535 * like {@link DowngradingConsistencyRetryPolicy}.
3636 */
37-public class DefaultRetryPolicy implements RetryPolicy {
37+public class DefaultRetryPolicy implements ExtendedRetryPolicy {
3838
3939 public static final DefaultRetryPolicy INSTANCE = new DefaultRetryPolicy();
4040
@@ -136,4 +136,19 @@
136136 ? RetryDecision.tryNextHost(cl)
137137 : RetryDecision.rethrow();
138138 }
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+
139154 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +15 −1
@@ -66,7 +66,7 @@
6666 * to make sure the data is persisted, and that reading something is better
6767 * than reading nothing, even if there is a risk of reading stale data.
6868 */
69-public class DowngradingConsistencyRetryPolicy implements RetryPolicy {
69+public class DowngradingConsistencyRetryPolicy implements ExtendedRetryPolicy {
7070
7171 public static final DowngradingConsistencyRetryPolicy INSTANCE = new DowngradingConsistencyRetryPolicy();
7272
@@ -195,4 +195,18 @@
195195 // Tries the biggest CL that is expected to work
196196 return maxLikelyToWorkCL(aliveReplica);
197197 }
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+ }
198212 }
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 @@
2525 * All of the methods of this retry policy unconditionally return {@link RetryPolicy.RetryDecision#rethrow}.
2626 * If this policy is used, retry will have to be implemented in business code.
2727 */
28-public class FallthroughRetryPolicy implements RetryPolicy {
28+public class FallthroughRetryPolicy implements ExtendedRetryPolicy {
2929
3030 public static final FallthroughRetryPolicy INSTANCE = new FallthroughRetryPolicy();
3131
@@ -87,4 +87,15 @@
8787 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
8888 return RetryDecision.rethrow();
8989 }
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+
90101 }
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 @@
1818 import com.datastax.driver.core.ConsistencyLevel;
1919 import com.datastax.driver.core.Statement;
2020 import com.datastax.driver.core.WriteType;
21+import com.google.common.annotations.VisibleForTesting;
2122 import org.slf4j.Logger;
2223 import org.slf4j.LoggerFactory;
2324
@@ -28,9 +29,42 @@
2829 * RETHROW decisions are just meant to propagate the cassandra exception). The
2930 * logging is done at the INFO level.
3031 */
31-public class LoggingRetryPolicy implements RetryPolicy {
32+public class LoggingRetryPolicy implements ExtendedRetryPolicy {
3233
3334 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+
3468 private final RetryPolicy policy;
3569
3670 /**
@@ -47,17 +81,19 @@
4781 return decision.getRetryConsistencyLevel() == null ? cl : decision.getRetryConsistencyLevel();
4882 }
4983
84+ private static String host(RetryDecision decision) {
85+ return decision.isRetryCurrent() ? "same host" : "next host";
86+ }
87+
5088 @Override
5189 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
5290 RetryDecision decision = policy.onReadTimeout(statement, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry);
5391 switch (decision.getType()) {
5492 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);
5794 break;
5895 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);
6197 break;
6298 }
6399 return decision;
@@ -68,12 +104,10 @@
68104 RetryDecision decision = policy.onWriteTimeout(statement, cl, writeType, requiredAcks, receivedAcks, nbRetry);
69105 switch (decision.getType()) {
70106 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);
73108 break;
74109 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);
77111 break;
78112 }
79113 return decision;
@@ -84,14 +118,44 @@
84118 RetryDecision decision = policy.onUnavailable(statement, cl, requiredReplica, aliveReplica, nbRetry);
85119 switch (decision.getType()) {
86120 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);
89141 break;
90142 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);
93144 break;
94145 }
95146 return decision;
96147 }
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+
97161 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +31 −24
@@ -20,8 +20,7 @@
2020 import com.datastax.driver.core.WriteType;
2121
2222 /**
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.
2524 * <p/>
2625 * Such policy allows to centralize the handling of query retries, allowing to
2726 * minimize the need for exception catching/handling in business code.
@@ -32,9 +31,9 @@
3231 * A retry decision to adopt on a Cassandra exception (read/write timeout
3332 * or unavailable exception).
3433 * <p/>
35- * There is three possible decision:
34+ * There are three possible decisions:
3635 * <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>
3837 * <li>RETRY: the operation will be retried. The consistency level of the
3938 * retry should be specified.</li>
4039 * <li>IGNORE: no retry should be attempted and the exception should be
@@ -44,14 +43,12 @@
4443 */
4544 class RetryDecision {
4645 /**
47- * The type of retry decisions.
46+ * The types of retry decisions.
4847 */
4948 public enum Type {
5049 RETRY, RETHROW, IGNORE
5150 }
5251
53- ;
54-
5552 private final Type type;
5653 private final ConsistencyLevel retryCL;
5754 private final boolean retryCurrent;
@@ -72,57 +69,67 @@
7269 }
7370
7471 /**
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.
7679 *
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.
7981 */
8082 public ConsistencyLevel getRetryConsistencyLevel() {
8183 return retryCL;
8284 }
8385
8486 /**
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.
8689 *
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}.
8892 */
8993 public boolean isRetryCurrent() {
9094 return retryCurrent;
9195 }
9296
9397 /**
94- * Creates a RETHROW retry decision.
98+ * Creates a {@link RetryDecision.Type#RETHROW} retry decision.
9599 *
96- * @return a RETHROW retry decision.
100+ * @return a {@link RetryDecision.Type#RETHROW} retry decision.
97101 */
98102 public static RetryDecision rethrow() {
99103 return new RetryDecision(Type.RETHROW, null, true);
100104 }
101105
102106 /**
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.
104109 *
105110 * @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
107113 */
108114 public static RetryDecision retry(ConsistencyLevel consistency) {
109115 return new RetryDecision(Type.RETRY, consistency, true);
110116 }
111117
112118 /**
113- * Creates an IGNORE retry decision.
119+ * Creates an {@link RetryDecision.Type#IGNORE} retry decision.
114120 *
115- * @return an IGNORE retry decision.
121+ * @return an {@link RetryDecision.Type#IGNORE} retry decision.
116122 */
117123 public static RetryDecision ignore() {
118124 return new RetryDecision(Type.IGNORE, null, true);
119125 }
120126
121127 /**
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.
124130 *
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.
126133 */
127134 public static RetryDecision tryNextHost(ConsistencyLevel retryCL) {
128135 return new RetryDecision(Type.RETRY, retryCL, false);
@@ -163,7 +170,7 @@
163170 * a {@link com.datastax.driver.core.exceptions.ReadTimeoutException} will
164171 * be thrown for the operation.
165172 */
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);
167174
168175 /**
169176 * Defines whether to retry and at which consistency level on a write timeout.
@@ -180,7 +187,7 @@
180187 * a {@link com.datastax.driver.core.exceptions.WriteTimeoutException} will
181188 * be thrown for the operation.
182189 */
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);
184191
185192 /**
186193 * Defines whether to retry and at which consistency level on an
@@ -198,5 +205,5 @@
198205 * an {@link com.datastax.driver.core.exceptions.UnavailableException} will
199206 * be thrown for the operation.
200207 */
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);
202209 }
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +8 −2
@@ -16,7 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.Metrics.Errors;
19-import com.datastax.driver.core.policies.RetryPolicy;
19+import com.datastax.driver.core.policies.ExtendedRetryPolicy;
2020 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
2121 import org.testng.annotations.Test;
2222
@@ -27,7 +27,7 @@
2727
2828 @Override
2929 public Cluster.Builder createClusterBuilder() {
30- return Cluster.builder().withRetryPolicy(new RetryPolicy() {
30+ return Cluster.builder().withRetryPolicy(new ExtendedRetryPolicy() {
3131 @Override
3232 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
3333 return retryDecision;
@@ -42,6 +42,12 @@
4242 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
4343 return retryDecision;
4444 }
45+
46+ @Override
47+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) {
48+ return retryDecision;
49+ }
50+
4551 });
4652 }
4753
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +2 −8
@@ -134,7 +134,7 @@
134134 .contains(ip)
135135 .contains(Integer.toString(scassandra.getBinaryPort()))
136136 .contains(query)
137- .contains(OperationTimedOutException.class.getName());
137+ .contains("Operation timed out");
138138 }
139139
140140 @DataProvider(name = "errors")
@@ -177,14 +177,8 @@
177177 } catch (Exception e) {
178178 if (e instanceof NoHostAvailableException) {
179179 assertThat(expectedException).isEqualTo(NoHostAvailableException.class);
180- // ok
181180 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);
188182 } else {
189183 assertThat(e).isInstanceOf(expectedException);
190184 }
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +11 −2
@@ -16,7 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
19-import com.datastax.driver.core.policies.RetryPolicy;
19+import com.datastax.driver.core.policies.ExtendedRetryPolicy;
2020 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
@@ -52,6 +52,7 @@
5252 cluster = Cluster.builder()
5353 .addContactPoints(scassandras.address(2).getAddress())
5454 .withPort(scassandras.getBinaryPort())
55+ .withProtocolVersion(ProtocolVersion.V2) // Scassandra does not support V3 nor V4 yet
5556 .withLoadBalancingPolicy(loadBalancingPolicy)
5657 .withSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(speculativeExecutionDelay, 1))
5758 .withQueryOptions(new QueryOptions().setDefaultIdempotence(true))
@@ -203,6 +204,8 @@
203204 Cluster cluster = Cluster.builder()
204205 .addContactPoints(scassandras.address(2).getAddress())
205206 .withPort(scassandras.getBinaryPort())
207+ // Scassandra does not support V3 nor V4 yet, and V4 may cause the server to crash
208+ .withProtocolVersion(ProtocolVersion.V2)
206209 .withSpeculativeExecutionPolicy(mockPolicy)
207210 .build();
208211
@@ -222,7 +225,7 @@
222225 * Custom retry policy that retries at ONE on read timeout.
223226 * This deals with the fact that Scassandra only allows read timeouts with 0 replicas.
224227 */
225- static class CustomRetryPolicy implements RetryPolicy {
228+ static class CustomRetryPolicy implements ExtendedRetryPolicy {
226229 @Override
227230 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
228231 if (nbRetry != 0)
@@ -239,6 +242,12 @@
239242 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
240243 return RetryDecision.rethrow();
241244 }
245+
246+ @Override
247+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) {
248+ return RetryDecision.tryNextHost(cl);
249+ }
250+
242251 }
243252
244253 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 @@
125125 /**
126126 * A retry policy that counts how many times it has seen the custom wrapper for UNAVAILABLE errors.
127127 */
128- static class CustomRetryPolicy implements RetryPolicy {
128+ static class CustomRetryPolicy implements ExtendedRetryPolicy {
129129 final AtomicInteger customStatementsHandled = new AtomicInteger();
130130
131131 @Override
@@ -144,5 +144,11 @@
144144 public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
145145 return RetryDecision.rethrow();
146146 }
147+
148+ @Override
149+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) {
150+ return RetryDecision.tryNextHost(cl);
151+ }
152+
147153 }
148154 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +57 −6
@@ -16,13 +16,19 @@
1616 package com.datastax.driver.core.policies;
1717
1818 import com.datastax.driver.core.*;
19+import com.datastax.driver.core.exceptions.OverloadedException;
20+import com.datastax.driver.core.exceptions.ServerError;
1921 import com.google.common.collect.ImmutableList;
2022 import com.google.common.collect.ImmutableMap;
2123 import org.mockito.Mockito;
2224 import org.scassandra.Scassandra;
25+import org.scassandra.http.client.ClosedConnectionConfig.CloseType;
26+import org.scassandra.http.client.Config;
2327 import org.scassandra.http.client.PrimingRequest;
28+import org.scassandra.http.client.PrimingRequest.PrimingRequestBuilder;
2429 import org.testng.annotations.AfterMethod;
2530 import org.testng.annotations.BeforeMethod;
31+import org.testng.annotations.DataProvider;
2632
2733 import java.util.List;
2834 import java.util.Map;
@@ -31,6 +37,8 @@
3137 import static org.assertj.core.api.Assertions.assertThat;
3238 import static org.mockito.Matchers.*;
3339 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;
3442
3543 /**
3644 * Base class for retry policy integration tests.
@@ -49,9 +57,16 @@
4957 protected Host host1, host2, host3;
5058 protected Session session;
5159
52- protected RetryPolicy retryPolicy;
60+ protected ExtendedRetryPolicy retryPolicy;
5361
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) {
5570 this.retryPolicy = Mockito.spy(retryPolicy);
5671 }
5772
@@ -65,6 +80,12 @@
6580 .withPort(scassandras.getBinaryPort())
6681 .withRetryPolicy(retryPolicy)
6782 .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))
6889 .withNettyOptions(nonQuietClusterCloseOptions)
6990 .build();
7091
@@ -84,10 +105,18 @@
84105 }
85106
86107 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()
88113 .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());
91120 }
92121
93122 protected void simulateNormalResponse(int hostNumber) {
@@ -97,7 +126,7 @@
97126 .build());
98127 }
99128
100- private static List<Map<String, ?>> row(String key, String value) {
129+ protected static List<Map<String, ?>> row(String key, String value) {
101130 return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value));
102131 }
103132
@@ -125,6 +154,11 @@
125154 any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
126155 }
127156
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+
128162 protected void assertQueried(int hostNumber, int times) {
129163 assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times);
130164 }
@@ -136,4 +170,21 @@
136170 if (scassandras != null)
137171 scassandras.stop();
138172 }
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+ }
139190 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +91 −7
@@ -15,17 +15,20 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
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;
2221 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;
2325 import org.testng.annotations.Test;
2426
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;
2729 import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
2830 import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
31+import static org.scassandra.http.client.PrimingRequest.then;
2932
3033 /**
3134 * Integration test with a custom implementation, to test retry and ignore decisions.
@@ -43,6 +46,9 @@
4346 assertThat(rs.iterator().hasNext()).isFalse(); // ignore decisions produce empty result sets
4447
4548 assertOnReadTimeoutWasCalled(1);
49+ assertThat(errors.getIgnores().getCount()).isEqualTo(1);
50+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
51+ assertThat(errors.getIgnoresOnReadTimeout().getCount()).isEqualTo(1);
4652 assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
4753 assertQueried(1, 1);
4854 assertQueried(2, 0);
@@ -59,16 +65,89 @@
5965 } catch (UnavailableException e) {/*expected*/}
6066
6167 assertOnUnavailableWasCalled(2);
68+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
69+ assertThat(errors.getUnavailables().getCount()).isEqualTo(2);
6270 assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
6371 assertQueried(1, 2);
6472 assertQueried(2, 0);
6573 assertQueried(3, 0);
6674 }
6775
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+
68146 /**
69147 * Ignores read and write timeouts, and retries at most once on unavailable.
148+ * Rethrows for unexpected errors.
70149 */
71- static class CustomRetryPolicy implements RetryPolicy {
150+ static class CustomRetryPolicy implements ExtendedRetryPolicy {
72151
73152 @Override
74153 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
@@ -86,5 +165,10 @@
86165 ? RetryDecision.retry(cl)
87166 : RetryDecision.rethrow();
88167 }
168+
169+ @Override
170+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, Exception e, int nbRetry) {
171+ return RetryDecision.rethrow();
172+ }
89173 }
90174 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +117 −0
@@ -18,18 +18,26 @@
1818 import com.datastax.driver.core.Cluster;
1919 import com.datastax.driver.core.Metrics;
2020 import com.datastax.driver.core.Session;
21+import com.datastax.driver.core.SocketOptions;
2122 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2223 import com.datastax.driver.core.exceptions.ReadTimeoutException;
2324 import com.datastax.driver.core.exceptions.UnavailableException;
2425 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;
2529 import org.scassandra.Scassandra;
30+import org.scassandra.http.client.ClosedConnectionConfig;
31+import org.scassandra.http.client.PrimingRequest;
2632 import org.testng.annotations.Test;
2733
34+import java.util.Collection;
2835 import java.util.Collections;
2936
3037 import static org.assertj.core.api.Assertions.assertThat;
3138 import static org.assertj.core.api.Assertions.fail;
3239 import static org.scassandra.http.client.PrimingRequest.Result.*;
40+import static org.scassandra.http.client.PrimingRequest.then;
3341
3442 public class DefaultRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
3543 public DefaultRetryPolicyIntegrationTest() {
@@ -46,6 +54,8 @@
4654 } catch (ReadTimeoutException e) {/*expected*/ }
4755
4856 assertOnReadTimeoutWasCalled(1);
57+ assertThat(errors.getReadTimeouts().getCount()).isEqualTo(1);
58+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
4959 assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
5060 assertQueried(1, 1);
5161 assertQueried(2, 0);
@@ -62,6 +72,8 @@
6272 } catch (WriteTimeoutException e) {/*expected*/}
6373
6474 assertOnWriteTimeoutWasCalled(1);
75+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1);
76+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
6577 assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0);
6678 assertQueried(1, 1);
6779 assertQueried(2, 0);
@@ -76,6 +88,8 @@
7688 query();
7789
7890 assertOnUnavailableWasCalled(1);
91+ assertThat(errors.getUnavailables().getCount()).isEqualTo(1);
92+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
7993 assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
8094 assertQueried(1, 1);
8195 assertQueried(2, 1);
@@ -93,6 +107,8 @@
93107 } catch (UnavailableException e) {/*expected*/}
94108
95109 assertOnUnavailableWasCalled(2);
110+ assertThat(errors.getUnavailables().getCount()).isEqualTo(2);
111+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
96112 assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
97113 assertQueried(1, 1);
98114 assertQueried(2, 1);
@@ -142,4 +158,105 @@
142158 whiteListedCluster.close();
143159 }
144160 }
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+ }
145262 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +424 −91
@@ -15,100 +15,433 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
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;
2228 import org.testng.annotations.Test;
2329
24-import static com.datastax.driver.core.ConsistencyLevel.*;
25-import static com.datastax.driver.core.TestUtils.ipOfNode;
30+import java.util.Collection;
31+
2632 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());
47437 }
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);
113446 }
114447 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +76 −3
@@ -15,14 +15,17 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
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;
2123 import org.testng.annotations.Test;
2224
2325 import static org.assertj.core.api.Assertions.assertThat;
2426 import static org.assertj.core.api.Assertions.fail;
2527 import static org.scassandra.http.client.PrimingRequest.Result.*;
28+import static org.scassandra.http.client.PrimingRequest.then;
2629
2730 public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
2831 public FallthroughRetryPolicyIntegrationTest() {
@@ -76,4 +79,74 @@
7679 assertQueried(2, 0);
7780 assertQueried(3, 0);
7881 }
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+ }
79152 }
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 @@
6060 <testng.version>6.8.8</testng.version>
6161 <assertj.version>1.7.0</assertj.version>
6262 <mockito.version>1.10.8</mockito.version>
63- <scassandra.version>0.10.0</scassandra.version>
63+ <scassandra.version>0.11.0</scassandra.version>
6464 <main.basedir>${project.basedir}</main.basedir>
6565 </properties>
6666