Elffuss BraidHub

kikocis/java-driver public

Backport Stress tests from 2.1 and enhance Socket cleanup validation.

Improved tests that validate leakiness of Sessions and Clusters to also
ensure that all created SocketChannels get closed appropriately.

Created SocketChannelMonitor which utilizes NettyOptions to observe
created SocketChannels and track them.
Changeset894f0a0ca7a5b7d9eb97e1c01187075e338304379daadc7bf1d536ba5183b837
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2015-04-10 00:17 -05:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-17 20:19 +02:00
Parents4292b382c806

Browse the files at this changeset

6 files changed

added driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +228 −0
@@ -0,0 +1,228 @@
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.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+import org.testng.annotations.Test;
23+
24+import java.net.InetSocketAddress;
25+import java.util.ArrayList;
26+import java.util.Collection;
27+import java.util.Collections;
28+import java.util.List;
29+import java.util.concurrent.*;
30+
31+import static org.testng.Assert.assertEquals;
32+
33+public class ClusterStressTest extends CCMBridge.PerClassSingleNodeCluster {
34+ private static final Logger logger = LoggerFactory.getLogger(ClusterStressTest.class);
35+
36+ private ExecutorService executorService;
37+
38+ public ClusterStressTest() {
39+ // 8 threads should be enough so that we stress the driver and not the OS thread scheduler
40+ executorService = Executors.newFixedThreadPool(8);
41+ }
42+
43+ @Override
44+ protected Collection<String> getTableDefinitions() {
45+ return new ArrayList<String>(0);
46+ }
47+
48+ @Test(groups = "long")
49+ public void clusters_should_not_leak_connections() {
50+ int numberOfClusters = 10;
51+ int numberOfIterations = 500;
52+ for (int i = 1; i < numberOfIterations; i++) {
53+ logger.info("On iteration {}/{}.", i, numberOfIterations);
54+ logger.info("Creating {} clusters", numberOfClusters);
55+ List<CreateClusterAndCheckConnections> actions =
56+ waitForCreates(createClustersConcurrently(numberOfClusters));
57+ waitForCloses(closeClustersConcurrently(actions));
58+ logger.debug("# {} threads currently running", Thread.getAllStackTraces().keySet().size());
59+ }
60+ }
61+
62+ private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters) {
63+ final CountDownLatch countDownLatch = new CountDownLatch(1);
64+ return createClustersConcurrently(numberOfClusters, countDownLatch);
65+ }
66+
67+ private List<Future<CreateClusterAndCheckConnections>> createClustersConcurrently(int numberOfClusters,
68+ CountDownLatch countDownLatch) {
69+ List<Future<CreateClusterAndCheckConnections>> clusterFutures =
70+ Lists.newArrayListWithCapacity(numberOfClusters);
71+ for (int i = 0; i < numberOfClusters; i++) {
72+ clusterFutures.add(executorService.submit(new CreateClusterAndCheckConnections(countDownLatch)));
73+ }
74+ countDownLatch.countDown();
75+ return clusterFutures;
76+ }
77+
78+ private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions) {
79+ final CountDownLatch countDownLatch = new CountDownLatch(1);
80+ return closeClustersConcurrently(actions, countDownLatch);
81+ }
82+
83+ private List<Future<Void>> closeClustersConcurrently(List<CreateClusterAndCheckConnections> actions,
84+ CountDownLatch startSignal) {
85+ List<Future<Void>> closeFutures = Lists.newArrayListWithCapacity(actions.size());
86+ for (CreateClusterAndCheckConnections action : actions) {
87+ closeFutures.add(executorService.submit(new CloseCluster(action.cluster, action.channelMonitor,
88+ startSignal)));
89+ }
90+ startSignal.countDown();
91+ return closeFutures;
92+ }
93+
94+ private List<CreateClusterAndCheckConnections> waitForCreates(
95+ List<Future<CreateClusterAndCheckConnections>> futures) {
96+ List<CreateClusterAndCheckConnections> actions = Lists.newArrayListWithCapacity(futures.size());
97+ // If an error occurs, we will abort the test, but we still want to close all the clusters
98+ // that were opened successfully, so we iterate over the whole list no matter what.
99+ AssertionError error = null;
100+ for (Future<CreateClusterAndCheckConnections> future : futures) {
101+ try {
102+ actions.add(future.get());
103+ } catch (InterruptedException e) {
104+ Thread.currentThread().interrupt();
105+ if (error == null)
106+ error = assertionError("Interrupted while waiting for future creation", e);
107+ } catch (ExecutionException e) {
108+ if (error == null) {
109+ Throwable cause = e.getCause();
110+ if (cause instanceof AssertionError)
111+ error = (AssertionError)cause;
112+ else
113+ error = assertionError("Error while creating a cluster", cause);
114+ }
115+ }
116+ }
117+ if (error != null) {
118+ for (CreateClusterAndCheckConnections action : actions)
119+ action.cluster.close();
120+ throw error;
121+ } else
122+ return actions;
123+ }
124+
125+ private List<Void> waitForCloses(List<Future<Void>> futures) {
126+ List<Void> result = new ArrayList<Void>(futures.size());
127+ AssertionError error = null;
128+ for (Future<Void> future : futures) {
129+ try {
130+ result.add(future.get());
131+ } catch (InterruptedException e) {
132+ Thread.currentThread().interrupt();
133+ if (error == null)
134+ error = assertionError("Interrupted while waiting for future", e);
135+ } catch (ExecutionException e) {
136+ if (error == null) {
137+ Throwable cause = e.getCause();
138+ if (cause instanceof AssertionError)
139+ error = (AssertionError)cause;
140+ else
141+ error = assertionError("Error while closing a cluster", cause);
142+ }
143+ }
144+ }
145+ if (error != null)
146+ throw error;
147+ else
148+ return result;
149+ }
150+
151+ private static class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> {
152+ private final CountDownLatch startSignal;
153+ private final Cluster cluster;
154+ private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
155+ private final List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
156+
157+ CreateClusterAndCheckConnections(CountDownLatch startSignal) {
158+ this.startSignal = startSignal;
159+ this.cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
160+ .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
161+ .withNettyOptions(channelMonitor.nettyOptions()).build();
162+ }
163+
164+ @Override
165+ public CreateClusterAndCheckConnections call() throws Exception {
166+ startSignal.await();
167+
168+ try {
169+ // There should be 1 control connection after initializing.
170+ cluster.init();
171+ assertEquals(cluster.manager.sessions.size(), 0);
172+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
173+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
174+
175+ // The first session initializes the cluster and its control connection
176+ Session session = cluster.connect();
177+ assertEquals(cluster.manager.sessions.size(), 1);
178+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
179+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + TestUtils.numberOfLocalCoreConnections(cluster));
180+
181+ // Closing the session keeps the control connection opened
182+ session.close();
183+ assertEquals(cluster.manager.sessions.size(), 0);
184+ assertEquals((int)cluster.getMetrics().getOpenConnections().getValue(), 1);
185+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
186+
187+ return this;
188+ } catch (AssertionError e) {
189+ // If an assertion fails, close the cluster now, because it's the last time we
190+ // have a reference to it.
191+ cluster.close();
192+ throw e;
193+ } finally {
194+ channelMonitor.stop();
195+ }
196+ }
197+ }
198+
199+ private static class CloseCluster implements Callable<Void> {
200+ private final Cluster cluster;
201+ private final SocketChannelMonitor channelMonitor;
202+ private final CountDownLatch startSignal;
203+
204+ CloseCluster(Cluster cluster, SocketChannelMonitor channelMonitor, CountDownLatch startSignal) {
205+ this.cluster = cluster;
206+ this.channelMonitor = channelMonitor;
207+ this.startSignal = startSignal;
208+ }
209+
210+ @Override
211+ public Void call() throws Exception {
212+ startSignal.await();
213+
214+ cluster.close();
215+ assertEquals(cluster.manager.sessions.size(), 0);
216+ assertEquals(channelMonitor.openChannels(Collections.singletonList(hostAddress)).size(), 0);
217+ channelMonitor.stop();
218+
219+ return null;
220+ }
221+ }
222+
223+ private static AssertionError assertionError(String message, Throwable cause) {
224+ AssertionError error = new AssertionError(message);
225+ error.initCause(cause);
226+ return error;
227+ }
228+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +25 −1
@@ -15,9 +15,14 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
1820 import org.testng.annotations.Test;
1921
22+import java.net.InetSocketAddress;
2023 import java.util.Collections;
24+import java.util.List;
25+import java.util.concurrent.TimeUnit;
2126
2227 import static org.testng.Assert.assertEquals;
2328
@@ -31,9 +36,18 @@
3136 CCMBridge ccmBridge;
3237 ccmBridge = CCMBridge.create("test", 1);
3338 Cluster cluster = null;
39+ SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
40+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
41+
42+ List<InetSocketAddress> nodes = Lists.newArrayList(
43+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
44+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042));
3445 try {
3546 // create a new cluster object and ensure 0 sessions and connections
36- cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
47+ cluster = Cluster.builder()
48+ .addContactPointsWithPorts(Collections.singletonList(
49+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
50+ .withNettyOptions(channelMonitor.nettyOptions()).build();
3751 cluster.init();
3852
3953 int corePoolSize = cluster.getConfiguration()
@@ -43,21 +57,25 @@
4357 assertEquals(cluster.manager.sessions.size(), 0);
4458 // Should be 1 control connection after initialization.
4559 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
60+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
4661
4762 // ensure sessions.size() returns with 1 control connection + core pool size.
4863 Session session = cluster.connect();
4964 assertEquals(cluster.manager.sessions.size(), 1);
5065 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
66+ assertEquals(channelMonitor.openChannels(nodes).size(), 1 + corePoolSize);
5167
5268 // ensure sessions.size() returns to 0 with only 1 active connection (the control connection)
5369 session.close();
5470 assertEquals(cluster.manager.sessions.size(), 0);
5571 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
72+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
5673
5774 // ensure bootstrapping a node does not create additional connections
5875 ccmBridge.bootstrapNode(2);
5976 assertEquals(cluster.manager.sessions.size(), 0);
6077 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
78+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
6179
6280 // ensure a new session gets registered and core connections are established
6381 // there should be corePoolSize more connections to accommodate for the new host.
@@ -65,12 +83,14 @@
6583 assertEquals(cluster.manager.sessions.size(), 1);
6684
6785 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + (corePoolSize * 2));
86+ assertEquals(channelMonitor.openChannels(nodes).size(), 1 + (corePoolSize * 2));
6887
6988 // ensure bootstrapping a node does not create additional connections that won't get cleaned up
7089 thisSession.close();
7190
7291 assertEquals(cluster.manager.sessions.size(), 0);
7392 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
93+ assertEquals(channelMonitor.openChannels(nodes).size(), 1);
7494 } finally {
7595 if(cluster != null){
7696 cluster.close();
@@ -78,6 +98,10 @@
7898 if (ccmBridge != null) {
7999 ccmBridge.remove();
80100 }
101+ // Ensure no channels remain open.
102+ channelMonitor.stop();
103+ channelMonitor.report();
104+ assertEquals(channelMonitor.openChannels(nodes).size(), 0);
81105 }
82106 }
83107 }
added driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +262 −0
@@ -0,0 +1,262 @@
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.utils.SocketChannelMonitor;
19+import com.google.common.collect.Lists;
20+import com.google.common.util.concurrent.*;
21+import org.slf4j.Logger;
22+import org.slf4j.LoggerFactory;
23+import org.testng.annotations.Test;
24+
25+import java.net.InetSocketAddress;
26+import java.util.*;
27+import java.util.concurrent.*;
28+
29+import static org.testng.Assert.assertEquals;
30+import static org.testng.Assert.fail;
31+
32+public class SessionStressTest extends CCMBridge.PerClassSingleNodeCluster {
33+
34+ private static final Logger logger = LoggerFactory.getLogger(SessionStressTest.class);
35+
36+ private ListeningExecutorService executorService;
37+
38+ public SessionStressTest() {
39+ // 8 threads should be enough so that we stress the driver and not the OS thread scheduler
40+ executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(8));
41+ }
42+
43+ @Override
44+ protected Collection<String> getTableDefinitions() {
45+ return new ArrayList<String>(0);
46+ }
47+
48+
49+ /**
50+ * Stress test on opening/closing sessions.
51+ * <p/>
52+ * This test opens and closes {@code Session} in a multithreaded environment and makes sure that there is not
53+ * connection leak. More specifically, this test performs the following steps:
54+ * <p/>
55+ * <ul>
56+ * <li>Open 2000 {@code Session} concurrently</li>
57+ * <li>Verify that 2000 sessions are reported as open by the {@code Cluster}</li>
58+ * <li>Verify that 4001 connections are reported as open by the {@code Cluster}</li>
59+ * <li>Close 1000 {@code Session} concurrently</li>
60+ * <li>Verify that 1000 sessions are reported as open by the {@code Cluster}</li>
61+ * <li>Verify that 2001 connections are reported as open by the {@code Cluster}</li>
62+ * <li>Open concurrently 1000 {@code Session} while 1000 other {@code Session} are closed concurrently</li>
63+ * <li>Verify that 1000 sessions are reported as open by the {@code Cluster}</li>
64+ * <li>Verify that 2001 connections are reported as open by the {@code Cluster}</li>
65+ * <li>Close 1000 {@code Session} concurrently</li>
66+ * <li>Verify that 0 sessions are reported as open by the {@code Cluster}</li>
67+ * <li>Verify that 1 connection is reported as open by the {@code Cluster}</li>
68+ * </ul>
69+ * <p/>
70+ * This test is linked to JAVA-432.
71+ */
72+ @Test(groups = "long")
73+ public void sessions_should_not_leak_connections() {
74+ // override inherited field with a new cluster object and ensure 0 sessions and connections
75+ SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
76+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
77+ List<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
78+ cluster = Cluster.builder().addContactPointsWithPorts(contactPoints)
79+ .withPoolingOptions(new PoolingOptions().setCoreConnectionsPerHost(HostDistance.LOCAL, 1))
80+ .withNettyOptions(channelMonitor.nettyOptions()).build();
81+ cluster.init();
82+
83+ // The cluster has been initialized, we should have 1 connection.
84+ assertEquals(cluster.manager.sessions.size(), 0);
85+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
86+
87+ // The first session initializes the cluster and its control connection
88+ // This is a local cluster so we also have 2 connections per session
89+ Session session = cluster.connect();
90+ assertEquals(cluster.manager.sessions.size(), 1);
91+ int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster);
92+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + coreConnections);
93+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + coreConnections);
94+
95+ // Closing the session keeps the control connection opened
96+ session.close();
97+ assertEquals(cluster.manager.sessions.size(), 0);
98+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
99+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
100+
101+ try {
102+ int nbOfSessions = 2000;
103+ int halfOfTheSessions = nbOfSessions / 2;
104+ int nbOfIterations = 5;
105+ int sleepTime = 20;
106+
107+ for (int iteration = 1; iteration <= nbOfIterations; iteration++) {
108+ logger.info("On iteration {}/{}.", iteration, nbOfIterations);
109+ logger.info("Creating {} sessions.", nbOfSessions);
110+ waitFor(openSessionsConcurrently(nbOfSessions));
111+
112+ // We should see the exact number of opened sessions
113+ // Since we have 2 connections per session, we should see 2 * sessions + control connection
114+ assertEquals(cluster.manager.sessions.size(), nbOfSessions);
115+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
116+ coreConnections * nbOfSessions + 1);
117+ assertEquals(channelMonitor.openChannels(contactPoints).size(), coreConnections * nbOfSessions + 1);
118+
119+ // Close half of the sessions asynchronously
120+ logger.info("Closing {}/{} sessions.", halfOfTheSessions, nbOfSessions);
121+ waitFor(closeSessionsConcurrently(halfOfTheSessions));
122+
123+ // Check that we have the right number of sessions and connections
124+ assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
125+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
126+ coreConnections * (nbOfSessions / 2) + 1);
127+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
128+ coreConnections * (nbOfSessions / 2) + 1);
129+
130+ // Close and open the same number of sessions concurrently
131+ logger.info("Closing and Opening {} sessions concurrently.", halfOfTheSessions);
132+ CountDownLatch startSignal = new CountDownLatch(2);
133+ List<ListenableFuture<Session>> openSessionFutures =
134+ openSessionsConcurrently(halfOfTheSessions, startSignal);
135+ List<ListenableFuture<Void>> closeSessionsFutures = closeSessionsConcurrently(halfOfTheSessions,
136+ startSignal);
137+ startSignal.countDown();
138+ waitFor(openSessionFutures);
139+ waitFor(closeSessionsFutures);
140+
141+ // Check that we have the same number of sessions and connections
142+ assertEquals(cluster.manager.sessions.size(), halfOfTheSessions);
143+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
144+ coreConnections * (nbOfSessions / 2) + 1);
145+ assertEquals(channelMonitor.openChannels(contactPoints).size(),
146+ coreConnections * (nbOfSessions / 2) + 1);
147+
148+ // Close the remaining sessions
149+ logger.info("Closing remaining {} sessions.", halfOfTheSessions);
150+ waitFor(closeSessionsConcurrently(halfOfTheSessions));
151+
152+ // Check that we have a clean state
153+ assertEquals(cluster.manager.sessions.size(), 0);
154+ assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
155+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
156+
157+ // On OSX, the TCP connections are released after 15s by default (sysctl -a net.inet.tcp.msl)
158+ logger.info("Sleeping {} seconds so that TCP connections are released by the OS", sleepTime);
159+ Uninterruptibles.sleepUninterruptibly(sleepTime, TimeUnit.SECONDS);
160+ }
161+ } finally {
162+ cluster.close();
163+
164+ // Ensure no channels remain open.
165+ channelMonitor.stop();
166+ channelMonitor.report();
167+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
168+ }
169+ }
170+
171+ private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations) {
172+ final CountDownLatch countDownLatch = new CountDownLatch(1);
173+ return openSessionsConcurrently(iterations, countDownLatch);
174+ }
175+
176+ private List<ListenableFuture<Session>> openSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
177+ // Open new sessions once all tasks have been created
178+ List<ListenableFuture<Session>> sessionFutures = Lists.newArrayListWithCapacity(iterations);
179+ for (int i = 0; i < iterations; i++) {
180+ sessionFutures.add(executorService.submit(new OpenSession(cluster, countDownLatch)));
181+ }
182+ countDownLatch.countDown();
183+ return sessionFutures;
184+ }
185+
186+ private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations) {
187+ final CountDownLatch countDownLatch = new CountDownLatch(1);
188+ return closeSessionsConcurrently(iterations, countDownLatch);
189+ }
190+
191+ private List<ListenableFuture<Void>> closeSessionsConcurrently(int iterations, CountDownLatch countDownLatch) {
192+ // Get a reference to every session we want to close
193+ Stack<Session> sessionsToClose = new Stack<Session>();
194+ Iterator<? extends Session> iterator = cluster.manager.sessions.iterator();
195+ for (int i = 0; i < iterations; i++) {
196+ sessionsToClose.push(iterator.next());
197+ }
198+
199+ // Close sessions asynchronously once all tasks have been created
200+ List<ListenableFuture<CloseFuture>> closeFutures = Lists.newArrayListWithCapacity(iterations);
201+ for (int i = 0; i < iterations; i++) {
202+ closeFutures.add(executorService.submit(new CloseSession(sessionsToClose.pop(), countDownLatch)));
203+ }
204+ countDownLatch.countDown();
205+
206+ // Immediately wait for CloseFutures, this should be very quick since all this work does is call closeAsync.
207+ List<ListenableFuture<Void>> futures = Lists.newArrayListWithCapacity(iterations);
208+ for(ListenableFuture<CloseFuture> closeFuture : closeFutures) {
209+ try {
210+ futures.add(closeFuture.get());
211+ } catch(Exception e) {
212+ logger.error("Got interrupted exception while waiting on closeFuture.", e);
213+ }
214+ }
215+ return futures;
216+ }
217+
218+ private <E> void waitFor(List<ListenableFuture<E>> futures) {
219+ for (Future<E> future : futures) {
220+ try {
221+ future.get();
222+ } catch (InterruptedException e) {
223+ throw new RuntimeException("Interrupted while waiting for future", e);
224+ } catch (ExecutionException e) {
225+ e.printStackTrace();
226+ fail(e.getMessage());
227+ }
228+ }
229+ }
230+
231+ private static class OpenSession implements Callable<Session> {
232+ private final Cluster cluster;
233+ private final CountDownLatch startSignal;
234+
235+ OpenSession(Cluster cluster, CountDownLatch startSignal) {
236+ this.cluster = cluster;
237+ this.startSignal = startSignal;
238+ }
239+
240+ @Override
241+ public Session call() throws Exception {
242+ startSignal.await();
243+ return cluster.connect();
244+ }
245+ }
246+
247+ private static class CloseSession implements Callable<CloseFuture> {
248+ private final Session session;
249+ private final CountDownLatch startSignal;
250+
251+ CloseSession(Session session, CountDownLatch startSignal) {
252+ this.session = session;
253+ this.startSignal = startSignal;
254+ }
255+
256+ @Override
257+ public CloseFuture call() throws Exception {
258+ startSignal.await();
259+ return session.closeAsync();
260+ }
261+ }
262+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +22 −1
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetSocketAddress;
1819 import java.util.*;
1920 import java.util.concurrent.CountDownLatch;
2021 import java.util.concurrent.ExecutorService;
@@ -22,6 +23,10 @@
2223 import java.util.concurrent.TimeUnit;
2324
2425 import com.datastax.driver.core.utils.CassandraVersion;
26+import com.datastax.driver.core.utils.SocketChannelMonitor;
27+import io.netty.channel.socket.SocketChannel;
28+import org.slf4j.Logger;
29+import org.slf4j.LoggerFactory;
2530 import org.testng.annotations.Test;
2631
2732 import static org.testng.Assert.assertEquals;
@@ -35,6 +40,8 @@
3540 */
3641 public class SessionTest extends CCMBridge.PerClassSingleNodeCluster {
3742
43+ private static final Logger logger = LoggerFactory.getLogger(SessionTest.class);
44+
3845 private static final String TABLE1 = "test1";
3946 private static final String TABLE2 = "test2";
4047 private static final String TABLE3 = "test3";
@@ -173,11 +180,15 @@
173180
174181 // create a new cluster object and ensure 0 sessions and connections
175182 int corePoolSize = 2;
183+ SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
184+ channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
176185 PoolingOptions poolingOptions = new PoolingOptions()
177186 .setCoreConnectionsPerHost(HostDistance.LOCAL, corePoolSize);
187+ Collection<InetSocketAddress> contactPoints = Collections.singletonList(hostAddress);
178188 Cluster cluster = Cluster.builder()
179- .addContactPointsWithPorts(Collections.singletonList(hostAddress))
189+ .addContactPointsWithPorts(contactPoints)
180190 .withPoolingOptions(poolingOptions)
191+ .withNettyOptions(channelMonitor.nettyOptions())
181192 .build();
182193
183194 try {
@@ -185,15 +196,18 @@
185196
186197 assertEquals(cluster.manager.sessions.size(), 0);
187198 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
199+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
188200
189201 Session session = cluster.connect();
190202 assertEquals(cluster.manager.sessions.size(), 1);
191203 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
204+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + corePoolSize);
192205
193206 // ensure sessions.size() returns to 0 with only 1 active connection
194207 session.close();
195208 assertEquals(cluster.manager.sessions.size(), 0);
196209 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
210+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
197211
198212 // give the driver time to close sessions
199213 Thread.sleep(10);
@@ -202,11 +216,13 @@
202216 // ensure 0 sessions with a single control connection
203217 assertEquals(cluster.manager.sessions.size(), 0);
204218 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
219+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
205220
206221 // ensure a new session gets registered and control connections are established
207222 session = cluster.connect();
208223 assertEquals(cluster.manager.sessions.size(), 1);
209224 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1 + corePoolSize);
225+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1 + corePoolSize);
210226 session.close();
211227
212228 // give the driver time to close sessions
@@ -215,9 +231,14 @@
215231 // ensure sessions.size() always returns to 0 with only 1 active connection
216232 assertEquals(cluster.manager.sessions.size(), 0);
217233 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
234+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 1);
218235 }
219236 } finally {
220237 cluster.close();
238+ // Ensure no channels remain open.
239+ channelMonitor.stop();
240+ channelMonitor.report();
241+ assertEquals(channelMonitor.openChannels(contactPoints).size(), 0);
221242 }
222243 }
223244
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +4 −0
@@ -393,6 +393,10 @@
393393 return null; // never reached
394394 }
395395
396+ public static int numberOfLocalCoreConnections(Cluster cluster) {
397+ Configuration configuration = cluster.getConfiguration();
398+ return configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL);
399+ }
396400 /**
397401 * @return A Scassandra instance with an arbitrarily chosen binary port from 8042-8142 and admin port from
398402 * 8052-8152.
added driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +160 −0
@@ -0,0 +1,160 @@
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.utils;
17+
18+import com.datastax.driver.core.NettyOptions;
19+import com.google.common.base.Predicate;
20+import com.google.common.base.Predicates;
21+import com.google.common.collect.Iterables;
22+import com.google.common.collect.Lists;
23+import com.google.common.collect.MapMaker;
24+import com.google.common.util.concurrent.ThreadFactoryBuilder;
25+import io.netty.channel.socket.SocketChannel;
26+import org.slf4j.Logger;
27+import org.slf4j.LoggerFactory;
28+
29+import java.net.InetSocketAddress;
30+import java.net.Socket;
31+import java.net.SocketAddress;
32+import java.util.*;
33+import java.util.concurrent.Executors;
34+import java.util.concurrent.ScheduledExecutorService;
35+import java.util.concurrent.TimeUnit;
36+import java.util.concurrent.atomic.AtomicLong;
37+
38+/**
39+ * Utility that observes {@link SocketChannel}s. Helpful for ensuring that Sockets are actually closed
40+ * when they should be. Utilizes {@link NettyOptions} to monitor created {@link SocketChannel}s.
41+ */
42+public class SocketChannelMonitor implements Runnable {
43+
44+ private static final Logger logger = LoggerFactory.getLogger(SocketChannelMonitor.class);
45+
46+ private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1,
47+ new ThreadFactoryBuilder().setDaemon(true).setNameFormat("SocketMonitor-%d").build());
48+
49+ // use a weak set so channels may be garbage collected.
50+ private final Collection<SocketChannel> channels = Collections.newSetFromMap(
51+ new MapMaker().weakKeys().<SocketChannel, Boolean>makeMap());
52+
53+ private final AtomicLong channelsCreated = new AtomicLong(0);
54+
55+ private final NettyOptions nettyOptions = new NettyOptions() {
56+ public void afterChannelInitialized(SocketChannel channel) throws Exception {
57+ channels.add(channel);
58+ channelsCreated.incrementAndGet();
59+ }
60+ };
61+
62+ @Override
63+ public void run() {
64+ try {
65+ report();
66+ } catch(Exception e) {
67+ logger.error("Error countered.", e);
68+ }
69+ }
70+
71+ public void stop() {
72+ executor.shutdown();
73+ try {
74+ executor.awaitTermination(1, TimeUnit.SECONDS);
75+ } catch (InterruptedException e) {
76+ }
77+ }
78+
79+ /**
80+ * @return A custom {@link NettyOptions} instance that hooks into afterChannelInitialized added channels may be
81+ * monitored.
82+ */
83+ public NettyOptions nettyOptions() {
84+ return nettyOptions;
85+ }
86+
87+ public static Predicate<SocketChannel> openChannels = new Predicate<SocketChannel>() {
88+ @Override
89+ public boolean apply(SocketChannel input) {
90+ return input.isOpen();
91+ }
92+ };
93+
94+ /**
95+ * Schedules a {@link #report()} to be called every configured interval.
96+ * @param interval how often to report.
97+ * @param timeUnit at what time precision to report at.
98+ */
99+ public void reportAtFixedInterval(int interval, TimeUnit timeUnit) {
100+ executor.scheduleAtFixedRate(this, interval, interval, timeUnit);
101+ }
102+
103+ /**
104+ * Reports for all sockets.
105+ */
106+ public void report() {
107+ report(Predicates.<SocketChannel>alwaysTrue());
108+ }
109+
110+ /**
111+ * <p>
112+ * Report for all sockets matching the given predicate. The report format reflects the number of open, closed,
113+ * live and total sockets created. This is logged at DEBUG if enabled.
114+ *
115+ * <p>
116+ * If TRACE is enabled, each individual socket will be logged as well.
117+ *
118+ * @param channelFilter used to determine which sockets to report on.
119+ */
120+ public void report(Predicate<SocketChannel> channelFilter) {
121+ if(logger.isDebugEnabled()) {
122+ Iterable<SocketChannel> channels = matchingChannels(channelFilter);
123+ Iterable<SocketChannel> open = Iterables.filter(channels, openChannels);
124+ Iterable<SocketChannel> closed = Iterables.filter(channels, Predicates.not(openChannels));
125+
126+ logger.debug("Channel states: {} open, {} closed, live {}, total sockets created " +
127+ "(including those that don't match filter) {}.",
128+ Iterables.size(open),
129+ Iterables.size(closed),
130+ Iterables.size(channels),
131+ channelsCreated.get());
132+
133+ if(logger.isTraceEnabled()) {
134+ logger.trace("Open channels {}.", open);
135+ logger.trace("Closed channels {}.", closed);
136+ }
137+ }
138+ }
139+
140+ /**
141+ * @param addresses The addresses to include.
142+ * @return Open channels matching the given socket addresses.
143+ */
144+ public Collection<SocketChannel> openChannels(final Collection<InetSocketAddress> addresses) {
145+ return Lists.newArrayList(matchingChannels(new Predicate<SocketChannel>() {
146+ @Override
147+ public boolean apply(SocketChannel input) {
148+ return input.isOpen() && input.remoteAddress() != null && addresses.contains(input.remoteAddress());
149+ }
150+ }));
151+ }
152+
153+ /**
154+ * @param channelFilter {@link Predicate} to use to determine whether or not a socket shall be considered.
155+ * @return Channels matching the given {@link Predicate}.
156+ */
157+ public Iterable<SocketChannel> matchingChannels(final Predicate<SocketChannel> channelFilter) {
158+ return Iterables.filter(Lists.newArrayList(channels), Predicates.and(Predicates.notNull(), channelFilter));
159+ }
160+}