Elffuss BraidHub

kikocis/java-driver public

Add tests for retry on connection errors + refactor downgrading policy tests to use Scassandra.
Changesetdd34cc62ef780450e20a5f59edf111712de41f8da441eb6047da0117dfdd5892
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2015-12-03 20:21 -06:00
Committerolim7t <omichallat+github@gmail.com> · 2015-12-18 15:53 +01:00
Parents32a6ba5e23ec

Browse the files at this changeset

7 files changed

modified driver-core/src/test/java/com/datastax/driver/core/policies/AbstractRetryPolicyIntegrationTest.java +36 −3
@@ -17,13 +17,19 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.DriverException;
20+import com.datastax.driver.core.exceptions.OverloadedException;
21+import com.datastax.driver.core.exceptions.ServerError;
2022 import com.google.common.collect.ImmutableList;
2123 import com.google.common.collect.ImmutableMap;
2224 import org.mockito.Mockito;
2325 import org.scassandra.Scassandra;
26+import org.scassandra.http.client.ClosedConnectionConfig.CloseType;
27+import org.scassandra.http.client.Config;
2428 import org.scassandra.http.client.PrimingRequest;
29+import org.scassandra.http.client.PrimingRequest.PrimingRequestBuilder;
2530 import org.testng.annotations.AfterMethod;
2631 import org.testng.annotations.BeforeMethod;
32+import org.testng.annotations.DataProvider;
2733
2834 import java.util.List;
2935 import java.util.Map;
@@ -32,6 +38,8 @@
3238 import static org.assertj.core.api.Assertions.assertThat;
3339 import static org.mockito.Matchers.*;
3440 import static org.mockito.Mockito.times;
41+import static org.scassandra.http.client.PrimingRequest.Result.overloaded;
42+import static org.scassandra.http.client.PrimingRequest.Result.server_error;
3543
3644 /**
3745 * Base class for retry policy integration tests.
@@ -97,10 +105,18 @@
97105 }
98106
99107 protected void simulateError(int hostNumber, PrimingRequest.Result result) {
100- scassandras.node(hostNumber).primingClient().prime(PrimingRequest.queryBuilder()
108+ simulateError(hostNumber, result, null);
109+ }
110+
111+ protected void simulateError(int hostNumber, PrimingRequest.Result result, Config config) {
112+ PrimingRequestBuilder builder = PrimingRequest.queryBuilder()
101113 .withQuery("mock query")
102- .withResult(result)
103- .build());
114+ .withResult(result);
115+
116+ if (config != null)
117+ builder = builder.withConfig(config);
118+
119+ scassandras.node(hostNumber).primingClient().prime(builder.build());
104120 }
105121
106122 protected void simulateNormalResponse(int hostNumber) {
@@ -154,4 +170,21 @@
154170 if (scassandras != null)
155171 scassandras.stop();
156172 }
173+
174+ @DataProvider
175+ public static Object[][] serverSideErrors() {
176+ return new Object[][]{
177+ {server_error, ServerError.class},
178+ {overloaded, OverloadedException.class},
179+ };
180+ }
181+
182+ @DataProvider
183+ public static Object[][] connectionErrors() {
184+ return new Object[][]{
185+ {CloseType.CLOSE},
186+ {CloseType.HALFCLOSE},
187+ {CloseType.RESET}
188+ };
189+ }
157190 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/CustomRetryPolicyIntegrationTest.java +30 −10
@@ -16,14 +16,19 @@
1616 package com.datastax.driver.core.policies;
1717
1818 import com.datastax.driver.core.*;
19-import com.datastax.driver.core.exceptions.*;
19+import com.datastax.driver.core.exceptions.DriverException;
20+import com.datastax.driver.core.exceptions.OperationTimedOutException;
21+import com.datastax.driver.core.exceptions.TransportException;
22+import com.datastax.driver.core.exceptions.UnavailableException;
23+import org.scassandra.http.client.ClosedConnectionConfig;
24+import org.scassandra.http.client.ClosedConnectionConfig.CloseType;
2025 import org.scassandra.http.client.PrimingRequest;
21-import org.testng.annotations.DataProvider;
2226 import org.testng.annotations.Test;
2327
2428 import static com.datastax.driver.core.Assertions.assertThat;
2529 import static org.assertj.core.api.Fail.fail;
26-import static org.scassandra.http.client.PrimingRequest.Result.*;
30+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
31+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
2732 import static org.scassandra.http.client.PrimingRequest.then;
2833
2934 /**
@@ -98,13 +103,6 @@
98103 }
99104 }
100105
101- @DataProvider
102- public static Object[][] serverSideErrors() {
103- return new Object[][]{
104- {server_error, ServerError.class},
105- {overloaded, OverloadedException.class}
106- };
107- }
108106
109107 @Test(groups = "short", dataProvider = "serverSideErrors")
110108 public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) {
@@ -124,6 +122,28 @@
124122 assertQueried(3, 0);
125123 }
126124
125+
126+ @Test(groups = "short", dataProvider = "connectionErrors")
127+ public void should_rethrow_on_connection_error(CloseType closeType) {
128+ simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
129+ try {
130+ query();
131+ fail("expected a TransportException");
132+ } catch (TransportException e) {
133+ assertThat(e.getMessage()).isEqualTo(
134+ String.format("[%s] Connection has been closed", host1.getAddress())
135+ );
136+ }
137+ assertOnRequestErrorWasCalled(1, TransportException.class);
138+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
139+ assertThat(errors.getConnectionErrors().getCount()).isEqualTo(1);
140+ assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0);
141+ assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(0);
142+ assertQueried(1, 1);
143+ assertQueried(2, 0);
144+ assertQueried(3, 0);
145+ }
146+
127147 /**
128148 * Ignores read and write timeouts, and retries at most once on unavailable.
129149 * Rethrows for unexpected errors.
modified driver-core/src/test/java/com/datastax/driver/core/policies/DefaultRetryPolicyIntegrationTest.java +28 −10
@@ -19,8 +19,8 @@
1919 import com.datastax.driver.core.exceptions.*;
2020 import org.assertj.core.api.Fail;
2121 import org.scassandra.Scassandra;
22+import org.scassandra.http.client.ClosedConnectionConfig;
2223 import org.scassandra.http.client.PrimingRequest;
23-import org.testng.annotations.DataProvider;
2424 import org.testng.annotations.Test;
2525
2626 import java.util.Collections;
@@ -174,7 +174,7 @@
174174 query();
175175 fail("expected a NoHostAvailableException");
176176 } catch (NoHostAvailableException e) {
177- assertThat(e.getErrors().keySet()).hasSize(3).containsOnlyOnce(
177+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
178178 host1.getSocketAddress(),
179179 host2.getSocketAddress(),
180180 host3.getSocketAddress());
@@ -199,13 +199,6 @@
199199 }
200200 }
201201
202- @DataProvider
203- public static Object[][] serverSideErrors() {
204- return new Object[][]{
205- {server_error, ServerError.class},
206- {overloaded, OverloadedException.class}
207- };
208- }
209202
210203 @Test(groups = "short", dataProvider = "serverSideErrors")
211204 public void should_try_next_host_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) {
@@ -216,7 +209,7 @@
216209 query();
217210 Fail.fail("expected a NoHostAvailableException");
218211 } catch (NoHostAvailableException e) {
219- assertThat(e.getErrors().keySet()).hasSize(3).containsOnlyOnce(
212+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
220213 host1.getSocketAddress(),
221214 host2.getSocketAddress(),
222215 host3.getSocketAddress());
@@ -231,4 +224,29 @@
231224 assertQueried(3, 1);
232225 }
233226
227+
228+ @Test(groups = "short", dataProvider = "connectionErrors")
229+ public void should_try_next_host_on_connection_error(ClosedConnectionConfig.CloseType closeType) {
230+ simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
231+ simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
232+ simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
233+ try {
234+ query();
235+ Fail.fail("expected a NoHostAvailableException");
236+ } catch (NoHostAvailableException e) {
237+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
238+ host1.getSocketAddress(),
239+ host2.getSocketAddress(),
240+ host3.getSocketAddress());
241+ assertThat(e.getErrors().values()).hasOnlyElementsOfType(TransportException.class);
242+ }
243+ assertOnRequestErrorWasCalled(3, TransportException.class);
244+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
245+ assertThat(errors.getConnectionErrors().getCount()).isEqualTo(3);
246+ assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0);
247+ assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(3);
248+ assertQueried(1, 1);
249+ assertQueried(2, 1);
250+ assertQueried(3, 1);
251+ }
234252 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DowngradingConsistencyRetryPolicyIntegrationTest.java +410 −73
@@ -15,90 +15,427 @@
1515 */
1616 package com.datastax.driver.core.policies;
1717
18-import com.datastax.driver.core.*;
19-import com.google.common.base.Objects;
20-import org.mockito.Mockito;
21-import org.mockito.verification.VerificationMode;
18+import com.datastax.driver.core.ConsistencyLevel;
19+import com.datastax.driver.core.SocketOptions;
20+import com.datastax.driver.core.WriteType;
21+import com.datastax.driver.core.exceptions.*;
22+import org.assertj.core.api.Assertions;
23+import org.assertj.core.api.Fail;
24+import org.scassandra.http.client.*;
25+import org.testng.annotations.DataProvider;
2226 import org.testng.annotations.Test;
2327
24-import static com.datastax.driver.core.ConsistencyLevel.*;
2528 import static org.assertj.core.api.Assertions.assertThat;
26-import static org.mockito.Matchers.any;
27-import static org.mockito.Matchers.anyInt;
28-import static org.mockito.Mockito.never;
29-import static org.mockito.Mockito.times;
30-
31-/**
32- * Note: we can't extend {@link AbstractRetryPolicyIntegrationTest} here, because SCassandra doesn't allow custom values for
33- * receivedResponses in primed responses.
34- * If that becomes possible in the future, we could refactor this test.
35- */
36-public class DowngradingConsistencyRetryPolicyIntegrationTest {
37-
38- @Test(groups = "long")
39- public void should_downgrade_if_not_enough_replicas_for_requested_CL() {
40- CCMBridge ccm = null;
41- Cluster cluster = null;
42- try {
43- // 3-node cluster, keyspace with RF = 3
44- ccm = CCMBridge.builder(this.getClass().getName()).withNodes(3).build();
45- cluster = Cluster.builder()
46- .addContactPoint(CCMBridge.ipOfNode(1))
47- .withRetryPolicy(Mockito.spy(DowngradingConsistencyRetryPolicy.INSTANCE))
48- .build();
49- Session session = cluster.connect();
50-
51- session.execute("CREATE KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 3}");
52- session.execute("CREATE TABLE test.foo(k int primary key)");
53- session.execute("INSERT INTO test.foo(k) VALUES (0)");
54-
55- // All replicas up: should achieve all levels without downgrading
56- checkAchievedConsistency(ALL, ALL, session);
57- checkAchievedConsistency(QUORUM, QUORUM, session);
58- checkAchievedConsistency(ONE, ONE, session);
59-
60- ccm.stop(1);
61- ccm.waitForDown(1);
62- // Two replicas remaining: should downgrade to 2 when CL > 2
63- checkAchievedConsistency(ALL, TWO, session);
64- checkAchievedConsistency(QUORUM, QUORUM, session); // since RF = 3, quorum is still achievable with two nodes
65- checkAchievedConsistency(TWO, TWO, session);
66- checkAchievedConsistency(ONE, ONE, session);
67-
68- ccm.stop(2);
69- ccm.waitForDown(2);
70- // One replica remaining: should downgrade to 1 when CL > 1
71- checkAchievedConsistency(ALL, ONE, session);
72- checkAchievedConsistency(QUORUM, ONE, session);
73- checkAchievedConsistency(TWO, ONE, session);
74- checkAchievedConsistency(ONE, ONE, session);
29+import static org.scassandra.http.client.PrimingRequest.Result.*;
30+import static org.scassandra.http.client.PrimingRequest.then;
31+import static org.scassandra.http.client.WriteTypePrime.UNLOGGED_BATCH;
32+import static org.testng.Assert.fail;
7533
76- } finally {
77- if (cluster != null)
78- cluster.close();
79- if (ccm != null)
80- ccm.remove();
34+public class DowngradingConsistencyRetryPolicyIntegrationTest extends AbstractRetryPolicyIntegrationTest {
35+
36+ public DowngradingConsistencyRetryPolicyIntegrationTest() {
37+ super(DowngradingConsistencyRetryPolicy.INSTANCE);
38+ }
39+
40+ /**
41+ * @return An array of pairs that match # of alive replicas with the expected downgraded CL used on read/write/unavailable.
42+ */
43+ @DataProvider
44+ public static Object[][] consistencyLevels() {
45+ return new Object[][]{
46+ {4, ConsistencyLevel.THREE},
47+ {3, ConsistencyLevel.THREE},
48+ {2, ConsistencyLevel.TWO},
49+ {1, ConsistencyLevel.ONE}
50+ };
51+ }
52+
53+
54+ /**
55+ * @return Write Types for which we expect a rethrow if used and there are no received acks.
56+ */
57+ @DataProvider
58+ public static Object[][] rethrowWriteTypes() {
59+ return new Object[][]{
60+ {WriteTypePrime.SIMPLE},
61+ {WriteTypePrime.BATCH},
62+ {WriteTypePrime.COUNTER},
63+ {WriteTypePrime.CAS}
64+ };
65+ }
66+
67+
68+ /**
69+ * @return Write Types for which we expect an ignore if used and there are received acks.
70+ */
71+ @DataProvider
72+ public static Object[][] ignoreWriteTypesWithReceivedAcks() {
73+ return new Object[][]{
74+ {WriteTypePrime.SIMPLE},
75+ {WriteTypePrime.BATCH}
76+ };
77+ }
78+
79+
80+ /**
81+ * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is
82+ * reattempted with a {@link ConsistencyLevel} that matches min(received acknowledgements, THREE) and is only
83+ * retried once.
84+ *
85+ * @param received The number of received acknowledgements to use in read timeout.
86+ * @param expectedDowngradedCL The consistency level that is expected to be used on the retry.
87+ * @test_category retry_policy
88+ */
89+ @Test(groups = "short", dataProvider = "consistencyLevels")
90+ public void should_retry_once_on_same_host_with_reduced_consistency_level_on_read_timeout(int received, ConsistencyLevel expectedDowngradedCL) {
91+ simulateError(1, read_request_timeout, new ReadTimeoutConfig(received, received + 1, true));
92+
93+ try {
94+ query();
95+ fail("expected an ReadTimeoutException");
96+ } catch (ReadTimeoutException e) {
97+ assertThat(e.getConsistencyLevel()).isEqualTo(expectedDowngradedCL);
98+ }
99+
100+ assertOnReadTimeoutWasCalled(2);
101+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
102+ assertThat(errors.getReadTimeouts().getCount()).isEqualTo(2);
103+ assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(1);
104+ assertQueried(1, 2);
105+ assertQueried(2, 0);
106+ assertQueried(3, 0);
107+ }
108+
109+
110+ /**
111+ * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is
112+ * reattempted if data was not retrieved, but enough replicas were alive to handle the request.
113+ *
114+ * @test_category retry_policy
115+ */
116+ @Test(groups = "short")
117+ public void should_retry_once_if_not_data_was_retrieved_and_enough_replicas_alive() {
118+ simulateError(1, read_request_timeout, new ReadTimeoutConfig(1, 1, false));
119+
120+ try {
121+ query();
122+ fail("expected an ReadTimeoutException");
123+ } catch (ReadTimeoutException e) {/*expected*/}
124+
125+ assertOnReadTimeoutWasCalled(2);
126+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
127+ assertThat(errors.getReadTimeouts().getCount()).isEqualTo(2);
128+ assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(1);
129+ assertQueried(1, 2);
130+ assertQueried(2, 0);
131+ assertQueried(3, 0);
132+ }
133+
134+
135+ /**
136+ * Ensures that when handling a read timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is not
137+ * attempted if no replicas were alive. In a real scenario, this would not be expected as we'd anticipate an
138+ * {@link UnavailableException} instead.
139+ *
140+ * @test_category retry_policy
141+ */
142+ @Test(groups = "short")
143+ public void should_rethrow_if_no_hosts_alive_on_read_timeout() {
144+ simulateError(1, read_request_timeout);
145+
146+ try {
147+ query();
148+ fail("expected a ReadTimeoutException");
149+ } catch (ReadTimeoutException e) {/*expected*/ }
150+
151+ assertOnReadTimeoutWasCalled(1);
152+ assertThat(errors.getReadTimeouts().getCount()).isEqualTo(1);
153+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
154+ assertThat(errors.getRetriesOnReadTimeout().getCount()).isEqualTo(0);
155+ assertQueried(1, 1);
156+ assertQueried(2, 0);
157+ assertQueried(3, 0);
158+ }
159+
160+
161+ /**
162+ * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that it rethrows
163+ * the exception if the {@link WriteType} was any of {@link #rethrowWriteTypes}.
164+ *
165+ * @param writeType writeType communicated by {@link WriteTimeoutException}.
166+ * @test_category retry_policy
167+ */
168+ @Test(groups = "short", dataProvider = "rethrowWriteTypes")
169+ public void should_rethrow_on_write_timeout_with_write_type(WriteTypePrime writeType) {
170+ simulateError(1, write_request_timeout, new WriteTimeoutConfig(writeType, 0, 2));
171+
172+ try {
173+ query();
174+ fail("expected a WriteTimeoutException");
175+ } catch (WriteTimeoutException e) {/*expected*/}
176+
177+ assertOnWriteTimeoutWasCalled(1);
178+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1);
179+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
180+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0);
181+ assertQueried(1, 1);
182+ assertQueried(2, 0);
183+ assertQueried(3, 0);
184+ }
185+
186+
187+ /**
188+ * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that it ignores
189+ * the exception if the {@link WriteType} was any of {@link #ignoreWriteTypesWithReceivedAcks} and we received acks
190+ * some at least one replica.
191+ *
192+ * @param writeType writeType communicated by {@link WriteTimeoutException}.
193+ * @test_category retry_policy
194+ */
195+ @Test(groups = "short", dataProvider = "ignoreWriteTypesWithReceivedAcks")
196+ public void should_ignore_on_write_timeout_with_write_type_and_received_acks(WriteTypePrime writeType) {
197+ simulateError(1, write_request_timeout, new WriteTimeoutConfig(writeType, 1, 2));
198+
199+ query();
200+
201+ assertOnWriteTimeoutWasCalled(1);
202+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(1);
203+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
204+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(0);
205+ assertThat(errors.getIgnoresOnWriteTimeout().getCount()).isEqualTo(1);
206+ assertQueried(1, 1);
207+ assertQueried(2, 0);
208+ assertQueried(3, 0);
209+ }
210+
211+
212+ /**
213+ * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is
214+ * attempted on the same host if the {@link WriteType} is {@link WriteType#BATCH_LOG}.
215+ *
216+ * @test_category retry_policy
217+ */
218+ @Test(groups = "short")
219+ public void should_retry_once_on_same_host_with_BATCH_LOG_write_type() {
220+ simulateError(1, write_request_timeout, new WriteTimeoutConfig(WriteTypePrime.BATCH_LOG, 1, 2));
221+
222+ try {
223+ query();
224+ fail("expected a WriteTimeoutException");
225+ } catch (WriteTimeoutException e) {/*expected*/}
226+
227+ assertOnWriteTimeoutWasCalled(2);
228+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
229+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(2);
230+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(1);
231+ assertQueried(1, 2);
232+ assertQueried(2, 0);
233+ assertQueried(3, 0);
234+ }
235+
236+
237+ /**
238+ * Ensures that when handling a write timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is
239+ * attempted on the same host with a reduced consistency level that matches min(received acknowledgments, THREE)
240+ * if the {@link WriteType} is {@link WriteType#UNLOGGED_BATCH} and is only retries once.
241+ *
242+ * @param alive The number of received acknowledgements to use in write timeout.
243+ * @param expectedDowngradedCL The consistency level that is expected to be used on the retry.
244+ * @test_category retry_policy
245+ */
246+ @Test(groups = "short", dataProvider = "consistencyLevels")
247+ public void should_retry_once_on_same_host_with_reduced_consistency_level_on_write_timeout(int alive, ConsistencyLevel expectedDowngradedCL) {
248+ simulateError(1, write_request_timeout, new WriteTimeoutConfig(UNLOGGED_BATCH, alive, alive + 1));
249+
250+ try {
251+ query();
252+ fail("expected a WriteTimeoutException");
253+ } catch (WriteTimeoutException e) {
254+ assertThat(e.getConsistencyLevel()).isEqualTo(expectedDowngradedCL);
255+ }
256+
257+ assertOnWriteTimeoutWasCalled(2);
258+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
259+ assertThat(errors.getWriteTimeouts().getCount()).isEqualTo(2);
260+ assertThat(errors.getRetriesOnWriteTimeout().getCount()).isEqualTo(1);
261+ assertQueried(1, 2);
262+ assertQueried(2, 0);
263+ assertQueried(3, 0);
264+ }
265+
266+
267+ /**
268+ * Ensures that when handling an unavailable with {@link DowngradingConsistencyRetryPolicy} that a retry is
269+ * reattempted with a {@link ConsistencyLevel} that matches min(received acknowledgements, THREE) and is only
270+ * retried once.
271+ *
272+ * @param alive The number of received acknowledgements to use in unavailable.
273+ * @param expectedDowngradedCL The consistency level that is expected to be used on the retry.
274+ * @test_category retry_policy
275+ */
276+ @Test(groups = "short", dataProvider = "consistencyLevels")
277+ public void should_retry_once_on_same_host_with_reduced_consistency_level_on_unavailable(int alive, ConsistencyLevel expectedDowngradedCL) {
278+ simulateError(1, unavailable, new UnavailableConfig(alive + 1, alive));
279+
280+ try {
281+ query();
282+ fail("expected an UnavailableException");
283+ } catch (UnavailableException e) {
284+ assertThat(e.getConsistencyLevel()).isEqualTo(expectedDowngradedCL);
81285 }
286+
287+ assertOnUnavailableWasCalled(2);
288+ assertThat(errors.getRetries().getCount()).isEqualTo(1);
289+ assertThat(errors.getUnavailables().getCount()).isEqualTo(2);
290+ assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(1);
291+ assertQueried(1, 2);
292+ assertQueried(2, 0);
293+ assertQueried(3, 0);
82294 }
83295
84- private void checkAchievedConsistency(ConsistencyLevel requested, ConsistencyLevel expected, Session session) {
85- RetryPolicy retryPolicy = session.getCluster().getConfiguration().getPolicies().getRetryPolicy();
86- Mockito.reset(retryPolicy);
87296
88- Statement s = new SimpleStatement("SELECT * FROM test.foo WHERE k = 0")
89- .setConsistencyLevel(requested);
297+ /**
298+ * Ensures that when handling an unavailable with {@link DowngradingConsistencyRetryPolicy} that a retry is
299+ * is not reattempted if no replicas are alive.
300+ *
301+ * @test_category retry_policy
302+ */
303+ @Test(groups = "short")
304+ public void should_rethrow_if_no_hosts_alive_on_unavailable() {
305+ simulateError(1, unavailable, new UnavailableConfig(1, 0));
306+
307+ try {
308+ query();
309+ fail("expected an UnavailableException");
310+ } catch (UnavailableException e) {/*expected*/}
311+
312+ assertOnUnavailableWasCalled(1);
313+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
314+ assertThat(errors.getUnavailables().getCount()).isEqualTo(1);
315+ assertThat(errors.getRetriesOnUnavailable().getCount()).isEqualTo(0);
316+ assertQueried(1, 1);
317+ assertQueried(2, 0);
318+ assertQueried(3, 0);
319+ }
320+
321+ /**
322+ * Ensures that when handling a client timeout with {@link DowngradingConsistencyRetryPolicy} that a retry is
323+ * attempted on the next host until all hosts are tried at which point a {@link NoHostAvailableException} is
324+ * returned.
325+ *
326+ * @test_category retry_policy
327+ */
328+ @Test(groups = "short")
329+ public void should_try_next_host_on_client_timeouts() {
330+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(1);
331+ try {
332+ scassandras
333+ .node(1).primingClient().prime(PrimingRequest.queryBuilder()
334+ .withQuery("mock query")
335+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result1")))
336+ .build());
337+ scassandras
338+ .node(2).primingClient().prime(PrimingRequest.queryBuilder()
339+ .withQuery("mock query")
340+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result2")))
341+ .build());
342+ scassandras
343+ .node(3).primingClient().prime(PrimingRequest.queryBuilder()
344+ .withQuery("mock query")
345+ .withThen(then().withFixedDelay(1000L).withRows(row("result", "result3")))
346+ .build());
347+ try {
348+ query();
349+ Assertions.fail("expected a NoHostAvailableException");
350+ } catch (NoHostAvailableException e) {
351+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
352+ host1.getSocketAddress(),
353+ host2.getSocketAddress(),
354+ host3.getSocketAddress());
355+ assertThat(e.getErrors().values())
356+ .hasOnlyElementsOfType(OperationTimedOutException.class)
357+ .extractingResultOf("getMessage")
358+ .containsOnlyOnce(
359+ String.format("[%s] Timed out waiting for server response", host1.getAddress()),
360+ String.format("[%s] Timed out waiting for server response", host2.getAddress()),
361+ String.format("[%s] Timed out waiting for server response", host3.getAddress())
362+ );
363+ }
364+ assertOnRequestErrorWasCalled(3, OperationTimedOutException.class);
365+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
366+ assertThat(errors.getClientTimeouts().getCount()).isEqualTo(3);
367+ assertThat(errors.getRetriesOnClientTimeout().getCount()).isEqualTo(3);
368+ assertQueried(1, 1);
369+ assertQueried(2, 1);
370+ assertQueried(3, 1);
371+ } finally {
372+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
373+ }
374+ }
90375
91- ResultSet rs = session.execute(s);
92376
93- ConsistencyLevel achieved = rs.getExecutionInfo().getAchievedConsistencyLevel();
94- // ExecutionInfo returns null when the requested level was met.
95- ConsistencyLevel actual = Objects.firstNonNull(achieved, requested);
377+ /**
378+ * Ensures that when handling a server error defined in {@link #serverSideErrors} with
379+ * {@link DowngradingConsistencyRetryPolicy} that a retry is attempted on the next host until all hosts are tried
380+ * at which point a {@link NoHostAvailableException} is raised and it's errors include the expected exception.
381+ *
382+ * @param error Server side error to be produced.
383+ * @param exception The exception we expect to be raised.
384+ * @test_category retry_policy
385+ */
386+ @Test(groups = "short", dataProvider = "serverSideErrors")
387+ public void should_try_next_host_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) {
388+ simulateError(1, error);
389+ simulateError(2, error);
390+ simulateError(3, error);
391+ try {
392+ query();
393+ Fail.fail("expected a NoHostAvailableException");
394+ } catch (NoHostAvailableException e) {
395+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
396+ host1.getSocketAddress(),
397+ host2.getSocketAddress(),
398+ host3.getSocketAddress());
399+ assertThat(e.getErrors().values()).hasOnlyElementsOfType(exception);
400+ }
401+ assertOnRequestErrorWasCalled(3, exception);
402+ assertThat(errors.getOthers().getCount()).isEqualTo(3);
403+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
404+ assertThat(errors.getRetriesOnOtherErrors().getCount()).isEqualTo(3);
405+ assertQueried(1, 1);
406+ assertQueried(2, 1);
407+ assertQueried(3, 1);
408+ }
96409
97- assertThat(actual).isEqualTo(expected);
98410
99- // If the level was downgraded the policy should have been invoked
100- VerificationMode expectedCallsToPolicy = (expected == requested) ? never() : times(1);
101- Mockito.verify(retryPolicy, expectedCallsToPolicy).onUnavailable(
102- any(Statement.class), any(ConsistencyLevel.class), anyInt(), anyInt(), anyInt());
411+ /**
412+ * Ensures that when handling a connection error caused by the connection closing during a request in a way
413+ * described by {@link #connectionErrors} that the next host is tried.
414+ *
415+ * @param closeType The way the connection should be closed during the request.
416+ */
417+ @Test(groups = "short", dataProvider = "connectionErrors")
418+ public void should_try_next_host_on_connection_error(ClosedConnectionConfig.CloseType closeType) {
419+ simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
420+ simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
421+ simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
422+ try {
423+ query();
424+ Fail.fail("expected a TransportException");
425+ } catch (NoHostAvailableException e) {
426+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
427+ host1.getSocketAddress(),
428+ host2.getSocketAddress(),
429+ host3.getSocketAddress());
430+ assertThat(e.getErrors().values()).hasOnlyElementsOfType(TransportException.class);
431+ }
432+ assertOnRequestErrorWasCalled(3, TransportException.class);
433+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
434+ assertThat(errors.getConnectionErrors().getCount()).isEqualTo(3);
435+ assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0);
436+ assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(3);
437+ assertQueried(1, 1);
438+ assertQueried(2, 1);
439+ assertQueried(3, 1);
103440 }
104441 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/FallthroughRetryPolicyIntegrationTest.java +22 −8
@@ -18,8 +18,8 @@
1818 import com.datastax.driver.core.SocketOptions;
1919 import com.datastax.driver.core.exceptions.*;
2020 import org.assertj.core.api.Fail;
21+import org.scassandra.http.client.ClosedConnectionConfig;
2122 import org.scassandra.http.client.PrimingRequest;
22-import org.testng.annotations.DataProvider;
2323 import org.testng.annotations.Test;
2424
2525 import static org.assertj.core.api.Assertions.assertThat;
@@ -109,13 +109,6 @@
109109 }
110110 }
111111
112- @DataProvider
113- public static Object[][] serverSideErrors() {
114- return new Object[][]{
115- {server_error, ServerError.class},
116- {overloaded, OverloadedException.class}
117- };
118- }
119112
120113 @Test(groups = "short", dataProvider = "serverSideErrors")
121114 public void should_rethrow_on_server_side_error(PrimingRequest.Result error, Class<? extends DriverException> exception) {
@@ -135,4 +128,25 @@
135128 assertQueried(3, 0);
136129 }
137130
131+
132+ @Test(groups = "short", dataProvider = "connectionErrors")
133+ public void should_rethrow_on_connection_error(ClosedConnectionConfig.CloseType closeType) {
134+ simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
135+ try {
136+ query();
137+ Fail.fail("expected a TransportException");
138+ } catch (TransportException e) {
139+ assertThat(e.getMessage()).isEqualTo(
140+ String.format("[%s] Connection has been closed", host1.getAddress())
141+ );
142+ }
143+ assertOnRequestErrorWasCalled(1, TransportException.class);
144+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
145+ assertThat(errors.getConnectionErrors().getCount()).isEqualTo(1);
146+ assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0);
147+ assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(0);
148+ assertQueried(1, 1);
149+ assertQueried(2, 0);
150+ assertQueried(3, 0);
151+ }
138152 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/IdempotenceAwareRetryPolicyIntegrationTest.java +54 −9
@@ -17,14 +17,15 @@
1717
1818 import com.datastax.driver.core.*;
1919 import com.datastax.driver.core.exceptions.*;
20+import org.assertj.core.api.Fail;
21+import org.scassandra.http.client.ClosedConnectionConfig;
2022 import org.scassandra.http.client.PrimingRequest;
2123 import org.testng.annotations.BeforeMethod;
22-import org.testng.annotations.DataProvider;
2324 import org.testng.annotations.Test;
2425
2526 import static org.assertj.core.api.Assertions.assertThat;
2627 import static org.assertj.core.api.Assertions.fail;
27-import static org.scassandra.http.client.PrimingRequest.Result.*;
28+import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
2829 import static org.scassandra.http.client.PrimingRequest.then;
2930
3031 /**
@@ -121,13 +122,6 @@
121122 }
122123 }
123124
124- @DataProvider
125- public static Object[][] serverSideErrors() {
126- return new Object[][]{
127- {server_error, ServerError.class},
128- {overloaded, OverloadedException.class}
129- };
130- }
131125
132126 @Test(groups = "short", dataProvider = "serverSideErrors")
133127 public void should_not_retry_on_server_error_if_statement_non_idempotent(PrimingRequest.Result error, Class<? extends DriverException> exception) {
@@ -172,6 +166,57 @@
172166 assertQueried(3, 1);
173167 }
174168
169+
170+ @Test(groups = "short", dataProvider = "connectionErrors")
171+ public void should_not_retry_on_connection_error_if_statement_non_idempotent(ClosedConnectionConfig.CloseType closeType) {
172+ simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
173+ simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
174+ simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
175+ try {
176+ query();
177+ Fail.fail("expected a TransportException");
178+ } catch (TransportException e) {
179+ assertThat(e.getMessage()).isEqualTo(
180+ String.format("[%s] Connection has been closed", host1.getAddress())
181+ );
182+ }
183+ assertOnRequestErrorWasCalled(1, TransportException.class);
184+ assertThat(errors.getRetries().getCount()).isEqualTo(0);
185+ assertThat(errors.getConnectionErrors().getCount()).isEqualTo(1);
186+ assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0);
187+ assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(0);
188+ assertQueried(1, 1);
189+ assertQueried(2, 0);
190+ assertQueried(3, 0);
191+ }
192+
193+
194+ @Test(groups = "short", dataProvider = "connectionErrors")
195+ public void should_retry_on_connection_error_if_statement_idempotent(ClosedConnectionConfig.CloseType closeType) {
196+ simulateError(1, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
197+ simulateError(2, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
198+ simulateError(3, PrimingRequest.Result.closed_connection, new ClosedConnectionConfig(closeType));
199+ try {
200+ session.execute(new SimpleStatement("mock query").setIdempotent(true));
201+ Fail.fail("expected a TransportException");
202+ } catch (NoHostAvailableException e) {
203+ assertThat(e.getErrors().keySet()).hasSize(3).containsOnly(
204+ host1.getSocketAddress(),
205+ host2.getSocketAddress(),
206+ host3.getSocketAddress());
207+ assertThat(e.getErrors().values()).hasOnlyElementsOfType(TransportException.class);
208+ }
209+ assertOnRequestErrorWasCalled(3, TransportException.class);
210+ assertThat(errors.getRetries().getCount()).isEqualTo(3);
211+ assertThat(errors.getConnectionErrors().getCount()).isEqualTo(3);
212+ assertThat(errors.getIgnoresOnConnectionError().getCount()).isEqualTo(0);
213+ assertThat(errors.getRetriesOnConnectionError().getCount()).isEqualTo(3);
214+ assertQueried(1, 1);
215+ assertQueried(2, 1);
216+ assertQueried(3, 1);
217+ }
218+
219+
175220 /**
176221 * Retries everything on the next host.
177222 */
modified pom.xml +1 −1
@@ -64,7 +64,7 @@
6464 <assertj.version>1.7.0</assertj.version>
6565 <mockito.version>1.10.8</mockito.version>
6666 <commons-exec.version>1.3</commons-exec.version>
67- <scassandra.version>0.10.0</scassandra.version>
67+ <scassandra.version>0.11.0</scassandra.version>
6868 <main.basedir>${project.basedir}</main.basedir>
6969 <!-- Set default javadoc.opts, overriden by profiles -->
7070 <javadoc.opts />