Elffuss BraidHub

kikocis/java-driver public

Make connection and pool creation fully async (JAVA-692).

This is a squashed commit, it contains significant contributions from
@tolbertam and @adutra.
Changeset0e7ff2256dc1d0fa02a5adf3dd8408b2ac787df827db83d13981eb4842e8f5d5
Authorolim7t <omichallat+github@gmail.com> · 2015-04-03 18:02 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-04-17 20:19 +02:00
Parentsa5bd5b316c2f

Browse the files at this changeset

11 files changed

modified driver-core/CHANGELOG.rst +1 −0
@@ -38,6 +38,7 @@
3838 (JAVA-619)
3939 - [new feature] Expose an API to check for schema agreement after a
4040 schema-altering statement (JAVA-669)
41+- [improvement] Make connection and pool creation fully async (JAVA-692)
4142
4243 Merged from 2.0.9_fixes branch:
4344
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +3 −3
@@ -21,7 +21,6 @@
2121 import java.util.concurrent.ExecutionException;
2222 import java.util.concurrent.LinkedBlockingDeque;
2323
24-import com.google.common.util.concurrent.Futures;
2524 import com.google.common.util.concurrent.ListenableFuture;
2625 import com.google.common.util.concurrent.SettableFuture;
2726 import com.google.common.util.concurrent.Uninterruptibles;
@@ -29,6 +28,7 @@
2928 import org.slf4j.LoggerFactory;
3029
3130 import com.datastax.driver.core.exceptions.DriverInternalError;
31+import com.datastax.driver.core.utils.MoreFutures;
3232
3333 /**
3434 * Default implementation of a result set, backed by an ArrayDeque of ArrayList.
@@ -178,7 +178,7 @@
178178 }
179179
180180 public ListenableFuture<Void> fetchMoreResults() {
181- return Futures.immediateFuture(null);
181+ return MoreFutures.VOID_SUCCESS;
182182 }
183183
184184 public ExecutionInfo getExecutionInfo() {
@@ -287,7 +287,7 @@
287287
288288 private ListenableFuture<Void> fetchMoreResults(FetchingState fetchState) {
289289 if (fetchState == null)
290- return Futures.immediateFuture(null);
290+ return MoreFutures.VOID_SUCCESS;
291291
292292 if (fetchState.inProgress != null)
293293 return fetchState.inProgress;
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +52 −66
@@ -1409,16 +1409,8 @@
14091409 });
14101410 }
14111411
1412- private void onUp(final Host host) throws InterruptedException, ExecutionException {
1413- // Note that in generalize we can parallelize the pool creation on
1414- // each session, but we shouldn't use executor since we're already
1415- // running on it most probably (and so we could deadlock). Use the
1416- // blockingExecutor instead, that's why it's for.
1417- onUp(host, blockingExecutor);
1418- }
1419-
14201412 // Use triggerOnUp unless you're sure you want to run this on the current thread.
1421- private void onUp(final Host host, ListeningExecutorService poolCreationExecutor) throws InterruptedException, ExecutionException {
1413+ private void onUp(final Host host) throws InterruptedException, ExecutionException {
14221414 logger.debug("Host {} is UP", host);
14231415
14241416 if (isClosed())
@@ -1472,42 +1464,39 @@
14721464
14731465 logger.trace("Adding/renewing host pools for newly UP host {}", host);
14741466
1475- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1467+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
14761468 for (SessionManager s : sessions)
1477- futures.add(s.forceRenewPool(host, poolCreationExecutor));
1478-
1479- // Only mark the node up once all session have re-added their pool (if the load-balancing
1480- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1481- // to the node.
1482- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1483- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1484- public void onSuccess(List<Boolean> poolCreationResults) {
1485- // If any of the creation failed, they will have signaled a connection failure
1486- // which will trigger a reconnection to the node. So don't bother marking UP.
1487- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1488- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1489- return;
1490- }
1469+ futures.add(s.forceRenewPool(host));
14911470
1492- host.setUp();
1493-
1494- for (Host.StateListener listener : listeners)
1495- listener.onUp(host);
1471+ try {
1472+ // Only mark the node up once all session have re-added their pool (if the load-balancing
1473+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1474+ // to the node.
1475+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
1476+
1477+ // If any of the creation failed, they will have signaled a connection failure
1478+ // which will trigger a reconnection to the node. So don't bother marking UP.
1479+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1480+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1481+ return;
14961482 }
14971483
1498- public void onFailure(Throwable t) {
1499- // That future is not really supposed to throw unexpected exceptions
1500- if (!(t instanceof InterruptedException))
1501- logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1502- }
1503- });
1484+ host.setUp();
15041485
1505- f.get();
1486+ for (Host.StateListener listener : listeners)
1487+ listener.onUp(host);
1488+
1489+ } catch (ExecutionException e) {
1490+ Throwable t = e.getCause();
1491+ // That future is not really supposed to throw unexpected exceptions
1492+ if (!(t instanceof InterruptedException))
1493+ logger.error("Unexpected error while marking node UP: while this shouldn't happen, this shouldn't be critical", t);
1494+ }
15061495
15071496 // Now, check if there isn't pools to create/remove following the addition.
15081497 // We do that now only so that it's not called before we've set the node up.
15091498 for (SessionManager s : sessions)
1510- s.updateCreatedPools(blockingExecutor);
1499+ s.updateCreatedPools();
15111500
15121501 } finally {
15131502 host.notificationsLock.unlock();
@@ -1567,7 +1556,7 @@
15671556 connectionFactory.open(host).closeAsync();
15681557 // Note that we want to do the pool creation on this thread because we want that
15691558 // when onUp return, the host is ready for querying
1570- onUp(host, MoreExecutors.sameThreadExecutor());
1559+ onUp(host);
15711560 // If one of the connections in onUp failed, it signaled the error and triggerd onDown,
15721561 // but onDown aborted because this reconnection attempt was in progress (JAVA-577).
15731562 // Test the state now to check than onUp succeeded (we know it's up-to-date since onUp was
@@ -1819,42 +1808,39 @@
18191808
18201809 controlConnection.onAdd(host);
18211810
1822- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(sessions.size());
1811+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
18231812 for (SessionManager s : sessions)
1824- futures.add(s.maybeAddPool(host, blockingExecutor));
1825-
1826- // Only mark the node up once all session have added their pool (if the load-balancing
1827- // policy says it should), so that Host.isUp() don't return true before we're reconnected
1828- // to the node.
1829- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
1830- Futures.addCallback(f, new FutureCallback<List<Boolean>>() {
1831- public void onSuccess(List<Boolean> poolCreationResults) {
1832- // If any of the creation failed, they will have signaled a connection failure
1833- // which will trigger a reconnection to the node. So don't bother marking UP.
1834- if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1835- logger.debug("Connection pool cannot be created, not marking {} UP", host);
1836- return;
1837- }
1813+ futures.add(s.maybeAddPool(host));
18381814
1839- host.setUp();
1840-
1841- for (Host.StateListener listener : listeners)
1842- listener.onAdd(host);
1815+ try {
1816+ // Only mark the node up once all session have added their pool (if the load-balancing
1817+ // policy says it should), so that Host.isUp() don't return true before we're reconnected
1818+ // to the node.
1819+ List<Boolean> poolCreationResults = Futures.allAsList(futures).get();
1820+
1821+ // If any of the creation failed, they will have signaled a connection failure
1822+ // which will trigger a reconnection to the node. So don't bother marking UP.
1823+ if (Iterables.any(poolCreationResults, Predicates.equalTo(false))) {
1824+ logger.debug("Connection pool cannot be created, not marking {} UP", host);
1825+ return;
18431826 }
18441827
1845- public void onFailure(Throwable t) {
1846- // That future is not really supposed to throw unexpected exceptions
1847- if (!(t instanceof InterruptedException))
1848- logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1849- }
1850- });
1828+ host.setUp();
1829+
1830+ for (Host.StateListener listener : listeners)
1831+ listener.onAdd(host);
18511832
1852- f.get();
1833+ } catch (ExecutionException e) {
1834+ Throwable t = e.getCause();
1835+ // That future is not really supposed to throw unexpected exceptions
1836+ if (!(t instanceof InterruptedException))
1837+ logger.error("Unexpected error while adding node: while this shouldn't happen, this shouldn't be critical", t);
1838+ }
18531839
18541840 // Now, check if there isn't pools to create/remove following the addition.
18551841 // We do that now only so that it's not called before we've set the node up.
18561842 for (SessionManager s : sessions)
1857- s.updateCreatedPools(blockingExecutor);
1843+ s.updateCreatedPools();
18581844
18591845 } finally {
18601846 host.notificationsLock.unlock();
@@ -2221,7 +2207,7 @@
22212207 controlConnection.reconnect();
22222208
22232209 for (SessionManager s : sessions)
2224- s.updateCreatedPools(executor);
2210+ s.updateCreatedPools();
22252211 }
22262212
22272213 void refreshConnectedHost(Host host) {
@@ -2231,7 +2217,7 @@
22312217 controlConnection.reconnect();
22322218
22332219 for (SessionManager s : sessions)
2234- s.updateCreatedPools(host, executor);
2220+ s.updateCreatedPools(host);
22352221 }
22362222
22372223 private class ClusterCloseFuture extends CloseFuture.Forwarding {
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +254 −139
@@ -26,8 +26,7 @@
2626 import java.util.concurrent.atomic.AtomicReference;
2727
2828 import com.google.common.collect.Lists;
29-import com.google.common.util.concurrent.AbstractFuture;
30-import com.google.common.util.concurrent.Uninterruptibles;
29+import com.google.common.util.concurrent.*;
3130 import io.netty.bootstrap.Bootstrap;
3231 import io.netty.channel.*;
3332 import io.netty.channel.group.ChannelGroup;
@@ -47,7 +46,8 @@
4746 import static io.netty.handler.timeout.IdleState.ALL_IDLE;
4847
4948 import com.datastax.driver.core.exceptions.AuthenticationException;
50-import com.datastax.driver.core.exceptions.DriverInternalError;
49+import com.datastax.driver.core.exceptions.DriverException;
50+import com.datastax.driver.core.utils.MoreFutures;
5151
5252 // For LoggingHandler
5353 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -66,7 +66,7 @@
6666 public final InetSocketAddress address;
6767 private final String name;
6868
69- private final Channel channel;
69+ private volatile Channel channel;
7070 private final Factory factory;
7171
7272 private final Dispatcher dispatcher = new Dispatcher();
@@ -86,19 +86,23 @@
8686 * Create a new connection to a Cassandra node.
8787 *
8888 * The connection is open and initialized by the constructor.
89- *
90- * @throws ConnectionException if the connection attempts fails or is
91- * refused by the server.
9289 */
93- protected Connection(String name, InetSocketAddress address, Factory factory) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
90+ protected Connection(String name, InetSocketAddress address, Factory factory) {
9491 this.address = address;
9592 this.factory = factory;
9693 this.name = name;
94+ }
95+
96+ public ListenableFuture<Void> initAsync() {
97+ if (factory.isShutdown)
98+ return Futures.immediateFailedFuture(new ConnectionException(address, "Connection factory is shut down"));
99+
100+ int protocolVersion = factory.protocolVersion == 1 ? 1 : 2;
101+ final SettableFuture<Void> channelReadyFuture = SettableFuture.create();
97102
98103 try {
99104 Bootstrap bootstrap = factory.newBootstrap();
100105 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
101- int protocolVersion = factory.protocolVersion == 1 ? 1 : 2;
102106 bootstrap.handler(
103107 new Initializer(this, protocolVersion, protocolOptions.getCompression().compressor(), protocolOptions.getSSLOptions(),
104108 factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(),
@@ -107,41 +111,81 @@
107111 ChannelFuture future = bootstrap.connect(address);
108112
109113 writer.incrementAndGet();
110- try {
111- // Wait until the connection attempt succeeds or fails.
112- this.channel = future.awaitUninterruptibly().channel();
113- this.factory.allChannels.add(this.channel);
114- if (!future.isSuccess()) {
115- if (logger.isDebugEnabled())
116- logger.debug(String.format("%s Error connecting to %s%s", this, address, extractMessage(future.cause())));
117- throw defunct(new TransportException(address, "Cannot connect", future.cause()));
114+ future.addListener(new ChannelFutureListener() {
115+ @Override
116+ public void operationComplete(ChannelFuture future) throws Exception {
117+ writer.decrementAndGet();
118+ channel = future.channel();
119+ if (isClosed()) {
120+ channel.close().addListener(new ChannelFutureListener() {
121+ @Override
122+ public void operationComplete(ChannelFuture future) throws Exception {
123+ channelReadyFuture.setException(new TransportException(Connection.this.address, "Connection closed during initialization."));
124+ }
125+ });
126+ } else {
127+ Connection.this.factory.allChannels.add(channel);
128+ if (!future.isSuccess()) {
129+ if (logger.isDebugEnabled())
130+ logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause())));
131+ channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause()));
132+ } else {
133+ logger.debug("{} Connection opened successfully", Connection.this);
134+ channel.closeFuture().addListener(new ChannelCloseListener());
135+ channelReadyFuture.set(null);
136+ }
137+ }
118138 }
119- channel.closeFuture().addListener(new ChannelCloseListener());
120- } finally {
121- writer.decrementAndGet();
122- }
123-
124- logger.trace("{} Connection opened successfully", this);
125- initializeTransport(protocolVersion, factory.manager.metadata.clusterName);
126- logger.debug("{} Transport initialized and ready", this);
127- isInitialized = true;
128-
129- } catch (ConnectionException e) {
130- closeAsync().force();
131- throw e;
132- } catch (ClusterNameMismatchException e) {
133- closeAsync().force();
134- throw e;
135- } catch (UnsupportedProtocolVersionException e) {
136- closeAsync().force();
137- throw e;
138- } catch (InterruptedException e) {
139- closeAsync().force();
140- throw e;
139+ });
141140 } catch (RuntimeException e) {
142141 closeAsync().force();
143142 throw e;
144143 }
144+
145+ Executor initExecutor = factory.manager.configuration.getPoolingOptions().getInitializationExecutor();
146+
147+ ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
148+ onChannelReady(protocolVersion, initExecutor), initExecutor);
149+
150+ // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
151+ ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() {
152+ @Override
153+ public ListenableFuture<Void> create(Throwable t) throws Exception {
154+ SettableFuture<Void> future = SettableFuture.create();
155+ // Make sure the connection gets properly closed.
156+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
157+ // These exceptions cause the node to be ignored, so just propagate
158+ closeAsync().force();
159+ future.setException(t);
160+ } else {
161+ // Defunct to ensure that the error will be signaled (marking the host down)
162+ ConnectionException ce = (t instanceof ConnectionException)
163+ ? (ConnectionException)t
164+ : new ConnectionException(Connection.this.address,
165+ String.format("Unexpected error during transport initialization (%s)", t),
166+ t);
167+ future.setException(defunct(ce));
168+ }
169+ return future;
170+ }
171+ }, initExecutor);
172+
173+ // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel.
174+ Futures.addCallback(initFuture, new FutureCallback<Void>() {
175+ @Override
176+ public void onSuccess(Void result) {
177+ isInitialized = true;
178+ }
179+
180+ @Override
181+ public void onFailure(Throwable t) {
182+ if (!isClosed()) {
183+ closeAsync().force();
184+ }
185+ }
186+ }, initExecutor);
187+
188+ return initFuture;
145189 }
146190
147191 private static String extractMessage(Throwable t) {
@@ -153,119 +197,157 @@
153197 return " (" + msg + ')';
154198 }
155199
156- private void initializeTransport(int version, String clusterName) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
157- try {
158- ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
159- Message.Response response = write(new Requests.Startup(compression)).get();
160- switch (response.type) {
161- case READY:
162- break;
163- case ERROR:
164- Responses.Error error = (Responses.Error)response;
165- // Testing for a specific string is a tad fragile but well, we don't have much choice
166- if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
167- throw unsupportedProtocolVersionException(version);
168- throw defunct(new TransportException(address, String.format("Error initializing connection: %s", error.message)));
169- case AUTHENTICATE:
170- Authenticator authenticator = factory.authProvider.newAuthenticator(address);
171- if (version == 1)
172- {
173- if (authenticator instanceof ProtocolV1Authenticator)
174- authenticateV1(authenticator);
175- else
176- // DSE 3.x always uses SASL authentication backported from protocol v2
177- authenticateV2(authenticator);
178- }
179- else
180- authenticateV2(authenticator);
181- break;
182- default:
183- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type)));
200+ private AsyncFunction<Void, Void> onChannelReady(final int protocolVersion, final Executor initExecutor) {
201+ return new AsyncFunction<Void, Void>() {
202+ @Override
203+ public ListenableFuture<Void> apply(Void input) throws Exception {
204+ ProtocolOptions.Compression compression = factory.configuration.getProtocolOptions().getCompression();
205+ Future startupResponseFuture = write(new Requests.Startup(compression));
206+ return Futures.transform(startupResponseFuture,
207+ onStartupResponse(protocolVersion, initExecutor), initExecutor);
184208 }
209+ };
210+ }
185211
186- checkClusterName(clusterName);
187- } catch (BusyConnectionException e) {
188- throw defunct(new DriverInternalError("Newly created connection should not be busy"));
189- } catch (ExecutionException e) {
190- throw defunct(new ConnectionException(address, String.format("Unexpected error during transport initialization (%s)", e.getCause()), e.getCause()));
191- }
212+ private AsyncFunction<Message.Response, Void> onStartupResponse(final int protocolVersion, final Executor initExecutor) {
213+ return new AsyncFunction<Message.Response, Void>() {
214+ @Override
215+ public ListenableFuture<Void> apply(Message.Response response) throws Exception {
216+ switch (response.type) {
217+ case READY:
218+ return checkClusterName(initExecutor);
219+ case ERROR:
220+ Responses.Error error = (Responses.Error)response;
221+ // Testing for a specific string is a tad fragile but well, we don't have much choice
222+ if (error.code == ExceptionCode.PROTOCOL_ERROR && error.message.contains("Invalid or unsupported protocol version"))
223+ throw unsupportedProtocolVersionException(protocolVersion);
224+ throw new TransportException(address, String.format("Error initializing connection: %s", error.message));
225+ case AUTHENTICATE:
226+ Authenticator authenticator = factory.authProvider.newAuthenticator(address);
227+ if (protocolVersion == 1)
228+ {
229+ if (authenticator instanceof ProtocolV1Authenticator)
230+ return authenticateV1(authenticator, initExecutor);
231+ else
232+ // DSE 3.x always uses SASL authentication backported from protocol v2
233+ return authenticateV2(authenticator, initExecutor);
234+ }
235+ else
236+ return authenticateV2(authenticator, initExecutor);
237+ default:
238+ throw new TransportException(address, String.format("Unexpected %s response message from server to a STARTUP message", response.type));
239+ }
240+ }
241+ };
192242 }
193243
194- private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) {
195- logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion);
196- return new UnsupportedProtocolVersionException(address, triedVersion);
244+ // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
245+ // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting
246+ // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397).
247+ private ListenableFuture<Void> checkClusterName(final Executor executor) {
248+ final String expected = factory.manager.metadata.clusterName;
249+
250+ // At initialization, the cluster is not known yet
251+ if (expected == null)
252+ return MoreFutures.VOID_SUCCESS;
253+
254+ DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local"));
255+ try {
256+ write(clusterNameFuture);
257+ return Futures.transform(clusterNameFuture,
258+ new AsyncFunction<ResultSet, Void>() {
259+ @Override
260+ public ListenableFuture<Void> apply(ResultSet rs) throws Exception {
261+ Row row = rs.one();
262+ String actual = row.getString("cluster_name");
263+ if (!expected.equals(actual))
264+ throw new ClusterNameMismatchException(address, actual, expected);
265+ return MoreFutures.VOID_SUCCESS;
266+ }
267+ }, executor);
268+ } catch (Exception e) {
269+ return Futures.immediateFailedFuture(e);
270+ }
197271 }
198272
199- private void authenticateV1(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
273+ private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final Executor executor) {
200274 Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
201- Message.Response authResponse = write(creds).get();
202- switch (authResponse.type) {
203- case READY:
204- break;
205- case ERROR:
206- throw defunct(new AuthenticationException(address, ((Responses.Error)authResponse).message));
207- default:
208- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)));
275+ try {
276+ Future authResponseFuture = write(creds);
277+ return Futures.transform(authResponseFuture,
278+ new AsyncFunction<Message.Response, Void>() {
279+ @Override
280+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
281+ switch (authResponse.type) {
282+ case READY:
283+ return checkClusterName(executor);
284+ case ERROR:
285+ throw new AuthenticationException(address, ((Responses.Error)authResponse).message);
286+ default:
287+ throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type));
288+ }
289+ }
290+ }, executor);
291+ } catch (Exception e) {
292+ return Futures.immediateFailedFuture(e);
209293 }
210294 }
211295
212- private void authenticateV2(Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
296+ private ListenableFuture<Void> authenticateV2(final Authenticator authenticator, final Executor executor) {
213297 byte[] initialResponse = authenticator.initialResponse();
214298 if (null == initialResponse)
215299 initialResponse = EMPTY_BYTE_ARRAY;
216300
217- Message.Response authResponse = write(new Requests.AuthResponse(initialResponse)).get();
218- waitForAuthCompletion(authResponse, authenticator);
301+ try {
302+ Future authResponseFuture = write(new Requests.AuthResponse(initialResponse));
303+ return Futures.transform(authResponseFuture, onV2AuthResponse(authenticator, executor), executor);
304+ } catch (Exception e) {
305+ return Futures.immediateFailedFuture(e);
306+ }
219307 }
220308
221- private void waitForAuthCompletion(Message.Response authResponse, Authenticator authenticator) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
222- switch (authResponse.type) {
223- case AUTH_SUCCESS:
224- logger.trace("{} Authentication complete", this);
225- authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
226- break;
227- case AUTH_CHALLENGE:
228- byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
229- if (responseToServer == null) {
230- // If we generate a null response, then authentication has completed, return without
231- // sending a further response back to the server.
232- logger.trace("{} Authentication complete (No response to server)", this);
233- return;
234- } else {
235- // Otherwise, send the challenge response back to the server
236- logger.trace("{} Sending Auth response to challenge", this);
237- waitForAuthCompletion(write(new Requests.AuthResponse(responseToServer)).get(), authenticator);
309+ private AsyncFunction<Message.Response, Void> onV2AuthResponse(final Authenticator authenticator, final Executor executor) {
310+ return new AsyncFunction<Message.Response, Void>() {
311+ @Override
312+ public ListenableFuture<Void> apply(Message.Response authResponse) throws Exception {
313+ switch (authResponse.type) {
314+ case AUTH_SUCCESS:
315+ logger.trace("{} Authentication complete", this);
316+ authenticator.onAuthenticationSuccess(((Responses.AuthSuccess)authResponse).token);
317+ return checkClusterName(executor);
318+ case AUTH_CHALLENGE:
319+ byte[] responseToServer = authenticator.evaluateChallenge(((Responses.AuthChallenge)authResponse).token);
320+ if (responseToServer == null) {
321+ // If we generate a null response, then authentication has completed, proceed without
322+ // sending a further response back to the server.
323+ logger.trace("{} Authentication complete (No response to server)", this);
324+ return checkClusterName(executor);
325+ } else {
326+ // Otherwise, send the challenge response back to the server
327+ logger.trace("{} Sending Auth response to challenge", this);
328+ Future nextResponseFuture = write(new Requests.AuthResponse(responseToServer));
329+ return Futures.transform(nextResponseFuture, onV2AuthResponse(authenticator, executor), executor);
330+ }
331+ case ERROR:
332+ // This is not very nice, but we're trying to identify if we
333+ // attempted v2 auth against a server which only supports v1
334+ // The AIOOBE indicates that the server didn't recognise the
335+ // initial AuthResponse message
336+ String message = ((Responses.Error)authResponse).message;
337+ if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
338+ message = String.format("Cannot use authenticator %s with protocol version 1, "
339+ + "only plain text authentication is supported with this protocol version", authenticator);
340+ throw new AuthenticationException(address, message);
341+ default:
342+ throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type));
238343 }
239- break;
240- case ERROR:
241- // This is not very nice, but we're trying to identify if we
242- // attempted v2 auth against a server which only supports v1
243- // The AIOOBE indicates that the server didn't recognise the
244- // initial AuthResponse message
245- String message = ((Responses.Error)authResponse).message;
246- if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15"))
247- message = String.format("Cannot use authenticator %s with protocol version 1, "
248- + "only plain text authentication is supported with this protocol version", authenticator);
249- throw defunct(new AuthenticationException(address, message));
250- default:
251- throw defunct(new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type)));
252- }
344+ }
345+ };
253346 }
254347
255- // Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
256- // If these nodes have been recommissionned to another cluster and are up, nothing prevents the driver from connecting
257- // to them. So we check that the cluster the node thinks it belongs to is our cluster (JAVA-397).
258- private void checkClusterName(String expected) throws ClusterNameMismatchException, ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
259- // At initialization, the cluster is not known yet
260- if (expected == null)
261- return;
262-
263- DefaultResultSetFuture future = new DefaultResultSetFuture(null,new Requests.Query("select cluster_name from system.local"));
264- write(future);
265- Row row = future.get().one();
266- String actual = row.getString("cluster_name");
267- if (!expected.equals(actual))
268- throw new ClusterNameMismatchException(address, actual, expected);
348+ private UnsupportedProtocolVersionException unsupportedProtocolVersionException(int triedVersion) {
349+ logger.debug("Got unsupported protocol version error from {} for version {}", address, triedVersion);
350+ return new UnsupportedProtocolVersionException(address, triedVersion);
269351 }
270352
271353 public boolean isDefunct() {
@@ -585,22 +667,55 @@
585667 throw new ConnectionException(address, "Connection factory is shut down");
586668
587669 String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement();
588- return new Connection(name, address, this);
670+ Connection connection = new Connection(name, address, this);
671+ // This method opens the connection synchronously, so wait until it's initialized
672+ try {
673+ connection.initAsync().get();
674+ return connection;
675+ } catch (ExecutionException e) {
676+ throw launderAsyncInitException(e);
677+ }
589678 }
590679
591680 /**
592681 * Same as open, but associate the created connection to the provided connection pool.
593682 */
594683 public PooledConnection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
595- InetSocketAddress address = pool.host.getSocketAddress();
596-
597- if (isShutdown)
598- throw new ConnectionException(address, "Connection factory is shut down");
684+ try {
685+ PooledConnection connection = newConnection(pool);
686+ connection.initAsync().get();
687+ return connection;
688+ } catch (ExecutionException e) {
689+ throw launderAsyncInitException(e);
690+ }
691+ }
599692
693+ /**
694+ * Creates a new connection and associates it to the provided connection pool, but does not start it.
695+ */
696+ public PooledConnection newConnection(HostConnectionPool pool) {
697+ InetSocketAddress address = pool.host.getSocketAddress();
600698 String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
699+
601700 return new PooledConnection(name, address, this, pool);
602701 }
603702
703+ static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
704+ Throwable t = e.getCause();
705+ if (t instanceof ConnectionException)
706+ throw (ConnectionException)t;
707+ if (t instanceof InterruptedException)
708+ throw (InterruptedException)t;
709+ if (t instanceof UnsupportedProtocolVersionException)
710+ throw (UnsupportedProtocolVersionException)t;
711+ if (t instanceof ClusterNameMismatchException)
712+ throw (ClusterNameMismatchException)t;
713+ if (t instanceof DriverException)
714+ throw (DriverException)t;
715+
716+ return new RuntimeException("Unexpected exception during connection initialization", t);
717+ }
718+
604719 private AtomicInteger getIdGenerator(Host host) {
605720 AtomicInteger g = idGenerators.get(host);
606721 if (g == null) {
@@ -925,7 +1040,7 @@
9251040 public ConnectionCloseFuture force() {
9261041 // Note: we must not call releaseExternalResources on the bootstrap, because this shutdown the executors, which are shared
9271042
928- // This method can be thrown during Connection ctor, at which point channel is not yet set. This is ok.
1043+ // This method can be thrown during initialization, at which point channel is not yet set. This is ok.
9291044 if (channel == null) {
9301045 set(null);
9311046 return this;
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +3 −1
@@ -249,7 +249,9 @@
249249 if (!super.cancel(mayInterruptIfRunning))
250250 return false;
251251
252- handler.cancel();
252+ if(handler != null) {
253+ handler.cancel();
254+ }
253255 return true;
254256 }
255257
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +3 −1
@@ -27,6 +27,8 @@
2727 import org.slf4j.Logger;
2828 import org.slf4j.LoggerFactory;
2929
30+import com.datastax.driver.core.utils.MoreFutures;
31+
3032 /**
3133 * A Cassandra node.
3234 *
@@ -48,7 +50,7 @@
4850 private final Cluster.Manager manager;
4951
5052 // Tracks the first "immediate" reconnection attempt when a node get suspected.
51- final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(Futures.immediateFuture(null));
53+ final AtomicReference<ListenableFuture<?>> initialReconnectionAttempt = new AtomicReference<ListenableFuture<?>>(MoreFutures.VOID_SUCCESS);
5254
5355 // Tracks later reconnection attempts to that host so we avoid adding multiple tasks.
5456 final AtomicReference<ListenableFuture<?>> reconnectionAttempt = new AtomicReference<ListenableFuture<?>>();
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +63 −42
@@ -15,14 +15,10 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-
1918 import java.util.ArrayList;
2019 import java.util.List;
2120 import java.util.Set;
22-import java.util.concurrent.CopyOnWriteArrayList;
23-import java.util.concurrent.CopyOnWriteArraySet;
24-import java.util.concurrent.TimeUnit;
25-import java.util.concurrent.TimeoutException;
21+import java.util.concurrent.*;
2622 import java.util.concurrent.atomic.AtomicInteger;
2723 import java.util.concurrent.atomic.AtomicReference;
2824 import java.util.concurrent.locks.Condition;
@@ -30,13 +26,16 @@
3026 import java.util.concurrent.locks.ReentrantLock;
3127
3228 import com.google.common.collect.Lists;
33-import com.google.common.util.concurrent.MoreExecutors;
29+import com.google.common.util.concurrent.*;
3430 import org.slf4j.Logger;
3531 import org.slf4j.LoggerFactory;
3632
3733 import com.datastax.driver.core.exceptions.AuthenticationException;
3834
39-import static com.datastax.driver.core.PooledConnection.State.*;
35+import static com.datastax.driver.core.PooledConnection.State.GONE;
36+import static com.datastax.driver.core.PooledConnection.State.OPEN;
37+import static com.datastax.driver.core.PooledConnection.State.RESURRECTING;
38+import static com.datastax.driver.core.PooledConnection.State.TRASHED;
4039
4140 class HostConnectionPool {
4241
@@ -69,10 +68,12 @@
6968
7069 private final AtomicInteger scheduledForCreation = new AtomicInteger();
7170
72- private volatile boolean isClosing;
7371 private final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
7472
75- public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
73+ private enum Phase { INITIALIZING, READY, INIT_FAILED, CLOSING }
74+ private volatile Phase phase = Phase.INITIALIZING;
75+
76+ public HostConnectionPool(final Host host, HostDistance hostDistance, final SessionManager manager) {
7677 assert hostDistance != HostDistance.IGNORED;
7778 this.host = host;
7879 this.hostDistance = hostDistance;
@@ -86,37 +87,55 @@
8687 }
8788 };
8889
90+ this.connections = new CopyOnWriteArrayList<PooledConnection>();
91+ this.open = new AtomicInteger();
92+ }
93+
94+ public ListenableFuture<Void> initAsync() {
8995 // Create initial core connections
90- List<PooledConnection> l = new ArrayList<PooledConnection>(options().getCoreConnectionsPerHost(hostDistance));
91- try {
92- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++)
93- l.add(manager.connectionFactory().open(this));
94- } catch (InterruptedException e) {
95- Thread.currentThread().interrupt();
96- // If asked to interrupt, we can skip opening core connections, the pool will still work.
97- // But we ignore otherwise cause I'm not sure we can do much better currently.
98- } catch (ConnectionException e) {
99- forceClose(l);
100- throw e;
101- } catch (UnsupportedProtocolVersionException e) {
102- forceClose(l);
103- throw e;
104- } catch (ClusterNameMismatchException e) {
105- forceClose(l);
106- throw e;
107- } catch (RuntimeException e) {
108- forceClose(l);
109- throw e;
96+ int capacity = options().getCoreConnectionsPerHost(hostDistance);
97+ final List<PooledConnection> connections = Lists.newArrayListWithCapacity(capacity);
98+ final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
99+ for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
100+ PooledConnection connection = manager.connectionFactory().newConnection(this);
101+ connections.add(connection);
102+ connectionFutures.add(connection.initAsync());
110103 }
111- this.connections = new CopyOnWriteArrayList<PooledConnection>(l);
112- this.open = new AtomicInteger(connections.size());
113104
114- logger.trace("Created connection pool to host {}", host);
105+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
106+
107+ ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
108+
109+ final SettableFuture<Void> initFuture = SettableFuture.create();
110+ Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
111+ @Override
112+ public void onSuccess(List<Void> l) {
113+ HostConnectionPool.this.connections.addAll(connections);
114+ open.set(l.size());
115+ if (isClosed()) {
116+ initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
117+ // we're not sure if closeAsync() saw the connections, so ensure they get closed
118+ forceClose(connections);
119+ } else {
120+ logger.trace("Created connection pool to host {}", host);
121+ phase = Phase.READY;
122+ initFuture.set(null);
123+ }
124+ }
125+
126+ @Override
127+ public void onFailure(Throwable t) {
128+ phase = Phase.INIT_FAILED;
129+ forceClose(connections);
130+ initFuture.setException(t);
131+ }
132+ }, initExecutor);
133+ return initFuture;
115134 }
116135
117136 // Clean up if we got an error at construction time but still created part of the core connections
118- private void forceClose(List<PooledConnection> l) {
119- for (PooledConnection connection : l) {
137+ private void forceClose(List<PooledConnection> connections) {
138+ for (PooledConnection connection : connections) {
120139 connection.closeAsync().force();
121140 }
122141 }
@@ -126,10 +145,13 @@
126145 }
127146
128147 public PooledConnection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
129- if (isClosed())
148+ if (phase == Phase.INITIALIZING)
149+ throw new ConnectionException(host.getSocketAddress(), "Pool is initializing.");
150+
151+ if (phase != Phase.READY)
130152 // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host.
131153 // That being said, maybe having a specific exception could be cleaner.
132- throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown");
154+ throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
133155
134156 if (connections.isEmpty()) {
135157 for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
@@ -355,7 +377,7 @@
355377 break;
356378 }
357379
358- if (isClosing) {
380+ if (phase != Phase.READY) {
359381 open.decrementAndGet();
360382 return false;
361383 }
@@ -372,7 +394,7 @@
372394 newConnection.state.compareAndSet(RESURRECTING, OPEN); // no-op if it was already OPEN
373395
374396 // We might have raced with pool shutdown since the last check; ensure the connection gets closed in case the pool did not do it.
375- if (isClosing && !newConnection.isClosed()) {
397+ if (phase != Phase.READY && !newConnection.isClosed()) {
376398 close(newConnection);
377399 open.decrementAndGet();
378400 return false;
@@ -517,7 +539,7 @@
517539 if (future != null)
518540 return future;
519541
520- isClosing = true;
542+ phase = Phase.CLOSING;
521543
522544 // Wake up all threads that wait
523545 signalAllAvailableConnection();
@@ -538,9 +560,8 @@
538560 }
539561
540562 private List<CloseFuture> discardAvailableConnections() {
541- // This can happen if creating the connections in the constructor fails
542- if (connections == null)
543- return Lists.newArrayList(CloseFuture.immediateFuture());
563+ // Note: if this gets called before initialization has completed, both connections and trash will be empty,
564+ // so this will return an empty list
544565
545566 List<CloseFuture> futures = new ArrayList<CloseFuture>(connections.size() + trash.size());
546567
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +1 −1
@@ -31,7 +31,7 @@
3131
3232 volatile long maxIdleTime;
3333
34- PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
34+ PooledConnection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) {
3535 super(name, address, factory);
3636 this.pool = pool;
3737 }
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +45 −0
@@ -15,6 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.concurrent.Executor;
19+
20+import com.google.common.base.Preconditions;
21+import com.google.common.util.concurrent.MoreExecutors;
22+
1823 /**
1924 * Options related to connection pooling.
2025 * <p>
@@ -53,6 +58,8 @@
5358 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
5459 private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
5560
61+ private static final Executor DEFAULT_INITIALIZATION_EXECUTOR = MoreExecutors.sameThreadExecutor();
62+
5663 private volatile Cluster.Manager manager;
5764
5865 private final int[] maxSimultaneousRequests = new int[]{ DEFAULT_MAX_REQUESTS, DEFAULT_MAX_REQUESTS, 0 };
@@ -64,6 +71,8 @@
6471 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
6572 private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
6673
74+ private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR;
75+
6776 public PoolingOptions() {}
6877
6978 void register(Cluster.Manager manager) {
@@ -308,6 +317,42 @@
308317 return this;
309318 }
310319
320+ /**
321+ * Returns the executor to use for connection initialization.
322+ *
323+ * @return the executor.
324+ * @see #setInitializationExecutor(java.util.concurrent.Executor)
325+ */
326+ public Executor getInitializationExecutor() {
327+ return initializationExecutor;
328+ }
329+
330+ /**
331+ * Sets the executor to use for connection initialization.
332+ * <p>
333+ * Connections are open in a completely asynchronous manner. Since initializing the transport
334+ * requires separate CQL queries, the futures representing the completion of these queries are
335+ * transformed and chained. This executor is where these transformations happen.
336+ * <p>
337+ * <b>This is an advanced option, which should be rarely needed in practice.</b> It defaults to
338+ * Guava's {@code MoreExecutors.sameThreadExecutor()}, which results in running the transformations
339+ * on the network I/O threads; this is fine if the transformations are fast and not I/O bound
340+ * (which is the case by default).
341+ * One reason why you might want to provide a custom executor is if you use authentication with
342+ * a custom {@link com.datastax.driver.core.Authenticator} implementation that performs blocking
343+ * calls.
344+ *
345+ * @param initializationExecutor the executor to use
346+ * @return this {@code PoolingOptions}
347+ *
348+ * @throws java.lang.NullPointerException if the executor is null
349+ */
350+ public PoolingOptions setInitializationExecutor(Executor initializationExecutor) {
351+ Preconditions.checkNotNull(initializationExecutor);
352+ this.initializationExecutor = initializationExecutor;
353+ return this;
354+ }
355+
311356 /**
312357 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
313358 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +123 −115
@@ -20,10 +20,10 @@
2020 import java.util.*;
2121 import java.util.concurrent.*;
2222 import java.util.concurrent.atomic.AtomicReference;
23-import java.util.concurrent.locks.Lock;
2423
2524 import com.google.common.base.Function;
2625 import com.google.common.collect.ImmutableList;
26+import com.google.common.collect.Lists;
2727 import com.google.common.util.concurrent.*;
2828 import org.slf4j.Logger;
2929 import org.slf4j.LoggerFactory;
@@ -33,6 +33,7 @@
3333 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
3434 import com.datastax.driver.core.policies.LoadBalancingPolicy;
3535 import com.datastax.driver.core.policies.ReconnectionPolicy;
36+import com.datastax.driver.core.utils.MoreFutures;
3637
3738 /**
3839 * Driver implementation of the Session interface.
@@ -46,8 +47,6 @@
4647 final HostConnectionPool.PoolState poolsState;
4748 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
4849
49- private final Striped<Lock> poolCreationLocks = Striped.lazyWeakLock(5);
50-
5150 private volatile boolean isInit;
5251 private volatile boolean isClosing;
5352
@@ -67,50 +66,28 @@
6766
6867 // Create pools to initial nodes (and wait for them to be created)
6968 Collection<Host> hosts = cluster.getMetadata().allHosts();
70- if (cluster.manager.sessions.size() == 1) {
71- // We only do it in parallel if this is the first session (meaning that the cluster just initialized).
72- createPoolsInParallel(hosts);
73- } else {
74- // Otherwise, we don't want to fill executor() because this is also where up/down notifications are processed,
75- // it's important that existing sessions get them in a timely manner. So we create the pools one by one:
76- createPoolsSequentially(hosts);
77- }
69+ createPoolsInParallel(hosts);
7870
7971 isInit = true;
80- updateCreatedPools(executor());
72+ updateCreatedPools();
8173 return this;
8274 }
8375
8476 private void createPoolsInParallel(Collection<Host> hosts) {
85- List<ListenableFuture<Boolean>> futures = new ArrayList<ListenableFuture<Boolean>>(hosts.size());
77+ List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
8678 for (Host host : hosts)
8779 if (host.state != Host.State.DOWN)
88- futures.add(maybeAddPool(host, executor()));
89- ListenableFuture<List<Boolean>> f = Futures.allAsList(futures);
80+ futures.add(maybeAddPool(host));
9081 try {
91- f.get();
82+ Futures.successfulAsList(futures).get();
9283 } catch (ExecutionException e) {
93- // This is not supposed to happen
94- throw new DriverInternalError(e);
84+ // Won't happen because we used successfulAsList
85+ // And if a particular pool failed, maybeAddPool already handled it
9586 } catch (InterruptedException e) {
9687 Thread.currentThread().interrupt();
9788 }
9889 }
9990
100- private void createPoolsSequentially(Collection<Host> hosts) {
101- for (Host host : cluster.getMetadata().allHosts()) {
102- try {
103- if (host.state != Host.State.DOWN)
104- maybeAddPool(host, executor()).get();
105- } catch (ExecutionException e) {
106- // This is not supposed to happen
107- throw new DriverInternalError(e);
108- } catch (InterruptedException e) {
109- Thread.currentThread().interrupt();
110- }
111- }
112- }
113-
11491 public String getLoggedKeyspace() {
11592 return poolsState.keyspace;
11693 }
@@ -215,77 +192,94 @@
215192 }
216193
217194 // Returns whether there was problem creating the pool
218- ListenableFuture<Boolean> forceRenewPool(final Host host, ListeningExecutorService executor) {
195+ ListenableFuture<Boolean> forceRenewPool(final Host host) {
219196 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
220197 if (distance == HostDistance.IGNORED)
221198 return Futures.immediateFuture(true);
222199
223- // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
224- return executor.submit(new Callable<Boolean>() {
225- public Boolean call() {
226- while (true) {
227- try {
228- if (isClosing)
229- return true;
230-
231- HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this);
232- HostConnectionPool previous = pools.put(host, newPool);
233- if (previous == null) {
234- logger.debug("Added connection pool for {}", host);
235- } else {
236- logger.debug("Renewed connection pool for {}", host);
237- previous.closeAsync();
238- }
200+ if (isClosing)
201+ return Futures.immediateFuture(false);
202+
203+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, SessionManager.this);
204+ ListenableFuture<Void> poolInitFuture = newPool.initAsync();
205+
206+ final SettableFuture<Boolean> future = SettableFuture.create();
207+
208+ Futures.addCallback(poolInitFuture, new FutureCallback<Void>() {
209+ @Override
210+ public void onSuccess(Void result) {
211+ // If we raced with a session shutdown, ensure that the pool will be closed.
212+ HostConnectionPool previous = pools.put(host, newPool);
213+ if (previous == null) {
214+ logger.debug("Added connection pool for {}", host);
215+ } else {
216+ logger.debug("Renewed connection pool for {}", host);
217+ previous.closeAsync();
218+ }
239219
240- // If we raced with a session shutdown, ensure that the pool will be closed.
241- if (isClosing)
242- newPool.closeAsync();
243-
244- return true;
245- } catch (Exception e) {
246- logger.error("Error creating pool to " + host, e);
247- return false;
248- }
220+ // If we raced with a session shutdown, ensure that the pool will be closed.
221+ if (isClosing) {
222+ newPool.closeAsync();
223+ pools.remove(host);
224+ future.set(false);
225+ } else {
226+ future.set(true);
249227 }
250228 }
229+
230+ @Override
231+ public void onFailure(Throwable t) {
232+ logger.error("Error creating pool to " + host, t);
233+ future.set(false);
234+ }
251235 });
236+
237+ return future;
252238 }
253239
254- // Replace pool for a given only if it's the given previous value (which can be null)
255- // Note that the goal of this function is to make sure that 2 concurrent thread calling
256- // maybeAddPool don't end up creating 2 HostConnectionPool. We can't rely on the pools
257- // ConcurrentMap only for that since it's the duplicate HostConnectionPool creation we
258- // want to avoid
259- private boolean replacePool(Host host, HostDistance distance, HostConnectionPool condition) throws ConnectionException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
240+ // Replace pool for a given host only if it's the given previous value (which can be null)
241+ // This returns a future if the replacement was successful, or null if we raced.
242+ private ListenableFuture<Void> replacePool(final Host host, HostDistance distance, HostConnectionPool previous) {
260243 if (isClosing)
261- return true;
262-
263- Lock l = poolCreationLocks.get(host);
264- l.lock();
265- try {
266- HostConnectionPool previous = pools.get(host);
267- if (previous != condition)
268- return false;
269-
270- HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
271- previous = pools.put(host, newPool);
272- if (previous != null && !previous.isClosed()) {
244+ return MoreFutures.VOID_SUCCESS;
245+
246+ final HostConnectionPool newPool = new HostConnectionPool(host, distance, this);
247+ if (previous == null) {
248+ if (pools.putIfAbsent(host, newPool) != null) {
249+ return null;
250+ }
251+ } else {
252+ if (!pools.replace(host, previous, newPool)) {
253+ return null;
254+ }
255+ if (!previous.isClosed()) {
273256 logger.warn("Replacing a pool that wasn't closed. Closing it now, but this was not expected.");
274257 previous.closeAsync();
275258 }
259+ }
276260
277- // If we raced with a session shutdown, ensure that the pool will be closed.
278- if (isClosing)
279- newPool.closeAsync();
261+ ListenableFuture<Void> poolInitFuture = newPool.initAsync();
262+
263+ Futures.addCallback(poolInitFuture, new FutureCallback<Void>() {
264+ @Override
265+ public void onSuccess(Void result) {
266+ // If we raced with a session shutdown, ensure that the pool will be closed.
267+ if (isClosing) {
268+ newPool.closeAsync();
269+ pools.remove(host);
270+ }
271+ }
280272
281- return true;
282- } finally {
283- l.unlock();
284- }
273+ @Override
274+ public void onFailure(Throwable t) {
275+ pools.remove(host);
276+ }
277+ });
278+ return poolInitFuture;
285279 }
286280
287281 // Returns whether there was problem creating the pool
288- ListenableFuture<Boolean> maybeAddPool(final Host host, ListeningExecutorService executor) {
282+ ListenableFuture<Boolean> maybeAddPool(final Host host) {
289283 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
290284 if (distance == HostDistance.IGNORED)
291285 return Futures.immediateFuture(true);
@@ -294,34 +288,39 @@
294288 if (previous != null && !previous.isClosed())
295289 return Futures.immediateFuture(true);
296290
297- // Creating a pool is somewhat long since it has to create the connection, so do it asynchronously.
298- return executor.submit(new Callable<Boolean>() {
299- public Boolean call() {
300- try {
301- while (true) {
302- HostConnectionPool previous = pools.get(host);
303- if (previous != null && !previous.isClosed())
304- return true;
305-
306- if (replacePool(host, distance, previous)) {
307- logger.debug("Added connection pool for {}", host);
308- return true;
291+ while (true) {
292+ previous = pools.get(host);
293+ if (previous != null && !previous.isClosed())
294+ return Futures.immediateFuture(true);
295+
296+ final SettableFuture<Boolean> future = SettableFuture.create();
297+ ListenableFuture<Void> newPoolInit = replacePool(host, distance, previous);
298+ if (newPoolInit != null) {
299+ Futures.addCallback(newPoolInit, new FutureCallback<Void>() {
300+ @Override
301+ public void onSuccess(Void result) {
302+ logger.debug("Added connection pool for {}", host);
303+ future.set(true);
304+ }
305+
306+ @Override
307+ public void onFailure(Throwable t) {
308+ if (t instanceof UnsupportedProtocolVersionException) {
309+ cluster.manager.logUnsupportedVersionProtocol(host);
310+ cluster.manager.triggerOnDown(host, false);
311+ } else if (t instanceof ClusterNameMismatchException) {
312+ ClusterNameMismatchException e = (ClusterNameMismatchException)t;
313+ cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
314+ cluster.manager.triggerOnDown(host, false);
315+ } else {
316+ logger.error("Error creating pool to " + host, t);
309317 }
318+ future.set(false);
310319 }
311- } catch (UnsupportedProtocolVersionException e) {
312- cluster.manager.logUnsupportedVersionProtocol(host);
313- cluster.manager.triggerOnDown(host, false);
314- return false;
315- } catch (ClusterNameMismatchException e) {
316- cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
317- cluster.manager.triggerOnDown(host, false);
318- return false;
319- } catch (Exception e) {
320- logger.error("Error creating pool to " + host, e);
321- return false;
322- }
320+ });
321+ return future;
323322 }
324- });
323+ }
325324 }
326325
327326 CloseFuture removePool(Host host) {
@@ -340,7 +339,7 @@
340339 * This method ensures that all hosts for which a pool should exist
341340 * have one, and hosts that shouldn't don't.
342341 */
343- void updateCreatedPools(ListeningExecutorService executor) {
342+ void updateCreatedPools() {
344343 // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if
345344 // we execute the code below we would try to create their pool over and over again.
346345 // It's called explicitly at the end of init(), once isInit has been set to true.
@@ -359,7 +358,7 @@
359358
360359 if (pool == null) {
361360 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
362- poolCreationFutures.add(maybeAddPool(h, executor));
361+ poolCreationFutures.add(maybeAddPool(h));
363362 } else if (dist != pool.hostDistance) {
364363 if (dist == HostDistance.IGNORED) {
365364 toRemove.add(h);
@@ -371,7 +370,12 @@
371370 }
372371
373372 // Wait pool creation before removing, so we don't lose connectivity
374- Futures.allAsList(poolCreationFutures).get();
373+ try {
374+ Futures.successfulAsList(poolCreationFutures).get();
375+ } catch (ExecutionException e) {
376+ // Won't happen because we used successfulAsList
377+ // And if a particular pool failed, maybeAddPool already handled it
378+ }
375379
376380 List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size());
377381 for (Host h : toRemove)
@@ -385,14 +389,18 @@
385389 }
386390 }
387391
388- void updateCreatedPools(Host h, ListeningExecutorService executor) {
392+ void updateCreatedPools(Host h) {
389393 HostDistance dist = loadBalancingPolicy().distance(h);
390394 HostConnectionPool pool = pools.get(h);
391395
392396 try {
393397 if (pool == null) {
394398 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
395- maybeAddPool(h, executor).get();
399+ try {
400+ maybeAddPool(h).get();
401+ } catch (ExecutionException e) {
402+ // Ignore, maybeAddPool has already handled the error
403+ }
396404 } else if (dist != pool.hostDistance) {
397405 if (dist == HostDistance.IGNORED) {
398406 removePool(h).get();
@@ -412,7 +420,7 @@
412420 // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary
413421 // since updateCreatedPools should take care of it. But better protect against non well behaving policies.
414422 removePool(host).force().get();
415- updateCreatedPools(MoreExecutors.sameThreadExecutor());
423+ updateCreatedPools();
416424 }
417425
418426 void onSuspected(Host host) {
added driver-core/src/main/java/com/datastax/driver/core/utils/MoreFutures.java +46 −0
@@ -0,0 +1,46 @@
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.google.common.util.concurrent.FutureCallback;
19+import com.google.common.util.concurrent.Futures;
20+import com.google.common.util.concurrent.ListenableFuture;
21+
22+/**
23+ * Helpers to work with Guava's {@link ListenableFuture}.
24+ */
25+public class MoreFutures {
26+ /**
27+ * An immediate successful {@code ListenableFuture<Void>}.
28+ */
29+ public static final ListenableFuture<Void> VOID_SUCCESS = Futures.immediateFuture(null);
30+
31+ /**
32+ * A {@link FutureCallback} that does nothing on failure.
33+ */
34+ public static abstract class SuccessCallback<V> implements FutureCallback<V> {
35+ @Override
36+ public void onFailure(Throwable t) { /* nothing */ }
37+ }
38+
39+ /**
40+ * A {@link FutureCallback} that does nothing on success.
41+ */
42+ public static abstract class FailureCallback<V> implements FutureCallback<V> {
43+ @Override
44+ public void onSuccess(V result) { /* nothing */ }
45+ }
46+}