Elffuss BraidHub

kikocis/java-driver public

Tests for JAVA-544. Refactor HostConnectionPoolTest to use Scassandra.

Add MockRequest to HostConnectionPoolTest.

Add more tests for JAVA-544.

Multi Pool test
Changeset44dc7480709ddeb13917e4893a3d969f38e2595d8cb87802ce62208d42d29011
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2015-08-17 21:55 -05:00
CommitterAndrew Tolbert <andrew.tolbert@datastax.com> · 2015-09-14 13:55 -05:00
Parentsa5f98239766e

Browse the files at this changeset

10 files changed

modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +6 −3
@@ -25,6 +25,7 @@
2525 import java.util.concurrent.atomic.AtomicInteger;
2626 import java.util.concurrent.atomic.AtomicReference;
2727
28+import com.google.common.annotations.VisibleForTesting;
2829 import com.google.common.collect.MapMaker;
2930 import com.google.common.util.concurrent.*;
3031 import io.netty.bootstrap.Bootstrap;
@@ -77,10 +78,12 @@
7778 public final InetSocketAddress address;
7879 private final String name;
7980
80- private volatile Channel channel;
81+ @VisibleForTesting
82+ volatile Channel channel;
8183 private final Factory factory;
8284
83- private final Dispatcher dispatcher = new Dispatcher();
85+ @VisibleForTesting
86+ final Dispatcher dispatcher = new Dispatcher();
8487
8588 // Used by connection pooling to count how many requests are "in flight" on that connection.
8689 public final AtomicInteger inFlight = new AtomicInteger(0);
@@ -926,7 +929,7 @@
926929 flusher.start();
927930 }
928931
929- private class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
932+ class Dispatcher extends SimpleChannelInboundHandler<Message.Response> {
930933
931934 public final StreamIdGenerator streamIdHandler = new StreamIdGenerator();
932935 private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +3 −1
@@ -22,6 +22,7 @@
2222 import java.util.concurrent.*;
2323 import java.util.concurrent.atomic.AtomicReference;
2424
25+import com.google.common.annotations.VisibleForTesting;
2526 import com.google.common.base.Objects;
2627 import com.google.common.util.concurrent.ListenableFuture;
2728 import org.slf4j.Logger;
@@ -55,7 +56,8 @@
5556 private static final String SELECT_SCHEMA_PEERS = "SELECT peer, rpc_address, schema_version FROM system.peers";
5657 private static final String SELECT_SCHEMA_LOCAL = "SELECT schema_version FROM system.local WHERE key='local'";
5758
58- private final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
59+ @VisibleForTesting
60+ final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
5961
6062 private final Cluster.Manager cluster;
6163
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +8 −4
@@ -15,16 +15,15 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.net.InetSocketAddress;
18+import com.google.common.collect.Iterators;
19+import org.assertj.core.api.AbstractAssert;
20+
1921 import java.util.Iterator;
2022 import java.util.Set;
2123 import java.util.TreeSet;
2224
2325 import static org.assertj.core.api.Assertions.assertThat;
2426
25-import com.google.common.collect.Iterators;
26-import org.assertj.core.api.AbstractAssert;
27-
2827 public class ClusterAssert extends AbstractAssert<ClusterAssert, Cluster> {
2928 protected ClusterAssert(Cluster actual) {
3029 super(actual, ClusterAssert.class);
@@ -42,6 +41,11 @@
4241 return this;
4342 }
4443
44+ public ClusterAssert hasOpenControlConnection() {
45+ assertThat(actual.manager.controlConnection.isOpen()).isTrue();
46+ return this;
47+ }
48+
4549 public HostAssert host(int hostNumber) {
4650 // TODO at some point this won't work anymore if we have assertions that wait for a node to
4751 // join the cluster, e.g. assertThat(cluster).node(3).comesUp().
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +10 −0
@@ -41,6 +41,16 @@
4141 return this;
4242 }
4343
44+ public HostAssert isUp() {
45+ assertThat(actual.isUp()).isTrue();
46+ return this;
47+ }
48+
49+ public HostAssert isDown() {
50+ assertThat(actual.isUp()).isFalse();
51+ return this;
52+ }
53+
4454 public HostAssert isAtDistance(HostDistance expected) {
4555 LoadBalancingPolicy loadBalancingPolicy = cluster.manager.loadBalancingPolicy();
4656 assertThat(loadBalancingPolicy.distance(actual)).isEqualTo(expected);
added driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolMultiTest.java +118 −0
@@ -0,0 +1,118 @@
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 com.datastax.driver.core.policies.ConstantReconnectionPolicy;
19+import com.google.common.util.concurrent.Uninterruptibles;
20+import org.testng.annotations.AfterMethod;
21+import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.Test;
23+
24+import java.net.InetSocketAddress;
25+
26+import static com.datastax.driver.core.Assertions.assertThat;
27+import static com.datastax.driver.core.HostDistance.LOCAL;
28+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
29+import static java.util.concurrent.TimeUnit.SECONDS;
30+
31+import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
32+
33+public class HostConnectionPoolMultiTest {
34+
35+ private SCassandraCluster scassandra;
36+
37+ private Cluster cluster;
38+
39+ @BeforeMethod(groups={"short", "long"})
40+ private void setUp() {
41+ scassandra = new SCassandraCluster(2);
42+ }
43+
44+ @AfterMethod(groups={"short", "long"})
45+ private void tearDown() {
46+ if(cluster != null) {
47+ cluster.close();
48+ }
49+ scassandra.stop();
50+ }
51+
52+ private void createCluster(int core, int max) {
53+ PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, core, max);
54+ SocketOptions socketOptions = new SocketOptions().setReadTimeoutMillis(1000);
55+ cluster = Cluster.builder()
56+ .addContactPoint(CCMBridge.ipOfNode(1))
57+ .withQueryOptions(nonDebouncingQueryOptions())
58+ .withPoolingOptions(poolingOptions)
59+ .withSocketOptions(socketOptions)
60+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
61+ .build();
62+ cluster.connect();
63+ }
64+
65+ /**
66+ * Ensures that if all connections fail to a host on pool init that the host is marked down.
67+ *
68+ * @jira_ticket JAVA-544
69+ * @test_category connection:connection_pool
70+ * @since 2.0.11
71+ */
72+ @Test(groups="short")
73+ public void should_mark_host_down_if_all_connections_fail_on_init() {
74+ // Prevent any connections on node 2.
75+ scassandra.instance(2).currentClient().disableListener();
76+ createCluster(8,8);
77+
78+ // Node 2 should be in a down state while node 1 stays up.
79+ assertThat(cluster).host(2).goesDownWithin(10, SECONDS);
80+ assertThat(cluster).host(1).isUp();
81+
82+ // Node 2 should come up as soon as it is able to reconnect.
83+ scassandra.instance(2).currentClient().enableListener();
84+ assertThat(cluster).host(2).comesUpWithin(2, SECONDS);
85+ }
86+
87+ /**
88+ * Ensures that if the control connection goes down, but the Host bound the control connection
89+ * still has an up pool, the Host should remain up and the Control Connection should be replaced.
90+ *
91+ * @jira_ticket JAVA-544
92+ * @test_category connection:connection_pool
93+ * @since 2.0.11
94+ */
95+ @Test(groups="short")
96+ public void should_replace_control_connection_if_it_goes_down_but_host_remains_up() {
97+ createCluster(1,2);
98+
99+ // Ensure control connection is on node 1.
100+ assertThat(cluster).usesControlHost(1);
101+
102+ // Identify the socket associated with the control connection.
103+ Connection controlConnection = cluster.manager.controlConnection.connectionRef.get();
104+ InetSocketAddress controlSocket = (InetSocketAddress)controlConnection.channel.localAddress();
105+
106+ // Close the control connection.
107+ scassandra.instance(1).currentClient()
108+ .closeConnection(CLOSE, controlSocket);
109+
110+ // Sleep reconnect interval * 2 to allow time to reconnect.
111+ Uninterruptibles.sleepUninterruptibly(2, SECONDS);
112+
113+ // Ensure the control connection was replaced and host 1 remains up.
114+ assertThat(cluster).hasOpenControlConnection()
115+ .host(1).isUp();
116+ assertThat(cluster.manager.controlConnection.connectionRef.get()).isNotEqualTo(controlConnection);
117+ }
118+}
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +898 −223
@@ -15,32 +15,95 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.Collection;
18+import java.net.InetSocketAddress;
19+import java.util.Iterator;
1920 import java.util.List;
2021 import java.util.concurrent.*;
2122 import java.util.concurrent.atomic.AtomicBoolean;
23+import java.util.concurrent.atomic.AtomicReference;
2224
23-import static java.util.concurrent.TimeUnit.MILLISECONDS;
25+import static java.util.Collections.singletonList;
2426 import static java.util.concurrent.TimeUnit.SECONDS;
2527
2628 import com.codahale.metrics.Gauge;
27-import com.google.common.collect.Lists;
29+import com.google.common.util.concurrent.Uninterruptibles;
30+import org.scassandra.cql.PrimitiveType;
31+import org.scassandra.http.client.PrimingRequest;
32+import org.testng.annotations.BeforeClass;
2833 import org.testng.annotations.Test;
2934
30-import static org.assertj.core.api.Assertions.assertThat;
31-import static org.mockito.Mockito.doReturn;
32-import static org.mockito.Mockito.spy;
35+import static com.google.common.collect.Lists.newArrayList;
36+import static org.mockito.Mockito.*;
37+import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE;
38+import static org.scassandra.http.client.PrimingRequest.then;
3339 import static org.testng.Assert.fail;
3440
35-public class HostConnectionPoolTest extends CCMBridge.PerClassSingleNodeCluster {
36- @Override
37- protected Collection<String> getTableDefinitions() {
38- StringBuilder sb = new StringBuilder("CREATE TABLE Java349 (mykey INT primary key");
39- for (int i = 0; i < 1000; i++) {
40- sb.append(", column").append(i).append(" INT");
41+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
42+
43+import static com.datastax.driver.core.Assertions.assertThat;
44+
45+public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster {
46+
47+
48+ @BeforeClass(groups={"short", "long"})
49+ public void reinitializeCluster() {
50+ // Don't use the provided cluster, each test will create its own instead.
51+ cluster.close();
52+ }
53+
54+ /**
55+ * Sends 101 requests on pool, asserting that the connection used is in expectedConnections, except for the last request.
56+ */
57+ private List<MockRequest> fillConnectionToThreshold(HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
58+ List<MockRequest> requests = sendRequests(100, pool, expectedConnections);
59+ requests.add(MockRequest.send(pool));
60+ return requests;
61+ }
62+
63+ /**
64+ * Sends count requests on pool.
65+ */
66+ private List<MockRequest> sendRequests(int count, HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
67+ return sendRequests(count, pool, null);
68+ }
69+
70+ /**
71+ * Sends count requests on pool, asserting that the connection used is in expectedConnections.
72+ */
73+ private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException {
74+ List<MockRequest> requests = newArrayList();
75+ for(int i = 0; i < count; i++) {
76+ MockRequest request = MockRequest.send(pool);
77+ requests.add(request);
78+ if(expectedConnections != null)
79+ assertThat(expectedConnections).contains(request.connection);
80+ }
81+ return requests;
82+ }
83+
84+ /**
85+ * Completes count requests by simulating a successful response.
86+ */
87+ private void completeRequests(int count, List<MockRequest> requests) {
88+ Iterator<MockRequest> requestIt = requests.iterator();
89+ for(int i = 0; i < count; i++) {
90+ if(requestIt.hasNext()) {
91+ MockRequest request = requestIt.next();
92+ request.simulateSuccessResponse();
93+ requestIt.remove();
94+ } else {
95+ break;
96+ }
97+ }
98+ }
99+
100+ /**
101+ * Completes all requests by simulating a successful response.
102+ */
103+ private void completeRequests(List<MockRequest> requests) {
104+ for(MockRequest request : requests) {
105+ request.simulateSuccessResponse();
41106 }
42- sb.append(")");
43- return Lists.newArrayList(sb.toString());
44107 }
45108
46109 /**
@@ -52,24 +115,24 @@
52115 * @test_category connection:connection_pool
53116 */
54117 @Test(groups = "short")
55- public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException {
56- HostConnectionPool pool = createPool(2, 2);
57-
58- assertThat(pool.connections.size()).isEqualTo(2);
59- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
60-
61- for (int i = 0; i < 256; i++) {
62- Connection connection = pool.borrowConnection(100, MILLISECONDS);
63- assertThat(coreConnections).contains(connection);
64- }
65-
66- boolean timedOut = false;
118+ public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException {
119+ Cluster cluster = createClusterBuilder().build();
120+ List<MockRequest> requests = newArrayList();
67121 try {
68- pool.borrowConnection(100, MILLISECONDS);
69- } catch (TimeoutException e) {
70- timedOut = true;
122+ HostConnectionPool pool = createPool(cluster, 2, 2);
123+
124+ assertThat(pool.connections.size()).isEqualTo(2);
125+ List<Connection> coreConnections = newArrayList(pool.connections);
126+ requests.addAll(sendRequests(256, pool, coreConnections));
127+
128+ try {
129+ MockRequest.send(pool);
130+ Assertions.fail("Expected a TimeoutException");
131+ } catch (TimeoutException e) { /*expected*/}
132+ } finally {
133+ completeRequests(requests);
134+ cluster.close();
71135 }
72- assertThat(timedOut).isTrue();
73136 }
74137
75138 /**
@@ -81,31 +144,44 @@
81144 * @test_category connection:connection_pool
82145 */
83146 @Test(groups = "short")
84- public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws ConnectionException, TimeoutException {
85- HostConnectionPool pool = createPool(1, 2);
86-
87- assertThat(pool.connections.size()).isEqualTo(1);
88- List<Connection> coreConnections = Lists.newArrayList(pool.connections);
89-
90- //
91- for (int i = 0; i < 128; i++) {
92- Connection connection = pool.borrowConnection(100, MILLISECONDS);
93- assertThat(coreConnections).contains(connection);
94- }
95-
96- // Borrow more and ensure the connection returned is a non-core connection.
97- for (int i = 0; i < 128; i++) {
98- Connection connection = pool.borrowConnection(100, MILLISECONDS);
99- assertThat(coreConnections).doesNotContain(connection);
100- }
101-
102- boolean timedOut = false;
147+ public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception {
148+ Cluster cluster = createClusterBuilder().build();
149+ List<MockRequest> requests = newArrayList();
103150 try {
104- pool.borrowConnection(100, MILLISECONDS);
105- } catch (TimeoutException e) {
106- timedOut = true;
151+ HostConnectionPool pool = createPool(cluster, 1, 2);
152+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
153+ cluster.manager.connectionFactory = factory;
154+
155+ assertThat(pool.connections.size()).isEqualTo(1);
156+ List<Connection> coreConnections = newArrayList(pool.connections);
157+
158+ // Fill enough connections to hit the threshold.
159+ requests.addAll(fillConnectionToThreshold(pool, coreConnections));
160+
161+ // Allow time for new connection to be spawned.
162+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
163+
164+ // Borrow more and ensure the connection returned is a non-core connection.
165+ for (int i = 0; i < 100; i++) {
166+ MockRequest request = MockRequest.send(pool);
167+ assertThat(coreConnections).doesNotContain(request.connection);
168+ requests.add(request);
169+ }
170+
171+ // Fill remaining connections (28 + 28) - 1
172+ requests.addAll(sendRequests(55, pool));
173+
174+ boolean timedOut = false;
175+ try {
176+ MockRequest.send(pool);
177+ } catch (TimeoutException e) {
178+ timedOut = true;
179+ }
180+ assertThat(timedOut).isTrue();
181+ } finally {
182+ completeRequests(requests);
183+ cluster.close();
107184 }
108- assertThat(timedOut).isTrue();
109185 }
110186
111187 /**
@@ -116,22 +192,25 @@
116192 * @test_category connection:connection_pool
117193 */
118194 @Test(groups = "short")
119- public void should_add_extra_connection_when_core_full() throws ConnectionException, TimeoutException, InterruptedException {
120- cluster.getConfiguration().getPoolingOptions()
121- .setIdleTimeoutSeconds(20);
122-
123- HostConnectionPool pool = createPool(1, 2);
124- Connection core = pool.connections.get(0);
125-
126- // Fill core connection
127- for (int i = 0; i < 128; i++)
128- assertThat(
129- pool.borrowConnection(100, MILLISECONDS)
130- ).isEqualTo(core);
131-
132- // Reaching 128 on the core connection should have triggered the creation of an extra one
133- TimeUnit.MILLISECONDS.sleep(100);
134- assertThat(pool.connections).hasSize(2);
195+ public void should_add_extra_connection_when_core_full() throws Exception {
196+ Cluster cluster = createClusterBuilder().build();
197+ List<MockRequest> requests = newArrayList();
198+ try {
199+ HostConnectionPool pool = createPool(cluster, 1, 2);
200+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
201+ cluster.manager.connectionFactory = factory;
202+ Connection core = pool.connections.get(0);
203+
204+ // Fill core connection + 1
205+ requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
206+
207+ // Reaching the threshold should have triggered the creation of an extra one
208+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
209+ assertThat(pool.connections).hasSize(2);
210+ } finally {
211+ completeRequests(requests);
212+ cluster.close();
213+ }
135214 }
136215
137216 /**
@@ -143,52 +222,55 @@
143222 * @test_category connection:connection_pool
144223 */
145224 @Test(groups = "long")
146- public void should_resurrect_trashed_connection_within_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
147- cluster.getConfiguration().getPoolingOptions()
148- .setIdleTimeoutSeconds(20);
149-
150- HostConnectionPool pool = createPool(1, 2);
151- Connection connection1 = pool.connections.get(0);
152-
153- for (int i = 0; i < 101; i++)
154- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
155-
156- TimeUnit.MILLISECONDS.sleep(100);
157- assertThat(pool.connections).hasSize(2);
158- Connection connection2 = pool.connections.get(1);
159-
160- assertThat(connection1.inFlight.get()).isEqualTo(101);
161- assertThat(connection2.inFlight.get()).isEqualTo(0);
162-
163- // Go back under the capacity of 1 connection
164- for (int i = 0; i < 51; i++)
165- pool.returnConnection(connection1);
166-
167- assertThat(connection1.inFlight.get()).isEqualTo(50);
168- assertThat(connection2.inFlight.get()).isEqualTo(0);
169-
170- // Given enough time, one connection gets trashed (and the implementation picks the first one)
171- TimeUnit.SECONDS.sleep(20);
172- assertThat(pool.connections).containsExactly(connection2);
173- assertThat(pool.trash).containsExactly(connection1);
174-
175- // Now borrow enough to go just under the 1 connection threshold
176- for (int i = 0; i < 50; i++)
177- pool.borrowConnection(100, MILLISECONDS);
178-
179- assertThat(pool.connections).containsExactly(connection2);
180- assertThat(pool.trash).containsExactly(connection1);
181- assertThat(connection1.inFlight.get()).isEqualTo(50);
182- assertThat(connection2.inFlight.get()).isEqualTo(50);
183-
184- // Borrowing one more time should resurrect the trashed connection
185- pool.borrowConnection(100, MILLISECONDS);
186- TimeUnit.MILLISECONDS.sleep(100);
187-
188- assertThat(pool.connections).containsExactly(connection2, connection1);
189- assertThat(pool.trash).isEmpty();
190- assertThat(connection1.inFlight.get()).isEqualTo(50);
191- assertThat(connection2.inFlight.get()).isEqualTo(51);
225+ public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception {
226+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
227+ List<MockRequest> requests = newArrayList();
228+ try {
229+ HostConnectionPool pool = createPool(cluster, 1, 2);
230+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
231+ cluster.manager.connectionFactory = factory;
232+ Connection connection1 = pool.connections.get(0);
233+
234+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
235+
236+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
237+ assertThat(pool.connections).hasSize(2);
238+ Connection connection2 = pool.connections.get(1);
239+
240+ assertThat(connection1.inFlight.get()).isEqualTo(101);
241+ assertThat(connection2.inFlight.get()).isEqualTo(0);
242+
243+ // Go back under the capacity of 1 connection
244+ completeRequests(51, requests);
245+
246+ assertThat(connection1.inFlight.get()).isEqualTo(50);
247+ assertThat(connection2.inFlight.get()).isEqualTo(0);
248+
249+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
250+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
251+ assertThat(pool.connections).containsExactly(connection2);
252+ assertThat(pool.trash).containsExactly(connection1);
253+
254+ // Now borrow enough to go just under the 1 connection threshold
255+ requests.addAll(sendRequests(50, pool));
256+
257+ assertThat(pool.connections).containsExactly(connection2);
258+ assertThat(pool.trash).containsExactly(connection1);
259+ assertThat(connection1.inFlight.get()).isEqualTo(50);
260+ assertThat(connection2.inFlight.get()).isEqualTo(50);
261+
262+ // Borrowing one more time should resurrect the trashed connection
263+ requests.addAll(sendRequests(1, pool));
264+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
265+
266+ assertThat(pool.connections).containsExactly(connection2, connection1);
267+ assertThat(pool.trash).isEmpty();
268+ assertThat(connection1.inFlight.get()).isEqualTo(50);
269+ assertThat(connection2.inFlight.get()).isEqualTo(51);
270+ } finally {
271+ completeRequests(requests);
272+ cluster.close();
273+ }
192274 }
193275
194276 /**
@@ -200,157 +282,674 @@
200282 * @test_category connection:connection_pool
201283 */
202284 @Test(groups = "long")
203- public void should_not_resurrect_trashed_connection_after_idle_timeout() throws ConnectionException, TimeoutException, InterruptedException {
204- cluster.getConfiguration().getPoolingOptions()
205- .setIdleTimeoutSeconds(20);
285+ public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception {
286+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
287+ List<MockRequest> requests = newArrayList();
288+ try {
289+ HostConnectionPool pool = createPool(cluster, 1, 2);
290+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
291+ cluster.manager.connectionFactory = factory;
292+ Connection connection1 = pool.connections.get(0);
293+
294+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
295+
296+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
297+ reset(factory);
298+ assertThat(pool.connections).hasSize(2);
299+ Connection connection2 = pool.connections.get(1);
300+
301+ assertThat(connection1.inFlight.get()).isEqualTo(101);
302+ assertThat(connection2.inFlight.get()).isEqualTo(0);
303+
304+ // Go back under the capacity of 1 connection
305+ completeRequests(51, requests);
306+
307+ assertThat(connection1.inFlight.get()).isEqualTo(50);
308+ assertThat(connection2.inFlight.get()).isEqualTo(0);
309+
310+ // Given enough time, one connection gets trashed (and the implementation picks the first one)
311+ Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
312+ assertThat(pool.connections).containsExactly(connection2);
313+ assertThat(pool.trash).containsExactly(connection1);
314+
315+ // Return trashed connection down to 0 inFlight
316+ completeRequests(50, requests);
317+ assertThat(connection1.inFlight.get()).isEqualTo(0);
318+
319+ // Give enough time for trashed connection to be cleaned up from the trash:
320+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
321+ assertThat(pool.connections).containsExactly(connection2);
322+ assertThat(pool.trash).isEmpty();
323+ assertThat(connection1.isClosed()).isTrue();
324+
325+ // Fill the live connection to go over the threshold where a second one is needed
326+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2)));
327+ assertThat(connection2.inFlight.get()).isEqualTo(101);
328+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
329+
330+ // Borrow again to get the new connection
331+ MockRequest request = MockRequest.send(pool);
332+ requests.add(request);
333+ assertThat(request.connection)
334+ .isNotEqualTo(connection2) // should not be the full connection
335+ .isNotEqualTo(connection1); // should not be the previously trashed one
336+ } finally {
337+ completeRequests(requests);
338+ cluster.close();
339+ }
340+ }
341+
342+ /**
343+ * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
344+ *
345+ * @since 2.0.10, 2.1.6
346+ * @jira_ticket JAVA-419
347+ * @test_category connection:connection_pool
348+ */
349+ @Test(groups = "long")
350+ public void should_not_close_trashed_connection_until_no_in_flight() throws Exception {
351+ Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build();
352+ List<MockRequest> requests = newArrayList();
353+
354+ try {
355+ HostConnectionPool pool = createPool(cluster, 1, 2);
356+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
357+ cluster.manager.connectionFactory = factory;
358+ Connection connection1 = pool.connections.get(0);
359+
360+ // Fill core connection enough to trigger creation of another one
361+ requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1)));
362+
363+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
364+ assertThat(pool.connections).hasSize(2);
365+
366+ // Return enough times to get back under the threshold where one connection is enough
367+ completeRequests(50, requests);
368+
369+ // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
370+ // It still has in-flight requests so should not get closed.
371+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
372+ assertThat(pool.trash).containsExactly(connection1);
373+ assertThat(connection1.inFlight.get()).isEqualTo(51);
374+ assertThat(connection1.isClosed()).isFalse();
375+
376+ // Consume all inFlight requests on the trashed connection.
377+ completeRequests(51, requests);
378+
379+ // Sleep enough time for the connection to be consider idled and closed.
380+ Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS);
381+
382+ // The connection should be now closed.
383+ // The trashed connection should be closed and not in the pool or trash.
384+ assertThat(connection1.isClosed()).isTrue();
385+ assertThat(pool.connections).doesNotContain(connection1);
386+ assertThat(pool.trash).doesNotContain(connection1);
387+ } finally {
388+ completeRequests(requests);
389+ cluster.close();
390+ }
391+ }
392+
393+ /**
394+ * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
395+ * the connection is put in the trash.
396+ *
397+ * @since 2.0.10, 2.1.6
398+ * @jira_ticket JAVA-419
399+ * @test_category connection:connection_pool
400+ */
401+ @Test(groups = "short")
402+ public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception {
403+ Cluster cluster = createClusterBuilder().build();
404+ List<MockRequest> requests = newArrayList();
405+ try {
406+ HostConnectionPool pool = createPool(cluster, 1, 2);
407+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
408+ cluster.manager.connectionFactory = factory;
409+ Connection core = pool.connections.get(0);
410+
411+ requests.addAll(fillConnectionToThreshold(pool, singletonList(core)));
412+
413+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
414+ assertThat(pool.connections).hasSize(2);
415+
416+ // Grab the new non-core connection and replace it with a spy.
417+ Connection extra1 = spy(pool.connections.get(1));
418+ pool.connections.set(1, extra1);
419+
420+ // Borrow 10 times to ensure pool is utilized.
421+ requests.addAll(sendRequests(10, pool));
422+ assertThat(pool.connections).hasSize(2);
423+
424+ // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
425+ // this should cause the connection to be replaced and trashed on returnConnection.
426+ doReturn(0).when(extra1).maxAvailableStreams();
427+
428+ // On returning of the connection, should detect that there are no available streams and trash it.
429+ assertThat(pool.trash).hasSize(0);
430+ pool.returnConnection(extra1);
431+ assertThat(pool.connections).hasSize(1);
432+ assertThat(pool.trash).hasSize(1);
433+ } finally {
434+ completeRequests(requests);
435+ cluster.close();
436+ }
437+ }
438+
439+ /**
440+ * Ensures that if a connection on a host is lost but other connections remain intact in the Pool that the
441+ * host is not marked down.
442+ *
443+ * @jira_ticket JAVA-544
444+ * @test_category connection:connection_pool
445+ * @since 2.0.11
446+ */
447+ @Test(groups="short")
448+ public void should_keep_host_up_when_one_connection_lost() throws Exception {
449+ Cluster cluster = createClusterBuilder().build();
450+ try {
451+ HostConnectionPool pool = createPool(cluster, 2, 2);
452+ Connection core0 = pool.connections.get(0);
453+ Connection core1 = pool.connections.get(1);
454+
455+ // Drop a connection and ensure the host stays up.
456+ currentClient.disableListener();
457+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
458+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
459+
460+ // connection 0 should be down, while connection 1 and the Host should remain up.
461+ assertThat(core0.isClosed()).isTrue();
462+ assertThat(core1.isClosed()).isFalse();
463+ assertThat(pool.connections).doesNotContain(core0);
464+ assertThat(cluster).host(1).hasState(Host.State.UP);
465+ assertThat(cluster).hasOpenControlConnection();
466+ } finally {
467+ cluster.close();
468+ }
469+ }
206470
207- HostConnectionPool pool = createPool(1, 2);
208- Connection connection1 = pool.connections.get(0);
209471
210- for (int i = 0; i < 101; i++)
211- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
472+ /**
473+ * Ensures that if all connections on a host are closed that the host is marked
474+ * down and the control connection is notified of that fact and re-established
475+ * itself.
476+ *
477+ * @jira_ticket JAVA-544
478+ * @test_category connection:connection_pool
479+ * @since 2.0.11
480+ */
481+ @Test(groups="short")
482+ public void should_mark_host_down_when_no_connections_remaining() throws Exception {
483+ int readTimeout = 1000;
484+ int reconnectInterval = 1000;
485+ Cluster cluster = this.createClusterBuilder()
486+ .withSocketOptions(new SocketOptions()
487+ .setConnectTimeoutMillis(readTimeout)
488+ .setReadTimeoutMillis(reconnectInterval))
489+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
490+ try {
491+ cluster.init();
212492
213- TimeUnit.MILLISECONDS.sleep(100);
214- assertThat(pool.connections).hasSize(2);
215- Connection connection2 = pool.connections.get(1);
493+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
494+ cluster.manager.connectionFactory = factory;
216495
217- assertThat(connection1.inFlight.get()).isEqualTo(101);
218- assertThat(connection2.inFlight.get()).isEqualTo(0);
496+ HostConnectionPool pool = createPool(cluster, 8,8);
497+ // copy list to track these connections.
498+ List<Connection> connections = newArrayList(pool.connections);
219499
220- // Go back under the capacity of 1 connection
221- for (int i = 0; i < 51; i++)
222- pool.returnConnection(connection1);
500+ reset(factory);
223501
224- assertThat(connection1.inFlight.get()).isEqualTo(50);
225- assertThat(connection2.inFlight.get()).isEqualTo(0);
502+ // Drop all connections.
503+ currentClient.disableListener();
504+ currentClient.closeConnections(CLOSE);
226505
227- // Given enough time, one connection gets trashed (and the implementation picks the first one)
228- TimeUnit.SECONDS.sleep(20);
229- assertThat(pool.connections).containsExactly(connection2);
230- assertThat(pool.trash).containsExactly(connection1);
506+ // The host should be marked down and the control connection closed.
507+ assertThat(cluster).host(1).goesDownWithin(10, TimeUnit.SECONDS);
508+ assertThat(cluster).hasClosedControlConnection();
231509
232- // Return trashed connection down to 0 inFlight
233- for (int i = 0; i < 50; i++)
234- pool.returnConnection(connection1);
235- assertThat(connection1.inFlight.get()).isEqualTo(0);
510+ // Ensure all connections are closed.
511+ for(Connection connection : connections) {
512+ assertThat(connection.isClosed()).isTrue();
513+ }
236514
237- // Give enough time for trashed connection to be cleaned up from the trash:
238- TimeUnit.SECONDS.sleep(30);
239- assertThat(pool.connections).containsExactly(connection2);
240- assertThat(pool.trash).isEmpty();
241- assertThat(connection1.isClosed()).isTrue();
515+ // Expect a reconnect attempt on host after reconnect interval
516+ // on behalf of the control connection.
517+ verify(factory, timeout(reconnectInterval*2).atLeastOnce()).open(host);
518+
519+ // Sleep for a bit to allow reconnect to fail.
520+ Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
521+
522+ // Ensure control connection is still closed.
523+ assertThat(cluster).hasClosedControlConnection();
524+
525+ // Reenable connectivity.
526+ currentClient.enableListener();
527+
528+ // Reconnect attempt should have been connected for control connection
529+ // and pool.
530+ // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
531+ verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
532+ // 7 attempts for core connections after first initial connection.
533+ verify(factory, timeout(reconnectInterval*2).times(7)).newConnection(any(HostConnectionPool.class));
534+
535+ // Wait some reasonable amount of time for connection to reestablish.
536+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
537+
538+ // Control Connection should now be open.
539+ assertThat(cluster).hasOpenControlConnection();
540+ assertThat(cluster).host(1).hasState(Host.State.UP);
541+ } finally {
542+ cluster.close();
543+ }
544+ }
242545
243- // Fill the live connection to go over the threshold where a second one is needed
244- for (int i = 0; i < 101; i++)
245- assertThat(pool.borrowConnection(100, TimeUnit.MILLISECONDS)).isEqualTo(connection2);
246- assertThat(connection2.inFlight.get()).isEqualTo(101);
247- TimeUnit.MILLISECONDS.sleep(100);
248546
249- // Borrow again to get the new connection
250- Connection connection3 = pool.borrowConnection(100, MILLISECONDS);
251- assertThat(connection3)
252- .isNotEqualTo(connection2) // should not be the full connection
253- .isNotEqualTo(connection1); // should not be the previously trashed one
547+ /**
548+ * Ensures that if a connection on a host is lost that brings the number of active connections in a pool
549+ * under core connection count that up to core connections are re-established, but only after the
550+ * next reconnect schedule has elapsed.
551+ *
552+ * @jira_ticket JAVA-544
553+ * @test_category connection:connection_pool
554+ * @since 2.0.11
555+ */
556+ @Test(groups="short")
557+ public void should_create_new_connections_when_connection_lost_and_under_core_connections() throws Exception {
558+ int readTimeout = 1000;
559+ int reconnectInterval = 1000;
560+ Cluster cluster = this.createClusterBuilder()
561+ .withSocketOptions(new SocketOptions()
562+ .setConnectTimeoutMillis(readTimeout)
563+ .setReadTimeoutMillis(reconnectInterval))
564+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
565+ List<MockRequest> requests = newArrayList();
566+ try {
567+ cluster.init();
568+
569+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
570+ cluster.manager.connectionFactory = factory;
571+
572+ HostConnectionPool pool = createPool(cluster, 3, 3);
573+ Connection core0 = pool.connections.get(0);
574+ Connection core1 = pool.connections.get(1);
575+ Connection core2 = pool.connections.get(2);
576+
577+ // Drop two core connections.
578+ // Disable new connections initially and we'll eventually reenable it.
579+ currentClient.disableListener();
580+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
581+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core2.channel.localAddress()));
582+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
583+
584+ // Since we have a connection left the host should remain up.
585+ assertThat(cluster).host(1).hasState(Host.State.UP);
586+ assertThat(pool.connections).hasSize(1);
587+
588+ // The borrowed connection should be the open one.
589+ MockRequest request = MockRequest.send(pool);
590+ requests.add(request);
591+ assertThat(request.connection).isEqualTo(core1);
592+
593+ // Should not have tried to create a new core connection since reconnection time had not elapsed.
594+ verify(factory, never()).open(any(HostConnectionPool.class));
595+
596+ // Sleep to elapse the Reconnection Policy.
597+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
598+
599+ // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection.
600+ request = MockRequest.send(pool);
601+ requests.add(request);
602+ assertThat(request.connection).isEqualTo(core1);
603+
604+ // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core.
605+ verify(factory, timeout(reconnectInterval).times(1)).open(any(HostConnectionPool.class));
606+ reset(factory);
607+
608+ // Sleep for reconnect interval to allow reconnection time to elapse.
609+ Uninterruptibles.sleepUninterruptibly((readTimeout + reconnectInterval) * 2, TimeUnit.MILLISECONDS);
610+
611+ // Enable listening so new connections succeed.
612+ currentClient.enableListener();
613+ // Sleep to elapse the Reconnection Policy.
614+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
615+
616+ // Try to borrow a connection, the pool should grow.
617+ requests.add(MockRequest.send(pool));
618+ verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
619+ reset(factory);
620+
621+ // Another core connection should be opened as result of another request to get us up to core connections.
622+ requests.add(MockRequest.send(pool));
623+ verify(factory, timeout((reconnectInterval + readTimeout) * 2).times(1)).open(any(HostConnectionPool.class));
624+ reset(factory);
625+
626+ // Sending another request should not grow the pool any more, since we are now at core connections.
627+ requests.add(MockRequest.send(pool));
628+ verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class));
629+ } finally {
630+ completeRequests(requests);
631+ cluster.close();
632+ }
254633 }
255634
256635 /**
257- * Ensures that a trashed connection that has been timed out should not be closed until it has 0 in flight requests.
636+ * Ensures that if a connection on a host is lost and the number of remaining connections is at
637+ * core connection count that no connections are re-established until after there are enough
638+ * inflight requests to justify creating one and the reconnection interval has elapsed.
258639 *
259- * @since 2.0.10, 2.1.6
260- * @jira_ticket JAVA-419
640+ * @jira_ticket JAVA-544
261641 * @test_category connection:connection_pool
642+ * @since 2.0.11
262643 */
263- @Test(groups = "long")
264- public void should_not_close_trashed_connection_until_no_in_flight()
265- throws ConnectionException, TimeoutException, InterruptedException {
266- cluster.getConfiguration().getPoolingOptions()
267- .setIdleTimeoutSeconds(20);
644+ @Test(groups = "short")
645+ public void should_not_schedule_reconnect_when_connection_lost_and_at_core_connections() throws Exception {
646+ int readTimeout = 1000;
647+ int reconnectInterval = 1000;
648+ Cluster cluster = this.createClusterBuilder()
649+ .withSocketOptions(new SocketOptions()
650+ .setConnectTimeoutMillis(readTimeout)
651+ .setReadTimeoutMillis(reconnectInterval))
652+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
653+ List<MockRequest> requests = newArrayList();
654+ try {
655+ cluster.init();
656+
657+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
658+ cluster.manager.connectionFactory = factory;
659+
660+ HostConnectionPool pool = createPool(cluster, 1, 2);
661+ Connection core0 = pool.connections.get(0);
662+
663+ // Create enough inFlight requests to spawn another connection.
664+ List<MockRequest> core0requests = newArrayList();
665+ for (int i = 0; i < 101; i++) {
666+ MockRequest request = MockRequest.send(pool);
667+ assertThat(request.connection).isEqualTo(core0);
668+ core0requests.add(request);
669+ }
268670
269- HostConnectionPool pool = createPool(1, 2);
270- Connection connection1 = pool.connections.get(0);
671+ // Pool should grow by 1.
672+ verify(factory, after(1000).times(1)).open(any(HostConnectionPool.class));
673+ assertThat(pool.connections).hasSize(2);
271674
272- // Fill core connection enough to trigger creation of another one
273- for (int i = 0; i < 110; i++)
274- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(connection1);
675+ // Reset factory mock as we'll be checking for new open() invokes later.
676+ reset(factory);
275677
276- TimeUnit.MILLISECONDS.sleep(100);
277- assertThat(pool.connections).hasSize(2);
678+ // Grab the new non-core connection.
679+ Connection extra1 = pool.connections.get(1);
278680
279- // Return enough times to get back under the threshold where one connection is enough
280- for (int i = 0; i < 50; i++)
281- pool.returnConnection(connection1);
681+ // Drop a connection and disable listening.
682+ currentClient.closeConnection(CLOSE, ((InetSocketAddress)core0.channel.localAddress()));
683+ Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
684+ currentClient.disableListener();
282685
283- // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one.
284- // It still has in-flight requests so should not get closed.
285- TimeUnit.SECONDS.sleep(30);
286- assertThat(pool.trash).containsExactly(connection1);
287- assertThat(connection1.inFlight.get()).isEqualTo(60);
288- assertThat(connection1.isClosed()).isFalse();
686+ // Since core0 was closed, all of it's requests should have errored.
687+ for(MockRequest request : core0requests) {
688+ verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt());
689+ }
289690
290- // Consume all inFlight requests on the trashed connection.
291- while (connection1.inFlight.get() > 0) {
292- pool.returnConnection(connection1);
691+ assertThat(cluster).host(1).hasState(Host.State.UP);
692+
693+ // Create enough inFlight requests to fill connection.
694+ requests.addAll(sendRequests(100, pool, singletonList(extra1)));
695+ assertThat(pool.connections).hasSize(1);
696+
697+ // A new connection should never have been spawned since we didn't max out core.
698+ verify(factory, after(readTimeout).never()).open(any(HostConnectionPool.class));
699+
700+ // Borrow another connection, since we exceed max another connection should be opened.
701+ MockRequest request = MockRequest.send(pool);
702+ requests.add(request);
703+ assertThat(request.connection).isEqualTo(extra1);
704+
705+ // After some time the a connection should attempt to be opened (but will fail).
706+ verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
707+ assertThat(pool.connections).hasSize(1);
708+
709+ // Wait some reasonable amount of time for connection to reestablish then check pool size.
710+ Uninterruptibles.sleepUninterruptibly(readTimeout * 2, TimeUnit.MILLISECONDS);
711+ // Reconnecting failed since listening was enabled.
712+ assertThat(pool.connections).hasSize(1);
713+
714+ // Re enable listening then wait for reconnect.
715+ currentClient.enableListener();
716+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
717+
718+ // Borrow another connection, since we exceed max another connection should be opened.
719+ request = MockRequest.send(pool);
720+ requests.add(request);
721+ assertThat(request.connection).isEqualTo(extra1);
722+
723+ // Wait some reasonable amount of time for connection to reestablish then check pool size.
724+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
725+ // Reconnecting should have exceeded and pool will have grown.
726+ assertThat(pool.connections).hasSize(2);
727+
728+ // Borrowed connection should be the newly spawned connection since the other one has some inflight requests.
729+ request = MockRequest.send(pool);
730+ requests.add(request);
731+ assertThat(request.connection).isNotEqualTo(core0).isNotEqualTo(extra1);
732+ } finally {
733+ completeRequests(requests);
734+ cluster.close();
293735 }
736+ }
294737
295- // Sleep enough time for the connection to be consider idled and closed.
296- TimeUnit.SECONDS.sleep(30);
297-
298- // The connection should be now closed.
299- // The trashed connection should be closed and not in the pool or trash.
300- assertThat(connection1.isClosed()).isTrue();
301- assertThat(pool.connections).doesNotContain(connection1);
302- assertThat(pool.trash).doesNotContain(connection1);
738+ /**
739+ * Ensures that if some connections fail on pool init that the host and subsequently the
740+ * control connection is not marked down. The test also ensures that when making requests
741+ * on the pool that connections are brought up to core.
742+ *
743+ * @jira_ticket JAVA-544
744+ * @test_category connection:connection_pool
745+ * @since 2.0.11
746+ */
747+ @Test(groups="short")
748+ public void should_not_mark_host_down_if_some_connections_fail_on_init() throws Exception {
749+ int readTimeout = 1000;
750+ int reconnectInterval = 1000;
751+ Cluster cluster = this.createClusterBuilder()
752+ .withSocketOptions(new SocketOptions()
753+ .setConnectTimeoutMillis(readTimeout)
754+ .setReadTimeoutMillis(reconnectInterval))
755+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
756+ List<MockRequest> requests = newArrayList();
757+ try {
758+ cluster.init();
759+
760+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
761+ cluster.manager.connectionFactory = factory;
762+
763+ // Allow the first 4 connections to establish, but disable after that.
764+ currentClient.disableListener(4);
765+ HostConnectionPool pool = createPool(cluster, 8, 8);
766+
767+ reset(factory);
768+
769+ // Pool size should show all successful connections.
770+ assertThat(pool.connections).hasSize(4);
771+
772+ // Control connection should remain up in addition to to host.
773+ assertThat(cluster).host(1).hasState(Host.State.UP);
774+ assertThat(cluster).hasOpenControlConnection();
775+
776+ // Reenable listener, wait reconnectInterval and then try borrowing a connection.
777+ currentClient.enableListener();
778+
779+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
780+
781+ // Should open up to core connections, however it will only spawn up to 1 connection
782+ // per request, so we need to make enough requests to make up the deficit. Additionally
783+ // we need to wait for connections to be established between requests for the pool
784+ // to spawn new connections (since it only allows one simultaneous creation).
785+ for (int i = 5; i <= 8; i++) {
786+ requests.add(MockRequest.send(pool));
787+ verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class));
788+ reset(factory);
789+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
790+ assertThat(pool.connections).hasSize(i);
791+ }
792+ } finally {
793+ completeRequests(requests);
794+ cluster.close();
795+ }
303796 }
304797
305798 /**
306- * Ensures that if a connection that has less than the minimum available stream ids is returned to the pool that
307- * the connection is put in the trash.
799+ * Ensures that if all connections fail on pool init that the host and subsequently the
800+ * control connection is not marked down since the control connection is still active.
801+ * on the pool that a TimeoutException is yielded if we are still in the reconnection window
802+ * according to the ConvictionPolicy.
308803 *
309- * @since 2.0.10, 2.1.6
310- * @jira_ticket JAVA-419
804+ * @jira_ticket JAVA-544
311805 * @test_category connection:connection_pool
806+ * @since 2.0.11
312807 */
313- @Test(groups = "short")
314- public void should_trash_on_returning_connection_with_insufficient_streams()
315- throws ConnectionException, TimeoutException, InterruptedException {
316- HostConnectionPool pool = createPool(1, 2);
317- Connection core = pool.connections.get(0);
808+ @Test(groups = "short", expectedExceptions = TimeoutException.class)
809+ public void should_throw_exception_if_convicted_and_no_connections_available() throws Exception {
810+ int readTimeout = 1000;
811+ int reconnectInterval = 1000;
812+ Cluster cluster = this.createClusterBuilder()
813+ .withSocketOptions(new SocketOptions()
814+ .setConnectTimeoutMillis(readTimeout)
815+ .setReadTimeoutMillis(reconnectInterval))
816+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
817+ try {
818+ // Init cluster so control connection is created.
819+ cluster.init();
820+ assertThat(cluster).hasOpenControlConnection();
821+
822+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
823+ cluster.manager.connectionFactory = factory;
318824
319- for (int i = 0; i < 128; i++)
320- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(core);
825+ // Disable listener so all connections on pool fail.
826+ currentClient.disableListener();
827+ HostConnectionPool pool = createPool(cluster, 8, 8);
321828
322- TimeUnit.MILLISECONDS.sleep(100);
323- assertThat(pool.connections).hasSize(2);
829+ reset(factory);
324830
325- // Grab the new non-core connection and replace it with a spy.
326- Connection extra1 = spy(pool.connections.get(1));
327- pool.connections.set(1, extra1);
831+ // Pool should be empty.
832+ assertThat(pool.connections).hasSize(0);
328833
329- // Borrow 10 times to ensure pool is utilized.
330- for (int i = 0; i < 10; i++) {
331- assertThat(pool.borrowConnection(100, MILLISECONDS)).isEqualTo(extra1);
834+ // Control connection should stay up with the host.
835+ assertThat(cluster).host(1).hasState(Host.State.UP);
836+ assertThat(cluster).hasOpenControlConnection();
837+
838+ MockRequest.send(pool);
839+ } finally {
840+ cluster.close();
332841 }
842+ }
333843
334- // Return connection, it should not be trashed since it still has 9 inflight requests.
335- pool.returnConnection(extra1);
336- assertThat(pool.connections).hasSize(2);
337844
338- // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams.
339- // this should cause the connection to be replaced and trashed on returnConnection.
340- doReturn(0).when(extra1).maxAvailableStreams();
845+ /**
846+ * Ensures that if all connections fail on pool init that the host and subsequently the
847+ * control connection is not marked down. The test also ensures that when making requests
848+ * on the pool after the conviction period that all core connections are created.
849+ *
850+ * @jira_ticket JAVA-544
851+ * @test_category connection:connection_pool
852+ * @since 2.0.11
853+ */
854+ @Test(groups="short")
855+ public void should_wait_on_connection_if_not_convicted_and_no_connections_available() throws Exception {
856+ int readTimeout = 1000;
857+ int reconnectInterval = 1000;
858+ Cluster cluster = this.createClusterBuilder()
859+ .withSocketOptions(new SocketOptions()
860+ .setConnectTimeoutMillis(readTimeout)
861+ .setReadTimeoutMillis(reconnectInterval))
862+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
863+ try {
864+ // Init cluster so control connection is created.
865+ cluster.init();
866+ assertThat(cluster).hasOpenControlConnection();
867+
868+ Connection.Factory factory = spy(cluster.manager.connectionFactory);
869+ cluster.manager.connectionFactory = factory;
870+
871+ // Disable listener so all connections on pool fail.
872+ currentClient.disableListener();
873+ HostConnectionPool pool = createPool(cluster, 8, 8);
874+
875+ // Pool should be empty.
876+ assertThat(pool.connections).hasSize(0);
877+
878+ // Control connection should stay up with the host.
879+ assertThat(cluster).host(1).hasState(Host.State.UP);
880+ assertThat(cluster).hasOpenControlConnection();
881+
882+ currentClient.enableListener();
883+
884+ // Wait for reconnectInterval so ConvictionPolicy allows connection to be created.
885+ Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS);
886+
887+ reset(factory);
888+ MockRequest request = MockRequest.send(pool);
889+ request.simulateSuccessResponse();
890+
891+ // Should create up to core connections.
892+ verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class));
893+ Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
894+ assertThat(pool.connections).hasSize(8);
895+ } finally {
896+ cluster.close();
897+ }
898+ }
341899
342- // On returning of the connection, should detect that there are no available streams and trash it.
343- pool.returnConnection(extra1);
344- assertThat(pool.connections).hasSize(1);
900+ /**
901+ * Ensures that if a pool is created with zero core connections that when a request
902+ * is first sent that one and only one connection is created and that it waits on availability
903+ * of that connection and returns it.
904+ *
905+ * @jira_ticket JAVA-544
906+ * @test_category connection:connection_pool
907+ * @since 2.0.11
908+ */
909+ @Test(groups="short")
910+ public void should_wait_on_connection_if_zero_core_connections() throws Exception {
911+ int readTimeout = 1000;
912+ int reconnectInterval = 1000;
913+ Cluster cluster = this.createClusterBuilder()
914+ .withSocketOptions(new SocketOptions()
915+ .setConnectTimeoutMillis(readTimeout)
916+ .setReadTimeoutMillis(reconnectInterval))
917+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build();
918+ try {
919+ // Init cluster so control connection is created.
920+ cluster.init();
921+ assertThat(cluster).hasOpenControlConnection();
922+
923+ HostConnectionPool pool = createPool(cluster, 0, 2);
924+
925+ // Pool should be empty.
926+ assertThat(pool.connections).hasSize(0);
927+
928+ // Control connection should stay up with the host.
929+ assertThat(cluster).host(1).hasState(Host.State.UP);
930+ assertThat(cluster).hasOpenControlConnection();
931+
932+ // Send a request, this should create a connection.
933+ MockRequest request = MockRequest.send(pool);
934+ request.simulateSuccessResponse();
935+
936+ // Should create up to core connections.
937+ assertThat(pool.connections).hasSize(1);
938+ } finally {
939+ cluster.close();
940+ }
345941 }
346942
347- private HostConnectionPool createPool(int coreConnections, int maxConnections) {
943+ private HostConnectionPool createPool(Cluster cluster, int coreConnections, int maxConnections) {
348944 cluster.getConfiguration().getPoolingOptions()
349- .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections)
350- .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections);
945+ .setMaxConnectionsPerHost(HostDistance.LOCAL, maxConnections)
946+ .setCoreConnectionsPerHost(HostDistance.LOCAL, coreConnections);
351947 Session session = cluster.connect();
352948 Host host = TestUtils.findHost(cluster, 1);
353- return ((SessionManager)session).pools.get(host);
949+
950+ // Replace the existing pool with a spy pool and return it.
951+ SessionManager sm = ((SessionManager)session);
952+ return sm.pools.get(host);
354953 }
355954
356955 /**
@@ -396,7 +995,8 @@
396995 // Insert 100k lines in a newly created 1k columns table
397996 PreparedStatement insertStatement = session.prepare(generateJava349InsertStatement());
398997 for (int key = 0; key < numberOfInserts; key++) {
399- session.executeAsync(insertStatement.bind(key)).addListener(progressReporter, progressReportExecutor);
998+ ResultSetFuture future = session.executeAsync(insertStatement.bind(key));
999+ future.addListener(progressReporter, progressReportExecutor);
4001000 }
4011001
4021002 // Wait for all inserts to happen and stop connections and progress tracking
@@ -419,6 +1019,81 @@
4191019 sb.append(", ").append(i);
4201020 }
4211021 sb.append(");");
1022+
1023+ PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()
1024+ .withQuery(sb.toString())
1025+ .withThen(then().withVariableTypes(PrimitiveType.INT))
1026+ .build();
1027+ primingClient.prime(preparedStatementPrime);
4221028 return sb.toString();
4231029 }
1030+
1031+ /** Mock ResponseCallback that simulates the behavior of SpeculativeExecution (in terms of borrowing/releasing connections). */
1032+ static class MockRequest implements Connection.ResponseCallback {
1033+
1034+ enum State { START, COMPLETED, FAILED, TIMED_OUT }
1035+
1036+ final Connection connection;
1037+ private Connection.ResponseHandler responseHandler;
1038+
1039+ private final AtomicReference<State> state = new AtomicReference<State>(State.START);
1040+
1041+ static MockRequest send(HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException {
1042+ // Create a MockRequest and spy on it. Create a response handler and add it to the connection's dispatcher.
1043+ MockRequest request = spy(new MockRequest(pool));
1044+ request.responseHandler = new Connection.ResponseHandler(request.connection, request);
1045+ request.connection.dispatcher.add(request.responseHandler);
1046+ return request;
1047+ }
1048+
1049+ private MockRequest(HostConnectionPool pool) throws ConnectionException, TimeoutException, BusyConnectionException {
1050+ connection = pool.borrowConnection(500, TimeUnit.MILLISECONDS);
1051+ }
1052+
1053+ void simulateSuccessResponse() {
1054+ onSet(connection, null, 0, 0);
1055+ }
1056+
1057+ @SuppressWarnings("unused")
1058+ void simulateErrorResponse() {
1059+ onException(connection, null, 0, 0);
1060+ }
1061+
1062+ @SuppressWarnings("unused")
1063+ void simulateTimeout() {
1064+ if (onTimeout(connection, 0, 0))
1065+ responseHandler.cancelHandler();
1066+ }
1067+
1068+ @Override
1069+ public void onSet(Connection connection, Message.Response response, long latency, int retryCount) {
1070+ if (state.compareAndSet(State.START, State.COMPLETED)) {
1071+ connection.release();
1072+ connection.dispatcher.removeHandler(responseHandler, true);
1073+ }
1074+ }
1075+
1076+ @Override
1077+ public void onException(Connection connection, Exception exception, long latency, int retryCount) {
1078+ if (state.compareAndSet(State.START, State.FAILED)) {
1079+ connection.release();
1080+ connection.dispatcher.removeHandler(responseHandler, true);
1081+ }
1082+ }
1083+
1084+ @Override
1085+ public boolean onTimeout(Connection connection, long latency, int retryCount) {
1086+ return state.compareAndSet(State.START, State.TIMED_OUT);
1087+ }
1088+
1089+ @Override
1090+ public Message.Request request() {
1091+ return null; // not needed for this test class
1092+ }
1093+
1094+ @Override
1095+ public int retryCount() {
1096+ return 0; // value not important for this test class
1097+ }
1098+ }
4241099 }
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +4 −0
@@ -123,6 +123,10 @@
123123 activityClient.clearAllRecordedActivity();
124124 }
125125
126+ public Scassandra instance(int node) {
127+ return scassandras.get(node -1);
128+ }
129+
126130 private void primePeers() {
127131 for (int i = 0; i < scassandras.size(); i++)
128132 primePeers(primingClients.get(i), scassandras.get(i));
modified driver-core/src/test/java/com/datastax/driver/core/ScassandraTestBase.java +23 −3
@@ -16,9 +16,12 @@
1616 package com.datastax.driver.core;
1717
1818 import java.net.InetSocketAddress;
19+import java.util.Collections;
1920
2021 import org.scassandra.Scassandra;
22+import org.scassandra.ScassandraFactory;
2123 import org.scassandra.http.client.ActivityClient;
24+import org.scassandra.http.client.CurrentClient;
2225 import org.scassandra.http.client.PrimingClient;
2326 import org.slf4j.Logger;
2427 import org.slf4j.LoggerFactory;
@@ -38,6 +41,8 @@
3841 * consider using {@link com.datastax.driver.core.ScassandraTestBase.PerClassCluster} instead.
3942 */
4043 public abstract class ScassandraTestBase {
44+ private static final int BINARY_PORT = 9042;
45+ private static final int ADMIN_PORT = 9052;
4146
4247 private static final Logger logger = LoggerFactory.getLogger(ScassandraTestBase.class);
4348
@@ -49,13 +54,17 @@
4954
5055 protected ActivityClient activityClient;
5156
57+ protected CurrentClient currentClient;
58+
5259 @BeforeClass(groups = { "short", "long" })
5360 public void startScassandra() {
54- scassandra = TestUtils.createScassandraServer();
61+ String ip = CCMBridge.IP_PREFIX + "1";
62+ scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
5563 scassandra.start();
5664 primingClient = scassandra.primingClient();
5765 activityClient = scassandra.activityClient();
58- hostAddress = new InetSocketAddress("127.0.0.1", scassandra.getBinaryPort());
66+ currentClient = scassandra.currentClient();
67+ hostAddress = new InetSocketAddress(ip, scassandra.getBinaryPort());
5968 }
6069
6170 @AfterClass(groups = { "short", "long" })
@@ -69,11 +78,12 @@
6978 public void resetClients() {
7079 activityClient.clearAllRecordedActivity();
7180 primingClient.clearAllPrimes();
81+ currentClient.enableListener();
7282 }
7383
7484 protected Cluster.Builder createClusterBuilder() {
7585 Cluster.Builder builder = Cluster.builder()
76- .addContactPoint("127.0.0.1")
86+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
7787 .withPoolingOptions(new PoolingOptions()
7888 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
7989 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
@@ -82,6 +92,16 @@
8292 return builder;
8393 }
8494
95+ /**
96+ * An overrideable method for building on to the Cluster.Builder used for this
97+ * class.
98+ * @param builder
99+ * @return
100+ */
101+ protected Cluster.Builder configure(Cluster.Builder builder) {
102+ return builder;
103+ }
104+
85105 protected Host retrieveSingleHost(Cluster cluster) {
86106 Host host = cluster.getMetadata().getHost(hostAddress);
87107 if(host == null) {
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +5 −0
@@ -397,6 +397,11 @@
397397 return null;
398398 }
399399
400+ public static HostConnectionPool poolOf(Session session, int hostNumber) {
401+ SessionManager sessionManager = (SessionManager)session;
402+ return sessionManager.pools.get(findHost(session.getCluster(), hostNumber));
403+ }
404+
400405 public static int numberOfLocalCoreConnections(Cluster cluster) {
401406 Configuration configuration = cluster.getConfiguration();
402407 return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL);
modified pom.xml +1 −1
@@ -60,7 +60,7 @@
6060 <testng.version>6.8.8</testng.version>
6161 <assertj.version>1.7.0</assertj.version>
6262 <mockito.version>1.10.8</mockito.version>
63- <scassandra.version>0.9.1</scassandra.version>
63+ <scassandra.version>0.10.0</scassandra.version>
6464 <main.basedir>${project.basedir}</main.basedir>
6565 </properties>
6666