Elffuss BraidHub

kikocis/java-driver public

Merge pull request #542 from datastax/java819-3.0

JAVA-819: [3.0] Driver shouldn't retry on client timeout if statement is not idempotent.
Changeset90375e85200e9fdd074d5562c494b0c107188d8132f8fd636522f6e399c56b13
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-12-04 19:13 +01:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-12-04 19:13 +01:00
Parentsb4554bb54c38, 51433ff5ddfe

Browse the files at this changeset

67 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/AbstractReconnectionHandler.java +5 −3
@@ -25,6 +25,8 @@
2525 import org.slf4j.LoggerFactory;
2626
2727 import com.datastax.driver.core.exceptions.AuthenticationException;
28+import com.datastax.driver.core.exceptions.ConnectionException;
29+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
2830 import com.datastax.driver.core.policies.ReconnectionPolicy;
2931
3032 /**
@@ -140,7 +142,7 @@
140142 if (onAuthenticationException(e, nextDelay)) {
141143 reschedule(nextDelay);
142144 } else {
143- logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.getHost());
145+ logger.error("Retries against {} have been suspended. It won't be retried unless the node is restarted.", e.getHost());
144146 currentAttempt.compareAndSet(handlerFuture, null);
145147 }
146148 } catch (InterruptedException e) {
@@ -151,7 +153,7 @@
151153 if (onUnsupportedProtocolVersionException(e, nextDelay)) {
152154 reschedule(nextDelay);
153155 } else {
154- logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.address);
156+ logger.error("Retries against {} have been suspended. It won't be retried unless the node is restarted.", e.getHost());
155157 currentAttempt.compareAndSet(handlerFuture, null);
156158 }
157159 } catch (ClusterNameMismatchException e) {
@@ -160,7 +162,7 @@
160162 if (onClusterNameMismatchException(e, nextDelay)) {
161163 reschedule(nextDelay);
162164 } else {
163- logger.error("Retry against {} have been suspended. It won't be retried unless the node is restarted.", e.address);
165+ logger.error("Retries against {} have been suspended. It won't be retried unless the node is restarted.", e.address.getAddress());
164166 currentAttempt.compareAndSet(handlerFuture, null);
165167 }
166168 } catch (Exception e) {
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −0
@@ -28,6 +28,7 @@
2828 import org.slf4j.Logger;
2929 import org.slf4j.LoggerFactory;
3030
31+import com.datastax.driver.core.exceptions.ConnectionException;
3132 import com.datastax.driver.core.exceptions.DriverInternalError;
3233
3334 /**
deleted driver-core/src/main/java/com/datastax/driver/core/BusyConnectionException.java +0 −25
@@ -1,25 +0,0 @@
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;
17-
18-class BusyConnectionException extends Exception
19-{
20- private static final long serialVersionUID = 0;
21-
22- public BusyConnectionException() {
23- super();
24- }
25-}
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +5 −8
@@ -34,10 +34,7 @@
3434 import org.slf4j.Logger;
3535 import org.slf4j.LoggerFactory;
3636
37-import com.datastax.driver.core.exceptions.AuthenticationException;
38-import com.datastax.driver.core.exceptions.DriverInternalError;
39-import com.datastax.driver.core.exceptions.InvalidQueryException;
40-import com.datastax.driver.core.exceptions.NoHostAvailableException;
37+import com.datastax.driver.core.exceptions.*;
4138 import com.datastax.driver.core.policies.*;
4239 import com.datastax.driver.core.utils.MoreFutures;
4340
@@ -1404,9 +1401,9 @@
14041401 try {
14051402 controlConnection.connect();
14061403 } catch (UnsupportedProtocolVersionException e) {
1407- logger.debug("Cannot connect with protocol {}, trying {}", e.unsupportedVersion, e.serverVersion);
1404+ logger.debug("Cannot connect with protocol {}, trying {}", e.getUnsupportedVersion(), e.getServerVersion());
14081405
1409- connectionFactory.protocolVersion = e.serverVersion;
1406+ connectionFactory.protocolVersion = e.getServerVersion();
14101407 try {
14111408 controlConnection.connect();
14121409 } catch (UnsupportedProtocolVersionException e1) {
@@ -1682,7 +1679,7 @@
16821679 Thread.currentThread().interrupt();
16831680 // Don't propagate because we don't want to prevent other listener to run
16841681 } catch (UnsupportedProtocolVersionException e) {
1685- logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1682+ logUnsupportedVersionProtocol(host, e.getUnsupportedVersion());
16861683 return;
16871684 } catch (ClusterNameMismatchException e) {
16881685 logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
@@ -1969,7 +1966,7 @@
19691966 Thread.currentThread().interrupt();
19701967 // Don't propagate because we don't want to prevent other listener to run
19711968 } catch (UnsupportedProtocolVersionException e) {
1972- logUnsupportedVersionProtocol(host, e.unsupportedVersion);
1969+ logUnsupportedVersionProtocol(host, e.getUnsupportedVersion());
19731970 return;
19741971 } catch (ClusterNameMismatchException e) {
19751972 logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +3 −3
@@ -47,9 +47,7 @@
4747 import static io.netty.handler.timeout.IdleState.ALL_IDLE;
4848
4949 import com.datastax.driver.core.Responses.Result.SetKeyspace;
50-import com.datastax.driver.core.exceptions.AuthenticationException;
51-import com.datastax.driver.core.exceptions.DriverException;
52-import com.datastax.driver.core.exceptions.DriverInternalError;
50+import com.datastax.driver.core.exceptions.*;
5351 import com.datastax.driver.core.utils.MoreFutures;
5452
5553 import static com.datastax.driver.core.Message.Response.Type.ERROR;
@@ -1225,6 +1223,8 @@
12251223 public ResponseHandler(Connection connection, ResponseCallback callback) throws BusyConnectionException {
12261224 this.connection = connection;
12271225 this.streamId = connection.dispatcher.streamIdHandler.next();
1226+ if (streamId == -1)
1227+ throw new BusyConnectionException(connection.address);
12281228 this.callback = callback;
12291229 this.retryCount = callback.retryCount();
12301230
deleted driver-core/src/main/java/com/datastax/driver/core/ConnectionException.java +0 −42
@@ -1,42 +0,0 @@
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;
17-
18-import java.net.InetSocketAddress;
19-
20-class ConnectionException extends Exception {
21-
22- private static final long serialVersionUID = 0;
23-
24- public final InetSocketAddress address;
25-
26- public ConnectionException(InetSocketAddress address, String msg, Throwable cause)
27- {
28- super(msg, cause);
29- this.address = address;
30- }
31-
32- public ConnectionException(InetSocketAddress address, String msg)
33- {
34- super(msg);
35- this.address = address;
36- }
37-
38- @Override
39- public String getMessage() {
40- return String.format("[%s] %s", address, super.getMessage());
41- }
42-}
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +1 −3
@@ -28,9 +28,7 @@
2828 import org.slf4j.Logger;
2929 import org.slf4j.LoggerFactory;
3030
31-import com.datastax.driver.core.exceptions.DriverException;
32-import com.datastax.driver.core.exceptions.DriverInternalError;
33-import com.datastax.driver.core.exceptions.NoHostAvailableException;
31+import com.datastax.driver.core.exceptions.*;
3432
3533 import static com.datastax.driver.core.SchemaElement.*;
3634
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +2 −0
@@ -34,6 +34,8 @@
3434 import org.slf4j.LoggerFactory;
3535
3636 import com.datastax.driver.core.exceptions.AuthenticationException;
37+import com.datastax.driver.core.exceptions.ConnectionException;
38+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
3739 import com.datastax.driver.core.utils.MoreFutures;
3840
3941 import static com.datastax.driver.core.Connection.State.GONE;
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
deleted driver-core/src/main/java/com/datastax/driver/core/OperationTimedOutException.java +0 −28
@@ -1,28 +0,0 @@
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;
17-
18-import java.net.InetSocketAddress;
19-
20-/**
21- * Thrown on a client-side timeout, i.e. when the client didn't hear back from the server within
22- * {@link SocketOptions#getReadTimeoutMillis()}.
23- */
24-class OperationTimedOutException extends ConnectionException {
25- public OperationTimedOutException(InetSocketAddress address) {
26- super(address, "Operation timed out");
27- }
28-}
modified driver-core/src/main/java/com/datastax/driver/core/RegularStatement.java +1 −0
@@ -18,6 +18,7 @@
1818 import java.nio.ByteBuffer;
1919
2020 import com.datastax.driver.core.exceptions.InvalidTypeException;
21+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
2122
2223 /**
2324 * A regular (non-prepared and non batched) CQL statement.
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +112 −71
@@ -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,33 +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- DriverException overloaded = new DriverException("Host overloaded");
509- logError(connection.address, overloaded);
510- 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()) {
511542 metrics().getErrorMetrics().getOthers().inc();
512- retry(false, null);
513- 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;
514549 case SERVER_ERROR:
515550 connection.release();
516- // Defunct connection and try another node
517- logger.warn("{} replied with server error ({}), trying next host.", connection.address, err.message);
518- DriverException exception = new DriverException("Host replied with server error: " + err.message);
519- logError(connection.address, exception);
520- connection.defunct(exception);
521- if (metricsEnabled())
551+ assert exceptionToReport instanceof ServerError;
552+ logger.warn("{} replied with server error ({}), defuncting connection.", connection.address, err.message);
553+ // Defunct connection
554+ connection.defunct(exceptionToReport);
555+ retry = retryPolicy.onRequestError(statement,
556+ request().consistency(),
557+ (ServerError)exceptionToReport, retriesByPolicy);
558+ if (metricsEnabled()) {
522559 metrics().getErrorMetrics().getOthers().inc();
523- retry(false, null);
524- 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;
525566 case IS_BOOTSTRAPPING:
526567 connection.release();
527- // Try another node
568+ assert exceptionToReport instanceof BootstrappingException;
528569 logger.error("Query sent to {} but it is bootstrapping. This shouldn't happen but trying next host.", connection.address);
529- DriverException bootstrapping = new DriverException("Host is bootstrapping");
530- logError(connection.address, bootstrapping);
531- if (metricsEnabled())
570+ if (metricsEnabled()) {
532571 metrics().getErrorMetrics().getOthers().inc();
572+ }
573+ logError(connection.address, exceptionToReport);
533574 retry(false, null);
534575 return;
535576 case UNPREPARED:
@@ -575,26 +616,7 @@
575616 if (retry == null)
576617 setFinalResult(connection, response);
577618 else {
578- switch (retry.getType()) {
579- case RETRY:
580- ++retriesByPolicy;
581- if (logger.isDebugEnabled())
582- logger.debug("Doing retry {} for query {} at consistency {}", retriesByPolicy, statement, retry.getRetryConsistencyLevel());
583- if (metricsEnabled())
584- metrics().getErrorMetrics().getRetries().inc();
585- if (!retry.isRetryCurrent())
586- logError(connection.address, exceptionToReport);
587- retry(retry.isRetryCurrent(), retry.getRetryConsistencyLevel());
588- break;
589- case RETHROW:
590- setFinalResult(connection, response);
591- break;
592- case IGNORE:
593- if (metricsEnabled())
594- metrics().getErrorMetrics().getIgnores().inc();
595- setFinalResult(connection, new Responses.Result.Void());
596- break;
597- }
619+ processRetryDecision(retry, connection, exceptionToReport);
598620 }
599621 break;
600622 default:
@@ -612,6 +634,11 @@
612634 }
613635
614636 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.
615642 return new Connection.ResponseCallback() {
616643
617644 @Override
@@ -639,7 +666,6 @@
639666
640667 connection.release();
641668
642- // TODO should we check the response ?
643669 switch (response.type) {
644670 case RESULT:
645671 if (((Responses.Result)response).kind == Responses.Result.Kind.PREPARED) {
@@ -678,7 +704,7 @@
678704 return false;
679705 }
680706 connection.release();
681- logError(connection.address, new DriverException("Timeout waiting for response to prepare message"));
707+ logError(connection.address, new OperationTimedOutException(connection.address, "Timed out waiting for response to PREPARE message"));
682708 retry(false, null);
683709 return true;
684710 }
@@ -700,11 +726,16 @@
700726 connection.release();
701727
702728 if (exception instanceof ConnectionException) {
703- if (metricsEnabled())
729+ RetryPolicy retryPolicy = retryPolicy();
730+ RetryPolicy.RetryDecision decision = retryPolicy.onRequestError(statement, request().consistency(), (ConnectionException)exception, retriesByPolicy);
731+ if (metricsEnabled()) {
704732 metrics().getErrorMetrics().getConnectionErrors().inc();
705- ConnectionException ce = (ConnectionException)exception;
706- logError(ce.address, ce);
707- 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);
708739 return;
709740 }
710741 setFinalException(connection, exception);
@@ -728,12 +759,22 @@
728759 }
729760
730761 Host queriedHost = current;
731- OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address);
762+
763+ OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address, "Timed out waiting for server response");
764+
732765 try {
733766 connection.release();
734767
735- logError(connection.address, timeoutException);
736- 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);
737778 } catch (Exception e) {
738779 // This shouldn't happen, but if it does, we want to signal the callback, not let it hang indefinitely
739780 setFinalException(null, new DriverInternalError("An unexpected error happened while handling timeout", e));
modified driver-core/src/main/java/com/datastax/driver/core/SchemaParser.java +3 −0
@@ -23,6 +23,9 @@
2323 import org.slf4j.Logger;
2424 import org.slf4j.LoggerFactory;
2525
26+import com.datastax.driver.core.exceptions.BusyConnectionException;
27+import com.datastax.driver.core.exceptions.ConnectionException;
28+
2629 import static com.datastax.driver.core.SchemaElement.*;
2730
2831 abstract class SchemaParser {
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +2 −1
@@ -32,6 +32,7 @@
3232 import com.datastax.driver.core.exceptions.DriverInternalError;
3333 import com.datastax.driver.core.exceptions.InvalidQueryException;
3434 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
35+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
3536 import com.datastax.driver.core.policies.LoadBalancingPolicy;
3637 import com.datastax.driver.core.policies.ReconnectionPolicy;
3738 import com.datastax.driver.core.policies.SpeculativeExecutionPolicy;
@@ -357,7 +358,7 @@
357358 @Override
358359 public void onFailure(Throwable t) {
359360 if (t instanceof UnsupportedProtocolVersionException) {
360- cluster.manager.logUnsupportedVersionProtocol(host, ((UnsupportedProtocolVersionException)t).unsupportedVersion);
361+ cluster.manager.logUnsupportedVersionProtocol(host, ((UnsupportedProtocolVersionException)t).getUnsupportedVersion());
361362 cluster.manager.triggerOnDown(host, false);
362363 } else if (t instanceof ClusterNameMismatchException) {
363364 ClusterNameMismatchException e = (ClusterNameMismatchException)t;
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/Statement.java +1 −0
@@ -21,6 +21,7 @@
2121 import com.google.common.collect.ImmutableMap;
2222
2323 import com.datastax.driver.core.exceptions.PagingStateException;
24+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
2425 import com.datastax.driver.core.policies.RetryPolicy;
2526 import com.datastax.driver.core.querybuilder.BuiltStatement;
2627
modified driver-core/src/main/java/com/datastax/driver/core/StreamIdGenerator.java +2 −2
@@ -81,7 +81,7 @@
8181 offset = new AtomicInteger(bits.length() - 1);
8282 }
8383
84- public int next() throws BusyConnectionException {
84+ public int next() {
8585 int previousOffset, myOffset;
8686 do {
8787 previousOffset = offset.get();
@@ -95,7 +95,7 @@
9595 if (id >= 0)
9696 return id + (64 * j);
9797 }
98- throw new BusyConnectionException();
98+ return -1;
9999 }
100100
101101 public void release(int streamId) {
deleted driver-core/src/main/java/com/datastax/driver/core/TransportException.java +0 −37
@@ -1,37 +0,0 @@
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;
17-
18-import java.net.InetSocketAddress;
19-
20-/**
21- * A connection exception that has to do with the transport itself, i.e. that
22- * suggests the node is down.
23- */
24-class TransportException extends ConnectionException
25-{
26- private static final long serialVersionUID = 0;
27-
28- public TransportException(InetSocketAddress address, String msg, Throwable cause)
29- {
30- super(address, msg, cause);
31- }
32-
33- public TransportException(InetSocketAddress address, String msg)
34- {
35- super(address, msg);
36- }
37-}
deleted driver-core/src/main/java/com/datastax/driver/core/UnsupportedProtocolVersionException.java +0 −39
@@ -1,39 +0,0 @@
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;
17-
18-import java.net.InetSocketAddress;
19-
20-/**
21- * Indicates that we've attempted to connect to a 1.2 C* node with version 2 of
22- * the protocol.
23- */
24-class UnsupportedProtocolVersionException extends Exception {
25-
26- private static final long serialVersionUID = 0;
27-
28- public final InetSocketAddress address;
29- public final ProtocolVersion unsupportedVersion;
30- public final ProtocolVersion serverVersion;
31-
32- public UnsupportedProtocolVersionException(InetSocketAddress address, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion)
33- {
34- super(String.format("[%s] Host %s does not support protocol version %s but %s", address, address, unsupportedVersion, serverVersion));
35- this.address = address;
36- this.unsupportedVersion = unsupportedVersion;
37- this.serverVersion = serverVersion;
38- }
39-}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java +2 −6
@@ -19,13 +19,9 @@
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 */
28-public class BootstrappingException extends DriverInternalError implements CoordinatorException {
24+public class BootstrappingException extends QueryExecutionException implements CoordinatorException {
2925
3026 private static final long serialVersionUID = 0;
3127
added driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyConnectionException.java +55 −0
@@ -0,0 +1,55 @@
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.exceptions;
17+
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
21+/**
22+ * Indicates that a connection has run out of stream IDs.
23+ */
24+public class BusyConnectionException extends DriverException implements CoordinatorException {
25+
26+ private static final long serialVersionUID = 0;
27+
28+ private final InetSocketAddress address;
29+
30+ public BusyConnectionException(InetSocketAddress address) {
31+ super(String.format("[%s] Connection has run out of stream IDs", address.getAddress()));
32+ this.address = address;
33+ }
34+
35+ public BusyConnectionException(InetSocketAddress address, Throwable cause) {
36+ super(String.format("[%s] Connection has run out of stream IDs", address.getAddress()), cause);
37+ this.address = address;
38+ }
39+
40+ @Override
41+ public InetAddress getHost() {
42+ return address.getAddress();
43+ }
44+
45+ @Override
46+ public InetSocketAddress getAddress() {
47+ return address;
48+ }
49+
50+ @Override
51+ public BusyConnectionException copy() {
52+ return new BusyConnectionException(address, this);
53+ }
54+
55+}
added driver-core/src/main/java/com/datastax/driver/core/exceptions/ConnectionException.java +65 −0
@@ -0,0 +1,65 @@
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.exceptions;
17+
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
21+/**
22+ * Indicates that a connection to a host has encountered a problem
23+ * and that it should be closed.
24+ */
25+public class ConnectionException extends DriverException implements CoordinatorException {
26+
27+ private static final long serialVersionUID = 0;
28+
29+ public final InetSocketAddress address;
30+
31+ public ConnectionException(InetSocketAddress address, String msg, Throwable cause) {
32+ super(msg, cause);
33+ this.address = address;
34+ }
35+
36+ public ConnectionException(InetSocketAddress address, String msg) {
37+ super(msg);
38+ this.address = address;
39+ }
40+
41+ @Override
42+ public InetAddress getHost() {
43+ return address.getAddress();
44+ }
45+
46+ @Override
47+ public InetSocketAddress getAddress() {
48+ return address;
49+ }
50+
51+ @Override
52+ public String getMessage() {
53+ return String.format("[%s] %s", getHost(), getRawMessage());
54+ }
55+
56+ @Override
57+ public ConnectionException copy() {
58+ return new ConnectionException(address, getRawMessage(), this);
59+ }
60+
61+ String getRawMessage() {
62+ return super.getMessage();
63+ }
64+
65+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java +5 −5
@@ -20,25 +20,25 @@
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.
28+ * The coordinator host that was contacted.
2929 * <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 */
3636 InetAddress getHost();
3737
3838 /**
39- * The full address of the coordinator host that caused this exception to be raised.
39+ * The full address of the coordinator host that was contacted.
4040 *
41- * @return the full address of the coordinator host that caused this exception to be raised;
41+ * @return the full address of the coordinator host that was contacted;
4242 * may be {@code null} if the coordinator is not known.
4343 */
4444 InetSocketAddress getAddress();
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverException.java +1 −5
@@ -22,10 +22,6 @@
2222
2323 private static final long serialVersionUID = 0;
2424
25- DriverException() {
26- super();
27- }
28-
2925 public DriverException(String message) {
3026 super(message);
3127 }
@@ -41,7 +37,7 @@
4137 /**
4238 * Copy the exception.
4339 * <p>
44- * This return a new exception, equivalent to the original one, except that
40+ * This returns a new exception, equivalent to the original one, except that
4541 * because a new object is created in the current thread, the top-most
4642 * element in the stacktrace of the exception will refer to the current
4743 * thread (this is mainly intended for internal use by the driver). The cause of
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 *
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/InvalidTypeException.java +8 −1
@@ -15,6 +15,13 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+/**
19+ * Thrown when a {@link com.datastax.driver.core.TypeCodec}
20+ * is unable to perform the requested operation (serialization,
21+ * deserialization, parsing or formatting) because the
22+ * object or the byte buffer content being processed does not
23+ * comply with the expected Java and/or CQL type.
24+ */
1825 public class InvalidTypeException extends DriverException {
1926
2027 private static final long serialVersionUID = 0;
@@ -28,7 +35,7 @@
2835 }
2936
3037 @Override
31- public DriverException copy() {
38+ public InvalidTypeException copy() {
3239 return new InvalidTypeException(getMessage(), this);
3340 }
3441 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/NoHostAvailableException.java +8 −8
@@ -22,17 +22,17 @@
2222 import java.util.Map;
2323
2424 /**
25- * Exception thrown when a query cannot be performed because no host are
25+ * Exception thrown when a query cannot be performed because no host is
2626 * available.
27- *
28- * This exception is thrown if
27+ * <p>
28+ * This exception is thrown if either:
2929 * <ul>
30- * <li>either there is no host live in the cluster at the moment of the query</li>
31- * <li>all host that have been tried have failed due to a connection problem</li>
30+ * <li>there is no host live in the cluster at the moment of the query;</li>
31+ * <li>all hosts that have been tried have failed.</li>
3232 * </ul>
3333 *
34- * For debugging purpose, the list of hosts that have been tried along with the
35- * failure cause can be retrieved using the {@link #errors} method.
34+ * For debugging purposes, the list of hosts that have been tried along with the
35+ * failure cause can be retrieved using the {@link #getErrors()} method.
3636 */
3737 public class NoHostAvailableException extends DriverException {
3838
@@ -80,7 +80,7 @@
8080 }
8181
8282 @Override
83- public DriverException copy() {
83+ public NoHostAvailableException copy() {
8484 return new NoHostAvailableException(getMessage(), this, errors);
8585 }
8686
added driver-core/src/main/java/com/datastax/driver/core/exceptions/OperationTimedOutException.java +47 −0
@@ -0,0 +1,47 @@
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.exceptions;
17+
18+import java.net.InetSocketAddress;
19+
20+import com.datastax.driver.core.SocketOptions;
21+
22+/**
23+ * Thrown on a client-side timeout, i.e. when the client didn't hear back from the server within
24+ * {@link SocketOptions#getReadTimeoutMillis()}.
25+ */
26+public class OperationTimedOutException extends ConnectionException {
27+
28+ private static final long serialVersionUID = 0;
29+
30+ public OperationTimedOutException(InetSocketAddress address) {
31+ super(address, "Operation timed out");
32+ }
33+
34+ public OperationTimedOutException(InetSocketAddress address, String msg) {
35+ super(address, msg);
36+ }
37+
38+ public OperationTimedOutException(InetSocketAddress address, String msg, Throwable cause) {
39+ super(address, msg, cause);
40+ }
41+
42+ @Override
43+ public OperationTimedOutException copy() {
44+ return new OperationTimedOutException(address, getRawMessage(), this);
45+ }
46+
47+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +1 −5
@@ -20,12 +20,8 @@
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 */
28-public class OverloadedException extends DriverInternalError implements CoordinatorException {
24+public class OverloadedException extends QueryExecutionException implements CoordinatorException {
2925
3026 private static final long serialVersionUID = 0;
3127
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/PagingStateException.java +8 −1
@@ -15,6 +15,13 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+/**
19+ * Indicates an error while deserializing a (previously serialized)
20+ * {@link com.datastax.driver.core.PagingState} object,
21+ * or when a paging state does not match the statement being executed.
22+ *
23+ * @see com.datastax.driver.core.PagingState
24+ */
1825 public class PagingStateException extends DriverException {
1926
2027 private static final long serialVersionUID = 0;
@@ -27,4 +34,4 @@
2734 super(msg, cause);
2835 }
2936
30-}
No newline at the end of the file
37+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryExecutionException.java +2 −2
@@ -17,8 +17,8 @@
1717
1818 /**
1919 * Exception related to the execution of a query.
20- *
21- * This correspond to the exception that Cassandra throw when a (valid) query
20+ * <p>
21+ * This corresponds to the exception that Cassandra throws when a (valid) query
2222 * cannot be executed (TimeoutException, UnavailableException, ...).
2323 */
2424 @SuppressWarnings("serial")
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadFailureException.java +3 −3
@@ -80,12 +80,12 @@
8080 }
8181
8282 @Override
83- public DriverException copy() {
83+ public ReadFailureException copy() {
8484 return new ReadFailureException(getAddress(), getMessage(), this, getConsistencyLevel(), getReceivedAcknowledgements(),
8585 getRequiredAcknowledgements(), getFailures(), wasDataRetrieved());
8686 }
8787
88- public DriverException copy(InetSocketAddress address) {
88+ public ReadFailureException copy(InetSocketAddress address) {
8989 return new ReadFailureException(
9090 address,
9191 getMessage(),
@@ -96,4 +96,4 @@
9696 failed,
9797 dataPresent);
9898 }
99-}
No newline at the end of the file
99+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java +1 −1
@@ -77,7 +77,7 @@
7777 }
7878
7979 @Override
80- public DriverException copy() {
80+ public ReadTimeoutException copy() {
8181 return new ReadTimeoutException(
8282 getAddress(),
8383 getMessage(),
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ServerError.java +2 −1
@@ -19,7 +19,8 @@
1919 import java.net.InetSocketAddress;
2020
2121 /**
22- * Indicates that the contacted host reported un expected error.
22+ * Indicates that the contacted host reported an internal 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/exceptions/SyntaxError.java +1 −1
@@ -62,7 +62,7 @@
6262 }
6363
6464 @Override
65- public DriverException copy() {
65+ public SyntaxError copy() {
6666 return new SyntaxError(getAddress(), getMessage(), this);
6767 }
6868 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/TraceRetrievalException.java +1 −1
@@ -33,7 +33,7 @@
3333 }
3434
3535 @Override
36- public DriverException copy() {
36+ public TraceRetrievalException copy() {
3737 return new TraceRetrievalException(getMessage(), this);
3838 }
3939 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/TransportException.java +41 −0
@@ -0,0 +1,41 @@
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.exceptions;
17+
18+import java.net.InetSocketAddress;
19+
20+/**
21+ * A connection exception that has to do with the transport itself, i.e. that
22+ * suggests the node is down.
23+ */
24+public class TransportException extends ConnectionException {
25+
26+ private static final long serialVersionUID = 0;
27+
28+ public TransportException(InetSocketAddress address, String msg, Throwable cause) {
29+ super(address, msg, cause);
30+ }
31+
32+ public TransportException(InetSocketAddress address, String msg) {
33+ super(address, msg);
34+ }
35+
36+ @Override
37+ public TransportException copy() {
38+ return new TransportException(address, getRawMessage(), this);
39+ }
40+
41+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java +1 −1
@@ -62,7 +62,7 @@
6262 }
6363
6464 @Override
65- public DriverException copy() {
65+ public TruncateException copy() {
6666 return new TruncateException(getAddress(), getMessage(), this);
6767 }
6868 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java +1 −1
@@ -63,7 +63,7 @@
6363 }
6464
6565 @Override
66- public DriverException copy() {
66+ public UnauthorizedException copy() {
6767 return new UnauthorizedException(getAddress(), getMessage(), this);
6868 }
6969 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java +4 −4
@@ -21,7 +21,7 @@
2121 import com.datastax.driver.core.ConsistencyLevel;
2222
2323 /**
24- * Exception thrown when the coordinator knows there is not enough replica
24+ * Exception thrown when the coordinator knows there is not enough replicas
2525 * alive to perform a query with the requested consistency level.
2626 */
2727 public class UnavailableException extends QueryExecutionException implements CoordinatorException {
@@ -78,10 +78,10 @@
7878 }
7979
8080 /**
81- * The number of replica that were known to be alive by the Cassandra
81+ * The number of replicas that were known to be alive by the Cassandra
8282 * coordinator node when it tried to execute the operation.
8383 *
84- * @return The number of replica that were known to be alive by the Cassandra
84+ * @return The number of replicas that were known to be alive by the Cassandra
8585 * coordinator node when it tried to execute the operation.
8686 */
8787 public int getAliveReplicas() {
@@ -105,7 +105,7 @@
105105 }
106106
107107 @Override
108- public DriverException copy() {
108+ public UnavailableException copy() {
109109 return new UnavailableException(getAddress(), getMessage(), this, consistency, required, alive);
110110 }
111111
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java +1 −5
@@ -20,12 +20,8 @@
2020
2121 /**
2222 * Indicates that the contacted host replied with an UNPREPARED error code.
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 prepare the query and execute it again;
26- * but such exceptions are likely to appear occasionally in the driver logs.
2723 */
28-public class UnpreparedException extends DriverInternalError implements CoordinatorException {
24+public class UnpreparedException extends QueryValidationException implements CoordinatorException {
2925
3026 private static final long serialVersionUID = 0;
3127
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnresolvedUserTypeException.java +9 −2
@@ -17,8 +17,15 @@
1717
1818 /**
1919 * Thrown when a user type cannot be resolved.
20+ * <p>
21+ * This exception can be raised when the driver is rebuilding
22+ * its schema metadata, and a user-defined type cannot be completely
23+ * constructed due to some missing information.
24+ * It should only appear in the driver logs, never in client code.
25+ * It shouldn't be considered as a severe error as long as it only
26+ * appears occasionally.
2027 */
21-public class UnresolvedUserTypeException extends InvalidTypeException {
28+public class UnresolvedUserTypeException extends DriverException {
2229
2330 private final String keyspaceName;
2431
@@ -45,7 +52,7 @@
4552 }
4653
4754 @Override
48- public DriverException copy() {
55+ public UnresolvedUserTypeException copy() {
4956 return new UnresolvedUserTypeException(keyspaceName, name, this);
5057 }
5158
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedFeatureException.java +8 −0
@@ -25,7 +25,15 @@
2525
2626 private static final long serialVersionUID = 0;
2727
28+ private final ProtocolVersion currentVersion;
29+
2830 public UnsupportedFeatureException(ProtocolVersion currentVersion, String msg) {
2931 super("Unsupported feature with the native protocol " + currentVersion + " (which is currently in use): " + msg);
32+ this.currentVersion = currentVersion;
3033 }
34+
35+ public ProtocolVersion getCurrentVersion() {
36+ return currentVersion;
37+ }
38+
3139 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/UnsupportedProtocolVersionException.java +75 −0
@@ -0,0 +1,75 @@
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.exceptions;
17+
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
21+import com.datastax.driver.core.ProtocolVersion;
22+
23+/**
24+ * Indicates that we've attempted to connect to a Cassandra node with a protocol version
25+ * that it cannot handle (e.g., connecting to a C* 1.2 node with protocol version 2).
26+ */
27+public class UnsupportedProtocolVersionException extends DriverException implements CoordinatorException {
28+
29+ private static final long serialVersionUID = 0;
30+
31+ private final InetSocketAddress address;
32+
33+ private final ProtocolVersion unsupportedVersion;
34+
35+ private final ProtocolVersion serverVersion;
36+
37+ public UnsupportedProtocolVersionException(InetSocketAddress address, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion) {
38+ super(String.format("[%s] Host does not support protocol version %s but %s", address, unsupportedVersion, serverVersion));
39+ this.address = address;
40+ this.unsupportedVersion = unsupportedVersion;
41+ this.serverVersion = serverVersion;
42+ }
43+
44+ public UnsupportedProtocolVersionException(InetSocketAddress address, ProtocolVersion unsupportedVersion, ProtocolVersion serverVersion, Throwable cause) {
45+ super(String.format("[%s] Host does not support protocol version %s but %s", address, unsupportedVersion, serverVersion), cause);
46+ this.address = address;
47+ this.unsupportedVersion = unsupportedVersion;
48+ this.serverVersion = serverVersion;
49+ }
50+
51+ @Override
52+ public InetAddress getHost() {
53+ return address.getAddress();
54+ }
55+
56+ @Override
57+ public InetSocketAddress getAddress() {
58+ return address;
59+ }
60+
61+ public ProtocolVersion getServerVersion() {
62+ return serverVersion;
63+ }
64+
65+ public ProtocolVersion getUnsupportedVersion() {
66+ return unsupportedVersion;
67+ }
68+
69+ @Override
70+ public UnsupportedProtocolVersionException copy() {
71+ return new UnsupportedProtocolVersionException(address, unsupportedVersion, serverVersion, this);
72+ }
73+
74+
75+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteFailureException.java +2 −2
@@ -75,12 +75,12 @@
7575 }
7676
7777 @Override
78- public DriverException copy() {
78+ public WriteFailureException copy() {
7979 return new WriteFailureException(getAddress(), getMessage(), this, getConsistencyLevel(), getWriteType(),
8080 getReceivedAcknowledgements(), getRequiredAcknowledgements(), getFailures());
8181 }
8282
83- public DriverException copy(InetSocketAddress address) {
83+ public WriteFailureException copy(InetSocketAddress address) {
8484 return new WriteFailureException(
8585 address,
8686 getMessage(),
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java +1 −1
@@ -62,7 +62,7 @@
6262 }
6363
6464 @Override
65- public DriverException copy() {
65+ public WriteTimeoutException copy() {
6666 return new WriteTimeoutException(
6767 getAddress(),
6868 getMessage(),
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/AbstractReconnectionHandlerTest.java +2 −0
@@ -40,6 +40,8 @@
4040
4141 import com.datastax.driver.core.AbstractReconnectionHandler.HandlerFuture;
4242 import com.datastax.driver.core.AbstractReconnectionHandlerTest.MockReconnectionWork.ReconnectBehavior;
43+import com.datastax.driver.core.exceptions.ConnectionException;
44+import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException;
4345 import com.datastax.driver.core.policies.ReconnectionPolicy.ReconnectionSchedule;
4446
4547 public class AbstractReconnectionHandlerTest {
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +2 −0
@@ -38,6 +38,8 @@
3838 import static org.scassandra.http.client.PrimingRequest.then;
3939 import static org.testng.Assert.fail;
4040
41+import com.datastax.driver.core.exceptions.BusyConnectionException;
42+import com.datastax.driver.core.exceptions.ConnectionException;
4143 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
4244
4345 import static com.datastax.driver.core.Assertions.assertThat;
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 +3 −9
@@ -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,14 +174,8 @@
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);
179- assertThat(error).isNotNull();
180- if(loggedException.getSuperclass() == DriverInternalError.class) {
181- assertThat(error).isOfAnyClassIn(DriverException.class);
182- } else {
183- assertThat(error).isOfAnyClassIn(loggedException);
184- }
178+ assertThat(error).isNotNull().isOfAnyClassIn(loggedException);
185179 } else {
186180 assertThat(e).isInstanceOf(expectedException);
187181 }
@@ -196,4 +190,4 @@
196190 .contains(loggedException.getName());
197191 }
198192
199-}
No newline at the end of the file
193+}
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/StreamIdGeneratorTest.java +3 −6
@@ -19,6 +19,8 @@
1919 import static org.testng.Assert.assertEquals;
2020 import static org.testng.Assert.fail;
2121
22+import com.datastax.driver.core.exceptions.BusyConnectionException;
23+
2224 public class StreamIdGeneratorTest {
2325
2426 @Test(groups = "unit")
@@ -42,11 +44,6 @@
4244 generator.release(100);
4345 assertEquals(generator.next(), 100);
4446
45- try {
46- generator.next();
47- fail("No more streamId should be available");
48- } catch (BusyConnectionException e) {
49- // Ok, expected
50- }
47+ assertEquals(generator.next(), -1);
5148 }
5249 }
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