Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset221b4b695b84ae88b9a4225a042b9c68fbd940e6c0e2ec4363a02255cc59e2ab
Authorolim7t <omichallat+github@gmail.com> · 2015-11-06 11:10 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-11-06 11:10 +01:00
Parents0d619c82c5fa, 5e3e86a8f8bb

Browse the files at this changeset

44 files changed

modified README.md +6 −2
@@ -68,9 +68,9 @@
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
7070
71-## Maven
71+## Getting the driver
7272
73-The last release of the driver is available on Maven Central. You can install
73+The latest release of the driver is available on Maven Central. You can install
7474 it in your application using the following Maven dependency:
7575
7676 ```xml
@@ -94,6 +94,10 @@
9494 We also provide a [shaded JAR](features/shaded_jar/)
9595 to avoid the explicit dependency to Netty.
9696
97+If you can't use a dependency management tool, a
98+[binary tarball](http://downloads.datastax.com/java-driver/cassandra-java-driver-2.0.11.tar.gz)
99+is available for download.
100+
97101 ## Compatibility
98102
99103 The Java client driver 2.1 ([branch 2.1](https://github.com/datastax/java-driver/tree/2.1)) is compatible with Apache
modified changelog/README.md +31 −0
@@ -4,6 +4,21 @@
44
55 - [bug] Fix implementation of UserType.hashCode() (JAVA-942)
66
7+Merged from 2.0 branch:
8+
9+- [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace.
10+- [improvement] JAVA-920: Downgrade "error creating pool" message to WARN.
11+- [bug] JAVA-954: Don't trigger reconnection before initialization complete.
12+- [improvement] JAVA-914: Avoid rejected tasks at shutdown.
13+- [improvement] JAVA-921: Add SimpleStatement.getValuesCount().
14+- [bug] JAVA-901: Move call to connection.release() out of cancelHandler.
15+- [bug] JAVA-960: Avoid race in control connection shutdown.
16+- [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo.
17+- [bug] JAVA-966: Count uninitialized connections in conviction policy.
18+- [improvement] JAVA-917: Document SSL configuration.
19+- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder.
20+- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs.
21+
722
823 ### 2.1.8
924
@@ -318,6 +333,22 @@
318333 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
319334
320335
336+### 2.0.12 (in progress)
337+
338+- [bug] JAVA-950: Fix Cluster.connect with a case-sensitive keyspace.
339+- [improvement] JAVA-920: Downgrade "error creating pool" message to WARN.
340+- [bug] JAVA-954: Don't trigger reconnection before initialization complete.
341+- [improvement] JAVA-914: Avoid rejected tasks at shutdown.
342+- [improvement] JAVA-921: Add SimpleStatement.getValuesCount().
343+- [bug] JAVA-901: Move call to connection.release() out of cancelHandler.
344+- [bug] JAVA-960: Avoid race in control connection shutdown.
345+- [bug] JAVA-656: Fix NPE in ControlConnection.updateLocationInfo.
346+- [bug] JAVA-966: Count uninitialized connections in conviction policy.
347+- [improvement] JAVA-917: Document SSL configuration.
348+- [improvement] JAVA-652: Add DCAwareRoundRobinPolicy builder.
349+- [improvement] JAVA-808: Add generic filtering policy that can be used to exclude specific DCs.
350+
351+
321352 ### 2.0.11
322353
323354 - [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 +33 −11
@@ -26,6 +26,7 @@
2626 import java.util.concurrent.atomic.AtomicReference;
2727
2828 import com.google.common.annotations.VisibleForTesting;
29+import com.google.common.base.Functions;
2930 import com.google.common.base.Predicates;
3031 import com.google.common.base.Strings;
3132 import com.google.common.collect.*;
@@ -35,6 +36,7 @@
3536
3637 import com.datastax.driver.core.exceptions.AuthenticationException;
3738 import com.datastax.driver.core.exceptions.DriverInternalError;
39+import com.datastax.driver.core.exceptions.InvalidQueryException;
3840 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3941 import com.datastax.driver.core.policies.*;
4042 import com.datastax.driver.core.utils.MoreFutures;
@@ -222,7 +224,7 @@
222224 */
223225 public Session newSession() {
224226 checkNotClosed(manager);
225- return manager.newSession(null);
227+ return manager.newSession();
226228 }
227229
228230 /**
@@ -273,6 +275,7 @@
273275 * be contacted to set the {@code keyspace}.
274276 * @throws AuthenticationException if an authentication error occurs while
275277 * contacting the initial contact points.
278+ * @throws InvalidQueryException if the keyspace does not exists.
276279 * @throws IllegalStateException if the Cluster was closed prior to calling
277280 * this method. This can occur either directly (through {@link #close()} or
278281 * {@link #closeAsync()}), or as a result of an error while initializing the
@@ -333,11 +336,28 @@
333336 * {@link #closeAsync()}), or as a result of an error while initializing the
334337 * Cluster.
335338 */
336- public ListenableFuture<Session> connectAsync(String keyspace) {
339+ public ListenableFuture<Session> connectAsync(final String keyspace) {
337340 checkNotClosed(manager);
338341 init();
339- AsyncInitSession session = manager.newSession(keyspace);
340- return session.initAsync();
342+ final AsyncInitSession session = manager.newSession();
343+ ListenableFuture<Session> sessionInitialized = session.initAsync();
344+ if (keyspace == null) {
345+ return sessionInitialized;
346+ } else {
347+ ListenableFuture<ResultSet> keyspaceSet = Futures.transform(sessionInitialized, new AsyncFunction<Session, ResultSet>() {
348+ @Override
349+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
350+ return session.executeAsync("USE " + keyspace);
351+ }
352+ });
353+ Futures.addCallback(keyspaceSet, new MoreFutures.FailureCallback<ResultSet>() {
354+ @Override
355+ public void onFailure(Throwable t) {
356+ session.closeAsync();
357+ }
358+ });
359+ return Futures.transform(keyspaceSet, Functions.<Session>constant(session));
360+ }
341361 }
342362
343363 /**
@@ -1445,6 +1465,7 @@
14451465 loadBalancingPolicy().onDown(host);
14461466 for (Host.StateListener listener : listeners)
14471467 listener.onDown(host);
1468+ startPeriodicReconnectionAttempt(host, true);
14481469 }
14491470
14501471 configuration.getPoolingOptions().setProtocolVersion(protocolVersion());
@@ -1527,8 +1548,8 @@
15271548 return translated == null ? sa : translated;
15281549 }
15291550
1530- private AsyncInitSession newSession(String keyspace) {
1531- SessionManager session = new SessionManager(Cluster.this, keyspace);
1551+ private AsyncInitSession newSession() {
1552+ SessionManager session = new SessionManager(Cluster.this);
15321553 sessions.add(session);
15331554 return session;
15341555 }
@@ -1965,7 +1986,7 @@
19651986
19661987 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
19671988 for (SessionManager s : sessions)
1968- futures.add(s.maybeAddPool(host, reusedConnection, false));
1989+ futures.add(s.maybeAddPool(host, reusedConnection));
19691990
19701991 try {
19711992 // Only mark the node up once all session have added their pool (if the load-balancing
@@ -2044,14 +2065,15 @@
20442065 }
20452066 }
20462067
2047- public boolean signalConnectionFailure(Host host, ConnectionException exception,
2048- boolean connectionInitialized, boolean isHostAddition) {
2049- // Don't signal failure until we've fully initialized the controlConnection as this might mess up with
2068+ public boolean signalConnectionFailure(Host host, Connection connection,
2069+ boolean isHostAddition) {
2070+ boolean isDown = host.convictionPolicy.signalConnectionFailure(connection);
2071+
2072+ // Don't mark the node down until we've fully initialized the controlConnection as this might mess up with
20502073 // the protocol detection
20512074 if (!isFullyInit || isClosed())
20522075 return true;
20532076
2054- boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized);
20552077 if (isDown)
20562078 triggerOnDown(host, isHostAddition, true);
20572079 return isDown;
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +75 −79
@@ -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;
@@ -46,14 +48,13 @@
4648
4749 import static io.netty.handler.timeout.IdleState.ALL_IDLE;
4850
51+import com.datastax.driver.core.Responses.Result.SetKeyspace;
4952 import com.datastax.driver.core.exceptions.AuthenticationException;
5053 import com.datastax.driver.core.exceptions.DriverException;
5154 import com.datastax.driver.core.exceptions.DriverInternalError;
52-import com.datastax.driver.core.exceptions.InvalidQueryException;
5355 import com.datastax.driver.core.utils.MoreFutures;
5456
5557 import static com.datastax.driver.core.Message.Response.Type.ERROR;
56-import static com.datastax.driver.core.Message.Response.Type.RESULT;
5758
5859 // For LoggingHandler
5960 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -160,7 +161,7 @@
160161 logger.debug(String.format("%s Error connecting to %s%s", Connection.this, Connection.this.address, extractMessage(future.cause())));
161162 channelReadyFuture.setException(new TransportException(Connection.this.address, "Cannot connect", future.cause()));
162163 } else {
163- logger.debug("{} Connection opened successfully", Connection.this);
164+ logger.debug("{} Connection established, initializing transport", Connection.this);
164165 channel.closeFuture().addListener(new ChannelCloseListener());
165166 channelReadyFuture.set(null);
166167 }
@@ -177,13 +178,14 @@
177178 ListenableFuture<Void> initializeTransportFuture = Futures.transform(channelReadyFuture,
178179 onChannelReady(protocolVersion, initExecutor), initExecutor);
179180
181+
180182 // Fallback on initializeTransportFuture so we can properly propagate specific exceptions.
181183 ListenableFuture<Void> initFuture = Futures.withFallback(initializeTransportFuture, new FutureFallback<Void>() {
182184 @Override
183185 public ListenableFuture<Void> create(Throwable t) throws Exception {
184186 SettableFuture<Void> future = SettableFuture.create();
185187 // Make sure the connection gets properly closed.
186- if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException || t instanceof SetKeyspaceException) {
188+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
187189 // Just propagate
188190 closeAsync().force();
189191 future.setException(t);
@@ -200,16 +202,8 @@
200202 }
201203 }, initExecutor);
202204
203- // If initFuture fails, close the connection. This is needed as withFallback doesn't account for cancel.
204- Futures.addCallback(initFuture, new FutureCallback<Void>() {
205- @Override
206- public void onSuccess(Void result) {
207- Host host = factory.manager.metadata.getHost(address);
208- if (host != null)
209- host.convictionPolicy.signalConnectionCreated();
210- isInitialized = true;
211- }
212-
205+ // Ensure the connection gets closed if the caller cancels the returned future.
206+ Futures.addCallback(initFuture, new MoreFutures.FailureCallback<Void>() {
213207 @Override
214208 public void onFailure(Throwable t) {
215209 if (!isClosed()) {
@@ -284,8 +278,10 @@
284278 final String expected = factory.manager.metadata.clusterName;
285279
286280 // At initialization, the cluster is not known yet
287- if (expected == null)
281+ if (expected == null) {
282+ markInitialized();
288283 return MoreFutures.VOID_SUCCESS;
284+ }
289285
290286 DefaultResultSetFuture clusterNameFuture = new DefaultResultSetFuture(null, protocolVersion, new Requests.Query("select cluster_name from system.local"));
291287 try {
@@ -298,6 +294,7 @@
298294 String actual = row.getString("cluster_name");
299295 if (!expected.equals(actual))
300296 throw new ClusterNameMismatchException(address, actual, expected);
297+ markInitialized();
301298 return MoreFutures.VOID_SUCCESS;
302299 }
303300 }, executor);
@@ -306,6 +303,11 @@
306303 }
307304 }
308305
306+ private void markInitialized() {
307+ isInitialized = true;
308+ Host.statesLogger.debug("[{}] {} Transport initialized, connection ready", address, this);
309+ }
310+
309311 private ListenableFuture<Void> authenticateV1(Authenticator authenticator, final ProtocolVersion protocolVersion, final Executor executor) {
310312 Requests.Credentials creds = new Requests.Credentials(((ProtocolV1Authenticator)authenticator).getCredentials());
311313 try {
@@ -395,33 +397,18 @@
395397 }
396398
397399 <E extends Exception> E defunct(E e) {
398- if (!isDefunct.compareAndSet(false, true))
399- return e;
400-
401- if (Host.statesLogger.isTraceEnabled())
402- Host.statesLogger.trace("Defuncting " + this, e);
403- else if (Host.statesLogger.isDebugEnabled())
404- Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
405-
406- ConnectionException ce = e instanceof ConnectionException
407- ? (ConnectionException)e
408- : new ConnectionException(address, "Connection problem", e);
409-
410- Host host = factory.manager.metadata.getHost(address);
411- if (host != null) {
412- boolean isDown = factory.manager.signalConnectionFailure(host, ce, isInitialized, host.wasJustAdded());
413-
414- if (!isDown)
415- notifyOwnerWhenDefunct();
416- // else the driver will destroy all pools and notify the control connection as part of marking the host down,
417- // so no need to notify
400+ if (isDefunct.compareAndSet(false, true)) {
401+
402+ if (Host.statesLogger.isTraceEnabled())
403+ Host.statesLogger.trace("Defuncting " + this, e);
404+ else if (Host.statesLogger.isDebugEnabled())
405+ Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage());
406+
407+ // Force the connection to close to make sure the future completes. Otherwise force() might never get called and
408+ // threads will wait on the future forever.
409+ // (this also errors out pending handlers)
410+ closeAsync().force();
418411 }
419-
420- // Force the connection to close to make sure the future completes. Otherwise force() might never get called and
421- // threads will wait on the future forever.
422- // (this also errors out pending handlers)
423- closeAsync().force();
424-
425412 return e;
426413 }
427414
@@ -457,10 +444,6 @@
457444 } catch (ExecutionException e) {
458445 Throwable cause = e.getCause();
459446 if (cause instanceof OperationTimedOutException) {
460- // The timeout logic released the connection, but that's wrong since we did not borrow it in the first place.
461- // JAVA-901 will fix this, in the meantime make sure the inFlight count is not off by one.
462- inFlight.incrementAndGet();
463-
464447 // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down
465448 logger.warn("Timeout while setting keyspace on connection to {}. "
466449 + "This should not happen but is not critical (it will be retried)", address);
@@ -478,19 +461,13 @@
478461 return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
479462 @Override
480463 public ListenableFuture<Void> apply(Message.Response response) throws Exception {
481- if (response.type == RESULT) {
482- Connection.this.keyspace = keyspace;
464+ if (response instanceof SetKeyspace) {
465+ Connection.this.keyspace = ((SetKeyspace)response).keyspace;
483466 return MoreFutures.VOID_SUCCESS;
484467 } else if (response.type == ERROR) {
485468 closeAsync().force();
486469 Responses.Error error = (Responses.Error)response;
487- Exception e = error.asException(address);
488- if (e instanceof InvalidQueryException) {
489- // Most likely means that the keyspace name is wrong. Wrap that in a specific exception, because we want
490- // to treat it specially in case of a Session init.
491- e = new SetKeyspaceException(e);
492- }
493- throw e;
470+ throw error.asException(address);
494471 } else {
495472 closeAsync().force();
496473 throw new DriverInternalError("Unexpected response while setting keyspace: " + response);
@@ -581,12 +558,14 @@
581558 // requires its writeLock.
582559 // Therefore if multiple connections in the same pool get a write error, they could deadlock;
583560 // we run defunct on a separate thread to avoid that.
584- factory.manager.executor.execute(new Runnable() {
585- @Override
586- public void run() {
587- handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount);
588- }
589- });
561+ ListeningExecutorService executor = factory.manager.executor;
562+ if (!executor.isShutdown())
563+ executor.execute(new Runnable() {
564+ @Override
565+ public void run() {
566+ handler.callback.onException(Connection.this, defunct(ce), latency, handler.retryCount);
567+ }
568+ });
590569 } else {
591570 logger.trace("{}, stream {}, request sent successfully", Connection.this, request.getStreamId());
592571 }
@@ -638,10 +617,18 @@
638617
639618 logger.debug("{} closing connection", this);
640619
641- if (isInitialized && !isDefunct.get()) {
642- Host host = factory.manager.metadata.getHost(address);
643- if(host != null)
644- host.convictionPolicy.signalConnectionClosed();
620+ Host host = factory.manager.metadata.getHost(address);
621+ if (host != null) {
622+ if (isDefunct.get()) {
623+ boolean isDown = factory.manager.signalConnectionFailure(host, this, host.wasJustAdded());
624+
625+ if (!isDown)
626+ notifyOwnerWhenDefunct();
627+ // else the driver will destroy all pools and notify the control connection as part of marking the host down,
628+ // so no need to notify
629+ } else {
630+ host.convictionPolicy.signalConnectionClosed(this);
631+ }
645632 }
646633
647634 boolean terminated = tryTerminate(false);
@@ -741,8 +728,8 @@
741728 if (isShutdown)
742729 throw new ConnectionException(address, "Connection factory is shut down");
743730
744- String name = address.toString() + '-' + getIdGenerator(host).getAndIncrement();
745- Connection connection = new Connection(name, address, this);
731+ host.convictionPolicy.signalConnectionsOpening(1);
732+ Connection connection = new Connection(buildConnectionName(host), address, this);
746733 // This method opens the connection synchronously, so wait until it's initialized
747734 try {
748735 connection.initAsync().get();
@@ -756,8 +743,9 @@
756743 * Same as open, but associate the created connection to the provided connection pool.
757744 */
758745 public Connection open(HostConnectionPool pool) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
746+ pool.host.convictionPolicy.signalConnectionsOpening(1);
747+ Connection connection = new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool);
759748 try {
760- Connection connection = newConnection(pool);
761749 connection.initAsync().get();
762750 return connection;
763751 } catch (ExecutionException e) {
@@ -766,13 +754,18 @@
766754 }
767755
768756 /**
769- * Creates a new connection and associates it to the provided connection pool, but does not start it.
757+ * Creates new connections and associate them to the provided connection pool, but does not start them.
770758 */
771- public Connection newConnection(HostConnectionPool pool) {
772- InetSocketAddress address = pool.host.getSocketAddress();
773- String name = address.toString() + '-' + getIdGenerator(pool.host).getAndIncrement();
759+ public List<Connection> newConnections(HostConnectionPool pool, int count) {
760+ pool.host.convictionPolicy.signalConnectionsOpening(count);
761+ List<Connection> connections = Lists.newArrayListWithCapacity(count);
762+ for (int i = 0; i < count; i++)
763+ connections.add(new Connection(buildConnectionName(pool.host), pool.host.getSocketAddress(), this, pool));
764+ return connections;
765+ }
774766
775- return new Connection(name, address, this, pool);
767+ private String buildConnectionName(Host host) {
768+ return host.getSocketAddress().toString() + '-' + getIdGenerator(host).getAndIncrement();
776769 }
777770
778771 static RuntimeException launderAsyncInitException(ExecutionException e) throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
@@ -875,9 +868,12 @@
875868 boolean doneWork = false;
876869 FlushItem flush;
877870 while (null != (flush = queued.poll())) {
878- channels.add(flush.channel);
879- flush.channel.write(flush.request).addListener(flush.listener);
880- doneWork = true;
871+ Channel channel = flush.channel;
872+ if (channel.isActive()) {
873+ channels.add(channel);
874+ channel.write(flush.request).addListener(flush.listener);
875+ doneWork = true;
876+ }
881877 }
882878
883879 // Always flush what we have (don't artificially delay to try to coalesce more messages)
@@ -897,7 +893,7 @@
897893 }
898894
899895 EventLoop eventLoop = eventLoopRef.get();
900- if (eventLoop != null) {
896+ if (eventLoop != null && !eventLoop.isShuttingDown()) {
901897 eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
902898 }
903899 }
@@ -1243,16 +1239,16 @@
12431239 timeout.cancel();
12441240 }
12451241
1246- public void cancelHandler() {
1242+ public boolean cancelHandler() {
12471243 if (!isCancelled.compareAndSet(false, true))
1248- return;
1244+ return false;
12491245
12501246 // We haven't really received a response: we want to remove the handle because we gave up on that
12511247 // request and there is no point in holding the handler, but we don't release the streamId. If we
12521248 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
12531249 // of its own answer, and we would have no way to detect that.
12541250 connection.dispatcher.removeHandler(this, false);
1255- connection.release();
1251+ return true;
12561252 }
12571253
12581254 private TimerTask onTimeoutTask() {
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +23 −3
@@ -128,6 +128,9 @@
128128 new AbstractReconnectionHandler("Control connection", cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) {
129129 @Override
130130 protected Connection tryReconnect() throws ConnectionException {
131+ if (isShutdown)
132+ throw new ConnectionException(null, "Control connection was shut down");
133+
131134 try {
132135 return reconnectInternal(queryPlan(), false);
133136 } catch (NoHostAvailableException e) {
@@ -141,17 +144,28 @@
141144
142145 @Override
143146 protected void onReconnection(Connection connection) {
147+ if (isShutdown) {
148+ connection.closeAsync();
149+ return;
150+ }
151+
144152 setNewConnection(connection);
145153 }
146154
147155 @Override
148156 protected boolean onConnectionException(ConnectionException e, long nextDelayMs) {
157+ if (isShutdown)
158+ return false;
159+
149160 logger.error("[Control connection] Cannot connect to any host, scheduling retry in {} milliseconds", nextDelayMs);
150161 return true;
151162 }
152163
153164 @Override
154165 protected boolean onUnknownException(Exception e, long nextDelayMs) {
166+ if (isShutdown)
167+ return false;
168+
155169 logger.error(String.format("[Control connection] Unknown error during reconnection, scheduling retry in %d milliseconds", nextDelayMs), e);
156170 return true;
157171 }
@@ -198,7 +212,6 @@
198212 // Mark the host down right away so that we don't try it again during the initialization process.
199213 // We don't call cluster.triggerOnDown because it does a bunch of other things we don't want to do here (notify LBP, etc.)
200214 host.setDown();
201- cluster.startPeriodicReconnectionAttempt(host, true);
202215 }
203216 } catch (ExecutionException e) {
204217 errors = logError(host, e.getCause(), errors, iter);
@@ -604,8 +617,15 @@
604617 if (host == null) {
605618 // We don't know that node, create the Host object but wait until we've set the known
606619 // info before signaling the addition.
607- host = cluster.metadata.add(foundHosts.get(i));
608- isNew = true;
620+ Host newHost = cluster.metadata.newHost(foundHosts.get(i));
621+ Host existing = cluster.metadata.addIfAbsent(newHost);
622+ if (existing == null) {
623+ host = newHost;
624+ isNew = true;
625+ } else {
626+ host = existing;
627+ isNew = false;
628+ }
609629 }
610630 if (dcs.get(i) != null || racks.get(i) != null)
611631 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
@@ -275,7 +275,6 @@
275275
276276 void setDown() {
277277 state = State.DOWN;
278- convictionPolicy.reset();
279278 }
280279
281280 void setUp() {
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +15 −33
@@ -105,28 +105,26 @@
105105 * pool.
106106 */
107107 ListenableFuture<Void> initAsync(Connection reusedConnection) {
108- String keyspace = manager.poolsState.keyspace;
109-
110108 Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
111109
112110 // Create initial core connections
113111 final int coreSize = options().getCoreConnectionsPerHost(hostDistance);
114112 final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize);
115113 final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(coreSize);
116- for (int i = 0; i < coreSize; i++) {
117- Connection connection;
118- ListenableFuture<Void> connectionFuture;
119- // reuse the existing connection only once
120- if (reusedConnection != null && reusedConnection.setOwner(this)) {
121- connection = reusedConnection;
122- connectionFuture = MoreFutures.VOID_SUCCESS;
123- } else {
124- connection = manager.connectionFactory().newConnection(this);
125- connectionFuture = connection.initAsync();
126- }
127- reusedConnection = null;
128- connections.add(connection);
129- connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor));
114+
115+ int toCreate = coreSize;
116+
117+ if (reusedConnection != null && reusedConnection.setOwner(this)) {
118+ toCreate -= 1;
119+ connections.add(reusedConnection);
120+ connectionFutures.add(MoreFutures.VOID_SUCCESS);
121+ }
122+
123+ List<Connection> newConnections = manager.connectionFactory().newConnections(this, toCreate);
124+ connections.addAll(newConnections);
125+ for (Connection connection : newConnections) {
126+ ListenableFuture<Void> connectionFuture = connection.initAsync();
127+ connectionFutures.add(handleErrors(connectionFuture, initExecutor));
130128 }
131129
132130 ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
@@ -175,7 +173,6 @@
175173 // accordingly in SessionManager#maybeAddPool.
176174 Throwables.propagateIfInstanceOf(t, ClusterNameMismatchException.class);
177175 Throwables.propagateIfInstanceOf(t, UnsupportedProtocolVersionException.class);
178- Throwables.propagateIfInstanceOf(t, SetKeyspaceException.class);
179176
180177 // We don't want to swallow Errors either as they probably indicate a more serious issue (OOME...)
181178 Throwables.propagateIfInstanceOf(t, Error.class);
@@ -186,17 +183,6 @@
186183 }, executor);
187184 }
188185
189- private ListenableFuture<Void> setKeyspaceAsync(ListenableFuture<Void> initFuture, final Connection connection, final String keyspace) {
190- return (keyspace == null)
191- ? initFuture
192- : Futures.transform(initFuture, new AsyncFunction<Void, Void>() {
193- @Override
194- public ListenableFuture<Void> apply(Void input) throws Exception {
195- return connection.setKeyspaceAsync(keyspace);
196- }
197- });
198- }
199-
200186 // Clean up if we got a fatal error at construction time but still created part of the core connections
201187 private void forceClose(List<Connection> connections) {
202188 for (Connection connection : connections) {
@@ -528,7 +514,7 @@
528514 }
529515
530516 private void maybeSpawnNewConnection() {
531- if (!host.convictionPolicy.canReconnectNow())
517+ if (isClosed() || !host.convictionPolicy.canReconnectNow())
532518 return;
533519
534520 while (true) {
@@ -687,10 +673,6 @@
687673 static class PoolState {
688674 volatile String keyspace;
689675
690- PoolState(String keyspace) {
691- this.keyspace = keyspace;
692- }
693-
694676 void setKeyspace(String keyspace) {
695677 this.keyspace = keyspace;
696678 }
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +10 −3
@@ -361,10 +361,17 @@
361361 this.tokenMap = TokenMap.build(factory, allTokens, keyspaces.values());
362362 }
363363
364+ Host newHost(InetSocketAddress address) {
365+ return new Host(address, cluster.convictionPolicyFactory, cluster);
366+ }
367+
368+ Host addIfAbsent(Host host) {
369+ Host previous = hosts.putIfAbsent(host.getSocketAddress(), host);
370+ return previous == null ? host : null;
371+ }
372+
364373 Host add(InetSocketAddress address) {
365- Host newHost = new Host(address, cluster.convictionPolicyFactory, cluster);
366- Host previous = hosts.putIfAbsent(address, newHost);
367- return previous == null ? newHost : null;
374+ return addIfAbsent(newHost(address));
368375 }
369376
370377 boolean remove(Host host) {
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +4 −9
@@ -183,22 +183,17 @@
183183 * <p>
184184 * This gives the implementor a chance to close the {@link EventLoopGroup} properly, if required.
185185 * <p>
186- * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully(long, long, TimeUnit) graceful shutdown}
187- * of the passed {@link EventLoopGroup} instance with no "quiet period" and a timeout of 15 seconds;
188- * then waits uninterruptibly for the shutdown to complete, or the timeout to occur, whichever happens first.
186+ * The default implementation initiates a {@link EventLoopGroup#shutdownGracefully() graceful shutdown}
187+ * of the passed {@link EventLoopGroup}, then waits uninterruptibly for the shutdown to complete or timeout.
189188 * <p>
190189 * Implementation note: if the {@link EventLoopGroup} instance is being shared, or used for other purposes than to
191- * coordinate Netty events for the current cluster, than it should not be shut down here;
190+ * coordinate Netty events for the current cluster, then it should not be shut down here;
192191 * subclasses would have to override this method accordingly to take the appropriate action.
193192 *
194193 * @param eventLoopGroup the event loop group used by the cluster being closed
195194 */
196195 public void onClusterClose(EventLoopGroup eventLoopGroup) {
197- // shutdownGracefully with default parameters employs a quiet period of 2 seconds
198- // where in pre-Netty4 versions, closing a cluster instance was very quick (milliseconds).
199- // Since we close the channels before shutting down the eventLoopGroup,
200- // it is safe to reduce the quiet period to 0 seconds
201- eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly();
196+ eventLoopGroup.shutdownGracefully().syncUninterruptibly();
202197 }
203198
204199 /**
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
@@ -352,8 +352,8 @@
352352 // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have
353353 // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice,
354354 // but it knows how to deal with it).
355- if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS)
356- connectionHandler.cancelHandler();
355+ if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS && connectionHandler.cancelHandler())
356+ connection.release();
357357 }
358358
359359 private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
@@ -391,8 +391,8 @@
391391 logger.trace("[{}] Cancelled while in progress", id);
392392 // The connectionHandler should be non-null, but we might miss the update if we're racing with write().
393393 // If it's still null, this will be handled by re-checking queryStateRef at the end of write().
394- if (connectionHandler != null)
395- connectionHandler.cancelHandler();
394+ if (connectionHandler != null && connectionHandler.cancelHandler())
395+ connectionHandler.connection.release();
396396 return;
397397 } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) {
398398 if(logger.isTraceEnabled())
@@ -671,6 +671,7 @@
671671 retryCount, queryState, queryStateRef.get());
672672 return false;
673673 }
674+ connection.release();
674675 logError(connection.address, new DriverException("Timeout waiting for response to prepare message"));
675676 retry(false, null);
676677 return true;
@@ -723,6 +724,8 @@
723724 Host queriedHost = current;
724725 OperationTimedOutException timeoutException = new OperationTimedOutException(connection.address);
725726 try {
727+ connection.release();
728+
726729 logError(connection.address, timeoutException);
727730 retry(false, null);
728731 } 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/SessionManager.java +9 −17
@@ -21,9 +21,7 @@
2121 import java.util.concurrent.*;
2222 import java.util.concurrent.atomic.AtomicReference;
2323
24-import com.google.common.base.Function;
2524 import com.google.common.base.Functions;
26-import com.google.common.base.Throwables;
2725 import com.google.common.collect.ImmutableList;
2826 import com.google.common.collect.Lists;
2927 import com.google.common.util.concurrent.*;
@@ -56,10 +54,10 @@
5654 private volatile boolean isClosing;
5755
5856 // Package protected, only Cluster should construct that.
59- SessionManager(Cluster cluster, String keyspace) {
57+ SessionManager(Cluster cluster) {
6058 this.cluster = cluster;
6159 this.pools = new ConcurrentHashMap<Host, HostConnectionPool>();
62- this.poolsState = new HostConnectionPool.PoolState(keyspace);
60+ this.poolsState = new HostConnectionPool.PoolState();
6361 }
6462
6563 public Session init() {
@@ -113,7 +111,7 @@
113111 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
114112 for (Host host : hosts)
115113 if (host.state != Host.State.DOWN)
116- futures.add(maybeAddPool(host, null, true));
114+ futures.add(maybeAddPool(host, null));
117115 return Futures.allAsList(futures);
118116 }
119117
@@ -278,7 +276,7 @@
278276
279277 @Override
280278 public void onFailure(Throwable t) {
281- logger.error("Error creating pool to " + host, t);
279+ logger.warn("Error creating pool to " + host, t);
282280 future.set(false);
283281 }
284282 });
@@ -328,7 +326,7 @@
328326 }
329327
330328 // Returns whether there was problem creating the pool
331- ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) {
329+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
332330 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
333331 if (distance == HostDistance.IGNORED)
334332 return Futures.immediateFuture(true);
@@ -361,11 +359,8 @@
361359 ClusterNameMismatchException e = (ClusterNameMismatchException)t;
362360 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
363361 cluster.manager.triggerOnDown(host, false);
364- } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) {
365- future.setException(t.getCause());
366- return;
367362 } else {
368- logger.error("Error creating pool to " + host, t);
363+ logger.warn("Error creating pool to " + host, t);
369364 }
370365 future.set(false);
371366 }
@@ -409,7 +404,7 @@
409404
410405 if (pool == null) {
411406 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
412- poolCreatedFutures.add(maybeAddPool(h, null, false));
407+ poolCreatedFutures.add(maybeAddPool(h, null));
413408 } else if (dist != pool.hostDistance) {
414409 if (dist == HostDistance.IGNORED) {
415410 toRemove.add(h);
@@ -443,7 +438,7 @@
443438 if (pool == null) {
444439 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
445440 try {
446- maybeAddPool(h, null, false).get();
441+ maybeAddPool(h, null).get();
447442 } catch (ExecutionException e) {
448443 // Ignore, maybeAddPool has already handled the error
449444 }
@@ -607,10 +602,7 @@
607602 @Override
608603 public void onFailure(Throwable t) {
609604 logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t);
610-
611- // If the query timed out, that already released the connection, otherwise do it now
612- if (!(t instanceof OperationTimedOutException))
613- c.release();
605+ c.release();
614606 }
615607 });
616608 futures.add(future);
deleted driver-core/src/main/java/com/datastax/driver/core/SetKeyspaceException.java +0 −23
@@ -1,23 +0,0 @@
1-/*
2- * Copyright (C) 2012-2015 DataStax Inc.
3- *
4- * Licensed under the Apache License, Version 2.0 (the "License");
5- * you may not use this file except in compliance with the License.
6- * You may obtain a copy of the License at
7- *
8- * http://www.apache.org/licenses/LICENSE-2.0
9- *
10- * Unless required by applicable law or agreed to in writing, software
11- * distributed under the License is distributed on an "AS IS" BASIS,
12- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13- * See the License for the specific language governing permissions and
14- * limitations under the License.
15- */
16-package com.datastax.driver.core;
17-
18-@SuppressWarnings("serial")
19-class SetKeyspaceException extends Exception {
20- SetKeyspaceException(Exception cause) {
21- super(cause);
22- }
23-}
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +107 −88
@@ -21,19 +21,15 @@
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, CloseableLoadBalancingPolicy {
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();
@@ -68,101 +72,35 @@
6872 private volatile Configuration configuration;
6973
7074 /**
71- * Creates a new datacenter aware round robin policy that auto-discover
72- * the local data-center.
73- * <p>
74- * If this constructor is used, the data-center used as local will the
75- * data-center of the first Cassandra node the driver connects to. This
76- * will always be ok if all the contact points use at {@code Cluster}
77- * creation are in the local data-center. If it's not the case, you should
78- * provide the local data-center name yourself by using one of the other
79- * constructor of this class.
80- * <p>
81- * This constructor is a shortcut for {@code new DCAwareRoundRobinPolicy(null)},
82- * and as such will ignore all hosts in remote data-centers.
75+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
76+ * backward-compatibility purposes, it is equivalent to {@code DCAwareRoundRobinPolicy.builder().build()}.
8377 */
78+ @Deprecated
8479 public DCAwareRoundRobinPolicy() {
8580 this(null, 0, false, true);
8681 }
8782
8883 /**
89- * Creates a new datacenter aware round robin policy given the name of
90- * the local datacenter.
91- * <p>
92- * The name of the local datacenter provided must be the local
93- * datacenter name as known by Cassandra.
94- * <p>
95- * The policy created will ignore all remote hosts. In other words,
96- * this is equivalent to {@code new DCAwareRoundRobinPolicy(localDc, 0)}.
97- *
98- * @param localDc the name of the local datacenter (as known by
99- * Cassandra). If this is {@code null}, the policy will default to the
100- * data-center of the first node connected to.
84+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
85+ * backward-compatibility purposes, it is equivalent to {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).build()}.
10186 */
10287 public DCAwareRoundRobinPolicy(String localDc) {
10388 this(localDc, 0, false, false);
10489 }
10590
10691 /**
107- * Creates a new DCAwareRoundRobin policy given the name of the local
108- * datacenter and that uses the provided number of host per remote
109- * datacenter as failover for the local hosts.
110- * <p>
111- * The name of the local datacenter provided must be the local
112- * datacenter name as known by Cassandra.
113- * <p>
114- * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host
115- * in the local datacenter can be reached and if the consistency
116- * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM},
117- * then up to {@code usedHostsPerRemoteDc} host per remote data-center
118- * will be tried by the policy as a fallback. Please note that no
119- * remote host will be used for {@code LOCAL_ONE} and {@code LOCAL_QUORUM}
120- * since this would change the meaning of the consistency level (and
121- * thus somewhat break the consistency contract).
122- *
123- * @param localDc the name of the local datacenter (as known by
124- * Cassandra). If this is {@code null}, the policy will default to the
125- * data-center of the first node connected to.
126- * @param usedHostsPerRemoteDc the number of host per remote
127- * datacenter that policies created by the returned factory should
128- * consider. Created policies {@code distance} method will return a
129- * {@code HostDistance.REMOTE} distance for only {@code
130- * usedHostsPerRemoteDc} hosts per remote datacenter. Other hosts
131- * of the remote datacenters will be ignored (and thus no
132- * connections to them will be maintained).
92+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
93+ * backward-compatibility purposes, it is equivalent to
94+ * {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).withUsedHostsPerRemoteDc(usedHostsPerRemoteDc).build()}.
13395 */
13496 public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc) {
13597 this(localDc, usedHostsPerRemoteDc, false, false);
13698 }
13799
138100 /**
139- * Creates a new DCAwareRoundRobin policy given the name of the local
140- * datacenter and that uses the provided number of host per remote
141- * datacenter as failover for the local hosts.
142- * <p>
143- * This constructor is equivalent to {@link #DCAwareRoundRobinPolicy(String, int)}
144- * but allows to override the policy of never using remote data-center
145- * nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is
146- * however inadvisable to do so in almost all cases, as this would
147- * potentially break consistency guarantees and if you are fine with that,
148- * it's probably better to use a weaker consitency like {@code ONE}, {@code
149- * TWO} or {@code THREE}. As such, this constructor should generally
150- * be avoided in favor of {@link #DCAwareRoundRobinPolicy(String, int)}.
151- * Use it only if you know and understand what you do.
152- *
153- * @param localDc the name of the local datacenter (as known by
154- * Cassandra). If this is {@code null}, the policy will default to the
155- * data-center of the first node connected to.
156- * @param usedHostsPerRemoteDc the number of host per remote
157- * datacenter that policies created by the returned factory should
158- * consider. Created policies {@code distance} method will return a
159- * {@code HostDistance.REMOTE} distance for only {@code
160- * usedHostsPerRemoteDc} hosts per remote datacenter. Other hosts
161- * of the remote datacenters will be ignored (and thus no
162- * connections to them will be maintained).
163- * @param allowRemoteDCsForLocalConsistencyLevel whether or not the
164- * policy may return remote host when building query plan for query
165- * having consitency {@code LOCAL_ONE} and {@code LOCAL_QUORUM}.
101+ * @deprecated {@link #builder()} is the recommended way to build instances of this class. This constructor was preserved for
102+ * backward-compatibility purposes, it is equivalent to
103+ * {@code DCAwareRoundRobinPolicy.builder().withLocalDc(localDc).withUsedHostsPerRemoteDc(usedHostsPerRemoteDc).allowRemoteDCsForLocalConsistencyLevel().build()}.
166104 */
167105 public DCAwareRoundRobinPolicy(String localDc, int usedHostsPerRemoteDc, boolean allowRemoteDCsForLocalConsistencyLevel) {
168106 this(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, false);
@@ -382,4 +320,85 @@
382320 public void close() {
383321 // nothing to do
384322 }
323+
324+ /**
325+ * Helper class to build the policy.
326+ */
327+ public static class Builder {
328+ private String localDc;
329+ private int usedHostsPerRemoteDc;
330+ private boolean allowRemoteDCsForLocalConsistencyLevel;
331+
332+ /**
333+ * Sets the name of the datacenter that will be considered "local" by the policy.
334+ * <p>
335+ * This must be the name as known by Cassandra (in other words, the name in that appears in
336+ * {@code system.peers}, or in the output of admin tools like nodetool).
337+ * <p>
338+ * If this method isn't called, the policy will default to the datacenter of the first node
339+ * connected to. This will always be ok if all the contact points use at {@code Cluster}
340+ * creation are in the local data-center. Otherwise, you should provide the name yourself
341+ * with this method.
342+ *
343+ * @param localDc the name of the datacenter. It should not be {@code null}.
344+ * @return this builder.
345+ */
346+ public Builder withLocalDc(String localDc) {
347+ Preconditions.checkArgument(!Strings.isNullOrEmpty(localDc),
348+ "localDc name can't be null or empty. If you want to let the policy autodetect the datacenter, don't call Builder.withLocalDC");
349+ this.localDc = localDc;
350+ return this;
351+ }
352+
353+ /**
354+ * Sets the number of hosts per remote datacenter that the policy should consider.
355+ * <p>
356+ * The policy's {@code distance()} method will return a {@code HostDistance.REMOTE} distance for only {@code usedHostsPerRemoteDc}
357+ * hosts per remote datacenter. Other hosts of the remote datacenters will be ignored (and thus no connections to them will be
358+ * maintained).
359+ * <p>
360+ * If {@code usedHostsPerRemoteDc > 0}, then if for a query no host in the local datacenter can be reached and if the consistency
361+ * level of the query is not {@code LOCAL_ONE} or {@code LOCAL_QUORUM}, then up to {@code usedHostsPerRemoteDc} hosts per remote
362+ * datacenter will be tried by the policy as a fallback. By default, no remote host will be used for {@code LOCAL_ONE} and
363+ * {@code LOCAL_QUORUM}, since this would change the meaning of the consistency level, somewhat breaking the consistency contract
364+ * (this can be overridden with {@link #allowRemoteDCsForLocalConsistencyLevel()}).
365+ * <p>
366+ * If this method isn't called, the policy will default to 0.
367+ *
368+ * @param usedHostsPerRemoteDc the number.
369+ * @return this builder.
370+ */
371+ public Builder withUsedHostsPerRemoteDc(int usedHostsPerRemoteDc) {
372+ Preconditions.checkArgument(usedHostsPerRemoteDc >= 0,
373+ "usedHostsPerRemoteDc must be equal or greater than 0");
374+ this.usedHostsPerRemoteDc = usedHostsPerRemoteDc;
375+ return this;
376+ }
377+
378+ /**
379+ * Allows the policy to return remote hosts when building query plans for queries having consistency level {@code LOCAL_ONE}
380+ * or {@code LOCAL_QUORUM}.
381+ * <p>
382+ * When used in conjunction with {@link #withUsedHostsPerRemoteDc(int) usedHostsPerRemoteDc} > 0, this overrides the policy of
383+ * never using remote datacenter nodes for {@code LOCAL_ONE} and {@code LOCAL_QUORUM} queries. It is however inadvisable to do
384+ * so in almost all cases, as this would potentially break consistency guarantees and if you are fine with that, it's probably
385+ * better to use a weaker consitency like {@code ONE}, {@code TWO} or {@code THREE}. As such, this method should generally be
386+ * avoided; use it only if you know and understand what you do.
387+ *
388+ * @return this builder.
389+ */
390+ public Builder allowRemoteDCsForLocalConsistencyLevel() {
391+ this.allowRemoteDCsForLocalConsistencyLevel = true;
392+ return this;
393+ }
394+
395+ /**
396+ * Builds the policy configured by this builder.
397+ *
398+ * @return the policy.
399+ */
400+ public DCAwareRoundRobinPolicy build() {
401+ return new DCAwareRoundRobinPolicy(localDc, usedHostsPerRemoteDc, allowRemoteDCsForLocalConsistencyLevel, true);
402+ }
403+ }
385404 }
added driver-core/src/main/java/com/datastax/driver/core/policies/HostFilterPolicy.java +184 −0
@@ -0,0 +1,184 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import java.net.InetSocketAddress;
19+import java.util.ArrayList;
20+import java.util.Collection;
21+import java.util.Iterator;
22+import java.util.List;
23+
24+import com.google.common.base.Predicate;
25+import com.google.common.base.Predicates;
26+import com.google.common.collect.ImmutableSet;
27+
28+import com.datastax.driver.core.Cluster;
29+import com.datastax.driver.core.Host;
30+import com.datastax.driver.core.HostDistance;
31+import com.datastax.driver.core.Statement;
32+
33+/**
34+ * A load balancing policy wrapper that ensures that only hosts matching the predicate
35+ * will ever be returned.
36+ * <p>
37+ * This policy wraps another load balancing policy and will delegate the choice
38+ * of hosts to the wrapped policy with the exception that only hosts matching
39+ * the predicate provided when constructing this policy will ever be
40+ * returned. Any host not matching the predicate will be considered {@code IGNORED}
41+ * and thus will not be connected to.
42+ */
43+public class HostFilterPolicy implements ChainableLoadBalancingPolicy, CloseableLoadBalancingPolicy {
44+ private final LoadBalancingPolicy childPolicy;
45+ private final Predicate<Host> predicate;
46+
47+ /**
48+ * Create a new policy that wraps the provided child policy but only "allows" hosts
49+ * matching the predicate.
50+ *
51+ * @param childPolicy the wrapped policy.
52+ * @param predicate the host predicate. Only hosts matching this predicate may get connected
53+ * to (whether they will get connected to or not depends on the child policy).
54+ */
55+ public HostFilterPolicy(LoadBalancingPolicy childPolicy, Predicate<Host> predicate) {
56+ this.childPolicy = childPolicy;
57+ this.predicate = predicate;
58+ }
59+
60+ @Override
61+ public LoadBalancingPolicy getChildPolicy() {
62+ return childPolicy;
63+ }
64+
65+ /**
66+ * {@inheritDoc}
67+ *
68+ * @throws IllegalArgumentException if none of the host in {@code hosts}
69+ * (which will correspond to the contact points) matches the predicate.
70+ */
71+ @Override
72+ public void init(Cluster cluster, Collection<Host> hosts) {
73+ List<Host> whiteHosts = new ArrayList<Host>(hosts.size());
74+ for (Host host : hosts)
75+ if (predicate.apply(host))
76+ whiteHosts.add(host);
77+
78+ if (whiteHosts.isEmpty())
79+ throw new IllegalArgumentException(String.format("Cannot use HostFilterPolicy where the filter allows none of the contacts points (%s)", hosts));
80+
81+ childPolicy.init(cluster, whiteHosts);
82+ }
83+
84+ /**
85+ * {@inheritDoc}
86+ *
87+ * @return {@link HostDistance#IGNORED} if {@code host} is not matching the predicate, the HostDistance
88+ * as returned by the wrapped policy otherwise.
89+ */
90+ @Override
91+ public HostDistance distance(Host host) {
92+ return predicate.apply(host)
93+ ? childPolicy.distance(host)
94+ : HostDistance.IGNORED;
95+ }
96+
97+ /**
98+ * {@inheritDoc}
99+ * <p>
100+ * It is guaranteed that only hosts matching the predicate will be returned.
101+ */
102+ @Override
103+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
104+ // Just delegate to the child policy, since we filter the hosts not white
105+ // listed upfront, the child policy will never see a host that is not white
106+ // listed and thus can't return one.
107+ return childPolicy.newQueryPlan(loggedKeyspace, statement);
108+ }
109+
110+ @Override
111+ public void onUp(Host host) {
112+ if (predicate.apply(host))
113+ childPolicy.onUp(host);
114+ }
115+
116+ @SuppressWarnings("deprecation")
117+ @Override
118+ public void onSuspected(Host host) {
119+ if (predicate.apply(host))
120+ childPolicy.onSuspected(host);
121+ }
122+
123+ @Override
124+ public void onDown(Host host) {
125+ if (predicate.apply(host))
126+ childPolicy.onDown(host);
127+ }
128+
129+ @Override
130+ public void onAdd(Host host) {
131+ if (predicate.apply(host))
132+ childPolicy.onAdd(host);
133+ }
134+
135+ @Override
136+ public void onRemove(Host host) {
137+ if (predicate.apply(host))
138+ childPolicy.onRemove(host);
139+ }
140+
141+ @Override
142+ public void close() {
143+ if (childPolicy instanceof CloseableLoadBalancingPolicy)
144+ ((CloseableLoadBalancingPolicy)childPolicy).close();
145+ }
146+
147+ /**
148+ * Create a new policy that wraps the provided child policy but only "allows" hosts
149+ * whose DC belongs to the provided list.
150+ *
151+ * @param childPolicy the wrapped policy.
152+ * @param dcs the DCs.
153+ *
154+ * @return the policy.
155+ */
156+ public static HostFilterPolicy fromDCWhiteList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
157+ return new HostFilterPolicy(childPolicy, hostDCPredicate(dcs, true));
158+ }
159+
160+ /**
161+ * Create a new policy that wraps the provided child policy but only "forbids" hosts
162+ * whose DC belongs to the provided list.
163+ *
164+ * @param childPolicy the wrapped policy.
165+ * @param dcs the DCs.
166+ *
167+ * @return the policy.
168+ */
169+ public static HostFilterPolicy fromDCBlackList(LoadBalancingPolicy childPolicy, Iterable<String> dcs) {
170+ return new HostFilterPolicy(childPolicy, Predicates.not(hostDCPredicate(dcs, false)));
171+ }
172+
173+ private static Predicate<Host> hostDCPredicate(Iterable<String> dcs, final boolean includeNullDC) {
174+ final ImmutableSet<String> _dcs = ImmutableSet.copyOf(dcs);
175+ return new Predicate<Host>() {
176+ @Override
177+ public boolean apply(Host host) {
178+ String hdc = host.getDatacenter();
179+ return (hdc == null) ? includeNullDC : _dcs.contains(hdc);
180+ }
181+ };
182+ }
183+
184+}
modified driver-core/src/main/java/com/datastax/driver/core/policies/Policies.java +1 −1
@@ -85,7 +85,7 @@
8585 public static LoadBalancingPolicy defaultLoadBalancingPolicy() {
8686 // Note: balancing policies are stateful, so we can't store that in a static or that would screw thing
8787 // up if multiple Cluster instance are started in the same JVM.
88- return new TokenAwarePolicy(new DCAwareRoundRobinPolicy());
88+ return new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().build());
8989 }
9090
9191 /**
modified driver-core/src/main/java/com/datastax/driver/core/policies/WhiteListPolicy.java +14 −106
@@ -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, CloseableLoadBalancingPolicy {
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,103 +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 onSuspected(Host host) {
135- if (whiteList.contains(host.getSocketAddress()))
136- childPolicy.onSuspected(host);
137- }
138-
139- @Override
140- public void onDown(Host host) {
141- if (whiteList.contains(host.getSocketAddress()))
142- childPolicy.onDown(host);
143- }
144-
145- @Override
146- public void onAdd(Host host) {
147- if (whiteList.contains(host.getSocketAddress()))
148- childPolicy.onAdd(host);
149- }
150-
151- @Override
152- public void onRemove(Host host) {
153- if (whiteList.contains(host.getSocketAddress()))
154- childPolicy.onRemove(host);
155- }
156-
157- @Override
158- public void close() {
159- if (childPolicy instanceof CloseableLoadBalancingPolicy)
160- ((CloseableLoadBalancingPolicy)childPolicy).close();
161- }
16270 }
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Insert.java +1 −1
@@ -148,7 +148,7 @@
148148 * Sets the 'IF NOT EXISTS' option for this INSERT statement.
149149 * <p>
150150 * An insert with that option will not succeed unless the row does not
151- * exist at the time the insertion is execution. The existence check and
151+ * exist at the time the insertion is executed. The existence check and
152152 * insertions are done transactionally in the sense that if multiple
153153 * clients attempt to create a given row with this option, then at most one
154154 * 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/AsyncQueryTest.java +42 −19
@@ -16,15 +16,13 @@
1616 package com.datastax.driver.core;
1717
1818 import java.util.Collection;
19-import java.util.concurrent.ExecutionException;
20-import java.util.concurrent.TimeUnit;
19+import java.util.List;
20+import java.util.concurrent.*;
2121
2222 import com.google.common.base.Function;
2323 import com.google.common.collect.Lists;
24-import com.google.common.util.concurrent.AsyncFunction;
25-import com.google.common.util.concurrent.Futures;
26-import com.google.common.util.concurrent.ListenableFuture;
27-import com.google.common.util.concurrent.Uninterruptibles;
24+import com.google.common.util.concurrent.*;
25+import org.testng.annotations.DataProvider;
2826 import org.testng.annotations.Test;
2927
3028 import static org.assertj.core.api.Assertions.assertThat;
@@ -35,12 +33,24 @@
3533
3634 public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
3735
36+ @DataProvider(name="keyspace")
37+ public static Object[][] keyspace() {
38+ return new Object[][]{ { "asyncquerytest" }, { "\"AsyncQueryTest\"" } };
39+ }
40+
3841 @Override
3942 protected Collection<String> getTableDefinitions() {
40- return Lists.newArrayList(
41- "create table foo(k int primary key, v int)",
42- "insert into foo (k, v) values (1, 1)"
43- );
43+ List<String> definitions = Lists.newArrayList();
44+
45+ for (Object[] objects : keyspace()) {
46+ String keyspace = (String)objects[0];
47+
48+ definitions.add(String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace));
49+ definitions.add(String.format("create table %s.foo(k int primary key, v int)", keyspace));
50+ definitions.add(String.format("insert into %s.foo (k, v) values (1, 1)", keyspace));
51+ }
52+
53+ return definitions;
4454 }
4555
4656 /**
@@ -76,27 +86,40 @@
7686 // Neither cluster2 nor session2 are initialized at this point
7787 assertThat(cluster2.manager.metadata).isNull();
7888
79- ResultSetFuture future = session2.executeAsync(String.format("select v from %s.foo where k = 1", keyspace));
89+ ResultSetFuture future = session2.executeAsync("select release_version from system.local");
8090 Row row = Uninterruptibles.getUninterruptibly(future).one();
8191
82- assertThat(row.getInt(0)).isEqualTo(1);
92+ assertThat(row.getString(0)).isNotEmpty();
8393 } finally {
8494 if (cluster2 != null)
8595 cluster2.close();
8696 }
8797 }
8898
89- @Test(groups = "short")
90- public void should_chain_query_on_async_session_init() throws Exception {
91- ListenableFuture<Integer> resultFuture = connectAndQuery(this.keyspace);
99+ @Test(groups = "short", dataProvider = "keyspace", enabled = false,
100+ description = "disabled because the blocking USE call in the current pool implementation makes it deadlock")
101+ public void should_chain_query_on_async_session_init_with_same_executor(String keyspace) throws Exception {
102+ ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, MoreExecutors.sameThreadExecutor());
92103
93104 Integer result = Uninterruptibles.getUninterruptibly(resultFuture);
94105 assertThat(result).isEqualTo(1);
95106 }
96107
108+ @Test(groups = "short", dataProvider = "keyspace")
109+ public void should_chain_query_on_async_session_init_with_different_executor(String keyspace) throws Exception {
110+ ExecutorService executor = Executors.newFixedThreadPool(1);
111+
112+ ListenableFuture<Integer> resultFuture = connectAndQuery(keyspace, executor);
113+
114+ Integer result = Uninterruptibles.getUninterruptibly(resultFuture);
115+ assertThat(result).isEqualTo(1);
116+
117+ executor.shutdownNow();
118+ }
119+
97120 @Test(groups = "short")
98121 public void should_propagate_error_to_chained_query_if_session_init_fails() throws Exception {
99- ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace");
122+ ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace", MoreExecutors.sameThreadExecutor());
100123
101124 try {
102125 Uninterruptibles.getUninterruptibly(resultFuture);
@@ -107,20 +130,20 @@
107130 }
108131 }
109132
110- private ListenableFuture<Integer> connectAndQuery(String keyspace) {
133+ private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) {
111134 ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace);
112135 ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
113136 @Override
114137 public ListenableFuture<ResultSet> apply(Session session) throws Exception {
115138 return session.executeAsync("select v from foo where k = 1");
116139 }
117- });
140+ }, executor);
118141 return Futures.transform(queryFuture, new Function<ResultSet, Integer>() {
119142 @Override
120143 public Integer apply(ResultSet rs) {
121144 return rs.one().getInt(0);
122145 }
123- });
146+ }, executor);
124147 }
125148
126149 private static HostConnectionPool getPool(Session session) {
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +22 −5
@@ -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
@@ -478,7 +482,9 @@
478482
479483 builder = configure(builder);
480484
481- cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
485+ cluster = builder.addContactPointsWithPorts(Collections.singletonList(hostAddress))
486+ .withNettyOptions(TestUtils.nonQuietClusterCloseOptions)
487+ .build();
482488 session = cluster.connect();
483489 keyspace = SIMPLE_KEYSPACE + "_" + ksNumber.incrementAndGet();
484490 session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
@@ -506,19 +512,30 @@
506512
507513 private void clearSimpleKeyspace() {
508514 if(keyspace != null) {
509- // Temporarily extend read timeout to 1 minute to accommodate keyspaces with many tables.
510- // This should be more than enough although some tests create many tables, so dropping a keyspace
511- // could take as long as 12 seconds on restricted hardware.
515+ logger.debug("Removing keyspace {}.", keyspace);
516+ // Temporarily extend read timeout to 1 minute to accommodate dropping keyspaces and
517+ // tables being slow, particularly in a CI environment.
512518 int currentTimeout = cluster.getConfiguration().getSocketOptions().getReadTimeoutMillis();
513519 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(60000);
514520 try {
521+ KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace);
522+ if (ksm != null) {
523+ // drop each table individually as this seems to be more dependable than dropping
524+ // the entire keyspace at once if it has many tables.
525+ if(ksm.getTables().size() > 10) {
526+ for (TableMetadata table : ksm.getTables()) {
527+ logger.debug("Dropping table {}.{}.", keyspace, table.getName());
528+ session.execute("DROP TABLE " + keyspace + "." + table.getName());
529+ }
530+ }
531+ }
532+ logger.debug("Dropping keyspace {}.", keyspace);
515533 session.execute("DROP KEYSPACE " + keyspace);
516534 } finally {
517535 cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(currentTimeout);
518536 }
519537 }
520538 }
521-
522539 }
523540
524541 public static class CCMCluster {
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 +56 −8
@@ -27,6 +27,7 @@
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.util.concurrent.Uninterruptibles;
3031 import org.scassandra.Scassandra;
3132 import org.scassandra.http.client.PrimingClient;
3233 import org.scassandra.http.client.PrimingRequest;
@@ -42,14 +43,13 @@
4243
4344 import com.datastax.driver.core.exceptions.NoHostAvailableException;
4445 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
45-import com.datastax.driver.core.utils.CassandraVersion;
4646
47-import static com.datastax.driver.core.Assertions.*;
47+import static com.datastax.driver.core.Assertions.assertThat;
48+import static com.datastax.driver.core.Assertions.fail;
4849 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;
5150 import static com.datastax.driver.core.HostDistance.LOCAL;
5251 import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
52+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
5353
5454 public class ClusterInitTest {
5555 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -59,7 +59,6 @@
5959 * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host.
6060 */
6161 @Test(groups = "short")
62- @CassandraVersion(major=2.0, description = "Scassandra currently broken with protocol version 1.")
6362 public void should_handle_failing_or_missing_contact_points() throws UnknownHostException {
6463 if (TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V2) > 0)
6564 throw new SkipException("Scassandra does not yet support protocol >= V3");
@@ -132,9 +131,22 @@
132131 verify(socketOptions, atLeast(6)).getKeepAlive();
133132 verify(socketOptions, atMost(7)).getKeepAlive();
134133
135- assertThat(cluster).host(realHostAddress).isNotNull().hasState(UP);
136- for (FakeHost failingHost : failingHosts)
137- assertThat(cluster).host(failingHost.address).hasState(DOWN);
134+ assertThat(cluster).host(realHostAddress).isNotNull().isUp();
135+ // It is likely but not guaranteed that a host is marked down at this point.
136+ // It should eventually be marked down as Cluster.Manager.triggerOnDown should be
137+ // called and submit a task that marks the host down.
138+ for (FakeHost failingHost : failingHosts) {
139+ assertThat(cluster).host(failingHost.address).goesDownWithin(10, TimeUnit.SECONDS);
140+ Host host = TestUtils.findHost(cluster, failingHost.address);
141+ // There is a possible race here in that the host is marked down in a separate Executor in onDown
142+ // and then starts a periodic reconnection attempt shortly after. Since setDown is called before
143+ // startPeriodicReconnectionAttempt, we add a slight delay here if the future isn't set yet.
144+ if(host.getReconnectionAttemptFuture() == null || host.getReconnectionAttemptFuture().isDone()) {
145+ logger.warn("Periodic Reconnection Attempt hasn't started yet for {}, waiting 1 second and then checking.", host);
146+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
147+ }
148+ assertThat(cluster).host(failingHost.address).isReconnectingFromDown();
149+ }
138150 assertThat(cluster).host(missingHostAddress).isNull();
139151
140152 } finally {
@@ -147,6 +159,41 @@
147159 }
148160 }
149161
162+ /**
163+ * Validates that if hosts are unreachable during Cluster initialization, no background reconnection to them
164+ * is scheduled before the initialization is complete.
165+ *
166+ * @test_category connection
167+ * @jira_ticket JAVA-954
168+ * @expected_result No reconnection scheduled.
169+ */
170+ @Test(groups="short", expectedExceptions = NoHostAvailableException.class)
171+ public void should_not_schedule_reconnections_before_init_complete() {
172+ // Both contact points time out so we're sure we'll try both of them and init will never complete.
173+ List<FakeHost> hosts = Lists.newArrayList(
174+ new FakeHost(CCMBridge.ipOfNode(0), 9042, THROWING_CONNECT_TIMEOUTS),
175+ new FakeHost(CCMBridge.ipOfNode(1), 9042, THROWING_CONNECT_TIMEOUTS));
176+ // Use a low reconnection interval and keep the default connect timeout (5 seconds). So if a reconnection was scheduled,
177+ // we would see a call to the reconnection policy.
178+ CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(100));
179+ Cluster cluster = Cluster.builder()
180+ .addContactPoints(hosts.get(0).address, hosts.get(1).address)
181+ .withReconnectionPolicy(reconnectionPolicy)
182+ .build();
183+ try {
184+ cluster.init();
185+ } finally {
186+ // We expect a nextDelay invocation from the ConvictionPolicy for each host, but that will
187+ // not trigger a reconnection.
188+ assertThat(reconnectionPolicy.count.get()).isEqualTo(2);
189+ for (FakeHost fakeHost : hosts) {
190+ fakeHost.stop();
191+ }
192+ }
193+ // We don't test that reconnections are scheduled if init succeeds, but that's covered in
194+ // should_handle_failing_or_missing_contact_points
195+ }
196+
150197 /**
151198 * Validates that a Cluster that was never able to successfully establish connection a session can be closed
152199 * properly.
@@ -158,6 +205,7 @@
158205 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
159206 Cluster cluster = Cluster.builder()
160207 .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
208+ .withNettyOptions(nonQuietClusterCloseOptions)
161209 .build();
162210 try {
163211 cluster.connect();
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.DelegatingLoadBalancingPolicy;
3536 import com.datastax.driver.core.policies.LoadBalancingPolicy;
@@ -194,6 +195,7 @@
194195 for(int i = 0; i < iterations; i++) {
195196 Cluster cluster = Cluster.builder()
196197 .addContactPoints(scassandras.addresses())
198+ .withNettyOptions(nonQuietClusterCloseOptions)
197199 .build();
198200
199201 try {
added driver-core/src/test/java/com/datastax/driver/core/CountingReconnectionPolicy.java +51 −0
@@ -0,0 +1,51 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.concurrent.atomic.AtomicInteger;
19+
20+import com.datastax.driver.core.policies.ReconnectionPolicy;
21+
22+/**
23+ * A reconnection policy that tracks how many times its schedule has been invoked.
24+ */
25+public class CountingReconnectionPolicy implements ReconnectionPolicy {
26+ public final AtomicInteger count = new AtomicInteger();
27+ private final ReconnectionPolicy childPolicy;
28+
29+ public CountingReconnectionPolicy(ReconnectionPolicy childPolicy) {
30+ this.childPolicy = childPolicy;
31+ }
32+
33+ @Override
34+ public ReconnectionSchedule newSchedule() {
35+ return new CountingSchedule(childPolicy.newSchedule());
36+ }
37+
38+ class CountingSchedule implements ReconnectionSchedule {
39+ private final ReconnectionSchedule childSchedule;
40+
41+ public CountingSchedule(ReconnectionSchedule childSchedule) {
42+ this.childSchedule = childSchedule;
43+ }
44+
45+ @Override
46+ public long nextDelayMs() {
47+ count.incrementAndGet();
48+ return childSchedule.nextDelayMs();
49+ }
50+ }
51+}
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +6 −22
@@ -57,6 +57,12 @@
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,26 +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 onSuspected(Host host) {
129- }
130-
131- @Override
132- public void onDown(Host host) {
133- }
134-
135- @Override
136- public void onRemove(Host host) {
137- }
138- }
139123 }
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +1 −1
@@ -538,7 +538,7 @@
538538 // 2 attempts for connection.open (reconnect control connection and initial connection for host state).
539539 verify(factory, after(reconnectInterval*2).atLeast(2)).open(host);
540540 // 7 attempts for core connections after first initial connection.
541- verify(factory, timeout(reconnectInterval*2).times(7)).newConnection(any(HostConnectionPool.class));
541+ verify(factory, timeout(reconnectInterval*2)).newConnections(any(HostConnectionPool.class), eq(7));
542542
543543 // Wait some reasonable amount of time for connection to reestablish.
544544 Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS);
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 −31
@@ -314,37 +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-
348317 /**
349318 * A load balancing policy that:
350319 * - 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/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
@@ -33,7 +33,7 @@
3333 import static org.testng.Assert.assertTrue;
3434 import static org.testng.Assert.fail;
3535
36-
36+import static com.datastax.driver.core.TestUtils.nonQuietClusterCloseOptions;
3737
3838 /**
3939 * Simple test of the Sessions methods against a one node cluster.
@@ -173,7 +173,10 @@
173173
174174 // Use our own cluster and session (not the ones provided by the parent class) because we want an uninitialized cluster
175175 // (note the use of newSession below)
176- final Cluster cluster = Cluster.builder().addContactPointsWithPorts(Collections.singletonList(hostAddress)).build();
176+ final Cluster cluster = Cluster.builder()
177+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
178+ .withNettyOptions(nonQuietClusterCloseOptions)
179+ .build();
177180 final Session session = cluster.newSession();
178181
179182 // Spawn two threads to simulate the race
@@ -209,7 +212,7 @@
209212 startLatch.countDown();
210213
211214 executor.shutdown();
212- boolean normalShutdown = executor.awaitTermination(1, TimeUnit.SECONDS);
215+ boolean normalShutdown = executor.awaitTermination(5, TimeUnit.SECONDS);
213216 assertTrue(normalShutdown);
214217
215218 // The deadlock occurred here before JAVA-418
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +10 −0
@@ -48,4 +48,14 @@
4848 assertThat(actual).isSameAs(expected);
4949 }
5050
51+ @Test(groups = "unit")
52+ public void should_return_number_of_values() {
53+ assertThat(
54+ new SimpleStatement("doesn't matter").valuesCount()
55+ ).isEqualTo(0);
56+ assertThat(
57+ new SimpleStatement("doesn't matter", 1, 2).valuesCount()
58+ ).isEqualTo(2);
59+ }
60+
5161 }
added driver-core/src/test/java/com/datastax/driver/core/StateListenerBase.java +40 −0
@@ -0,0 +1,40 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+public class StateListenerBase implements Host.StateListener {
19+ @Override
20+ public void onAdd(Host host) {
21+ }
22+
23+ @Override
24+ public void onUp(Host host) {
25+ }
26+
27+ @Override
28+ public void onSuspected(Host host) {
29+
30+ }
31+
32+ @Override
33+ public void onDown(Host host) {
34+ }
35+
36+ @Override
37+ public void onRemove(Host host) {
38+ }
39+
40+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +47 −0
@@ -23,8 +23,11 @@
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;
@@ -382,6 +385,38 @@
382385 }
383386 }
384387
388+ public static Host findOrWaitForHost(Cluster cluster, int node, long duration, TimeUnit unit) {
389+ return findOrWaitForHost(cluster, CCMBridge.ipOfNode(node), duration, unit);
390+ }
391+
392+ public static Host findOrWaitForHost(final Cluster cluster, final String address, long duration, TimeUnit unit) {
393+ Host host = findHost(cluster, address);
394+ if(host == null) {
395+ final CountDownLatch addSignal = new CountDownLatch(1);
396+ Host.StateListener addListener = new StateListenerBase() {
397+ @Override
398+ public void onAdd(Host host) {
399+ if(host.getAddress().getHostAddress().equals(address)) {
400+ // for a new node, because of this we also listen for add events.
401+ addSignal.countDown();
402+ }
403+ }
404+ };
405+ cluster.register(addListener);
406+ try {
407+ // Wait until an add event occurs or we timeout.
408+ if (addSignal.await(duration, unit)) {
409+ host = findHost(cluster, address);
410+ }
411+ } catch (InterruptedException e) {
412+ return null;
413+ } finally {
414+ cluster.unregister(addListener);
415+ }
416+ }
417+ return host;
418+ }
419+
385420 public static Host findHost(Cluster cluster, int hostNumber) {
386421 return findHost(cluster, CCMBridge.ipOfNode(hostNumber));
387422 }
@@ -473,4 +508,16 @@
473508 .setRefreshNodeListIntervalMillis(0)
474509 .setRefreshSchemaIntervalMillis(0);
475510 }
511+
512+ /**
513+ * A custom {@link NettyOptions} that shuts down the {@link EventLoopGroup} after
514+ * no quiet time. This is useful for tests that consistently close clusters as
515+ * otherwise there is a 2 second delay (from JAVA-914).
516+ */
517+ public static NettyOptions nonQuietClusterCloseOptions = new NettyOptions() {
518+ @Override
519+ public void onClusterClose(EventLoopGroup eventLoopGroup) {
520+ eventLoopGroup.shutdownGracefully(0, 15, TimeUnit.SECONDS).syncUninterruptibly();
521+ }
522+ };
476523 }
added driver-core/src/test/java/com/datastax/driver/core/policies/HostFilterPolicyTest.java +168 −0
@@ -0,0 +1,168 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.policies;
17+
18+import java.net.InetSocketAddress;
19+import java.util.Collection;
20+
21+import com.google.common.base.Predicate;
22+import com.google.common.base.Predicates;
23+import com.google.common.collect.Iterators;
24+import com.google.common.collect.Lists;
25+import org.mockito.ArgumentCaptor;
26+import org.mockito.Captor;
27+import org.mockito.Mock;
28+import org.mockito.MockitoAnnotations;
29+import org.testng.annotations.BeforeMethod;
30+import org.testng.annotations.Test;
31+
32+import static org.assertj.core.api.Assertions.assertThat;
33+import static org.mockito.Mockito.*;
34+
35+import com.datastax.driver.core.Cluster;
36+import com.datastax.driver.core.Host;
37+import com.datastax.driver.core.HostDistance;
38+import com.datastax.driver.core.Statement;
39+
40+public class HostFilterPolicyTest {
41+ @Mock
42+ Cluster cluster;
43+
44+ @Mock
45+ Host host1, host2, host3;
46+
47+ InetSocketAddress address1 = InetSocketAddress.createUnresolved("192.168.1.1", 2345);
48+ InetSocketAddress address2 = InetSocketAddress.createUnresolved("192.168.1.2", 9876);
49+ InetSocketAddress address3 = InetSocketAddress.createUnresolved("192.168.1.3", 6666);
50+
51+ @Mock
52+ CloseableLoadBalancingPolicy wrappedPolicy;
53+
54+ @Captor
55+ ArgumentCaptor<Collection<Host>> hostsCaptor;
56+
57+ @BeforeMethod(groups = "unit")
58+ public void setup() {
59+ MockitoAnnotations.initMocks(this);
60+
61+ when(host1.getSocketAddress()).thenReturn(address1);
62+ when(host2.getSocketAddress()).thenReturn(address2);
63+ when(host3.getSocketAddress()).thenReturn(address3);
64+
65+ when(wrappedPolicy.distance(any(Host.class))).thenReturn(HostDistance.LOCAL);
66+ }
67+
68+ @Test(groups = "unit")
69+ public void should_delegate_to_wrapped_policy_when_predicate_is_true() {
70+ Predicate<Host> predicate = Predicates.alwaysTrue();
71+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
72+
73+ policy.onAdd(host1);
74+ verify(wrappedPolicy).onAdd(host1);
75+
76+ policy.onDown(host1);
77+ verify(wrappedPolicy).onDown(host1);
78+
79+ policy.onUp(host1);
80+ verify(wrappedPolicy).onUp(host1);
81+
82+ policy.onRemove(host1);
83+ verify(wrappedPolicy).onRemove(host1);
84+
85+ assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
86+
87+ policy.close();
88+ verify(wrappedPolicy).close();
89+ }
90+
91+ @Test(groups = "unit")
92+ public void should_not_delegate_to_wrapped_policy_when_predicate_is_false() {
93+ Predicate<Host> predicate = Predicates.alwaysFalse();
94+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
95+
96+ policy.onAdd(host1);
97+ verify(wrappedPolicy, never()).onAdd(host1);
98+
99+ policy.onDown(host1);
100+ verify(wrappedPolicy, never()).onDown(host1);
101+
102+ policy.onUp(host1);
103+ verify(wrappedPolicy, never()).onUp(host1);
104+
105+ policy.onRemove(host1);
106+ verify(wrappedPolicy, never()).onRemove(host1);
107+
108+ assertThat(policy.distance(host1)).isSameAs(HostDistance.IGNORED);
109+ }
110+
111+ @Test(groups = "unit")
112+ public void should_filter_init_hosts_with_predicate() {
113+ Predicate<Host> predicate = Predicates.in(Lists.newArrayList(host1, host2));
114+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
115+
116+ policy.init(cluster, Lists.newArrayList(host1, host2, host3));
117+
118+ verify(wrappedPolicy).init(eq(cluster), hostsCaptor.capture());
119+ assertThat(hostsCaptor.getValue()).containsOnly(host1, host2);
120+ }
121+
122+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)
123+ public void should_throw_if_predicate_filters_out_all_init_hosts() {
124+ Predicate<Host> predicate = Predicates.alwaysFalse();
125+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, predicate);
126+
127+ policy.init(cluster, Lists.newArrayList(host1, host2, host3));
128+ }
129+
130+ @Test(groups = "unit")
131+ public void should_return_query_plan_of_wrapped_policy() {
132+ when(wrappedPolicy.newQueryPlan(any(String.class), any(Statement.class)))
133+ .thenReturn(Iterators.forArray(host1, host2, host3));
134+
135+ HostFilterPolicy policy = new HostFilterPolicy(wrappedPolicy, null);
136+
137+ assertThat(policy.newQueryPlan("keyspace", mock(Statement.class)))
138+ .containsExactly(host1, host2, host3);
139+ }
140+
141+ @Test(groups = "unit")
142+ public void should_ignore_DCs_in_black_list() {
143+ when(host1.getDatacenter()).thenReturn("dc1");
144+ when(host2.getDatacenter()).thenReturn("dc2");
145+ when(host3.getDatacenter()).thenReturn(null);
146+
147+ HostFilterPolicy policy = HostFilterPolicy.fromDCBlackList(wrappedPolicy,
148+ Lists.newArrayList("dc2"));
149+
150+ assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
151+ assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED);
152+ assertThat(policy.distance(host3)).isSameAs(HostDistance.LOCAL);
153+ }
154+
155+ @Test(groups = "unit")
156+ public void should_ignore_DCs_not_in_white_list_and_not_null() {
157+ when(host1.getDatacenter()).thenReturn("dc1");
158+ when(host2.getDatacenter()).thenReturn("dc2");
159+ when(host3.getDatacenter()).thenReturn(null);
160+
161+ HostFilterPolicy policy = HostFilterPolicy.fromDCWhiteList(wrappedPolicy,
162+ Lists.newArrayList("dc1"));
163+
164+ assertThat(policy.distance(host1)).isSameAs(HostDistance.LOCAL);
165+ assertThat(policy.distance(host2)).isSameAs(HostDistance.IGNORED);
166+ assertThat(policy.distance(host3)).isSameAs(HostDistance.LOCAL);
167+ }
168+}
modified driver-core/src/test/java/com/datastax/driver/core/utils/SocketChannelMonitor.java +7 −0
@@ -22,6 +22,7 @@
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
added features/ssl/README.md +180 −0
@@ -0,0 +1,180 @@
1+## SSL
2+
3+You can secure traffic between the driver and Cassandra with SSL. There
4+are two aspects to that:
5+
6+* **client-to-node encryption**, where the traffic is encrypted, and the
7+ client verifies the identity of the Cassandra nodes it connects to;
8+* optionally, **client certificate authentication**, where Cassandra
9+ nodes also verify the identity of the client.
10+
11+This section describes the driver-side configuration; it assumes that
12+you've already configured SSL in Cassandra:
13+
14+* [the Cassandra documentation](http://docs.datastax.com/en/cassandra/2.0/cassandra/security/secureSSLClientToNode_t.html)
15+ covers a basic approach with self-signed certificates, which is fine
16+ for development and tests.
17+* [this blog post](http://thelastpickle.com/blog/2015/09/30/hardening-cassandra-step-by-step-part-1-server-to-server.html)
18+ details a more advanced solution based on a Certificate Authority
19+ (CA).
20+
21+### Preparing the certificates
22+
23+#### Client truststore
24+
25+This is required for client-to-node encryption.
26+
27+If you're using self-signed certificates, you need to export the public
28+part of each node's certificate from that node's keystore:
29+
30+```
31+keytool -export -alias cassandra -file cassandranode0.cer -keystore .keystore
32+```
33+
34+Then add all public certificates to the client truststore:
35+
36+```
37+keytool -import -v -trustcacerts -alias <cassandra_node0> -file cassandranode0.cer -keystore client.truststore
38+keytool -import -v -trustcacerts -alias <cassandra_node1> -file cassandranode1.cer -keystore client.truststore
39+...
40+```
41+
42+If you're using a Certificate Authority, the client truststore only
43+needs to contain the CA's certificate:
44+
45+```
46+keytool -import -v -trustcacerts -alias CARoot -file ca.cer -keystore client.truststore
47+```
48+
49+#### Client keystore
50+
51+If you also intend to use client certificate authentication, generate
52+the public and private key pair for the client:
53+
54+```
55+keytool -genkey -keyalg RSA -alias client -keystore client.keystore
56+```
57+
58+If you're using self-signed certificates, extract the public part of the
59+client certificate, and import it in the truststore of each Cassandra
60+node:
61+
62+```
63+keytool -export -alias client -file client.cer -keystore client.keystore
64+keytool -import -v -trustcacerts -alias client -file client.cer -keystore server.truststore
65+```
66+
67+If you're using a CA, sign the client certificate with it (see the blog
68+post linked at the top of this page). Then the nodes' truststores only
69+need to contain the CA's certificate (which should already be the case
70+if you've followed the steps for inter-node encryption).
71+
72+### Driver configuration
73+
74+#### Property-based
75+
76+`withSSL()` gives you a basic JSSE configuration:
77+
78+```java
79+Cluster cluster = Cluster.builder()
80+ .addContactPoint("127.0.0.1")
81+ .withSSL()
82+ .build();
83+```
84+
85+You can then use
86+[JSSE system properties](http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization)
87+for specific details, like keystore locations and passwords:
88+
89+```
90+-Djavax.net.ssl.trustStore=/path/to/client.truststore
91+-Djavax.net.ssl.trustStorePassword=password123
92+# If you're using client authentication:
93+-Djavax.net.ssl.keyStore=/path/to/client.keystore
94+-Djavax.net.ssl.keyStorePassword=password123
95+```
96+
97+#### Programmatic
98+
99+If you need more control than what system properties allow, you can
100+configure SSL programmatically by creating an [SSLOptions] instance:
101+
102+```java
103+SSLContext sslContext = ... // create and configure SSL context
104+String[] cipherSuites = ...
105+
106+SSLOptions sslOptions = new SSLOptions(sslContext, cipherSuites);
107+
108+Cluster cluster = Cluster.builder()
109+ .addContactPoint("127.0.0.1")
110+ .withSSL(sslOptions)
111+ .build();
112+```
113+
114+A known limitation of the current API is that you can't customize the
115+`SSLEngine`, which prevents advanced features like hostname
116+verification. This will be fixed in 3.0 (see
117+[JAVA-841](https://datastax-oss.atlassian.net/browse/JAVA-841)), in the
118+meantime see below for a workaround.
119+
120+
121+### Bypassing `SSLOptions`
122+
123+For advanced use cases, it's possible to bypass `SSLOptions` entirely:
124+since the driver provides a hook into the Netty pipeline (by way of
125+[NettyOptions]), you can add the SSL handler yourself:
126+
127+```java
128+import io.netty.handler.ssl.SslHandler;
129+import javax.net.ssl.SSLContext;
130+import javax.net.ssl.SSLEngine;
131+
132+// Base implementation: each time a connection is established, create an SSL handler
133+// and add it to the pipeline:
134+public abstract class SslNettyOptions extends NettyOptions {
135+ @Override
136+ public void afterChannelInitialized(SocketChannel channel) throws Exception {
137+ channel.pipeline().addFirst("ssl", createSslHandler(channel));
138+ }
139+
140+ protected abstract SslHandler createSslHandler(SocketChannel channel);
141+}
142+
143+// Concrete implementation based on JSSE
144+public class MyNettyOptions extends SslNettyOptions {
145+
146+ private final SSLContext sslContext = createContext();
147+
148+ protected SslHandler createSslHandler(SocketChannel channel) {
149+ return new SslHandler(createEngine(sslContext, channel));
150+ }
151+
152+ private static SSLContext createContext() {
153+ ... // create and configure context
154+ }
155+
156+ private static SSLEngine createEngine(SSLContext sslContext, SocketChannel channel) {
157+ SSLEngine engine = sslContext.createSSLEngine();
158+ engine.setUseClientMode(true);
159+ ... // any extra configuration
160+ return engine;
161+ }
162+}
163+
164+cluster = Cluster.builder()
165+ .addContactPoint("127.0.0.1")
166+ .withNettyOptions(new MyNettyOptions())
167+ .build();
168+```
169+
170+This could be used for the following use cases:
171+
172+* fine control over JSSE configuration, for example tuning the SSL
173+ engine for hostname verification;
174+* bypassing JSSE altogether in favor of another SSL implementation:
175+ recent Netty versions support
176+ [OpenSSL](http://netty.io/wiki/forked-tomcat-native.html)
177+ for improved performance.
178+
179+[SSLOptions]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SSLOptions.html
180+[NettyOptions]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/NettyOptions.html