kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 1c1573fc91251a8ce8f8777ea4340492993037c8f12172d7d56d2823e8ef6738 |
|---|---|
| Author | Alexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-12 13:52 +01:00 |
| Committer | Alexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-12 13:52 +01:00 |
| Parents | 82394f45c894, e0535ea4aa45 |
59 files changed
modified README.md +5 −1
| @@ -67,7 +67,7 @@ | ||
| 67 | 67 | |
| 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 | -## Maven | |
| 70 | +## Getting the driver | |
| 71 | 71 | |
| 72 | 72 | The last release of the driver is available on Maven Central. You can install |
| 73 | 73 | it in your application using the following Maven dependency: |
| @@ -93,6 +93,10 @@ | ||
| 93 | 93 | We also provide a [shaded JAR](features/shaded_jar/) |
| 94 | 94 | to avoid the explicit dependency to Netty. |
| 95 | 95 | |
| 96 | +If you can't use a dependency management tool, a | |
| 97 | +[binary tarball](http://downloads.datastax.com/java-driver/cassandra-java-driver-3.0.0-alpha4.tar.gz) | |
| 98 | +is available for download. | |
| 99 | + | |
| 96 | 100 | ## Compatibility |
| 97 | 101 | |
| 98 | 102 | The Java client driver 3.0 ([branch 3.0](https://github.com/datastax/java-driver/tree/3.0)) is compatible with Apache |
modified changelog/README.md +105 −0
| @@ -9,6 +9,22 @@ | ||
| 9 | 9 | - [improvement] Raise an exception when an older version of guava (<16.01) is found (JAVA-961) |
| 10 | 10 | - [bug] TypeCodec.parse() implementations should be case insensitive when checking for keyword NULL (JAVA-972) |
| 11 | 11 | |
| 12 | +Merged from 2.1 branch: | |
| 13 | + | |
| 14 | +- [bug] JAVA-854: avoid early return in Cluster.init when a node doesn't support the protocol version. | |
| 15 | +- [bug] JAVA-978: Fix quoting issue that caused Mapper.getTableMetadata() to return null. | |
| 16 | +- [improvement] JAVA-920: Downgrade "error creating pool" message to WARN. | |
| 17 | +- [bug] JAVA-954: Don't trigger reconnection before initialization complete. | |
| 18 | +- [improvement] JAVA-914: Avoid rejected tasks at shutdown. | |
| 19 | +- [improvement] JAVA-921: Add SimpleStatement.getValuesCount(). | |
| 20 | +- [bug] JAVA-901: Move call to connection.release() out of cancelHandler. | |
| 21 | +- [bug] JAVA-960: Avoid race in control connection shutdown. | |
| 22 | +- [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo. | |
| 23 | +- [bug] JAVA-966: Count uninitialized connections in conviction policy. | |
| 24 | +- [improvement] JAVA-917: Document SSL configuration. | |
| 25 | +- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder. | |
| 26 | +- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs. | |
| 27 | + | |
| 12 | 28 | ### 3.0.0-alpha4 |
| 13 | 29 | |
| 14 | 30 | - [improvement] Change default consistency level to LOCAL_QUORUM (JAVA-926) |
| @@ -196,6 +212,79 @@ | ||
| 196 | 212 | - [improvement] Unify "Target" enum for schema elements (JAVA-782) |
| 197 | 213 | |
| 198 | 214 | |
| 215 | +### 2.1.9 | |
| 216 | + | |
| 217 | +- [bug] Fix implementation of UserType.hashCode() (JAVA-942) | |
| 218 | +- [bug] JAVA-854: avoid early return in Cluster.init when a node doesn't support the protocol version. | |
| 219 | +- [bug] JAVA-978: Fix quoting issue that caused Mapper.getTableMetadata() to return null. | |
| 220 | + | |
| 221 | +Merged from 2.0 branch: | |
| 222 | + | |
| 223 | +- [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace. | |
| 224 | +- [improvement] JAVA-920: Downgrade "error creating pool" message to WARN. | |
| 225 | +- [bug] JAVA-954: Don't trigger reconnection before initialization complete. | |
| 226 | +- [improvement] JAVA-914: Avoid rejected tasks at shutdown. | |
| 227 | +- [improvement] JAVA-921: Add SimpleStatement.getValuesCount(). | |
| 228 | +- [bug] JAVA-901: Move call to connection.release() out of cancelHandler. | |
| 229 | +- [bug] JAVA-960: Avoid race in control connection shutdown. | |
| 230 | +- [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo. | |
| 231 | +- [bug] JAVA-966: Count uninitialized connections in conviction policy. | |
| 232 | +- [improvement] JAVA-917: Document SSL configuration. | |
| 233 | +- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder. | |
| 234 | +- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs. | |
| 235 | + | |
| 236 | + | |
| 237 | +### 2.1.8 | |
| 238 | + | |
| 239 | +Merged from 2.0 branch: | |
| 240 | + | |
| 241 | +- [improvement] Log streamid at the trace level on sending request and receiving response (JAVA-718) | |
| 242 | + | |
| 243 | +- [bug] Fix SpeculativeExecutionPolicy.init() and close() are never called (JAVA-796) | |
| 244 | +- [improvement] Suppress unnecessary warning at shutdown (JAVA-710) | |
| 245 | +- [improvement] Allow DNS name with multiple A-records as contact point (#340) | |
| 246 | +- [bug] Allow tracing across multiple result pages (JAVA-794) | |
| 247 | +- [bug] DowngradingConsistencyRetryPolicy ignores write timeouts (JAVA-737) | |
| 248 | +- [bug] Forbid bind marker in QueryBuilder add/append/prepend (JAVA-736) | |
| 249 | +- [bug] Prevent QueryBuilder.quote() from applying duplicate double quotes (JAVA-712) | |
| 250 | +- [bug] Prevent QueryBuilder from trying to serialize raw string (JAVA-688) | |
| 251 | +- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679) | |
| 252 | +- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475) | |
| 253 | +- [improvement] Create values() function for Insert builder using List (JAVA-225) | |
| 254 | +- [improvement] Warn when ReplicationStrategy encounters invalid | |
| 255 | + replication factors (JAVA-702) | |
| 256 | +- [improvement] Add PoolingOptions method to set both core and max | |
| 257 | + connections (JAVA-662). | |
| 258 | +- [improvement] Do not include epoll JAR in binary distribution (JAVA-766) | |
| 259 | +- [improvement] Optimize internal copies of Request objects (JAVA-726) | |
| 260 | +- [bug] Preserve tracing across retries (JAVA-815) | |
| 261 | +- [improvement] New RetryDecision.tryNextHost() (JAVA-709) | |
| 262 | +- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733) | |
| 263 | +- [improvement] Provide API to retrieve values of a Parameterized SimpleStatement (JAVA-765) | |
| 264 | +- [improvement] implement UPDATE ... IF EXISTS in QueryBuilder (JAVA-827) | |
| 265 | +- [improvement] Randomize contact points list to prevent hotspots (JAVA-618) | |
| 266 | +- [improvement] Surface the coordinator used on query failure (JAVA-720) | |
| 267 | +- [bug] Handle contact points removed during init (JAVA-792) | |
| 268 | +- [improvement] Allow PlainTextAuthProvider to change its credentials at runtime (JAVA-719) | |
| 269 | +- [new feature] Make it possible to register for SchemaChange Events (JAVA-151) | |
| 270 | +- [improvement] Downgrade "Asked to rebuild table" log from ERROR to INFO level (JAVA-861) | |
| 271 | +- [improvement] Provide an option to prepare statements only on one node (JAVA-797) | |
| 272 | +- [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658) | |
| 273 | +- [improvement] Customizable creation of netty timer (JAVA-853) | |
| 274 | +- [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859) | |
| 275 | +- [improvement] Debounce control connection queries (JAVA-657) | |
| 276 | +- [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784) | |
| 277 | +- [new feature] Make driver-side metadata optional (JAVA-828) | |
| 278 | +- [improvement] Allow hosts to remain partially up (JAVA-544) | |
| 279 | +- [improvement] Remove internal blocking calls and expose async session | |
| 280 | + creation (JAVA-821, JAVA-822) | |
| 281 | +- [improvement] Use parallel calls when re-preparing statement on other | |
| 282 | + hosts (JAVA-725) | |
| 283 | +- [bug] Don't use connection timeout for unrelated internal queries (JAVA-629) | |
| 284 | +- [bug] Fix NPE in speculative executions when metrics disabled | |
| 285 | + (JAVA-892) | |
| 286 | + | |
| 287 | + | |
| 199 | 288 | ### 2.1.7.1 |
| 200 | 289 | |
| 201 | 290 | - [bug] Special case check for 'null' string in index_options column (JAVA-834) |
| @@ -458,6 +547,22 @@ | ||
| 458 | 547 | - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391) |
| 459 | 548 | |
| 460 | 549 | |
| 550 | +### 2.0.12 | |
| 551 | + | |
| 552 | +- [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace. | |
| 553 | +- [improvement] JAVA-920: Downgrade "error creating pool" message to WARN. | |
| 554 | +- [bug] JAVA-954: Don't trigger reconnection before initialization complete. | |
| 555 | +- [improvement] JAVA-914: Avoid rejected tasks at shutdown. | |
| 556 | +- [improvement] JAVA-921: Add SimpleStatement.getValuesCount(). | |
| 557 | +- [bug] JAVA-901: Move call to connection.release() out of cancelHandler. | |
| 558 | +- [bug] JAVA-960: Avoid race in control connection shutdown. | |
| 559 | +- [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo. | |
| 560 | +- [bug] JAVA-966: Count uninitialized connections in conviction policy. | |
| 561 | +- [improvement] JAVA-917: Document SSL configuration. | |
| 562 | +- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder. | |
| 563 | +- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs. | |
| 564 | + | |
| 565 | + | |
| 461 | 566 | ### 2.0.11 |
| 462 | 567 | |
| 463 | 568 | - [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 +11 −9
| @@ -280,7 +280,7 @@ | ||
| 280 | 280 | * be contacted to set the {@code keyspace}. |
| 281 | 281 | * @throws AuthenticationException if an authentication error occurs while |
| 282 | 282 | * contacting the initial contact points. |
| 283 | - * @throws InvalidQueryException if the keyspace does not exists. | |
| 283 | + * @throws InvalidQueryException if the keyspace does not exist. | |
| 284 | 284 | * @throws IllegalStateException if the Cluster was closed prior to calling |
| 285 | 285 | * this method. This can occur either directly (through {@link #close()} or |
| 286 | 286 | * {@link #closeAsync()}), or as a result of an error while initializing the |
| @@ -421,8 +421,8 @@ | ||
| 421 | 421 | * The cluster metrics. |
| 422 | 422 | * |
| 423 | 423 | * @return the cluster metrics, or {@code null} if metrics collection has |
| 424 | - * been disabled (that is if {@code cluster.getConfiguration().getMetricsOptions().isEnabled()} | |
| 425 | - * returns {@code false}). | |
| 424 | + * been disabled (that is if {@link Configuration#getMetricsOptions} | |
| 425 | + * returns {@code null}). | |
| 426 | 426 | */ |
| 427 | 427 | public Metrics getMetrics() { |
| 428 | 428 | checkNotClosed(manager); |
| @@ -915,7 +915,7 @@ | ||
| 915 | 915 | * this one. However, this can be useful if the Cassandra nodes are behind |
| 916 | 916 | * a router and are not accessed directly. Note that if you are in this |
| 917 | 917 | * situtation (Cassandra nodes are behind a router, not directly accessible), |
| 918 | - * you almost surely want to provide a specific {@code AddressTranslator} | |
| 918 | + * you almost surely want to provide a specific {@link AddressTranslator} | |
| 919 | 919 | * (through {@link #withAddressTranslator}) to translate actual Cassandra node |
| 920 | 920 | * addresses to the addresses the driver should use, otherwise the driver |
| 921 | 921 | * will not be able to auto-detect new nodes (and will generally not function |
| @@ -1443,6 +1443,7 @@ | ||
| 1443 | 1443 | loadBalancingPolicy().onDown(host); |
| 1444 | 1444 | for (Host.StateListener listener : listeners) |
| 1445 | 1445 | listener.onDown(host); |
| 1446 | + startPeriodicReconnectionAttempt(host, true); | |
| 1446 | 1447 | } |
| 1447 | 1448 | |
| 1448 | 1449 | configuration.getPoolingOptions().setProtocolVersion(protocolVersion()); |
| @@ -1459,7 +1460,7 @@ | ||
| 1459 | 1460 | |
| 1460 | 1461 | if (!connectionFactory.protocolVersion.isSupportedBy(host)) { |
| 1461 | 1462 | logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion); |
| 1462 | - return; | |
| 1463 | + continue; | |
| 1463 | 1464 | } |
| 1464 | 1465 | |
| 1465 | 1466 | if (!contactPointHosts.contains(host)) |
| @@ -2039,14 +2040,15 @@ | ||
| 2039 | 2040 | } |
| 2040 | 2041 | } |
| 2041 | 2042 | |
| 2042 | - public boolean signalConnectionFailure(Host host, ConnectionException exception, | |
| 2043 | - boolean connectionInitialized, boolean isHostAddition) { | |
| 2044 | - // Don't signal failure until we've fully initialized the controlConnection as this might mess up with | |
| 2043 | + public boolean signalConnectionFailure(Host host, Connection connection, | |
| 2044 | + boolean isHostAddition) { | |
| 2045 | + boolean isDown = host.convictionPolicy.signalConnectionFailure(connection); | |
| 2046 | + | |
| 2047 | + // Don't mark the node down until we've fully initialized the controlConnection as this might mess up with | |
| 2045 | 2048 | // the protocol detection |
| 2046 | 2049 | if (!isFullyInit || isClosed()) |
| 2047 | 2050 | return true; |
| 2048 | 2051 | |
| 2049 | - boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized); | |
| 2050 | 2052 | if (isDown) |
| 2051 | 2053 | triggerOnDown(host, isHostAddition, true); |
| 2052 | 2054 | return isDown; |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +76 −72
| @@ -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; |
| @@ -47,7 +49,9 @@ | ||
| 47 | 49 | import static io.netty.handler.timeout.IdleState.ALL_IDLE; |
| 48 | 50 | |
| 49 | 51 | import com.datastax.driver.core.Responses.Result.SetKeyspace; |
| 50 | -import com.datastax.driver.core.exceptions.*; | |
| 52 | +import com.datastax.driver.core.exceptions.AuthenticationException; | |
| 53 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 54 | +import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 51 | 55 | import com.datastax.driver.core.utils.MoreFutures; |
| 52 | 56 | |
| 53 | 57 | import static com.datastax.driver.core.Message.Response.Type.ERROR; |
| @@ -157,7 +161,7 @@ | ||
| 157 | 161 | logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause()))); |
| 158 | 162 | channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause())); |
| 159 | 163 | } else { |
| 160 | - logger.debug("{} Connection opened successfully", Connection.this); | |
| 164 | + logger.debug("{} Connection established, initializing transport", Connection.this); | |
| 161 | 165 | channel.closeFuture().addListener(new ChannelCloseListener()); |
| 162 | 166 | channelReadyFuture.set(null); |
| 163 | 167 | } |
| @@ -197,16 +201,8 @@ | ||
| 197 | 201 | } |
| 198 | 202 | }, initExecutor); |
| 199 | 203 | |
| 200 | - // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel. | |
| 201 | - Futures.addCallback(initFuture, new FutureCallback<Void>() { | |
| 202 | - @Override | |
| 203 | - public void onSuccess(Void result) { | |
| 204 | - Host host = factory.manager.metadata.getHost(address); | |
| 205 | - if (host != null) | |
| 206 | - host.convictionPolicy.signalConnectionCreated(); | |
| 207 | - isInitialized = true; | |
| 208 | - } | |
| 209 | - | |
| 204 | + // Ensure the connection gets closed if the caller cancels the returned future. | |
| 205 | + Futures.addCallback(initFuture, new MoreFutures.FailureCallback<Void>() { | |
| 210 | 206 | @Override |
| 211 | 207 | public void onFailure(Throwable t) { |
| 212 | 208 | if (!isClosed()) { |
| @@ -285,8 +281,10 @@ | ||
| 285 | 281 | final String expected = factory.manager.metadata.clusterName; |
| 286 | 282 | |
| 287 | 283 | // At initialization, the cluster is not known yet |
| 288 | - if (expected == null) | |
| 284 | + if (expected == null) { | |
| 285 | + markInitialized(); | |
| 289 | 286 | return MoreFutures.VOID_SUCCESS; |
| 287 | + } | |
| 290 | 288 | |
| 291 | 289 | DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null, protocolVersion, new Requests.Query("select cluster_name from system.local")); |
| 292 | 290 | try { |
| @@ -299,6 +297,7 @@ | ||
| 299 | 297 | String actual = row.getString("cluster_name"); |
| 300 | 298 | if (!expected.equals(actual)) |
| 301 | 299 | throw new ClusterNameMismatchException(address, actual, expected); |
| 300 | + markInitialized(); | |
| 302 | 301 | return MoreFutures.VOID_SUCCESS; |
| 303 | 302 | } |
| 304 | 303 | }, executor); |
| @@ -307,6 +306,11 @@ | ||
| 307 | 306 | } |
| 308 | 307 | } |
| 309 | 308 | |
| 309 | + private void markInitialized() { | |
| 310 | + isInitialized = true; | |
| 311 | + Host.statesLogger.debug("[{}] {} Transport initialized, connection ready", address, this); | |
| 312 | + } | |
| 313 | + | |
| 310 | 314 | private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) { |
| 311 | 315 | Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials()); |
| 312 | 316 | try { |
| @@ -396,33 +400,18 @@ | ||
| 396 | 400 | } |
| 397 | 401 | |
| 398 | 402 | <E extends Exception> E defunct(E e) { |
| 399 | - if (!isDefunct.compareAndSet(false, true)) | |
| 400 | - return e; | |
| 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 | - ConnectionException ce = e instanceof ConnectionException | |
| 408 | - ? (ConnectionException)e | |
| 409 | - : new ConnectionException(address, "Connection problem", e); | |
| 410 | - | |
| 411 | - Host host = factory.manager.metadata.getHost(address); | |
| 412 | - if (host != null) { | |
| 413 | - boolean isDown = factory.manager.signalConnectionFailure(host, ce, isInitialized, host.wasJustAdded()); | |
| 414 | - | |
| 415 | - if (!isDown) | |
| 416 | - notifyOwnerWhenDefunct(); | |
| 417 | - // else the driver will destroy all pools and notify the control connection as part of marking the host down, | |
| 418 | - // so no need to notify | |
| 403 | + if (isDefunct.compareAndSet(false, true)) { | |
| 404 | + | |
| 405 | + if (Host.statesLogger.isTraceEnabled()) | |
| 406 | + Host.statesLogger.trace("Defuncting " + this, e); | |
| 407 | + else if (Host.statesLogger.isDebugEnabled()) | |
| 408 | + Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); | |
| 409 | + | |
| 410 | + // Force the connection to close to make sure the future completes. Otherwise force() might never get called and | |
| 411 | + // threads will wait on the future forever. | |
| 412 | + // (this also errors out pending handlers) | |
| 413 | + closeAsync().force(); | |
| 419 | 414 | } |
| 420 | - | |
| 421 | - // Force the connection to close to make sure the future completes. Otherwise force() might never get called and | |
| 422 | - // threads will wait on the future forever. | |
| 423 | - // (this also errors out pending handlers) | |
| 424 | - closeAsync().force(); | |
| 425 | - | |
| 426 | 415 | return e; |
| 427 | 416 | } |
| 428 | 417 | |
| @@ -452,19 +441,15 @@ | ||
| 452 | 441 | } catch (ConnectionException e) { |
| 453 | 442 | throw defunct(e); |
| 454 | 443 | } catch (BusyConnectionException e) { |
| 455 | - logger.warn("Tried to set the keyspace on busy connection to {}. " | |
| 456 | - + "This should not happen but is not critical (it will be retried)", address); | |
| 444 | + logger.warn("Tried to set the keyspace on busy {}. " | |
| 445 | + + "This should not happen but is not critical (it will be retried)", this); | |
| 457 | 446 | throw new ConnectionException(address, "Tried to set the keyspace on busy connection"); |
| 458 | 447 | } catch (ExecutionException e) { |
| 459 | 448 | Throwable cause = e.getCause(); |
| 460 | 449 | if (cause instanceof OperationTimedOutException) { |
| 461 | - // The timeout logic released the connection, but that's wrong since we did not borrow it in the first place. | |
| 462 | - // JAVA-901 will fix this, in the meantime make sure the inFlight count is not off by one. | |
| 463 | - inFlight.incrementAndGet(); | |
| 464 | - | |
| 465 | 450 | // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down |
| 466 | - logger.warn("Timeout while setting keyspace on connection to {}. " | |
| 467 | - + "This should not happen but is not critical (it will be retried)", address); | |
| 451 | + logger.warn("Timeout while setting keyspace on {}. " | |
| 452 | + + "This should not happen but is not critical (it will be retried)", this); | |
| 468 | 453 | throw new ConnectionException(address, "Timeout while setting keyspace on connection"); |
| 469 | 454 | } else { |
| 470 | 455 | throw defunct(new ConnectionException(address, "Error while setting keyspace", cause)); |
| @@ -576,12 +561,14 @@ | ||
| 576 | 561 | // requires its writeLock. |
| 577 | 562 | // Therefore if multiple connections in the same pool get a write error, they could deadlock; |
| 578 | 563 | // we run defunct on a separate thread to avoid that. |
| 579 | - factory.manager.executor.execute(new Runnable() { | |
| 580 | - @Override | |
| 581 | - public void run() { | |
| 582 | - handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount); | |
| 583 | - } | |
| 584 | - }); | |
| 564 | + ListeningExecutorService executor = factory.manager.executor; | |
| 565 | + if (!executor.isShutdown()) | |
| 566 | + executor.execute(new Runnable() { | |
| 567 | + @Override | |
| 568 | + public void run() { | |
| 569 | + handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount); | |
| 570 | + } | |
| 571 | + }); | |
| 585 | 572 | } else { |
| 586 | 573 | logger.trace("{}, stream {}, request sent successfully", Connection.this, request.getStreamId()); |
| 587 | 574 | } |
| @@ -633,10 +620,18 @@ | ||
| 633 | 620 | |
| 634 | 621 | logger.debug("{} closing connection", this); |
| 635 | 622 | |
| 636 | - if (isInitialized && !isDefunct.get()) { | |
| 637 | - Host host = factory.manager.metadata.getHost(address); | |
| 638 | - if(host != null) | |
| 639 | - host.convictionPolicy.signalConnectionClosed(); | |
| 623 | + Host host = factory.manager.metadata.getHost(address); | |
| 624 | + if (host != null) { | |
| 625 | + if (isDefunct.get()) { | |
| 626 | + boolean isDown = factory.manager.signalConnectionFailure(host, this, host.wasJustAdded()); | |
| 627 | + | |
| 628 | + if (!isDown) | |
| 629 | + notifyOwnerWhenDefunct(); | |
| 630 | + // else the driver will destroy all pools and notify the control connection as part of marking the host down, | |
| 631 | + // so no need to notify | |
| 632 | + } else { | |
| 633 | + host.convictionPolicy.signalConnectionClosed(this); | |
| 634 | + } | |
| 640 | 635 | } |
| 641 | 636 | |
| 642 | 637 | boolean terminated = tryTerminate(false); |
| @@ -736,8 +731,8 @@ | ||
| 736 | 731 | if (isShutdown) |
| 737 | 732 | throw new ConnectionException(address, "Connection factory is shut down"); |
| 738 | 733 | |
| 739 | - String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement(); | |
| 740 | - Connection connection = new Connection(name, address, this); | |
| 734 | + host.convictionPolicy.signalConnectionsOpening(1); | |
| 735 | + Connection connection = new Connection(buildConnectionName(host), address, this); | |
| 741 | 736 | // This method opens the connection synchronously, so wait until it's initialized |
| 742 | 737 | try { |
| 743 | 738 | connection.initAsync().get(); |
| @@ -751,8 +746,9 @@ | ||
| 751 | 746 | * Same as open, but associate the created connection to the provided connection pool. |
| 752 | 747 | */ |
| 753 | 748 | public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 749 | + pool.host.convictionPolicy.signalConnectionsOpening(1); | |
| 750 | + Connection connection = new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool); | |
| 754 | 751 | try { |
| 755 | - Connection connection = newConnection(pool); | |
| 756 | 752 | connection.initAsync().get(); |
| 757 | 753 | return connection; |
| 758 | 754 | } catch (ExecutionException e) { |
| @@ -761,13 +757,18 @@ | ||
| 761 | 757 | } |
| 762 | 758 | |
| 763 | 759 | /** |
| 764 | - * Creates a new connection and associates it to the provided connection pool, but does not start it. | |
| 760 | + * Creates new connections and associate them to the provided connection pool, but does not start them. | |
| 765 | 761 | */ |
| 766 | - public Connection newConnection(HostConnectionPool pool) { | |
| 767 | - InetSocketAddress address = pool.host.getSocketAddress(); | |
| 768 | - String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement(); | |
| 762 | + public List<Connection> newConnections(HostConnectionPool pool, int count) { | |
| 763 | + pool.host.convictionPolicy.signalConnectionsOpening(count); | |
| 764 | + List<Connection> connections = Lists.newArrayListWithCapacity(count); | |
| 765 | + for (int i = 0; i < count; i++) | |
| 766 | + connections.add(new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool)); | |
| 767 | + return connections; | |
| 768 | + } | |
| 769 | 769 | |
| 770 | - return new Connection(name, address, this, pool); | |
| 770 | + private String buildConnectionName(Host host) { | |
| 771 | + return host.getSocketAddress().toString() + '-' + getIdGenerator(host).getAndIncrement(); | |
| 771 | 772 | } |
| 772 | 773 | |
| 773 | 774 | static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| @@ -870,9 +871,12 @@ | ||
| 870 | 871 | boolean doneWork = false; |
| 871 | 872 | FlushItem flush; |
| 872 | 873 | while (null != (flush = queued.poll())) { |
| 873 | - channels.add(flush.channel); | |
| 874 | - flush.channel.write(flush.request).addListener(flush.listener); | |
| 875 | - doneWork = true; | |
| 874 | + Channel channel = flush.channel; | |
| 875 | + if (channel.isActive()) { | |
| 876 | + channels.add(channel); | |
| 877 | + channel.write(flush.request).addListener(flush.listener); | |
| 878 | + doneWork = true; | |
| 879 | + } | |
| 876 | 880 | } |
| 877 | 881 | |
| 878 | 882 | // Always flush what we have (don't artificially delay to try to coalesce more messages) |
| @@ -892,7 +896,7 @@ | ||
| 892 | 896 | } |
| 893 | 897 | |
| 894 | 898 | EventLoop eventLoop = eventLoopRef.get(); |
| 895 | - if (eventLoop != null) { | |
| 899 | + if (eventLoop != null && !eventLoop.isShuttingDown()) { | |
| 896 | 900 | eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS); |
| 897 | 901 | } |
| 898 | 902 | } |
| @@ -1238,16 +1242,16 @@ | ||
| 1238 | 1242 | timeout.cancel(); |
| 1239 | 1243 | } |
| 1240 | 1244 | |
| 1241 | - public void cancelHandler() { | |
| 1245 | + public boolean cancelHandler() { | |
| 1242 | 1246 | if (!isCancelled.compareAndSet(false, true)) |
| 1243 | - return; | |
| 1247 | + return false; | |
| 1244 | 1248 | |
| 1245 | 1249 | // We haven't really received a response: we want to remove the handle because we gave up on that |
| 1246 | 1250 | // request and there is no point in holding the handler, but we don't release the streamId. If we |
| 1247 | 1251 | // were, a new request could reuse that ID but get the answer to the request we just gave up on instead |
| 1248 | 1252 | // of its own answer, and we would have no way to detect that. |
| 1249 | 1253 | connection.dispatcher.removeHandler(this, false); |
| 1250 | - connection.release(); | |
| 1254 | + return true; | |
| 1251 | 1255 | } |
| 1252 | 1256 | |
| 1253 | 1257 | private TimerTask onTimeoutTask() { |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +23 −3
| @@ -121,6 +121,9 @@ | ||
| 121 | 121 | new AbstractReconnectionHandler("Control connection", cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) { |
| 122 | 122 | @Override |
| 123 | 123 | protected Connection tryReconnect() throws ConnectionException { |
| 124 | + if (isShutdown) | |
| 125 | + throw new ConnectionException(null, "Control connection was shut down"); | |
| 126 | + | |
| 124 | 127 | try { |
| 125 | 128 | return reconnectInternal(queryPlan(), false); |
| 126 | 129 | } catch (NoHostAvailableException e) { |
| @@ -134,17 +137,28 @@ | ||
| 134 | 137 | |
| 135 | 138 | @Override |
| 136 | 139 | protected void onReconnection(Connection connection) { |
| 140 | + if (isShutdown) { | |
| 141 | + connection.closeAsync(); | |
| 142 | + return; | |
| 143 | + } | |
| 144 | + | |
| 137 | 145 | setNewConnection(connection); |
| 138 | 146 | } |
| 139 | 147 | |
| 140 | 148 | @Override |
| 141 | 149 | protected boolean onConnectionException(ConnectionException e, long nextDelayMs) { |
| 150 | + if (isShutdown) | |
| 151 | + return false; | |
| 152 | + | |
| 142 | 153 | logger.error("[Control connection] Cannot connect to any host, scheduling retry in {} milliseconds", nextDelayMs); |
| 143 | 154 | return true; |
| 144 | 155 | } |
| 145 | 156 | |
| 146 | 157 | @Override |
| 147 | 158 | protected boolean onUnknownException(Exception e, long nextDelayMs) { |
| 159 | + if (isShutdown) | |
| 160 | + return false; | |
| 161 | + | |
| 148 | 162 | logger.error(String.format("[Control connection] Unknown error during reconnection, scheduling retry in %d milliseconds", nextDelayMs), e); |
| 149 | 163 | return true; |
| 150 | 164 | } |
| @@ -191,7 +205,6 @@ | ||
| 191 | 205 | // Mark the host down right away so that we don't try it again during the initialization process. |
| 192 | 206 | // We don't call cluster.triggerOnDown because it does a bunch of other things we don't want to do here (notify LBP, etc.) |
| 193 | 207 | host.setDown(); |
| 194 | - cluster.startPeriodicReconnectionAttempt(host, true); | |
| 195 | 208 | } |
| 196 | 209 | } catch (ExecutionException e) { |
| 197 | 210 | errors = logError(host, e.getCause(), errors, iter); |
| @@ -551,8 +564,15 @@ | ||
| 551 | 564 | if (host == null) { |
| 552 | 565 | // We don't know that node, create the Host object but wait until we've set the known |
| 553 | 566 | // info before signaling the addition. |
| 554 | - host = cluster.metadata.add(foundHosts.get(i)); | |
| 555 | - isNew = true; | |
| 567 | + Host newHost = cluster.metadata.newHost(foundHosts.get(i)); | |
| 568 | + Host existing = cluster.metadata.addIfAbsent(newHost); | |
| 569 | + if (existing == null) { | |
| 570 | + host = newHost; | |
| 571 | + isNew = true; | |
| 572 | + } else { | |
| 573 | + host = existing; | |
| 574 | + isNew = false; | |
| 575 | + } | |
| 556 | 576 | } |
| 557 | 577 | if (dcs.get(i) != null || racks.get(i) != null) |
| 558 | 578 | 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
| @@ -257,7 +257,6 @@ | ||
| 257 | 257 | |
| 258 | 258 | void setDown() { |
| 259 | 259 | state = State.DOWN; |
| 260 | - convictionPolicy.reset(); | |
| 261 | 260 | } |
| 262 | 261 | |
| 263 | 262 | void setUp() { |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +14 −15
| @@ -111,19 +111,19 @@ | ||
| 111 | 111 | final int coreSize = options().getCoreConnectionsPerHost(hostDistance); |
| 112 | 112 | final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize); |
| 113 | 113 | final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(coreSize); |
| 114 | - for (int i = 0; i < coreSize; i++) { | |
| 115 | - Connection connection; | |
| 116 | - ListenableFuture<Void> connectionFuture; | |
| 117 | - // reuse the existing connection only once | |
| 118 | - if (reusedConnection != null && reusedConnection.setOwner(this)) { | |
| 119 | - connection = reusedConnection; | |
| 120 | - connectionFuture = MoreFutures.VOID_SUCCESS; | |
| 121 | - } else { | |
| 122 | - connection = manager.connectionFactory().newConnection(this); | |
| 123 | - connectionFuture = connection.initAsync(); | |
| 124 | - } | |
| 125 | - reusedConnection = null; | |
| 126 | - connections.add(connection); | |
| 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 | 127 | connectionFutures.add(handleErrors(connectionFuture, initExecutor)); |
| 128 | 128 | } |
| 129 | 129 | |
| @@ -451,7 +451,6 @@ | ||
| 451 | 451 | } |
| 452 | 452 | logger.debug("Creating new connection on busy pool to {}", host); |
| 453 | 453 | newConnection = manager.connectionFactory().open(this); |
| 454 | - newConnection.setKeyspace(manager.poolsState.keyspace); | |
| 455 | 454 | } |
| 456 | 455 | connections.add(newConnection); |
| 457 | 456 | |
| @@ -514,7 +513,7 @@ | ||
| 514 | 513 | } |
| 515 | 514 | |
| 516 | 515 | private void maybeSpawnNewConnection() { |
| 517 | - if (!host.convictionPolicy.canReconnectNow()) | |
| 516 | + if (isClosed() || !host.convictionPolicy.canReconnectNow()) | |
| 518 | 517 | return; |
| 519 | 518 | |
| 520 | 519 | while (true) { |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +10 −3
| @@ -71,10 +71,17 @@ | ||
| 71 | 71 | } |
| 72 | 72 | } |
| 73 | 73 | |
| 74 | + Host newHost(InetSocketAddress address) { | |
| 75 | + return new Host(address, cluster.convictionPolicyFactory, cluster); | |
| 76 | + } | |
| 77 | + | |
| 78 | + Host addIfAbsent(Host host) { | |
| 79 | + Host previous = hosts.putIfAbsent(host.getSocketAddress(), host); | |
| 80 | + return previous == null ? host : null; | |
| 81 | + } | |
| 82 | + | |
| 74 | 83 | Host add(InetSocketAddress address) { |
| 75 | - Host newHost = new Host(address, cluster.convictionPolicyFactory, cluster); | |
| 76 | - Host previous = hosts.putIfAbsent(address, newHost); | |
| 77 | - return previous == null ? newHost : null; | |
| 84 | + return addIfAbsent(newHost(address)); | |
| 78 | 85 | } |
| 79 | 86 | |
| 80 | 87 | boolean remove(Host host) { |
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +13 −24
| @@ -16,17 +16,12 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.util.concurrent.ThreadFactory; |
| 19 | -import java.util.concurrent.TimeUnit; | |
| 20 | - | |
| 21 | -import static java.util.concurrent.TimeUnit.SECONDS; | |
| 22 | 19 | |
| 23 | 20 | import io.netty.bootstrap.Bootstrap; |
| 24 | 21 | import io.netty.buffer.PooledByteBufAllocator; |
| 25 | 22 | import io.netty.channel.ChannelOption; |
| 26 | 23 | import io.netty.channel.EventLoopGroup; |
| 27 | -import io.netty.channel.nio.NioEventLoopGroup; | |
| 28 | 24 | import io.netty.channel.socket.SocketChannel; |
| 29 | -import io.netty.channel.socket.nio.NioSocketChannel; | |
| 30 | 25 | import io.netty.util.HashedWheelTimer; |
| 31 | 26 | import io.netty.util.Timer; |
| 32 | 27 | |
| @@ -68,7 +63,6 @@ | ||
| 68 | 63 | * and in particular for OSGi applications, it is likely that such a configuration would lead to |
| 69 | 64 | * compile and/or runtime errors.</strong> |
| 70 | 65 | * |
| 71 | - * @jira_ticket JAVA-640 | |
| 72 | 66 | * @since 2.0.10 |
| 73 | 67 | */ |
| 74 | 68 | public class NettyOptions { |
| @@ -79,7 +73,7 @@ | ||
| 79 | 73 | public static final NettyOptions DEFAULT_INSTANCE = new NettyOptions(); |
| 80 | 74 | |
| 81 | 75 | /** |
| 82 | - * Return the {@link EventLoopGroup} instance to use. | |
| 76 | + * Return the {@code EventLoopGroup} instance to use. | |
| 83 | 77 | * <p> |
| 84 | 78 | * This hook is invoked only once at {@link Cluster} initialization; |
| 85 | 79 | * the returned instance will be kept in use throughout the cluster lifecycle. |
| @@ -89,30 +83,30 @@ | ||
| 89 | 83 | * case implementors should also override {@link #onClusterClose(EventLoopGroup)} |
| 90 | 84 | * to prevent the shared instance to be closed when the cluster is closed. |
| 91 | 85 | * <p> |
| 92 | - * The default implementation returns a new instance of {@link io.netty.channel.epoll.EpollEventLoopGroup} | |
| 86 | + * The default implementation returns a new instance of {@code io.netty.channel.epoll.EpollEventLoopGroup} | |
| 93 | 87 | * if {@link NettyUtil#isEpollAvailable() epoll is available}, |
| 94 | - * or {@link NioEventLoopGroup} otherwise. | |
| 88 | + * or {@code io.netty.channel.nio.NioEventLoopGroup} otherwise. | |
| 95 | 89 | * |
| 96 | - * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link EventLoopGroup} instance; | |
| 90 | + * @param threadFactory The {@link ThreadFactory} to use when creating a new {@code EventLoopGroup} instance; | |
| 97 | 91 | * The driver will provide its own internal thread factory here. |
| 98 | 92 | * It is safe to ignore it and use another thread factory. |
| 99 | - * @return the {@link EventLoopGroup} instance to use. | |
| 93 | + * @return the {@code EventLoopGroup} instance to use. | |
| 100 | 94 | */ |
| 101 | 95 | public EventLoopGroup eventLoopGroup(ThreadFactory threadFactory) { |
| 102 | 96 | return NettyUtil.newEventLoopGroupInstance(threadFactory); |
| 103 | 97 | } |
| 104 | 98 | |
| 105 | 99 | /** |
| 106 | - * Return the specific {@link SocketChannel} subclass to use. | |
| 100 | + * Return the specific {@code SocketChannel} subclass to use. | |
| 107 | 101 | * <p> |
| 108 | 102 | * This hook is invoked only once at {@link Cluster} initialization; |
| 109 | 103 | * the returned instance will then be used each time the driver creates a new {@link Connection} |
| 110 | 104 | * and configures a new instance of {@link Bootstrap} for it. |
| 111 | 105 | * <p> |
| 112 | - * The default implementation returns {@link io.netty.channel.epoll.EpollSocketChannel} if {@link NettyUtil#isEpollAvailable() epoll is available}, | |
| 113 | - * or {@link NioSocketChannel} otherwise. | |
| 106 | + * The default implementation returns {@code io.netty.channel.epoll.EpollSocketChannel} if {@link NettyUtil#isEpollAvailable() epoll is available}, | |
| 107 | + * or {@code io.netty.channel.socket.nio.NioSocketChannel} otherwise. | |
| 114 | 108 | * |
| 115 | - * @return The {@link SocketChannel} subclass to use. | |
| 109 | + * @return The {@code SocketChannel} subclass to use. | |
| 116 | 110 | */ |
| 117 | 111 | public Class<? extends SocketChannel> channelClass() { |
| 118 | 112 | return NettyUtil.channelClass(); |
| @@ -183,22 +177,17 @@ | ||
| 183 | 177 | * <p> |
| 184 | 178 | * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required. |
| 185 | 179 | * <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. | |
| 180 | + * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully() graceful shutdown} | |
| 181 | + * of the passed {@link EventLoopGroup}, then waits uninterruptibly for the shutdown to complete or timeout. | |
| 189 | 182 | * <p> |
| 190 | 183 | * 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; | |
| 184 | + * coordinate Netty events for the current cluster, then it should not be shut down here; | |
| 192 | 185 | * subclasses would have to override this method accordingly to take the appropriate action. |
| 193 | 186 | * |
| 194 | 187 | * @param eventLoopGroup the event loop group used by the cluster being closed |
| 195 | 188 | */ |
| 196 | 189 | 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(); | |
| 190 | + eventLoopGroup.shutdownGracefully().syncUninterruptibly(); | |
| 202 | 191 | } |
| 203 | 192 | |
| 204 | 193 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +3 −3
| @@ -119,12 +119,12 @@ | ||
| 119 | 119 | * resolution and separation. This must be an integer between 0 and 5. |
| 120 | 120 | * <p> |
| 121 | 121 | * If not set explicitly, this value defaults to 3. |
| 122 | + * <p> | |
| 123 | + * See <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a> | |
| 124 | + * for a more detailed explanation on how this parameter affects the resolution of recorded samples. | |
| 122 | 125 | * |
| 123 | 126 | * @param numberOfSignificantValueDigits the new value. |
| 124 | 127 | * @return this builder. |
| 125 | - * | |
| 126 | - * @see <a href="http://hdrhistogram.github.io/HdrHistogram/JavaDoc/org/HdrHistogram/Histogram.html">the HdrHistogram Javadocs</a> | |
| 127 | - * for a more detailed explanation on how this parameter affects the resolution of recorded samples. | |
| 128 | 128 | */ |
| 129 | 129 | public Builder withNumberOfSignificantValueDigits(int numberOfSignificantValueDigits) { |
| 130 | 130 | this.numberOfSignificantValueDigits = numberOfSignificantValueDigits; |
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
| @@ -355,8 +355,8 @@ | ||
| 355 | 355 | // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have |
| 356 | 356 | // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice, |
| 357 | 357 | // but it knows how to deal with it). |
| 358 | - if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS) | |
| 359 | - connectionHandler.cancelHandler(); | |
| 358 | + if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS && connectionHandler.cancelHandler()) | |
| 359 | + connection.release(); | |
| 360 | 360 | } |
| 361 | 361 | |
| 362 | 362 | private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { |
| @@ -394,8 +394,8 @@ | ||
| 394 | 394 | logger.trace("[{}] Cancelled while in progress", id); |
| 395 | 395 | // The connectionHandler should be non-null, but we might miss the update if we're racing with write(). |
| 396 | 396 | // If it's still null, this will be handled by re-checking queryStateRef at the end of write(). |
| 397 | - if (connectionHandler != null) | |
| 398 | - connectionHandler.cancelHandler(); | |
| 397 | + if (connectionHandler != null && connectionHandler.cancelHandler()) | |
| 398 | + connectionHandler.connection.release(); | |
| 399 | 399 | return; |
| 400 | 400 | } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) { |
| 401 | 401 | if(logger.isTraceEnabled()) |
| @@ -677,6 +677,7 @@ | ||
| 677 | 677 | retryCount, queryState, queryStateRef.get()); |
| 678 | 678 | return false; |
| 679 | 679 | } |
| 680 | + connection.release(); | |
| 680 | 681 | logError(connection.address, new DriverException("Timeout waiting for response to prepare message")); |
| 681 | 682 | retry(false, null); |
| 682 | 683 | return true; |
| @@ -729,6 +730,8 @@ | ||
| 729 | 730 | Host queriedHost = current; |
| 730 | 731 | OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address); |
| 731 | 732 | try { |
| 733 | + connection.release(); | |
| 734 | + | |
| 732 | 735 | logError(connection.address, timeoutException); |
| 733 | 736 | retry(false, null); |
| 734 | 737 | } 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/Session.java +1 −0
| @@ -396,6 +396,7 @@ | ||
| 396 | 396 | * If you want to do so, use {@link Cluster#close}, but note that it will |
| 397 | 397 | * close all sessions created from that cluster. |
| 398 | 398 | */ |
| 399 | + @Override | |
| 399 | 400 | void close(); |
| 400 | 401 | |
| 401 | 402 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +3 −6
| @@ -280,7 +280,7 @@ | ||
| 280 | 280 | |
| 281 | 281 | @Override |
| 282 | 282 | public void onFailure(Throwable t) { |
| 283 | - logger.error("Error creating pool to " + host, t); | |
| 283 | + logger.warn("Error creating pool to " + host, t); | |
| 284 | 284 | future.set(false); |
| 285 | 285 | } |
| 286 | 286 | }); |
| @@ -364,7 +364,7 @@ | ||
| 364 | 364 | cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); |
| 365 | 365 | cluster.manager.triggerOnDown(host, false); |
| 366 | 366 | } else { |
| 367 | - logger.error("Error creating pool to " + host, t); | |
| 367 | + logger.warn("Error creating pool to " + host, t); | |
| 368 | 368 | } |
| 369 | 369 | future.set(false); |
| 370 | 370 | } |
| @@ -615,10 +615,7 @@ | ||
| 615 | 615 | @Override |
| 616 | 616 | public void onFailure(Throwable t) { |
| 617 | 617 | logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t); |
| 618 | - | |
| 619 | - // If the query timed out, that already released the connection, otherwise do it now | |
| 620 | - if (!(t instanceof OperationTimedOutException)) | |
| 621 | - c.release(); | |
| 618 | + c.release(); | |
| 622 | 619 | } |
| 623 | 620 | }); |
| 624 | 621 | futures.add(future); |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +98 −114
| @@ -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 { |
| 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(); |
| @@ -67,107 +71,6 @@ | ||
| 67 | 71 | |
| 68 | 72 | private volatile Configuration configuration; |
| 69 | 73 | |
| 70 | - /** | |
| 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. | |
| 83 | - */ | |
| 84 | - public DCAwareRoundRobinPolicy() { | |
| 85 | - this(null, 0, false, true); | |
| 86 | - } | |
| 87 | - | |
| 88 | - /** | |
| 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. | |
| 101 | - */ | |
| 102 | - public DCAwareRoundRobinPolicy(String localDc) { | |
| 103 | - this(localDc, 0, false, false); | |
| 104 | - } | |
| 105 | - | |
| 106 | - /** | |
| 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). | |
| 133 | - */ | |
| 134 | - public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc) { | |
| 135 | - this(localDc, usedHostsPerRemoteDc, false, false); | |
| 136 | - } | |
| 137 | - | |
| 138 | - /** | |
| 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}. | |
| 166 | - */ | |
| 167 | - public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc, boolean allowRemoteDCsForLocalConsistencyLevel) { | |
| 168 | - this(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, false); | |
| 169 | - } | |
| 170 | - | |
| 171 | 74 | private DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc, boolean allowRemoteDCsForLocalConsistencyLevel, boolean allowEmptyLocalDc) { |
| 172 | 75 | if (!allowEmptyLocalDc && Strings.isNullOrEmpty(localDc)) |
| 173 | 76 | throw new IllegalArgumentException("Null or empty data center specified for DC-aware policy"); |
| @@ -230,8 +133,8 @@ | ||
| 230 | 133 | * For each remote datacenter, it considers a configurable number of |
| 231 | 134 | * hosts as {@code REMOTE} and the rest is {@code IGNORED}. |
| 232 | 135 | * <p> |
| 233 | - * To configure how many host in each remote datacenter is considered | |
| 234 | - * {@code REMOTE}, see {@link #DCAwareRoundRobinPolicy(String, int)}. | |
| 136 | + * To configure how many hosts in each remote datacenter should be considered, | |
| 137 | + * see {@link Builder#withUsedHostsPerRemoteDc(int)}. | |
| 235 | 138 | * |
| 236 | 139 | * @param host the host of which to return the distance of. |
| 237 | 140 | * @return the HostDistance to {@code host}. |
| @@ -378,4 +281,85 @@ | ||
| 378 | 281 | public void close() { |
| 379 | 282 | // nothing to do |
| 380 | 283 | } |
| 284 | + | |
| 285 | + /** | |
| 286 | + * Helper class to build the policy. | |
| 287 | + */ | |
| 288 | + public static class Builder { | |
| 289 | + private String localDc; | |
| 290 | + private int usedHostsPerRemoteDc; | |
| 291 | + private boolean allowRemoteDCsForLocalConsistencyLevel; | |
| 292 | + | |
| 293 | + /** | |
| 294 | + * Sets the name of the datacenter that will be considered "local" by the policy. | |
| 295 | + * <p> | |
| 296 | + * This must be the name as known by Cassandra (in other words, the name in that appears in | |
| 297 | + * {@code system.peers}, or in the output of admin tools like nodetool). | |
| 298 | + * <p> | |
| 299 | + * If this method isn't called, the policy will default to the datacenter of the first node | |
| 300 | + * connected to. This will always be ok if all the contact points use at {@code Cluster} | |
| 301 | + * creation are in the local data-center. Otherwise, you should provide the name yourself | |
| 302 | + * with this method. | |
| 303 | + * | |
| 304 | + * @param localDc the name of the datacenter. It should not be {@code null}. | |
| 305 | + * @return this builder. | |
| 306 | + */ | |
| 307 | + public Builder withLocalDc(String localDc) { | |
| 308 | + Preconditions.checkArgument(!Strings.isNullOrEmpty(localDc), | |
| 309 | + "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC"); | |
| 310 | + this.localDc = localDc; | |
| 311 | + return this; | |
| 312 | + } | |
| 313 | + | |
| 314 | + /** | |
| 315 | + * Sets the number of hosts per remote datacenter that the policy should consider. | |
| 316 | + * <p> | |
| 317 | + * The policy's {@code distance()} method will return a {@code HostDistance.REMOTE} distance for only {@code usedHostsPerRemoteDc} | |
| 318 | + * hosts per remote datacenter. Other hosts of the remote datacenters will be ignored (and thus no connections to them will be | |
| 319 | + * maintained). | |
| 320 | + * <p> | |
| 321 | + * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host in the local datacenter can be reached and if the consistency | |
| 322 | + * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, then up to {@code usedHostsPerRemoteDc} hosts per remote | |
| 323 | + * datacenter will be tried by the policy as a fallback. By default, no remote host will be used for {@code LOCAL_ONE} and | |
| 324 | + * {@code LOCAL_QUORUM}, since this would change the meaning of the consistency level, somewhat breaking the consistency contract | |
| 325 | + * (this can be overridden with {@link #allowRemoteDCsForLocalConsistencyLevel()}). | |
| 326 | + * <p> | |
| 327 | + * If this method isn't called, the policy will default to 0. | |
| 328 | + * | |
| 329 | + * @param usedHostsPerRemoteDc the number. | |
| 330 | + * @return this builder. | |
| 331 | + */ | |
| 332 | + public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) { | |
| 333 | + Preconditions.checkArgument(usedHostsPerRemoteDc >= 0, | |
| 334 | + "usedHostsPerRemoteDc must be equal or greater than 0"); | |
| 335 | + this.usedHostsPerRemoteDc = usedHostsPerRemoteDc; | |
| 336 | + return this; | |
| 337 | + } | |
| 338 | + | |
| 339 | + /** | |
| 340 | + * Allows the policy to return remote hosts when building query plans for queries having consistency level {@code LOCAL_ONE} | |
| 341 | + * or {@code LOCAL_QUORUM}. | |
| 342 | + * <p> | |
| 343 | + * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of | |
| 344 | + * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do | |
| 345 | + * so in almost all cases, as this would potentially break consistency guarantees and if you are fine with that, it's probably | |
| 346 | + * better to use a weaker consitency like {@code ONE}, {@code TWO} or {@code THREE}. As such, this method should generally be | |
| 347 | + * avoided; use it only if you know and understand what you do. | |
| 348 | + * | |
| 349 | + * @return this builder. | |
| 350 | + */ | |
| 351 | + public Builder allowRemoteDCsForLocalConsistencyLevel() { | |
| 352 | + this.allowRemoteDCsForLocalConsistencyLevel = true; | |
| 353 | + return this; | |
| 354 | + } | |
| 355 | + | |
| 356 | + /** | |
| 357 | + * Builds the policy configured by this builder. | |
| 358 | + * | |
| 359 | + * @return the policy. | |
| 360 | + */ | |
| 361 | + public DCAwareRoundRobinPolicy build() { | |
| 362 | + return new DCAwareRoundRobinPolicy(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, true); | |
| 363 | + } | |
| 364 | + } | |
| 381 | 365 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +3 −2
| @@ -111,8 +111,9 @@ | ||
| 111 | 111 | * unavailable exception. |
| 112 | 112 | * <p> |
| 113 | 113 | * This method triggers a retry iff no retry has been executed before |
| 114 | - * (nbRetry == 0), with {@link RetryDecision#tryNextHost}, otherwise it | |
| 115 | - * throws an exception. The retry will be processed on the next host | |
| 114 | + * (nbRetry == 0), with | |
| 115 | + * {@link RetryPolicy.RetryDecision#tryNextHost(ConsistencyLevel) RetryDecision.tryNextHost(cl)}, | |
| 116 | + * otherwise it throws an exception. The retry will be processed on the next host | |
| 116 | 117 | * in the query plan according to the current Load Balancing Policy. |
| 117 | 118 | * Where retrying on the same host in the event of an Unavailable exception |
| 118 | 119 | * has almost no chance of success, if the first replica tried happens to |
added driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java +175 −0
| @@ -0,0 +1,175 @@ | ||
| 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.util.ArrayList; | |
| 19 | +import java.util.Collection; | |
| 20 | +import java.util.Iterator; | |
| 21 | +import java.util.List; | |
| 22 | + | |
| 23 | +import com.google.common.base.Predicate; | |
| 24 | +import com.google.common.base.Predicates; | |
| 25 | +import com.google.common.collect.ImmutableSet; | |
| 26 | + | |
| 27 | +import com.datastax.driver.core.Cluster; | |
| 28 | +import com.datastax.driver.core.Host; | |
| 29 | +import com.datastax.driver.core.HostDistance; | |
| 30 | +import com.datastax.driver.core.Statement; | |
| 31 | + | |
| 32 | +/** | |
| 33 | + * A load balancing policy wrapper that ensures that only hosts matching the predicate | |
| 34 | + * will ever be returned. | |
| 35 | + * <p> | |
| 36 | + * This policy wraps another load balancing policy and will delegate the choice | |
| 37 | + * of hosts to the wrapped policy with the exception that only hosts matching | |
| 38 | + * the predicate provided when constructing this policy will ever be | |
| 39 | + * returned. Any host not matching the predicate will be considered {@code IGNORED} | |
| 40 | + * and thus will not be connected to. | |
| 41 | + */ | |
| 42 | +public class HostFilterPolicy implements ChainableLoadBalancingPolicy { | |
| 43 | + private final LoadBalancingPolicy childPolicy; | |
| 44 | + private final Predicate<Host> predicate; | |
| 45 | + | |
| 46 | + /** | |
| 47 | + * Create a new policy that wraps the provided child policy but only "allows" hosts | |
| 48 | + * matching the predicate. | |
| 49 | + * | |
| 50 | + * @param childPolicy the wrapped policy. | |
| 51 | + * @param predicate the host predicate. Only hosts matching this predicate may get connected | |
| 52 | + * to (whether they will get connected to or not depends on the child policy). | |
| 53 | + */ | |
| 54 | + public HostFilterPolicy(LoadBalancingPolicy childPolicy, Predicate<Host> predicate) { | |
| 55 | + this.childPolicy = childPolicy; | |
| 56 | + this.predicate = predicate; | |
| 57 | + } | |
| 58 | + | |
| 59 | + @Override | |
| 60 | + public LoadBalancingPolicy getChildPolicy() { | |
| 61 | + return childPolicy; | |
| 62 | + } | |
| 63 | + | |
| 64 | + /** | |
| 65 | + * {@inheritDoc} | |
| 66 | + * | |
| 67 | + * @throws IllegalArgumentException if none of the host in {@code hosts} | |
| 68 | + * (which will correspond to the contact points) matches the predicate. | |
| 69 | + */ | |
| 70 | + @Override | |
| 71 | + public void init(Cluster cluster, Collection<Host> hosts) { | |
| 72 | + List<Host> whiteHosts = new ArrayList<Host>(hosts.size()); | |
| 73 | + for (Host host : hosts) | |
| 74 | + if (predicate.apply(host)) | |
| 75 | + whiteHosts.add(host); | |
| 76 | + | |
| 77 | + if (whiteHosts.isEmpty()) | |
| 78 | + throw new IllegalArgumentException(String.format("Cannot use HostFilterPolicy where the filter allows none of the contacts points (%s)", hosts)); | |
| 79 | + | |
| 80 | + childPolicy.init(cluster, whiteHosts); | |
| 81 | + } | |
| 82 | + | |
| 83 | + /** | |
| 84 | + * {@inheritDoc} | |
| 85 | + * | |
| 86 | + * @return {@link HostDistance#IGNORED} if {@code host} is not matching the predicate, the HostDistance | |
| 87 | + * as returned by the wrapped policy otherwise. | |
| 88 | + */ | |
| 89 | + @Override | |
| 90 | + public HostDistance distance(Host host) { | |
| 91 | + return predicate.apply(host) | |
| 92 | + ? childPolicy.distance(host) | |
| 93 | + : HostDistance.IGNORED; | |
| 94 | + } | |
| 95 | + | |
| 96 | + /** | |
| 97 | + * {@inheritDoc} | |
| 98 | + * <p> | |
| 99 | + * It is guaranteed that only hosts matching the predicate will be returned. | |
| 100 | + */ | |
| 101 | + @Override | |
| 102 | + public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { | |
| 103 | + // Just delegate to the child policy, since we filter the hosts not white | |
| 104 | + // listed upfront, the child policy will never see a host that is not white | |
| 105 | + // listed and thus can't return one. | |
| 106 | + return childPolicy.newQueryPlan(loggedKeyspace, statement); | |
| 107 | + } | |
| 108 | + | |
| 109 | + @Override | |
| 110 | + public void onUp(Host host) { | |
| 111 | + if (predicate.apply(host)) | |
| 112 | + childPolicy.onUp(host); | |
| 113 | + } | |
| 114 | + | |
| 115 | + @Override | |
| 116 | + public void onDown(Host host) { | |
| 117 | + if (predicate.apply(host)) | |
| 118 | + childPolicy.onDown(host); | |
| 119 | + } | |
| 120 | + | |
| 121 | + @Override | |
| 122 | + public void onAdd(Host host) { | |
| 123 | + if (predicate.apply(host)) | |
| 124 | + childPolicy.onAdd(host); | |
| 125 | + } | |
| 126 | + | |
| 127 | + @Override | |
| 128 | + public void onRemove(Host host) { | |
| 129 | + if (predicate.apply(host)) | |
| 130 | + childPolicy.onRemove(host); | |
| 131 | + } | |
| 132 | + | |
| 133 | + @Override | |
| 134 | + public void close() { | |
| 135 | + childPolicy.close(); | |
| 136 | + } | |
| 137 | + | |
| 138 | + /** | |
| 139 | + * Create a new policy that wraps the provided child policy but only "allows" hosts | |
| 140 | + * whose DC belongs to the provided list. | |
| 141 | + * | |
| 142 | + * @param childPolicy the wrapped policy. | |
| 143 | + * @param dcs the DCs. | |
| 144 | + * | |
| 145 | + * @return the policy. | |
| 146 | + */ | |
| 147 | + public static HostFilterPolicy fromDCWhiteList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) { | |
| 148 | + return new HostFilterPolicy(childPolicy, hostDCPredicate(dcs, true)); | |
| 149 | + } | |
| 150 | + | |
| 151 | + /** | |
| 152 | + * Create a new policy that wraps the provided child policy but only "forbids" hosts | |
| 153 | + * whose DC belongs to the provided list. | |
| 154 | + * | |
| 155 | + * @param childPolicy the wrapped policy. | |
| 156 | + * @param dcs the DCs. | |
| 157 | + * | |
| 158 | + * @return the policy. | |
| 159 | + */ | |
| 160 | + public static HostFilterPolicy fromDCBlackList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) { | |
| 161 | + return new HostFilterPolicy(childPolicy, Predicates.not(hostDCPredicate(dcs, false))); | |
| 162 | + } | |
| 163 | + | |
| 164 | + private static Predicate<Host> hostDCPredicate(Iterable<String> dcs, final boolean includeNullDC) { | |
| 165 | + final ImmutableSet<String> _dcs = ImmutableSet.copyOf(dcs); | |
| 166 | + return new Predicate<Host>() { | |
| 167 | + @Override | |
| 168 | + public boolean apply(Host host) { | |
| 169 | + String hdc = host.getDatacenter(); | |
| 170 | + return (hdc == null) ? includeNullDC : _dcs.contains(hdc); | |
| 171 | + } | |
| 172 | + }; | |
| 173 | + } | |
| 174 | + | |
| 175 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +1 −1
| @@ -76,7 +76,7 @@ | ||
| 76 | 76 | public static LoadBalancingPolicy defaultLoadBalancingPolicy() { |
| 77 | 77 | // Note: balancing policies are stateful, so we can't store that in a static or that would screw thing |
| 78 | 78 | // up if multiple Cluster instance are started in the same JVM. |
| 79 | - return new TokenAwarePolicy(new DCAwareRoundRobinPolicy()); | |
| 79 | + return new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build()); | |
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 82 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +14 −99
| @@ -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 { | |
| 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,96 +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 onDown(Host host) { | |
| 135 | - if (whiteList.contains(host.getSocketAddress())) | |
| 136 | - childPolicy.onDown(host); | |
| 137 | - } | |
| 138 | - | |
| 139 | - @Override | |
| 140 | - public void onAdd(Host host) { | |
| 141 | - if (whiteList.contains(host.getSocketAddress())) | |
| 142 | - childPolicy.onAdd(host); | |
| 143 | - } | |
| 144 | - | |
| 145 | - @Override | |
| 146 | - public void onRemove(Host host) { | |
| 147 | - if (whiteList.contains(host.getSocketAddress())) | |
| 148 | - childPolicy.onRemove(host); | |
| 149 | - } | |
| 150 | - | |
| 151 | - @Override | |
| 152 | - public void close() { | |
| 153 | - childPolicy.close(); | |
| 154 | - } | |
| 155 | 70 | } |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +1 −1
| @@ -152,7 +152,7 @@ | ||
| 152 | 152 | * Sets the 'IF NOT EXISTS' option for this INSERT statement. |
| 153 | 153 | * <p> |
| 154 | 154 | * An insert with that option will not succeed unless the row does not |
| 155 | - * exist at the time the insertion is execution. The existence check and | |
| 155 | + * exist at the time the insertion is executed. The existence check and | |
| 156 | 156 | * insertions are done transactionally in the sense that if multiple |
| 157 | 157 | * clients attempt to create a given row with this option, then at most one |
| 158 | 158 | * 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/CCMBridge.java +22 −4
| @@ -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 | |
| @@ -488,7 +492,9 @@ | ||
| 488 | 492 | |
| 489 | 493 | builder = configure(builder); |
| 490 | 494 | |
| 491 | - cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)).build(); | |
| 495 | + cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 496 | + .withNettyOptions(TestUtils.nonQuietClusterCloseOptions) | |
| 497 | + .build(); | |
| 492 | 498 | session = cluster.connect(); |
| 493 | 499 | keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet(); |
| 494 | 500 | session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); |
| @@ -516,12 +522,24 @@ | ||
| 516 | 522 | |
| 517 | 523 | private void clearSimpleKeyspace() { |
| 518 | 524 | if(keyspace != null) { |
| 519 | - // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables. | |
| 520 | - // This should be more than enough although some tests create many tables, so dropping a keyspace | |
| 521 | - // could take as long as 12 seconds on restricted hardware. | |
| 525 | + logger.debug("Removing keyspace {}.", keyspace); | |
| 526 | + // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and | |
| 527 | + // tables being slow, particularly in a CI environment. | |
| 522 | 528 | int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis(); |
| 523 | 529 | cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000); |
| 524 | 530 | try { |
| 531 | + KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace); | |
| 532 | + if (ksm != null) { | |
| 533 | + // drop each table individually as this seems to be more dependable than dropping | |
| 534 | + // the entire keyspace at once if it has many tables. | |
| 535 | + if(ksm.getTables().size() > 10) { | |
| 536 | + for (TableMetadata table : ksm.getTables()) { | |
| 537 | + logger.debug("Dropping table {}.{}.", keyspace, table.getName()); | |
| 538 | + session.execute("DROP TABLE " + keyspace + "." + table.getName()); | |
| 539 | + } | |
| 540 | + } | |
| 541 | + } | |
| 542 | + logger.debug("Dropping keyspace {}.", keyspace); | |
| 525 | 543 | session.execute("DROP KEYSPACE " + keyspace); |
| 526 | 544 | } finally { |
| 527 | 545 | cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout); |
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 +95 −8
| @@ -27,6 +27,8 @@ | ||
| 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.collect.Maps; | |
| 31 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 30 | 32 | import org.scassandra.Scassandra; |
| 31 | 33 | import org.scassandra.http.client.PrimingClient; |
| 32 | 34 | import org.scassandra.http.client.PrimingRequest; |
| @@ -42,14 +44,13 @@ | ||
| 42 | 44 | |
| 43 | 45 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 44 | 46 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 45 | -import com.datastax.driver.core.utils.CassandraVersion; | |
| 46 | 47 | |
| 47 | -import static com.datastax.driver.core.Assertions.*; | |
| 48 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 49 | +import static com.datastax.driver.core.Assertions.fail; | |
| 48 | 50 | 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 | 51 | import static com.datastax.driver.core.HostDistance.LOCAL; |
| 52 | 52 | import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; |
| 53 | +import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; | |
| 53 | 54 | |
| 54 | 55 | public class ClusterInitTest { |
| 55 | 56 | private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class); |
| @@ -59,7 +60,6 @@ | ||
| 59 | 60 | * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host. |
| 60 | 61 | */ |
| 61 | 62 | @Test(groups = "short") |
| 62 | - @CassandraVersion(major=2.0, description = "Scassandra currently broken with protocol version 1.") | |
| 63 | 63 | public void should_handle_failing_or_missing_contact_points() throws UnknownHostException { |
| 64 | 64 | if (TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V2) > 0) |
| 65 | 65 | throw new SkipException("Scassandra does not yet support protocol >= V3"); |
| @@ -132,9 +132,22 @@ | ||
| 132 | 132 | verify(socketOptions, atLeast(6)).getKeepAlive(); |
| 133 | 133 | verify(socketOptions, atMost(7)).getKeepAlive(); |
| 134 | 134 | |
| 135 | - assertThat(cluster).host(realHostAddress).isNotNull().hasState(UP); | |
| 136 | - for (FakeHost failingHost : failingHosts) | |
| 137 | - assertThat(cluster).host(failingHost.address).hasState(DOWN); | |
| 135 | + assertThat(cluster).host(realHostAddress).isNotNull().isUp(); | |
| 136 | + // It is likely but not guaranteed that a host is marked down at this point. | |
| 137 | + // It should eventually be marked down as Cluster.Manager.triggerOnDown should be | |
| 138 | + // called and submit a task that marks the host down. | |
| 139 | + for (FakeHost failingHost : failingHosts) { | |
| 140 | + assertThat(cluster).host(failingHost.address).goesDownWithin(10, TimeUnit.SECONDS); | |
| 141 | + Host host = TestUtils.findHost(cluster, failingHost.address); | |
| 142 | + // There is a possible race here in that the host is marked down in a separate Executor in onDown | |
| 143 | + // and then starts a periodic reconnection attempt shortly after. Since setDown is called before | |
| 144 | + // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet. | |
| 145 | + if(host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) { | |
| 146 | + logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host); | |
| 147 | + Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS); | |
| 148 | + } | |
| 149 | + assertThat(cluster).host(failingHost.address).isReconnectingFromDown(); | |
| 150 | + } | |
| 138 | 151 | assertThat(cluster).host(missingHostAddress).isNull(); |
| 139 | 152 | |
| 140 | 153 | } finally { |
| @@ -147,6 +160,41 @@ | ||
| 147 | 160 | } |
| 148 | 161 | } |
| 149 | 162 | |
| 163 | + /** | |
| 164 | + * Validates that if hosts are unreachable during Cluster initialization, no background reconnection to them | |
| 165 | + * is scheduled before the initialization is complete. | |
| 166 | + * | |
| 167 | + * @test_category connection | |
| 168 | + * @jira_ticket JAVA-954 | |
| 169 | + * @expected_result No reconnection scheduled. | |
| 170 | + */ | |
| 171 | + @Test(groups="short", expectedExceptions = NoHostAvailableException.class) | |
| 172 | + public void should_not_schedule_reconnections_before_init_complete() { | |
| 173 | + // Both contact points time out so we're sure we'll try both of them and init will never complete. | |
| 174 | + List<FakeHost> hosts = Lists.newArrayList( | |
| 175 | + new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS), | |
| 176 | + new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS)); | |
| 177 | + // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled, | |
| 178 | + // we would see a call to the reconnection policy. | |
| 179 | + CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100)); | |
| 180 | + Cluster cluster = Cluster.builder() | |
| 181 | + .addContactPoints(hosts.get(0).address, hosts.get(1).address) | |
| 182 | + .withReconnectionPolicy(reconnectionPolicy) | |
| 183 | + .build(); | |
| 184 | + try { | |
| 185 | + cluster.init(); | |
| 186 | + } finally { | |
| 187 | + // We expect a nextDelay invocation from the ConvictionPolicy for each host, but that will | |
| 188 | + // not trigger a reconnection. | |
| 189 | + assertThat(reconnectionPolicy.count.get()).isEqualTo(2); | |
| 190 | + for (FakeHost fakeHost : hosts) { | |
| 191 | + fakeHost.stop(); | |
| 192 | + } | |
| 193 | + } | |
| 194 | + // We don't test that reconnections are scheduled if init succeeds, but that's covered in | |
| 195 | + // should_handle_failing_or_missing_contact_points | |
| 196 | + } | |
| 197 | + | |
| 150 | 198 | /** |
| 151 | 199 | * Validates that a Cluster that was never able to successfully establish connection a session can be closed |
| 152 | 200 | * properly. |
| @@ -158,6 +206,7 @@ | ||
| 158 | 206 | public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception { |
| 159 | 207 | Cluster cluster = Cluster.builder() |
| 160 | 208 | .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534))) |
| 209 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 161 | 210 | .build(); |
| 162 | 211 | try { |
| 163 | 212 | cluster.connect(); |
| @@ -172,6 +221,43 @@ | ||
| 172 | 221 | } |
| 173 | 222 | } |
| 174 | 223 | |
| 224 | + /** | |
| 225 | + * Ensures that if a node is detected that does not support the protocol version in use on init that | |
| 226 | + * the node is ignored and remains in an added state and the all other hosts are appropriately marked up. | |
| 227 | + * | |
| 228 | + * @jira_ticket JAVA-854 | |
| 229 | + * @test_category host:state | |
| 230 | + */ | |
| 231 | + @Test(groups="short") | |
| 232 | + public void should_not_abort_init_if_host_does_not_support_protocol_version() { | |
| 233 | + Map<Integer,Map<String,Object>> nodeProperties = Maps.newHashMap(); | |
| 234 | + // Configure node 2 to run with an older version which uses protocol v1. | |
| 235 | + nodeProperties.put(2, ImmutableMap.<String,Object>of("release_version", "1.2.19")); | |
| 236 | + SCassandraCluster scassandraCluster = new SCassandraCluster(CCMBridge.IP_PREFIX, 5, nodeProperties); | |
| 237 | + Cluster cluster = Cluster.builder() | |
| 238 | + .addContactPoints(scassandraCluster.addresses().get(0)) | |
| 239 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 240 | + .build(); | |
| 241 | + | |
| 242 | + try { | |
| 243 | + cluster.init(); | |
| 244 | + for(int i = 0; i < scassandraCluster.addresses().size(); i++) { | |
| 245 | + String hostAddress = scassandraCluster.addresses().get(i).getHostAddress(); | |
| 246 | + if (i == 2) { | |
| 247 | + // As this host is at an older protocol version, it should be ignored and not marked up. | |
| 248 | + assertThat(cluster).host(hostAddress).hasState(Host.State.ADDED); | |
| 249 | + } else { | |
| 250 | + // All hosts should be set as 'UP' as part of cluster.init(). If they are | |
| 251 | + // in 'ADDED' state it's possible that cluster.init() did not fully complete. | |
| 252 | + assertThat(cluster).host(hostAddress).hasState(Host.State.UP); | |
| 253 | + } | |
| 254 | + } | |
| 255 | + } finally { | |
| 256 | + cluster.close(); | |
| 257 | + scassandraCluster.stop(); | |
| 258 | + } | |
| 259 | + } | |
| 260 | + | |
| 175 | 261 | private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException { |
| 176 | 262 | PrimingClient primingClient = PrimingClient.builder() |
| 177 | 263 | .withHost("localhost").withPort(scassandra.getAdminPort()) |
| @@ -187,6 +273,7 @@ | ||
| 187 | 273 | .put("rpc_address", address) |
| 188 | 274 | .put("data_center", "datacenter1") |
| 189 | 275 | .put("rack", "rack1") |
| 276 | + .put("release_version", "2.0.1") | |
| 190 | 277 | .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++))) |
| 191 | 278 | .build()); |
| 192 | 279 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +1 −1
| @@ -653,7 +653,7 @@ | ||
| 653 | 653 | @Test(groups = "long") |
| 654 | 654 | public void testRFThreeDowngradingCLTwoDCsDCAware() throws Throwable { |
| 655 | 655 | Cluster.Builder builder = Cluster.builder() |
| 656 | - .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"), false)) | |
| 656 | + .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false)) | |
| 657 | 657 | .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE); |
| 658 | 658 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder); |
| 659 | 659 | try { |
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.*; |
| 35 | 36 | import com.datastax.driver.core.utils.CassandraVersion; |
| @@ -181,6 +182,7 @@ | ||
| 181 | 182 | for(int i = 0; i < iterations; i++) { |
| 182 | 183 | Cluster cluster = Cluster.builder() |
| 183 | 184 | .addContactPoints(scassandras.addresses()) |
| 185 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 184 | 186 | .build(); |
| 185 | 187 | |
| 186 | 188 | try { |
added driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java +58 −0
| @@ -0,0 +1,58 @@ | ||
| 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 | + | |
| 52 | + @Override | |
| 53 | + public void init(Cluster cluster) {} | |
| 54 | + | |
| 55 | + @Override | |
| 56 | + public void close() { childPolicy.close(); } | |
| 57 | + | |
| 58 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +6 −26
| @@ -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,30 +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 onDown(Host host) { | |
| 129 | - } | |
| 130 | - | |
| 131 | - @Override | |
| 132 | - public void onRemove(Host host) { | |
| 133 | - } | |
| 134 | - | |
| 135 | - @Override | |
| 136 | - public void onRegister(Cluster cluster) { | |
| 137 | - } | |
| 138 | - | |
| 139 | - @Override | |
| 140 | - public void onUnregister(Cluster cluster) { | |
| 141 | - } | |
| 142 | - } | |
| 143 | 123 | } |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +1 −1
| @@ -537,7 +537,7 @@ | ||
| 537 | 537 | // 2 attempts for connection.open (reconnect control connection and initial connection for host state). |
| 538 | 538 | verify(factory, after(reconnectInterval*2).atLeast(2)).open(host); |
| 539 | 539 | // 7 attempts for core connections after first initial connection. |
| 540 | - verify(factory, timeout(reconnectInterval*2).times(7)).newConnection(any(HostConnectionPool.class)); | |
| 540 | + verify(factory, timeout(reconnectInterval*2)).newConnections(any(HostConnectionPool.class), eq(7)); | |
| 541 | 541 | |
| 542 | 542 | // Wait some reasonable amount of time for connection to reestablish. |
| 543 | 543 | Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS); |
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyTest.java +3 −3
| @@ -155,7 +155,7 @@ | ||
| 155 | 155 | @Test(groups = "long") |
| 156 | 156 | public void DCAwareRoundRobinTest() throws Throwable { |
| 157 | 157 | |
| 158 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc2")); | |
| 158 | + Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build()); | |
| 159 | 159 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder); |
| 160 | 160 | try { |
| 161 | 161 | |
| @@ -180,7 +180,7 @@ | ||
| 180 | 180 | @Test(groups = "long") |
| 181 | 181 | public void DCAwareRoundRobinTest2() throws Throwable { |
| 182 | 182 | |
| 183 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc1")); | |
| 183 | + Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc1").build()); | |
| 184 | 184 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder); |
| 185 | 185 | try { |
| 186 | 186 | |
| @@ -205,7 +205,7 @@ | ||
| 205 | 205 | @Test(groups = "long") |
| 206 | 206 | public void dcAwareRoundRobinTestWithOneRemoteHost() throws Throwable { |
| 207 | 207 | |
| 208 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc2", 1)); | |
| 208 | + Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").withUsedHostsPerRemoteDc(1).build()); | |
| 209 | 209 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder); |
| 210 | 210 | try { |
| 211 | 211 |
modified driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +0 −1
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | import java.util.concurrent.TimeUnit; |
| 20 | 20 | |
| 21 | 21 | import org.mockito.ArgumentCaptor; |
| 22 | -import org.mockito.Mockito; | |
| 23 | 22 | import org.testng.annotations.Test; |
| 24 | 23 | |
| 25 | 24 | import static com.google.common.collect.Lists.newArrayList; |
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 −37
| @@ -314,43 +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 | - @Override | |
| 348 | - public void init(Cluster cluster) {} | |
| 349 | - | |
| 350 | - @Override | |
| 351 | - public void close() { childPolicy.close(); } | |
| 352 | - } | |
| 353 | - | |
| 354 | 317 | /** |
| 355 | 318 | * A load balancing policy that: |
| 356 | 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/SCassandraCluster.java +16 −4
| @@ -35,6 +35,7 @@ | ||
| 35 | 35 | * and a CCM cluster is not running at the same time. |
| 36 | 36 | */ |
| 37 | 37 | public class SCassandraCluster { |
| 38 | + private static final Map<Integer,Map<String,Object>> EMPTY_MAP = ImmutableMap.of(); | |
| 38 | 39 | public static final int BINARY_PORT = 9042; |
| 39 | 40 | private static final int ADMIN_PORT = 9052; |
| 40 | 41 | |
| @@ -42,16 +43,22 @@ | ||
| 42 | 43 | private final List<InetAddress> addresses; |
| 43 | 44 | private final List<PrimingClient> primingClients; |
| 44 | 45 | private final List<ActivityClient> activityClients; |
| 46 | + private final Map<Integer,Map<String,Object>> propertyMap; | |
| 45 | 47 | |
| 46 | 48 | public SCassandraCluster(int nodeCount) { |
| 47 | 49 | this(CCMBridge.IP_PREFIX, nodeCount); |
| 48 | 50 | } |
| 49 | 51 | |
| 50 | 52 | public SCassandraCluster(String ipPrefix, int nodeCount) { |
| 53 | + this(ipPrefix, nodeCount, EMPTY_MAP); | |
| 54 | + } | |
| 55 | + | |
| 56 | + public SCassandraCluster(String ipPrefix, int nodeCount, Map<Integer,Map<String,Object>> propertyMap) { | |
| 51 | 57 | scassandras = Lists.newArrayListWithCapacity(nodeCount); |
| 52 | 58 | addresses = Lists.newArrayListWithCapacity(nodeCount); |
| 53 | 59 | primingClients = Lists.newArrayListWithCapacity(nodeCount); |
| 54 | 60 | activityClients = Lists.newArrayListWithCapacity(nodeCount); |
| 61 | + this.propertyMap = propertyMap; | |
| 55 | 62 | |
| 56 | 63 | for (int i = 1; i <= nodeCount; i++) { |
| 57 | 64 | String ip = ipPrefix + i; |
| @@ -142,10 +149,10 @@ | ||
| 142 | 149 | Map<String, ?> row = ImmutableMap.<String, Object>builder() |
| 143 | 150 | .put("peer", address) |
| 144 | 151 | .put("rpc_address", address) |
| 145 | - .put("data_center", "datacenter1") | |
| 146 | - .put("rack", "rack1") | |
| 147 | - .put("release_version", "2.0.1") | |
| 148 | - .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i))) | |
| 152 | + .put("data_center", getProperty(i, "data_center", "datacenter1")) | |
| 153 | + .put("rack", getProperty(i, "rack1", "rack1")) | |
| 154 | + .put("release_version", getProperty(i, "release_version", "2.0.1")) | |
| 155 | + .put("tokens", getProperty(i, "tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i)))) | |
| 149 | 156 | .build(); |
| 150 | 157 | |
| 151 | 158 | rows.add(row); |
| @@ -166,6 +173,11 @@ | ||
| 166 | 173 | .build()); |
| 167 | 174 | } |
| 168 | 175 | |
| 176 | + private Object getProperty(int node, String property, Object defaultValue) { | |
| 177 | + Map<String,Object> nodeProperties = propertyMap.get(node); | |
| 178 | + return nodeProperties != null && nodeProperties.containsKey(property) ? nodeProperties.get(property) : defaultValue; | |
| 179 | + } | |
| 180 | + | |
| 169 | 181 | static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES = |
| 170 | 182 | ImmutableMap.<String, ColumnTypes>builder() |
| 171 | 183 | .put("peer", ColumnTypes.Inet) |
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
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | import static org.testng.Assert.assertTrue; |
| 32 | 32 | import static org.testng.Assert.fail; |
| 33 | 33 | |
| 34 | - | |
| 34 | +import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions; | |
| 35 | 35 | |
| 36 | 36 | /** |
| 37 | 37 | * Simple test of the Sessions methods against a one node cluster. |
| @@ -171,7 +171,10 @@ | ||
| 171 | 171 | |
| 172 | 172 | // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster |
| 173 | 173 | // (note the use of newSession below) |
| 174 | - final Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress)).build(); | |
| 174 | + final Cluster cluster = Cluster.builder() | |
| 175 | + .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 176 | + .withNettyOptions(nonQuietClusterCloseOptions) | |
| 177 | + .build(); | |
| 175 | 178 | final Session session = cluster.newSession(); |
| 176 | 179 | |
| 177 | 180 | // Spawn two threads to simulate the race |
| @@ -207,7 +210,7 @@ | ||
| 207 | 210 | startLatch.countDown(); |
| 208 | 211 | |
| 209 | 212 | executor.shutdown(); |
| 210 | - boolean normalShutdown = executor.awaitTermination(1, TimeUnit.SECONDS); | |
| 213 | + boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS); | |
| 211 | 214 | assertTrue(normalShutdown); |
| 212 | 215 | |
| 213 | 216 | // The deadlock occurred here before JAVA-418 |
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +11 −1
| @@ -51,7 +51,6 @@ | ||
| 51 | 51 | new SimpleStatement("doesn't matter", cluster).getObject(0); |
| 52 | 52 | } |
| 53 | 53 | |
| 54 | - | |
| 55 | 54 | @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class }) |
| 56 | 55 | public void should_throw_IOOBE_if_getObject_called_with_wrong_index() { |
| 57 | 56 | new SimpleStatement("doesn't matter", cluster, new Object()).getObject(1); |
| @@ -63,4 +62,15 @@ | ||
| 63 | 62 | Object actual = new SimpleStatement("doesn't matter", cluster, expected).getObject(0); |
| 64 | 63 | assertThat(actual).isSameAs(expected); |
| 65 | 64 | } |
| 65 | + | |
| 66 | + @Test(groups = "unit") | |
| 67 | + public void should_return_number_of_values() { | |
| 68 | + assertThat( | |
| 69 | + new SimpleStatement("doesn't matter", cluster).valuesCount() | |
| 70 | + ).isEqualTo(0); | |
| 71 | + assertThat( | |
| 72 | + new SimpleStatement("doesn't matter", cluster, 1, 2).valuesCount() | |
| 73 | + ).isEqualTo(2); | |
| 74 | + } | |
| 75 | + | |
| 66 | 76 | } |
added driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java +45 −0
| @@ -0,0 +1,45 @@ | ||
| 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 onDown(Host host) { | |
| 29 | + } | |
| 30 | + | |
| 31 | + @Override | |
| 32 | + public void onRemove(Host host) { | |
| 33 | + } | |
| 34 | + | |
| 35 | + @Override | |
| 36 | + public void onRegister(Cluster cluster) { | |
| 37 | + | |
| 38 | + } | |
| 39 | + | |
| 40 | + @Override | |
| 41 | + public void onUnregister(Cluster cluster) { | |
| 42 | + | |
| 43 | + } | |
| 44 | + | |
| 45 | +} |
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; |
| @@ -550,6 +553,38 @@ | ||
| 550 | 553 | } |
| 551 | 554 | } |
| 552 | 555 | |
| 556 | + public static Host findOrWaitForHost(Cluster cluster, int node, long duration, TimeUnit unit) { | |
| 557 | + return findOrWaitForHost(cluster, CCMBridge.ipOfNode(node), duration, unit); | |
| 558 | + } | |
| 559 | + | |
| 560 | + public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) { | |
| 561 | + Host host = findHost(cluster, address); | |
| 562 | + if(host == null) { | |
| 563 | + final CountDownLatch addSignal = new CountDownLatch(1); | |
| 564 | + Host.StateListener addListener = new StateListenerBase() { | |
| 565 | + @Override | |
| 566 | + public void onAdd(Host host) { | |
| 567 | + if(host.getAddress().getHostAddress().equals(address)) { | |
| 568 | + // for a new node, because of this we also listen for add events. | |
| 569 | + addSignal.countDown(); | |
| 570 | + } | |
| 571 | + } | |
| 572 | + }; | |
| 573 | + cluster.register(addListener); | |
| 574 | + try { | |
| 575 | + // Wait until an add event occurs or we timeout. | |
| 576 | + if (addSignal.await(duration, unit)) { | |
| 577 | + host = findHost(cluster, address); | |
| 578 | + } | |
| 579 | + } catch (InterruptedException e) { | |
| 580 | + return null; | |
| 581 | + } finally { | |
| 582 | + cluster.unregister(addListener); | |
| 583 | + } | |
| 584 | + } | |
| 585 | + return host; | |
| 586 | + } | |
| 587 | + | |
| 553 | 588 | public static Host findHost(Cluster cluster, int hostNumber) { |
| 554 | 589 | return findHost(cluster, CCMBridge.ipOfNode(hostNumber)); |
| 555 | 590 | } |
| @@ -652,4 +687,16 @@ | ||
| 652 | 687 | .setRefreshNodeListIntervalMillis(0) |
| 653 | 688 | .setRefreshSchemaIntervalMillis(0); |
| 654 | 689 | } |
| 690 | + | |
| 691 | + /** | |
| 692 | + * A custom {@link NettyOptions} that shuts down the {@link EventLoopGroup} after | |
| 693 | + * no quiet time. This is useful for tests that consistently close clusters as | |
| 694 | + * otherwise there is a 2 second delay (from JAVA-914). | |
| 695 | + */ | |
| 696 | + public static NettyOptions nonQuietClusterCloseOptions = new NettyOptions() { | |
| 697 | + @Override | |
| 698 | + public void onClusterClose(EventLoopGroup eventLoopGroup) { | |
| 699 | + eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly(); | |
| 700 | + } | |
| 701 | + }; | |
| 655 | 702 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +2 −2
| @@ -179,11 +179,11 @@ | ||
| 179 | 179 | Set<Host> initHosts = new CopyOnWriteArraySet<Host>(); |
| 180 | 180 | |
| 181 | 181 | CountingDCAwarePolicy() { |
| 182 | - super(new DCAwareRoundRobinPolicy()); | |
| 182 | + super(DCAwareRoundRobinPolicy.builder().build()); | |
| 183 | 183 | } |
| 184 | 184 | |
| 185 | 185 | CountingDCAwarePolicy(String localDc) { |
| 186 | - super(new DCAwareRoundRobinPolicy(localDc)); | |
| 186 | + super(DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).build()); | |
| 187 | 187 | } |
| 188 | 188 | |
| 189 | 189 | String getLocalDc() { |
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 | + LoadBalancingPolicy 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 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +1 −1
| @@ -75,7 +75,7 @@ | ||
| 75 | 75 | this.mapper = mapper; |
| 76 | 76 | |
| 77 | 77 | KeyspaceMetadata keyspace = session().getCluster().getMetadata().getKeyspace(mapper.getKeyspace()); |
| 78 | - this.tableMetadata = keyspace == null ? null : keyspace.getTable(Metadata.quote(mapper.getTable())); | |
| 78 | + this.tableMetadata = keyspace == null ? null : keyspace.getTable(mapper.getTable()); | |
| 79 | 79 | |
| 80 | 80 | this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); |
| 81 | 81 | this.mapOneFunction = new Function<ResultSet, T>() { |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +25 −14
| @@ -18,9 +18,6 @@ | ||
| 18 | 18 | import java.util.Collections; |
| 19 | 19 | import java.util.HashMap; |
| 20 | 20 | import java.util.Map; |
| 21 | -import java.util.Set; | |
| 22 | - | |
| 23 | -import com.google.common.collect.Sets; | |
| 24 | 21 | |
| 25 | 22 | import com.datastax.driver.core.ProtocolVersion; |
| 26 | 23 | import com.datastax.driver.core.Session; |
| @@ -35,30 +32,22 @@ | ||
| 35 | 32 | public class MappingManager { |
| 36 | 33 | |
| 37 | 34 | private final Session session; |
| 38 | - private final ProtocolVersion protocolVersion; | |
| 39 | 35 | final boolean isCassandraV1; |
| 40 | 36 | |
| 41 | 37 | private volatile Map<Class<?>, Mapper<?>> mappers = Collections.emptyMap(); |
| 42 | 38 | private volatile Map<Class<?>, MappedUDTCodec<?>> udtCodecs = Collections.emptyMap(); |
| 43 | 39 | private volatile Map<Class<?>, Object> accessors = Collections.emptyMap(); |
| 44 | 40 | |
| 45 | - private final Set<Class<?>> registeredUDTs = Sets.newConcurrentHashSet(); | |
| 46 | - | |
| 47 | 41 | /** |
| 48 | 42 | * Creates a new {@code MappingManager} using the provided {@code Session}. |
| 49 | 43 | * <p> |
| 50 | - * Note that this constructor forces the initialization of the session. | |
| 44 | + * Note that this constructor forces the initialization of the session (see | |
| 45 | + * {@link #MappingManager(Session, ProtocolVersion)} if that is a problem for you). | |
| 51 | 46 | * |
| 52 | 47 | * @param session the {@code Session} to use. |
| 53 | 48 | */ |
| 54 | 49 | public MappingManager(Session session) { |
| 55 | - this.session = session; | |
| 56 | - this.protocolVersion = getProtocolVersion(session); | |
| 57 | - // This is not strictly correct because we could connect to C* 2.0 with the v1 protocol. | |
| 58 | - // But mappers need to make a decision early so that generated queries are compatible, and we don't know in advance | |
| 59 | - // which nodes might join the cluster later. | |
| 60 | - // At least if protocol >=2 we know there won't be any 1.2 nodes ever. | |
| 61 | - this.isCassandraV1 = protocolVersion == ProtocolVersion.V1; | |
| 50 | + this(session, getProtocolVersion(session)); | |
| 62 | 51 | } |
| 63 | 52 | |
| 64 | 53 | private static ProtocolVersion getProtocolVersion(Session session) { |
| @@ -66,6 +55,28 @@ | ||
| 66 | 55 | return session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); |
| 67 | 56 | } |
| 68 | 57 | |
| 58 | + /** | |
| 59 | + * Creates a new {@code MappingManager} using the provided {@code Session}. | |
| 60 | + * <p> | |
| 61 | + * This constructor is only provided for backward compatibility: before 2.1.7, {@code MappingManager} could be | |
| 62 | + * built from an uninitialized session; since 2.1.7, the mapper needs to know the active protocol version to | |
| 63 | + * adapt its internal requests, so {@link #MappingManager(Session)} will now initialize the session if needed. | |
| 64 | + * If you rely on the session not being initialized, use this constructor and provide the version manually. | |
| 65 | + * | |
| 66 | + * @param session the {@code Session} to use. | |
| 67 | + * @param protocolVersion the protocol version that will be used with this session. | |
| 68 | + * | |
| 69 | + * @since 2.1.7 | |
| 70 | + */ | |
| 71 | + public MappingManager(Session session, ProtocolVersion protocolVersion) { | |
| 72 | + this.session = session; | |
| 73 | + // This is not strictly correct because we could connect to C* 2.0 with the v1 protocol. | |
| 74 | + // But mappers need to make a decision early so that generated queries are compatible, and we don't know in advance | |
| 75 | + // which nodes might join the cluster later. | |
| 76 | + // At least if protocol >=2 we know there won't be any 1.2 nodes ever. | |
| 77 | + this.isCassandraV1 = (protocolVersion == ProtocolVersion.V1); | |
| 78 | + } | |
| 79 | + | |
| 69 | 80 | /** |
| 70 | 81 | * The underlying {@code Session} used by this manager. |
| 71 | 82 | * <p> |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +25 −0
| @@ -418,4 +418,29 @@ | ||
| 418 | 418 | // cleanup |
| 419 | 419 | session.execute("delete from posts where user_id = " + u1.getUserId()); |
| 420 | 420 | } |
| 421 | + | |
| 422 | + | |
| 423 | + @Test(groups="short") | |
| 424 | + public void should_return_table_metadata() throws Exception { | |
| 425 | + MappingManager manager = new MappingManager(session); | |
| 426 | + | |
| 427 | + Mapper<Post> m = manager.mapper(Post.class); | |
| 428 | + | |
| 429 | + assertThat(m.getTableMetadata()).isNotNull(); | |
| 430 | + assertThat(m.getTableMetadata().getName()).isEqualTo("posts"); | |
| 431 | + assertThat(m.getTableMetadata().getPartitionKey()).hasSize(1); | |
| 432 | + } | |
| 433 | + | |
| 434 | + @Test(groups="short") | |
| 435 | + public void should_not_initialize_session_when_protocol_version_provided() { | |
| 436 | + Session newSession = cluster.newSession(); | |
| 437 | + | |
| 438 | + // Ensures that a Session is not initialized when a protocol version is provided. | |
| 439 | + MappingManager manager = new MappingManager(newSession, ProtocolVersion.V1); | |
| 440 | + assertThat(newSession.getState().getConnectedHosts()).hasSize(0); | |
| 441 | + | |
| 442 | + // Session should be initialized on first query. | |
| 443 | + newSession.execute("USE " + keyspace); | |
| 444 | + assertThat(newSession.getState().getConnectedHosts()).hasSize(1); | |
| 445 | + } | |
| 421 | 446 | } |
modified features/async/README.md +3 −3
| @@ -97,6 +97,6 @@ | ||
| 97 | 97 | hasn't been fetched already. |
| 98 | 98 | |
| 99 | 99 | [ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained |
| 100 | -[init]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#init() | |
| 101 | -[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 102 | -[query trace]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryTrace.html | |
| 100 | +[init]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#init() | |
| 101 | +[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int) | |
| 102 | +[query trace]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryTrace.html |
modified features/metadata/README.md +2 −2
| @@ -47,8 +47,8 @@ | ||
| 47 | 47 | otherwise the listener could be notified with a great deal of "Added" events as |
| 48 | 48 | the driver builds the schema metadata from scratch for the first time. |
| 49 | 49 | |
| 50 | -[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SchemaChangeListener.html | |
| 51 | -[registerListener]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener) | |
| 50 | +[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SchemaChangeListener.html | |
| 51 | +[registerListener]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener) | |
| 52 | 52 | |
| 53 | 53 | #### Schema agreement |
| 54 | 54 |
modified features/object_mapper/creating/README.md +1 −1
| @@ -44,7 +44,7 @@ | ||
| 44 | 44 | getters. |
| 45 | 45 | |
| 46 | 46 | [table]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/mapping/annotations/Table.html |
| 47 | -[case-sensitive]:http://docs.datastax.com/en/cql/3.2/cql/cql_reference/ucase-lcase_r.html | |
| 47 | +[case-sensitive]:http://docs.datastax.com/en/cql/3.3/cql/cql_reference/ucase-lcase_r.html | |
| 48 | 48 | [consistency level]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/ConsistencyLevel.html |
| 49 | 49 | |
| 50 | 50 | #### Column names |
modified features/object_mapper/using/README.md +1 −1
| @@ -228,7 +228,7 @@ | ||
| 228 | 228 | |
| 229 | 229 | If a method argument is a Java enumeration, it must be annotated with |
| 230 | 230 | `@Enumerated` to indicate how to convert it to a CQL type (the rules are |
| 231 | -the same as in [mapping definition](http://localhost:9090/features/object_mapper/creating/#enumerations)): | |
| 231 | +the same as in [mapping definition](../creating/#enumerations)): | |
| 232 | 232 | |
| 233 | 233 | ```java |
| 234 | 234 | @Query("insert into user (key, gender) values (?,?)") |
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.1/com/datastax/driver/core/SSLOptions.html | |
| 180 | +[NettyOptions]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/NettyOptions.html |
modified features/statements/README.md +10 −10
| @@ -42,13 +42,13 @@ | ||
| 42 | 42 | properties that influence statement execution. To achieve this, you can |
| 43 | 43 | wrap your statements in a custom [StatementWrapper] implementation. |
| 44 | 44 | |
| 45 | -[Statement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Statement.html | |
| 46 | -[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SimpleStatement.html | |
| 47 | -[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/BoundStatement.html | |
| 48 | -[BatchStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/BatchStatement.html | |
| 49 | -[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 50 | -[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/querybuilder/BuiltStatement.html | |
| 51 | -[StatementWrapper]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/StatementWrapper.html | |
| 52 | -[RetryPolicy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/RetryPolicy.html | |
| 53 | -[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 54 | -[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html | |
| 45 | +[Statement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/Statement.html | |
| 46 | +[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/SimpleStatement.html | |
| 47 | +[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BoundStatement.html | |
| 48 | +[BatchStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/BatchStatement.html | |
| 49 | +[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/QueryBuilder.html | |
| 50 | +[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/querybuilder/BuiltStatement.html | |
| 51 | +[StatementWrapper]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/StatementWrapper.html | |
| 52 | +[RetryPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/RetryPolicy.html | |
| 53 | +[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 54 | +[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html |
modified features/statements/prepared/README.md +2 −2
| @@ -184,5 +184,5 @@ | ||
| 184 | 184 | specific situations; read each method's Javadoc for detailed |
| 185 | 185 | explanations. |
| 186 | 186 | |
| 187 | -[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean) | |
| 188 | -[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean) | |
| 187 | +[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean) | |
| 188 | +[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.1/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean) |