Elffuss BraidHub

kikocis/java-driver public

Merge pull request #443 from datastax/scassandra010

Update tests to use Scassandra 0.10.0, tests for JAVA-544, other test cleanup.
Changeset9e2d831fa720518a846fd600023cf971ca7a0aae697ec68210dd33240509e339
AuthorOlivier Michallat <olim7t@users.noreply.github.com> · 2015-09-29 16:32 -07:00
CommitterOlivier Michallat <olim7t@users.noreply.github.com> · 2015-09-29 16:32 -07:00
Parentsa5f98239766e, d4baa70f2ddd

Browse the files at this changeset

19 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/AbstractReconnectionHandlerTest.java +31 −5
@@ -46,7 +46,7 @@
4646 final AtomicReference<ListenableFuture<?>> future = new AtomicReference<ListenableFuture<?>>();
4747 AbstractReconnectionHandler handler;
4848
49- @BeforeMethod(groups = "unit")
49+ @BeforeMethod(groups = {"unit", "short"})
5050 public void setup() {
5151 executor = Executors.newScheduledThreadPool(2);
5252 schedule = new MockReconnectionSchedule();
@@ -65,7 +65,7 @@
6565 };
6666 }
6767
68- @AfterMethod(groups = "unit")
68+ @AfterMethod(groups = {"unit", "short"})
6969 public void tearDown() {
7070 if (future.get() != null)
7171 future.get().cancel(false);
@@ -115,10 +115,9 @@
115115 }
116116
117117 @Test(groups = "unit")
118- public void should_stop_if_cancelled_between_attempts() {
119- handler.start();
120-
118+ public void should_stop_if_cancelled_before_first_attempt() {
121119 schedule.delay = 10 * 1000; // give ourselves time to cancel
120+ handler.start();
122121 schedule.tick();
123122
124123 future.get().cancel(false);
@@ -130,6 +129,33 @@
130129 assertThat(future.get().isCancelled()).isTrue();
131130 }
132131
132+ @Test(groups = "short")
133+ public void should_stop_if_cancelled_between_attempts() {
134+ handler.start();
135+
136+ // Force a failed reconnect.
137+ schedule.tick();
138+ work.nextReconnect = ReconnectBehavior.THROW_EXCEPTION;
139+ // Tick work, should trigger the barrier in tryReconnect.
140+ work.tick();
141+
142+ // Tick schedule, should cause nextDelayMs to proceed, reconnect handler will call reschedule.
143+ schedule.delay = 3000;
144+ schedule.tick();
145+
146+ // At this point the reconnect should be scheduled but not executed yet, cancel the future.
147+ future.get().cancel(false);
148+
149+ // Should block until scheduler runs, detects cancel and exits.
150+ waitForCompletion();
151+
152+ assertThat(work.success).isFalse();
153+ // Should have had 1 failed attempt, no second attempt since cancelled.
154+ assertThat(work.tries).isEqualTo(1);
155+ // The future will be marked null once it is detected as cancelled.
156+ assertThat(future.get()).isNull();
157+ }
158+
133159 @Test(groups = "unit")
134160 public void should_complete_if_cancelled_during_successful_reconnect() throws InterruptedException {
135161 handler.start();
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +26 −25
@@ -25,12 +25,11 @@
2525
2626 import com.google.common.collect.ImmutableList;
2727 import com.google.common.collect.ImmutableList.Builder;
28-import org.mockito.Mockito;
2928
3029 import static org.mockito.Mockito.mock;
31-import static org.testng.Assert.*;
32-
33-import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
30+import static org.testng.Assert.assertEquals;
31+import static org.testng.Assert.assertNotNull;
32+import static org.testng.Assert.assertTrue;
3433
3534 /**
3635 * Base class for replication strategy tests. Currently only supports testing
@@ -40,25 +39,27 @@
4039
4140 private static final Token.Factory partitioner = Token.getFactory("Murmur3Partitioner");
4241
42+ private static final Cluster.Manager mockManager = mock(Cluster.Manager.class);
43+
4344 protected static class HostMock extends Host {
44- private final String address;
45+ private final InetSocketAddress address;
4546
46- private HostMock(String address, Cluster.Manager manager) throws UnknownHostException {
47- super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager);
47+ private HostMock(InetSocketAddress address, Cluster.Manager manager) {
48+ super(address, new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager);
4849 this.address = address;
4950 }
5051
51- private HostMock(String address, String dc, String rack, Cluster.Manager manager) throws UnknownHostException {
52+ private HostMock(InetSocketAddress address, String dc, String rack, Cluster.Manager manager) {
5253 this(address, manager);
5354 this.setLocationInfo(dc, rack);
5455 }
5556
5657 @Override
5758 public String toString() {
58- return address;
59+ return address.getHostName();
5960 }
6061
61- public String getMockAddress() {
62+ public InetSocketAddress getMockAddress() {
6263 return address;
6364 }
6465
@@ -84,24 +85,16 @@
8485 * Convenience method to quickly create a mock host by a given address.
8586 * Specified address must be accessible, otherwise a RuntimeException is thrown
8687 */
87- protected static HostMock host(String address) {
88- try {
89- return new HostMock(address, mock(Cluster.Manager.class));
90- } catch (UnknownHostException ex) {
91- throw new RuntimeException(ex); //wrap to avoid declarations
92- }
88+ protected static HostMock host(InetSocketAddress address) {
89+ return new HostMock(address, mockManager);
9390 }
9491
9592 /**
9693 * Convenience method to quickly create a mock host by the given address
9794 * located in the given datacenter/rack
9895 */
99- protected static HostMock host(String address, String dc, String rack) {
100- try {
101- return new HostMock(address, dc, rack, mock(Cluster.Manager.class));
102- } catch (UnknownHostException ex) {
103- throw new RuntimeException(ex); //wrap to avoid declarations
104- }
96+ protected static HostMock host(InetSocketAddress address, String dc, String rack) {
97+ return new HostMock(address, dc, rack, mockManager);
10598 }
10699
107100 /**
@@ -117,7 +110,7 @@
117110 * if created by the <code>host(...)</code> methods. Returns null if
118111 * given host is not a mock.
119112 */
120- protected static String mockAddress(Host host) {
113+ protected static InetSocketAddress mockAddress(Host host) {
121114 HostMock mock = asMock(host);
122115 return mock == null ? null : mock.getMockAddress();
123116 }
@@ -138,7 +131,7 @@
138131 * Asserts that the replica map for a given token contains the expected list of replica hosts.
139132 * Hosts are checked in order, replica placement should be an ordered set
140133 */
141- protected static void assertReplicaPlacement(Map<Token, Set<Host>> replicaMap, Token token, String... expected) {
134+ protected static void assertReplicaPlacement(Map<Token, Set<Host>> replicaMap, Token token, InetSocketAddress... expected) {
142135 Set<Host> replicaSet = replicaMap.get(token);
143136 assertNotNull(replicaSet);
144137 assertReplicasForToken(replicaSet, expected);
@@ -147,7 +140,7 @@
147140 /**
148141 * Checks if a given ordered set of replicas matches the expected list of replica hosts
149142 */
150- protected static void assertReplicasForToken(Set<Host> replicaSet, String... expected) {
143+ protected static void assertReplicasForToken(Set<Host> replicaSet, InetSocketAddress... expected) {
151144 final String message = "Contents of replica set: " + replicaSet + " do not match expected hosts: " + Arrays.toString(expected);
152145 assertEquals(replicaSet.size(), expected.length, message);
153146
@@ -161,4 +154,12 @@
161154 assertTrue(match, message);
162155 }
163156 }
157+
158+ protected static InetSocketAddress socketAddress(String address) {
159+ try {
160+ return new InetSocketAddress(InetAddress.getByName(address), 9042);
161+ } catch(UnknownHostException ex) {
162+ throw new RuntimeException(ex);
163+ }
164+ }
164165 }
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/ClusterInitTest.java +1 −1
@@ -150,7 +150,7 @@
150150 * @test_category connection
151151 * @expected_result Cluster closes within 1 second.
152152 */
153- @Test(groups = "unit")
153+ @Test(groups = "short")
154154 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
155155 Cluster cluster = Cluster.builder()
156156 .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
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/LargeDataTest.java +5 −5
@@ -181,7 +181,7 @@
181181 * Test a wide row of size 1,000,000
182182 * @throws Throwable
183183 */
184- @Test(groups = "long")
184+ @Test(groups = "stress")
185185 @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle reading wide rows well.")
186186 public void wideRows() throws Throwable {
187187 Cluster.Builder builder = Cluster.builder();
@@ -205,7 +205,7 @@
205205 * Test a batch that writes a row of size 10,000
206206 * @throws Throwable
207207 */
208- @Test(groups = "short")
208+ @Test(groups = "stress")
209209 @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle large batches well.")
210210 public void wideBatchRows() throws Throwable {
211211 Cluster.Builder builder = Cluster.builder();
@@ -229,7 +229,7 @@
229229 * Test a wide row of size 1,000,000 consisting of a ByteBuffer
230230 * @throws Throwable
231231 */
232- @Test(groups = "long")
232+ @Test(groups = "stress")
233233 public void wideByteRows() throws Throwable {
234234 Cluster.Builder builder = Cluster.builder();
235235 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -252,7 +252,7 @@
252252 * Test a row with a single extra large text value
253253 * @throws Throwable
254254 */
255- @Test(groups = "short")
255+ @Test(groups = "stress")
256256 public void largeText() throws Throwable {
257257 Cluster.Builder builder = Cluster.builder();
258258 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -275,7 +275,7 @@
275275 * Creates a table with 330 columns
276276 * @throws Throwable
277277 */
278- @Test(groups = "short")
278+ @Test(groups = "stress")
279279 public void wideTable() throws Throwable {
280280 Cluster.Builder builder = Cluster.builder();
281281 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +20 −11
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetSocketAddress;
1819 import java.util.List;
1920 import java.util.Map;
2021 import java.util.Set;
@@ -93,14 +94,14 @@
9394 private static final Token TOKEN18 = token("8000000000000000000");
9495 private static final Token TOKEN19 = token("9000000000000000000");
9596
96- private static final String IP1 = "127.0.0.101";
97- private static final String IP2 = "127.0.0.102";
98- private static final String IP3 = "127.0.0.103";
99- private static final String IP4 = "127.0.0.104";
100- private static final String IP5 = "127.0.0.105";
101- private static final String IP6 = "127.0.0.106";
102- private static final String IP7 = "127.0.0.107";
103- private static final String IP8 = "127.0.0.108";
97+ private static final InetSocketAddress IP1 = socketAddress("127.0.0.101");
98+ private static final InetSocketAddress IP2 = socketAddress("127.0.0.102");
99+ private static final InetSocketAddress IP3 = socketAddress("127.0.0.103");
100+ private static final InetSocketAddress IP4 = socketAddress("127.0.0.104");
101+ private static final InetSocketAddress IP5 = socketAddress("127.0.0.105");
102+ private static final InetSocketAddress IP6 = socketAddress("127.0.0.106");
103+ private static final InetSocketAddress IP7 = socketAddress("127.0.0.107");
104+ private static final InetSocketAddress IP8 = socketAddress("127.0.0.108");
104105
105106 private static final ReplicationStrategy exampleStrategy = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2));
106107
@@ -110,10 +111,11 @@
110111 private static final Map<Token, Host> largeRingTokenToPrimary = Maps.newHashMap();
111112 static {
112113 for (int i = 0; i < 100; i++) {
114+ InetSocketAddress address = socketAddress("127.0.0." + i);
113115 for (int vnodes = 0; vnodes < 256; vnodes++) {
114116 Token token = token("" + ((i * 256) + vnodes));
115117 largeRing.add(token);
116- largeRingTokenToPrimary.put(token, host("127.0.0." + i, DC1, RACK11));
118+ largeRingTokenToPrimary.put(token, host(address, DC1, RACK11));
117119 }
118120 }
119121 }
@@ -591,13 +593,20 @@
591593 .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing);
592594 assertThat(System.currentTimeMillis() - t1).isLessThan(10000);
593595
596+ InetSocketAddress currNode = null;
597+ InetSocketAddress nextNode;
594598 for (int node = 0; node < 99; node++) { // 100th wraps so doesn't match this, check after
599+ if(currNode == null) {
600+ currNode = socketAddress("127.0.0." + node);
601+ }
602+ nextNode = socketAddress("127.0.0." + (node+1));
595603 for (int vnodes = 0; vnodes < 256; vnodes++) {
596604 Token token = token("" + ((node * 256) + vnodes));
597- assertReplicaPlacement(replicaMap, token, "127.0.0." + node, "127.0.0." + (node + 1));
605+ assertReplicaPlacement(replicaMap, token, currNode, nextNode);
598606 }
607+ currNode = nextNode;
599608 }
600- assertReplicaPlacement(replicaMap, token(""+ 99 * 256), "127.0.0.99", "127.0.0.0");
609+ assertReplicaPlacement(replicaMap, token(""+ 99 * 256), currNode, socketAddress("127.0.0.0"));
601610 }
602611
603612
modified driver-core/src/test/java/com/datastax/driver/core/QueryLoggerErrorsTest.java +60 −98
@@ -16,23 +16,21 @@
1616 package com.datastax.driver.core;
1717
1818 import org.apache.log4j.Logger;
19+import org.scassandra.http.client.PrimingRequest;
1920 import org.testng.annotations.AfterMethod;
2021 import org.testng.annotations.BeforeMethod;
22+import org.testng.annotations.DataProvider;
2123 import org.testng.annotations.Test;
2224
2325 import static org.apache.log4j.Level.DEBUG;
2426 import static org.apache.log4j.Level.INFO;
2527 import static org.assertj.core.api.Assertions.assertThat;
2628 import static org.assertj.core.api.Assertions.fail;
27-import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
28-import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
29-import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
29+import static org.scassandra.http.client.PrimingRequest.Result.*;
3030 import static org.scassandra.http.client.PrimingRequest.queryBuilder;
31+import static org.scassandra.http.client.PrimingRequest.then;
3132
32-import com.datastax.driver.core.exceptions.NoHostAvailableException;
33-import com.datastax.driver.core.exceptions.ReadTimeoutException;
34-import com.datastax.driver.core.exceptions.UnavailableException;
35-import com.datastax.driver.core.exceptions.WriteTimeoutException;
33+import com.datastax.driver.core.exceptions.*;
3634
3735 import static com.datastax.driver.core.QueryLogger.builder;
3836
@@ -49,38 +47,34 @@
4947 private MemoryAppender slowAppender;
5048 private MemoryAppender errorAppender;
5149
52- private QueryLogger queryLogger;
50+ private Cluster cluster = null;
51+ private Session session = null;
52+ private QueryLogger queryLogger = null;
5353
5454 @BeforeMethod(groups = { "short", "unit" })
55- public void startCapturingLogs() {
55+ public void setUp() {
56+ slow.setLevel(INFO);
57+ error.setLevel(INFO);
5658 slow.addAppender(slowAppender = new MemoryAppender());
5759 error.addAppender(errorAppender = new MemoryAppender());
60+
61+ queryLogger = null;
62+
63+ cluster = createClusterBuilder().build();
64+ session = cluster.connect();
5865 }
5966
6067 @AfterMethod(groups = { "short", "unit" })
61- public void stopCapturingLogs() {
68+ public void tearDown() {
6269 slow.setLevel(null);
6370 error.setLevel(null);
6471 slow.removeAppender(slowAppender);
6572 error.removeAppender(errorAppender);
66- }
67-
68- @BeforeMethod(groups = { "short", "unit" })
69- @AfterMethod(groups = { "short", "unit" })
70- public void resetLogLevels() {
71- slow.setLevel(INFO);
72- error.setLevel(INFO);
73- }
7473
75- @BeforeMethod(groups = { "short", "unit" })
76- public void resetQueryLogger() {
7774 queryLogger = null;
78- }
7975
80- @AfterMethod(groups = { "short", "unit" })
81- public void unregisterQueryLogger() {
82- if(cluster != null && queryLogger != null) {
83- cluster.unregister(queryLogger);
76+ if(cluster != null) {
77+ cluster.close();
8478 }
8579 }
8680
@@ -96,7 +90,7 @@
9690 primingClient.prime(
9791 queryBuilder()
9892 .withQuery(query)
99- .withFixedDelay(100)
93+ .withThen(then().withFixedDelay(100L))
10094 .build()
10195 );
10296 // when
@@ -105,7 +99,7 @@
10599 String line = slowAppender.waitAndGet(5000);
106100 assertThat(line)
107101 .contains("Query too slow")
108- .contains("127.0.0.1")
102+ .contains(ip)
109103 .contains(query);
110104 }
111105
@@ -120,7 +114,7 @@
120114 primingClient.prime(
121115 queryBuilder()
122116 .withQuery(query)
123- .withFixedDelay(100)
117+ .withThen(then().withFixedDelay(100L))
124118 .build()
125119 );
126120 // when
@@ -134,74 +128,34 @@
134128 String line = errorAppender.waitAndGet(5000);
135129 assertThat(line)
136130 .contains("Query error")
137- .contains("127.0.0.1")
131+ .contains(ip)
138132 .contains(Integer.toString(scassandra.getBinaryPort()))
139133 .contains(query)
140134 .contains(OperationTimedOutException.class.getName());
141135 }
142136
143- @Test(groups = "short")
144- public void should_log_read_timeout_errors() throws Exception {
145- // given
146- error.setLevel(DEBUG);
147- queryLogger = builder(cluster).build();
148- cluster.register(queryLogger);
149- String query = "SELECT foo FROM bar";
150- primingClient.prime(
151- queryBuilder()
152- .withQuery(query)
153- .withResult(read_request_timeout)
154- .build()
155- );
156- // when
157- try {
158- session.execute(query);
159- fail("Should have thrown ReadTimeoutException");
160- } catch (ReadTimeoutException e) {
161- // ok
162- }
163- // then
164- String line = errorAppender.waitAndGet(5000);
165- assertThat(line)
166- .contains("Query error")
167- .contains("127.0.0.1")
168- .contains(Integer.toString(scassandra.getBinaryPort()))
169- .contains(query)
170- .contains(ReadTimeoutException.class.getName());
171- }
172-
173- @Test(groups = "short")
174- public void should_log_write_timeout_errors() throws Exception {
175- // given
176- error.setLevel(DEBUG);
177- queryLogger = builder(cluster).build();
178- cluster.register(queryLogger);
179- String query = "UPDATE test SET foo = 'bar' where qix = ?";
180- primingClient.prime(
181- queryBuilder()
182- .withQuery(query)
183- .withResult(write_request_timeout)
184- .build()
185- );
186- // when
187- try {
188- session.execute(query);
189- fail("Should have thrown WriteTimeoutException");
190- } catch (WriteTimeoutException e) {
191- // ok
192- }
193- // then
194- String line = errorAppender.waitAndGet(5000);
195- assertThat(line)
196- .contains("Query error")
197- .contains("127.0.0.1")
198- .contains(Integer.toString(scassandra.getBinaryPort()))
199- .contains(query)
200- .contains(WriteTimeoutException.class.getName());
137+ @DataProvider(name="errors")
138+ public static Object[][] createErrors() {
139+ return new Object[][] {
140+ { unavailable, NoHostAvailableException.class, UnavailableException.class },
141+ { write_request_timeout, WriteTimeoutException.class, WriteTimeoutException.class },
142+ { read_request_timeout, ReadTimeoutException.class, ReadTimeoutException.class },
143+ { server_error, NoHostAvailableException.class, ServerError.class },
144+ { protocol_error, ProtocolError.class, ProtocolError.class },
145+ { bad_credentials, AuthenticationException.class, AuthenticationException.class },
146+ { overloaded, NoHostAvailableException.class, OverloadedException.class },
147+ { is_bootstrapping, NoHostAvailableException.class, BootstrappingException.class },
148+ { truncate_error, TruncateException.class, TruncateException.class },
149+ { syntax_error, SyntaxError.class, SyntaxError.class },
150+ { invalid, InvalidQueryException.class, InvalidQueryException.class },
151+ { config_error, InvalidConfigurationInQueryException.class, InvalidConfigurationInQueryException.class },
152+ { already_exists, AlreadyExistsException.class, AlreadyExistsException.class },
153+ { unprepared, DriverInternalError.class, UnpreparedException.class }
154+ };
201155 }
202156
203- @Test(groups = "short")
204- public void should_log_unavailable_errors() throws Exception {
157+ @Test(groups = "short", dataProvider="errors")
158+ public void should_log_exception_from_the_given_result(PrimingRequest.Result result, Class<? extends Exception> expectedException, Class<? extends Exception> loggedException) throws Exception {
205159 // given
206160 error.setLevel(DEBUG);
207161 queryLogger = builder(cluster).build();
@@ -210,28 +164,36 @@
210164 primingClient.prime(
211165 queryBuilder()
212166 .withQuery(query)
213- .withResult(unavailable)
167+ .withThen(then().withResult(result))
214168 .build()
215169 );
216170 // when
217- // when
218171 try {
219172 session.execute(query);
220173 fail("Should have thrown NoHostAvailableException");
221- } catch(NoHostAvailableException e) {
222- // ok
223- Throwable error = e.getErrors().get(hostAddress);
224- assertThat(error).isNotNull();
225- assertThat(error).isInstanceOf(UnavailableException.class);
174+ } catch(Exception e) {
175+ if(e instanceof NoHostAvailableException) {
176+ assertThat(expectedException).isEqualTo(NoHostAvailableException.class);
177+ // ok
178+ Throwable error = ((NoHostAvailableException)e).getErrors().get(hostAddress);
179+ assertThat(error).isNotNull();
180+ if(loggedException.getSuperclass() == DriverInternalError.class) {
181+ assertThat(error).isOfAnyClassIn(DriverException.class);
182+ } else {
183+ assertThat(error).isOfAnyClassIn(loggedException);
184+ }
185+ } else {
186+ assertThat(e).isInstanceOf(expectedException);
187+ }
226188 }
227189 // then
228190 String line = errorAppender.waitAndGet(5000);
229191 assertThat(line)
230192 .contains("Query error")
231- .contains("127.0.0.1")
193+ .contains(ip)
232194 .contains(Integer.toString(scassandra.getBinaryPort()))
233195 .contains(query)
234- .contains(UnavailableException.class.getName());
196+ .contains(loggedException.getName());
235197 }
236198
237199 }
No newline at the end of the file
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 +24 −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,18 @@
4954
5055 protected ActivityClient activityClient;
5156
57+ protected CurrentClient currentClient;
58+
59+ protected static String ip = CCMBridge.IP_PREFIX + "1";
60+
5261 @BeforeClass(groups = { "short", "long" })
5362 public void startScassandra() {
54- scassandra = TestUtils.createScassandraServer();
63+ scassandra = ScassandraFactory.createServer(ip, BINARY_PORT, ip, ADMIN_PORT);
5564 scassandra.start();
5665 primingClient = scassandra.primingClient();
5766 activityClient = scassandra.activityClient();
58- hostAddress = new InetSocketAddress("127.0.0.1", scassandra.getBinaryPort());
67+ currentClient = scassandra.currentClient();
68+ hostAddress = new InetSocketAddress(ip, scassandra.getBinaryPort());
5969 }
6070
6171 @AfterClass(groups = { "short", "long" })
@@ -69,11 +79,12 @@
6979 public void resetClients() {
7080 activityClient.clearAllRecordedActivity();
7181 primingClient.clearAllPrimes();
82+ currentClient.enableListener();
7283 }
7384
7485 protected Cluster.Builder createClusterBuilder() {
7586 Cluster.Builder builder = Cluster.builder()
76- .addContactPoint("127.0.0.1")
87+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
7788 .withPoolingOptions(new PoolingOptions()
7889 .setCoreConnectionsPerHost(HostDistance.LOCAL, 1)
7990 .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)
@@ -82,6 +93,16 @@
8293 return builder;
8394 }
8495
96+ /**
97+ * An overrideable method for building on to the Cluster.Builder used for this
98+ * class.
99+ * @param builder
100+ * @return
101+ */
102+ protected Cluster.Builder configure(Cluster.Builder builder) {
103+ return builder;
104+ }
105+
85106 protected Host retrieveSingleHost(Cluster cluster) {
86107 Host host = cluster.getMetadata().getHost(hostAddress);
87108 if(host == null) {
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +22 −1
@@ -17,6 +17,8 @@
1717
1818 import java.util.*;
1919
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
2022 import org.testng.annotations.Test;
2123 import static org.testng.Assert.assertEquals;
2224
@@ -24,6 +26,7 @@
2426 * Test we correctly process and print schema.
2527 */
2628 public class SchemaTest extends CCMBridge.PerClassSingleNodeCluster {
29+ static final Logger logger = LoggerFactory.getLogger(SchemaTest.class);
2730
2831 private static final Map<String, String> cql3 = new HashMap<String, String>();
2932 private static final Map<String, String> compact = new HashMap<String, String>();
@@ -96,6 +99,24 @@
9699 compact.put("compact_dynamic", compactDynamic);
97100 compact.put("compact_composite", compactComposite);
98101
102+ Properties properties = System.getProperties();
103+ String vmVersion = properties.getProperty("java.vm.specification.version");
104+ double javaVersion = 1.6;
105+ if(vmVersion != null) {
106+ try {
107+ javaVersion = Double.parseDouble(vmVersion);
108+ } catch (NumberFormatException e) {
109+ logger.warn("Could not parse java version from {}. Assuming {}.", vmVersion, javaVersion);
110+ }
111+ }
112+
113+ // Ordering of compaction options will be dependent on JDK. See schemaOptionsTest comments for explanation of why this is needed.
114+ String compactionOptions;
115+ if(javaVersion >= 1.8)
116+ compactionOptions = " AND compaction = { 'sstable_size_in_mb' : 15, 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy' }\n";
117+ else
118+ compactionOptions = " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n";
119+
99120 withOptions = String.format("CREATE TABLE %s.with_options (\n"
100121 + " k text,\n"
101122 + " v1 int,\n"
@@ -110,7 +131,7 @@
110131 + " AND bloom_filter_fp_chance = 0.01\n"
111132 + " AND caching = 'ALL'\n"
112133 + " AND comment = 'My awesome table'\n"
113- + " AND compaction = { 'class' : 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'sstable_size_in_mb' : 15 }\n"
134+ + compactionOptions
114135 + " AND compression = { 'sstable_compression' : 'org.apache.cassandra.io.compress.SnappyCompressor', 'chunk_length_kb' : 128 };", keyspace);
115136
116137 List<String> allDefs = new ArrayList<String>();
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStrategyTest.java +7 −6
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetSocketAddress;
1819 import java.util.List;
1920 import java.util.Map;
2021 import java.util.Set;
@@ -60,12 +61,12 @@
6061 private static final Token TOKEN18 = token("8000000000000000000");
6162 private static final Token TOKEN19 = token("9000000000000000000");
6263
63- private static final String IP1 = "127.0.0.101";
64- private static final String IP2 = "127.0.0.102";
65- private static final String IP3 = "127.0.0.103";
66- private static final String IP4 = "127.0.0.104";
67- private static final String IP5 = "127.0.0.105";
68- private static final String IP6 = "127.0.0.106";
64+ private static final InetSocketAddress IP1 = socketAddress("127.0.0.101");
65+ private static final InetSocketAddress IP2 = socketAddress("127.0.0.102");
66+ private static final InetSocketAddress IP3 = socketAddress("127.0.0.103");
67+ private static final InetSocketAddress IP4 = socketAddress("127.0.0.104");
68+ private static final InetSocketAddress IP5 = socketAddress("127.0.0.105");
69+ private static final InetSocketAddress IP6 = socketAddress("127.0.0.106");
6970
7071 private static final ReplicationStrategy exampleStrategy = simpleStrategy(3);
7172
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 driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +3 −3
@@ -69,7 +69,7 @@
6969
7070 static List<InetSocketAddress> nodes;
7171
72- @BeforeClass(groups = "long")
72+ @BeforeClass(groups = "stress")
7373 public void beforeClass() throws Exception {
7474 ccmBridge = CCMBridge.builder("test").withNodes(3).build();
7575 channelMonitor = new SocketChannelMonitor();
@@ -89,7 +89,7 @@
8989 .build();
9090 }
9191
92- @AfterClass(groups = "long")
92+ @AfterClass(groups = "stress")
9393 public void afterClass() {
9494 if(ccmBridge != null) {
9595 ccmBridge.stop();
@@ -125,7 +125,7 @@
125125 * @jira_ticket JAVA-692
126126 * @since 2.0.10, 2.1.6
127127 */
128- @Test(groups = "long")
128+ @Test(groups = "stress")
129129 public void host_state_should_be_maintained_with_timeouts() throws Exception {
130130 // Setup schema and insert records.
131131 Session session = cluster.connect();
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