kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 221b4b695b84ae88b9a4225a042b9c68fbd940e6c0e2ec4363a02255cc59e2ab |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-11-06 11:10 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-11-06 11:10 +01:00 |
| Parents | 0d619c82c5fa, 5e3e86a8f8bb |
44 files changed
modified README.md +6 −2
| @@ -68,9 +68,9 @@ | ||
| 68 | 68 | **Feeback requested:** help us focus our efforts, provide your input on the [Platform and Runtime Survey](http://goo.gl/forms/qwUE6qnL7U) (we kept it short). |
| 69 | 69 | |
| 70 | 70 | |
| 71 | -## Maven | |
| 71 | +## Getting the driver | |
| 72 | 72 | |
| 73 | -The last release of the driver is available on Maven Central. You can install | |
| 73 | +The latest release of the driver is available on Maven Central. You can install | |
| 74 | 74 | it in your application using the following Maven dependency: |
| 75 | 75 | |
| 76 | 76 | ```xml |
| @@ -94,6 +94,10 @@ | ||
| 94 | 94 | We also provide a [shaded JAR](features/shaded_jar/) |
| 95 | 95 | to avoid the explicit dependency to Netty. |
| 96 | 96 | |
| 97 | +If you can't use a dependency management tool, a | |
| 98 | +[binary tarball](http://downloads.datastax.com/java-driver/cassandra-java-driver-2.0.11.tar.gz) | |
| 99 | +is available for download. | |
| 100 | + | |
| 97 | 101 | ## Compatibility |
| 98 | 102 | |
| 99 | 103 | The Java client driver 2.1 ([branch 2.1](https://github.com/datastax/java-driver/tree/2.1)) is compatible with Apache |
modified changelog/README.md +31 −0
| @@ -4,6 +4,21 @@ | ||
| 4 | 4 | |
| 5 | 5 | - [bug] Fix implementation of UserType.hashCode() (JAVA-942) |
| 6 | 6 | |
| 7 | +Merged from 2.0 branch: | |
| 8 | + | |
| 9 | +- [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace. | |
| 10 | +- [improvement] JAVA-920: Downgrade "error creating pool" message to WARN. | |
| 11 | +- [bug] JAVA-954: Don't trigger reconnection before initialization complete. | |
| 12 | +- [improvement] JAVA-914: Avoid rejected tasks at shutdown. | |
| 13 | +- [improvement] JAVA-921: Add SimpleStatement.getValuesCount(). | |
| 14 | +- [bug] JAVA-901: Move call to connection.release() out of cancelHandler. | |
| 15 | +- [bug] JAVA-960: Avoid race in control connection shutdown. | |
| 16 | +- [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo. | |
| 17 | +- [bug] JAVA-966: Count uninitialized connections in conviction policy. | |
| 18 | +- [improvement] JAVA-917: Document SSL configuration. | |
| 19 | +- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder. | |
| 20 | +- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs. | |
| 21 | + | |
| 7 | 22 | |
| 8 | 23 | ### 2.1.8 |
| 9 | 24 | |
| @@ -318,6 +333,22 @@ | ||
| 318 | 333 | - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391) |
| 319 | 334 | |
| 320 | 335 | |
| 336 | +### 2.0.12 (in progress) | |
| 337 | + | |
| 338 | +- [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace. | |
| 339 | +- [improvement] JAVA-920: Downgrade "error creating pool" message to WARN. | |
| 340 | +- [bug] JAVA-954: Don't trigger reconnection before initialization complete. | |
| 341 | +- [improvement] JAVA-914: Avoid rejected tasks at shutdown. | |
| 342 | +- [improvement] JAVA-921: Add SimpleStatement.getValuesCount(). | |
| 343 | +- [bug] JAVA-901: Move call to connection.release() out of cancelHandler. | |
| 344 | +- [bug] JAVA-960: Avoid race in control connection shutdown. | |
| 345 | +- [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo. | |
| 346 | +- [bug] JAVA-966: Count uninitialized connections in conviction policy. | |
| 347 | +- [improvement] JAVA-917: Document SSL configuration. | |
| 348 | +- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder. | |
| 349 | +- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs. | |
| 350 | + | |
| 351 | + | |
| 321 | 352 | ### 2.0.11 |
| 322 | 353 | |
| 323 | 354 | - [improvement] Log streamid at the trace level on sending request and receiving response (JAVA-718) |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +3 −1
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import java.util.concurrent.*; |
| 19 | 19 | import java.util.concurrent.atomic.AtomicReference; |
| 20 | 20 | |
| 21 | +import com.google.common.annotations.VisibleForTesting; | |
| 21 | 22 | import com.google.common.util.concurrent.ListenableFuture; |
| 22 | 23 | import com.google.common.util.concurrent.AbstractFuture; |
| 23 | 24 | import org.slf4j.Logger; |
| @@ -183,7 +184,8 @@ | ||
| 183 | 184 | } |
| 184 | 185 | |
| 185 | 186 | // The future that the handler exposes to its clients via currentAttempt |
| 186 | - private static class HandlerFuture extends AbstractFuture<Void> { | |
| 187 | + @VisibleForTesting | |
| 188 | + static class HandlerFuture extends AbstractFuture<Void> { | |
| 187 | 189 | // A future representing completion of the next task submitted to the executor |
| 188 | 190 | volatile ScheduledFuture<?> nextTry; |
| 189 | 191 |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +33 −11
| @@ -26,6 +26,7 @@ | ||
| 26 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 27 | 27 | |
| 28 | 28 | import com.google.common.annotations.VisibleForTesting; |
| 29 | +import com.google.common.base.Functions; | |
| 29 | 30 | import com.google.common.base.Predicates; |
| 30 | 31 | import com.google.common.base.Strings; |
| 31 | 32 | import com.google.common.collect.*; |
| @@ -35,6 +36,7 @@ | ||
| 35 | 36 | |
| 36 | 37 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 37 | 38 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 39 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 38 | 40 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 39 | 41 | import com.datastax.driver.core.policies.*; |
| 40 | 42 | import com.datastax.driver.core.utils.MoreFutures; |
| @@ -222,7 +224,7 @@ | ||
| 222 | 224 | */ |
| 223 | 225 | public Session newSession() { |
| 224 | 226 | checkNotClosed(manager); |
| 225 | - return manager.newSession(null); | |
| 227 | + return manager.newSession(); | |
| 226 | 228 | } |
| 227 | 229 | |
| 228 | 230 | /** |
| @@ -273,6 +275,7 @@ | ||
| 273 | 275 | * be contacted to set the {@code keyspace}. |
| 274 | 276 | * @throws AuthenticationException if an authentication error occurs while |
| 275 | 277 | * contacting the initial contact points. |
| 278 | + * @throws InvalidQueryException if the keyspace does not exists. | |
| 276 | 279 | * @throws IllegalStateException if the Cluster was closed prior to calling |
| 277 | 280 | * this method. This can occur either directly (through {@link #close()} or |
| 278 | 281 | * {@link #closeAsync()}), or as a result of an error while initializing the |
| @@ -333,11 +336,28 @@ | ||
| 333 | 336 | * {@link #closeAsync()}), or as a result of an error while initializing the |
| 334 | 337 | * Cluster. |
| 335 | 338 | */ |
| 336 | - public ListenableFuture<Session> connectAsync(String keyspace) { | |
| 339 | + public ListenableFuture<Session> connectAsync(final String keyspace) { | |
| 337 | 340 | checkNotClosed(manager); |
| 338 | 341 | init(); |
| 339 | - AsyncInitSession session = manager.newSession(keyspace); | |
| 340 | - return session.initAsync(); | |
| 342 | + final AsyncInitSession session = manager.newSession(); | |
| 343 | + ListenableFuture<Session> sessionInitialized = session.initAsync(); | |
| 344 | + if (keyspace == null) { | |
| 345 | + return sessionInitialized; | |
| 346 | + } else { | |
| 347 | + ListenableFuture<ResultSet> keyspaceSet = Futures.transform(sessionInitialized, new AsyncFunction<Session, ResultSet>() { | |
| 348 | + @Override | |
| 349 | + public ListenableFuture<ResultSet> apply(Session session) throws Exception { | |
| 350 | + return session.executeAsync("USE " + keyspace); | |
| 351 | + } | |
| 352 | + }); | |
| 353 | + Futures.addCallback(keyspaceSet, new MoreFutures.FailureCallback<ResultSet>() { | |
| 354 | + @Override | |
| 355 | + public void onFailure(Throwable t) { | |
| 356 | + session.closeAsync(); | |
| 357 | + } | |
| 358 | + }); | |
| 359 | + return Futures.transform(keyspaceSet, Functions.<Session>constant(session)); | |
| 360 | + } | |
| 341 | 361 | } |
| 342 | 362 | |
| 343 | 363 | /** |
| @@ -1445,6 +1465,7 @@ | ||
| 1445 | 1465 | loadBalancingPolicy().onDown(host); |
| 1446 | 1466 | for (Host.StateListener listener : listeners) |
| 1447 | 1467 | listener.onDown(host); |
| 1468 | + startPeriodicReconnectionAttempt(host, true); | |
| 1448 | 1469 | } |
| 1449 | 1470 | |
| 1450 | 1471 | configuration.getPoolingOptions().setProtocolVersion(protocolVersion()); |
| @@ -1527,8 +1548,8 @@ | ||
| 1527 | 1548 | return translated == null ? sa : translated; |
| 1528 | 1549 | } |
| 1529 | 1550 | |
| 1530 | - private AsyncInitSession newSession(String keyspace) { | |
| 1531 | - SessionManager session = new SessionManager(Cluster.this, keyspace); | |
| 1551 | + private AsyncInitSession newSession() { | |
| 1552 | + SessionManager session = new SessionManager(Cluster.this); | |
| 1532 | 1553 | sessions.add(session); |
| 1533 | 1554 | return session; |
| 1534 | 1555 | } |
| @@ -1965,7 +1986,7 @@ | ||
| 1965 | 1986 | |
| 1966 | 1987 | List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); |
| 1967 | 1988 | for (SessionManager s : sessions) |
| 1968 | - futures.add(s.maybeAddPool(host, reusedConnection, false)); | |
| 1989 | + futures.add(s.maybeAddPool(host, reusedConnection)); | |
| 1969 | 1990 | |
| 1970 | 1991 | try { |
| 1971 | 1992 | // Only mark the node up once all session have added their pool (if the load-balancing |
| @@ -2044,14 +2065,15 @@ | ||
| 2044 | 2065 | } |
| 2045 | 2066 | } |
| 2046 | 2067 | |
| 2047 | - public boolean signalConnectionFailure(Host host, ConnectionException exception, | |
| 2048 | - boolean connectionInitialized, boolean isHostAddition) { | |
| 2049 | - // Don't signal failure until we've fully initialized the controlConnection as this might mess up with | |
| 2068 | + public boolean signalConnectionFailure(Host host, Connection connection, | |
| 2069 | + boolean isHostAddition) { | |
| 2070 | + boolean isDown = host.convictionPolicy.signalConnectionFailure(connection); | |
| 2071 | + | |
| 2072 | + // Don't mark the node down until we've fully initialized the controlConnection as this might mess up with | |
| 2050 | 2073 | // the protocol detection |
| 2051 | 2074 | if (!isFullyInit || isClosed()) |
| 2052 | 2075 | return true; |
| 2053 | 2076 | |
| 2054 | - boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized); | |
| 2055 | 2077 | if (isDown) |
| 2056 | 2078 | triggerOnDown(host, isHostAddition, true); |
| 2057 | 2079 | return isDown; |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +75 −79
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | import java.util.HashSet; |
| 21 | 21 | import java.util.Iterator; |
| 22 | +import java.util.List; | |
| 22 | 23 | import java.util.Queue; |
| 23 | 24 | import java.util.concurrent.*; |
| 24 | 25 | import java.util.concurrent.atomic.AtomicBoolean; |
| @@ -26,6 +27,7 @@ | ||
| 26 | 27 | import java.util.concurrent.atomic.AtomicReference; |
| 27 | 28 | |
| 28 | 29 | import com.google.common.annotations.VisibleForTesting; |
| 30 | +import com.google.common.collect.Lists; | |
| 29 | 31 | import com.google.common.collect.MapMaker; |
| 30 | 32 | import com.google.common.util.concurrent.*; |
| 31 | 33 | import io.netty.bootstrap.Bootstrap; |
| @@ -46,14 +48,13 @@ | ||
| 46 | 48 | |
| 47 | 49 | import static io.netty.handler.timeout.IdleState.ALL_IDLE; |
| 48 | 50 | |
| 51 | +import com.datastax.driver.core.Responses.Result.SetKeyspace; | |
| 49 | 52 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 50 | 53 | import com.datastax.driver.core.exceptions.DriverException; |
| 51 | 54 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 52 | -import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 53 | 55 | import com.datastax.driver.core.utils.MoreFutures; |
| 54 | 56 | |
| 55 | 57 | import static com.datastax.driver.core.Message.Response.Type.ERROR; |
| 56 | -import static com.datastax.driver.core.Message.Response.Type.RESULT; | |
| 57 | 58 | |
| 58 | 59 | // For LoggingHandler |
| 59 | 60 | //import org.jboss.netty.handler.logging.LoggingHandler; |
| @@ -160,7 +161,7 @@ | ||
| 160 | 161 | logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause()))); |
| 161 | 162 | channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause())); |
| 162 | 163 | } else { |
| 163 | - logger.debug("{} Connection opened successfully", Connection.this); | |
| 164 | + logger.debug("{} Connection established, initializing transport", Connection.this); | |
| 164 | 165 | channel.closeFuture().addListener(new ChannelCloseListener()); |
| 165 | 166 | channelReadyFuture.set(null); |
| 166 | 167 | } |
| @@ -177,13 +178,14 @@ | ||
| 177 | 178 | ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture, |
| 178 | 179 | onChannelReady(protocolVersion, initExecutor), initExecutor); |
| 179 | 180 | |
| 181 | + | |
| 180 | 182 | // Fallback on initializeTransportFuture so we can properly propagate specific exceptions. |
| 181 | 183 | ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() { |
| 182 | 184 | @Override |
| 183 | 185 | public ListenableFuture<Void> create(Throwable t) throws Exception { |
| 184 | 186 | SettableFuture<Void> future = SettableFuture.create(); |
| 185 | 187 | // Make sure the connection gets properly closed. |
| 186 | - if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException || t instanceof SetKeyspaceException) { | |
| 188 | + if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) { | |
| 187 | 189 | // Just propagate |
| 188 | 190 | closeAsync().force(); |
| 189 | 191 | future.setException(t); |
| @@ -200,16 +202,8 @@ | ||
| 200 | 202 | } |
| 201 | 203 | }, initExecutor); |
| 202 | 204 | |
| 203 | - // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel. | |
| 204 | - Futures.addCallback(initFuture, new FutureCallback<Void>() { | |
| 205 | - @Override | |
| 206 | - public void onSuccess(Void result) { | |
| 207 | - Host host = factory.manager.metadata.getHost(address); | |
| 208 | - if (host != null) | |
| 209 | - host.convictionPolicy.signalConnectionCreated(); | |
| 210 | - isInitialized = true; | |
| 211 | - } | |
| 212 | - | |
| 205 | + // Ensure the connection gets closed if the caller cancels the returned future. | |
| 206 | + Futures.addCallback(initFuture, new MoreFutures.FailureCallback<Void>() { | |
| 213 | 207 | @Override |
| 214 | 208 | public void onFailure(Throwable t) { |
| 215 | 209 | if (!isClosed()) { |
| @@ -284,8 +278,10 @@ | ||
| 284 | 278 | final String expected = factory.manager.metadata.clusterName; |
| 285 | 279 | |
| 286 | 280 | // At initialization, the cluster is not known yet |
| 287 | - if (expected == null) | |
| 281 | + if (expected == null) { | |
| 282 | + markInitialized(); | |
| 288 | 283 | return MoreFutures.VOID_SUCCESS; |
| 284 | + } | |
| 289 | 285 | |
| 290 | 286 | DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null, protocolVersion, new Requests.Query("select cluster_name from system.local")); |
| 291 | 287 | try { |
| @@ -298,6 +294,7 @@ | ||
| 298 | 294 | String actual = row.getString("cluster_name"); |
| 299 | 295 | if (!expected.equals(actual)) |
| 300 | 296 | throw new ClusterNameMismatchException(address, actual, expected); |
| 297 | + markInitialized(); | |
| 301 | 298 | return MoreFutures.VOID_SUCCESS; |
| 302 | 299 | } |
| 303 | 300 | }, executor); |
| @@ -306,6 +303,11 @@ | ||
| 306 | 303 | } |
| 307 | 304 | } |
| 308 | 305 | |
| 306 | + private void markInitialized() { | |
| 307 | + isInitialized = true; | |
| 308 | + Host.statesLogger.debug("[{}] {} Transport initialized, connection ready", address, this); | |
| 309 | + } | |
| 310 | + | |
| 309 | 311 | private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) { |
| 310 | 312 | Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials()); |
| 311 | 313 | try { |
| @@ -395,33 +397,18 @@ | ||
| 395 | 397 | } |
| 396 | 398 | |
| 397 | 399 | <E extends Exception> E defunct(E e) { |
| 398 | - if (!isDefunct.compareAndSet(false, true)) | |
| 399 | - return e; | |
| 400 | - | |
| 401 | - if (Host.statesLogger.isTraceEnabled()) | |
| 402 | - Host.statesLogger.trace("Defuncting " + this, e); | |
| 403 | - else if (Host.statesLogger.isDebugEnabled()) | |
| 404 | - Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); | |
| 405 | - | |
| 406 | - ConnectionException ce = e instanceof ConnectionException | |
| 407 | - ? (ConnectionException)e | |
| 408 | - : new ConnectionException(address, "Connection problem", e); | |
| 409 | - | |
| 410 | - Host host = factory.manager.metadata.getHost(address); | |
| 411 | - if (host != null) { | |
| 412 | - boolean isDown = factory.manager.signalConnectionFailure(host, ce, isInitialized, host.wasJustAdded()); | |
| 413 | - | |
| 414 | - if (!isDown) | |
| 415 | - notifyOwnerWhenDefunct(); | |
| 416 | - // else the driver will destroy all pools and notify the control connection as part of marking the host down, | |
| 417 | - // so no need to notify | |
| 400 | + if (isDefunct.compareAndSet(false, true)) { | |
| 401 | + | |
| 402 | + if (Host.statesLogger.isTraceEnabled()) | |
| 403 | + Host.statesLogger.trace("Defuncting " + this, e); | |
| 404 | + else if (Host.statesLogger.isDebugEnabled()) | |
| 405 | + Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); | |
| 406 | + | |
| 407 | + // Force the connection to close to make sure the future completes. Otherwise force() might never get called and | |
| 408 | + // threads will wait on the future forever. | |
| 409 | + // (this also errors out pending handlers) | |
| 410 | + closeAsync().force(); | |
| 418 | 411 | } |
| 419 | - | |
| 420 | - // Force the connection to close to make sure the future completes. Otherwise force() might never get called and | |
| 421 | - // threads will wait on the future forever. | |
| 422 | - // (this also errors out pending handlers) | |
| 423 | - closeAsync().force(); | |
| 424 | - | |
| 425 | 412 | return e; |
| 426 | 413 | } |
| 427 | 414 | |
| @@ -457,10 +444,6 @@ | ||
| 457 | 444 | } catch (ExecutionException e) { |
| 458 | 445 | Throwable cause = e.getCause(); |
| 459 | 446 | if (cause instanceof OperationTimedOutException) { |
| 460 | - // The timeout logic released the connection, but that's wrong since we did not borrow it in the first place. | |
| 461 | - // JAVA-901 will fix this, in the meantime make sure the inFlight count is not off by one. | |
| 462 | - inFlight.incrementAndGet(); | |
| 463 | - | |
| 464 | 447 | // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down |
| 465 | 448 | logger.warn("Timeout while setting keyspace on connection to {}. " |
| 466 | 449 | + "This should not happen but is not critical (it will be retried)", address); |
| @@ -478,19 +461,13 @@ | ||
| 478 | 461 | return Futures.transform(future, new AsyncFunction<Message.Response, Void>() { |
| 479 | 462 | @Override |
| 480 | 463 | public ListenableFuture<Void> apply(Message.Response response) throws Exception { |
| 481 | - if (response.type == RESULT) { | |
| 482 | - Connection.this.keyspace = keyspace; | |
| 464 | + if (response instanceof SetKeyspace) { | |
| 465 | + Connection.this.keyspace = ((SetKeyspace)response).keyspace; | |
| 483 | 466 | return MoreFutures.VOID_SUCCESS; |
| 484 | 467 | } else if (response.type == ERROR) { |
| 485 | 468 | closeAsync().force(); |
| 486 | 469 | Responses.Error error = (Responses.Error)response; |
| 487 | - Exception e = error.asException(address); | |
| 488 | - if (e instanceof InvalidQueryException) { | |
| 489 | - // Most likely means that the keyspace name is wrong. Wrap that in a specific exception, because we want | |
| 490 | - // to treat it specially in case of a Session init. | |
| 491 | - e = new SetKeyspaceException(e); | |
| 492 | - } | |
| 493 | - throw e; | |
| 470 | + throw error.asException(address); | |
| 494 | 471 | } else { |
| 495 | 472 | closeAsync().force(); |
| 496 | 473 | throw new DriverInternalError("Unexpected response while setting keyspace: " + response); |
| @@ -581,12 +558,14 @@ | ||
| 581 | 558 | // requires its writeLock. |
| 582 | 559 | // Therefore if multiple connections in the same pool get a write error, they could deadlock; |
| 583 | 560 | // we run defunct on a separate thread to avoid that. |
| 584 | - factory.manager.executor.execute(new Runnable() { | |
| 585 | - @Override | |
| 586 | - public void run() { | |
| 587 | - handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount); | |
| 588 | - } | |
| 589 | - }); | |
| 561 | + ListeningExecutorService executor = factory.manager.executor; | |
| 562 | + if (!executor.isShutdown()) | |
| 563 | + executor.execute(new Runnable() { | |
| 564 | + @Override | |
| 565 | + public void run() { | |
| 566 | + handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount); | |
| 567 | + } | |
| 568 | + }); | |
| 590 | 569 | } else { |
| 591 | 570 | logger.trace("{}, stream {}, request sent successfully", Connection.this, request.getStreamId()); |
| 592 | 571 | } |
| @@ -638,10 +617,18 @@ | ||
| 638 | 617 | |
| 639 | 618 | logger.debug("{} closing connection", this); |
| 640 | 619 | |
| 641 | - if (isInitialized && !isDefunct.get()) { | |
| 642 | - Host host = factory.manager.metadata.getHost(address); | |
| 643 | - if(host != null) | |
| 644 | - host.convictionPolicy.signalConnectionClosed(); | |
| 620 | + Host host = factory.manager.metadata.getHost(address); | |
| 621 | + if (host != null) { | |
| 622 | + if (isDefunct.get()) { | |
| 623 | + boolean isDown = factory.manager.signalConnectionFailure(host, this, host.wasJustAdded()); | |
| 624 | + | |
| 625 | + if (!isDown) | |
| 626 | + notifyOwnerWhenDefunct(); | |
| 627 | + // else the driver will destroy all pools and notify the control connection as part of marking the host down, | |
| 628 | + // so no need to notify | |
| 629 | + } else { | |
| 630 | + host.convictionPolicy.signalConnectionClosed(this); | |
| 631 | + } | |
| 645 | 632 | } |
| 646 | 633 | |
| 647 | 634 | boolean terminated = tryTerminate(false); |
| @@ -741,8 +728,8 @@ | ||
| 741 | 728 | if (isShutdown) |
| 742 | 729 | throw new ConnectionException(address, "Connection factory is shut down"); |
| 743 | 730 | |
| 744 | - String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement(); | |
| 745 | - Connection connection = new Connection(name, address, this); | |
| 731 | + host.convictionPolicy.signalConnectionsOpening(1); | |
| 732 | + Connection connection = new Connection(buildConnectionName(host), address, this); | |
| 746 | 733 | // This method opens the connection synchronously, so wait until it's initialized |
| 747 | 734 | try { |
| 748 | 735 | connection.initAsync().get(); |
| @@ -756,8 +743,9 @@ | ||
| 756 | 743 | * Same as open, but associate the created connection to the provided connection pool. |
| 757 | 744 | */ |
| 758 | 745 | public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 746 | + pool.host.convictionPolicy.signalConnectionsOpening(1); | |
| 747 | + Connection connection = new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool); | |
| 759 | 748 | try { |
| 760 | - Connection connection = newConnection(pool); | |
| 761 | 749 | connection.initAsync().get(); |
| 762 | 750 | return connection; |
| 763 | 751 | } catch (ExecutionException e) { |
| @@ -766,13 +754,18 @@ | ||
| 766 | 754 | } |
| 767 | 755 | |
| 768 | 756 | /** |
| 769 | - * Creates a new connection and associates it to the provided connection pool, but does not start it. | |
| 757 | + * Creates new connections and associate them to the provided connection pool, but does not start them. | |
| 770 | 758 | */ |
| 771 | - public Connection newConnection(HostConnectionPool pool) { | |
| 772 | - InetSocketAddress address = pool.host.getSocketAddress(); | |
| 773 | - String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement(); | |
| 759 | + public List<Connection> newConnections(HostConnectionPool pool, int count) { | |
| 760 | + pool.host.convictionPolicy.signalConnectionsOpening(count); | |
| 761 | + List<Connection> connections = Lists.newArrayListWithCapacity(count); | |
| 762 | + for (int i = 0; i < count; i++) | |
| 763 | + connections.add(new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool)); | |
| 764 | + return connections; | |
| 765 | + } | |
| 774 | 766 | |
| 775 | - return new Connection(name, address, this, pool); | |
| 767 | + private String buildConnectionName(Host host) { | |
| 768 | + return host.getSocketAddress().toString() + '-' + getIdGenerator(host).getAndIncrement(); | |
| 776 | 769 | } |
| 777 | 770 | |
| 778 | 771 | static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| @@ -875,9 +868,12 @@ | ||
| 875 | 868 | boolean doneWork = false; |
| 876 | 869 | FlushItem flush; |
| 877 | 870 | while (null != (flush = queued.poll())) { |
| 878 | - channels.add(flush.channel); | |
| 879 | - flush.channel.write(flush.request).addListener(flush.listener); | |
| 880 | - doneWork = true; | |
| 871 | + Channel channel = flush.channel; | |
| 872 | + if (channel.isActive()) { | |
| 873 | + channels.add(channel); | |
| 874 | + channel.write(flush.request).addListener(flush.listener); | |
| 875 | + doneWork = true; | |
| 876 | + } | |
| 881 | 877 | } |
| 882 | 878 | |
| 883 | 879 | // Always flush what we have (don't artificially delay to try to coalesce more messages) |
| @@ -897,7 +893,7 @@ | ||
| 897 | 893 | } |
| 898 | 894 | |
| 899 | 895 | EventLoop eventLoop = eventLoopRef.get(); |
| 900 | - if (eventLoop != null) { | |
| 896 | + if (eventLoop != null && !eventLoop.isShuttingDown()) { | |
| 901 | 897 | eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS); |
| 902 | 898 | } |
| 903 | 899 | } |
| @@ -1243,16 +1239,16 @@ | ||
| 1243 | 1239 | timeout.cancel(); |
| 1244 | 1240 | } |
| 1245 | 1241 | |
| 1246 | - public void cancelHandler() { | |
| 1242 | + public boolean cancelHandler() { | |
| 1247 | 1243 | if (!isCancelled.compareAndSet(false, true)) |
| 1248 | - return; | |
| 1244 | + return false; | |
| 1249 | 1245 | |
| 1250 | 1246 | // We haven't really received a response: we want to remove the handle because we gave up on that |
| 1251 | 1247 | // request and there is no point in holding the handler, but we don't release the streamId. If we |
| 1252 | 1248 | // were, a new request could reuse that ID but get the answer to the request we just gave up on instead |
| 1253 | 1249 | // of its own answer, and we would have no way to detect that. |
| 1254 | 1250 | connection.dispatcher.removeHandler(this, false); |
| 1255 | - connection.release(); | |
| 1251 | + return true; | |
| 1256 | 1252 | } |
| 1257 | 1253 | |
| 1258 | 1254 | private TimerTask onTimeoutTask() { |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +23 −3
| @@ -128,6 +128,9 @@ | ||
| 128 | 128 | new AbstractReconnectionHandler("Control connection", cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) { |
| 129 | 129 | @Override |
| 130 | 130 | protected Connection tryReconnect() throws ConnectionException { |
| 131 | + if (isShutdown) | |
| 132 | + throw new ConnectionException(null, "Control connection was shut down"); | |
| 133 | + | |
| 131 | 134 | try { |
| 132 | 135 | return reconnectInternal(queryPlan(), false); |
| 133 | 136 | } catch (NoHostAvailableException e) { |
| @@ -141,17 +144,28 @@ | ||
| 141 | 144 | |
| 142 | 145 | @Override |
| 143 | 146 | protected void onReconnection(Connection connection) { |
| 147 | + if (isShutdown) { | |
| 148 | + connection.closeAsync(); | |
| 149 | + return; | |
| 150 | + } | |
| 151 | + | |
| 144 | 152 | setNewConnection(connection); |
| 145 | 153 | } |
| 146 | 154 | |
| 147 | 155 | @Override |
| 148 | 156 | protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { |
| 157 | + if (isShutdown) | |
| 158 | + return false; | |
| 159 | + | |
| 149 | 160 | logger.error("[Control connection] Cannot connect to any host, scheduling retry in {} milliseconds", nextDelayMs); |
| 150 | 161 | return true; |
| 151 | 162 | } |
| 152 | 163 | |
| 153 | 164 | @Override |
| 154 | 165 | protected boolean onUnknownException(Exception e, long nextDelayMs) { |
| 166 | + if (isShutdown) | |
| 167 | + return false; | |
| 168 | + | |
| 155 | 169 | logger.error(String.format("[Control connection] Unknown error during reconnection, scheduling retry in %d milliseconds", nextDelayMs), e); |
| 156 | 170 | return true; |
| 157 | 171 | } |
| @@ -198,7 +212,6 @@ | ||
| 198 | 212 | // Mark the host down right away so that we don't try it again during the initialization process. |
| 199 | 213 | // We don't call cluster.triggerOnDown because it does a bunch of other things we don't want to do here (notify LBP, etc.) |
| 200 | 214 | host.setDown(); |
| 201 | - cluster.startPeriodicReconnectionAttempt(host, true); | |
| 202 | 215 | } |
| 203 | 216 | } catch (ExecutionException e) { |
| 204 | 217 | errors = logError(host, e.getCause(), errors, iter); |
| @@ -604,8 +617,15 @@ | ||
| 604 | 617 | if (host == null) { |
| 605 | 618 | // We don't know that node, create the Host object but wait until we've set the known |
| 606 | 619 | // info before signaling the addition. |
| 607 | - host = cluster.metadata.add(foundHosts.get(i)); | |
| 608 | - isNew = true; | |
| 620 | + Host newHost = cluster.metadata.newHost(foundHosts.get(i)); | |
| 621 | + Host existing = cluster.metadata.addIfAbsent(newHost); | |
| 622 | + if (existing == null) { | |
| 623 | + host = newHost; | |
| 624 | + isNew = true; | |
| 625 | + } else { | |
| 626 | + host = existing; | |
| 627 | + isNew = false; | |
| 628 | + } | |
| 609 | 629 | } |
| 610 | 630 | if (dcs.get(i) != null || racks.get(i) != null) |
| 611 | 631 | updateLocationInfo(host, dcs.get(i), racks.get(i), isInitialConnection, cluster); |
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +16 −33
| @@ -33,31 +33,26 @@ | ||
| 33 | 33 | abstract class ConvictionPolicy { |
| 34 | 34 | |
| 35 | 35 | /** |
| 36 | - * Called when a new connection to the host has been successfully opened. | |
| 36 | + * Called when new connections to the host are about to be created. | |
| 37 | + * | |
| 38 | + * @param count the number of connections | |
| 37 | 39 | */ |
| 38 | - abstract void signalConnectionCreated(); | |
| 40 | + abstract void signalConnectionsOpening(int count); | |
| 39 | 41 | |
| 40 | 42 | /** |
| 41 | 43 | * Called when a connection closed normally. |
| 42 | 44 | */ |
| 43 | - abstract void signalConnectionClosed(); | |
| 45 | + abstract void signalConnectionClosed(Connection connection); | |
| 44 | 46 | |
| 45 | 47 | /** |
| 46 | 48 | * Called when a connection error occurs on a connection to the host this policy applies to. |
| 47 | 49 | * |
| 48 | - * @param exception the connection error that occurred. | |
| 49 | - * @param connectionInitialized whether the connection was initialized. | |
| 50 | 50 | * @return whether the host should be considered down. |
| 51 | 51 | */ |
| 52 | - abstract boolean signalConnectionFailure(ConnectionException exception, boolean connectionInitialized); | |
| 52 | + abstract boolean signalConnectionFailure(Connection connection); | |
| 53 | 53 | |
| 54 | 54 | abstract boolean canReconnectNow(); |
| 55 | 55 | |
| 56 | - /** | |
| 57 | - * Called when the host goes down. | |
| 58 | - */ | |
| 59 | - abstract void reset(); | |
| 60 | - | |
| 61 | 56 | /** |
| 62 | 57 | * Simple factory interface to allow creating {@link ConvictionPolicy} instances. |
| 63 | 58 | */ |
| @@ -86,33 +81,27 @@ | ||
| 86 | 81 | } |
| 87 | 82 | |
| 88 | 83 | @Override |
| 89 | - void signalConnectionCreated() { | |
| 90 | - int newCount = openConnections.incrementAndGet(); | |
| 91 | - Host.statesLogger.debug("[{}] new connection created, total = {}", host, newCount); | |
| 84 | + void signalConnectionsOpening(int count) { | |
| 85 | + int newTotal = openConnections.addAndGet(count); | |
| 86 | + Host.statesLogger.debug("[{}] preparing to open {} new connections, total = {}", host, count, newTotal); | |
| 92 | 87 | resetReconnectionTime(); |
| 93 | 88 | } |
| 94 | 89 | |
| 95 | 90 | @Override |
| 96 | - void signalConnectionClosed() { | |
| 97 | - if (host.state == Host.State.DOWN) | |
| 98 | - return; | |
| 91 | + void signalConnectionClosed(Connection connection) { | |
| 99 | 92 | int remaining = openConnections.decrementAndGet(); |
| 100 | 93 | assert remaining >= 0; |
| 101 | - Host.statesLogger.debug("[{}] connection closed, remaining = {}", host, remaining); | |
| 94 | + Host.statesLogger.debug("[{}] {} closed, remaining = {}", host, connection, remaining); | |
| 102 | 95 | } |
| 103 | 96 | |
| 104 | 97 | @Override |
| 105 | - boolean signalConnectionFailure(ConnectionException exception, boolean wasFullyInitialized) { | |
| 106 | - if (host.state == Host.State.DOWN) | |
| 107 | - return false; | |
| 108 | - | |
| 109 | - updateReconnectionTime(); | |
| 110 | - int remaining = (wasFullyInitialized) | |
| 111 | - ? openConnections.decrementAndGet() | |
| 112 | - : openConnections.get(); | |
| 98 | + boolean signalConnectionFailure(Connection connection) { | |
| 99 | + if (host.state != Host.State.DOWN) | |
| 100 | + updateReconnectionTime(); | |
| 113 | 101 | |
| 102 | + int remaining = openConnections.decrementAndGet(); | |
| 114 | 103 | assert remaining >= 0; |
| 115 | - Host.statesLogger.debug("[{}] remaining connections = {}", host, remaining); | |
| 104 | + Host.statesLogger.debug("[{}] {} failed, remaining = {}", host, connection, remaining); | |
| 116 | 105 | return remaining == 0; |
| 117 | 106 | } |
| 118 | 107 | |
| @@ -141,12 +130,6 @@ | ||
| 141 | 130 | System.nanoTime() >= nextReconnectionTime; |
| 142 | 131 | } |
| 143 | 132 | |
| 144 | - @Override | |
| 145 | - synchronized void reset() { | |
| 146 | - openConnections.set(0); | |
| 147 | - resetReconnectionTime(); | |
| 148 | - } | |
| 149 | - | |
| 150 | 133 | static class Factory implements ConvictionPolicy.Factory { |
| 151 | 134 | |
| 152 | 135 | @Override |
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +0 −1
| @@ -275,7 +275,6 @@ | ||
| 275 | 275 | |
| 276 | 276 | void setDown() { |
| 277 | 277 | state = State.DOWN; |
| 278 | - convictionPolicy.reset(); | |
| 279 | 278 | } |
| 280 | 279 | |
| 281 | 280 | void setUp() { |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +15 −33
| @@ -105,28 +105,26 @@ | ||
| 105 | 105 | * pool. |
| 106 | 106 | */ |
| 107 | 107 | ListenableFuture<Void> initAsync(Connection reusedConnection) { |
| 108 | - String keyspace = manager.poolsState.keyspace; | |
| 109 | - | |
| 110 | 108 | Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); |
| 111 | 109 | |
| 112 | 110 | // Create initial core connections |
| 113 | 111 | final int coreSize = options().getCoreConnectionsPerHost(hostDistance); |
| 114 | 112 | final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize); |
| 115 | 113 | final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(coreSize); |
| 116 | - for (int i = 0; i < coreSize; i++) { | |
| 117 | - Connection connection; | |
| 118 | - ListenableFuture<Void> connectionFuture; | |
| 119 | - // reuse the existing connection only once | |
| 120 | - if (reusedConnection != null && reusedConnection.setOwner(this)) { | |
| 121 | - connection = reusedConnection; | |
| 122 | - connectionFuture = MoreFutures.VOID_SUCCESS; | |
| 123 | - } else { | |
| 124 | - connection = manager.connectionFactory().newConnection(this); | |
| 125 | - connectionFuture = connection.initAsync(); | |
| 126 | - } | |
| 127 | - reusedConnection = null; | |
| 128 | - connections.add(connection); | |
| 129 | - connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor)); | |
| 114 | + | |
| 115 | + int toCreate = coreSize; | |
| 116 | + | |
| 117 | + if (reusedConnection != null && reusedConnection.setOwner(this)) { | |
| 118 | + toCreate -= 1; | |
| 119 | + connections.add(reusedConnection); | |
| 120 | + connectionFutures.add(MoreFutures.VOID_SUCCESS); | |
| 121 | + } | |
| 122 | + | |
| 123 | + List<Connection> newConnections = manager.connectionFactory().newConnections(this, toCreate); | |
| 124 | + connections.addAll(newConnections); | |
| 125 | + for (Connection connection : newConnections) { | |
| 126 | + ListenableFuture<Void> connectionFuture = connection.initAsync(); | |
| 127 | + connectionFutures.add(handleErrors(connectionFuture, initExecutor)); | |
| 130 | 128 | } |
| 131 | 129 | |
| 132 | 130 | ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures); |
| @@ -175,7 +173,6 @@ | ||
| 175 | 173 | // accordingly in SessionManager#maybeAddPool. |
| 176 | 174 | Throwables.propagateIfInstanceOf(t, ClusterNameMismatchException.class); |
| 177 | 175 | Throwables.propagateIfInstanceOf(t, UnsupportedProtocolVersionException.class); |
| 178 | - Throwables.propagateIfInstanceOf(t, SetKeyspaceException.class); | |
| 179 | 176 | |
| 180 | 177 | // We don't want to swallow Errors either as they probably indicate a more serious issue (OOME...) |
| 181 | 178 | Throwables.propagateIfInstanceOf(t, Error.class); |
| @@ -186,17 +183,6 @@ | ||
| 186 | 183 | }, executor); |
| 187 | 184 | } |
| 188 | 185 | |
| 189 | - private ListenableFuture<Void> setKeyspaceAsync(ListenableFuture<Void> initFuture, final Connection connection, final String keyspace) { | |
| 190 | - return (keyspace == null) | |
| 191 | - ? initFuture | |
| 192 | - : Futures.transform(initFuture, new AsyncFunction<Void, Void>() { | |
| 193 | - @Override | |
| 194 | - public ListenableFuture<Void> apply(Void input) throws Exception { | |
| 195 | - return connection.setKeyspaceAsync(keyspace); | |
| 196 | - } | |
| 197 | - }); | |
| 198 | - } | |
| 199 | - | |
| 200 | 186 | // Clean up if we got a fatal error at construction time but still created part of the core connections |
| 201 | 187 | private void forceClose(List<Connection> connections) { |
| 202 | 188 | for (Connection connection : connections) { |
| @@ -528,7 +514,7 @@ | ||
| 528 | 514 | } |
| 529 | 515 | |
| 530 | 516 | private void maybeSpawnNewConnection() { |
| 531 | - if (!host.convictionPolicy.canReconnectNow()) | |
| 517 | + if (isClosed() || !host.convictionPolicy.canReconnectNow()) | |
| 532 | 518 | return; |
| 533 | 519 | |
| 534 | 520 | while (true) { |
| @@ -687,10 +673,6 @@ | ||
| 687 | 673 | static class PoolState { |
| 688 | 674 | volatile String keyspace; |
| 689 | 675 | |
| 690 | - PoolState(String keyspace) { | |
| 691 | - this.keyspace = keyspace; | |
| 692 | - } | |
| 693 | - | |
| 694 | 676 | void setKeyspace(String keyspace) { |
| 695 | 677 | this.keyspace = keyspace; |
| 696 | 678 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +10 −3
| @@ -361,10 +361,17 @@ | ||
| 361 | 361 | this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values()); |
| 362 | 362 | } |
| 363 | 363 | |
| 364 | + Host newHost(InetSocketAddress address) { | |
| 365 | + return new Host(address, cluster.convictionPolicyFactory, cluster); | |
| 366 | + } | |
| 367 | + | |
| 368 | + Host addIfAbsent(Host host) { | |
| 369 | + Host previous = hosts.putIfAbsent(host.getSocketAddress(), host); | |
| 370 | + return previous == null ? host : null; | |
| 371 | + } | |
| 372 | + | |
| 364 | 373 | Host add(InetSocketAddress address) { |
| 365 | - Host newHost = new Host(address, cluster.convictionPolicyFactory, cluster); | |
| 366 | - Host previous = hosts.putIfAbsent(address, newHost); | |
| 367 | - return previous == null ? newHost : null; | |
| 374 | + return addIfAbsent(newHost(address)); | |
| 368 | 375 | } |
| 369 | 376 | |
| 370 | 377 | boolean remove(Host host) { |
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +4 −9
| @@ -183,22 +183,17 @@ | ||
| 183 | 183 | * <p> |
| 184 | 184 | * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required. |
| 185 | 185 | * <p> |
| 186 | - * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully(long, long, TimeUnit) graceful shutdown} | |
| 187 | - * of the passed {@link EventLoopGroup} instance with no "quiet period" and a timeout of 15 seconds; | |
| 188 | - * then waits uninterruptibly for the shutdown to complete, or the timeout to occur, whichever happens first. | |
| 186 | + * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully() graceful shutdown} | |
| 187 | + * of the passed {@link EventLoopGroup}, then waits uninterruptibly for the shutdown to complete or timeout. | |
| 189 | 188 | * <p> |
| 190 | 189 | * Implementation note: if the {@link EventLoopGroup} instance is being shared, or used for other purposes than to |
| 191 | - * coordinate Netty events for the current cluster, than it should not be shut down here; | |
| 190 | + * coordinate Netty events for the current cluster, then it should not be shut down here; | |
| 192 | 191 | * subclasses would have to override this method accordingly to take the appropriate action. |
| 193 | 192 | * |
| 194 | 193 | * @param eventLoopGroup the event loop group used by the cluster being closed |
| 195 | 194 | */ |
| 196 | 195 | public void onClusterClose(EventLoopGroup eventLoopGroup) { |
| 197 | - // shutdownGracefully with default parameters employs a quiet period of 2 seconds | |
| 198 | - // where in pre-Netty4 versions, closing a cluster instance was very quick (milliseconds). | |
| 199 | - // Since we close the channels before shutting down the eventLoopGroup, | |
| 200 | - // it is safe to reduce the quiet period to 0 seconds | |
| 201 | - eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly(); | |
| 196 | + eventLoopGroup.shutdownGracefully().syncUninterruptibly(); | |
| 202 | 197 | } |
| 203 | 198 | |
| 204 | 199 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +1 −1
| @@ -168,7 +168,7 @@ | ||
| 168 | 168 | public static final Logger SLOW_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.SLOW"); |
| 169 | 169 | |
| 170 | 170 | /** |
| 171 | - * The logger used to log unsuccessful queries, i.e., queries that did not completed normally and threw an exception. | |
| 171 | + * The logger used to log unsuccessful queries, i.e., queries that did not complete normally and threw an exception. | |
| 172 | 172 | * <p> |
| 173 | 173 | * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}. |
| 174 | 174 | * Additionally, if the level is set to {@code TRACE} and the statement being logged is a {@link BoundStatement}, |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +7 −4
| @@ -352,8 +352,8 @@ | ||
| 352 | 352 | // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have |
| 353 | 353 | // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice, |
| 354 | 354 | // but it knows how to deal with it). |
| 355 | - if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS) | |
| 356 | - connectionHandler.cancelHandler(); | |
| 355 | + if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS && connectionHandler.cancelHandler()) | |
| 356 | + connection.release(); | |
| 357 | 357 | } |
| 358 | 358 | |
| 359 | 359 | private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { |
| @@ -391,8 +391,8 @@ | ||
| 391 | 391 | logger.trace("[{}] Cancelled while in progress", id); |
| 392 | 392 | // The connectionHandler should be non-null, but we might miss the update if we're racing with write(). |
| 393 | 393 | // If it's still null, this will be handled by re-checking queryStateRef at the end of write(). |
| 394 | - if (connectionHandler != null) | |
| 395 | - connectionHandler.cancelHandler(); | |
| 394 | + if (connectionHandler != null && connectionHandler.cancelHandler()) | |
| 395 | + connectionHandler.connection.release(); | |
| 396 | 396 | return; |
| 397 | 397 | } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) { |
| 398 | 398 | if(logger.isTraceEnabled()) |
| @@ -671,6 +671,7 @@ | ||
| 671 | 671 | retryCount, queryState, queryStateRef.get()); |
| 672 | 672 | return false; |
| 673 | 673 | } |
| 674 | + connection.release(); | |
| 674 | 675 | logError(connection.address, new DriverException("Timeout waiting for response to prepare message")); |
| 675 | 676 | retry(false, null); |
| 676 | 677 | return true; |
| @@ -723,6 +724,8 @@ | ||
| 723 | 724 | Host queriedHost = current; |
| 724 | 725 | OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address); |
| 725 | 726 | try { |
| 727 | + connection.release(); | |
| 728 | + | |
| 726 | 729 | logError(connection.address, timeoutException); |
| 727 | 730 | retry(false, null); |
| 728 | 731 | } catch (Exception e) { |
modified driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java +1 −7
| @@ -24,8 +24,6 @@ | ||
| 24 | 24 | */ |
| 25 | 25 | public class SSLOptions { |
| 26 | 26 | |
| 27 | - private static final String SSL_PROTOCOL = "TLS"; | |
| 28 | - | |
| 29 | 27 | /** |
| 30 | 28 | * The default SSL cipher suites. |
| 31 | 29 | */ |
| @@ -63,12 +61,8 @@ | ||
| 63 | 61 | |
| 64 | 62 | private static SSLContext makeDefaultContext() throws IllegalStateException { |
| 65 | 63 | try { |
| 66 | - SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL); | |
| 67 | - ctx.init(null, null, null); // use defaults | |
| 68 | - return ctx; | |
| 64 | + return SSLContext.getDefault(); | |
| 69 | 65 | } catch (NoSuchAlgorithmException e) { |
| 70 | - throw new RuntimeException("This JVM doesn't support TLS, this shouldn't happen"); | |
| 71 | - } catch (KeyManagementException e) { | |
| 72 | 66 | throw new IllegalStateException("Cannot initialize SSL Context", e); |
| 73 | 67 | } |
| 74 | 68 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +9 −17
| @@ -21,9 +21,7 @@ | ||
| 21 | 21 | import java.util.concurrent.*; |
| 22 | 22 | import java.util.concurrent.atomic.AtomicReference; |
| 23 | 23 | |
| 24 | -import com.google.common.base.Function; | |
| 25 | 24 | import com.google.common.base.Functions; |
| 26 | -import com.google.common.base.Throwables; | |
| 27 | 25 | import com.google.common.collect.ImmutableList; |
| 28 | 26 | import com.google.common.collect.Lists; |
| 29 | 27 | import com.google.common.util.concurrent.*; |
| @@ -56,10 +54,10 @@ | ||
| 56 | 54 | private volatile boolean isClosing; |
| 57 | 55 | |
| 58 | 56 | // Package protected, only Cluster should construct that. |
| 59 | - SessionManager(Cluster cluster, String keyspace) { | |
| 57 | + SessionManager(Cluster cluster) { | |
| 60 | 58 | this.cluster = cluster; |
| 61 | 59 | this.pools = new ConcurrentHashMap<Host, HostConnectionPool>(); |
| 62 | - this.poolsState = new HostConnectionPool.PoolState(keyspace); | |
| 60 | + this.poolsState = new HostConnectionPool.PoolState(); | |
| 63 | 61 | } |
| 64 | 62 | |
| 65 | 63 | public Session init() { |
| @@ -113,7 +111,7 @@ | ||
| 113 | 111 | List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size()); |
| 114 | 112 | for (Host host : hosts) |
| 115 | 113 | if (host.state != Host.State.DOWN) |
| 116 | - futures.add(maybeAddPool(host, null, true)); | |
| 114 | + futures.add(maybeAddPool(host, null)); | |
| 117 | 115 | return Futures.allAsList(futures); |
| 118 | 116 | } |
| 119 | 117 | |
| @@ -278,7 +276,7 @@ | ||
| 278 | 276 | |
| 279 | 277 | @Override |
| 280 | 278 | public void onFailure(Throwable t) { |
| 281 | - logger.error("Error creating pool to " + host, t); | |
| 279 | + logger.warn("Error creating pool to " + host, t); | |
| 282 | 280 | future.set(false); |
| 283 | 281 | } |
| 284 | 282 | }); |
| @@ -328,7 +326,7 @@ | ||
| 328 | 326 | } |
| 329 | 327 | |
| 330 | 328 | // Returns whether there was problem creating the pool |
| 331 | - ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) { | |
| 329 | + ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) { | |
| 332 | 330 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 333 | 331 | if (distance == HostDistance.IGNORED) |
| 334 | 332 | return Futures.immediateFuture(true); |
| @@ -361,11 +359,8 @@ | ||
| 361 | 359 | ClusterNameMismatchException e = (ClusterNameMismatchException)t; |
| 362 | 360 | cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); |
| 363 | 361 | cluster.manager.triggerOnDown(host, false); |
| 364 | - } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) { | |
| 365 | - future.setException(t.getCause()); | |
| 366 | - return; | |
| 367 | 362 | } else { |
| 368 | - logger.error("Error creating pool to " + host, t); | |
| 363 | + logger.warn("Error creating pool to " + host, t); | |
| 369 | 364 | } |
| 370 | 365 | future.set(false); |
| 371 | 366 | } |
| @@ -409,7 +404,7 @@ | ||
| 409 | 404 | |
| 410 | 405 | if (pool == null) { |
| 411 | 406 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 412 | - poolCreatedFutures.add(maybeAddPool(h, null, false)); | |
| 407 | + poolCreatedFutures.add(maybeAddPool(h, null)); | |
| 413 | 408 | } else if (dist != pool.hostDistance) { |
| 414 | 409 | if (dist == HostDistance.IGNORED) { |
| 415 | 410 | toRemove.add(h); |
| @@ -443,7 +438,7 @@ | ||
| 443 | 438 | if (pool == null) { |
| 444 | 439 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 445 | 440 | try { |
| 446 | - maybeAddPool(h, null, false).get(); | |
| 441 | + maybeAddPool(h, null).get(); | |
| 447 | 442 | } catch (ExecutionException e) { |
| 448 | 443 | // Ignore, maybeAddPool has already handled the error |
| 449 | 444 | } |
| @@ -607,10 +602,7 @@ | ||
| 607 | 602 | @Override |
| 608 | 603 | public void onFailure(Throwable t) { |
| 609 | 604 | logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t); |
| 610 | - | |
| 611 | - // If the query timed out, that already released the connection, otherwise do it now | |
| 612 | - if (!(t instanceof OperationTimedOutException)) | |
| 613 | - c.release(); | |
| 605 | + c.release(); | |
| 614 | 606 | } |
| 615 | 607 | }); |
| 616 | 608 | futures.add(future); |
deleted driver-core/src/main/java/com/datastax/driver/core/SetKeyspaceException.java +0 −23
| @@ -1,23 +0,0 @@ | ||
| 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/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +107 −88
| @@ -21,19 +21,15 @@ | ||
| 21 | 21 | import java.util.concurrent.CopyOnWriteArrayList; |
| 22 | 22 | import java.util.concurrent.atomic.AtomicInteger; |
| 23 | 23 | |
| 24 | +import com.google.common.annotations.VisibleForTesting; | |
| 24 | 25 | import com.google.common.base.Joiner; |
| 26 | +import com.google.common.base.Preconditions; | |
| 25 | 27 | import com.google.common.base.Strings; |
| 26 | -import com.google.common.annotations.VisibleForTesting; | |
| 27 | 28 | import com.google.common.collect.AbstractIterator; |
| 28 | 29 | import org.slf4j.Logger; |
| 29 | 30 | import org.slf4j.LoggerFactory; |
| 30 | 31 | |
| 31 | -import com.datastax.driver.core.Cluster; | |
| 32 | -import com.datastax.driver.core.Configuration; | |
| 33 | -import com.datastax.driver.core.ConsistencyLevel; | |
| 34 | -import com.datastax.driver.core.Host; | |
| 35 | -import com.datastax.driver.core.HostDistance; | |
| 36 | -import com.datastax.driver.core.Statement; | |
| 32 | +import com.datastax.driver.core.*; | |
| 37 | 33 | |
| 38 | 34 | /** |
| 39 | 35 | * A data-center aware Round-robin load balancing policy. |
| @@ -46,15 +42,23 @@ | ||
| 46 | 42 | * data center can be reached. |
| 47 | 43 | * <p> |
| 48 | 44 | * If used with a single data center, this policy is equivalent to the |
| 49 | - * {@code LoadBalancingPolicy.RoundRobin} policy, but its DC awareness | |
| 50 | - * incurs a slight overhead so the {@code LoadBalancingPolicy.RoundRobin} | |
| 51 | - * policy could be preferred to this policy in that case. | |
| 45 | + * {@link RoundRobinPolicy}, but its DC awareness incurs a slight overhead | |
| 46 | + * so the latter should be preferred to this policy in that case. | |
| 52 | 47 | */ |
| 53 | 48 | public class DCAwareRoundRobinPolicy implements LoadBalancingPolicy, CloseableLoadBalancingPolicy { |
| 54 | 49 | |
| 55 | 50 | private static final Logger logger = LoggerFactory.getLogger(DCAwareRoundRobinPolicy.class); |
| 56 | 51 | |
| 57 | - private final String UNSET = ""; | |
| 52 | + /** | |
| 53 | + * Returns a builder to create a new instance. | |
| 54 | + * | |
| 55 | + * @return the builder. | |
| 56 | + */ | |
| 57 | + public static Builder builder() { | |
| 58 | + return new Builder(); | |
| 59 | + } | |
| 60 | + | |
| 61 | + private static final String UNSET = ""; | |
| 58 | 62 | |
| 59 | 63 | private final ConcurrentMap<String, CopyOnWriteArrayList<Host>> perDcLiveHosts = new ConcurrentHashMap<String, CopyOnWriteArrayList<Host>>(); |
| 60 | 64 | private final AtomicInteger index = new AtomicInteger(); |
| @@ -68,101 +72,35 @@ | ||
| 68 | 72 | private volatile Configuration configuration; |
| 69 | 73 | |
| 70 | 74 | /** |
| 71 | - * Creates a new datacenter aware round robin policy that auto-discover | |
| 72 | - * the local data-center. | |
| 73 | - * <p> | |
| 74 | - * If this constructor is used, the data-center used as local will the | |
| 75 | - * data-center of the first Cassandra node the driver connects to. This | |
| 76 | - * will always be ok if all the contact points use at {@code Cluster} | |
| 77 | - * creation are in the local data-center. If it's not the case, you should | |
| 78 | - * provide the local data-center name yourself by using one of the other | |
| 79 | - * constructor of this class. | |
| 80 | - * <p> | |
| 81 | - * This constructor is a shortcut for {@code new DCAwareRoundRobinPolicy(null)}, | |
| 82 | - * and as such will ignore all hosts in remote data-centers. | |
| 75 | + * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for | |
| 76 | + * backward-compatibility purposes, it is equivalent to {@code DCAwareRoundRobinPolicy.builder().build()}. | |
| 83 | 77 | */ |
| 78 | + @Deprecated | |
| 84 | 79 | public DCAwareRoundRobinPolicy() { |
| 85 | 80 | this(null, 0, false, true); |
| 86 | 81 | } |
| 87 | 82 | |
| 88 | 83 | /** |
| 89 | - * Creates a new datacenter aware round robin policy given the name of | |
| 90 | - * the local datacenter. | |
| 91 | - * <p> | |
| 92 | - * The name of the local datacenter provided must be the local | |
| 93 | - * datacenter name as known by Cassandra. | |
| 94 | - * <p> | |
| 95 | - * The policy created will ignore all remote hosts. In other words, | |
| 96 | - * this is equivalent to {@code new DCAwareRoundRobinPolicy(localDc, 0)}. | |
| 97 | - * | |
| 98 | - * @param localDc the name of the local datacenter (as known by | |
| 99 | - * Cassandra). If this is {@code null}, the policy will default to the | |
| 100 | - * data-center of the first node connected to. | |
| 84 | + * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for | |
| 85 | + * backward-compatibility purposes, it is equivalent to {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).build()}. | |
| 101 | 86 | */ |
| 102 | 87 | public DCAwareRoundRobinPolicy(String localDc) { |
| 103 | 88 | this(localDc, 0, false, false); |
| 104 | 89 | } |
| 105 | 90 | |
| 106 | 91 | /** |
| 107 | - * Creates a new DCAwareRoundRobin policy given the name of the local | |
| 108 | - * datacenter and that uses the provided number of host per remote | |
| 109 | - * datacenter as failover for the local hosts. | |
| 110 | - * <p> | |
| 111 | - * The name of the local datacenter provided must be the local | |
| 112 | - * datacenter name as known by Cassandra. | |
| 113 | - * <p> | |
| 114 | - * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host | |
| 115 | - * in the local datacenter can be reached and if the consistency | |
| 116 | - * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, | |
| 117 | - * then up to {@code usedHostsPerRemoteDc} host per remote data-center | |
| 118 | - * will be tried by the policy as a fallback. Please note that no | |
| 119 | - * remote host will be used for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} | |
| 120 | - * since this would change the meaning of the consistency level (and | |
| 121 | - * thus somewhat break the consistency contract). | |
| 122 | - * | |
| 123 | - * @param localDc the name of the local datacenter (as known by | |
| 124 | - * Cassandra). If this is {@code null}, the policy will default to the | |
| 125 | - * data-center of the first node connected to. | |
| 126 | - * @param usedHostsPerRemoteDc the number of host per remote | |
| 127 | - * datacenter that policies created by the returned factory should | |
| 128 | - * consider. Created policies {@code distance} method will return a | |
| 129 | - * {@code HostDistance.REMOTE} distance for only {@code | |
| 130 | - * usedHostsPerRemoteDc} hosts per remote datacenter. Other hosts | |
| 131 | - * of the remote datacenters will be ignored (and thus no | |
| 132 | - * connections to them will be maintained). | |
| 92 | + * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for | |
| 93 | + * backward-compatibility purposes, it is equivalent to | |
| 94 | + * {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).withUsedHostsPerRemoteDc(usedHostsPerRemoteDc).build()}. | |
| 133 | 95 | */ |
| 134 | 96 | public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc) { |
| 135 | 97 | this(localDc, usedHostsPerRemoteDc, false, false); |
| 136 | 98 | } |
| 137 | 99 | |
| 138 | 100 | /** |
| 139 | - * Creates a new DCAwareRoundRobin policy given the name of the local | |
| 140 | - * datacenter and that uses the provided number of host per remote | |
| 141 | - * datacenter as failover for the local hosts. | |
| 142 | - * <p> | |
| 143 | - * This constructor is equivalent to {@link #DCAwareRoundRobinPolicy(String, int)} | |
| 144 | - * but allows to override the policy of never using remote data-center | |
| 145 | - * nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is | |
| 146 | - * however inadvisable to do so in almost all cases, as this would | |
| 147 | - * potentially break consistency guarantees and if you are fine with that, | |
| 148 | - * it's probably better to use a weaker consitency like {@code ONE}, {@code | |
| 149 | - * TWO} or {@code THREE}. As such, this constructor should generally | |
| 150 | - * be avoided in favor of {@link #DCAwareRoundRobinPolicy(String, int)}. | |
| 151 | - * Use it only if you know and understand what you do. | |
| 152 | - * | |
| 153 | - * @param localDc the name of the local datacenter (as known by | |
| 154 | - * Cassandra). If this is {@code null}, the policy will default to the | |
| 155 | - * data-center of the first node connected to. | |
| 156 | - * @param usedHostsPerRemoteDc the number of host per remote | |
| 157 | - * datacenter that policies created by the returned factory should | |
| 158 | - * consider. Created policies {@code distance} method will return a | |
| 159 | - * {@code HostDistance.REMOTE} distance for only {@code | |
| 160 | - * usedHostsPerRemoteDc} hosts per remote datacenter. Other hosts | |
| 161 | - * of the remote datacenters will be ignored (and thus no | |
| 162 | - * connections to them will be maintained). | |
| 163 | - * @param allowRemoteDCsForLocalConsistencyLevel whether or not the | |
| 164 | - * policy may return remote host when building query plan for query | |
| 165 | - * having consitency {@code LOCAL_ONE} and {@code LOCAL_QUORUM}. | |
| 101 | + * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for | |
| 102 | + * backward-compatibility purposes, it is equivalent to | |
| 103 | + * {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).withUsedHostsPerRemoteDc(usedHostsPerRemoteDc).allowRemoteDCsForLocalConsistencyLevel().build()}. | |
| 166 | 104 | */ |
| 167 | 105 | public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc, boolean allowRemoteDCsForLocalConsistencyLevel) { |
| 168 | 106 | this(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, false); |
| @@ -382,4 +320,85 @@ | ||
| 382 | 320 | public void close() { |
| 383 | 321 | // nothing to do |
| 384 | 322 | } |
| 323 | + | |
| 324 | + /** | |
| 325 | + * Helper class to build the policy. | |
| 326 | + */ | |
| 327 | + public static class Builder { | |
| 328 | + private String localDc; | |
| 329 | + private int usedHostsPerRemoteDc; | |
| 330 | + private boolean allowRemoteDCsForLocalConsistencyLevel; | |
| 331 | + | |
| 332 | + /** | |
| 333 | + * Sets the name of the datacenter that will be considered "local" by the policy. | |
| 334 | + * <p> | |
| 335 | + * This must be the name as known by Cassandra (in other words, the name in that appears in | |
| 336 | + * {@code system.peers}, or in the output of admin tools like nodetool). | |
| 337 | + * <p> | |
| 338 | + * If this method isn't called, the policy will default to the datacenter of the first node | |
| 339 | + * connected to. This will always be ok if all the contact points use at {@code Cluster} | |
| 340 | + * creation are in the local data-center. Otherwise, you should provide the name yourself | |
| 341 | + * with this method. | |
| 342 | + * | |
| 343 | + * @param localDc the name of the datacenter. It should not be {@code null}. | |
| 344 | + * @return this builder. | |
| 345 | + */ | |
| 346 | + public Builder withLocalDc(String localDc) { | |
| 347 | + Preconditions.checkArgument(!Strings.isNullOrEmpty(localDc), | |
| 348 | + "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC"); | |
| 349 | + this.localDc = localDc; | |
| 350 | + return this; | |
| 351 | + } | |
| 352 | + | |
| 353 | + /** | |
| 354 | + * Sets the number of hosts per remote datacenter that the policy should consider. | |
| 355 | + * <p> | |
| 356 | + * The policy's {@code distance()} method will return a {@code HostDistance.REMOTE} distance for only {@code usedHostsPerRemoteDc} | |
| 357 | + * hosts per remote datacenter. Other hosts of the remote datacenters will be ignored (and thus no connections to them will be | |
| 358 | + * maintained). | |
| 359 | + * <p> | |
| 360 | + * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host in the local datacenter can be reached and if the consistency | |
| 361 | + * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, then up to {@code usedHostsPerRemoteDc} hosts per remote | |
| 362 | + * datacenter will be tried by the policy as a fallback. By default, no remote host will be used for {@code LOCAL_ONE} and | |
| 363 | + * {@code LOCAL_QUORUM}, since this would change the meaning of the consistency level, somewhat breaking the consistency contract | |
| 364 | + * (this can be overridden with {@link #allowRemoteDCsForLocalConsistencyLevel()}). | |
| 365 | + * <p> | |
| 366 | + * If this method isn't called, the policy will default to 0. | |
| 367 | + * | |
| 368 | + * @param usedHostsPerRemoteDc the number. | |
| 369 | + * @return this builder. | |
| 370 | + */ | |
| 371 | + public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) { | |
| 372 | + Preconditions.checkArgument(usedHostsPerRemoteDc >= 0, | |
| 373 | + "usedHostsPerRemoteDc must be equal or greater than 0"); | |
| 374 | + this.usedHostsPerRemoteDc = usedHostsPerRemoteDc; | |
| 375 | + return this; | |
| 376 | + } | |
| 377 | + | |
| 378 | + /** | |
| 379 | + * Allows the policy to return remote hosts when building query plans for queries having consistency level {@code LOCAL_ONE} | |
| 380 | + * or {@code LOCAL_QUORUM}. | |
| 381 | + * <p> | |
| 382 | + * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of | |
| 383 | + * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do | |
| 384 | + * so in almost all cases, as this would potentially break consistency guarantees and if you are fine with that, it's probably | |
| 385 | + * better to use a weaker consitency like {@code ONE}, {@code TWO} or {@code THREE}. As such, this method should generally be | |
| 386 | + * avoided; use it only if you know and understand what you do. | |
| 387 | + * | |
| 388 | + * @return this builder. | |
| 389 | + */ | |
| 390 | + public Builder allowRemoteDCsForLocalConsistencyLevel() { | |
| 391 | + this.allowRemoteDCsForLocalConsistencyLevel = true; | |
| 392 | + return this; | |
| 393 | + } | |
| 394 | + | |
| 395 | + /** | |
| 396 | + * Builds the policy configured by this builder. | |
| 397 | + * | |
| 398 | + * @return the policy. | |
| 399 | + */ | |
| 400 | + public DCAwareRoundRobinPolicy build() { | |
| 401 | + return new DCAwareRoundRobinPolicy(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, true); | |
| 402 | + } | |
| 403 | + } | |
| 385 | 404 | } |
added driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java +184 −0
| @@ -0,0 +1,184 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import java.net.InetSocketAddress; | |
| 19 | +import java.util.ArrayList; | |
| 20 | +import java.util.Collection; | |
| 21 | +import java.util.Iterator; | |
| 22 | +import java.util.List; | |
| 23 | + | |
| 24 | +import com.google.common.base.Predicate; | |
| 25 | +import com.google.common.base.Predicates; | |
| 26 | +import com.google.common.collect.ImmutableSet; | |
| 27 | + | |
| 28 | +import com.datastax.driver.core.Cluster; | |
| 29 | +import com.datastax.driver.core.Host; | |
| 30 | +import com.datastax.driver.core.HostDistance; | |
| 31 | +import com.datastax.driver.core.Statement; | |
| 32 | + | |
| 33 | +/** | |
| 34 | + * A load balancing policy wrapper that ensures that only hosts matching the predicate | |
| 35 | + * will ever be returned. | |
| 36 | + * <p> | |
| 37 | + * This policy wraps another load balancing policy and will delegate the choice | |
| 38 | + * of hosts to the wrapped policy with the exception that only hosts matching | |
| 39 | + * the predicate provided when constructing this policy will ever be | |
| 40 | + * returned. Any host not matching the predicate will be considered {@code IGNORED} | |
| 41 | + * and thus will not be connected to. | |
| 42 | + */ | |
| 43 | +public class HostFilterPolicy implements ChainableLoadBalancingPolicy, CloseableLoadBalancingPolicy { | |
| 44 | + private final LoadBalancingPolicy childPolicy; | |
| 45 | + private final Predicate<Host> predicate; | |
| 46 | + | |
| 47 | + /** | |
| 48 | + * Create a new policy that wraps the provided child policy but only "allows" hosts | |
| 49 | + * matching the predicate. | |
| 50 | + * | |
| 51 | + * @param childPolicy the wrapped policy. | |
| 52 | + * @param predicate the host predicate. Only hosts matching this predicate may get connected | |
| 53 | + * to (whether they will get connected to or not depends on the child policy). | |
| 54 | + */ | |
| 55 | + public HostFilterPolicy(LoadBalancingPolicy childPolicy, Predicate<Host> predicate) { | |
| 56 | + this.childPolicy = childPolicy; | |
| 57 | + this.predicate = predicate; | |
| 58 | + } | |
| 59 | + | |
| 60 | + @Override | |
| 61 | + public LoadBalancingPolicy getChildPolicy() { | |
| 62 | + return childPolicy; | |
| 63 | + } | |
| 64 | + | |
| 65 | + /** | |
| 66 | + * {@inheritDoc} | |
| 67 | + * | |
| 68 | + * @throws IllegalArgumentException if none of the host in {@code hosts} | |
| 69 | + * (which will correspond to the contact points) matches the predicate. | |
| 70 | + */ | |
| 71 | + @Override | |
| 72 | + public void init(Cluster cluster, Collection<Host> hosts) { | |
| 73 | + List<Host> whiteHosts = new ArrayList<Host>(hosts.size()); | |
| 74 | + for (Host host : hosts) | |
| 75 | + if (predicate.apply(host)) | |
| 76 | + whiteHosts.add(host); | |
| 77 | + | |
| 78 | + if (whiteHosts.isEmpty()) | |
| 79 | + throw new IllegalArgumentException(String.format("Cannot use HostFilterPolicy where the filter allows none of the contacts points (%s)", hosts)); | |
| 80 | + | |
| 81 | + childPolicy.init(cluster, whiteHosts); | |
| 82 | + } | |
| 83 | + | |
| 84 | + /** | |
| 85 | + * {@inheritDoc} | |
| 86 | + * | |
| 87 | + * @return {@link HostDistance#IGNORED} if {@code host} is not matching the predicate, the HostDistance | |
| 88 | + * as returned by the wrapped policy otherwise. | |
| 89 | + */ | |
| 90 | + @Override | |
| 91 | + public HostDistance distance(Host host) { | |
| 92 | + return predicate.apply(host) | |
| 93 | + ? childPolicy.distance(host) | |
| 94 | + : HostDistance.IGNORED; | |
| 95 | + } | |
| 96 | + | |
| 97 | + /** | |
| 98 | + * {@inheritDoc} | |
| 99 | + * <p> | |
| 100 | + * It is guaranteed that only hosts matching the predicate will be returned. | |
| 101 | + */ | |
| 102 | + @Override | |
| 103 | + public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 104 | + // Just delegate to the child policy, since we filter the hosts not white | |
| 105 | + // listed upfront, the child policy will never see a host that is not white | |
| 106 | + // listed and thus can't return one. | |
| 107 | + return childPolicy.newQueryPlan(loggedKeyspace, statement); | |
| 108 | + } | |
| 109 | + | |
| 110 | + @Override | |
| 111 | + public void onUp(Host host) { | |
| 112 | + if (predicate.apply(host)) | |
| 113 | + childPolicy.onUp(host); | |
| 114 | + } | |
| 115 | + | |
| 116 | + @SuppressWarnings("deprecation") | |
| 117 | + @Override | |
| 118 | + public void onSuspected(Host host) { | |
| 119 | + if (predicate.apply(host)) | |
| 120 | + childPolicy.onSuspected(host); | |
| 121 | + } | |
| 122 | + | |
| 123 | + @Override | |
| 124 | + public void onDown(Host host) { | |
| 125 | + if (predicate.apply(host)) | |
| 126 | + childPolicy.onDown(host); | |
| 127 | + } | |
| 128 | + | |
| 129 | + @Override | |
| 130 | + public void onAdd(Host host) { | |
| 131 | + if (predicate.apply(host)) | |
| 132 | + childPolicy.onAdd(host); | |
| 133 | + } | |
| 134 | + | |
| 135 | + @Override | |
| 136 | + public void onRemove(Host host) { | |
| 137 | + if (predicate.apply(host)) | |
| 138 | + childPolicy.onRemove(host); | |
| 139 | + } | |
| 140 | + | |
| 141 | + @Override | |
| 142 | + public void close() { | |
| 143 | + if (childPolicy instanceof CloseableLoadBalancingPolicy) | |
| 144 | + ((CloseableLoadBalancingPolicy)childPolicy).close(); | |
| 145 | + } | |
| 146 | + | |
| 147 | + /** | |
| 148 | + * Create a new policy that wraps the provided child policy but only "allows" hosts | |
| 149 | + * whose DC belongs to the provided list. | |
| 150 | + * | |
| 151 | + * @param childPolicy the wrapped policy. | |
| 152 | + * @param dcs the DCs. | |
| 153 | + * | |
| 154 | + * @return the policy. | |
| 155 | + */ | |
| 156 | + public static HostFilterPolicy fromDCWhiteList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) { | |
| 157 | + return new HostFilterPolicy(childPolicy, hostDCPredicate(dcs, true)); | |
| 158 | + } | |
| 159 | + | |
| 160 | + /** | |
| 161 | + * Create a new policy that wraps the provided child policy but only "forbids" hosts | |
| 162 | + * whose DC belongs to the provided list. | |
| 163 | + * | |
| 164 | + * @param childPolicy the wrapped policy. | |
| 165 | + * @param dcs the DCs. | |
| 166 | + * | |
| 167 | + * @return the policy. | |
| 168 | + */ | |
| 169 | + public static HostFilterPolicy fromDCBlackList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) { | |
| 170 | + return new HostFilterPolicy(childPolicy, Predicates.not(hostDCPredicate(dcs, false))); | |
| 171 | + } | |
| 172 | + | |
| 173 | + private static Predicate<Host> hostDCPredicate(Iterable<String> dcs, final boolean includeNullDC) { | |
| 174 | + final ImmutableSet<String> _dcs = ImmutableSet.copyOf(dcs); | |
| 175 | + return new Predicate<Host>() { | |
| 176 | + @Override | |
| 177 | + public boolean apply(Host host) { | |
| 178 | + String hdc = host.getDatacenter(); | |
| 179 | + return (hdc == null) ? includeNullDC : _dcs.contains(hdc); | |
| 180 | + } | |
| 181 | + }; | |
| 182 | + } | |
| 183 | + | |
| 184 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +1 −1
| @@ -85,7 +85,7 @@ | ||
| 85 | 85 | public static LoadBalancingPolicy defaultLoadBalancingPolicy() { |
| 86 | 86 | // Note: balancing policies are stateful, so we can't store that in a static or that would screw thing |
| 87 | 87 | // up if multiple Cluster instance are started in the same JVM. |
| 88 | - return new TokenAwarePolicy(new DCAwareRoundRobinPolicy()); | |
| 88 | + return new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build()); | |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | 91 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +14 −106
| @@ -16,18 +16,12 @@ | ||
| 16 | 16 | package com.datastax.driver.core.policies; |
| 17 | 17 | |
| 18 | 18 | import java.net.InetSocketAddress; |
| 19 | -import java.util.ArrayList; | |
| 20 | 19 | import java.util.Collection; |
| 21 | -import java.util.Iterator; | |
| 22 | -import java.util.List; | |
| 23 | -import java.util.Set; | |
| 24 | 20 | |
| 21 | +import com.google.common.base.Predicate; | |
| 25 | 22 | import com.google.common.collect.ImmutableSet; |
| 26 | 23 | |
| 27 | -import com.datastax.driver.core.Cluster; | |
| 28 | 24 | import com.datastax.driver.core.Host; |
| 29 | -import com.datastax.driver.core.HostDistance; | |
| 30 | -import com.datastax.driver.core.Statement; | |
| 31 | 25 | |
| 32 | 26 | /** |
| 33 | 27 | * A load balancing policy wrapper that ensure that only hosts from a provided |
| @@ -46,13 +40,13 @@ | ||
| 46 | 40 | * If all you want to do is limiting connections to hosts of the local |
| 47 | 41 | * data-center then you should use DCAwareRoundRobinPolicy and *not* this policy |
| 48 | 42 | * in particular. |
| 43 | + * | |
| 44 | + * @see HostFilterPolicy | |
| 49 | 45 | */ |
| 50 | -public class WhiteListPolicy implements ChainableLoadBalancingPolicy, CloseableLoadBalancingPolicy { | |
| 51 | - private final LoadBalancingPolicy childPolicy; | |
| 52 | - private final Set<InetSocketAddress> whiteList; | |
| 46 | +public class WhiteListPolicy extends HostFilterPolicy { | |
| 53 | 47 | |
| 54 | 48 | /** |
| 55 | - * Create a new policy that wraps the provided child policy but only "allow" hosts | |
| 49 | + * Creates a new policy that wraps the provided child policy but only "allows" hosts | |
| 56 | 50 | * from the provided while list. |
| 57 | 51 | * |
| 58 | 52 | * @param childPolicy the wrapped policy. |
| @@ -60,103 +54,17 @@ | ||
| 60 | 54 | * to (whether they will get connected to or not depends on the child policy). |
| 61 | 55 | */ |
| 62 | 56 | public WhiteListPolicy(LoadBalancingPolicy childPolicy, Collection<InetSocketAddress> whiteList) { |
| 63 | - this.childPolicy = childPolicy; | |
| 64 | - this.whiteList = ImmutableSet.copyOf(whiteList); | |
| 57 | + super(childPolicy, buildPredicate(whiteList)); | |
| 65 | 58 | } |
| 66 | 59 | |
| 67 | - @Override | |
| 68 | - public LoadBalancingPolicy getChildPolicy() { | |
| 69 | - return childPolicy; | |
| 60 | + private static Predicate<Host> buildPredicate(Collection<InetSocketAddress> whiteList) { | |
| 61 | + final ImmutableSet<InetSocketAddress> hosts = ImmutableSet.copyOf(whiteList); | |
| 62 | + return new Predicate<Host>() { | |
| 63 | + @Override | |
| 64 | + public boolean apply(Host host) { | |
| 65 | + return hosts.contains(host.getSocketAddress()); | |
| 66 | + } | |
| 67 | + }; | |
| 70 | 68 | } |
| 71 | 69 | |
| 72 | - /** | |
| 73 | - * Initialize this load balancing policy. | |
| 74 | - * | |
| 75 | - * @param cluster the {@code Cluster} instance for which the policy is created. | |
| 76 | - * @param hosts the initial hosts to use. | |
| 77 | - * | |
| 78 | - * @throws IllegalArgumentException if none of the host in {@code hosts} | |
| 79 | - * (which will correspond to the contact points) are part of the white list. | |
| 80 | - */ | |
| 81 | - @Override | |
| 82 | - public void init(Cluster cluster, Collection<Host> hosts) { | |
| 83 | - List<Host> whiteHosts = new ArrayList<Host>(hosts.size()); | |
| 84 | - for (Host host : hosts) | |
| 85 | - if (whiteList.contains(host.getSocketAddress())) | |
| 86 | - whiteHosts.add(host); | |
| 87 | - | |
| 88 | - if (whiteHosts.isEmpty()) | |
| 89 | - throw new IllegalArgumentException(String.format("Cannot use WhiteListPolicy where the white list (%s) contains none of the contacts points (%s)", whiteList, hosts)); | |
| 90 | - | |
| 91 | - childPolicy.init(cluster, whiteHosts); | |
| 92 | - } | |
| 93 | - | |
| 94 | - /** | |
| 95 | - * Return the HostDistance for the provided host. | |
| 96 | - * | |
| 97 | - * @param host the host of which to return the distance of. | |
| 98 | - * @return {@link HostDistance#IGNORED} if {@code host} is not part of the white list, the HostDistance | |
| 99 | - * as returned by the wrapped policy otherwise. | |
| 100 | - */ | |
| 101 | - @Override | |
| 102 | - public HostDistance distance(Host host) { | |
| 103 | - return whiteList.contains(host.getSocketAddress()) | |
| 104 | - ? childPolicy.distance(host) | |
| 105 | - : HostDistance.IGNORED; | |
| 106 | - } | |
| 107 | - | |
| 108 | - /** | |
| 109 | - * Returns the hosts to use for a new query. | |
| 110 | - * <p> | |
| 111 | - * It is guaranteed that only hosts from the white list will be returned. | |
| 112 | - * | |
| 113 | - * @param loggedKeyspace the currently logged keyspace (the one set through either | |
| 114 | - * {@link Cluster#connect(String)} or by manually doing a {@code USE} query) for | |
| 115 | - * the session on which this plan need to be built. This can be {@code null} if | |
| 116 | - * the corresponding session has no keyspace logged in. | |
| 117 | - * @param statement the query for which to build a plan. | |
| 118 | - */ | |
| 119 | - @Override | |
| 120 | - public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 121 | - // Just delegate to the child policy, since we filter the hosts not white | |
| 122 | - // listed upfront, the child policy will never see a host that is not white | |
| 123 | - // listed and thus can't return one. | |
| 124 | - return childPolicy.newQueryPlan(loggedKeyspace, statement); | |
| 125 | - } | |
| 126 | - | |
| 127 | - @Override | |
| 128 | - public void onUp(Host host) { | |
| 129 | - if (whiteList.contains(host.getSocketAddress())) | |
| 130 | - childPolicy.onUp(host); | |
| 131 | - } | |
| 132 | - | |
| 133 | - @Override | |
| 134 | - public void onSuspected(Host host) { | |
| 135 | - if (whiteList.contains(host.getSocketAddress())) | |
| 136 | - childPolicy.onSuspected(host); | |
| 137 | - } | |
| 138 | - | |
| 139 | - @Override | |
| 140 | - public void onDown(Host host) { | |
| 141 | - if (whiteList.contains(host.getSocketAddress())) | |
| 142 | - childPolicy.onDown(host); | |
| 143 | - } | |
| 144 | - | |
| 145 | - @Override | |
| 146 | - public void onAdd(Host host) { | |
| 147 | - if (whiteList.contains(host.getSocketAddress())) | |
| 148 | - childPolicy.onAdd(host); | |
| 149 | - } | |
| 150 | - | |
| 151 | - @Override | |
| 152 | - public void onRemove(Host host) { | |
| 153 | - if (whiteList.contains(host.getSocketAddress())) | |
| 154 | - childPolicy.onRemove(host); | |
| 155 | - } | |
| 156 | - | |
| 157 | - @Override | |
| 158 | - public void close() { | |
| 159 | - if (childPolicy instanceof CloseableLoadBalancingPolicy) | |
| 160 | - ((CloseableLoadBalancingPolicy)childPolicy).close(); | |
| 161 | - } | |
| 162 | 70 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +1 −1
| @@ -148,7 +148,7 @@ | ||
| 148 | 148 | * Sets the 'IF NOT EXISTS' option for this INSERT statement. |
| 149 | 149 | * <p> |
| 150 | 150 | * An insert with that option will not succeed unless the row does not |
| 151 | - * exist at the time the insertion is execution. The existence check and | |
| 151 | + * exist at the time the insertion is executed. The existence check and | |
| 152 | 152 | * insertions are done transactionally in the sense that if multiple |
| 153 | 153 | * clients attempt to create a given row with this option, then at most one |
| 154 | 154 | * may succeed. |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +26 −5
| @@ -25,6 +25,7 @@ | ||
| 25 | 25 | import com.google.common.util.concurrent.Futures; |
| 26 | 26 | import com.google.common.util.concurrent.ListenableFuture; |
| 27 | 27 | import com.google.common.util.concurrent.SettableFuture; |
| 28 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 28 | 29 | import org.slf4j.Logger; |
| 29 | 30 | import org.slf4j.LoggerFactory; |
| 30 | 31 | import org.testng.annotations.AfterMethod; |
| @@ -32,8 +33,12 @@ | ||
| 32 | 33 | import org.testng.annotations.Test; |
| 33 | 34 | |
| 34 | 35 | import static org.assertj.core.api.Assertions.assertThat; |
| 36 | +import static org.mockito.Mockito.spy; | |
| 37 | +import static org.mockito.Mockito.timeout; | |
| 38 | +import static org.mockito.Mockito.verify; | |
| 35 | 39 | import static org.testng.Assert.fail; |
| 36 | 40 | |
| 41 | +import com.datastax.driver.core.AbstractReconnectionHandler.HandlerFuture; | |
| 37 | 42 | import com.datastax.driver.core.AbstractReconnectionHandlerTest.MockReconnectionWork.ReconnectBehavior; |
| 38 | 43 | import com.datastax.driver.core.policies.ReconnectionPolicy.ReconnectionSchedule; |
| 39 | 44 | |
| @@ -48,7 +53,7 @@ | ||
| 48 | 53 | |
| 49 | 54 | @BeforeMethod(groups = {"unit", "short"}) |
| 50 | 55 | public void setup() { |
| 51 | - executor = Executors.newScheduledThreadPool(2); | |
| 56 | + executor = spy(Executors.newScheduledThreadPool(2)); | |
| 52 | 57 | schedule = new MockReconnectionSchedule(); |
| 53 | 58 | work = new MockReconnectionWork(); |
| 54 | 59 | future.set(null); |
| @@ -133,6 +138,9 @@ | ||
| 133 | 138 | public void should_stop_if_cancelled_between_attempts() { |
| 134 | 139 | handler.start(); |
| 135 | 140 | |
| 141 | + // Wait for the initial schedule of a reconnect. | |
| 142 | + verify(executor, timeout(1000)).schedule(handler, 0, TimeUnit.MILLISECONDS); | |
| 143 | + | |
| 136 | 144 | // Force a failed reconnect. |
| 137 | 145 | schedule.tick(); |
| 138 | 146 | work.nextReconnect = ReconnectBehavior.THROW_EXCEPTION; |
| @@ -143,17 +151,30 @@ | ||
| 143 | 151 | schedule.delay = 3000; |
| 144 | 152 | schedule.tick(); |
| 145 | 153 | |
| 146 | - // At this point the reconnect should be scheduled but not executed yet, cancel the future. | |
| 154 | + // Ensure reconnect is scheduled (slight timing window after handling failed reconnect | |
| 155 | + // and scheduling next reconnect). | |
| 156 | + verify(executor, timeout(1000)).schedule(handler, schedule.delay, TimeUnit.MILLISECONDS); | |
| 157 | + | |
| 158 | + // Add a short delay to account for nextTry being assigned after schedule completes. | |
| 159 | + Uninterruptibles.sleepUninterruptibly(5, TimeUnit.MILLISECONDS); | |
| 147 | 160 | future.get().cancel(false); |
| 148 | 161 | |
| 149 | - // Should block until scheduler runs, detects cancel and exits. | |
| 162 | + // Should immediately return as the future was cancelled while the task was scheduled. | |
| 150 | 163 | waitForCompletion(); |
| 151 | 164 | |
| 152 | 165 | assertThat(work.success).isFalse(); |
| 153 | 166 | // Should have had 1 failed attempt, no second attempt since cancelled. |
| 154 | 167 | assertThat(work.tries).isEqualTo(1); |
| 155 | - // The future will be marked null once it is detected as cancelled. | |
| 156 | - assertThat(future.get()).isNull(); | |
| 168 | + | |
| 169 | + // The future will be marked cancelled and thus not executed. | |
| 170 | + ListenableFuture<?> currentAttempt = future.get(); | |
| 171 | + assertThat(currentAttempt).isInstanceOf(HandlerFuture.class); | |
| 172 | + HandlerFuture handlerFuture = (HandlerFuture)currentAttempt; | |
| 173 | + assertThat(handlerFuture.isCancelled()); | |
| 174 | + | |
| 175 | + // The next try should also be cancelled. | |
| 176 | + assertThat(handlerFuture.nextTry).isNotNull(); | |
| 177 | + assertThat(handlerFuture.nextTry.isCancelled()); | |
| 157 | 178 | } |
| 158 | 179 | |
| 159 | 180 | @Test(groups = "unit") |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +1 −1
| @@ -56,7 +56,7 @@ | ||
| 56 | 56 | |
| 57 | 57 | @Override |
| 58 | 58 | public String toString() { |
| 59 | - return address.getHostName(); | |
| 59 | + return address.toString(); | |
| 60 | 60 | } |
| 61 | 61 | |
| 62 | 62 | public InetSocketAddress getMockAddress() { |
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +42 −19
| @@ -16,15 +16,13 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.util.Collection; |
| 19 | -import java.util.concurrent.ExecutionException; | |
| 20 | -import java.util.concurrent.TimeUnit; | |
| 19 | +import java.util.List; | |
| 20 | +import java.util.concurrent.*; | |
| 21 | 21 | |
| 22 | 22 | import com.google.common.base.Function; |
| 23 | 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; | |
| 24 | +import com.google.common.util.concurrent.*; | |
| 25 | +import org.testng.annotations.DataProvider; | |
| 28 | 26 | import org.testng.annotations.Test; |
| 29 | 27 | |
| 30 | 28 | import static org.assertj.core.api.Assertions.assertThat; |
| @@ -35,12 +33,24 @@ | ||
| 35 | 33 | |
| 36 | 34 | public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster { |
| 37 | 35 | |
| 36 | + @DataProvider(name="keyspace") | |
| 37 | + public static Object[][] keyspace() { | |
| 38 | + return new Object[][]{ { "asyncquerytest" }, { "\"AsyncQueryTest\"" } }; | |
| 39 | + } | |
| 40 | + | |
| 38 | 41 | @Override |
| 39 | 42 | protected Collection<String> getTableDefinitions() { |
| 40 | - return Lists.newArrayList( | |
| 41 | - "create table foo(k int primary key, v int)", | |
| 42 | - "insert into foo (k, v) values (1, 1)" | |
| 43 | - ); | |
| 43 | + List<String> definitions = Lists.newArrayList(); | |
| 44 | + | |
| 45 | + for (Object[] objects : keyspace()) { | |
| 46 | + String keyspace = (String)objects[0]; | |
| 47 | + | |
| 48 | + definitions.add(String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace)); | |
| 49 | + definitions.add(String.format("create table %s.foo(k int primary key, v int)", keyspace)); | |
| 50 | + definitions.add(String.format("insert into %s.foo (k, v) values (1, 1)", keyspace)); | |
| 51 | + } | |
| 52 | + | |
| 53 | + return definitions; | |
| 44 | 54 | } |
| 45 | 55 | |
| 46 | 56 | /** |
| @@ -76,27 +86,40 @@ | ||
| 76 | 86 | // Neither cluster2 nor session2 are initialized at this point |
| 77 | 87 | assertThat(cluster2.manager.metadata).isNull(); |
| 78 | 88 | |
| 79 | - ResultSetFuture future = session2.executeAsync(String.format("select v from %s.foo where k = 1", keyspace)); | |
| 89 | + ResultSetFuture future = session2.executeAsync("select release_version from system.local"); | |
| 80 | 90 | Row row = Uninterruptibles.getUninterruptibly(future).one(); |
| 81 | 91 | |
| 82 | - assertThat(row.getInt(0)).isEqualTo(1); | |
| 92 | + assertThat(row.getString(0)).isNotEmpty(); | |
| 83 | 93 | } finally { |
| 84 | 94 | if (cluster2 != null) |
| 85 | 95 | cluster2.close(); |
| 86 | 96 | } |
| 87 | 97 | } |
| 88 | 98 | |
| 89 | - @Test(groups = "short") | |
| 90 | - public void should_chain_query_on_async_session_init() throws Exception { | |
| 91 | - ListenableFuture<Integer> resultFuture = connectAndQuery(this.keyspace); | |
| 99 | + @Test(groups = "short", dataProvider = "keyspace", enabled = false, | |
| 100 | + description = "disabled because the blocking USE call in the current pool implementation makes it deadlock") | |
| 101 | + public void should_chain_query_on_async_session_init_with_same_executor(String keyspace) throws Exception { | |
| 102 | + ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, MoreExecutors.sameThreadExecutor()); | |
| 92 | 103 | |
| 93 | 104 | Integer result = Uninterruptibles.getUninterruptibly(resultFuture); |
| 94 | 105 | assertThat(result).isEqualTo(1); |
| 95 | 106 | } |
| 96 | 107 | |
| 108 | + @Test(groups = "short", dataProvider = "keyspace") | |
| 109 | + public void should_chain_query_on_async_session_init_with_different_executor(String keyspace) throws Exception { | |
| 110 | + ExecutorService executor = Executors.newFixedThreadPool(1); | |
| 111 | + | |
| 112 | + ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, executor); | |
| 113 | + | |
| 114 | + Integer result = Uninterruptibles.getUninterruptibly(resultFuture); | |
| 115 | + assertThat(result).isEqualTo(1); | |
| 116 | + | |
| 117 | + executor.shutdownNow(); | |
| 118 | + } | |
| 119 | + | |
| 97 | 120 | @Test(groups = "short") |
| 98 | 121 | public void should_propagate_error_to_chained_query_if_session_init_fails() throws Exception { |
| 99 | - ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace"); | |
| 122 | + ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace", MoreExecutors.sameThreadExecutor()); | |
| 100 | 123 | |
| 101 | 124 | try { |
| 102 | 125 | Uninterruptibles.getUninterruptibly(resultFuture); |
| @@ -107,20 +130,20 @@ | ||
| 107 | 130 | } |
| 108 | 131 | } |
| 109 | 132 | |
| 110 | - private ListenableFuture<Integer> connectAndQuery(String keyspace) { | |
| 133 | + private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) { | |
| 111 | 134 | ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace); |
| 112 | 135 | ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() { |
| 113 | 136 | @Override |
| 114 | 137 | public ListenableFuture<ResultSet> apply(Session session) throws Exception { |
| 115 | 138 | return session.executeAsync("select v from foo where k = 1"); |
| 116 | 139 | } |
| 117 | - }); | |
| 140 | + }, executor); | |
| 118 | 141 | return Futures.transform(queryFuture, new Function<ResultSet, Integer>() { |
| 119 | 142 | @Override |
| 120 | 143 | public Integer apply(ResultSet rs) { |
| 121 | 144 | return rs.one().getInt(0); |
| 122 | 145 | } |
| 123 | - }); | |
| 146 | + }, executor); | |
| 124 | 147 | } |
| 125 | 148 | |
| 126 | 149 | private static HostConnectionPool getPool(Session session) { |
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +22 −5
| @@ -60,9 +60,13 @@ | ||
| 60 | 60 | public static final String DEFAULT_CLIENT_TRUSTSTORE_PASSWORD = "cassandra1sfun"; |
| 61 | 61 | public static final String DEFAULT_CLIENT_TRUSTSTORE_PATH = "/client.truststore"; |
| 62 | 62 | |
| 63 | + public static final File DEFAULT_CLIENT_TRUSTSTORE_FILE = createTempStore(DEFAULT_CLIENT_TRUSTSTORE_PATH); | |
| 64 | + | |
| 63 | 65 | public static final String DEFAULT_CLIENT_KEYSTORE_PASSWORD = "cassandra1sfun"; |
| 64 | 66 | public static final String DEFAULT_CLIENT_KEYSTORE_PATH = "/client.keystore"; |
| 65 | 67 | |
| 68 | + public static final File DEFAULT_CLIENT_KEYSTORE_FILE = createTempStore(DEFAULT_CLIENT_KEYSTORE_PATH); | |
| 69 | + | |
| 66 | 70 | public static final String DEFAULT_SERVER_TRUSTSTORE_PASSWORD = "cassandra1sfun"; |
| 67 | 71 | public static final String DEFAULT_SERVER_TRUSTSTORE_PATH = "/server.truststore"; |
| 68 | 72 | |
| @@ -478,7 +482,9 @@ | ||
| 478 | 482 | |
| 479 | 483 | builder = configure(builder); |
| 480 | 484 | |
| 481 | - cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)).build(); | |
| 485 | + cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 486 | + .withNettyOptions(TestUtils.nonQuietClusterCloseOptions) | |
| 487 | + .build(); | |
| 482 | 488 | session = cluster.connect(); |
| 483 | 489 | keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet(); |
| 484 | 490 | session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); |
| @@ -506,19 +512,30 @@ | ||
| 506 | 512 | |
| 507 | 513 | private void clearSimpleKeyspace() { |
| 508 | 514 | if(keyspace != null) { |
| 509 | - // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables. | |
| 510 | - // This should be more than enough although some tests create many tables, so dropping a keyspace | |
| 511 | - // could take as long as 12 seconds on restricted hardware. | |
| 515 | + logger.debug("Removing keyspace {}.", keyspace); | |
| 516 | + // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and | |
| 517 | + // tables being slow, particularly in a CI environment. | |
| 512 | 518 | int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis(); |
| 513 | 519 | cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000); |
| 514 | 520 | try { |
| 521 | + KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace); | |
| 522 | + if (ksm != null) { | |
| 523 | + // drop each table individually as this seems to be more dependable than dropping | |
| 524 | + // the entire keyspace at once if it has many tables. | |
| 525 | + if(ksm.getTables().size() > 10) { | |
| 526 | + for (TableMetadata table : ksm.getTables()) { | |
| 527 | + logger.debug("Dropping table {}.{}.", keyspace, table.getName()); | |
| 528 | + session.execute("DROP TABLE " + keyspace + "." + table.getName()); | |
| 529 | + } | |
| 530 | + } | |
| 531 | + } | |
| 532 | + logger.debug("Dropping keyspace {}.", keyspace); | |
| 515 | 533 | session.execute("DROP KEYSPACE " + keyspace); |
| 516 | 534 | } finally { |
| 517 | 535 | cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout); |
| 518 | 536 | } |
| 519 | 537 | } |
| 520 | 538 | } |
| 521 | - | |
| 522 | 539 | } |
| 523 | 540 | |
| 524 | 541 | public static class CCMCluster { |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +12 −13
| @@ -15,12 +15,13 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.google.common.collect.Iterators; | |
| 19 | -import org.assertj.core.api.AbstractAssert; | |
| 20 | - | |
| 21 | 18 | import java.util.Iterator; |
| 22 | 19 | import java.util.Set; |
| 23 | 20 | import java.util.TreeSet; |
| 21 | +import java.util.concurrent.TimeUnit; | |
| 22 | + | |
| 23 | +import com.google.common.collect.Iterators; | |
| 24 | +import org.assertj.core.api.AbstractAssert; | |
| 24 | 25 | |
| 25 | 26 | import static org.assertj.core.api.Assertions.assertThat; |
| 26 | 27 | |
| @@ -47,19 +48,17 @@ | ||
| 47 | 48 | } |
| 48 | 49 | |
| 49 | 50 | public HostAssert host(int hostNumber) { |
| 50 | - // TODO at some point this won't work anymore if we have assertions that wait for a node to | |
| 51 | - // join the cluster, e.g. assertThat(cluster).node(3).comesUp(). | |
| 52 | - return new HostAssert( | |
| 53 | - TestUtils.findHost(actual, hostNumber), | |
| 54 | - actual); | |
| 51 | + // Wait for the node to be added if it's not already known. | |
| 52 | + // In 2.2+ C* does not send an added event until the node is ready so we wait a long time. | |
| 53 | + Host host = TestUtils.findOrWaitForHost(actual, hostNumber, | |
| 54 | + 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 55 | + return new HostAssert(host, actual); | |
| 55 | 56 | } |
| 56 | 57 | |
| 57 | 58 | public HostAssert host(String hostAddress) { |
| 58 | - // TODO at some point this won't work anymore if we have assertions that wait for a node to | |
| 59 | - // join the cluster, e.g. assertThat(cluster).node(3).comesUp(). | |
| 60 | - return new HostAssert( | |
| 61 | - TestUtils.findHost(actual, hostAddress), | |
| 62 | - actual); | |
| 59 | + Host host = TestUtils.findOrWaitForHost(actual, hostAddress, | |
| 60 | + 60 + Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 61 | + return new HostAssert(host, actual); | |
| 63 | 62 | } |
| 64 | 63 | |
| 65 | 64 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +56 −8
| @@ -27,6 +27,7 @@ | ||
| 27 | 27 | import com.google.common.collect.ImmutableMap; |
| 28 | 28 | import com.google.common.collect.ImmutableSet; |
| 29 | 29 | import com.google.common.collect.Lists; |
| 30 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 30 | 31 | import org.scassandra.Scassandra; |
| 31 | 32 | import org.scassandra.http.client.PrimingClient; |
| 32 | 33 | import org.scassandra.http.client.PrimingRequest; |
| @@ -42,14 +43,13 @@ | ||
| 42 | 43 | |
| 43 | 44 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 44 | 45 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 45 | -import com.datastax.driver.core.utils.CassandraVersion; | |
| 46 | 46 | |
| 47 | -import static com.datastax.driver.core.Assertions.*; | |
| 47 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 48 | +import static com.datastax.driver.core.Assertions.fail; | |
| 48 | 49 | import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS; |
| 49 | -import static com.datastax.driver.core.Host.State.DOWN; | |
| 50 | -import static com.datastax.driver.core.Host.State.UP; | |
| 51 | 50 | import static com.datastax.driver.core.HostDistance.LOCAL; |
| 52 | 51 | import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; |
| 52 | +import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; | |
| 53 | 53 | |
| 54 | 54 | public class ClusterInitTest { |
| 55 | 55 | private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class); |
| @@ -59,7 +59,6 @@ | ||
| 59 | 59 | * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host. |
| 60 | 60 | */ |
| 61 | 61 | @Test(groups = "short") |
| 62 | - @CassandraVersion(major=2.0, description = "Scassandra currently broken with protocol version 1.") | |
| 63 | 62 | public void should_handle_failing_or_missing_contact_points() throws UnknownHostException { |
| 64 | 63 | if (TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V2) > 0) |
| 65 | 64 | throw new SkipException("Scassandra does not yet support protocol >= V3"); |
| @@ -132,9 +131,22 @@ | ||
| 132 | 131 | verify(socketOptions, atLeast(6)).getKeepAlive(); |
| 133 | 132 | verify(socketOptions, atMost(7)).getKeepAlive(); |
| 134 | 133 | |
| 135 | - assertThat(cluster).host(realHostAddress).isNotNull().hasState(UP); | |
| 136 | - for (FakeHost failingHost : failingHosts) | |
| 137 | - assertThat(cluster).host(failingHost.address).hasState(DOWN); | |
| 134 | + assertThat(cluster).host(realHostAddress).isNotNull().isUp(); | |
| 135 | + // It is likely but not guaranteed that a host is marked down at this point. | |
| 136 | + // It should eventually be marked down as Cluster.Manager.triggerOnDown should be | |
| 137 | + // called and submit a task that marks the host down. | |
| 138 | + for (FakeHost failingHost : failingHosts) { | |
| 139 | + assertThat(cluster).host(failingHost.address).goesDownWithin(10, TimeUnit.SECONDS); | |
| 140 | + Host host = TestUtils.findHost(cluster, failingHost.address); | |
| 141 | + // There is a possible race here in that the host is marked down in a separate Executor in onDown | |
| 142 | + // and then starts a periodic reconnection attempt shortly after. Since setDown is called before | |
| 143 | + // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet. | |
| 144 | + if(host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) { | |
| 145 | + logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host); | |
| 146 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 147 | + } | |
| 148 | + assertThat(cluster).host(failingHost.address).isReconnectingFromDown(); | |
| 149 | + } | |
| 138 | 150 | assertThat(cluster).host(missingHostAddress).isNull(); |
| 139 | 151 | |
| 140 | 152 | } finally { |
| @@ -147,6 +159,41 @@ | ||
| 147 | 159 | } |
| 148 | 160 | } |
| 149 | 161 | |
| 162 | + /** | |
| 163 | + * Validates that if hosts are unreachable during Cluster initialization, no background reconnection to them | |
| 164 | + * is scheduled before the initialization is complete. | |
| 165 | + * | |
| 166 | + * @test_category connection | |
| 167 | + * @jira_ticket JAVA-954 | |
| 168 | + * @expected_result No reconnection scheduled. | |
| 169 | + */ | |
| 170 | + @Test(groups="short", expectedExceptions = NoHostAvailableException.class) | |
| 171 | + public void should_not_schedule_reconnections_before_init_complete() { | |
| 172 | + // Both contact points time out so we're sure we'll try both of them and init will never complete. | |
| 173 | + List<FakeHost> hosts = Lists.newArrayList( | |
| 174 | + new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS), | |
| 175 | + new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS)); | |
| 176 | + // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled, | |
| 177 | + // we would see a call to the reconnection policy. | |
| 178 | + CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100)); | |
| 179 | + Cluster cluster = Cluster.builder() | |
| 180 | + .addContactPoints(hosts.get(0).address, hosts.get(1).address) | |
| 181 | + .withReconnectionPolicy(reconnectionPolicy) | |
| 182 | + .build(); | |
| 183 | + try { | |
| 184 | + cluster.init(); | |
| 185 | + } finally { | |
| 186 | + // We expect a nextDelay invocation from the ConvictionPolicy for each host, but that will | |
| 187 | + // not trigger a reconnection. | |
| 188 | + assertThat(reconnectionPolicy.count.get()).isEqualTo(2); | |
| 189 | + for (FakeHost fakeHost : hosts) { | |
| 190 | + fakeHost.stop(); | |
| 191 | + } | |
| 192 | + } | |
| 193 | + // We don't test that reconnections are scheduled if init succeeds, but that's covered in | |
| 194 | + // should_handle_failing_or_missing_contact_points | |
| 195 | + } | |
| 196 | + | |
| 150 | 197 | /** |
| 151 | 198 | * Validates that a Cluster that was never able to successfully establish connection a session can be closed |
| 152 | 199 | * properly. |
| @@ -158,6 +205,7 @@ | ||
| 158 | 205 | public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception { |
| 159 | 206 | Cluster cluster = Cluster.builder() |
| 160 | 207 | .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534))) |
| 208 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 161 | 209 | .build(); |
| 162 | 210 | try { |
| 163 | 211 | cluster.connect(); |
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +2 −0
| @@ -30,6 +30,7 @@ | ||
| 30 | 30 | |
| 31 | 31 | import static com.datastax.driver.core.Assertions.assertThat; |
| 32 | 32 | import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; |
| 33 | +import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; | |
| 33 | 34 | |
| 34 | 35 | import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy; |
| 35 | 36 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| @@ -194,6 +195,7 @@ | ||
| 194 | 195 | for(int i = 0; i < iterations; i++) { |
| 195 | 196 | Cluster cluster = Cluster.builder() |
| 196 | 197 | .addContactPoints(scassandras.addresses()) |
| 198 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 197 | 199 | .build(); |
| 198 | 200 | |
| 199 | 201 | try { |
added driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java +51 −0
| @@ -0,0 +1,51 @@ | ||
| 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.atomic.AtomicInteger; | |
| 19 | + | |
| 20 | +import com.datastax.driver.core.policies.ReconnectionPolicy; | |
| 21 | + | |
| 22 | +/** | |
| 23 | + * A reconnection policy that tracks how many times its schedule has been invoked. | |
| 24 | + */ | |
| 25 | +public class CountingReconnectionPolicy implements ReconnectionPolicy { | |
| 26 | + public final AtomicInteger count = new AtomicInteger(); | |
| 27 | + private final ReconnectionPolicy childPolicy; | |
| 28 | + | |
| 29 | + public CountingReconnectionPolicy(ReconnectionPolicy childPolicy) { | |
| 30 | + this.childPolicy = childPolicy; | |
| 31 | + } | |
| 32 | + | |
| 33 | + @Override | |
| 34 | + public ReconnectionSchedule newSchedule() { | |
| 35 | + return new CountingSchedule(childPolicy.newSchedule()); | |
| 36 | + } | |
| 37 | + | |
| 38 | + class CountingSchedule implements ReconnectionSchedule { | |
| 39 | + private final ReconnectionSchedule childSchedule; | |
| 40 | + | |
| 41 | + public CountingSchedule(ReconnectionSchedule childSchedule) { | |
| 42 | + this.childSchedule = childSchedule; | |
| 43 | + } | |
| 44 | + | |
| 45 | + @Override | |
| 46 | + public long nextDelayMs() { | |
| 47 | + count.incrementAndGet(); | |
| 48 | + return childSchedule.nextDelayMs(); | |
| 49 | + } | |
| 50 | + } | |
| 51 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +6 −22
| @@ -57,6 +57,12 @@ | ||
| 57 | 57 | return this; |
| 58 | 58 | } |
| 59 | 59 | |
| 60 | + public HostAssert isReconnectingFromDown() { | |
| 61 | + assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone()) | |
| 62 | + .isTrue(); | |
| 63 | + return this; | |
| 64 | + } | |
| 65 | + | |
| 60 | 66 | public HostAssert isNotReconnectingFromDown() { |
| 61 | 67 | assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone()) |
| 62 | 68 | .isFalse(); |
| @@ -114,26 +120,4 @@ | ||
| 114 | 120 | fail(actual + " did not go down within " + duration + " " + unit); |
| 115 | 121 | return this; |
| 116 | 122 | } |
| 117 | - | |
| 118 | - public static class StateListenerBase implements StateListener { | |
| 119 | - @Override | |
| 120 | - public void onAdd(Host host) { | |
| 121 | - } | |
| 122 | - | |
| 123 | - @Override | |
| 124 | - public void onUp(Host host) { | |
| 125 | - } | |
| 126 | - | |
| 127 | - @Override | |
| 128 | - public void onSuspected(Host host) { | |
| 129 | - } | |
| 130 | - | |
| 131 | - @Override | |
| 132 | - public void onDown(Host host) { | |
| 133 | - } | |
| 134 | - | |
| 135 | - @Override | |
| 136 | - public void onRemove(Host host) { | |
| 137 | - } | |
| 138 | - } | |
| 139 | 123 | } |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +1 −1
| @@ -538,7 +538,7 @@ | ||
| 538 | 538 | // 2 attempts for connection.open (reconnect control connection and initial connection for host state). |
| 539 | 539 | verify(factory, after(reconnectInterval*2).atLeast(2)).open(host); |
| 540 | 540 | // 7 attempts for core connections after first initial connection. |
| 541 | - verify(factory, timeout(reconnectInterval*2).times(7)).newConnection(any(HostConnectionPool.class)); | |
| 541 | + verify(factory, timeout(reconnectInterval*2)).newConnections(any(HostConnectionPool.class), eq(7)); | |
| 542 | 542 | |
| 543 | 543 | // Wait some reasonable amount of time for connection to reestablish. |
| 544 | 544 | Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS); |
modified driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +2 −1
| @@ -66,7 +66,8 @@ | ||
| 66 | 66 | public void validatePrepared(boolean expectAll) { |
| 67 | 67 | // Prepare the statement |
| 68 | 68 | String query = "select sansa_stark from the_known_world"; |
| 69 | - session.prepare(query); | |
| 69 | + PreparedStatement statement = session.prepare(query); | |
| 70 | + assertThat(cluster.manager.preparedQueries).containsValue(statement); | |
| 70 | 71 | |
| 71 | 72 | // Ensure prepared properly based on expectation. |
| 72 | 73 | List<PreparedStatementPreparation> preparationOne = scassandra.retrievePreparedStatementPreparations(1); |
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +0 −31
| @@ -314,37 +314,6 @@ | ||
| 314 | 314 | } |
| 315 | 315 | } |
| 316 | 316 | |
| 317 | - /** | |
| 318 | - * A reconnection policy that tracks how many times its schedule has been invoked. | |
| 319 | - */ | |
| 320 | - public static class CountingReconnectionPolicy implements ReconnectionPolicy { | |
| 321 | - public final AtomicInteger count = new AtomicInteger(); | |
| 322 | - private final ReconnectionPolicy childPolicy; | |
| 323 | - | |
| 324 | - public CountingReconnectionPolicy(ReconnectionPolicy childPolicy) { | |
| 325 | - this.childPolicy = childPolicy; | |
| 326 | - } | |
| 327 | - | |
| 328 | - @Override | |
| 329 | - public ReconnectionSchedule newSchedule() { | |
| 330 | - return new CountingSchedule(childPolicy.newSchedule()); | |
| 331 | - } | |
| 332 | - | |
| 333 | - class CountingSchedule implements ReconnectionSchedule { | |
| 334 | - private final ReconnectionSchedule childSchedule; | |
| 335 | - | |
| 336 | - public CountingSchedule(ReconnectionSchedule childSchedule) { | |
| 337 | - this.childSchedule = childSchedule; | |
| 338 | - } | |
| 339 | - | |
| 340 | - @Override | |
| 341 | - public long nextDelayMs() { | |
| 342 | - count.incrementAndGet(); | |
| 343 | - return childSchedule.nextDelayMs(); | |
| 344 | - } | |
| 345 | - } | |
| 346 | - } | |
| 347 | - | |
| 348 | 317 | /** |
| 349 | 318 | * A load balancing policy that: |
| 350 | 319 | * - can be "disabled" by having its query plan return no hosts. |
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +2 −0
| @@ -78,6 +78,8 @@ | ||
| 78 | 78 | assertThat(cluster).host(2) |
| 79 | 79 | .hasState(State.UP) |
| 80 | 80 | .isAtDistance(HostDistance.LOCAL); |
| 81 | + | |
| 82 | + // Ensure that the host is added to the Cluster. | |
| 81 | 83 | assertThat(cluster).host(3) |
| 82 | 84 | .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS) |
| 83 | 85 | .isAtDistance(HostDistance.IGNORED); |
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +23 −2
| @@ -20,8 +20,7 @@ | ||
| 20 | 20 | |
| 21 | 21 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 22 | 22 | |
| 23 | -import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH; | |
| 24 | -import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH; | |
| 23 | +import static com.datastax.driver.core.CCMBridge.*; | |
| 25 | 24 | |
| 26 | 25 | public class SSLAuthenticatedEncryptionTest extends SSLTestBase { |
| 27 | 26 | |
| @@ -59,4 +58,26 @@ | ||
| 59 | 58 | public void should_not_connect_without_client_auth_but_node_requires_auth() throws Exception { |
| 60 | 59 | connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH))); |
| 61 | 60 | } |
| 61 | + | |
| 62 | + /** | |
| 63 | + * <p> | |
| 64 | + * Validates that SSL connectivity can be configured via the standard javax.net.ssl System properties. | |
| 65 | + * </p> | |
| 66 | + * | |
| 67 | + * @test_category connection:ssl, authentication | |
| 68 | + * @expected_result Connection can be established. | |
| 69 | + */ | |
| 70 | + @Test(groups="short") | |
| 71 | + public void should_use_system_properties_with_default_ssl_options() throws Exception { | |
| 72 | + try { | |
| 73 | + System.setProperty("javax.net.ssl.keyStore", DEFAULT_CLIENT_KEYSTORE_FILE.getAbsolutePath()); | |
| 74 | + System.setProperty("javax.net.ssl.keyStorePassword", DEFAULT_CLIENT_KEYSTORE_PASSWORD); | |
| 75 | + System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath()); | |
| 76 | + System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD); | |
| 77 | + | |
| 78 | + connectWithSSL(); | |
| 79 | + } finally { | |
| 80 | + clearSystemProperties(); | |
| 81 | + } | |
| 82 | + } | |
| 62 | 83 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +21 −2
| @@ -23,8 +23,7 @@ | ||
| 23 | 23 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 24 | 24 | |
| 25 | 25 | import static com.datastax.driver.core.Assertions.assertThat; |
| 26 | -import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PATH; | |
| 27 | -import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PATH; | |
| 26 | +import static com.datastax.driver.core.CCMBridge.*; | |
| 28 | 27 | |
| 29 | 28 | public class SSLEncryptionTest extends SSLTestBase { |
| 30 | 29 | |
| @@ -118,4 +117,24 @@ | ||
| 118 | 117 | cluster.close(); |
| 119 | 118 | } |
| 120 | 119 | } |
| 120 | + | |
| 121 | + /** | |
| 122 | + * <p> | |
| 123 | + * Validates that SSL connectivity can be configured via the standard javax.net.ssl System properties. | |
| 124 | + * </p> | |
| 125 | + * | |
| 126 | + * @test_category connection:ssl | |
| 127 | + * @expected_result Connection can be established. | |
| 128 | + */ | |
| 129 | + @Test(groups="short") | |
| 130 | + public void should_use_system_properties_with_default_ssl_options() throws Exception { | |
| 131 | + try { | |
| 132 | + System.setProperty("javax.net.ssl.trustStore", DEFAULT_CLIENT_TRUSTSTORE_FILE.getAbsolutePath()); | |
| 133 | + System.setProperty("javax.net.ssl.trustStorePassword", DEFAULT_CLIENT_TRUSTSTORE_PASSWORD); | |
| 134 | + | |
| 135 | + connectWithSSL(); | |
| 136 | + } finally { | |
| 137 | + clearSystemProperties(); | |
| 138 | + } | |
| 139 | + } | |
| 121 | 140 | } |
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +36 −0
| @@ -25,7 +25,9 @@ | ||
| 25 | 25 | import org.testng.annotations.AfterClass; |
| 26 | 26 | import org.testng.annotations.BeforeClass; |
| 27 | 27 | |
| 28 | +import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_FILE; | |
| 28 | 29 | import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD; |
| 30 | +import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE; | |
| 29 | 31 | import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD; |
| 30 | 32 | public abstract class SSLTestBase { |
| 31 | 33 | |
| @@ -74,6 +76,40 @@ | ||
| 74 | 76 | } |
| 75 | 77 | } |
| 76 | 78 | |
| 79 | + /** | |
| 80 | + * <p> | |
| 81 | + * Attempts to connect to a cassandra cluster with using {@link Cluster.Builder#withSSL} with no | |
| 82 | + * provided {@link SSLOptions} and then closes the created {@link Cluster} instance. | |
| 83 | + * </p> | |
| 84 | + * | |
| 85 | + * @throws Exception A {@link com.datastax.driver.core.exceptions.NoHostAvailableException} will be | |
| 86 | + * raised here if connection cannot be established. | |
| 87 | + */ | |
| 88 | + protected void connectWithSSL() throws Exception { | |
| 89 | + Cluster cluster = null; | |
| 90 | + try { | |
| 91 | + cluster = Cluster.builder() | |
| 92 | + .addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 93 | + .withSSL() | |
| 94 | + .build(); | |
| 95 | + | |
| 96 | + cluster.connect(); | |
| 97 | + } finally { | |
| 98 | + if (cluster != null) | |
| 99 | + cluster.close(); | |
| 100 | + } | |
| 101 | + } | |
| 102 | + | |
| 103 | + /** | |
| 104 | + * Clears all System properties associated with SSL key and trust stores. | |
| 105 | + */ | |
| 106 | + protected void clearSystemProperties() { | |
| 107 | + System.clearProperty("javax.net.ssl.keyStore"); | |
| 108 | + System.clearProperty("javax.net.ssl.keyStorePassword"); | |
| 109 | + System.clearProperty("javax.net.ssl.trustStore"); | |
| 110 | + System.clearProperty("javax.net.ssl.trustStorePassword"); | |
| 111 | + } | |
| 112 | + | |
| 77 | 113 | /** |
| 78 | 114 | * @param keyStorePath Path to keystore, if absent is not used. |
| 79 | 115 | * @param trustStorePath Path to truststore, if absent is not used. |
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +6 −3
| @@ -33,7 +33,7 @@ | ||
| 33 | 33 | import static org.testng.Assert.assertTrue; |
| 34 | 34 | import static org.testng.Assert.fail; |
| 35 | 35 | |
| 36 | - | |
| 36 | +import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; | |
| 37 | 37 | |
| 38 | 38 | /** |
| 39 | 39 | * Simple test of the Sessions methods against a one node cluster. |
| @@ -173,7 +173,10 @@ | ||
| 173 | 173 | |
| 174 | 174 | // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster |
| 175 | 175 | // (note the use of newSession below) |
| 176 | - final Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress)).build(); | |
| 176 | + final Cluster cluster = Cluster.builder() | |
| 177 | + .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 178 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 179 | + .build(); | |
| 177 | 180 | final Session session = cluster.newSession(); |
| 178 | 181 | |
| 179 | 182 | // Spawn two threads to simulate the race |
| @@ -209,7 +212,7 @@ | ||
| 209 | 212 | startLatch.countDown(); |
| 210 | 213 | |
| 211 | 214 | executor.shutdown(); |
| 212 | - boolean normalShutdown = executor.awaitTermination(1, TimeUnit.SECONDS); | |
| 215 | + boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS); | |
| 213 | 216 | assertTrue(normalShutdown); |
| 214 | 217 | |
| 215 | 218 | // The deadlock occurred here before JAVA-418 |
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +10 −0
| @@ -48,4 +48,14 @@ | ||
| 48 | 48 | assertThat(actual).isSameAs(expected); |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | + @Test(groups = "unit") | |
| 52 | + public void should_return_number_of_values() { | |
| 53 | + assertThat( | |
| 54 | + new SimpleStatement("doesn't matter").valuesCount() | |
| 55 | + ).isEqualTo(0); | |
| 56 | + assertThat( | |
| 57 | + new SimpleStatement("doesn't matter", 1, 2).valuesCount() | |
| 58 | + ).isEqualTo(2); | |
| 59 | + } | |
| 60 | + | |
| 51 | 61 | } |
added driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java +40 −0
| @@ -0,0 +1,40 @@ | ||
| 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 | +public class StateListenerBase implements Host.StateListener { | |
| 19 | + @Override | |
| 20 | + public void onAdd(Host host) { | |
| 21 | + } | |
| 22 | + | |
| 23 | + @Override | |
| 24 | + public void onUp(Host host) { | |
| 25 | + } | |
| 26 | + | |
| 27 | + @Override | |
| 28 | + public void onSuspected(Host host) { | |
| 29 | + | |
| 30 | + } | |
| 31 | + | |
| 32 | + @Override | |
| 33 | + public void onDown(Host host) { | |
| 34 | + } | |
| 35 | + | |
| 36 | + @Override | |
| 37 | + public void onRemove(Host host) { | |
| 38 | + } | |
| 39 | + | |
| 40 | +} | |
| No newline at the end of the file |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +47 −0
| @@ -23,8 +23,11 @@ | ||
| 23 | 23 | import java.net.ServerSocket; |
| 24 | 24 | import java.nio.ByteBuffer; |
| 25 | 25 | import java.util.*; |
| 26 | +import java.util.concurrent.CountDownLatch; | |
| 27 | +import java.util.concurrent.TimeUnit; | |
| 26 | 28 | |
| 27 | 29 | import com.google.common.util.concurrent.Futures; |
| 30 | +import io.netty.channel.EventLoopGroup; | |
| 28 | 31 | import org.scassandra.Scassandra; |
| 29 | 32 | import org.scassandra.ScassandraFactory; |
| 30 | 33 | import org.slf4j.Logger; |
| @@ -382,6 +385,38 @@ | ||
| 382 | 385 | } |
| 383 | 386 | } |
| 384 | 387 | |
| 388 | + public static Host findOrWaitForHost(Cluster cluster, int node, long duration, TimeUnit unit) { | |
| 389 | + return findOrWaitForHost(cluster, CCMBridge.ipOfNode(node), duration, unit); | |
| 390 | + } | |
| 391 | + | |
| 392 | + public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) { | |
| 393 | + Host host = findHost(cluster, address); | |
| 394 | + if(host == null) { | |
| 395 | + final CountDownLatch addSignal = new CountDownLatch(1); | |
| 396 | + Host.StateListener addListener = new StateListenerBase() { | |
| 397 | + @Override | |
| 398 | + public void onAdd(Host host) { | |
| 399 | + if(host.getAddress().getHostAddress().equals(address)) { | |
| 400 | + // for a new node, because of this we also listen for add events. | |
| 401 | + addSignal.countDown(); | |
| 402 | + } | |
| 403 | + } | |
| 404 | + }; | |
| 405 | + cluster.register(addListener); | |
| 406 | + try { | |
| 407 | + // Wait until an add event occurs or we timeout. | |
| 408 | + if (addSignal.await(duration, unit)) { | |
| 409 | + host = findHost(cluster, address); | |
| 410 | + } | |
| 411 | + } catch (InterruptedException e) { | |
| 412 | + return null; | |
| 413 | + } finally { | |
| 414 | + cluster.unregister(addListener); | |
| 415 | + } | |
| 416 | + } | |
| 417 | + return host; | |
| 418 | + } | |
| 419 | + | |
| 385 | 420 | public static Host findHost(Cluster cluster, int hostNumber) { |
| 386 | 421 | return findHost(cluster, CCMBridge.ipOfNode(hostNumber)); |
| 387 | 422 | } |
| @@ -473,4 +508,16 @@ | ||
| 473 | 508 | .setRefreshNodeListIntervalMillis(0) |
| 474 | 509 | .setRefreshSchemaIntervalMillis(0); |
| 475 | 510 | } |
| 511 | + | |
| 512 | + /** | |
| 513 | + * A custom {@link NettyOptions} that shuts down the {@link EventLoopGroup} after | |
| 514 | + * no quiet time. This is useful for tests that consistently close clusters as | |
| 515 | + * otherwise there is a 2 second delay (from JAVA-914). | |
| 516 | + */ | |
| 517 | + public static NettyOptions nonQuietClusterCloseOptions = new NettyOptions() { | |
| 518 | + @Override | |
| 519 | + public void onClusterClose(EventLoopGroup eventLoopGroup) { | |
| 520 | + eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly(); | |
| 521 | + } | |
| 522 | + }; | |
| 476 | 523 | } |
added driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java +168 −0
| @@ -0,0 +1,168 @@ | ||
| 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.policies; | |
| 17 | + | |
| 18 | +import java.net.InetSocketAddress; | |
| 19 | +import java.util.Collection; | |
| 20 | + | |
| 21 | +import com.google.common.base.Predicate; | |
| 22 | +import com.google.common.base.Predicates; | |
| 23 | +import com.google.common.collect.Iterators; | |
| 24 | +import com.google.common.collect.Lists; | |
| 25 | +import org.mockito.ArgumentCaptor; | |
| 26 | +import org.mockito.Captor; | |
| 27 | +import org.mockito.Mock; | |
| 28 | +import org.mockito.MockitoAnnotations; | |
| 29 | +import org.testng.annotations.BeforeMethod; | |
| 30 | +import org.testng.annotations.Test; | |
| 31 | + | |
| 32 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 33 | +import static org.mockito.Mockito.*; | |
| 34 | + | |
| 35 | +import com.datastax.driver.core.Cluster; | |
| 36 | +import com.datastax.driver.core.Host; | |
| 37 | +import com.datastax.driver.core.HostDistance; | |
| 38 | +import com.datastax.driver.core.Statement; | |
| 39 | + | |
| 40 | +public class HostFilterPolicyTest { | |
| 41 | + @Mock | |
| 42 | + Cluster cluster; | |
| 43 | + | |
| 44 | + @Mock | |
| 45 | + Host host1, host2, host3; | |
| 46 | + | |
| 47 | + InetSocketAddress address1 = InetSocketAddress.createUnresolved("192.168.1.1", 2345); | |
| 48 | + InetSocketAddress address2 = InetSocketAddress.createUnresolved("192.168.1.2", 9876); | |
| 49 | + InetSocketAddress address3 = InetSocketAddress.createUnresolved("192.168.1.3", 6666); | |
| 50 | + | |
| 51 | + @Mock | |
| 52 | + CloseableLoadBalancingPolicy wrappedPolicy; | |
| 53 | + | |
| 54 | + @Captor | |
| 55 | + ArgumentCaptor<Collection<Host>> hostsCaptor; | |
| 56 | + | |
| 57 | + @BeforeMethod(groups = "unit") | |
| 58 | + public void setup() { | |
| 59 | + MockitoAnnotations.initMocks(this); | |
| 60 | + | |
| 61 | + when(host1.getSocketAddress()).thenReturn(address1); | |
| 62 | + when(host2.getSocketAddress()).thenReturn(address2); | |
| 63 | + when(host3.getSocketAddress()).thenReturn(address3); | |
| 64 | + | |
| 65 | + when(wrappedPolicy.distance(any(Host.class))).thenReturn(HostDistance.LOCAL); | |
| 66 | + } | |
| 67 | + | |
| 68 | + @Test(groups = "unit") | |
| 69 | + public void should_delegate_to_wrapped_policy_when_predicate_is_true() { | |
| 70 | + Predicate<Host> predicate = Predicates.alwaysTrue(); | |
| 71 | + HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate); | |
| 72 | + | |
| 73 | + policy.onAdd(host1); | |
| 74 | + verify(wrappedPolicy).onAdd(host1); | |
| 75 | + | |
| 76 | + policy.onDown(host1); | |
| 77 | + verify(wrappedPolicy).onDown(host1); | |
| 78 | + | |
| 79 | + policy.onUp(host1); | |
| 80 | + verify(wrappedPolicy).onUp(host1); | |
| 81 | + | |
| 82 | + policy.onRemove(host1); | |
| 83 | + verify(wrappedPolicy).onRemove(host1); | |
| 84 | + | |
| 85 | + assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL); | |
| 86 | + | |
| 87 | + policy.close(); | |
| 88 | + verify(wrappedPolicy).close(); | |
| 89 | + } | |
| 90 | + | |
| 91 | + @Test(groups = "unit") | |
| 92 | + public void should_not_delegate_to_wrapped_policy_when_predicate_is_false() { | |
| 93 | + Predicate<Host> predicate = Predicates.alwaysFalse(); | |
| 94 | + HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate); | |
| 95 | + | |
| 96 | + policy.onAdd(host1); | |
| 97 | + verify(wrappedPolicy, never()).onAdd(host1); | |
| 98 | + | |
| 99 | + policy.onDown(host1); | |
| 100 | + verify(wrappedPolicy, never()).onDown(host1); | |
| 101 | + | |
| 102 | + policy.onUp(host1); | |
| 103 | + verify(wrappedPolicy, never()).onUp(host1); | |
| 104 | + | |
| 105 | + policy.onRemove(host1); | |
| 106 | + verify(wrappedPolicy, never()).onRemove(host1); | |
| 107 | + | |
| 108 | + assertThat(policy.distance(host1)).isSameAs(HostDistance.IGNORED); | |
| 109 | + } | |
| 110 | + | |
| 111 | + @Test(groups = "unit") | |
| 112 | + public void should_filter_init_hosts_with_predicate() { | |
| 113 | + Predicate<Host> predicate = Predicates.in(Lists.newArrayList(host1, host2)); | |
| 114 | + HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate); | |
| 115 | + | |
| 116 | + policy.init(cluster, Lists.newArrayList(host1, host2, host3)); | |
| 117 | + | |
| 118 | + verify(wrappedPolicy).init(eq(cluster), hostsCaptor.capture()); | |
| 119 | + assertThat(hostsCaptor.getValue()).containsOnly(host1, host2); | |
| 120 | + } | |
| 121 | + | |
| 122 | + @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class) | |
| 123 | + public void should_throw_if_predicate_filters_out_all_init_hosts() { | |
| 124 | + Predicate<Host> predicate = Predicates.alwaysFalse(); | |
| 125 | + HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate); | |
| 126 | + | |
| 127 | + policy.init(cluster, Lists.newArrayList(host1, host2, host3)); | |
| 128 | + } | |
| 129 | + | |
| 130 | + @Test(groups = "unit") | |
| 131 | + public void should_return_query_plan_of_wrapped_policy() { | |
| 132 | + when(wrappedPolicy.newQueryPlan(any(String.class), any(Statement.class))) | |
| 133 | + .thenReturn(Iterators.forArray(host1, host2, host3)); | |
| 134 | + | |
| 135 | + HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, null); | |
| 136 | + | |
| 137 | + assertThat(policy.newQueryPlan("keyspace", mock(Statement.class))) | |
| 138 | + .containsExactly(host1, host2, host3); | |
| 139 | + } | |
| 140 | + | |
| 141 | + @Test(groups = "unit") | |
| 142 | + public void should_ignore_DCs_in_black_list() { | |
| 143 | + when(host1.getDatacenter()).thenReturn("dc1"); | |
| 144 | + when(host2.getDatacenter()).thenReturn("dc2"); | |
| 145 | + when(host3.getDatacenter()).thenReturn(null); | |
| 146 | + | |
| 147 | + HostFilterPolicy policy = HostFilterPolicy.fromDCBlackList(wrappedPolicy, | |
| 148 | + Lists.newArrayList("dc2")); | |
| 149 | + | |
| 150 | + assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL); | |
| 151 | + assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED); | |
| 152 | + assertThat(policy.distance(host3)).isSameAs(HostDistance.LOCAL); | |
| 153 | + } | |
| 154 | + | |
| 155 | + @Test(groups = "unit") | |
| 156 | + public void should_ignore_DCs_not_in_white_list_and_not_null() { | |
| 157 | + when(host1.getDatacenter()).thenReturn("dc1"); | |
| 158 | + when(host2.getDatacenter()).thenReturn("dc2"); | |
| 159 | + when(host3.getDatacenter()).thenReturn(null); | |
| 160 | + | |
| 161 | + HostFilterPolicy policy = HostFilterPolicy.fromDCWhiteList(wrappedPolicy, | |
| 162 | + Lists.newArrayList("dc1")); | |
| 163 | + | |
| 164 | + assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL); | |
| 165 | + assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED); | |
| 166 | + assertThat(policy.distance(host3)).isSameAs(HostDistance.LOCAL); | |
| 167 | + } | |
| 168 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +7 −0
| @@ -22,6 +22,7 @@ | ||
| 22 | 22 | import com.google.common.collect.Lists; |
| 23 | 23 | import com.google.common.collect.MapMaker; |
| 24 | 24 | import com.google.common.util.concurrent.ThreadFactoryBuilder; |
| 25 | +import io.netty.channel.EventLoopGroup; | |
| 25 | 26 | import io.netty.channel.socket.SocketChannel; |
| 26 | 27 | import org.slf4j.Logger; |
| 27 | 28 | import org.slf4j.LoggerFactory; |
| @@ -53,10 +54,16 @@ | ||
| 53 | 54 | private final AtomicLong channelsCreated = new AtomicLong(0); |
| 54 | 55 | |
| 55 | 56 | private final NettyOptions nettyOptions = new NettyOptions() { |
| 57 | + @Override | |
| 56 | 58 | public void afterChannelInitialized(SocketChannel channel) throws Exception { |
| 57 | 59 | channels.add(channel); |
| 58 | 60 | channelsCreated.incrementAndGet(); |
| 59 | 61 | } |
| 62 | + | |
| 63 | + @Override | |
| 64 | + public void onClusterClose(EventLoopGroup eventLoopGroup) { | |
| 65 | + eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly(); | |
| 66 | + } | |
| 60 | 67 | }; |
| 61 | 68 | |
| 62 | 69 | @Override |
added features/ssl/README.md +180 −0
| @@ -0,0 +1,180 @@ | ||
| 1 | +## SSL | |
| 2 | + | |
| 3 | +You can secure traffic between the driver and Cassandra with SSL. There | |
| 4 | +are two aspects to that: | |
| 5 | + | |
| 6 | +* **client-to-node encryption**, where the traffic is encrypted, and the | |
| 7 | + client verifies the identity of the Cassandra nodes it connects to; | |
| 8 | +* optionally, **client certificate authentication**, where Cassandra | |
| 9 | + nodes also verify the identity of the client. | |
| 10 | + | |
| 11 | +This section describes the driver-side configuration; it assumes that | |
| 12 | +you've already configured SSL in Cassandra: | |
| 13 | + | |
| 14 | +* [the Cassandra documentation](http://docs.datastax.com/en/cassandra/2.0/cassandra/security/secureSSLClientToNode_t.html) | |
| 15 | + covers a basic approach with self-signed certificates, which is fine | |
| 16 | + for development and tests. | |
| 17 | +* [this blog post](http://thelastpickle.com/blog/2015/09/30/hardening-cassandra-step-by-step-part-1-server-to-server.html) | |
| 18 | + details a more advanced solution based on a Certificate Authority | |
| 19 | + (CA). | |
| 20 | + | |
| 21 | +### Preparing the certificates | |
| 22 | + | |
| 23 | +#### Client truststore | |
| 24 | + | |
| 25 | +This is required for client-to-node encryption. | |
| 26 | + | |
| 27 | +If you're using self-signed certificates, you need to export the public | |
| 28 | +part of each node's certificate from that node's keystore: | |
| 29 | + | |
| 30 | +``` | |
| 31 | +keytool -export -alias cassandra -file cassandranode0.cer -keystore .keystore | |
| 32 | +``` | |
| 33 | + | |
| 34 | +Then add all public certificates to the client truststore: | |
| 35 | + | |
| 36 | +``` | |
| 37 | +keytool -import -v -trustcacerts -alias <cassandra_node0> -file cassandranode0.cer -keystore client.truststore | |
| 38 | +keytool -import -v -trustcacerts -alias <cassandra_node1> -file cassandranode1.cer -keystore client.truststore | |
| 39 | +... | |
| 40 | +``` | |
| 41 | + | |
| 42 | +If you're using a Certificate Authority, the client truststore only | |
| 43 | +needs to contain the CA's certificate: | |
| 44 | + | |
| 45 | +``` | |
| 46 | +keytool -import -v -trustcacerts -alias CARoot -file ca.cer -keystore client.truststore | |
| 47 | +``` | |
| 48 | + | |
| 49 | +#### Client keystore | |
| 50 | + | |
| 51 | +If you also intend to use client certificate authentication, generate | |
| 52 | +the public and private key pair for the client: | |
| 53 | + | |
| 54 | +``` | |
| 55 | +keytool -genkey -keyalg RSA -alias client -keystore client.keystore | |
| 56 | +``` | |
| 57 | + | |
| 58 | +If you're using self-signed certificates, extract the public part of the | |
| 59 | +client certificate, and import it in the truststore of each Cassandra | |
| 60 | +node: | |
| 61 | + | |
| 62 | +``` | |
| 63 | +keytool -export -alias client -file client.cer -keystore client.keystore | |
| 64 | +keytool -import -v -trustcacerts -alias client -file client.cer -keystore server.truststore | |
| 65 | +``` | |
| 66 | + | |
| 67 | +If you're using a CA, sign the client certificate with it (see the blog | |
| 68 | +post linked at the top of this page). Then the nodes' truststores only | |
| 69 | +need to contain the CA's certificate (which should already be the case | |
| 70 | +if you've followed the steps for inter-node encryption). | |
| 71 | + | |
| 72 | +### Driver configuration | |
| 73 | + | |
| 74 | +#### Property-based | |
| 75 | + | |
| 76 | +`withSSL()` gives you a basic JSSE configuration: | |
| 77 | + | |
| 78 | +```java | |
| 79 | +Cluster cluster = Cluster.builder() | |
| 80 | + .addContactPoint("127.0.0.1") | |
| 81 | + .withSSL() | |
| 82 | + .build(); | |
| 83 | +``` | |
| 84 | + | |
| 85 | +You can then use | |
| 86 | +[JSSE system properties](http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization) | |
| 87 | +for specific details, like keystore locations and passwords: | |
| 88 | + | |
| 89 | +``` | |
| 90 | +-Djavax.net.ssl.trustStore=/path/to/client.truststore | |
| 91 | +-Djavax.net.ssl.trustStorePassword=password123 | |
| 92 | +# If you're using client authentication: | |
| 93 | +-Djavax.net.ssl.keyStore=/path/to/client.keystore | |
| 94 | +-Djavax.net.ssl.keyStorePassword=password123 | |
| 95 | +``` | |
| 96 | + | |
| 97 | +#### Programmatic | |
| 98 | + | |
| 99 | +If you need more control than what system properties allow, you can | |
| 100 | +configure SSL programmatically by creating an [SSLOptions] instance: | |
| 101 | + | |
| 102 | +```java | |
| 103 | +SSLContext sslContext = ... // create and configure SSL context | |
| 104 | +String[] cipherSuites = ... | |
| 105 | + | |
| 106 | +SSLOptions sslOptions = new SSLOptions(sslContext, cipherSuites); | |
| 107 | + | |
| 108 | +Cluster cluster = Cluster.builder() | |
| 109 | + .addContactPoint("127.0.0.1") | |
| 110 | + .withSSL(sslOptions) | |
| 111 | + .build(); | |
| 112 | +``` | |
| 113 | + | |
| 114 | +A known limitation of the current API is that you can't customize the | |
| 115 | +`SSLEngine`, which prevents advanced features like hostname | |
| 116 | +verification. This will be fixed in 3.0 (see | |
| 117 | +[JAVA-841](https://datastax-oss.atlassian.net/browse/JAVA-841)), in the | |
| 118 | +meantime see below for a workaround. | |
| 119 | + | |
| 120 | + | |
| 121 | +### Bypassing `SSLOptions` | |
| 122 | + | |
| 123 | +For advanced use cases, it's possible to bypass `SSLOptions` entirely: | |
| 124 | +since the driver provides a hook into the Netty pipeline (by way of | |
| 125 | +[NettyOptions]), you can add the SSL handler yourself: | |
| 126 | + | |
| 127 | +```java | |
| 128 | +import io.netty.handler.ssl.SslHandler; | |
| 129 | +import javax.net.ssl.SSLContext; | |
| 130 | +import javax.net.ssl.SSLEngine; | |
| 131 | + | |
| 132 | +// Base implementation: each time a connection is established, create an SSL handler | |
| 133 | +// and add it to the pipeline: | |
| 134 | +public abstract class SslNettyOptions extends NettyOptions { | |
| 135 | + @Override | |
| 136 | + public void afterChannelInitialized(SocketChannel channel) throws Exception { | |
| 137 | + channel.pipeline().addFirst("ssl", createSslHandler(channel)); | |
| 138 | + } | |
| 139 | + | |
| 140 | + protected abstract SslHandler createSslHandler(SocketChannel channel); | |
| 141 | +} | |
| 142 | + | |
| 143 | +// Concrete implementation based on JSSE | |
| 144 | +public class MyNettyOptions extends SslNettyOptions { | |
| 145 | + | |
| 146 | + private final SSLContext sslContext = createContext(); | |
| 147 | + | |
| 148 | + protected SslHandler createSslHandler(SocketChannel channel) { | |
| 149 | + return new SslHandler(createEngine(sslContext, channel)); | |
| 150 | + } | |
| 151 | + | |
| 152 | + private static SSLContext createContext() { | |
| 153 | + ... // create and configure context | |
| 154 | + } | |
| 155 | + | |
| 156 | + private static SSLEngine createEngine(SSLContext sslContext, SocketChannel channel) { | |
| 157 | + SSLEngine engine = sslContext.createSSLEngine(); | |
| 158 | + engine.setUseClientMode(true); | |
| 159 | + ... // any extra configuration | |
| 160 | + return engine; | |
| 161 | + } | |
| 162 | +} | |
| 163 | + | |
| 164 | +cluster = Cluster.builder() | |
| 165 | + .addContactPoint("127.0.0.1") | |
| 166 | + .withNettyOptions(new MyNettyOptions()) | |
| 167 | + .build(); | |
| 168 | +``` | |
| 169 | + | |
| 170 | +This could be used for the following use cases: | |
| 171 | + | |
| 172 | +* fine control over JSSE configuration, for example tuning the SSL | |
| 173 | + engine for hostname verification; | |
| 174 | +* bypassing JSSE altogether in favor of another SSL implementation: | |
| 175 | + recent Netty versions support | |
| 176 | + [OpenSSL](http://netty.io/wiki/forked-tomcat-native.html) | |
| 177 | + for improved performance. | |
| 178 | + | |
| 179 | +[SSLOptions]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SSLOptions.html | |
| 180 | +[NettyOptions]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/NettyOptions.html |