Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 3.0

Conflicts:
	README.md
	changelog/README.md
	driver-core/pom.xml
	driver-core/src/main/java/com/datastax/driver/core/Cluster.java
	driver-core/src/main/java/com/datastax/driver/core/ClusteringOrder.java
	driver-core/src/main/java/com/datastax/driver/core/Connection.java
	driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java
	driver-core/src/main/java/com/datastax/driver/core/SetKeyspaceException.java
	driver-core/src/main/java/com/datastax/driver/core/UserType.java
	driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java
	driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java
	driver-core/src/test/java/com/datastax/driver/core/HostAssert.java
	driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java
	driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java
	driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java
	driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java
	driver-dist/pom.xml
	driver-dse/pom.xml
	driver-examples/osgi/pom.xml
	driver-examples/pom.xml
	driver-examples/stress/pom.xml
	driver-mapping/pom.xml
	driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java
	features/compression/README.md
	features/object_mapper/README.md
	features/object_mapper/creating/README.md
	features/shaded_jar/README.md
	pom.xml
Changeset1c1573fc91251a8ce8f8777ea4340492993037c8f12172d7d56d2823e8ef6738
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-12 13:52 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2015-11-12 13:52 +01:00
Parents82394f45c894, e0535ea4aa45

Browse the files at this changeset

59 files changed

modified README.md +5 −1
@@ -67,7 +67,7 @@
6767
6868 **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).
6969
70-## Maven
70+## Getting the driver
7171
7272 The last release of the driver is available on Maven Central. You can install
7373 it in your application using the following Maven dependency:
@@ -93,6 +93,10 @@
9393 We also provide a [shaded JAR](features/shaded_jar/)
9494 to avoid the explicit dependency to Netty.
9595
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+
96100 ## Compatibility
97101
98102 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 @@
99 - [improvement] Raise an exception when an older version of guava (<16.01) is found (JAVA-961)
1010 - [bug] TypeCodec.parse() implementations should be case insensitive when checking for keyword NULL (JAVA-972)
1111
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+
1228 ### 3.0.0-alpha4
1329
1430 - [improvement] Change default consistency level to LOCAL_QUORUM (JAVA-926)
@@ -196,6 +212,79 @@
196212 - [improvement] Unify "Target" enum for schema elements (JAVA-782)
197213
198214
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+
199288 ### 2.1.7.1
200289
201290 - [bug] Special case check for 'null' string in index_options column (JAVA-834)
@@ -458,6 +547,22 @@
458547 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
459548
460549
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+
461566 ### 2.0.11
462567
463568 - [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 @@
1818 import java.util.concurrent.*;
1919 import java.util.concurrent.atomic.AtomicReference;
2020
21+import com.google.common.annotations.VisibleForTesting;
2122 import com.google.common.util.concurrent.ListenableFuture;
2223 import com.google.common.util.concurrent.AbstractFuture;
2324 import org.slf4j.Logger;
@@ -183,7 +184,8 @@
183184 }
184185
185186 // 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> {
187189 // A future representing completion of the next task submitted to the executor
188190 volatile ScheduledFuture<?> nextTry;
189191
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +11 −9
@@ -280,7 +280,7 @@
280280 * be contacted to set the {@code keyspace}.
281281 * @throws AuthenticationException if an authentication error occurs while
282282 * contacting the initial contact points.
283- * @throws InvalidQueryException if the keyspace does not exists.
283+ * @throws InvalidQueryException if the keyspace does not exist.
284284 * @throws IllegalStateException if the Cluster was closed prior to calling
285285 * this method. This can occur either directly (through {@link #close()} or
286286 * {@link #closeAsync()}), or as a result of an error while initializing the
@@ -421,8 +421,8 @@
421421 * The cluster metrics.
422422 *
423423 * @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}).
426426 */
427427 public Metrics getMetrics() {
428428 checkNotClosed(manager);
@@ -915,7 +915,7 @@
915915 * this one. However, this can be useful if the Cassandra nodes are behind
916916 * a router and are not accessed directly. Note that if you are in this
917917 * 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}
919919 * (through {@link #withAddressTranslator}) to translate actual Cassandra node
920920 * addresses to the addresses the driver should use, otherwise the driver
921921 * will not be able to auto-detect new nodes (and will generally not function
@@ -1443,6 +1443,7 @@
14431443 loadBalancingPolicy().onDown(host);
14441444 for (Host.StateListener listener : listeners)
14451445 listener.onDown(host);
1446+ startPeriodicReconnectionAttempt(host, true);
14461447 }
14471448
14481449 configuration.getPoolingOptions().setProtocolVersion(protocolVersion());
@@ -1459,7 +1460,7 @@
14591460
14601461 if (!connectionFactory.protocolVersion.isSupportedBy(host)) {
14611462 logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion);
1462- return;
1463+ continue;
14631464 }
14641465
14651466 if (!contactPointHosts.contains(host))
@@ -2039,14 +2040,15 @@
20392040 }
20402041 }
20412042
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
20452048 // the protocol detection
20462049 if (!isFullyInit || isClosed())
20472050 return true;
20482051
2049- boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized);
20502052 if (isDown)
20512053 triggerOnDown(host, isHostAddition, true);
20522054 return isDown;
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +76 −72
@@ -19,6 +19,7 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.HashSet;
2121 import java.util.Iterator;
22+import java.util.List;
2223 import java.util.Queue;
2324 import java.util.concurrent.*;
2425 import java.util.concurrent.atomic.AtomicBoolean;
@@ -26,6 +27,7 @@
2627 import java.util.concurrent.atomic.AtomicReference;
2728
2829 import com.google.common.annotations.VisibleForTesting;
30+import com.google.common.collect.Lists;
2931 import com.google.common.collect.MapMaker;
3032 import com.google.common.util.concurrent.*;
3133 import io.netty.bootstrap.Bootstrap;
@@ -47,7 +49,9 @@
4749 import static io.netty.handler.timeout.IdleState.ALL_IDLE;
4850
4951 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;
5155 import com.datastax.driver.core.utils.MoreFutures;
5256
5357 import static com.datastax.driver.core.Message.Response.Type.ERROR;
@@ -157,7 +161,7 @@
157161 logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause())));
158162 channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause()));
159163 } else {
160- logger.debug("{} Connection opened successfully", Connection.this);
164+ logger.debug("{} Connection established, initializing transport", Connection.this);
161165 channel.closeFuture().addListener(new ChannelCloseListener());
162166 channelReadyFuture.set(null);
163167 }
@@ -197,16 +201,8 @@
197201 }
198202 }, initExecutor);
199203
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>() {
210206 @Override
211207 public void onFailure(Throwable t) {
212208 if (!isClosed()) {
@@ -285,8 +281,10 @@
285281 final String expected = factory.manager.metadata.clusterName;
286282
287283 // At initialization, the cluster is not known yet
288- if (expected == null)
284+ if (expected == null) {
285+ markInitialized();
289286 return MoreFutures.VOID_SUCCESS;
287+ }
290288
291289 DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null, protocolVersion, new Requests.Query("select cluster_name from system.local"));
292290 try {
@@ -299,6 +297,7 @@
299297 String actual = row.getString("cluster_name");
300298 if (!expected.equals(actual))
301299 throw new ClusterNameMismatchException(address, actual, expected);
300+ markInitialized();
302301 return MoreFutures.VOID_SUCCESS;
303302 }
304303 }, executor);
@@ -307,6 +306,11 @@
307306 }
308307 }
309308
309+ private void markInitialized() {
310+ isInitialized = true;
311+ Host.statesLogger.debug("[{}] {} Transport initialized, connection ready", address, this);
312+ }
313+
310314 private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) {
311315 Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
312316 try {
@@ -396,33 +400,18 @@
396400 }
397401
398402 <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();
419414 }
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-
426415 return e;
427416 }
428417
@@ -452,19 +441,15 @@
452441 } catch (ConnectionException e) {
453442 throw defunct(e);
454443 } 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);
457446 throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
458447 } catch (ExecutionException e) {
459448 Throwable cause = e.getCause();
460449 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-
465450 // 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);
468453 throw new ConnectionException(address, "Timeout while setting keyspace on connection");
469454 } else {
470455 throw defunct(new ConnectionException(address, "Error while setting keyspace", cause));
@@ -576,12 +561,14 @@
576561 // requires its writeLock.
577562 // Therefore if multiple connections in the same pool get a write error, they could deadlock;
578563 // 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+ });
585572 } else {
586573 logger.trace("{}, stream {}, request sent successfully", Connection.this, request.getStreamId());
587574 }
@@ -633,10 +620,18 @@
633620
634621 logger.debug("{} closing connection", this);
635622
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+ }
640635 }
641636
642637 boolean terminated = tryTerminate(false);
@@ -736,8 +731,8 @@
736731 if (isShutdown)
737732 throw new ConnectionException(address, "Connection factory is shut down");
738733
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);
741736 // This method opens the connection synchronously, so wait until it's initialized
742737 try {
743738 connection.initAsync().get();
@@ -751,8 +746,9 @@
751746 * Same as open, but associate the created connection to the provided connection pool.
752747 */
753748 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);
754751 try {
755- Connection connection = newConnection(pool);
756752 connection.initAsync().get();
757753 return connection;
758754 } catch (ExecutionException e) {
@@ -761,13 +757,18 @@
761757 }
762758
763759 /**
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.
765761 */
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+ }
769769
770- return new Connection(name, address, this, pool);
770+ private String buildConnectionName(Host host) {
771+ return host.getSocketAddress().toString() + '-' + getIdGenerator(host).getAndIncrement();
771772 }
772773
773774 static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -870,9 +871,12 @@
870871 boolean doneWork = false;
871872 FlushItem flush;
872873 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+ }
876880 }
877881
878882 // Always flush what we have (don't artificially delay to try to coalesce more messages)
@@ -892,7 +896,7 @@
892896 }
893897
894898 EventLoop eventLoop = eventLoopRef.get();
895- if (eventLoop != null) {
899+ if (eventLoop != null && !eventLoop.isShuttingDown()) {
896900 eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
897901 }
898902 }
@@ -1238,16 +1242,16 @@
12381242 timeout.cancel();
12391243 }
12401244
1241- public void cancelHandler() {
1245+ public boolean cancelHandler() {
12421246 if (!isCancelled.compareAndSet(false, true))
1243- return;
1247+ return false;
12441248
12451249 // We haven't really received a response: we want to remove the handle because we gave up on that
12461250 // request and there is no point in holding the handler, but we don't release the streamId. If we
12471251 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
12481252 // of its own answer, and we would have no way to detect that.
12491253 connection.dispatcher.removeHandler(this, false);
1250- connection.release();
1254+ return true;
12511255 }
12521256
12531257 private TimerTask onTimeoutTask() {
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +23 −3
@@ -121,6 +121,9 @@
121121 new AbstractReconnectionHandler("Control connection", cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) {
122122 @Override
123123 protected Connection tryReconnect() throws ConnectionException {
124+ if (isShutdown)
125+ throw new ConnectionException(null, "Control connection was shut down");
126+
124127 try {
125128 return reconnectInternal(queryPlan(), false);
126129 } catch (NoHostAvailableException e) {
@@ -134,17 +137,28 @@
134137
135138 @Override
136139 protected void onReconnection(Connection connection) {
140+ if (isShutdown) {
141+ connection.closeAsync();
142+ return;
143+ }
144+
137145 setNewConnection(connection);
138146 }
139147
140148 @Override
141149 protected boolean onConnectionException(ConnectionException e, long nextDelayMs) {
150+ if (isShutdown)
151+ return false;
152+
142153 logger.error("[Control connection] Cannot connect to any host, scheduling retry in {} milliseconds", nextDelayMs);
143154 return true;
144155 }
145156
146157 @Override
147158 protected boolean onUnknownException(Exception e, long nextDelayMs) {
159+ if (isShutdown)
160+ return false;
161+
148162 logger.error(String.format("[Control connection] Unknown error during reconnection, scheduling retry in %d milliseconds", nextDelayMs), e);
149163 return true;
150164 }
@@ -191,7 +205,6 @@
191205 // Mark the host down right away so that we don't try it again during the initialization process.
192206 // We don't call cluster.triggerOnDown because it does a bunch of other things we don't want to do here (notify LBP, etc.)
193207 host.setDown();
194- cluster.startPeriodicReconnectionAttempt(host, true);
195208 }
196209 } catch (ExecutionException e) {
197210 errors = logError(host, e.getCause(), errors, iter);
@@ -551,8 +564,15 @@
551564 if (host == null) {
552565 // We don't know that node, create the Host object but wait until we've set the known
553566 // 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+ }
556576 }
557577 if (dcs.get(i) != null || racks.get(i) != null)
558578 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 @@
3333 abstract class ConvictionPolicy {
3434
3535 /**
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
3739 */
38- abstract void signalConnectionCreated();
40+ abstract void signalConnectionsOpening(int count);
3941
4042 /**
4143 * Called when a connection closed normally.
4244 */
43- abstract void signalConnectionClosed();
45+ abstract void signalConnectionClosed(Connection connection);
4446
4547 /**
4648 * Called when a connection error occurs on a connection to the host this policy applies to.
4749 *
48- * @param exception the connection error that occurred.
49- * @param connectionInitialized whether the connection was initialized.
5050 * @return whether the host should be considered down.
5151 */
52- abstract boolean signalConnectionFailure(ConnectionException exception, boolean connectionInitialized);
52+ abstract boolean signalConnectionFailure(Connection connection);
5353
5454 abstract boolean canReconnectNow();
5555
56- /**
57- * Called when the host goes down.
58- */
59- abstract void reset();
60-
6156 /**
6257 * Simple factory interface to allow creating {@link ConvictionPolicy} instances.
6358 */
@@ -86,33 +81,27 @@
8681 }
8782
8883 @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);
9287 resetReconnectionTime();
9388 }
9489
9590 @Override
96- void signalConnectionClosed() {
97- if (host.state == Host.State.DOWN)
98- return;
91+ void signalConnectionClosed(Connection connection) {
9992 int remaining = openConnections.decrementAndGet();
10093 assert remaining >= 0;
101- Host.statesLogger.debug("[{}] connection closed, remaining = {}", host, remaining);
94+ Host.statesLogger.debug("[{}] {} closed, remaining = {}", host, connection, remaining);
10295 }
10396
10497 @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();
113101
102+ int remaining = openConnections.decrementAndGet();
114103 assert remaining >= 0;
115- Host.statesLogger.debug("[{}] remaining connections = {}", host, remaining);
104+ Host.statesLogger.debug("[{}] {} failed, remaining = {}", host, connection, remaining);
116105 return remaining == 0;
117106 }
118107
@@ -141,12 +130,6 @@
141130 System.nanoTime() >= nextReconnectionTime;
142131 }
143132
144- @Override
145- synchronized void reset() {
146- openConnections.set(0);
147- resetReconnectionTime();
148- }
149-
150133 static class Factory implements ConvictionPolicy.Factory {
151134
152135 @Override
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +0 −1
@@ -257,7 +257,6 @@
257257
258258 void setDown() {
259259 state = State.DOWN;
260- convictionPolicy.reset();
261260 }
262261
263262 void setUp() {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +14 −15
@@ -111,19 +111,19 @@
111111 final int coreSize = options().getCoreConnectionsPerHost(hostDistance);
112112 final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize);
113113 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();
127127 connectionFutures.add(handleErrors(connectionFuture, initExecutor));
128128 }
129129
@@ -451,7 +451,6 @@
451451 }
452452 logger.debug("Creating new connection on busy pool to {}", host);
453453 newConnection = manager.connectionFactory().open(this);
454- newConnection.setKeyspace(manager.poolsState.keyspace);
455454 }
456455 connections.add(newConnection);
457456
@@ -514,7 +513,7 @@
514513 }
515514
516515 private void maybeSpawnNewConnection() {
517- if (!host.convictionPolicy.canReconnectNow())
516+ if (isClosed() || !host.convictionPolicy.canReconnectNow())
518517 return;
519518
520519 while (true) {
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +10 −3
@@ -71,10 +71,17 @@
7171 }
7272 }
7373
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+
7483 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));
7885 }
7986
8087 boolean remove(Host host) {
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +13 −24
@@ -16,17 +16,12 @@
1616 package com.datastax.driver.core;
1717
1818 import java.util.concurrent.ThreadFactory;
19-import java.util.concurrent.TimeUnit;
20-
21-import static java.util.concurrent.TimeUnit.SECONDS;
2219
2320 import io.netty.bootstrap.Bootstrap;
2421 import io.netty.buffer.PooledByteBufAllocator;
2522 import io.netty.channel.ChannelOption;
2623 import io.netty.channel.EventLoopGroup;
27-import io.netty.channel.nio.NioEventLoopGroup;
2824 import io.netty.channel.socket.SocketChannel;
29-import io.netty.channel.socket.nio.NioSocketChannel;
3025 import io.netty.util.HashedWheelTimer;
3126 import io.netty.util.Timer;
3227
@@ -68,7 +63,6 @@
6863 * and in particular for OSGi applications, it is likely that such a configuration would lead to
6964 * compile and/or runtime errors.</strong>
7065 *
71- * @jira_ticket JAVA-640
7266 * @since 2.0.10
7367 */
7468 public class NettyOptions {
@@ -79,7 +73,7 @@
7973 public static final NettyOptions DEFAULT_INSTANCE = new NettyOptions();
8074
8175 /**
82- * Return the {@link EventLoopGroup} instance to use.
76+ * Return the {@code EventLoopGroup} instance to use.
8377 * <p>
8478 * This hook is invoked only once at {@link Cluster} initialization;
8579 * the returned instance will be kept in use throughout the cluster lifecycle.
@@ -89,30 +83,30 @@
8983 * case implementors should also override {@link #onClusterClose(EventLoopGroup)}
9084 * to prevent the shared instance to be closed when the cluster is closed.
9185 * <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}
9387 * if {@link NettyUtil#isEpollAvailable() epoll is available},
94- * or {@link NioEventLoopGroup} otherwise.
88+ * or {@code io.netty.channel.nio.NioEventLoopGroup} otherwise.
9589 *
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;
9791 * The driver will provide its own internal thread factory here.
9892 * 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.
10094 */
10195 public EventLoopGroup eventLoopGroup(ThreadFactory threadFactory) {
10296 return NettyUtil.newEventLoopGroupInstance(threadFactory);
10397 }
10498
10599 /**
106- * Return the specific {@link SocketChannel} subclass to use.
100+ * Return the specific {@code SocketChannel} subclass to use.
107101 * <p>
108102 * This hook is invoked only once at {@link Cluster} initialization;
109103 * the returned instance will then be used each time the driver creates a new {@link Connection}
110104 * and configures a new instance of {@link Bootstrap} for it.
111105 * <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.
114108 *
115- * @return The {@link SocketChannel} subclass to use.
109+ * @return The {@code SocketChannel} subclass to use.
116110 */
117111 public Class<? extends SocketChannel> channelClass() {
118112 return NettyUtil.channelClass();
@@ -183,22 +177,17 @@
183177 * <p>
184178 * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required.
185179 * <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.
189182 * <p>
190183 * 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;
192185 * subclasses would have to override this method accordingly to take the appropriate action.
193186 *
194187 * @param eventLoopGroup the event loop group used by the cluster being closed
195188 */
196189 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();
202191 }
203192
204193 /**
modified driver-core/src/main/java/com/datastax/driver/core/PerHostPercentileTracker.java +3 −3
@@ -119,12 +119,12 @@
119119 * resolution and separation. This must be an integer between 0 and 5.
120120 * <p>
121121 * 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.
122125 *
123126 * @param numberOfSignificantValueDigits the new value.
124127 * @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.
128128 */
129129 public Builder withNumberOfSignificantValueDigits(int numberOfSignificantValueDigits) {
130130 this.numberOfSignificantValueDigits = numberOfSignificantValueDigits;
modified driver-core/src/main/java/com/datastax/driver/core/QueryLogger.java +1 −1
@@ -168,7 +168,7 @@
168168 public static final Logger SLOW_LOGGER = LoggerFactory.getLogger("com.datastax.driver.core.QueryLogger.SLOW");
169169
170170 /**
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.
172172 * <p>
173173 * This logger is activated by setting its level to {@code DEBUG} or {@code TRACE}.
174174 * 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 @@
355355 // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have
356356 // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice,
357357 // 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();
360360 }
361361
362362 private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
@@ -394,8 +394,8 @@
394394 logger.trace("[{}] Cancelled while in progress", id);
395395 // The connectionHandler should be non-null, but we might miss the update if we're racing with write().
396396 // 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();
399399 return;
400400 } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) {
401401 if(logger.isTraceEnabled())
@@ -677,6 +677,7 @@
677677 retryCount, queryState, queryStateRef.get());
678678 return false;
679679 }
680+ connection.release();
680681 logError(connection.address, new DriverException("Timeout waiting for response to prepare message"));
681682 retry(false, null);
682683 return true;
@@ -729,6 +730,8 @@
729730 Host queriedHost = current;
730731 OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address);
731732 try {
733+ connection.release();
734+
732735 logError(connection.address, timeoutException);
733736 retry(false, null);
734737 } catch (Exception e) {
modified driver-core/src/main/java/com/datastax/driver/core/SSLOptions.java +1 −7
@@ -24,8 +24,6 @@
2424 */
2525 public class SSLOptions {
2626
27- private static final String SSL_PROTOCOL = "TLS";
28-
2927 /**
3028 * The default SSL cipher suites.
3129 */
@@ -63,12 +61,8 @@
6361
6462 private static SSLContext makeDefaultContext() throws IllegalStateException {
6563 try {
66- SSLContext ctx = SSLContext.getInstance(SSL_PROTOCOL);
67- ctx.init(null, null, null); // use defaults
68- return ctx;
64+ return SSLContext.getDefault();
6965 } catch (NoSuchAlgorithmException e) {
70- throw new RuntimeException("This JVM doesn't support TLS, this shouldn't happen");
71- } catch (KeyManagementException e) {
7266 throw new IllegalStateException("Cannot initialize SSL Context", e);
7367 }
7468 }
modified driver-core/src/main/java/com/datastax/driver/core/Session.java +1 −0
@@ -396,6 +396,7 @@
396396 * If you want to do so, use {@link Cluster#close}, but note that it will
397397 * close all sessions created from that cluster.
398398 */
399+ @Override
399400 void close();
400401
401402 /**
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +3 −6
@@ -280,7 +280,7 @@
280280
281281 @Override
282282 public void onFailure(Throwable t) {
283- logger.error("Error creating pool to " + host, t);
283+ logger.warn("Error creating pool to " + host, t);
284284 future.set(false);
285285 }
286286 });
@@ -364,7 +364,7 @@
364364 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
365365 cluster.manager.triggerOnDown(host, false);
366366 } else {
367- logger.error("Error creating pool to " + host, t);
367+ logger.warn("Error creating pool to " + host, t);
368368 }
369369 future.set(false);
370370 }
@@ -615,10 +615,7 @@
615615 @Override
616616 public void onFailure(Throwable t) {
617617 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();
622619 }
623620 });
624621 futures.add(future);
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +98 −114
@@ -21,19 +21,15 @@
2121 import java.util.concurrent.CopyOnWriteArrayList;
2222 import java.util.concurrent.atomic.AtomicInteger;
2323
24+import com.google.common.annotations.VisibleForTesting;
2425 import com.google.common.base.Joiner;
26+import com.google.common.base.Preconditions;
2527 import com.google.common.base.Strings;
26-import com.google.common.annotations.VisibleForTesting;
2728 import com.google.common.collect.AbstractIterator;
2829 import org.slf4j.Logger;
2930 import org.slf4j.LoggerFactory;
3031
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.*;
3733
3834 /**
3935 * A data-center aware Round-robin load balancing policy.
@@ -46,15 +42,23 @@
4642 * data center can be reached.
4743 * <p>
4844 * 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.
5247 */
5348 public class DCAwareRoundRobinPolicy implements LoadBalancingPolicy {
5449
5550 private static final Logger logger = LoggerFactory.getLogger(DCAwareRoundRobinPolicy.class);
5651
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 = "";
5862
5963 private final ConcurrentMap<String, CopyOnWriteArrayList<Host>> perDcLiveHosts = new ConcurrentHashMap<String, CopyOnWriteArrayList<Host>>();
6064 private final AtomicInteger index = new AtomicInteger();
@@ -67,107 +71,6 @@
6771
6872 private volatile Configuration configuration;
6973
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-
17174 private DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc, boolean allowRemoteDCsForLocalConsistencyLevel, boolean allowEmptyLocalDc) {
17275 if (!allowEmptyLocalDc && Strings.isNullOrEmpty(localDc))
17376 throw new IllegalArgumentException("Null or empty data center specified for DC-aware policy");
@@ -230,8 +133,8 @@
230133 * For each remote datacenter, it considers a configurable number of
231134 * hosts as {@code REMOTE} and the rest is {@code IGNORED}.
232135 * <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)}.
235138 *
236139 * @param host the host of which to return the distance of.
237140 * @return the HostDistance to {@code host}.
@@ -378,4 +281,85 @@
378281 public void close() {
379282 // nothing to do
380283 }
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+ }
381365 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/DefaultRetryPolicy.java +3 −2
@@ -111,8 +111,9 @@
111111 * unavailable exception.
112112 * <p>
113113 * 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
116117 * in the query plan according to the current Load Balancing Policy.
117118 * Where retrying on the same host in the event of an Unavailable exception
118119 * 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 @@
7676 public static LoadBalancingPolicy defaultLoadBalancingPolicy() {
7777 // Note: balancing policies are stateful, so we can't store that in a static or that would screw thing
7878 // up if multiple Cluster instance are started in the same JVM.
79- return new TokenAwarePolicy(new DCAwareRoundRobinPolicy());
79+ return new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build());
8080 }
8181
8282 /**
modified driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +14 −99
@@ -16,18 +16,12 @@
1616 package com.datastax.driver.core.policies;
1717
1818 import java.net.InetSocketAddress;
19-import java.util.ArrayList;
2019 import java.util.Collection;
21-import java.util.Iterator;
22-import java.util.List;
23-import java.util.Set;
2420
21+import com.google.common.base.Predicate;
2522 import com.google.common.collect.ImmutableSet;
2623
27-import com.datastax.driver.core.Cluster;
2824 import com.datastax.driver.core.Host;
29-import com.datastax.driver.core.HostDistance;
30-import com.datastax.driver.core.Statement;
3125
3226 /**
3327 * A load balancing policy wrapper that ensure that only hosts from a provided
@@ -46,13 +40,13 @@
4640 * If all you want to do is limiting connections to hosts of the local
4741 * data-center then you should use DCAwareRoundRobinPolicy and *not* this policy
4842 * in particular.
43+ *
44+ * @see HostFilterPolicy
4945 */
50-public class WhiteListPolicy implements ChainableLoadBalancingPolicy {
51- private final LoadBalancingPolicy childPolicy;
52- private final Set<InetSocketAddress> whiteList;
46+public class WhiteListPolicy extends HostFilterPolicy {
5347
5448 /**
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
5650 * from the provided while list.
5751 *
5852 * @param childPolicy the wrapped policy.
@@ -60,96 +54,17 @@
6054 * to (whether they will get connected to or not depends on the child policy).
6155 */
6256 public WhiteListPolicy(LoadBalancingPolicy childPolicy, Collection<InetSocketAddress> whiteList) {
63- this.childPolicy = childPolicy;
64- this.whiteList = ImmutableSet.copyOf(whiteList);
57+ super(childPolicy, buildPredicate(whiteList));
6558 }
6659
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+ };
7068 }
7169
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- }
15570 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +1 −1
@@ -152,7 +152,7 @@
152152 * Sets the 'IF NOT EXISTS' option for this INSERT statement.
153153 * <p>
154154 * 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
156156 * insertions are done transactionally in the sense that if multiple
157157 * clients attempt to create a given row with this option, then at most one
158158 * may succeed.
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +26 −5
@@ -25,6 +25,7 @@
2525 import com.google.common.util.concurrent.Futures;
2626 import com.google.common.util.concurrent.ListenableFuture;
2727 import com.google.common.util.concurrent.SettableFuture;
28+import com.google.common.util.concurrent.Uninterruptibles;
2829 import org.slf4j.Logger;
2930 import org.slf4j.LoggerFactory;
3031 import org.testng.annotations.AfterMethod;
@@ -32,8 +33,12 @@
3233 import org.testng.annotations.Test;
3334
3435 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;
3539 import static org.testng.Assert.fail;
3640
41+import com.datastax.driver.core.AbstractReconnectionHandler.HandlerFuture;
3742 import com.datastax.driver.core.AbstractReconnectionHandlerTest.MockReconnectionWork.ReconnectBehavior;
3843 import com.datastax.driver.core.policies.ReconnectionPolicy.ReconnectionSchedule;
3944
@@ -48,7 +53,7 @@
4853
4954 @BeforeMethod(groups = {"unit", "short"})
5055 public void setup() {
51- executor = Executors.newScheduledThreadPool(2);
56+ executor = spy(Executors.newScheduledThreadPool(2));
5257 schedule = new MockReconnectionSchedule();
5358 work = new MockReconnectionWork();
5459 future.set(null);
@@ -133,6 +138,9 @@
133138 public void should_stop_if_cancelled_between_attempts() {
134139 handler.start();
135140
141+ // Wait for the initial schedule of a reconnect.
142+ verify(executor, timeout(1000)).schedule(handler, 0, TimeUnit.MILLISECONDS);
143+
136144 // Force a failed reconnect.
137145 schedule.tick();
138146 work.nextReconnect = ReconnectBehavior.THROW_EXCEPTION;
@@ -143,17 +151,30 @@
143151 schedule.delay = 3000;
144152 schedule.tick();
145153
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);
147160 future.get().cancel(false);
148161
149- // Should block until scheduler runs, detects cancel and exits.
162+ // Should immediately return as the future was cancelled while the task was scheduled.
150163 waitForCompletion();
151164
152165 assertThat(work.success).isFalse();
153166 // Should have had 1 failed attempt, no second attempt since cancelled.
154167 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());
157178 }
158179
159180 @Test(groups = "unit")
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +1 −1
@@ -56,7 +56,7 @@
5656
5757 @Override
5858 public String toString() {
59- return address.getHostName();
59+ return address.toString();
6060 }
6161
6262 public InetSocketAddress getMockAddress() {
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +22 −4
@@ -60,9 +60,13 @@
6060 public static final String DEFAULT_CLIENT_TRUSTSTORE_PASSWORD = "cassandra1sfun";
6161 public static final String DEFAULT_CLIENT_TRUSTSTORE_PATH = "/client.truststore";
6262
63+ public static final File DEFAULT_CLIENT_TRUSTSTORE_FILE = createTempStore(DEFAULT_CLIENT_TRUSTSTORE_PATH);
64+
6365 public static final String DEFAULT_CLIENT_KEYSTORE_PASSWORD = "cassandra1sfun";
6466 public static final String DEFAULT_CLIENT_KEYSTORE_PATH = "/client.keystore";
6567
68+ public static final File DEFAULT_CLIENT_KEYSTORE_FILE = createTempStore(DEFAULT_CLIENT_KEYSTORE_PATH);
69+
6670 public static final String DEFAULT_SERVER_TRUSTSTORE_PASSWORD = "cassandra1sfun";
6771 public static final String DEFAULT_SERVER_TRUSTSTORE_PATH = "/server.truststore";
6872
@@ -488,7 +492,9 @@
488492
489493 builder = configure(builder);
490494
491- cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
495+ cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress))
496+ .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
497+ .build();
492498 session = cluster.connect();
493499 keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
494500 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
@@ -516,12 +522,24 @@
516522
517523 private void clearSimpleKeyspace() {
518524 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.
522528 int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis();
523529 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000);
524530 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);
525543 session.execute("DROP KEYSPACE " + keyspace);
526544 } finally {
527545 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout);
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +12 −13
@@ -15,12 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import com.google.common.collect.Iterators;
19-import org.assertj.core.api.AbstractAssert;
20-
2118 import java.util.Iterator;
2219 import java.util.Set;
2320 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;
2425
2526 import static org.assertj.core.api.Assertions.assertThat;
2627
@@ -47,19 +48,17 @@
4748 }
4849
4950 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);
5556 }
5657
5758 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);
6362 }
6463
6564 /**
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +95 −8
@@ -27,6 +27,8 @@
2727 import com.google.common.collect.ImmutableMap;
2828 import com.google.common.collect.ImmutableSet;
2929 import com.google.common.collect.Lists;
30+import com.google.common.collect.Maps;
31+import com.google.common.util.concurrent.Uninterruptibles;
3032 import org.scassandra.Scassandra;
3133 import org.scassandra.http.client.PrimingClient;
3234 import org.scassandra.http.client.PrimingRequest;
@@ -42,14 +44,13 @@
4244
4345 import com.datastax.driver.core.exceptions.NoHostAvailableException;
4446 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
45-import com.datastax.driver.core.utils.CassandraVersion;
4647
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;
4850 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;
5151 import static com.datastax.driver.core.HostDistance.LOCAL;
5252 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
53+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
5354
5455 public class ClusterInitTest {
5556 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -59,7 +60,6 @@
5960 * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host.
6061 */
6162 @Test(groups = "short")
62- @CassandraVersion(major=2.0, description = "Scassandra currently broken with protocol version 1.")
6363 public void should_handle_failing_or_missing_contact_points() throws UnknownHostException {
6464 if (TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V2) > 0)
6565 throw new SkipException("Scassandra does not yet support protocol >= V3");
@@ -132,9 +132,22 @@
132132 verify(socketOptions, atLeast(6)).getKeepAlive();
133133 verify(socketOptions, atMost(7)).getKeepAlive();
134134
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+ }
138151 assertThat(cluster).host(missingHostAddress).isNull();
139152
140153 } finally {
@@ -147,6 +160,41 @@
147160 }
148161 }
149162
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+
150198 /**
151199 * Validates that a Cluster that was never able to successfully establish connection a session can be closed
152200 * properly.
@@ -158,6 +206,7 @@
158206 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
159207 Cluster cluster = Cluster.builder()
160208 .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
209+ .withNettyOptions(nonQuietClusterCloseOptions)
161210 .build();
162211 try {
163212 cluster.connect();
@@ -172,6 +221,43 @@
172221 }
173222 }
174223
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+
175261 private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException {
176262 PrimingClient primingClient = PrimingClient.builder()
177263 .withHost("localhost").withPort(scassandra.getAdminPort())
@@ -187,6 +273,7 @@
187273 .put("rpc_address", address)
188274 .put("data_center", "datacenter1")
189275 .put("rack", "rack1")
276+ .put("release_version", "2.0.1")
190277 .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
191278 .build());
192279 }
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +1 −1
@@ -653,7 +653,7 @@
653653 @Test(groups = "long")
654654 public void testRFThreeDowngradingCLTwoDCsDCAware() throws Throwable {
655655 Cluster.Builder builder = Cluster.builder()
656- .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy("dc2"), false))
656+ .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false))
657657 .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
658658 CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, 3, builder);
659659 try {
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +2 −0
@@ -30,6 +30,7 @@
3030
3131 import static com.datastax.driver.core.Assertions.assertThat;
3232 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
33+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3334
3435 import com.datastax.driver.core.policies.*;
3536 import com.datastax.driver.core.utils.CassandraVersion;
@@ -181,6 +182,7 @@
181182 for(int i = 0; i < iterations; i++) {
182183 Cluster cluster = Cluster.builder()
183184 .addContactPoints(scassandras.addresses())
185+ .withNettyOptions(nonQuietClusterCloseOptions)
184186 .build();
185187
186188 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 @@
5757 return this;
5858 }
5959
60+ public HostAssert isReconnectingFromDown() {
61+ assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone())
62+ .isTrue();
63+ return this;
64+ }
65+
6066 public HostAssert isNotReconnectingFromDown() {
6167 assertThat(actual.getReconnectionAttemptFuture() != null && !actual.getReconnectionAttemptFuture().isDone())
6268 .isFalse();
@@ -114,30 +120,4 @@
114120 fail(actual + " did not go down within " + duration + " " + unit);
115121 return this;
116122 }
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- }
143123 }
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +1 −1
@@ -537,7 +537,7 @@
537537 // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
538538 verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
539539 // 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));
541541
542542 // Wait some reasonable amount of time for connection to reestablish.
543543 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyTest.java +3 −3
@@ -155,7 +155,7 @@
155155 @Test(groups = "long")
156156 public void DCAwareRoundRobinTest() throws Throwable {
157157
158- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc2"));
158+ Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build());
159159 CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder);
160160 try {
161161
@@ -180,7 +180,7 @@
180180 @Test(groups = "long")
181181 public void DCAwareRoundRobinTest2() throws Throwable {
182182
183- Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(new DCAwareRoundRobinPolicy("dc1"));
183+ Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc1").build());
184184 CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder);
185185 try {
186186
@@ -205,7 +205,7 @@
205205 @Test(groups = "long")
206206 public void dcAwareRoundRobinTestWithOneRemoteHost() throws Throwable {
207207
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());
209209 CCMBridge.CCMCluster c = CCMBridge.buildCluster(2, 2, builder);
210210 try {
211211
modified driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +0 −1
@@ -19,7 +19,6 @@
1919 import java.util.concurrent.TimeUnit;
2020
2121 import org.mockito.ArgumentCaptor;
22-import org.mockito.Mockito;
2322 import org.testng.annotations.Test;
2423
2524 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 @@
6666 public void validatePrepared(boolean expectAll) {
6767 // Prepare the statement
6868 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);
7071
7172 // Ensure prepared properly based on expectation.
7273 List<PreparedStatementPreparation> preparationOne = scassandra.retrievePreparedStatementPreparations(1);
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +0 −37
@@ -314,43 +314,6 @@
314314 }
315315 }
316316
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-
354317 /**
355318 * A load balancing policy that:
356319 * - 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 @@
7878 assertThat(cluster).host(2)
7979 .hasState(State.UP)
8080 .isAtDistance(HostDistance.LOCAL);
81+
82+ // Ensure that the host is added to the Cluster.
8183 assertThat(cluster).host(3)
8284 .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
8385 .isAtDistance(HostDistance.IGNORED);
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +16 −4
@@ -35,6 +35,7 @@
3535 * and a CCM cluster is not running at the same time.
3636 */
3737 public class SCassandraCluster {
38+ private static final Map<Integer,Map<String,Object>> EMPTY_MAP = ImmutableMap.of();
3839 public static final int BINARY_PORT = 9042;
3940 private static final int ADMIN_PORT = 9052;
4041
@@ -42,16 +43,22 @@
4243 private final List<InetAddress> addresses;
4344 private final List<PrimingClient> primingClients;
4445 private final List<ActivityClient> activityClients;
46+ private final Map<Integer,Map<String,Object>> propertyMap;
4547
4648 public SCassandraCluster(int nodeCount) {
4749 this(CCMBridge.IP_PREFIX, nodeCount);
4850 }
4951
5052 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) {
5157 scassandras = Lists.newArrayListWithCapacity(nodeCount);
5258 addresses = Lists.newArrayListWithCapacity(nodeCount);
5359 primingClients = Lists.newArrayListWithCapacity(nodeCount);
5460 activityClients = Lists.newArrayListWithCapacity(nodeCount);
61+ this.propertyMap = propertyMap;
5562
5663 for (int i = 1; i <= nodeCount; i++) {
5764 String ip = ipPrefix + i;
@@ -142,10 +149,10 @@
142149 Map<String, ?> row = ImmutableMap.<String, Object>builder()
143150 .put("peer", address)
144151 .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))))
149156 .build();
150157
151158 rows.add(row);
@@ -166,6 +173,11 @@
166173 .build());
167174 }
168175
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+
169181 static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES =
170182 ImmutableMap.<String, ColumnTypes>builder()
171183 .put("peer", ColumnTypes.Inet)
modified driver-core/src/test/java/com/datastax/driver/core/SSLAuthenticatedEncryptionTest.java +23 −2
@@ -20,8 +20,7 @@
2020
2121 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2222
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.*;
2524
2625 public class SSLAuthenticatedEncryptionTest extends SSLTestBase {
2726
@@ -59,4 +58,26 @@
5958 public void should_not_connect_without_client_auth_but_node_requires_auth() throws Exception {
6059 connectWithSSLOptions(getSSLOptions(Optional.<String>absent(), Optional.of(DEFAULT_CLIENT_TRUSTSTORE_PATH)));
6160 }
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+ }
6283 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLEncryptionTest.java +21 −2
@@ -23,8 +23,7 @@
2323 import com.datastax.driver.core.exceptions.NoHostAvailableException;
2424
2525 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.*;
2827
2928 public class SSLEncryptionTest extends SSLTestBase {
3029
@@ -118,4 +117,24 @@
118117 cluster.close();
119118 }
120119 }
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+ }
121140 }
modified driver-core/src/test/java/com/datastax/driver/core/SSLTestBase.java +36 −0
@@ -25,7 +25,9 @@
2525 import org.testng.annotations.AfterClass;
2626 import org.testng.annotations.BeforeClass;
2727
28+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_FILE;
2829 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_KEYSTORE_PASSWORD;
30+import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_FILE;
2931 import static com.datastax.driver.core.CCMBridge.DEFAULT_CLIENT_TRUSTSTORE_PASSWORD;
3032 public abstract class SSLTestBase {
3133
@@ -74,6 +76,40 @@
7476 }
7577 }
7678
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+
77113 /**
78114 * @param keyStorePath Path to keystore, if absent is not used.
79115 * @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 @@
3131 import static org.testng.Assert.assertTrue;
3232 import static org.testng.Assert.fail;
3333
34-
34+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3535
3636 /**
3737 * Simple test of the Sessions methods against a one node cluster.
@@ -171,7 +171,10 @@
171171
172172 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
173173 // (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();
175178 final Session session = cluster.newSession();
176179
177180 // Spawn two threads to simulate the race
@@ -207,7 +210,7 @@
207210 startLatch.countDown();
208211
209212 executor.shutdown();
210- boolean normalShutdown = executor.awaitTermination(1, TimeUnit.SECONDS);
213+ boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS);
211214 assertTrue(normalShutdown);
212215
213216 // 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 @@
5151 new SimpleStatement("doesn't matter", cluster).getObject(0);
5252 }
5353
54-
5554 @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
5655 public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
5756 new SimpleStatement("doesn't matter", cluster, new Object()).getObject(1);
@@ -63,4 +62,15 @@
6362 Object actual = new SimpleStatement("doesn't matter", cluster, expected).getObject(0);
6463 assertThat(actual).isSameAs(expected);
6564 }
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+
6676 }
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 @@
2323 import java.net.ServerSocket;
2424 import java.nio.ByteBuffer;
2525 import java.util.*;
26+import java.util.concurrent.CountDownLatch;
27+import java.util.concurrent.TimeUnit;
2628
2729 import com.google.common.util.concurrent.Futures;
30+import io.netty.channel.EventLoopGroup;
2831 import org.scassandra.Scassandra;
2932 import org.scassandra.ScassandraFactory;
3033 import org.slf4j.Logger;
@@ -550,6 +553,38 @@
550553 }
551554 }
552555
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+
553588 public static Host findHost(Cluster cluster, int hostNumber) {
554589 return findHost(cluster, CCMBridge.ipOfNode(hostNumber));
555590 }
@@ -652,4 +687,16 @@
652687 .setRefreshNodeListIntervalMillis(0)
653688 .setRefreshSchemaIntervalMillis(0);
654689 }
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+ };
655702 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +2 −2
@@ -179,11 +179,11 @@
179179 Set<Host> initHosts = new CopyOnWriteArraySet<Host>();
180180
181181 CountingDCAwarePolicy() {
182- super(new DCAwareRoundRobinPolicy());
182+ super(DCAwareRoundRobinPolicy.builder().build());
183183 }
184184
185185 CountingDCAwarePolicy(String localDc) {
186- super(new DCAwareRoundRobinPolicy(localDc));
186+ super(DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).build());
187187 }
188188
189189 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 @@
2222 import com.google.common.collect.Lists;
2323 import com.google.common.collect.MapMaker;
2424 import com.google.common.util.concurrent.ThreadFactoryBuilder;
25+import io.netty.channel.EventLoopGroup;
2526 import io.netty.channel.socket.SocketChannel;
2627 import org.slf4j.Logger;
2728 import org.slf4j.LoggerFactory;
@@ -53,10 +54,16 @@
5354 private final AtomicLong channelsCreated = new AtomicLong(0);
5455
5556 private final NettyOptions nettyOptions = new NettyOptions() {
57+ @Override
5658 public void afterChannelInitialized(SocketChannel channel) throws Exception {
5759 channels.add(channel);
5860 channelsCreated.incrementAndGet();
5961 }
62+
63+ @Override
64+ public void onClusterClose(EventLoopGroup eventLoopGroup) {
65+ eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly();
66+ }
6067 };
6168
6269 @Override
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +1 −1
@@ -75,7 +75,7 @@
7575 this.mapper = mapper;
7676
7777 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());
7979
8080 this.protocolVersion = manager.getSession().getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
8181 this.mapOneFunction = new Function<ResultSet, T>() {
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappingManager.java +25 −14
@@ -18,9 +18,6 @@
1818 import java.util.Collections;
1919 import java.util.HashMap;
2020 import java.util.Map;
21-import java.util.Set;
22-
23-import com.google.common.collect.Sets;
2421
2522 import com.datastax.driver.core.ProtocolVersion;
2623 import com.datastax.driver.core.Session;
@@ -35,30 +32,22 @@
3532 public class MappingManager {
3633
3734 private final Session session;
38- private final ProtocolVersion protocolVersion;
3935 final boolean isCassandraV1;
4036
4137 private volatile Map<Class<?>, Mapper<?>> mappers = Collections.emptyMap();
4238 private volatile Map<Class<?>, MappedUDTCodec<?>> udtCodecs = Collections.emptyMap();
4339 private volatile Map<Class<?>, Object> accessors = Collections.emptyMap();
4440
45- private final Set<Class<?>> registeredUDTs = Sets.newConcurrentHashSet();
46-
4741 /**
4842 * Creates a new {@code MappingManager} using the provided {@code Session}.
4943 * <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).
5146 *
5247 * @param session the {@code Session} to use.
5348 */
5449 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));
6251 }
6352
6453 private static ProtocolVersion getProtocolVersion(Session session) {
@@ -66,6 +55,28 @@
6655 return session.getCluster().getConfiguration().getProtocolOptions().getProtocolVersion();
6756 }
6857
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+
6980 /**
7081 * The underlying {@code Session} used by this manager.
7182 * <p>
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperTest.java +25 −0
@@ -418,4 +418,29 @@
418418 // cleanup
419419 session.execute("delete from posts where user_id = " + u1.getUserId());
420420 }
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+ }
421446 }
modified features/async/README.md +3 −3
@@ -97,6 +97,6 @@
9797 hasn't been fetched already.
9898
9999 [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 @@
4747 otherwise the listener could be notified with a great deal of "Added" events as
4848 the driver builds the schema metadata from scratch for the first time.
4949
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)
5252
5353 #### Schema agreement
5454
modified features/object_mapper/creating/README.md +1 −1
@@ -44,7 +44,7 @@
4444 getters.
4545
4646 [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
4848 [consistency level]:http://docs.datastax.com/en/drivers/java/2.2/com/datastax/driver/core/ConsistencyLevel.html
4949
5050 #### Column names
modified features/object_mapper/using/README.md +1 −1
@@ -228,7 +228,7 @@
228228
229229 If a method argument is a Java enumeration, it must be annotated with
230230 `@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)):
232232
233233 ```java
234234 @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 @@
4242 properties that influence statement execution. To achieve this, you can
4343 wrap your statements in a custom [StatementWrapper] implementation.
4444
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 @@
184184 specific situations; read each method's Javadoc for detailed
185185 explanations.
186186
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)