kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | c470e10dc06cca87279e247a82e2a7cdd651ce18cb2ce78155d0e0f4f1887ad6 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-08-06 12:38 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-08-28 11:31 +02:00 |
| Parents | 9bd245c59c01 |
16 files changed
modified changelog/README.md +2 −0
| @@ -39,6 +39,8 @@ | ||
| 39 | 39 | - [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784) |
| 40 | 40 | - [new feature] Make driver-side metadata optional (JAVA-828) |
| 41 | 41 | - [improvement] Allow hosts to remain partially up (JAVA-544) |
| 42 | +- [improvement] Remove internal blocking calls and expose async session | |
| 43 | + creation (JAVA-821, JAVA-822) | |
| 42 | 44 | |
| 43 | 45 | Merged from 2.0.10_fixes branch: |
| 44 | 46 |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +4 −4
| @@ -26,7 +26,7 @@ | ||
| 26 | 26 | * |
| 27 | 27 | * This is primarly intended to make mocking easier. |
| 28 | 28 | */ |
| 29 | -public abstract class AbstractSession implements Session { | |
| 29 | +public abstract class AbstractSession implements Session, AsyncInitSession { | |
| 30 | 30 | |
| 31 | 31 | /** |
| 32 | 32 | * {@inheritDoc} |
| @@ -76,7 +76,7 @@ | ||
| 76 | 76 | try { |
| 77 | 77 | return Uninterruptibles.getUninterruptibly(prepareAsync(query)); |
| 78 | 78 | } catch (ExecutionException e) { |
| 79 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 79 | + throw DriverThrowables.propagateCause(e); | |
| 80 | 80 | } |
| 81 | 81 | } |
| 82 | 82 | |
| @@ -88,7 +88,7 @@ | ||
| 88 | 88 | try { |
| 89 | 89 | return Uninterruptibles.getUninterruptibly(prepareAsync(statement)); |
| 90 | 90 | } catch (ExecutionException e) { |
| 91 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 91 | + throw DriverThrowables.propagateCause(e); | |
| 92 | 92 | } |
| 93 | 93 | } |
| 94 | 94 | |
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | try { |
| 126 | 126 | closeAsync().get(); |
| 127 | 127 | } catch (ExecutionException e) { |
| 128 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 128 | + throw DriverThrowables.propagateCause(e); | |
| 129 | 129 | } catch (InterruptedException e) { |
| 130 | 130 | Thread.currentThread().interrupt(); |
| 131 | 131 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
| @@ -276,7 +276,7 @@ | ||
| 276 | 276 | try { |
| 277 | 277 | Uninterruptibles.getUninterruptibly(fetchMoreResults()); |
| 278 | 278 | } catch (ExecutionException e) { |
| 279 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 279 | + throw DriverThrowables.propagateCause(e); | |
| 280 | 280 | } |
| 281 | 281 | } |
| 282 | 282 | } |
added driver-core/src/main/java/com/datastax/driver/core/AsyncInitSession.java +36 −0
| @@ -0,0 +1,36 @@ | ||
| 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.google.common.util.concurrent.ListenableFuture; | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * A {@link Session} that can be initialized asynchronously. | |
| 22 | + * | |
| 23 | + * This interface exists only for backward compatibility reasons: {@link #initAsync()} should really be | |
| 24 | + * defined by {@link Session}, but adding it after the fact would break binary compatibility. | |
| 25 | + * | |
| 26 | + * By default, all sessions returned by the driver implement this interface. The only way you would get | |
| 27 | + * sessions that don't is if you use a custom {@link Cluster} subclass. | |
| 28 | + */ | |
| 29 | +public interface AsyncInitSession extends Session { | |
| 30 | + /** | |
| 31 | + * Initialize this session asynchronously. | |
| 32 | + * | |
| 33 | + * @return a future that will complete when the session is fully initialized. | |
| 34 | + */ | |
| 35 | + ListenableFuture<Session> initAsync(); | |
| 36 | +} |
added driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java +75 −0
| @@ -0,0 +1,75 @@ | ||
| 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 java.util.concurrent.ExecutionException; | |
| 19 | +import java.util.concurrent.TimeUnit; | |
| 20 | +import java.util.concurrent.TimeoutException; | |
| 21 | + | |
| 22 | +import com.google.common.util.concurrent.AbstractFuture; | |
| 23 | +import com.google.common.util.concurrent.FutureCallback; | |
| 24 | +import com.google.common.util.concurrent.Futures; | |
| 25 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 26 | + | |
| 27 | +/** | |
| 28 | + * A {@code ResultSetFuture} that will complete when its source future completes. | |
| 29 | + */ | |
| 30 | +class ChainedResultSetFuture extends AbstractFuture<ResultSet> implements ResultSetFuture { | |
| 31 | + | |
| 32 | + private volatile ResultSetFuture source; | |
| 33 | + | |
| 34 | + void setSource(ResultSetFuture source) { | |
| 35 | + if (this.isCancelled()) | |
| 36 | + source.cancel(false); | |
| 37 | + this.source = source; | |
| 38 | + Futures.addCallback(source, new FutureCallback<ResultSet>() { | |
| 39 | + @Override | |
| 40 | + public void onSuccess(ResultSet result) { | |
| 41 | + ChainedResultSetFuture.this.set(result); | |
| 42 | + } | |
| 43 | + | |
| 44 | + @Override | |
| 45 | + public void onFailure(Throwable t) { | |
| 46 | + ChainedResultSetFuture.this.setException(t); | |
| 47 | + } | |
| 48 | + }); | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Override | |
| 52 | + public boolean cancel(boolean mayInterruptIfRunning) { | |
| 53 | + return (source == null || source.cancel(mayInterruptIfRunning)) | |
| 54 | + && super.cancel(mayInterruptIfRunning); | |
| 55 | + } | |
| 56 | + | |
| 57 | + @Override | |
| 58 | + public ResultSet getUninterruptibly() { | |
| 59 | + try { | |
| 60 | + return Uninterruptibles.getUninterruptibly(this); | |
| 61 | + } catch (ExecutionException e) { | |
| 62 | + throw DriverThrowables.propagateCause(e); | |
| 63 | + } | |
| 64 | + } | |
| 65 | + | |
| 66 | + @Override | |
| 67 | + public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException { | |
| 68 | + try { | |
| 69 | + return Uninterruptibles.getUninterruptibly(this, timeout, unit); | |
| 70 | + } catch (ExecutionException e) { | |
| 71 | + throw DriverThrowables.propagateCause(e); | |
| 72 | + } | |
| 73 | + } | |
| 74 | +} | |
| 75 | + |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +76 −29
| @@ -28,6 +28,7 @@ | ||
| 28 | 28 | import com.google.common.annotations.VisibleForTesting; |
| 29 | 29 | import com.google.common.base.Objects; |
| 30 | 30 | import com.google.common.base.Predicates; |
| 31 | +import com.google.common.base.Throwables; | |
| 31 | 32 | import com.google.common.collect.*; |
| 32 | 33 | import com.google.common.util.concurrent.*; |
| 33 | 34 | import org.slf4j.Logger; |
| @@ -220,7 +221,7 @@ | ||
| 220 | 221 | */ |
| 221 | 222 | public Session newSession() { |
| 222 | 223 | checkNotClosed(manager); |
| 223 | - return manager.newSession(); | |
| 224 | + return manager.newSession(null); | |
| 224 | 225 | } |
| 225 | 226 | |
| 226 | 227 | /** |
| @@ -244,11 +245,11 @@ | ||
| 244 | 245 | * Cluster. |
| 245 | 246 | */ |
| 246 | 247 | public Session connect() { |
| 247 | - checkNotClosed(manager); | |
| 248 | - init(); | |
| 249 | - Session session = manager.newSession(); | |
| 250 | - session.init(); | |
| 251 | - return session; | |
| 248 | + try { | |
| 249 | + return Uninterruptibles.getUninterruptibly(connectAsync()); | |
| 250 | + } catch (ExecutionException e) { | |
| 251 | + throw DriverThrowables.propagateCause(e); | |
| 252 | + } | |
| 252 | 253 | } |
| 253 | 254 | |
| 254 | 255 | /** |
| @@ -277,25 +278,67 @@ | ||
| 277 | 278 | * Cluster. |
| 278 | 279 | */ |
| 279 | 280 | public Session connect(String keyspace) { |
| 280 | - long timeout = getConfiguration().getSocketOptions().getConnectTimeoutMillis(); | |
| 281 | - Session session = connect(); | |
| 282 | 281 | try { |
| 283 | - try { | |
| 284 | - ResultSetFuture future = session.executeAsync("USE " + keyspace); | |
| 285 | - // Note: using the connection timeout isn't perfectly correct, we should probably change that someday | |
| 286 | - Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); | |
| 287 | - return session; | |
| 288 | - } catch (TimeoutException e) { | |
| 289 | - throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout)); | |
| 290 | - } catch (ExecutionException e) { | |
| 291 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 292 | - } | |
| 293 | - } catch (RuntimeException e) { | |
| 294 | - session.close(); | |
| 295 | - throw e; | |
| 282 | + return Uninterruptibles.getUninterruptibly(connectAsync(keyspace)); | |
| 283 | + } catch (ExecutionException e) { | |
| 284 | + throw DriverThrowables.propagateCause(e); | |
| 296 | 285 | } |
| 297 | 286 | } |
| 298 | 287 | |
| 288 | + /** | |
| 289 | + * Creates a new session on this cluster and initializes it asynchronously. | |
| 290 | + * | |
| 291 | + * This will also initialize the {@code Cluster} if needed; note that cluster | |
| 292 | + * initialization happens synchronously on the thread that called this method. | |
| 293 | + * Therefore it is recommended to initialize the cluster at application | |
| 294 | + * startup, and not rely on this method to do it. | |
| 295 | + * | |
| 296 | + * @return a future that will complete when the session is fully initialized. | |
| 297 | + * | |
| 298 | + * @throws NoHostAvailableException if the Cluster has not been initialized | |
| 299 | + * yet ({@link #init} has not been called and this is the first connect call) | |
| 300 | + * and no host amongst the contact points can be reached. | |
| 301 | + * | |
| 302 | + * @throws IllegalStateException if the Cluster was closed prior to calling | |
| 303 | + * this method. This can occur either directly (through {@link #close()} or | |
| 304 | + * {@link #closeAsync()}), or as a result of an error while initializing the | |
| 305 | + * Cluster. | |
| 306 | + * | |
| 307 | + * @see #connect() | |
| 308 | + */ | |
| 309 | + public ListenableFuture<Session> connectAsync() { | |
| 310 | + return connectAsync(null); | |
| 311 | + } | |
| 312 | + | |
| 313 | + /** | |
| 314 | + * Creates a new session on this cluster, and initializes it to the given | |
| 315 | + * keyspace asynchronously. | |
| 316 | + * | |
| 317 | + * This will also initialize the {@code Cluster} if needed; note that cluster | |
| 318 | + * initialization happens synchronously on the thread that called this method. | |
| 319 | + * Therefore it is recommended to initialize the cluster at application | |
| 320 | + * startup, and not rely on this method to do it. | |
| 321 | + * | |
| 322 | + * @param keyspace The name of the keyspace to use for the created | |
| 323 | + * {@code Session}. | |
| 324 | + * @return a future that will complete when the session is fully initialized. | |
| 325 | + * | |
| 326 | + * @throws NoHostAvailableException if the Cluster has not been initialized | |
| 327 | + * yet ({@link #init} has not been called and this is the first connect call) | |
| 328 | + * and no host amongst the contact points can be reached. | |
| 329 | + * | |
| 330 | + * @throws IllegalStateException if the Cluster was closed prior to calling | |
| 331 | + * this method. This can occur either directly (through {@link #close()} or | |
| 332 | + * {@link #closeAsync()}), or as a result of an error while initializing the | |
| 333 | + * Cluster. | |
| 334 | + */ | |
| 335 | + public ListenableFuture<Session> connectAsync(String keyspace) { | |
| 336 | + checkNotClosed(manager); | |
| 337 | + init(); | |
| 338 | + AsyncInitSession session = manager.newSession(keyspace); | |
| 339 | + return session.initAsync(); | |
| 340 | + } | |
| 341 | + | |
| 299 | 342 | /** |
| 300 | 343 | * The name of this cluster object. |
| 301 | 344 | * <p> |
| @@ -500,7 +543,7 @@ | ||
| 500 | 543 | try { |
| 501 | 544 | closeAsync().get(); |
| 502 | 545 | } catch (ExecutionException e) { |
| 503 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 546 | + throw DriverThrowables.propagateCause(e); | |
| 504 | 547 | } catch (InterruptedException e) { |
| 505 | 548 | Thread.currentThread().interrupt(); |
| 506 | 549 | } |
| @@ -1444,8 +1487,8 @@ | ||
| 1444 | 1487 | return translated == null ? sa : translated; |
| 1445 | 1488 | } |
| 1446 | 1489 | |
| 1447 | - private Session newSession() { | |
| 1448 | - SessionManager session = new SessionManager(Cluster.this); | |
| 1490 | + private AsyncInitSession newSession(String keyspace) { | |
| 1491 | + SessionManager session = new SessionManager(Cluster.this, keyspace); | |
| 1449 | 1492 | sessions.add(session); |
| 1450 | 1493 | return session; |
| 1451 | 1494 | } |
| @@ -1643,7 +1686,7 @@ | ||
| 1643 | 1686 | // Now, check if there isn't pools to create/remove following the addition. |
| 1644 | 1687 | // We do that now only so that it's not called before we've set the node up. |
| 1645 | 1688 | for (SessionManager s : sessions) |
| 1646 | - s.updateCreatedPools(); | |
| 1689 | + s.updateCreatedPools().get(); | |
| 1647 | 1690 | |
| 1648 | 1691 | } finally { |
| 1649 | 1692 | host.notificationsLock.unlock(); |
| @@ -1882,7 +1925,7 @@ | ||
| 1882 | 1925 | |
| 1883 | 1926 | List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); |
| 1884 | 1927 | for (SessionManager s : sessions) |
| 1885 | - futures.add(s.maybeAddPool(host, reusedConnection)); | |
| 1928 | + futures.add(s.maybeAddPool(host, reusedConnection, false)); | |
| 1886 | 1929 | |
| 1887 | 1930 | try { |
| 1888 | 1931 | // Only mark the node up once all session have added their pool (if the load-balancing |
| @@ -1912,7 +1955,7 @@ | ||
| 1912 | 1955 | // Now, check if there isn't pools to create/remove following the addition. |
| 1913 | 1956 | // We do that now only so that it's not called before we've set the node up. |
| 1914 | 1957 | for (SessionManager s : sessions) |
| 1915 | - s.updateCreatedPools(); | |
| 1958 | + s.updateCreatedPools().get(); | |
| 1916 | 1959 | |
| 1917 | 1960 | } finally { |
| 1918 | 1961 | host.notificationsLock.unlock(); |
| @@ -2260,8 +2303,12 @@ | ||
| 2260 | 2303 | if (ccHost == null || loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL) |
| 2261 | 2304 | controlConnection.triggerReconnect(); |
| 2262 | 2305 | |
| 2263 | - for (SessionManager s : sessions) | |
| 2264 | - s.updateCreatedPools(); | |
| 2306 | + try { | |
| 2307 | + for (SessionManager s : sessions) | |
| 2308 | + Uninterruptibles.getUninterruptibly(s.updateCreatedPools()); | |
| 2309 | + } catch (ExecutionException e) { | |
| 2310 | + throw DriverThrowables.propagateCause(e); | |
| 2311 | + } | |
| 2265 | 2312 | } |
| 2266 | 2313 | |
| 2267 | 2314 | void refreshConnectedHost(Host host) { |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +40 −25
| @@ -35,7 +35,6 @@ | ||
| 35 | 35 | import io.netty.handler.ssl.SslHandler; |
| 36 | 36 | import io.netty.handler.timeout.IdleStateEvent; |
| 37 | 37 | import io.netty.handler.timeout.IdleStateHandler; |
| 38 | -import io.netty.util.HashedWheelTimer; | |
| 39 | 38 | import io.netty.util.Timeout; |
| 40 | 39 | import io.netty.util.Timer; |
| 41 | 40 | import io.netty.util.TimerTask; |
| @@ -48,8 +47,13 @@ | ||
| 48 | 47 | |
| 49 | 48 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 50 | 49 | import com.datastax.driver.core.exceptions.DriverException; |
| 50 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 51 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 51 | 52 | import com.datastax.driver.core.utils.MoreFutures; |
| 52 | 53 | |
| 54 | +import static com.datastax.driver.core.Message.Response.Type.ERROR; | |
| 55 | +import static com.datastax.driver.core.Message.Response.Type.RESULT; | |
| 56 | + | |
| 53 | 57 | // For LoggingHandler |
| 54 | 58 | //import org.jboss.netty.handler.logging.LoggingHandler; |
| 55 | 59 | //import org.jboss.netty.logging.InternalLogLevel; |
| @@ -175,8 +179,8 @@ | ||
| 175 | 179 | public ListenableFuture<Void> create(Throwable t) throws Exception { |
| 176 | 180 | SettableFuture<Void> future = SettableFuture.create(); |
| 177 | 181 | // Make sure the connection gets properly closed. |
| 178 | - if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) { | |
| 179 | - // These exceptions cause the node to be ignored, so just propagate | |
| 182 | + if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException || t instanceof SetKeyspaceException) { | |
| 183 | + // Just propagate | |
| 180 | 184 | closeAsync().force(); |
| 181 | 185 | future.setException(t); |
| 182 | 186 | } else { |
| @@ -197,7 +201,7 @@ | ||
| 197 | 201 | @Override |
| 198 | 202 | public void onSuccess(Void result) { |
| 199 | 203 | Host host = factory.manager.metadata.getHost(address); |
| 200 | - if(host != null) | |
| 204 | + if (host != null) | |
| 201 | 205 | host.convictionPolicy.signalConnectionCreated(); |
| 202 | 206 | isInitialized = true; |
| 203 | 207 | } |
| @@ -435,28 +439,11 @@ | ||
| 435 | 439 | if (this.keyspace != null && this.keyspace.equals(keyspace)) |
| 436 | 440 | return; |
| 437 | 441 | |
| 438 | - Future future = null; | |
| 442 | + ListenableFuture<Void> future = null; | |
| 439 | 443 | try { |
| 440 | - logger.trace("{} Setting keyspace {}", this, keyspace); | |
| 441 | 444 | long timeout = factory.getConnectTimeoutMillis(); |
| 442 | - // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already | |
| 443 | - future = write(new Requests.Query("USE \"" + keyspace + '"')); | |
| 444 | - Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); | |
| 445 | - switch (response.type) { | |
| 446 | - case RESULT: | |
| 447 | - this.keyspace = keyspace; | |
| 448 | - break; | |
| 449 | - default: | |
| 450 | - // The code set the keyspace only when a successful 'use' | |
| 451 | - // has been perform, so there shouldn't be any error here. | |
| 452 | - // It can happen however that the node we're connecting to | |
| 453 | - // is not up on the schema yet. In that case, defuncting | |
| 454 | - // the connection is not a bad choice. | |
| 455 | - String message = String.format("Problem while setting keyspace, got %s as response", response); | |
| 456 | - logger.warn("{} {}", this, message); | |
| 457 | - defunct(new ConnectionException(address, message)); | |
| 458 | - break; | |
| 459 | - } | |
| 445 | + future = setKeyspaceAsync(keyspace); | |
| 446 | + Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); | |
| 460 | 447 | } catch (ConnectionException e) { |
| 461 | 448 | throw defunct(e); |
| 462 | 449 | } catch (TimeoutException e) { |
| @@ -471,10 +458,38 @@ | ||
| 471 | 458 | logger.warn(String.format("Tried to set the keyspace on busy connection to %s. This should not happen but is not critical (it will retried)", address)); |
| 472 | 459 | throw new ConnectionException(address, "Tried to set the keyspace on busy connection"); |
| 473 | 460 | } catch (ExecutionException e) { |
| 474 | - throw defunct(new ConnectionException(address, "Error while setting keyspace", e)); | |
| 461 | + throw defunct(new ConnectionException(address, "Error while setting keyspace", e.getCause())); | |
| 475 | 462 | } |
| 476 | 463 | } |
| 477 | 464 | |
| 465 | + ListenableFuture<Void> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException { | |
| 466 | + logger.trace("{} Setting keyspace {}", this, keyspace); | |
| 467 | + // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already | |
| 468 | + Future future = write(new Requests.Query("USE \"" + keyspace + '"')); | |
| 469 | + return Futures.transform(future, new AsyncFunction<Message.Response, Void>() { | |
| 470 | + @Override | |
| 471 | + public ListenableFuture<Void> apply(Message.Response response) throws Exception { | |
| 472 | + if (response.type == RESULT) { | |
| 473 | + Connection.this.keyspace = keyspace; | |
| 474 | + return MoreFutures.VOID_SUCCESS; | |
| 475 | + } else if (response.type == ERROR) { | |
| 476 | + closeAsync().force(); | |
| 477 | + Responses.Error error = (Responses.Error)response; | |
| 478 | + Exception e = error.asException(address); | |
| 479 | + if (e instanceof InvalidQueryException) { | |
| 480 | + // Most likely means that the keyspace name is wrong. Wrap that in a specific exception, because we want | |
| 481 | + // to treat it specially in case of a Session init. | |
| 482 | + e = new SetKeyspaceException(e); | |
| 483 | + } | |
| 484 | + throw e; | |
| 485 | + } else { | |
| 486 | + closeAsync().force(); | |
| 487 | + throw new DriverInternalError("Unexpected response while setting keyspace: " + response); | |
| 488 | + } | |
| 489 | + } | |
| 490 | + }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor()); | |
| 491 | + } | |
| 492 | + | |
| 478 | 493 | /** |
| 479 | 494 | * Write a request on this connection. |
| 480 | 495 | * |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +2 −14
| @@ -198,7 +198,7 @@ | ||
| 198 | 198 | try { |
| 199 | 199 | return Uninterruptibles.getUninterruptibly(this); |
| 200 | 200 | } catch (ExecutionException e) { |
| 201 | - throw extractCauseFromExecutionException(e); | |
| 201 | + throw DriverThrowables.propagateCause(e); | |
| 202 | 202 | } |
| 203 | 203 | } |
| 204 | 204 | |
| @@ -230,7 +230,7 @@ | ||
| 230 | 230 | try { |
| 231 | 231 | return Uninterruptibles.getUninterruptibly(this, timeout, unit); |
| 232 | 232 | } catch (ExecutionException e) { |
| 233 | - throw extractCauseFromExecutionException(e); | |
| 233 | + throw DriverThrowables.propagateCause(e); | |
| 234 | 234 | } |
| 235 | 235 | } |
| 236 | 236 | |
| @@ -277,18 +277,6 @@ | ||
| 277 | 277 | return true; |
| 278 | 278 | } |
| 279 | 279 | |
| 280 | - static RuntimeException extractCauseFromExecutionException(ExecutionException e) { | |
| 281 | - // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been | |
| 282 | - // created on the I/O thread receiving the response. Which means that the stacktrace associated | |
| 283 | - // with said cause will make no mention of the current thread. This is painful for say, finding | |
| 284 | - // out which execute() statement actually raised the exception. So instead, we re-create the | |
| 285 | - // exception. | |
| 286 | - if (e.getCause() instanceof DriverException) | |
| 287 | - throw ((DriverException)e.getCause()).copy(); | |
| 288 | - else | |
| 289 | - throw new DriverInternalError("Unexpected exception thrown", e.getCause()); | |
| 290 | - } | |
| 291 | - | |
| 292 | 280 | @Override |
| 293 | 281 | public int retryCount() { |
| 294 | 282 | // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler). |
modified driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java +12 −0
| @@ -18,6 +18,8 @@ | ||
| 18 | 18 | import java.net.InetSocketAddress; |
| 19 | 19 | import java.util.Collections; |
| 20 | 20 | |
| 21 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 22 | + | |
| 21 | 23 | /** |
| 22 | 24 | * Base class for custom {@link Cluster} implementations that wrap another instance (delegate / decorator pattern). |
| 23 | 25 | */ |
| @@ -74,6 +76,16 @@ | ||
| 74 | 76 | return delegate().connect(keyspace); |
| 75 | 77 | } |
| 76 | 78 | |
| 79 | + @Override | |
| 80 | + public ListenableFuture<Session> connectAsync() { | |
| 81 | + return delegate().connectAsync(); | |
| 82 | + } | |
| 83 | + | |
| 84 | + @Override | |
| 85 | + public ListenableFuture<Session> connectAsync(String keyspace) { | |
| 86 | + return delegate().connectAsync(keyspace); | |
| 87 | + } | |
| 88 | + | |
| 77 | 89 | @Override |
| 78 | 90 | public Metadata getMetadata() { |
| 79 | 91 | return delegate().getMetadata(); |
added driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java +41 −0
| @@ -0,0 +1,41 @@ | ||
| 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 java.util.concurrent.ExecutionException; | |
| 19 | + | |
| 20 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 21 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 22 | + | |
| 23 | +class DriverThrowables { | |
| 24 | + | |
| 25 | + static RuntimeException propagateCause(ExecutionException e) { | |
| 26 | + Throwable cause = e.getCause(); | |
| 27 | + | |
| 28 | + if (cause instanceof Error) | |
| 29 | + throw ((Error)cause); | |
| 30 | + | |
| 31 | + // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been | |
| 32 | + // created on the I/O thread receiving the response. Which means that the stacktrace associated | |
| 33 | + // with said cause will make no mention of the current thread. This is painful for say, finding | |
| 34 | + // out which execute() statement actually raised the exception. So instead, we re-create the | |
| 35 | + // exception. | |
| 36 | + if (cause instanceof DriverException) | |
| 37 | + throw ((DriverException)cause).copy(); | |
| 38 | + else | |
| 39 | + throw new DriverInternalError("Unexpected exception thrown", cause); | |
| 40 | + } | |
| 41 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +53 −11
| @@ -26,11 +26,9 @@ | ||
| 26 | 26 | import java.util.concurrent.locks.Lock; |
| 27 | 27 | import java.util.concurrent.locks.ReentrantLock; |
| 28 | 28 | |
| 29 | +import com.google.common.base.Throwables; | |
| 29 | 30 | import com.google.common.collect.Lists; |
| 30 | -import com.google.common.util.concurrent.Futures; | |
| 31 | -import com.google.common.util.concurrent.ListenableFuture; | |
| 32 | -import com.google.common.util.concurrent.MoreExecutors; | |
| 33 | -import com.google.common.util.concurrent.SettableFuture; | |
| 31 | +import com.google.common.util.concurrent.*; | |
| 34 | 32 | import org.slf4j.Logger; |
| 35 | 33 | import org.slf4j.LoggerFactory; |
| 36 | 34 | |
| @@ -102,6 +100,10 @@ | ||
| 102 | 100 | * pool. |
| 103 | 101 | */ |
| 104 | 102 | public ListenableFuture<Void> initAsync(Connection reusedConnection) { |
| 103 | + String keyspace = manager.poolsState.keyspace; | |
| 104 | + | |
| 105 | + Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 106 | + | |
| 105 | 107 | // Create initial core connections |
| 106 | 108 | final int coreSize = options().getCoreConnectionsPerHost(hostDistance); |
| 107 | 109 | final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize); |
| @@ -119,15 +121,13 @@ | ||
| 119 | 121 | } |
| 120 | 122 | reusedConnection = null; |
| 121 | 123 | connections.add(connection); |
| 122 | - connectionFutures.add(connectionFuture); | |
| 124 | + connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor)); | |
| 123 | 125 | } |
| 124 | 126 | |
| 125 | - Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 126 | - | |
| 127 | - ListenableFuture<List<Void>> allConnectionsFuture = Futures.successfulAsList(connectionFutures); | |
| 127 | + ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures); | |
| 128 | 128 | |
| 129 | 129 | final SettableFuture<Void> initFuture = SettableFuture.create(); |
| 130 | - Futures.addCallback(allConnectionsFuture, new MoreFutures.SuccessCallback<List<Void>>() { | |
| 130 | + Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() { | |
| 131 | 131 | @Override |
| 132 | 132 | public void onSuccess(List<Void> l) { |
| 133 | 133 | // Some of the connections might have failed, keep only the successful ones |
| @@ -151,11 +151,48 @@ | ||
| 151 | 151 | initFuture.set(null); |
| 152 | 152 | } |
| 153 | 153 | } |
| 154 | + | |
| 155 | + @Override | |
| 156 | + public void onFailure(Throwable t) { | |
| 157 | + phase.compareAndSet(Phase.INITIALIZING, Phase.INIT_FAILED); | |
| 158 | + forceClose(connections); | |
| 159 | + initFuture.setException(t); | |
| 160 | + } | |
| 154 | 161 | }, initExecutor); |
| 155 | 162 | return initFuture; |
| 156 | 163 | } |
| 157 | 164 | |
| 158 | - // Clean up if we got an error at construction time but still created part of the core connections | |
| 165 | + private ListenableFuture<Void> handleErrors(ListenableFuture<Void> connectionInitFuture, Executor executor) { | |
| 166 | + return Futures.withFallback(connectionInitFuture, new FutureFallback<Void>() { | |
| 167 | + @Override | |
| 168 | + public ListenableFuture<Void> create(Throwable t) throws Exception { | |
| 169 | + // Propagate these exceptions because they mean no connection will ever succeed. They will be handled | |
| 170 | + // accordingly in SessionManager#maybeAddPool. | |
| 171 | + Throwables.propagateIfInstanceOf(t, ClusterNameMismatchException.class); | |
| 172 | + Throwables.propagateIfInstanceOf(t, UnsupportedProtocolVersionException.class); | |
| 173 | + Throwables.propagateIfInstanceOf(t, SetKeyspaceException.class); | |
| 174 | + | |
| 175 | + // We don't want to swallow Errors either as they probably indicate a more serious issue (OOME...) | |
| 176 | + Throwables.propagateIfInstanceOf(t, Error.class); | |
| 177 | + | |
| 178 | + // Otherwise, return success. The pool will simply ignore this connection when it sees that it's been closed. | |
| 179 | + return MoreFutures.VOID_SUCCESS; | |
| 180 | + } | |
| 181 | + }, executor); | |
| 182 | + } | |
| 183 | + | |
| 184 | + private ListenableFuture<Void> setKeyspaceAsync(ListenableFuture<Void> initFuture, final Connection connection, final String keyspace) { | |
| 185 | + return (keyspace == null) | |
| 186 | + ? initFuture | |
| 187 | + : Futures.transform(initFuture, new AsyncFunction<Void, Void>() { | |
| 188 | + @Override | |
| 189 | + public ListenableFuture<Void> apply(Void input) throws Exception { | |
| 190 | + return connection.setKeyspaceAsync(keyspace); | |
| 191 | + } | |
| 192 | + }); | |
| 193 | + } | |
| 194 | + | |
| 195 | + // Clean up if we got a fatal error at construction time but still created part of the core connections | |
| 159 | 196 | private void forceClose(List<Connection> connections) { |
| 160 | 197 | for (Connection connection : connections) { |
| 161 | 198 | connection.closeAsync().force(); |
| @@ -423,6 +460,7 @@ | ||
| 423 | 460 | } |
| 424 | 461 | logger.debug("Creating new connection on busy pool to {}", host); |
| 425 | 462 | newConnection = manager.connectionFactory().open(this); |
| 463 | + newConnection.setKeyspace(manager.poolsState.keyspace); | |
| 426 | 464 | } |
| 427 | 465 | connections.add(newConnection); |
| 428 | 466 | |
| @@ -644,7 +682,11 @@ | ||
| 644 | 682 | |
| 645 | 683 | volatile String keyspace; |
| 646 | 684 | |
| 647 | - public void setKeyspace(String keyspace) { | |
| 685 | + PoolState(String keyspace) { | |
| 686 | + this.keyspace = keyspace; | |
| 687 | + } | |
| 688 | + | |
| 689 | + void setKeyspace(String keyspace) { | |
| 648 | 690 | this.keyspace = keyspace; |
| 649 | 691 | } |
| 650 | 692 | } |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +4 −0
| @@ -385,6 +385,10 @@ | ||
| 385 | 385 | * Requests the driver to re-evaluate the {@link HostDistance} (through the configured |
| 386 | 386 | * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known |
| 387 | 387 | * hosts and to drop/add connections to each hosts according to the computed distance. |
| 388 | + * <p> | |
| 389 | + * Note that, due to backward compatibility issues, this method is not interruptible. If the | |
| 390 | + * caller thread gets interrupted, the method will complete and only then re-interrupt the | |
| 391 | + * thread (which you can check with {@code Thread.currentThread().isInterrupted()}). | |
| 388 | 392 | */ |
| 389 | 393 | public void refreshConnectedHosts() { |
| 390 | 394 | manager.refreshConnectedHosts(); |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +117 −72
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | import java.util.concurrent.atomic.AtomicReference; |
| 23 | 23 | |
| 24 | 24 | import com.google.common.base.Function; |
| 25 | +import com.google.common.base.Throwables; | |
| 25 | 26 | import com.google.common.collect.ImmutableList; |
| 26 | 27 | import com.google.common.collect.Lists; |
| 27 | 28 | import com.google.common.util.concurrent.*; |
| @@ -46,55 +47,98 @@ | ||
| 46 | 47 | final Cluster cluster; |
| 47 | 48 | final ConcurrentMap<Host, HostConnectionPool> pools; |
| 48 | 49 | final HostConnectionPool.PoolState poolsState; |
| 50 | + private final AtomicReference<ListenableFuture<Session>> initFuture = new AtomicReference<ListenableFuture<Session>>(); | |
| 49 | 51 | final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); |
| 50 | 52 | |
| 51 | 53 | private volatile boolean isInit; |
| 52 | 54 | private volatile boolean isClosing; |
| 53 | 55 | |
| 54 | 56 | // Package protected, only Cluster should construct that. |
| 55 | - SessionManager(Cluster cluster) { | |
| 57 | + SessionManager(Cluster cluster, String keyspace) { | |
| 56 | 58 | this.cluster = cluster; |
| 57 | 59 | this.pools = new ConcurrentHashMap<Host, HostConnectionPool>(); |
| 58 | - this.poolsState = new HostConnectionPool.PoolState(); | |
| 60 | + this.poolsState = new HostConnectionPool.PoolState(keyspace); | |
| 59 | 61 | } |
| 60 | 62 | |
| 61 | - public synchronized Session init() { | |
| 62 | - if (isInit) | |
| 63 | - return this; | |
| 63 | + public Session init() { | |
| 64 | + try { | |
| 65 | + return Uninterruptibles.getUninterruptibly(initAsync()); | |
| 66 | + } catch (ExecutionException e) { | |
| 67 | + throw DriverThrowables.propagateCause(e); | |
| 68 | + } | |
| 69 | + } | |
| 64 | 70 | |
| 71 | + public ListenableFuture<Session> initAsync() { | |
| 65 | 72 | // If we haven't initialized the cluster, do it now |
| 66 | 73 | cluster.init(); |
| 67 | 74 | |
| 68 | - // Create pools to initial nodes (and wait for them to be created) | |
| 75 | + ListenableFuture<Session> existing = initFuture.get(); | |
| 76 | + if (existing != null) | |
| 77 | + return existing; | |
| 78 | + | |
| 79 | + final SettableFuture<Session> myInitFuture = SettableFuture.create(); | |
| 80 | + if (!initFuture.compareAndSet(null, myInitFuture)) | |
| 81 | + return initFuture.get(); | |
| 82 | + | |
| 69 | 83 | Collection<Host> hosts = cluster.getMetadata().allHosts(); |
| 70 | - createPoolsInParallel(hosts); | |
| 71 | - | |
| 72 | - isInit = true; | |
| 73 | - updateCreatedPools(); | |
| 74 | - return this; | |
| 84 | + ListenableFuture<?> allPoolsCreatedFuture = createPools(hosts); | |
| 85 | + ListenableFuture<?> allPoolsUpdatedFuture = Futures.transform(allPoolsCreatedFuture, | |
| 86 | + new AsyncFunction<Object, Object>() { | |
| 87 | + @Override | |
| 88 | + @SuppressWarnings("unchecked") | |
| 89 | + public ListenableFuture<Object> apply(Object input) throws Exception { | |
| 90 | + isInit = true; | |
| 91 | + return (ListenableFuture<Object>)updateCreatedPools(); | |
| 92 | + } | |
| 93 | + }); | |
| 94 | + | |
| 95 | + Futures.addCallback(allPoolsUpdatedFuture, new FutureCallback<Object>() { | |
| 96 | + @Override | |
| 97 | + public void onSuccess(Object result) { | |
| 98 | + myInitFuture.set(SessionManager.this); | |
| 99 | + } | |
| 100 | + | |
| 101 | + @Override | |
| 102 | + public void onFailure(Throwable t) { | |
| 103 | + SessionManager.this.closeAsync(); // don't leak the session | |
| 104 | + myInitFuture.setException(t); | |
| 105 | + } | |
| 106 | + }); | |
| 107 | + return myInitFuture; | |
| 75 | 108 | } |
| 76 | 109 | |
| 77 | - private void createPoolsInParallel(Collection<Host> hosts) { | |
| 110 | + private ListenableFuture<?> createPools(Collection<Host> hosts) { | |
| 78 | 111 | List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size()); |
| 79 | 112 | for (Host host : hosts) |
| 80 | 113 | if (host.state != Host.State.DOWN) |
| 81 | - futures.add(maybeAddPool(host, null)); | |
| 82 | - try { | |
| 83 | - Futures.successfulAsList(futures).get(); | |
| 84 | - } catch (ExecutionException e) { | |
| 85 | - // Won't happen because we used successfulAsList | |
| 86 | - // And if a particular pool failed, maybeAddPool already handled it | |
| 87 | - } catch (InterruptedException e) { | |
| 88 | - Thread.currentThread().interrupt(); | |
| 89 | - } | |
| 114 | + futures.add(maybeAddPool(host, null, true)); | |
| 115 | + return Futures.allAsList(futures); | |
| 90 | 116 | } |
| 91 | 117 | |
| 92 | 118 | public String getLoggedKeyspace() { |
| 93 | 119 | return poolsState.keyspace; |
| 94 | 120 | } |
| 95 | 121 | |
| 96 | - public ResultSetFuture executeAsync(Statement statement) { | |
| 97 | - return executeQuery(makeRequestMessage(statement, null), statement); | |
| 122 | + public ResultSetFuture executeAsync(final Statement statement) { | |
| 123 | + if (isInit) { | |
| 124 | + DefaultResultSetFuture future = new DefaultResultSetFuture(this, makeRequestMessage(statement, null)); | |
| 125 | + new RequestHandler(this, future, statement).sendRequest(); | |
| 126 | + return future; | |
| 127 | + } else { | |
| 128 | + // If the session is not initialized, we can't call makeRequestMessage() synchronously, because it | |
| 129 | + // requires internal Cluster state that might not be initialized yet (like the protocol version). | |
| 130 | + // Because of the way the future is built, we need another 'proxy' future that we can return now. | |
| 131 | + final ChainedResultSetFuture chainedFuture = new ChainedResultSetFuture(); | |
| 132 | + this.initAsync().addListener(new Runnable() { | |
| 133 | + @Override | |
| 134 | + public void run() { | |
| 135 | + DefaultResultSetFuture actualFuture = new DefaultResultSetFuture(SessionManager.this, makeRequestMessage(statement, null)); | |
| 136 | + execute(actualFuture, statement); | |
| 137 | + chainedFuture.setSource(actualFuture); | |
| 138 | + } | |
| 139 | + }, executor()); | |
| 140 | + return chainedFuture; | |
| 141 | + } | |
| 98 | 142 | } |
| 99 | 143 | |
| 100 | 144 | public ListenableFuture<PreparedStatement> prepareAsync(String query) { |
| @@ -285,7 +329,7 @@ | ||
| 285 | 329 | } |
| 286 | 330 | |
| 287 | 331 | // Returns whether there was problem creating the pool |
| 288 | - ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) { | |
| 332 | + ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) { | |
| 289 | 333 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 290 | 334 | if (distance == HostDistance.IGNORED) |
| 291 | 335 | return Futures.immediateFuture(true); |
| @@ -318,6 +362,9 @@ | ||
| 318 | 362 | ClusterNameMismatchException e = (ClusterNameMismatchException)t; |
| 319 | 363 | cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); |
| 320 | 364 | cluster.manager.triggerOnDown(host, false); |
| 365 | + } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) { | |
| 366 | + future.setException(t.getCause()); | |
| 367 | + return; | |
| 321 | 368 | } else { |
| 322 | 369 | logger.error("Error creating pool to " + host, t); |
| 323 | 370 | } |
| @@ -345,54 +392,48 @@ | ||
| 345 | 392 | * This method ensures that all hosts for which a pool should exist |
| 346 | 393 | * have one, and hosts that shouldn't don't. |
| 347 | 394 | */ |
| 348 | - void updateCreatedPools() { | |
| 395 | + ListenableFuture<?> updateCreatedPools() { | |
| 349 | 396 | // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if |
| 350 | 397 | // we execute the code below we would try to create their pool over and over again. |
| 351 | 398 | // It's called explicitly at the end of init(), once isInit has been set to true. |
| 352 | 399 | if (!isInit) |
| 353 | - return; | |
| 400 | + return MoreFutures.VOID_SUCCESS; | |
| 354 | 401 | |
| 355 | - try { | |
| 356 | - // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second. | |
| 357 | - // That way, we'll avoid situation where we'll temporarily lose connectivity | |
| 358 | - List<Host> toRemove = new ArrayList<Host>(); | |
| 359 | - List<ListenableFuture<?>> poolCreationFutures = new ArrayList<ListenableFuture<?>>(); | |
| 360 | - | |
| 361 | - for (Host h : cluster.getMetadata().allHosts()) { | |
| 362 | - HostDistance dist = loadBalancingPolicy().distance(h); | |
| 363 | - HostConnectionPool pool = pools.get(h); | |
| 364 | - | |
| 365 | - if (pool == null) { | |
| 366 | - if (dist != HostDistance.IGNORED && h.state == Host.State.UP) | |
| 367 | - poolCreationFutures.add(maybeAddPool(h, null)); | |
| 368 | - } else if (dist != pool.hostDistance) { | |
| 369 | - if (dist == HostDistance.IGNORED) { | |
| 370 | - toRemove.add(h); | |
| 371 | - } else { | |
| 372 | - pool.hostDistance = dist; | |
| 373 | - pool.ensureCoreConnections(); | |
| 374 | - } | |
| 375 | - } | |
| 376 | - } | |
| 402 | + // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second. | |
| 403 | + // That way, we'll avoid situation where we'll temporarily lose connectivity | |
| 404 | + final List<Host> toRemove = new ArrayList<Host>(); | |
| 405 | + List<ListenableFuture<Boolean>> poolCreatedFutures = Lists.newArrayList(); | |
| 377 | 406 | |
| 378 | - // Wait pool creation before removing, so we don't lose connectivity | |
| 379 | - try { | |
| 380 | - Futures.successfulAsList(poolCreationFutures).get(); | |
| 381 | - } catch (ExecutionException e) { | |
| 382 | - // Won't happen because we used successfulAsList | |
| 383 | - // And if a particular pool failed, maybeAddPool already handled it | |
| 407 | + for (Host h : cluster.getMetadata().allHosts()) { | |
| 408 | + HostDistance dist = loadBalancingPolicy().distance(h); | |
| 409 | + HostConnectionPool pool = pools.get(h); | |
| 410 | + | |
| 411 | + if (pool == null) { | |
| 412 | + if (dist != HostDistance.IGNORED && h.state == Host.State.UP) | |
| 413 | + poolCreatedFutures.add(maybeAddPool(h, null, false)); | |
| 414 | + } else if (dist != pool.hostDistance) { | |
| 415 | + if (dist == HostDistance.IGNORED) { | |
| 416 | + toRemove.add(h); | |
| 417 | + } else { | |
| 418 | + pool.hostDistance = dist; | |
| 419 | + pool.ensureCoreConnections(); | |
| 420 | + } | |
| 384 | 421 | } |
| 422 | + } | |
| 385 | 423 | |
| 386 | - List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size()); | |
| 387 | - for (Host h : toRemove) | |
| 388 | - poolRemovalFutures.add(removePool(h)); | |
| 424 | + // Wait pool creation before removing, so we don't lose connectivity | |
| 425 | + ListenableFuture<?> allPoolsCreatedFuture = Futures.successfulAsList(poolCreatedFutures); | |
| 389 | 426 | |
| 390 | - Futures.allAsList(poolRemovalFutures).get(); | |
| 391 | - } catch (InterruptedException e) { | |
| 392 | - Thread.currentThread().interrupt(); | |
| 393 | - } catch (ExecutionException e) { | |
| 394 | - logger.error("Unexpected error while refreshing connection pools", e.getCause()); | |
| 395 | - } | |
| 427 | + return Futures.transform(allPoolsCreatedFuture, new AsyncFunction<Object, List<Void>>() { | |
| 428 | + @Override | |
| 429 | + public ListenableFuture<List<Void>> apply(Object input) throws Exception { | |
| 430 | + List<ListenableFuture<Void>> poolRemovedFuture = Lists.newArrayListWithCapacity(toRemove.size()); | |
| 431 | + for (Host h : toRemove) | |
| 432 | + poolRemovedFuture.add(removePool(h)); | |
| 433 | + | |
| 434 | + return Futures.successfulAsList(poolRemovedFuture); | |
| 435 | + } | |
| 436 | + }); | |
| 396 | 437 | } |
| 397 | 438 | |
| 398 | 439 | void updateCreatedPools(Host h) { |
| @@ -403,7 +444,7 @@ | ||
| 403 | 444 | if (pool == null) { |
| 404 | 445 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 405 | 446 | try { |
| 406 | - maybeAddPool(h, null).get(); | |
| 447 | + maybeAddPool(h, null, false).get(); | |
| 407 | 448 | } catch (ExecutionException e) { |
| 408 | 449 | // Ignore, maybeAddPool has already handled the error |
| 409 | 450 | } |
| @@ -426,7 +467,7 @@ | ||
| 426 | 467 | // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary |
| 427 | 468 | // since updateCreatedPools should take care of it. But better protect against non well behaving policies. |
| 428 | 469 | removePool(host).force().get(); |
| 429 | - updateCreatedPools(); | |
| 470 | + updateCreatedPools().get(); | |
| 430 | 471 | } |
| 431 | 472 | |
| 432 | 473 | void onRemove(Host host) throws InterruptedException, ExecutionException { |
| @@ -442,7 +483,7 @@ | ||
| 442 | 483 | } catch (TimeoutException e) { |
| 443 | 484 | throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout)); |
| 444 | 485 | } catch (ExecutionException e) { |
| 445 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 486 | + throw DriverThrowables.propagateCause(e); | |
| 446 | 487 | } |
| 447 | 488 | } |
| 448 | 489 | |
| @@ -528,11 +569,16 @@ | ||
| 528 | 569 | * This method will find a suitable node to connect to using the |
| 529 | 570 | * {@link LoadBalancingPolicy} and handle host failover. |
| 530 | 571 | */ |
| 531 | - void execute(RequestHandler.Callback callback, Statement statement) { | |
| 532 | - // init() locks, so avoid if we know we don't need it. | |
| 533 | - if (!isInit) | |
| 534 | - init(); | |
| 535 | - new RequestHandler(this, callback, statement).sendRequest(); | |
| 572 | + void execute(final RequestHandler.Callback callback, final Statement statement) { | |
| 573 | + if (isInit) | |
| 574 | + new RequestHandler(this, callback, statement).sendRequest(); | |
| 575 | + else | |
| 576 | + this.initAsync().addListener(new Runnable() { | |
| 577 | + @Override | |
| 578 | + public void run() { | |
| 579 | + new RequestHandler(SessionManager.this, callback, statement).sendRequest(); | |
| 580 | + } | |
| 581 | + }, executor()); | |
| 536 | 582 | } |
| 537 | 583 | |
| 538 | 584 | private void prepare(String query, InetSocketAddress toExclude) throws InterruptedException { |
| @@ -567,7 +613,6 @@ | ||
| 567 | 613 | } |
| 568 | 614 | |
| 569 | 615 | ResultSetFuture executeQuery(Message.Request msg, Statement statement) { |
| 570 | - | |
| 571 | 616 | DefaultResultSetFuture future = new DefaultResultSetFuture(this, msg); |
| 572 | 617 | execute(future, statement); |
| 573 | 618 | return future; |
added driver-core/src/main/java/com/datastax/driver/core/SetKeyspaceException.java +23 −0
| @@ -0,0 +1,23 @@ | ||
| 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 | +@SuppressWarnings("serial") | |
| 19 | +class SetKeyspaceException extends Exception { | |
| 20 | + SetKeyspaceException(Exception cause) { | |
| 21 | + super(cause); | |
| 22 | + } | |
| 23 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +78 −3
| @@ -16,26 +16,38 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.util.Collection; |
| 19 | +import java.util.concurrent.ExecutionException; | |
| 19 | 20 | import java.util.concurrent.TimeUnit; |
| 20 | 21 | |
| 22 | +import com.google.common.base.Function; | |
| 21 | 23 | import com.google.common.collect.Lists; |
| 24 | +import com.google.common.util.concurrent.AsyncFunction; | |
| 25 | +import com.google.common.util.concurrent.Futures; | |
| 26 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 27 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 22 | 28 | import org.testng.annotations.Test; |
| 23 | 29 | |
| 30 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 24 | 31 | import static org.testng.Assert.assertEquals; |
| 25 | 32 | import static org.testng.Assert.assertTrue; |
| 26 | 33 | |
| 34 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 35 | + | |
| 27 | 36 | public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster { |
| 28 | 37 | |
| 29 | 38 | @Override |
| 30 | 39 | protected Collection<String> getTableDefinitions() { |
| 31 | - return Lists.newArrayList(); | |
| 40 | + return Lists.newArrayList( | |
| 41 | + "create table foo(k int primary key, v int)", | |
| 42 | + "insert into foo (k, v) values (1, 1)" | |
| 43 | + ); | |
| 32 | 44 | } |
| 33 | 45 | |
| 34 | 46 | /** |
| 35 | 47 | * Checks that a cancelled query releases the connection (JAVA-407). |
| 36 | 48 | */ |
| 37 | 49 | @Test(groups = "short") |
| 38 | - public void cancelQueryTest() throws InterruptedException { | |
| 50 | + public void cancelled_query_should_release_the_connection() throws InterruptedException { | |
| 39 | 51 | ResultSetFuture future = session.executeAsync("select release_version from system.local"); |
| 40 | 52 | future.cancel(true); |
| 41 | 53 | assertTrue(future.isCancelled()); |
| @@ -48,8 +60,71 @@ | ||
| 48 | 60 | } |
| 49 | 61 | } |
| 50 | 62 | |
| 63 | + @Test(groups = "short") | |
| 64 | + public void should_init_cluster_and_session_if_needed() throws Exception { | |
| 65 | + // For this test we need an uninitialized cluster, so we can't reuse the one provided by the | |
| 66 | + // parent class. Rebuild a new one with the same (unique) host. | |
| 67 | + Host host = cluster.getMetadata().allHosts().iterator().next(); | |
| 68 | + | |
| 69 | + Cluster cluster2 = null; | |
| 70 | + try { | |
| 71 | + cluster2 = Cluster.builder() | |
| 72 | + .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress())) | |
| 73 | + .build(); | |
| 74 | + Session session2 = cluster2.newSession(); | |
| 75 | + | |
| 76 | + // Neither cluster2 nor session2 are initialized at this point | |
| 77 | + assertThat(cluster2.manager.metadata).isNull(); | |
| 78 | + | |
| 79 | + ResultSetFuture future = session2.executeAsync(String.format("select v from %s.foo where k = 1", keyspace)); | |
| 80 | + Row row = Uninterruptibles.getUninterruptibly(future).one(); | |
| 81 | + | |
| 82 | + assertThat(row.getInt(0)).isEqualTo(1); | |
| 83 | + } finally { | |
| 84 | + if (cluster2 != null) | |
| 85 | + cluster2.close(); | |
| 86 | + } | |
| 87 | + } | |
| 88 | + | |
| 89 | + @Test(groups = "short") | |
| 90 | + public void should_chain_query_on_async_session_init() throws Exception { | |
| 91 | + ListenableFuture<Integer> resultFuture = connectAndQuery(this.keyspace); | |
| 92 | + | |
| 93 | + Integer result = Uninterruptibles.getUninterruptibly(resultFuture); | |
| 94 | + assertThat(result).isEqualTo(1); | |
| 95 | + } | |
| 96 | + | |
| 97 | + @Test(groups = "short") | |
| 98 | + public void should_propagate_error_to_chained_query_if_session_init_fails() throws Exception { | |
| 99 | + ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace"); | |
| 100 | + | |
| 101 | + try { | |
| 102 | + Uninterruptibles.getUninterruptibly(resultFuture); | |
| 103 | + } catch (ExecutionException e) { | |
| 104 | + assertThat(e.getCause()) | |
| 105 | + .isInstanceOf(InvalidQueryException.class) | |
| 106 | + .hasMessage("Keyspace 'wrong_keyspace' does not exist"); | |
| 107 | + } | |
| 108 | + } | |
| 109 | + | |
| 110 | + private ListenableFuture<Integer> connectAndQuery(String keyspace) { | |
| 111 | + ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace); | |
| 112 | + ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() { | |
| 113 | + @Override | |
| 114 | + public ListenableFuture<ResultSet> apply(Session session) throws Exception { | |
| 115 | + return session.executeAsync("select v from foo where k = 1"); | |
| 116 | + } | |
| 117 | + }); | |
| 118 | + return Futures.transform(queryFuture, new Function<ResultSet, Integer>() { | |
| 119 | + @Override | |
| 120 | + public Integer apply(ResultSet rs) { | |
| 121 | + return rs.one().getInt(0); | |
| 122 | + } | |
| 123 | + }); | |
| 124 | + } | |
| 125 | + | |
| 51 | 126 | private static HostConnectionPool getPool(Session session) { |
| 52 | - Collection<HostConnectionPool> pools = ((SessionManager) session).pools.values(); | |
| 127 | + Collection<HostConnectionPool> pools = ((SessionManager)session).pools.values(); | |
| 53 | 128 | assertEquals(pools.size(), 1); |
| 54 | 129 | return pools.iterator().next(); |
| 55 | 130 | } |
added features/async/README.md +102 −0
| @@ -0,0 +1,102 @@ | ||
| 1 | +## Asynchronous programming | |
| 2 | + | |
| 3 | +The driver exposes an asynchronous API that allows you to write programs | |
| 4 | +in a fully-non blocking manner. Asynchronous methods return instances of | |
| 5 | +Guava's [ListenableFuture], that can be conveniently chained and | |
| 6 | +composed. | |
| 7 | + | |
| 8 | +Here is a short example that opens a session and runs a query | |
| 9 | +asynchronously: | |
| 10 | + | |
| 11 | +```java | |
| 12 | +import com.google.common.util.concurrent.*; | |
| 13 | + | |
| 14 | +ListenableFuture<Session> session = cluster.connectAsync(); | |
| 15 | + | |
| 16 | +// Use transform with an AsyncFunction to chain an async operation after another: | |
| 17 | +ListenableFuture<ResultSet> resultSet = Futures.transform(session, | |
| 18 | + new AsyncFunction<Session, ResultSet>() { | |
| 19 | + public ListenableFuture<ResultSet> apply(Session session) throws Exception { | |
| 20 | + return session.executeAsync("select release_version from system.local"); | |
| 21 | + } | |
| 22 | + }); | |
| 23 | + | |
| 24 | +// Use transform with a simple Function to apply a synchronous computation on the result: | |
| 25 | +ListenableFuture<String> version = Futures.transform(resultSet, | |
| 26 | + new Function<ResultSet, String>() { | |
| 27 | + public String apply(ResultSet rs) { | |
| 28 | + return rs.one().getString("release_version"); | |
| 29 | + } | |
| 30 | + }); | |
| 31 | + | |
| 32 | +// Use a callback to perform an action once the future is complete: | |
| 33 | +Futures.addCallback(version, new FutureCallback<String>() { | |
| 34 | + public void onSuccess(String version) { | |
| 35 | + System.out.printf("Cassandra version: %s%n", version); | |
| 36 | + } | |
| 37 | + | |
| 38 | + public void onFailure(Throwable t) { | |
| 39 | + System.out.printf("Failed to retrieve the version: %s%n", | |
| 40 | + t.getMessage()); | |
| 41 | + } | |
| 42 | +}); | |
| 43 | +``` | |
| 44 | + | |
| 45 | +### Good practices | |
| 46 | + | |
| 47 | +If your callback is slow, consider providing a separate executor. | |
| 48 | +Otherwise the callback might run on one of the driver's I/O threads, | |
| 49 | +blocking I/O operations for other requests while it is running: | |
| 50 | + | |
| 51 | +```java | |
| 52 | +ListenableFuture<String> result = Futures.transform(resultSet, | |
| 53 | + new Function<ResultSet, String>() { | |
| 54 | + public String apply(ResultSet rs) { | |
| 55 | + return someVeryLongComputation(rs); | |
| 56 | + } | |
| 57 | + }, myCustomExecutor); | |
| 58 | +``` | |
| 59 | + | |
| 60 | +Avoid blocking operations in callbacks, especially if you don't provide | |
| 61 | +a separate executor. This could easily lead to deadlock if the thread | |
| 62 | +that's supposed to complete the blocking call is also the thread that's | |
| 63 | +waiting on it: | |
| 64 | + | |
| 65 | +```java | |
| 66 | +ListenableFuture<ResultSet> resultSet = Futures.transform(session, | |
| 67 | + new Function<Session, ResultSet>() { | |
| 68 | + public ResultSet apply(Session session) { | |
| 69 | + // Synchronous operation in a callback. | |
| 70 | + // DON'T DO THIS! It might deadlock. | |
| 71 | + return session.execute("select release_version from system.local"); | |
| 72 | + } | |
| 73 | + }); | |
| 74 | +``` | |
| 75 | + | |
| 76 | +### Known limitations | |
| 77 | + | |
| 78 | +There are still a few places where the driver will block internally | |
| 79 | +(mainly for historical reasons): | |
| 80 | + | |
| 81 | +* [Cluster#init][init] performs blocking I/O operations. To avoid | |
| 82 | + issues, you should create your `Cluster` instances while bootstrapping | |
| 83 | + your application, and call `init` immediately. If you need to create new | |
| 84 | + instances at runtime, make sure this does not happen on an I/O thread. | |
| 85 | +* if a connection pool is busy, the driver will block until a connection | |
| 86 | + becomes available. To avoid this, set | |
| 87 | + [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the | |
| 88 | + driver will not block, just move to the next host immediately. | |
| 89 | +* if the session is set to a specific keyspace (either at startup or by | |
| 90 | + issuing a `USE` statement on a running session), the keyspace needs to | |
| 91 | + be propagated to any newly created connection. This is done when the | |
| 92 | + connection is first borrowed from the connection pool, and currently | |
| 93 | + blocks. To avoid any issue, only use a session with no keyspace set | |
| 94 | + (i.e. created by `Cluster#connect()`). This will be addressed in | |
| 95 | + [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893). | |
| 96 | +* trying to read fields from a [query trace] will block if the trace | |
| 97 | + hasn't been fetched already. | |
| 98 | + | |
| 99 | +[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained | |
| 100 | +[init]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#init() | |
| 101 | +[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 102 | +[query trace]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryTrace.html |