Elffuss BraidHub

kikocis/java-driver public

JAVA-819: Driver shouldn't retry on client timeout if statement is not idempotent.

This commit introduces a new method in RetryPolicy: onRequestError(), that handles
network errors, timeouts and server errors.

It also introduces a new retry policy: IdempotenceAwareRetryPolicy, that wraps
an inner policy and avoids retrying non-idempotent statements.

This commit contains contributions by Andrew Tolbert (@tolbertam).
Changeset51433ff5ddfe79ef9fb151c4156be779f76ddf67ca7deba994740cfdf545e81c
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-16 15:39 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-12-04 18:35 +01:00
Parents68ee5447be2a

Browse the files at this changeset

21 files changed

modified changelog/README.md +1 −0
@@ -10,6 +10,7 @@
1010 - [improvement] JAVA-1003: Change default consistency level to LOCAL_ONE (amends JAVA-926).
1111 - [improvement] JAVA-863: Idempotence propagation in prepared statements.
1212 - [improvement] JAVA-996: Make CodecRegistry available to ProtocolDecoder.
13+- [bug] JAVA-819: Driver shouldn't retry on client timeout if statement is not idempotent.
1314
1415 Merged from 2.1 branch:
1516
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +102 −7
@@ -273,6 +273,7 @@
273273 private final Counter writeTimeouts = registry.counter("write-timeouts");
274274 private final Counter readTimeouts = registry.counter("read-timeouts");
275275 private final Counter unavailables = registry.counter("unavailables");
276+ private final Counter clientTimeouts = registry.counter("client-timeouts");
276277
277278 private final Counter otherErrors = registry.counter("other-errors");
278279
@@ -280,10 +281,17 @@
280281 private final Counter retriesOnWriteTimeout = registry.counter("retries-on-write-timeout");
281282 private final Counter retriesOnReadTimeout = registry.counter("retries-on-read-timeout");
282283 private final Counter retriesOnUnavailable = registry.counter("retries-on-unavailable");
284+ private final Counter retriesOnClientTimeout = registry.counter("retries-on-client-timeout");
285+ private final Counter retriesOnConnectionError = registry.counter("retries-on-connection-error");
286+ private final Counter retriesOnOtherErrors = registry.counter("retries-on-other-errors");
287+
283288 private final Counter ignores = registry.counter("ignores");
284289 private final Counter ignoresOnWriteTimeout = registry.counter("ignores-on-write-timeout");
285290 private final Counter ignoresOnReadTimeout = registry.counter("ignores-on-read-timeout");
286291 private final Counter ignoresOnUnavailable = registry.counter("ignores-on-unavailable");
292+ private final Counter ignoresOnClientTimeout = registry.counter("ignores-on-client-timeout");
293+ private final Counter ignoresOnConnectionError = registry.counter("ignores-on-connection-error");
294+ private final Counter ignoresOnOtherErrors = registry.counter("ignores-on-other-errors");
287295
288296 private final Counter speculativeExecutions = registry.counter("speculative-executions");
289297
@@ -335,6 +343,16 @@
335343 return unavailables;
336344 }
337345
346+ /**
347+ * Returns the number of requests that timed out before the driver
348+ * received a response.
349+ *
350+ * @return the number of client timeouts.
351+ */
352+ public Counter getClientTimeouts() {
353+ return clientTimeouts;
354+ }
355+
338356 /**
339357 * Returns the number of requests that returned errors not accounted for by
340358 * another metric. This includes all types of invalid requests.
@@ -350,7 +368,7 @@
350368 * Returns the number of times a request was retried due to the
351369 * {@link com.datastax.driver.core.policies.RetryPolicy}.
352370 *
353- * @return the number of times a requests was retried due to the
371+ * @return the number of times a request was retried due to the
354372 * {@link com.datastax.driver.core.policies.RetryPolicy}.
355373 */
356374 public Counter getRetries() {
@@ -362,7 +380,7 @@
362380 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
363381 * read timed out.
364382 *
365- * @return the number of times a requests was retried due to the
383+ * @return the number of times a request was retried due to the
366384 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
367385 * read timed out.
368386 */
@@ -375,7 +393,7 @@
375393 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
376394 * write timed out.
377395 *
378- * @return the number of times a requests was retried due to the
396+ * @return the number of times a request was retried due to the
379397 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
380398 * write timed out.
381399 */
@@ -388,7 +406,7 @@
388406 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
389407 * unavailable exception.
390408 *
391- * @return the number of times a requests was retried due to the
409+ * @return the number of times a request was retried due to the
392410 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
393411 * unavailable exception.
394412 */
@@ -396,6 +414,45 @@
396414 return retriesOnUnavailable;
397415 }
398416
417+ /**
418+ * Returns the number of times a request was retried due to the
419+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
420+ * client timeout.
421+ *
422+ * @return the number of times a request was retried due to the
423+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
424+ * client timeout.
425+ */
426+ public Counter getRetriesOnClientTimeout() {
427+ return retriesOnClientTimeout;
428+ }
429+
430+ /**
431+ * Returns the number of times a request was retried due to the
432+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
433+ * connection error.
434+ *
435+ * @return the number of times a request was retried due to the
436+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
437+ * connection error.
438+ */
439+ public Counter getRetriesOnConnectionError() {
440+ return retriesOnConnectionError;
441+ }
442+
443+ /**
444+ * Returns the number of times a request was retried due to the
445+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
446+ * unexpected error.
447+ *
448+ * @return the number of times a request was retried due to the
449+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
450+ * unexpected error.
451+ */
452+ public Counter getRetriesOnOtherErrors() {
453+ return retriesOnOtherErrors;
454+ }
455+
399456 /**
400457 * Returns the number of times a request was ignored
401458 * due to the {@link com.datastax.driver.core.policies.RetryPolicy}, for
@@ -413,7 +470,7 @@
413470 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
414471 * read timed out.
415472 *
416- * @return the number of times a requests was ignored due to the
473+ * @return the number of times a request was ignored due to the
417474 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
418475 * read timed out.
419476 */
@@ -426,7 +483,7 @@
426483 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
427484 * write timed out.
428485 *
429- * @return the number of times a requests was ignored due to the
486+ * @return the number of times a request was ignored due to the
430487 * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
431488 * write timed out.
432489 */
@@ -439,7 +496,7 @@
439496 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
440497 * unavailable exception.
441498 *
442- * @return the number of times a requests was ignored due to the
499+ * @return the number of times a request was ignored due to the
443500 * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
444501 * unavailable exception.
445502 */
@@ -447,6 +504,44 @@
447504 return ignoresOnUnavailable;
448505 }
449506
507+ /**
508+ * Returns the number of times a request was ignored due to the
509+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
510+ * client timeout.
511+ *
512+ * @return the number of times a request was ignored due to the
513+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
514+ * client timeout.
515+ */
516+ public Counter getIgnoresOnClientTimeout() {
517+ return ignoresOnClientTimeout;
518+ }
519+
520+ /**
521+ * Returns the number of times a request was ignored due to the
522+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
523+ * connection error.
524+ *
525+ * @return the number of times a request was ignored due to the
526+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after a
527+ * connection error.
528+ */
529+ public Counter getIgnoresOnConnectionError() {
530+ return ignoresOnConnectionError;
531+ }
532+
533+ /**
534+ * Returns the number of times a request was ignored due to the
535+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
536+ * unexpected error.
537+ *
538+ * @return the number of times a request was ignored due to the
539+ * {@link com.datastax.driver.core.policies.RetryPolicy}, after an
540+ * unexpected error.
541+ */
542+ public Counter getIgnoresOnOtherErrors() {
543+ return ignoresOnOtherErrors;
544+ }
450545 /**
451546 * Returns the number of times a speculative execution was started
452547 * because a previous execution did not complete within the delay
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +111 −67
@@ -16,11 +16,11 @@
1616 package com.datastax.driver.core;
1717
1818 import java.net.InetSocketAddress;
19-import java.util.*;
20-import java.util.concurrent.ConcurrentHashMap;
21-import java.util.concurrent.CopyOnWriteArrayList;
22-import java.util.concurrent.TimeUnit;
23-import java.util.concurrent.TimeoutException;
19+import java.util.Collections;
20+import java.util.Iterator;
21+import java.util.List;
22+import java.util.Set;
23+import java.util.concurrent.*;
2424 import java.util.concurrent.atomic.AtomicBoolean;
2525 import java.util.concurrent.atomic.AtomicInteger;
2626 import java.util.concurrent.atomic.AtomicReference;
@@ -58,8 +58,7 @@
5858 private final io.netty.util.Timer scheduler;
5959
6060 private volatile List<Host> triedHosts;
61-
62- private volatile Map<InetSocketAddress, Throwable> errors;
61+ private volatile ConcurrentMap<InetSocketAddress, Throwable> errors;
6362
6463 private final Timer.Context timerContext;
6564 private final long startTime;
@@ -228,6 +227,12 @@
228227 return manager.cluster.manager.metrics;
229228 }
230229
230+ private RetryPolicy retryPolicy() {
231+ return statement.getRetryPolicy() == null
232+ ? manager.configuration().getPolicies().getRetryPolicy()
233+ : statement.getRetryPolicy();
234+ }
235+
231236 interface Callback extends Connection.ResponseCallback {
232237 void onSet(Connection connection, Message.Response response, ExecutionInfo info, Statement statement, long latency);
233238 void register(RequestHandler handler);
@@ -253,7 +258,7 @@
253258
254259 // This represents the number of times a retry has been triggered by the RetryPolicy (this is different from
255260 // queryStateRef.get().retryCount, because some retries don't involve the policy, for example after an
256- // OVERLOADED error).
261+ // UNPREPARED response).
257262 // This is incremented by one writer at a time, so volatile is good enough.
258263 private volatile int retriesByPolicy;
259264
@@ -359,6 +364,30 @@
359364 connection.release();
360365 }
361366
367+ private void processRetryDecision(RetryPolicy.RetryDecision retryDecision, Connection connection, Exception exceptionToReport) {
368+ switch (retryDecision.getType()) {
369+ case RETRY:
370+ retriesByPolicy++;
371+ if (logger.isDebugEnabled())
372+ logger.debug("[{}] Doing retry {} for query {} at consistency {}", id, retriesByPolicy, statement, retryDecision.getRetryConsistencyLevel());
373+ if (metricsEnabled())
374+ metrics().getErrorMetrics().getRetries().inc();
375+ // log error for the current host if we are switching to another one
376+ if (!retryDecision.isRetryCurrent())
377+ logError(connection.address, exceptionToReport);
378+ retry(retryDecision.isRetryCurrent(), retryDecision.getRetryConsistencyLevel());
379+ break;
380+ case RETHROW:
381+ setFinalException(connection, exceptionToReport);
382+ break;
383+ case IGNORE:
384+ if (metricsEnabled())
385+ metrics().getErrorMetrics().getIgnores().inc();
386+ setFinalResult(connection, new Responses.Result.Void());
387+ break;
388+ }
389+ }
390+
362391 private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
363392 final Host h = current;
364393 this.retryConsistencyLevel = newConsistencyLevel;
@@ -382,6 +411,18 @@
382411 });
383412 }
384413
414+ private void logError(InetSocketAddress address, Throwable exception) {
415+ logger.debug("[{}] Error querying {} : {}", id, address, exception.toString());
416+ if (errors == null) {
417+ synchronized (RequestHandler.this) {
418+ if (errors == null) {
419+ errors = new ConcurrentHashMap<InetSocketAddress, Throwable>();
420+ }
421+ }
422+ }
423+ errors.put(address, exception);
424+ }
425+
385426 void cancel() {
386427 // Atomically set a special QueryState, that will cause any further operation to abort.
387428 // We want to remember whether a request was in progress when we did this, so there are two cancel states.
@@ -435,16 +476,11 @@
435476 Responses.Error err = (Responses.Error)response;
436477 exceptionToReport = err.asException(connection.address);
437478 RetryPolicy.RetryDecision retry = null;
438- RetryPolicy retryPolicy = statement.getRetryPolicy() == null
439- ? manager.configuration().getPolicies().getRetryPolicy()
440- : statement.getRetryPolicy();
479+ RetryPolicy retryPolicy = retryPolicy();
441480 switch (err.code) {
442481 case READ_TIMEOUT:
443482 connection.release();
444483 assert err.infos instanceof ReadTimeoutException;
445- if (metricsEnabled())
446- metrics().getErrorMetrics().getReadTimeouts().inc();
447-
448484 ReadTimeoutException rte = (ReadTimeoutException)err.infos;
449485 retry = retryPolicy.onReadTimeout(statement,
450486 rte.getConsistencyLevel(),
@@ -452,8 +488,8 @@
452488 rte.getReceivedAcknowledgements(),
453489 rte.wasDataRetrieved(),
454490 retriesByPolicy);
455-
456491 if (metricsEnabled()) {
492+ metrics().getErrorMetrics().getReadTimeouts().inc();
457493 if (retry.getType() == Type.RETRY)
458494 metrics().getErrorMetrics().getRetriesOnReadTimeout().inc();
459495 if (retry.getType() == Type.IGNORE)
@@ -463,9 +499,6 @@
463499 case WRITE_TIMEOUT:
464500 connection.release();
465501 assert err.infos instanceof WriteTimeoutException;
466- if (metricsEnabled())
467- metrics().getErrorMetrics().getWriteTimeouts().inc();
468-
469502 WriteTimeoutException wte = (WriteTimeoutException)err.infos;
470503 retry = retryPolicy.onWriteTimeout(statement,
471504 wte.getConsistencyLevel(),
@@ -473,8 +506,8 @@
473506 wte.getRequiredAcknowledgements(),
474507 wte.getReceivedAcknowledgements(),
475508 retriesByPolicy);
476-
477509 if (metricsEnabled()) {
510+ metrics().getErrorMetrics().getWriteTimeouts().inc();
478511 if (retry.getType() == Type.RETRY)
479512 metrics().getErrorMetrics().getRetriesOnWriteTimeout().inc();
480513 if (retry.getType() == Type.IGNORE)
@@ -484,17 +517,14 @@
484517 case UNAVAILABLE:
485518 connection.release();
486519 assert err.infos instanceof UnavailableException;
487- if (metricsEnabled())
488- metrics().getErrorMetrics().getUnavailables().inc();
489-
490520 UnavailableException ue = (UnavailableException)err.infos;
491521 retry = retryPolicy.onUnavailable(statement,
492522 ue.getConsistencyLevel(),
493523 ue.getRequiredReplicas(),
494524 ue.getAliveReplicas(),
495525 retriesByPolicy);
496-
497526 if (metricsEnabled()) {
527+ metrics().getErrorMetrics().getUnavailables().inc();
498528 if (retry.getType() == Type.RETRY)
499529 metrics().getErrorMetrics().getRetriesOnUnavailable().inc();
500530 if (retry.getType() == Type.IGNORE)
@@ -503,30 +533,44 @@
503533 break;
504534 case OVERLOADED:
505535 connection.release();
506- // Try another node
507- logger.warn("Host {} is overloaded, trying next host.", connection.address);
508- logError(connection.address, exceptionToReport);
509- if (metricsEnabled())
536+ assert exceptionToReport instanceof OverloadedException;
537+ logger.warn("Host {} is overloaded.", connection.address);
538+ retry = retryPolicy.onRequestError(statement,
539+ request().consistency(),
540+ (OverloadedException)exceptionToReport, retriesByPolicy);
541+ if (metricsEnabled()) {
510542 metrics().getErrorMetrics().getOthers().inc();
511- retry(false, null);
512- return;
543+ if (retry.getType() == Type.RETRY)
544+ metrics().getErrorMetrics().getRetriesOnOtherErrors().inc();
545+ if (retry.getType() == Type.IGNORE)
546+ metrics().getErrorMetrics().getIgnoresOnOtherErrors().inc();
547+ }
548+ break;
513549 case SERVER_ERROR:
514550 connection.release();
515- // Defunct connection and try another node
516- logger.warn("{} replied with server error ({}), trying next host.", connection.address, err.message);
517- logError(connection.address, exceptionToReport);
551+ assert exceptionToReport instanceof ServerError;
552+ logger.warn("{} replied with server error ({}), defuncting connection.", connection.address, err.message);
553+ // Defunct connection
518554 connection.defunct(exceptionToReport);
519- if (metricsEnabled())
555+ retry = retryPolicy.onRequestError(statement,
556+ request().consistency(),
557+ (ServerError)exceptionToReport, retriesByPolicy);
558+ if (metricsEnabled()) {
520559 metrics().getErrorMetrics().getOthers().inc();
521- retry(false, null);
522- return;
560+ if (retry.getType() == Type.RETRY)
561+ metrics().getErrorMetrics().getRetriesOnOtherErrors().inc();
562+ if (retry.getType() == Type.IGNORE)
563+ metrics().getErrorMetrics().getIgnoresOnOtherErrors().inc();
564+ }
565+ break;
523566 case IS_BOOTSTRAPPING:
524567 connection.release();
525- // Try another node
568+ assert exceptionToReport instanceof BootstrappingException;
526569 logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address);
527- logError(connection.address, exceptionToReport);
528- if (metricsEnabled())
570+ if (metricsEnabled()) {
529571 metrics().getErrorMetrics().getOthers().inc();
572+ }
573+ logError(connection.address, exceptionToReport);
530574 retry(false, null);
531575 return;
532576 case UNPREPARED:
@@ -572,26 +616,7 @@
572616 if (retry == null)
573617 setFinalResult(connection, response);
574618 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- }
619+ processRetryDecision(retry, connection, exceptionToReport);
595620 }
596621 break;
597622 default:
@@ -609,6 +634,11 @@
609634 }
610635
611636 private Connection.ResponseCallback prepareAndRetry(final String toPrepare) {
637+ // do not bother inspecting retry policy at this step, no other decision
638+ // makes sense than retry on the same host if the query was prepared,
639+ // or on another host, if an error/timeout occurred.
640+ // The original request hasn't been executed so far, so there is no risk
641+ // of re-executing non-idempotent statements.
612642 return new Connection.ResponseCallback() {
613643
614644 @Override
@@ -636,7 +666,6 @@
636666
637667 connection.release();
638668
639- // TODO should we check the response ?
640669 switch (response.type) {
641670 case RESULT:
642671 if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) {
@@ -675,7 +704,7 @@
675704 return false;
676705 }
677706 connection.release();
678- logError(connection.address, new OperationTimedOutException(connection.address, "Timeout waiting for response to prepare message"));
707+ logError(connection.address, new OperationTimedOutException(connection.address, "Timed out waiting for response to PREPARE message"));
679708 retry(false, null);
680709 return true;
681710 }
@@ -697,11 +726,16 @@
697726 connection.release();
698727
699728 if (exception instanceof ConnectionException) {
700- if (metricsEnabled())
729+ RetryPolicy retryPolicy = retryPolicy();
730+ RetryPolicy.RetryDecision decision = retryPolicy.onRequestError(statement, request().consistency(), (ConnectionException)exception, retriesByPolicy);
731+ if (metricsEnabled()) {
701732 metrics().getErrorMetrics().getConnectionErrors().inc();
702- ConnectionException ce = (ConnectionException)exception;
703- logError(ce.address, ce);
704- 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);
705739 return;
706740 }
707741 setFinalException(connection, exception);
@@ -725,12 +759,22 @@
725759 }
726760
727761 Host queriedHost = current;
728- OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address);
762+
763+ OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address, "Timed out waiting for server response");
764+
729765 try {
730766 connection.release();
731767
732- logError(connection.address, timeoutException);
733- retry(false, null);
768+ RetryPolicy retryPolicy = retryPolicy();
769+ RetryPolicy.RetryDecision decision = retryPolicy.onRequestError(statement, request().consistency(), timeoutException, retriesByPolicy);
770+ if (metricsEnabled()) {
771+ metrics().getErrorMetrics().getClientTimeouts().inc();
772+ if (decision.getType() == Type.RETRY)
773+ metrics().getErrorMetrics().getRetriesOnClientTimeout().inc();
774+ if (decision.getType() == Type.IGNORE)
775+ metrics().getErrorMetrics().getIgnoresOnClientTimeout().inc();
776+ }
777+ processRetryDecision(decision, connection, timeoutException);
734778 } catch (Exception e) {
735779 // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely
736780 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
@@ -86,8 +86,9 @@
8686 * answer a query.
8787 * <p>
8888 * Please note that this is not the maximum time a call to {@link Session#execute} may block;
89- * this is the maximum time that call will wait for one particular
90- * Cassandra host, but other hosts will be tried if one of them times out. In
89+ * this is the maximum time that a call will wait for one particular
90+ * Cassandra host, but other hosts could be tried if one of them times out, depending
91+ * on the {@link com.datastax.driver.core.policies.RetryPolicy} in use. In
9192 * other words, a {@link Session#execute} call may theoretically wait up to
9293 * {@code getReadTimeoutMillis() * <number_of_cassandra_hosts>} (though the
9394 * total number of hosts tried for a given query also depends on the
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +15 −0
@@ -19,6 +19,7 @@
1919 import com.datastax.driver.core.ConsistencyLevel;
2020 import com.datastax.driver.core.Statement;
2121 import com.datastax.driver.core.WriteType;
22+import com.datastax.driver.core.exceptions.DriverException;
2223
2324 /**
2425 * The default retry policy.
@@ -137,6 +138,20 @@
137138 : RetryDecision.rethrow();
138139 }
139140
141+ /**
142+ * {@inheritDoc}
143+ * <p>
144+ * For historical reasons, this implementation triggers a retry on the next host in the query plan
145+ * with the same consistency level, regardless of the statement's idempotence.
146+ * Note that this breaks the general rule
147+ * stated in {@link RetryPolicy#onRequestError(Statement, ConsistencyLevel, DriverException, int)}:
148+ * "a retry should only be attempted if the request is known to be idempotent".
149+ */
150+ @Override
151+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
152+ return RetryDecision.tryNextHost(cl);
153+ }
154+
140155 @Override
141156 public void init(Cluster cluster) {
142157 // nothing to do
modified driver-core/src/main/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicy.java +15 −0
@@ -19,6 +19,7 @@
1919 import com.datastax.driver.core.ConsistencyLevel;
2020 import com.datastax.driver.core.Statement;
2121 import com.datastax.driver.core.WriteType;
22+import com.datastax.driver.core.exceptions.DriverException;
2223
2324 /**
2425 * A retry policy that sometimes retry with a lower consistency level than
@@ -196,6 +197,20 @@
196197 return maxLikelyToWorkCL(aliveReplica);
197198 }
198199
200+ /**
201+ * {@inheritDoc}
202+ * <p>
203+ * For historical reasons, this implementation triggers a retry on the next host in the query plan
204+ * with the same consistency level, regardless of the statement's idempotence.
205+ * Note that this breaks the general rule
206+ * stated in {@link RetryPolicy#onRequestError(Statement, ConsistencyLevel, DriverException, int)}:
207+ * "a retry should only be attempted if the request is known to be idempotent".`
208+ */
209+ @Override
210+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
211+ return RetryDecision.tryNextHost(cl);
212+ }
213+
199214 @Override
200215 public void init(Cluster cluster) {
201216 // nothing to do
modified driver-core/src/main/java/com/datastax/driver/core/policies/FallthroughRetryPolicy.java +12 −0
@@ -19,6 +19,7 @@
1919 import com.datastax.driver.core.ConsistencyLevel;
2020 import com.datastax.driver.core.Statement;
2121 import com.datastax.driver.core.WriteType;
22+import com.datastax.driver.core.exceptions.DriverException;
2223
2324 /**
2425 * A retry policy that never retry (nor ignore).
@@ -88,6 +89,17 @@
8889 return RetryDecision.rethrow();
8990 }
9091
92+ /**
93+ * {@inheritDoc}
94+ * <p>
95+ * This implementation always returns {@code RetryDecision.rethrow()}.
96+ */
97+ @Override
98+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
99+ return RetryDecision.rethrow();
100+ }
101+
102+
91103 @Override
92104 public void init(Cluster cluster) {
93105 // nothing to do
added driver-core/src/main/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicy.java +102 −0
@@ -0,0 +1,102 @@
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+
21+/**
22+ * A retry policy that avoids retrying non-idempotent statements.
23+ * <p>
24+ * In case of write timeouts or unexpected errors, this policy will always return {@link RetryDecision#rethrow()}
25+ * if the statement is deemed non-idempotent (see {@link #isIdempotent(Statement)}).
26+ * <p>
27+ * For all other cases, this policy delegates the decision to the child policy.
28+ */
29+public class IdempotenceAwareRetryPolicy implements RetryPolicy {
30+
31+ private final RetryPolicy childPolicy;
32+
33+ private QueryOptions queryOptions;
34+
35+ /**
36+ * Creates a new instance.
37+ * @param childPolicy the policy to wrap.
38+ */
39+ public IdempotenceAwareRetryPolicy(RetryPolicy childPolicy) {
40+ this.childPolicy = childPolicy;
41+ }
42+
43+ @Override
44+ public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
45+ return childPolicy.onReadTimeout(statement, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry);
46+ }
47+
48+ @Override
49+ public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
50+ if(isIdempotent(statement))
51+ return childPolicy.onWriteTimeout(statement, cl, writeType, requiredAcks, receivedAcks, nbRetry);
52+ else
53+ return RetryDecision.rethrow();
54+ }
55+
56+ @Override
57+ public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
58+ return childPolicy.onUnavailable(statement, cl, requiredReplica, aliveReplica, nbRetry);
59+ }
60+
61+ @Override
62+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
63+ if(isIdempotent(statement))
64+ return childPolicy.onRequestError(statement, cl, e, nbRetry);
65+ else
66+ return RetryDecision.rethrow();
67+ }
68+
69+ @Override
70+ public void init(Cluster cluster) {
71+ queryOptions = cluster.getConfiguration().getQueryOptions();
72+ }
73+
74+ @Override
75+ public void close() {
76+ // nothing to do
77+ }
78+
79+ /**
80+ * Determines whether the given statement is idempotent or not.
81+ * <p>
82+ * The current implementation inspects the statement's
83+ * {@link Statement#isIdempotent() idempotent flag};
84+ * if this flag is not set, then it inspects
85+ * {@link QueryOptions#getDefaultIdempotence()}.
86+ * <p>
87+ * Subclasses may override if they have better knowledge of
88+ * the statement being executed.
89+ *
90+ * @param statement The statement to execute.
91+ * @return {@code true} if the given statement is idempotent,
92+ * {@code false} otherwise
93+ */
94+ protected boolean isIdempotent(Statement statement) {
95+ Boolean myValue = statement.isIdempotent();
96+ if (myValue != null)
97+ return myValue;
98+ else
99+ return queryOptions.getDefaultIdempotence();
100+ }
101+
102+}
modified driver-core/src/main/java/com/datastax/driver/core/policies/LoggingRetryPolicy.java +64 −12
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import com.google.common.annotations.VisibleForTesting;
1819 import org.slf4j.Logger;
1920 import org.slf4j.LoggerFactory;
2021
@@ -22,6 +23,7 @@
2223 import com.datastax.driver.core.ConsistencyLevel;
2324 import com.datastax.driver.core.Statement;
2425 import com.datastax.driver.core.WriteType;
26+import com.datastax.driver.core.exceptions.DriverException;
2527
2628 /**
2729 * A retry policy that wraps another policy, logging the decision made by its sub-policy.
@@ -33,6 +35,31 @@
3335 public class LoggingRetryPolicy implements RetryPolicy {
3436
3537 private static final Logger logger = LoggerFactory.getLogger(LoggingRetryPolicy.class);
38+
39+ @VisibleForTesting static final String IGNORING_READ_TIMEOUT =
40+ "Ignoring read timeout (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})";
41+
42+ @VisibleForTesting static final String RETRYING_ON_READ_TIMEOUT =
43+ "Retrying on read timeout on {} at consistency {} (initial consistency: {}, required responses: {}, received responses: {}, data retrieved: {}, retries: {})";
44+
45+ @VisibleForTesting static final String IGNORING_WRITE_TIMEOUT =
46+ "Ignoring write timeout (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})";
47+
48+ @VisibleForTesting static final String RETRYING_ON_WRITE_TIMEOUT =
49+ "Retrying on write timeout on {} at consistency {} (initial consistency: {}, write type: {}, required acknowledgments: {}, received acknowledgments: {}, retries: {})";
50+
51+ @VisibleForTesting static final String IGNORING_UNAVAILABLE =
52+ "Ignoring unavailable exception (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})";
53+
54+ @VisibleForTesting static final String RETRYING_ON_UNAVAILABLE =
55+ "Retrying on unavailable exception on {} at consistency {} (initial consistency: {}, required replica: {}, alive replica: {}, retries: {})";
56+
57+ @VisibleForTesting static final String IGNORING_REQUEST_ERROR =
58+ "Ignoring request error (initial consistency: {}, retries: {}, exception: {})";
59+
60+ @VisibleForTesting static final String RETRYING_ON_REQUEST_ERROR =
61+ "Retrying on request error on {} at consistency {} (initial consistency: {}, retries: {}, exception: {})";
62+
3663 private final RetryPolicy policy;
3764
3865 /**
@@ -49,17 +76,19 @@
4976 return decision.getRetryConsistencyLevel() == null ? cl : decision.getRetryConsistencyLevel();
5077 }
5178
79+ private static String host(RetryDecision decision) {
80+ return decision.isRetryCurrent() ? "same host" : "next host";
81+ }
82+
5283 @Override
5384 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
5485 RetryDecision decision = policy.onReadTimeout(statement, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry);
5586 switch (decision.getType()) {
5687 case IGNORE:
57- String f1 = "Ignoring read timeout (initial consistency: %s, required responses: %d, received responses: %d, data retrieved: %b, retries: %d)";
58- logger.info(String.format(f1, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry));
88+ logDecision(IGNORING_READ_TIMEOUT, cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry);
5989 break;
6090 case RETRY:
61- String f2 = "Retrying on read timeout at consistency %s (initial consistency: %s, required responses: %d, received responses: %d, data retrieved: %b, retries: %d)";
62- logger.info(String.format(f2, cl(cl, decision), cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry));
91+ logDecision(RETRYING_ON_READ_TIMEOUT, host(decision), cl(cl, decision), cl, requiredResponses, receivedResponses, dataRetrieved, nbRetry);
6392 break;
6493 }
6594 return decision;
@@ -70,12 +99,10 @@
7099 RetryDecision decision = policy.onWriteTimeout(statement, cl, writeType, requiredAcks, receivedAcks, nbRetry);
71100 switch (decision.getType()) {
72101 case IGNORE:
73- String f1 = "Ignoring write timeout (initial consistency: %s, write type: %s, required acknowledgments: %d, received acknowledgments: %d, retries: %d)";
74- logger.info(String.format(f1, cl, writeType, requiredAcks, receivedAcks, nbRetry));
102+ logDecision(IGNORING_WRITE_TIMEOUT, cl, writeType, requiredAcks, receivedAcks, nbRetry);
75103 break;
76104 case RETRY:
77- String f2 = "Retrying on write timeout at consistency %s(initial consistency: %s, write type: %s, required acknowledgments: %d, received acknowledgments: %d, retries: %d)";
78- logger.info(String.format(f2, cl(cl, decision), cl, writeType, requiredAcks, receivedAcks, nbRetry));
105+ logDecision(RETRYING_ON_WRITE_TIMEOUT, host(decision), cl(cl, decision), cl, writeType, requiredAcks, receivedAcks, nbRetry);
79106 break;
80107 }
81108 return decision;
@@ -86,12 +113,24 @@
86113 RetryDecision decision = policy.onUnavailable(statement, cl, requiredReplica, aliveReplica, nbRetry);
87114 switch (decision.getType()) {
88115 case IGNORE:
89- String f1 = "Ignoring unavailable exception (initial consistency: %s, required replica: %d, alive replica: %d, retries: %d)";
90- logger.info(String.format(f1, cl, requiredReplica, aliveReplica, nbRetry));
116+ logDecision(IGNORING_UNAVAILABLE, cl, requiredReplica, aliveReplica, nbRetry);
117+ break;
118+ case RETRY:
119+ logDecision(RETRYING_ON_UNAVAILABLE, host(decision), cl(cl, decision), cl, requiredReplica, aliveReplica, nbRetry);
120+ break;
121+ }
122+ return decision;
123+ }
124+
125+ @Override
126+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
127+ RetryDecision decision = policy.onRequestError(statement, cl, e, nbRetry);
128+ switch (decision.getType()) {
129+ case IGNORE:
130+ logDecision(IGNORING_REQUEST_ERROR, cl, nbRetry, e);
91131 break;
92132 case RETRY:
93- String f2 = "Retrying on unavailable exception at consistency %s (initial consistency: %s, required replica: %d, alive replica: %d, retries: %d)";
94- logger.info(String.format(f2, cl(cl, decision), cl, requiredReplica, aliveReplica, nbRetry));
133+ logDecision(RETRYING_ON_REQUEST_ERROR, host(decision), cl(cl, decision), cl, nbRetry, e);
95134 break;
96135 }
97136 return decision;
@@ -106,4 +145,17 @@
106145 public void close() {
107146 policy.close();
108147 }
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+
109161 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/RetryPolicy.java +60 −27
@@ -15,14 +15,11 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.datastax.driver.core.Cluster;
19-import com.datastax.driver.core.ConsistencyLevel;
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;
2220
2321 /**
24- * A policy that defines a default behavior to adopt when a request returns
25- * a TimeoutException or an UnavailableException.
22+ * A policy that defines a default behavior to adopt when a request fails.
2623 *
2724 * Such policy allows to centralize the handling of query retries, allowing to
2825 * minimize the need for exception catching/handling in business code.
@@ -33,9 +30,9 @@
3330 * A retry decision to adopt on a Cassandra exception (read/write timeout
3431 * or unavailable exception).
3532 * <p>
36- * There is three possible decision:
33+ * There are three possible decisions:
3734 * <ul>
38- * <li>RETHROW: no retry should be attempted and an exception should be thrown</li>
35+ * <li>RETHROW: no retry should be attempted and an exception should be thrown.</li>
3936 * <li>RETRY: the operation will be retried. The consistency level of the
4037 * retry should be specified.</li>
4138 * <li>IGNORE: no retry should be attempted and the exception should be
@@ -45,9 +42,9 @@
4542 */
4643 class RetryDecision {
4744 /**
48- * The type of retry decisions.
45+ * The types of retry decisions.
4946 */
50- public enum Type { RETRY, RETHROW, IGNORE };
47+ public enum Type { RETRY, RETHROW, IGNORE }
5148
5249 private final Type type;
5350 private final ConsistencyLevel retryCL;
@@ -69,57 +66,67 @@
6966 }
7067
7168 /**
72- * The consistency level for a retry decision.
69+ * The consistency level for this retry decision.
70+ * This is only meaningful for {@code RETRY} decisions.
71+ * The consistency level is always {@code null} for an
72+ * {@code IGNORE} or a {@code RETHROW} decision;
73+ * for a {@code RETRY} decision, the consistency level can be {@code null},
74+ * in which case the retry is done at the same consistency level
75+ * as in the original attempt.
7376 *
74- * @return the consistency level for a retry decision or {@code null}
75- * if this retry decision is an {@code IGNORE} or a {@code RETHROW}.
77+ * @return the consistency level for a retry decision.
7678 */
7779 public ConsistencyLevel getRetryConsistencyLevel() {
7880 return retryCL;
7981 }
8082
8183 /**
82- * Whether the retry policy uses the same host for retry decision.
84+ * Whether this decision is to retry the same host.
85+ * This is only meaningful for {@code RETRY} decisions.
8386 *
84- * @return the retry on next host boolean. Default is false.
87+ * @return {@code true} if the decision is to retry the same host,
88+ * {@code false} otherwise. Default is {@code false}.
8589 */
8690 public boolean isRetryCurrent() {
8791 return retryCurrent;
8892 }
8993
9094 /**
91- * Creates a RETHROW retry decision.
95+ * Creates a {@link RetryDecision.Type#RETHROW} retry decision.
9296 *
93- * @return a RETHROW retry decision.
97+ * @return a {@link RetryDecision.Type#RETHROW} retry decision.
9498 */
9599 public static RetryDecision rethrow() {
96100 return new RetryDecision(Type.RETHROW, null, true);
97101 }
98102
99103 /**
100- * Creates a RETRY retry decision using the provided consistency level.
104+ * Creates a {@link RetryDecision.Type#RETRY} retry decision using
105+ * the same host and the provided consistency level.
101106 *
102107 * @param consistency the consistency level to use for the retry.
103- * @return a RETRY with consistency level {@code consistency} retry decision.
108+ * @return a {@link RetryDecision.Type#RETRY} decision using
109+ * the same host and the provided consistency level
104110 */
105111 public static RetryDecision retry(ConsistencyLevel consistency) {
106112 return new RetryDecision(Type.RETRY, consistency, true);
107113 }
108114
109115 /**
110- * Creates an IGNORE retry decision.
116+ * Creates an {@link RetryDecision.Type#IGNORE} retry decision.
111117 *
112- * @return an IGNORE retry decision.
118+ * @return an {@link RetryDecision.Type#IGNORE} retry decision.
113119 */
114120 public static RetryDecision ignore() {
115121 return new RetryDecision(Type.IGNORE, null, true);
116122 }
117123
118124 /**
119- * Creates a RETRY retry decision and indicates to retry on another host
120- * using the provided consistency level.
125+ * Creates a {@link RetryDecision.Type#RETRY} retry decision using the next host
126+ * in the query plan, and using the provided consistency level.
121127 *
122- * @return a RETRY retry decision.
128+ * @return a {@link RetryDecision.Type#RETRY} retry decision using the next host
129+ * in the query plan, and using the provided consistency level.
123130 */
124131 public static RetryDecision tryNextHost(ConsistencyLevel retryCL) {
125132 return new RetryDecision(Type.RETRY, retryCL, false);
@@ -157,7 +164,7 @@
157164 * a {@link com.datastax.driver.core.exceptions.ReadTimeoutException} will
158165 * be thrown for the operation.
159166 */
160- public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry);
167+ RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry);
161168
162169 /**
163170 * Defines whether to retry and at which consistency level on a write timeout.
@@ -174,7 +181,7 @@
174181 * a {@link com.datastax.driver.core.exceptions.WriteTimeoutException} will
175182 * be thrown for the operation.
176183 */
177- public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry);
184+ RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry);
178185
179186 /**
180187 * Defines whether to retry and at which consistency level on an
@@ -192,7 +199,33 @@
192199 * an {@link com.datastax.driver.core.exceptions.UnavailableException} will
193200 * be thrown for the operation.
194201 */
195- public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry);
202+ RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry);
203+
204+ /**
205+ * Defines whether to retry and at which consistency level on an
206+ * unexpected error.
207+ * <p>
208+ * This method might be invoked in the following situations:
209+ * <ol>
210+ * <li>On a client timeout, while waiting for the server response
211+ * (see {@link SocketOptions#getReadTimeoutMillis()});</li>
212+ * <li>On a connection error (socket closed, etc.);</li>
213+ * <li>When the contacted host replies with an error, such as
214+ * {@code OVERLOADED}, {@code IS_BOOTSTRAPPING}, {@code SERVER_ERROR}, etc.</li>
215+ * </ol>
216+ *
217+ * Note that when this method is invoked, <em>the driver cannot guarantee that the mutation has
218+ * been effectively applied server-side</em>; a retry should only be attempted if the request
219+ * is known to be idempotent.
220+ *
221+ * @param statement the original query that failed.
222+ * @param cl the original consistency level for the operation.
223+ * @param e the exception that caused this request to fail.
224+ * @param nbRetry the number of retries already performed for this operation.
225+ * @return the retry decision. If {@code RetryDecision.RETHROW} is returned,
226+ * the {@link DriverException} passed to this method will be thrown for the operation.
227+ */
228+ RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry);
196229
197230 /**
198231 * Gets invoked at cluster startup.
modified driver-core/src/test/java/com/datastax/driver/core/MetricsTest.java +6 −0
@@ -29,6 +29,7 @@
2929 import static org.testng.Assert.assertEquals;
3030
3131 import com.datastax.driver.core.Metrics.Errors;
32+import com.datastax.driver.core.exceptions.DriverException;
3233 import com.datastax.driver.core.policies.RetryPolicy;
3334 import com.datastax.driver.core.policies.RetryPolicy.RetryDecision;
3435
@@ -57,6 +58,11 @@
5758 return retryDecision;
5859 }
5960
61+ @Override
62+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
63+ return retryDecision;
64+ }
65+
6066 @Override
6167 public void init(Cluster cluster) {}
6268
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +1 −2
@@ -131,7 +131,7 @@
131131 .contains(ip)
132132 .contains(Integer.toString(scassandra.getBinaryPort()))
133133 .contains(query)
134- .contains(OperationTimedOutException.class.getName());
134+ .contains("Timed out waiting for server response");
135135 }
136136
137137 @DataProvider(name="errors")
@@ -174,7 +174,6 @@
174174 } catch(Exception e) {
175175 if(e instanceof NoHostAvailableException) {
176176 assertThat(expectedException).isEqualTo(NoHostAvailableException.class);
177- // ok
178177 Throwable error = ((NoHostAvailableException)e).getErrors().get(hostAddress);
179178 assertThat(error).isNotNull().isOfAnyClassIn(loggedException);
180179 } else {
modified driver-core/src/test/java/com/datastax/driver/core/SpeculativeExecutionTest.java +16 −8
@@ -15,25 +15,28 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
18+import java.util.List;
19+import java.util.Map;
1920
20-import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2121 import com.google.common.collect.ImmutableList;
2222 import com.google.common.collect.ImmutableMap;
23-import org.scassandra.Scassandra;
2423 import org.scassandra.http.client.PrimingRequest;
25-import org.testng.annotations.*;
24+import org.testng.annotations.AfterMethod;
25+import org.testng.annotations.BeforeMethod;
26+import org.testng.annotations.Test;
27+
28+import static org.mockito.Mockito.mock;
29+import static org.mockito.Mockito.times;
30+import static org.mockito.Mockito.verify;
2631
32+import com.datastax.driver.core.exceptions.DriverException;
2733 import com.datastax.driver.core.policies.ConstantSpeculativeExecutionPolicy;
2834 import com.datastax.driver.core.policies.RetryPolicy;
35+import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
2936
3037 import static com.datastax.driver.core.Assertions.assertThat;
3138 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3239
33-import static org.mockito.Mockito.mock;
34-import static org.mockito.Mockito.times;
35-import static org.mockito.Mockito.verify;
36-
3740 public class SpeculativeExecutionTest {
3841 ScassandraCluster scassandras;
3942
@@ -243,6 +246,11 @@
243246 return RetryDecision.rethrow();
244247 }
245248
249+ @Override
250+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
251+ return RetryDecision.tryNextHost(cl);
252+ }
253+
246254 @Override
247255 public void init(Cluster cluster) {}
248256
modified driver-core/src/test/java/com/datastax/driver/core/StatementWrapperTest.java +7 −1
@@ -24,6 +24,7 @@
2424
2525 import static org.assertj.core.api.Assertions.assertThat;
2626
27+import com.datastax.driver.core.exceptions.DriverException;
2728 import com.datastax.driver.core.policies.*;
2829
2930 public class StatementWrapperTest extends CCMBridge.PerClassSingleNodeCluster {
@@ -144,6 +145,11 @@
144145 return RetryDecision.rethrow();
145146 }
146147
148+ @Override
149+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
150+ return RetryDecision.tryNextHost(cl);
151+ }
152+
147153 @Override
148154 public void init(Cluster cluster) {
149155 // nothing to do
@@ -154,4 +160,4 @@
154160 // nothing to do
155161 }
156162 }
157-}
No newline at the end of the file
163+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +14 −3
@@ -23,9 +23,7 @@
2323 import org.mockito.Mockito;
2424 import org.scassandra.Scassandra;
2525 import org.scassandra.http.client.PrimingRequest;
26-import org.testng.annotations.AfterClass;
2726 import org.testng.annotations.AfterMethod;
28-import org.testng.annotations.BeforeClass;
2927 import org.testng.annotations.BeforeMethod;
3028
3129 import static org.assertj.core.api.Assertions.assertThat;
@@ -35,6 +33,7 @@
3533 import static org.mockito.Mockito.times;
3634
3735 import com.datastax.driver.core.*;
36+import com.datastax.driver.core.exceptions.DriverException;
3837
3938 import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
4039
@@ -57,7 +56,14 @@
5756
5857 protected RetryPolicy retryPolicy;
5958
59+ protected AbstractRetryPolicyIntegrationTest() {
60+ }
61+
6062 protected AbstractRetryPolicyIntegrationTest(RetryPolicy retryPolicy) {
63+ setRetryPolicy(retryPolicy);
64+ }
65+
66+ protected final void setRetryPolicy(RetryPolicy retryPolicy) {
6167 this.retryPolicy = Mockito.spy(retryPolicy);
6268 }
6369
@@ -108,7 +114,7 @@
108114 .build());
109115 }
110116
111- private static List<Map<String, ?>> row(String key, String value) {
117+ protected static List<Map<String, ?>> row(String key, String value) {
112118 return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value));
113119 }
114120
@@ -136,6 +142,11 @@
136142 any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
137143 }
138144
145+ protected void assertOnRequestErrorWasCalled(int times, Class<? extends DriverException> expected) {
146+ Mockito.verify(retryPolicy, times(times)).onRequestError(
147+ any(Statement.class), any(ConsistencyLevel.class), any(expected), anyInt());
148+ }
149+
139150 protected void assertQueried(int hostNumber, int times) {
140151 assertThat(scassandras.node(hostNumber).activityClient().retrieveQueries()).hasSize(times);
141152 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +74 −5
@@ -15,15 +15,18 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import org.scassandra.http.client.PrimingRequest;
19+import org.testng.annotations.DataProvider;
1820 import org.testng.annotations.Test;
1921
20-import static org.assertj.core.api.Assertions.assertThat;
21-import static org.assertj.core.api.Assertions.fail;
22-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
23-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
22+import static org.assertj.core.api.Fail.fail;
23+import static org.scassandra.http.client.PrimingRequest.Result.*;
24+import static org.scassandra.http.client.PrimingRequest.then;
2425
2526 import com.datastax.driver.core.*;
26-import com.datastax.driver.core.exceptions.UnavailableException;
27+import com.datastax.driver.core.exceptions.*;
28+
29+import static com.datastax.driver.core.Assertions.assertThat;
2730
2831 /**
2932 * Integration test with a custom implementation, to test retry and ignore decisions.
@@ -41,6 +44,9 @@
4144 assertThat(rs.iterator().hasNext()).isFalse(); // ignore decisions produce empty result sets
4245
4346 assertOnReadTimeoutWasCalled(1);
47+ assertThat(errors.getIgnores().getCount()).isEqualTo(1);
48+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
49+ assertThat(errors.getIgnoresOnReadTimeout().getCount()).isEqualTo(1);
4450 assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
4551 assertQueried(1, 1);
4652 assertQueried(2, 0);
@@ -57,14 +63,72 @@
5763 } catch (UnavailableException e) {/*expected*/}
5864
5965 assertOnUnavailableWasCalled(2);
66+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
67+ assertThat(errors.getUnavailables().getCount()).isEqualTo(2);
6068 assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
6169 assertQueried(1, 2);
6270 assertQueried(2, 0);
6371 assertQueried(3, 0);
6472 }
6573
74+ @Test(groups = "short")
75+ public void should_rethrow_on_client_timeouts() {
76+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
77+ try {
78+ scassandras
79+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
80+ .withQuery("mock query")
81+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
82+ .build());
83+ try {
84+ query();
85+ fail("expected an OperationTimedOutException");
86+ } catch (OperationTimedOutException e) {
87+ assertThat(e.getMessage()).isEqualTo(
88+ String.format("[%s] Timed out waiting for server response", host1.getAddress())
89+ );
90+ }
91+ assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
92+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
93+ assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1);
94+ assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(0);
95+ assertQueried(1, 1);
96+ assertQueried(2, 0);
97+ assertQueried(3, 0);
98+ } finally {
99+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
100+ }
101+ }
102+
103+ @DataProvider
104+ public static Object[][] serverSideErrors() {
105+ return new Object[][]{
106+ {server_error, ServerError.class},
107+ {overloaded, OverloadedException.class}
108+ };
109+ }
110+
111+ @Test(groups = "short", dataProvider = "serverSideErrors")
112+ public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) {
113+ simulateError(1, error);
114+ try {
115+ query();
116+ fail("expected a DriverException");
117+ } catch (DriverException e) {
118+ assertThat(e).isInstanceOf(exception);
119+ }
120+ assertOnRequestErrorWasCalled(1, exception);
121+ assertThat(errors.getOthers().getCount()).isEqualTo(1);
122+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
123+ assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(0);
124+ assertQueried(1, 1);
125+ assertQueried(2, 0);
126+ assertQueried(3, 0);
127+ }
128+
66129 /**
67130 * Ignores read and write timeouts, and retries at most once on unavailable.
131+ * Rethrows for unexpected errors.
68132 */
69133 static class CustomRetryPolicy implements RetryPolicy {
70134
@@ -85,6 +149,11 @@
85149 : RetryDecision.rethrow();
86150 }
87151
152+ @Override
153+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
154+ return RetryDecision.rethrow();
155+ }
156+
88157 @Override
89158 public void init(Cluster cluster) {/*nothing to do*/}
90159
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +95 −8
@@ -16,20 +16,18 @@
1616 package com.datastax.driver.core.policies;
1717
1818 import com.datastax.driver.core.*;
19-import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.exceptions.*;
2020
21+import org.assertj.core.api.Fail;
2122 import org.scassandra.Scassandra;
23+import org.scassandra.http.client.PrimingRequest;
24+import org.testng.annotations.DataProvider;
2225 import org.testng.annotations.Test;
2326
2427 import static org.assertj.core.api.Assertions.assertThat;
2528 import static org.assertj.core.api.Assertions.fail;
26-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
27-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
28-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
29-
30-import com.datastax.driver.core.exceptions.ReadTimeoutException;
31-import com.datastax.driver.core.exceptions.UnavailableException;
32-import com.datastax.driver.core.exceptions.WriteTimeoutException;
29+import static org.scassandra.http.client.PrimingRequest.Result.*;
30+import static org.scassandra.http.client.PrimingRequest.then;
3331
3432 import java.util.Collections;
3533
@@ -48,6 +46,8 @@
4846 } catch (ReadTimeoutException e) {/*expected*/ }
4947
5048 assertOnReadTimeoutWasCalled(1);
49+ assertThat(errors.getReadTimeouts().getCount()).isEqualTo(1);
50+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
5151 assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
5252 assertQueried(1, 1);
5353 assertQueried(2, 0);
@@ -64,6 +64,8 @@
6464 } catch (WriteTimeoutException e) {/*expected*/}
6565
6666 assertOnWriteTimeoutWasCalled(1);
67+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1);
68+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
6769 assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0);
6870 assertQueried(1, 1);
6971 assertQueried(2, 0);
@@ -78,6 +80,8 @@
7880 query();
7981
8082 assertOnUnavailableWasCalled(1);
83+ assertThat(errors.getUnavailables().getCount()).isEqualTo(1);
84+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
8185 assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
8286 assertQueried(1, 1);
8387 assertQueried(2, 1);
@@ -95,6 +99,8 @@
9599 } catch (UnavailableException e) {/*expected*/}
96100
97101 assertOnUnavailableWasCalled(2);
102+ assertThat(errors.getUnavailables().getCount()).isEqualTo(2);
103+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
98104 assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
99105 assertQueried(1, 1);
100106 assertQueried(2, 1);
@@ -145,4 +151,85 @@
145151 whiteListedCluster.close();
146152 }
147153 }
154+
155+ @Test(groups = "short")
156+ public void should_try_next_host_on_client_timeouts() {
157+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
158+ try {
159+ scassandras
160+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
161+ .withQuery("mock query")
162+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
163+ .build());
164+ scassandras
165+ .node(2).primingClient().prime(PrimingRequest.queryBuilder()
166+ .withQuery("mock query")
167+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result2")))
168+ .build());
169+ scassandras
170+ .node(3).primingClient().prime(PrimingRequest.queryBuilder()
171+ .withQuery("mock query")
172+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result3")))
173+ .build());
174+ try {
175+ query();
176+ fail("expected a NoHostAvailableException");
177+ } catch (NoHostAvailableException e) {
178+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnlyOnce(
179+ host1.getSocketAddress(),
180+ host2.getSocketAddress(),
181+ host3.getSocketAddress());
182+ assertThat(e.getErrors().values())
183+ .hasOnlyElementsOfType(OperationTimedOutException.class)
184+ .extractingResultOf("getMessage")
185+ .containsOnlyOnce(
186+ String.format("[%s] Timed out waiting for server response", host1.getAddress()),
187+ String.format("[%s] Timed out waiting for server response", host2.getAddress()),
188+ String.format("[%s] Timed out waiting for server response", host3.getAddress())
189+ );
190+ }
191+ assertOnRequestErrorWasCalled(3, OperationTimedOutException.class);
192+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
193+ assertThat(errors.getClientTimeouts().getCount()).isEqualTo(3);
194+ assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(3);
195+ assertQueried(1, 1);
196+ assertQueried(2, 1);
197+ assertQueried(3, 1);
198+ } finally {
199+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
200+ }
201+ }
202+
203+ @DataProvider
204+ public static Object[][] serverSideErrors() {
205+ return new Object[][]{
206+ {server_error, ServerError.class},
207+ {overloaded, OverloadedException.class}
208+ };
209+ }
210+
211+ @Test(groups = "short", dataProvider = "serverSideErrors")
212+ public void should_try_next_host_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) {
213+ simulateError(1, error);
214+ simulateError(2, error);
215+ simulateError(3, error);
216+ try {
217+ query();
218+ Fail.fail("expected a NoHostAvailableException");
219+ } catch (NoHostAvailableException e) {
220+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnlyOnce(
221+ host1.getSocketAddress(),
222+ host2.getSocketAddress(),
223+ host3.getSocketAddress());
224+ assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception);
225+ }
226+ assertOnRequestErrorWasCalled(3, exception);
227+ assertThat(errors.getOthers().getCount()).isEqualTo(3);
228+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
229+ assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(3);
230+ assertQueried(1, 1);
231+ assertQueried(2, 1);
232+ assertQueried(3, 1);
233+ }
234+
148235 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +63 −6
@@ -15,17 +15,18 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18+import org.assertj.core.api.Fail;
19+import org.scassandra.http.client.PrimingRequest;
20+import org.testng.annotations.DataProvider;
1821 import org.testng.annotations.Test;
1922
2023 import static org.assertj.core.api.Assertions.assertThat;
2124 import static org.assertj.core.api.Assertions.fail;
22-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
23-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
24-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
25+import static org.scassandra.http.client.PrimingRequest.Result.*;
26+import static org.scassandra.http.client.PrimingRequest.then;
2527
26-import com.datastax.driver.core.exceptions.ReadTimeoutException;
27-import com.datastax.driver.core.exceptions.UnavailableException;
28-import com.datastax.driver.core.exceptions.WriteTimeoutException;
28+import com.datastax.driver.core.SocketOptions;
29+import com.datastax.driver.core.exceptions.*;
2930
3031 public class FallthroughRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
3132 public FallthroughRetryPolicyIntegrationTest() {
@@ -79,4 +80,60 @@
7980 assertQueried(2, 0);
8081 assertQueried(3, 0);
8182 }
83+
84+ @Test(groups = "short")
85+ public void should_rethrow_on_client_timeouts() {
86+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
87+ try {
88+ scassandras
89+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
90+ .withQuery("mock query")
91+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
92+ .build());
93+ try {
94+ query();
95+ Fail.fail("expected an OperationTimedOutException");
96+ } catch (OperationTimedOutException e) {
97+ assertThat(e.getMessage()).isEqualTo(
98+ String.format("[%s] Timed out waiting for server response", host1.getAddress())
99+ );
100+ }
101+ assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
102+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
103+ assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1);
104+ assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(0);
105+ assertQueried(1, 1);
106+ assertQueried(2, 0);
107+ assertQueried(3, 0);
108+ } finally {
109+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
110+ }
111+ }
112+
113+ @DataProvider
114+ public static Object[][] serverSideErrors() {
115+ return new Object[][]{
116+ {server_error, ServerError.class},
117+ {overloaded, OverloadedException.class}
118+ };
119+ }
120+
121+ @Test(groups = "short", dataProvider = "serverSideErrors")
122+ public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) {
123+ simulateError(1, error);
124+ try {
125+ query();
126+ Fail.fail("expected a DriverException");
127+ } catch (DriverException e) {
128+ assertThat(e).isInstanceOf(exception);
129+ }
130+ assertOnRequestErrorWasCalled(1, ServerError.class);
131+ assertThat(errors.getOthers().getCount()).isEqualTo(1);
132+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
133+ assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(0);
134+ assertQueried(1, 1);
135+ assertQueried(2, 0);
136+ assertQueried(3, 0);
137+ }
138+
82139 }
added driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +214 −0
@@ -0,0 +1,214 @@
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 org.scassandra.http.client.PrimingRequest;
19+import org.testng.annotations.BeforeMethod;
20+import org.testng.annotations.DataProvider;
21+import org.testng.annotations.Test;
22+
23+import static org.assertj.core.api.Assertions.assertThat;
24+import static org.assertj.core.api.Assertions.fail;
25+import static org.scassandra.http.client.PrimingRequest.Result.overloaded;
26+import static org.scassandra.http.client.PrimingRequest.Result.server_error;
27+import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
28+import static org.scassandra.http.client.PrimingRequest.then;
29+
30+import com.datastax.driver.core.*;
31+import com.datastax.driver.core.exceptions.*;
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()));
40+ }
41+
42+ @BeforeMethod(groups = "short")
43+ public void setUpDefaultIdempotence(){
44+ cluster.getConfiguration().getQueryOptions().setDefaultIdempotence(false);
45+ }
46+
47+ @Test(groups = "short")
48+ public void should_not_retry_on_write_timeout_if_statement_non_idempotent() {
49+ simulateError(1, write_request_timeout);
50+ try {
51+ query();
52+ fail("expected an WriteTimeoutException");
53+ } catch (WriteTimeoutException e) {/* expected */}
54+ assertOnWriteTimeoutWasCalled(1);
55+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1);
56+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
57+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0);
58+ assertQueried(1, 1);
59+ assertQueried(2, 0);
60+ assertQueried(3, 0);
61+ }
62+
63+ @Test(groups = "short")
64+ public void should_retry_on_write_timeout_if_statement_idempotent() {
65+ simulateError(1, write_request_timeout);
66+ session.execute(session.newSimpleStatement("mock query").setIdempotent(true));
67+ assertOnWriteTimeoutWasCalled(1);
68+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1);
69+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
70+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(1);
71+ assertQueried(1, 1);
72+ assertQueried(2, 1);
73+ assertQueried(3, 0);
74+ }
75+
76+ @Test(groups = "short")
77+ public void should_not_retry_on_client_timeout_if_statement_non_idempotent() {
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 an OperationTimedOutException");
88+ } catch (OperationTimedOutException e) {
89+ assertThat(e.getMessage()).isEqualTo(
90+ String.format("[%s] Timed out waiting for server response", host1.getAddress())
91+ );
92+ }
93+ assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
94+ assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1);
95+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
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+ @Test(groups = "short")
106+ public void should_retry_on_client_timeout_if_statement_idempotent() {
107+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
108+ try {
109+ scassandras
110+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
111+ .withQuery("mock query")
112+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
113+ .build());
114+ session.execute(session.newSimpleStatement("mock query").setIdempotent(true));
115+ assertOnRequestErrorWasCalled(1, OperationTimedOutException.class);
116+ assertThat(errors.getClientTimeouts().getCount()).isEqualTo(1);
117+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
118+ assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(1);
119+ assertQueried(1, 1);
120+ assertQueried(2, 1);
121+ assertQueried(3, 0);
122+ } finally {
123+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
124+ }
125+ }
126+
127+ @DataProvider
128+ public static Object[][] serverSideErrors() {
129+ return new Object[][]{
130+ {server_error, ServerError.class},
131+ {overloaded, OverloadedException.class}
132+ };
133+ }
134+
135+ @Test(groups = "short", dataProvider = "serverSideErrors")
136+ public void should_not_retry_on_server_error_if_statement_non_idempotent(PrimingRequest.Result error, Class<? extends DriverException> exception) {
137+ simulateError(1, error);
138+ try {
139+ query();
140+ fail("expected " + exception);
141+ } catch (DriverException e) {
142+ assertThat(e).isInstanceOf(exception);
143+ }
144+ assertOnRequestErrorWasCalled(1, ServerError.class);
145+ assertThat(errors.getOthers().getCount()).isEqualTo(1);
146+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
147+ assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(0);
148+ assertQueried(1, 1);
149+ assertQueried(2, 0);
150+ assertQueried(3, 0);
151+ }
152+
153+ @SuppressWarnings("UnusedParameters")
154+ @Test(groups = "short", dataProvider = "serverSideErrors")
155+ public void should_retry_on_server_error_if_statement_idempotent(PrimingRequest.Result error, Class<? extends DriverException> exception) {
156+ simulateError(1, error);
157+ simulateError(2, error);
158+ simulateError(3, error);
159+ try {
160+ session.execute(session.newSimpleStatement("mock query").setIdempotent(true));
161+ fail("expected a NoHostAvailableException");
162+ } catch (NoHostAvailableException e) {
163+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
164+ host1.getSocketAddress(),
165+ host2.getSocketAddress(),
166+ host3.getSocketAddress());
167+ assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception);
168+ }
169+ assertOnRequestErrorWasCalled(3, exception);
170+ assertThat(errors.getOthers().getCount()).isEqualTo(3);
171+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
172+ assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(3);
173+ assertQueried(1, 1);
174+ assertQueried(2, 1);
175+ assertQueried(3, 1);
176+ }
177+
178+ /**
179+ * Retries everything on the next host.
180+ */
181+ static class CustomRetryPolicy implements RetryPolicy {
182+
183+ @Override
184+ public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
185+ return RetryDecision.tryNextHost(cl);
186+ }
187+
188+ @Override
189+ public RetryDecision onWriteTimeout(Statement statement, ConsistencyLevel cl, WriteType writeType, int requiredAcks, int receivedAcks, int nbRetry) {
190+ return RetryDecision.tryNextHost(cl);
191+ }
192+
193+ @Override
194+ public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
195+ return RetryDecision.tryNextHost(cl);
196+ }
197+
198+ @Override
199+ public RetryDecision onRequestError(Statement statement, ConsistencyLevel cl, DriverException e, int nbRetry) {
200+ return RetryDecision.tryNextHost(cl);
201+ }
202+
203+ @Override
204+ public void init(Cluster cluster) {
205+ // nothing to do
206+ }
207+
208+ @Override
209+ public void close() {
210+ // nothing to do
211+ }
212+
213+ }
214+}
added driver-core/src/test/java/com/datastax/driver/core/policies/LoggingRetryPolicyIntegrationTest.java +189 −0
@@ -0,0 +1,189 @@
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 org.apache.log4j.Level;
19+import org.apache.log4j.Logger;
20+import org.slf4j.helpers.MessageFormatter;
21+import org.testng.annotations.*;
22+
23+import static org.apache.log4j.Level.INFO;
24+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
25+import static org.scassandra.http.client.PrimingRequest.Result.server_error;
26+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
27+import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
28+
29+import com.datastax.driver.core.*;
30+import com.datastax.driver.core.exceptions.DriverException;
31+import com.datastax.driver.core.exceptions.ServerError;
32+
33+import static com.datastax.driver.core.Assertions.assertThat;
34+import static com.datastax.driver.core.ConsistencyLevel.LOCAL_ONE;
35+import static com.datastax.driver.core.WriteType.SIMPLE;
36+import static com.datastax.driver.core.policies.LoggingRetryPolicy.*;
37+import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.ignore;
38+import static com.datastax.driver.core.policies.RetryPolicy.RetryDecision.tryNextHost;
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 RetryPolicy {
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, DriverException e, int nbRetry) {
175+ return retryDecision;
176+ }
177+
178+ @Override
179+ public void init(Cluster cluster) {
180+ // nothing to do
181+ }
182+
183+ @Override
184+ public void close() {
185+ // nothing to do
186+ }
187+
188+ }
189+}
modified upgrade_guide/README.md +8 −0
@@ -235,6 +235,14 @@
235235 and now the `PreparedStatement` interface exposes 2 new methods,
236236 `setIdempotent(Boolean)` and `isIdempotent()`.
237237
238+22. `RetryPolicy` and `ExtendedRetryPolicy` (introduced in 2.1.10)
239+ were merged together; as a consequence, `RetryPolicy` now has one
240+ more method: `onRequestError`; see
241+ [JAVA-819](https://datastax-oss.atlassian.net/browse/JAVA-819) for
242+ more information. Furthermore, `FallthroughRetryPolicy` now returns
243+ `RetryDecision.rethrow()` when `onRequestError` is called.
244+
245+
238246 ### 2.1.8
239247
240248 2.1.8 is binary-compatible with 2.1.7 but introduces a small change in the