Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.1' into 2.2
Changesetff0d4e2c49872906f19cf643dc7f2991efa3a55e0c056da6f9f13c8112da5b05
Authorolim7t <omichallat+github@gmail.com> · 2015-09-16 21:04 +02:00
Committerolim7t <omichallat+github@gmail.com> · 2015-09-17 02:38 +02:00
Parents96af18c4bcd8, e0c6a4e0504f

Browse the files at this changeset

116 files changed

modified .gitignore +2 −0
@@ -13,3 +13,5 @@
1313 *.iml
1414
1515 /driver-core/dependency-reduced-pom.xml
16+.java-version
17+
modified changelog/README.md +75 −1
@@ -1,5 +1,55 @@
11 ## Changelog
22
3+### 2.2.0-rc4 (in progress)
4+
5+Merged from 2.0 branch:
6+
7+- [improvement] Log streamid at the trace level on sending request and receiving response (JAVA-718)
8+- [bug] Fix SpeculativeExecutionPolicy.init() and close() are never called (JAVA-796)
9+- [improvement] Suppress unnecessary warning at shutdown (JAVA-710)
10+- [improvement] Allow DNS name with multiple A-records as contact point (#340)
11+- [bug] Allow tracing across multiple result pages (JAVA-794)
12+- [bug] DowngradingConsistencyRetryPolicy ignores write timeouts (JAVA-737)
13+- [bug] Forbid bind marker in QueryBuilder add/append/prepend (JAVA-736)
14+- [bug] Prevent QueryBuilder.quote() from applying duplicate double quotes (JAVA-712)
15+- [bug] Prevent QueryBuilder from trying to serialize raw string (JAVA-688)
16+- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679)
17+- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475)
18+- [improvement] Create values() function for Insert builder using List (JAVA-225)
19+- [improvement] Warn when ReplicationStrategy encounters invalid
20+ replication factors (JAVA-702)
21+- [improvement] Add PoolingOptions method to set both core and max
22+ connections (JAVA-662).
23+- [improvement] Do not include epoll JAR in binary distribution (JAVA-766)
24+- [improvement] Optimize internal copies of Request objects (JAVA-726)
25+- [bug] Preserve tracing across retries (JAVA-815)
26+- [improvement] New RetryDecision.tryNextHost() (JAVA-709)
27+- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
28+- [improvement] Provide API to retrieve values of a Parameterized SimpleStatement (JAVA-765)
29+- [improvement] implement UPDATE ... IF EXISTS in QueryBuilder (JAVA-827)
30+- [improvement] Randomize contact points list to prevent hotspots (JAVA-618)
31+- [improvement] Surface the coordinator used on query failure (JAVA-720)
32+- [bug] Handle contact points removed during init (JAVA-792)
33+- [improvement] Allow PlainTextAuthProvider to change its credentials at runtime (JAVA-719)
34+- [new feature] Make it possible to register for SchemaChange Events (JAVA-151)
35+- [improvement] Downgrade "Asked to rebuild table" log from ERROR to INFO level (JAVA-861)
36+- [improvement] Provide an option to prepare statements only on one node (JAVA-797)
37+- [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658)
38+- [improvement] Customizable creation of netty timer (JAVA-853)
39+- [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859)
40+- [improvement] Debounce control connection queries (JAVA-657)
41+- [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784)
42+- [new feature] Make driver-side metadata optional (JAVA-828)
43+- [improvement] Allow hosts to remain partially up (JAVA-544)
44+- [improvement] Remove internal blocking calls and expose async session
45+ creation (JAVA-821, JAVA-822)
46+- [improvement] Use parallel calls when re-preparing statement on other
47+ hosts (JAVA-725)
48+- [bug] Don't use connection timeout for unrelated internal queries (JAVA-629)
49+- [bug] Fix NPE in speculative executions when metrics disabled
50+ (JAVA-892)
51+
52+
353 ### 2.2.0-rc3
454
555 - [bug] Propagate CodecRegistry to nested UDTs (JAVA-847)
@@ -346,8 +396,9 @@
346396 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
347397
348398
349-### 2.0.11 (in progress)
399+### 2.0.11
350400
401+- [improvement] Log streamid at the trace level on sending request and receiving response (JAVA-718)
351402 - [bug] Fix SpeculativeExecutionPolicy.init() and close() are never called (JAVA-796)
352403 - [improvement] Suppress unnecessary warning at shutdown (JAVA-710)
353404 - [improvement] Allow DNS name with multiple A-records as contact point (#340)
@@ -368,6 +419,29 @@
368419 - [bug] Preserve tracing across retries (JAVA-815)
369420 - [improvement] New RetryDecision.tryNextHost() (JAVA-709)
370421 - [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733)
422+- [improvement] Provide API to retrieve values of a Parameterized SimpleStatement (JAVA-765)
423+- [improvement] implement UPDATE ... IF EXISTS in QueryBuilder (JAVA-827)
424+- [improvement] Randomize contact points list to prevent hotspots (JAVA-618)
425+- [improvement] Surface the coordinator used on query failure (JAVA-720)
426+- [bug] Handle contact points removed during init (JAVA-792)
427+- [improvement] Allow PlainTextAuthProvider to change its credentials at runtime (JAVA-719)
428+- [new feature] Make it possible to register for SchemaChange Events (JAVA-151)
429+- [improvement] Downgrade "Asked to rebuild table" log from ERROR to INFO level (JAVA-861)
430+- [improvement] Provide an option to prepare statements only on one node (JAVA-797)
431+- [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658)
432+- [improvement] Customizable creation of netty timer (JAVA-853)
433+- [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859)
434+- [improvement] Debounce control connection queries (JAVA-657)
435+- [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784)
436+- [new feature] Make driver-side metadata optional (JAVA-828)
437+- [improvement] Allow hosts to remain partially up (JAVA-544)
438+- [improvement] Remove internal blocking calls and expose async session
439+ creation (JAVA-821, JAVA-822)
440+- [improvement] Use parallel calls when re-preparing statement on other
441+ hosts (JAVA-725)
442+- [bug] Don't use connection timeout for unrelated internal queries (JAVA-629)
443+- [bug] Fix NPE in speculative executions when metrics disabled
444+ (JAVA-892)
371445
372446 Merged from 2.0.10_fixes branch:
373447
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +7 −4
@@ -40,6 +40,7 @@
4040
4141 private static final Logger logger = LoggerFactory.getLogger(AbstractReconnectionHandler.class);
4242
43+ private final String name;
4344 private final ScheduledExecutorService executor;
4445 private final ReconnectionPolicy.ReconnectionSchedule schedule;
4546 /**
@@ -53,11 +54,12 @@
5354
5455 private final CountDownLatch ready = new CountDownLatch(1);
5556
56- public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt) {
57- this(executor, schedule, currentAttempt, -1);
57+ public AbstractReconnectionHandler(String name, ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt) {
58+ this(name, executor, schedule, currentAttempt, -1);
5859 }
5960
60- public AbstractReconnectionHandler(ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt, long initialDelayMs) {
61+ public AbstractReconnectionHandler(String name, ScheduledExecutorService executor, ReconnectionPolicy.ReconnectionSchedule schedule, AtomicReference<ListenableFuture<?>> currentAttempt, long initialDelayMs) {
62+ this.name = name;
6163 this.executor = executor;
6264 this.schedule = schedule;
6365 this.currentAttempt = currentAttempt;
@@ -92,7 +94,7 @@
9294 break;
9395 }
9496 if (currentAttempt.compareAndSet(previous, handlerFuture)) {
95- logger.debug("Becoming the active handler");
97+ Host.statesLogger.debug("[{}] starting reconnection attempt", name);
9698 break;
9799 }
98100 }
@@ -176,6 +178,7 @@
176178 return;
177179 }
178180
181+ Host.statesLogger.debug("[{}] next reconnection attempt in {} ms", name, nextDelay);
179182 handlerFuture.nextTry = executor.schedule(this, nextDelay, TimeUnit.MILLISECONDS);
180183 }
181184
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +4 −4
@@ -29,7 +29,7 @@
2929 *
3030 * This is primarly intended to make mocking easier.
3131 */
32-public abstract class AbstractSession implements Session {
32+public abstract class AbstractSession implements Session, AsyncInitSession {
3333
3434 /**
3535 * {@inheritDoc}
@@ -95,7 +95,7 @@
9595 try {
9696 return Uninterruptibles.getUninterruptibly(prepareAsync(query));
9797 } catch (ExecutionException e) {
98- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
98+ throw DriverThrowables.propagateCause(e);
9999 }
100100 }
101101
@@ -107,7 +107,7 @@
107107 try {
108108 return Uninterruptibles.getUninterruptibly(prepareAsync(statement));
109109 } catch (ExecutionException e) {
110- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
110+ throw DriverThrowables.propagateCause(e);
111111 }
112112 }
113113
@@ -163,7 +163,7 @@
163163 try {
164164 closeAsync().get();
165165 } catch (ExecutionException e) {
166- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
166+ throw DriverThrowables.propagateCause(e);
167167 } catch (InterruptedException e) {
168168 Thread.currentThread().interrupt();
169169 }
modified driver-core/src/main/java/com/datastax/driver/core/AggregateMetadata.java +26 −0
@@ -19,6 +19,7 @@
1919 import java.util.Collections;
2020 import java.util.List;
2121
22+import com.google.common.base.Objects;
2223 import com.google.common.collect.ImmutableList;
2324 import com.google.common.collect.Lists;
2425
@@ -289,4 +290,29 @@
289290 public DataType getStateType() {
290291 return stateType;
291292 }
293+
294+ @Override
295+ public boolean equals(Object other) {
296+ if (other instanceof AggregateMetadata) {
297+ AggregateMetadata that = (AggregateMetadata)other;
298+ return this.keyspace.getName().equals(that.keyspace.getName()) &&
299+ this.fullName.equals(that.fullName) &&
300+ this.argumentTypes.equals(that.argumentTypes) &&
301+ Objects.equal(this.finalFuncFullName, that.finalFuncFullName) &&
302+ // Note: this might be a problem if a custom codec has been registered for the initCond's type, with a target Java type that
303+ // does not properly implement equals. We don't have any control over this, at worst this would lead to spurious change
304+ // notifications.
305+ Objects.equal(this.initCond, that.initCond) &&
306+ this.returnType.equals(that.returnType) &&
307+ this.stateFuncFullName.equals(that.stateFuncFullName) &&
308+ this.stateType.equals(that.stateType);
309+ }
310+ return false;
311+ }
312+
313+ @Override
314+ public int hashCode() {
315+ return Objects.hashCode(this.keyspace.getName(), this.fullName, this.argumentTypes,
316+ this.finalFuncFullName, this.initCond, this.returnType, this.stateFuncFullName, this.stateType);
317+ }
292318 }
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
@@ -294,7 +294,7 @@
294294 try {
295295 Uninterruptibles.getUninterruptibly(fetchMoreResults());
296296 } catch (ExecutionException e) {
297- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
297+ throw DriverThrowables.propagateCause(e);
298298 }
299299 }
300300 }
added driver-core/src/main/java/com/datastax/driver/core/AsyncInitSession.java +36 −0
@@ -0,0 +1,36 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.google.common.util.concurrent.ListenableFuture;
19+
20+/**
21+ * A {@link Session} that can be initialized asynchronously.
22+ *
23+ * This interface exists only for backward compatibility reasons: {@link #initAsync()} should really be
24+ * defined by {@link Session}, but adding it after the fact would break binary compatibility.
25+ *
26+ * By default, all sessions returned by the driver implement this interface. The only way you would get
27+ * sessions that don't is if you use a custom {@link Cluster} subclass.
28+ */
29+public interface AsyncInitSession extends Session {
30+ /**
31+ * Initialize this session asynchronously.
32+ *
33+ * @return a future that will complete when the session is fully initialized.
34+ */
35+ ListenableFuture<Session> initAsync();
36+}
added driver-core/src/main/java/com/datastax/driver/core/ChainedResultSetFuture.java +75 −0
@@ -0,0 +1,75 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.concurrent.ExecutionException;
19+import java.util.concurrent.TimeUnit;
20+import java.util.concurrent.TimeoutException;
21+
22+import com.google.common.util.concurrent.AbstractFuture;
23+import com.google.common.util.concurrent.FutureCallback;
24+import com.google.common.util.concurrent.Futures;
25+import com.google.common.util.concurrent.Uninterruptibles;
26+
27+/**
28+ * A {@code ResultSetFuture} that will complete when its source future completes.
29+ */
30+class ChainedResultSetFuture extends AbstractFuture<ResultSet> implements ResultSetFuture {
31+
32+ private volatile ResultSetFuture source;
33+
34+ void setSource(ResultSetFuture source) {
35+ if (this.isCancelled())
36+ source.cancel(false);
37+ this.source = source;
38+ Futures.addCallback(source, new FutureCallback<ResultSet>() {
39+ @Override
40+ public void onSuccess(ResultSet result) {
41+ ChainedResultSetFuture.this.set(result);
42+ }
43+
44+ @Override
45+ public void onFailure(Throwable t) {
46+ ChainedResultSetFuture.this.setException(t);
47+ }
48+ });
49+ }
50+
51+ @Override
52+ public boolean cancel(boolean mayInterruptIfRunning) {
53+ return (source == null || source.cancel(mayInterruptIfRunning))
54+ && super.cancel(mayInterruptIfRunning);
55+ }
56+
57+ @Override
58+ public ResultSet getUninterruptibly() {
59+ try {
60+ return Uninterruptibles.getUninterruptibly(this);
61+ } catch (ExecutionException e) {
62+ throw DriverThrowables.propagateCause(e);
63+ }
64+ }
65+
66+ @Override
67+ public ResultSet getUninterruptibly(long timeout, TimeUnit unit) throws TimeoutException {
68+ try {
69+ return Uninterruptibles.getUninterruptibly(this, timeout, unit);
70+ } catch (ExecutionException e) {
71+ throw DriverThrowables.propagateCause(e);
72+ }
73+ }
74+}
75+
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +529 −149
@@ -27,6 +27,7 @@
2727
2828 import com.google.common.annotations.VisibleForTesting;
2929 import com.google.common.base.Predicates;
30+import com.google.common.base.Strings;
3031 import com.google.common.collect.*;
3132 import com.google.common.util.concurrent.*;
3233 import org.slf4j.Logger;
@@ -36,6 +37,7 @@
3637 import com.datastax.driver.core.exceptions.DriverInternalError;
3738 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3839 import com.datastax.driver.core.policies.*;
40+import com.datastax.driver.core.utils.MoreFutures;
3941
4042 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
4143
@@ -220,7 +222,7 @@
220222 */
221223 public Session newSession() {
222224 checkNotClosed(manager);
223- return manager.newSession();
225+ return manager.newSession(null);
224226 }
225227
226228 /**
@@ -244,11 +246,11 @@
244246 * Cluster.
245247 */
246248 public Session connect() {
247- checkNotClosed(manager);
248- init();
249- Session session = manager.newSession();
250- session.init();
251- return session;
249+ try {
250+ return Uninterruptibles.getUninterruptibly(connectAsync());
251+ } catch (ExecutionException e) {
252+ throw DriverThrowables.propagateCause(e);
253+ }
252254 }
253255
254256 /**
@@ -277,25 +279,67 @@
277279 * Cluster.
278280 */
279281 public Session connect(String keyspace) {
280- long timeout = getConfiguration().getSocketOptions().getConnectTimeoutMillis();
281- Session session = connect();
282282 try {
283- try {
284- ResultSetFuture future = session.executeAsync("USE " + keyspace);
285- // Note: using the connection timeout isn't perfectly correct, we should probably change that someday
286- Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
287- return session;
288- } catch (TimeoutException e) {
289- throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
290- } catch (ExecutionException e) {
291- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
292- }
293- } catch (RuntimeException e) {
294- session.close();
295- throw e;
283+ return Uninterruptibles.getUninterruptibly(connectAsync(keyspace));
284+ } catch (ExecutionException e) {
285+ throw DriverThrowables.propagateCause(e);
296286 }
297287 }
298288
289+ /**
290+ * Creates a new session on this cluster and initializes it asynchronously.
291+ *
292+ * This will also initialize the {@code Cluster} if needed; note that cluster
293+ * initialization happens synchronously on the thread that called this method.
294+ * Therefore it is recommended to initialize the cluster at application
295+ * startup, and not rely on this method to do it.
296+ *
297+ * @return a future that will complete when the session is fully initialized.
298+ *
299+ * @throws NoHostAvailableException if the Cluster has not been initialized
300+ * yet ({@link #init} has not been called and this is the first connect call)
301+ * and no host amongst the contact points can be reached.
302+ *
303+ * @throws IllegalStateException if the Cluster was closed prior to calling
304+ * this method. This can occur either directly (through {@link #close()} or
305+ * {@link #closeAsync()}), or as a result of an error while initializing the
306+ * Cluster.
307+ *
308+ * @see #connect()
309+ */
310+ public ListenableFuture<Session> connectAsync() {
311+ return connectAsync(null);
312+ }
313+
314+ /**
315+ * Creates a new session on this cluster, and initializes it to the given
316+ * keyspace asynchronously.
317+ *
318+ * This will also initialize the {@code Cluster} if needed; note that cluster
319+ * initialization happens synchronously on the thread that called this method.
320+ * Therefore it is recommended to initialize the cluster at application
321+ * startup, and not rely on this method to do it.
322+ *
323+ * @param keyspace The name of the keyspace to use for the created
324+ * {@code Session}.
325+ * @return a future that will complete when the session is fully initialized.
326+ *
327+ * @throws NoHostAvailableException if the Cluster has not been initialized
328+ * yet ({@link #init} has not been called and this is the first connect call)
329+ * and no host amongst the contact points can be reached.
330+ *
331+ * @throws IllegalStateException if the Cluster was closed prior to calling
332+ * this method. This can occur either directly (through {@link #close()} or
333+ * {@link #closeAsync()}), or as a result of an error while initializing the
334+ * Cluster.
335+ */
336+ public ListenableFuture<Session> connectAsync(String keyspace) {
337+ checkNotClosed(manager);
338+ init();
339+ AsyncInitSession session = manager.newSession(keyspace);
340+ return session.initAsync();
341+ }
342+
299343 /**
300344 * The name of this cluster object.
301345 * <p>
@@ -440,6 +484,38 @@
440484 return this;
441485 }
442486
487+ /**
488+ * Registers the provided listener to be updated with schema change events.
489+ * <p>
490+ * Registering the same listener multiple times is a no-op.
491+ *
492+ * @param listener the new {@link SchemaChangeListener} to register.
493+ * @return this {@code Cluster} object;
494+ */
495+ public Cluster register(SchemaChangeListener listener) {
496+ checkNotClosed(manager);
497+ listener.onRegister(this);
498+ manager.schemaChangeListeners.add(listener);
499+ return this;
500+ }
501+
502+ /**
503+ * Unregisters the provided schema change listener from being updated
504+ * with schema change events.
505+ * <p>
506+ * This method is a no-op if {@code listener} hadn't previously be
507+ * registered against this Cluster.
508+ *
509+ * @param listener the {@link SchemaChangeListener} to unregister.
510+ * @return this {@code Cluster} object;
511+ */
512+ public Cluster unregister(SchemaChangeListener listener) {
513+ checkNotClosed(manager);
514+ listener.onUnregister(this);
515+ manager.schemaChangeListeners.remove(listener);
516+ return this;
517+ }
518+
443519 /**
444520 * Initiates a shutdown of this cluster instance.
445521 * <p>
@@ -472,7 +548,7 @@
472548 try {
473549 closeAsync().get();
474550 } catch (ExecutionException e) {
475- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
551+ throw DriverThrowables.propagateCause(e);
476552 } catch (InterruptedException e) {
477553 Thread.currentThread().interrupt();
478554 }
@@ -1185,7 +1261,7 @@
11851261 Connection.Factory connectionFactory;
11861262 ControlConnection controlConnection;
11871263
1188- final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.Simple.Factory();
1264+ final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.DefaultConvictionPolicy.Factory();
11891265
11901266 ScheduledThreadPoolExecutor reconnectionExecutor;
11911267 ScheduledThreadPoolExecutor scheduledTasksExecutor;
@@ -1214,6 +1290,11 @@
12141290
12151291 final Set<Host.StateListener> listeners;
12161292 final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>();
1293+ final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>();
1294+
1295+ EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer;
1296+ EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer;
1297+ EventDebouncer<SchemaRefreshRequest> schemaRefreshRequestDebouncer;
12171298
12181299 private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) {
12191300 this.clusterName = clusterName == null ? generateClusterName() : clusterName;
@@ -1250,8 +1331,28 @@
12501331 this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this);
12511332 this.preparedQueries = new MapMaker().weakValues().makeMap();
12521333
1253- this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
1334+ // create debouncers - at this stage, they are not running yet
1335+ QueryOptions queryOptions = configuration.getQueryOptions();
1336+ this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>(
1337+ "Node list refresh",
1338+ scheduledTasksExecutor,
1339+ new NodeListRefreshRequestDeliveryCallback(),
1340+ queryOptions.getRefreshNodeListIntervalMillis(),
1341+ queryOptions.getMaxPendingRefreshNodeListRequests());
1342+ this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>(
1343+ "Node refresh",
1344+ scheduledTasksExecutor,
1345+ new NodeRefreshRequestDeliveryCallback(),
1346+ queryOptions.getRefreshNodeIntervalMillis(),
1347+ queryOptions.getMaxPendingRefreshNodeRequests());
1348+ this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>(
1349+ "Schema refresh",
1350+ scheduledTasksExecutor,
1351+ new SchemaRefreshRequestDeliveryCallback(),
1352+ queryOptions.getRefreshSchemaIntervalMillis(),
1353+ queryOptions.getMaxPendingRefreshSchemaRequests());
12541354
1355+ this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS);
12551356
12561357 for (InetSocketAddress address : contactPoints) {
12571358 // We don't want to signal -- call onAdd() -- because nothing is ready
@@ -1259,10 +1360,12 @@
12591360 // create the Host object so we can initialize the control connection.
12601361 metadata.add(address);
12611362 }
1262-
1363+
1364+ Collection<Host> allHosts = metadata.allHosts();
1365+
12631366 // At this stage, metadata.allHosts() only contains the contact points, that's what we want to pass to LBP.init().
12641367 // But the control connection will initialize first and discover more hosts, so make a copy.
1265- Set<Host> contactPointHosts = Sets.newHashSet(metadata.allHosts());
1368+ Set<Host> contactPointHosts = Sets.newHashSet(allHosts);
12661369
12671370 try {
12681371 try {
@@ -1278,11 +1381,17 @@
12781381 }
12791382 }
12801383
1281- // The control connection can mark hosts down if it failed to connect to them, separate them
1384+ // The control connection can mark hosts down if it failed to connect to them, or remove them if they weren't found
1385+ // in the control host's system.peers. Separate them:
12821386 Set<Host> downContactPointHosts = Sets.newHashSet();
1283- for (Host host : contactPointHosts)
1284- if (host.state == Host.State.DOWN)
1387+ Set<Host> removedContactPointHosts = Sets.newHashSet();
1388+ for (Host host : contactPointHosts) {
1389+ if (!allHosts.contains(host))
1390+ removedContactPointHosts.add(host);
1391+ else if (host.state == Host.State.DOWN)
12851392 downContactPointHosts.add(host);
1393+ }
1394+ contactPointHosts.removeAll(removedContactPointHosts);
12861395 contactPointHosts.removeAll(downContactPointHosts);
12871396
12881397 // Now that the control connection is ready, we have all the information we need about the nodes (datacenter,
@@ -1298,6 +1407,12 @@
12981407 for (Host.StateListener listener : listeners)
12991408 listener.onRegister(Cluster.this);
13001409
1410+ for (Host host : removedContactPointHosts) {
1411+ loadBalancingPolicy().onRemove(host);
1412+ for (Host.StateListener listener : listeners)
1413+ listener.onRemove(host);
1414+ }
1415+
13011416 for (Host host : downContactPointHosts) {
13021417 loadBalancingPolicy().onDown(host);
13031418 for (Host.StateListener listener : listeners)
@@ -1306,7 +1421,7 @@
13061421
13071422 configuration.getPoolingOptions().setProtocolVersion(protocolVersion());
13081423
1309- for (Host host : metadata.allHosts()) {
1424+ for (Host host : allHosts) {
13101425 // If the host is down at this stage, it's a contact point that the control connection failed to reach.
13111426 // Reconnection attempts are already scheduled, and the LBP and listeners have been notified above.
13121427 if (host.state == Host.State.DOWN) continue;
@@ -1329,6 +1444,12 @@
13291444 for (Host.StateListener listener : listeners)
13301445 listener.onAdd(host);
13311446 }
1447+
1448+ // start debouncers
1449+ this.nodeListRefreshRequestDebouncer.start();
1450+ this.schemaRefreshRequestDebouncer.start();
1451+ this.nodeRefreshRequestDebouncer.start();
1452+
13321453 isFullyInit = true;
13331454 } catch (NoHostAvailableException e) {
13341455 close();
@@ -1378,8 +1499,8 @@
13781499 return translated == null ? sa : translated;
13791500 }
13801501
1381- private Session newSession() {
1382- SessionManager session = new SessionManager(Cluster.this);
1502+ private AsyncInitSession newSession(String keyspace) {
1503+ SessionManager session = new SessionManager(Cluster.this, keyspace);
13831504 sessions.add(session);
13841505 return session;
13851506 }
@@ -1407,6 +1528,11 @@
14071528 if (isInit) {
14081529 logger.debug("Shutting down");
14091530
1531+ // stop debouncers
1532+ nodeListRefreshRequestDebouncer.stop();
1533+ nodeRefreshRequestDebouncer.stop();
1534+ schemaRefreshRequestDebouncer.stop();
1535+
14101536 // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications
14111537 // delivery or blocking tasks so we use shutdownNow
14121538 shutdownNow(reconnectionExecutor);
@@ -1429,6 +1555,8 @@
14291555 tracker.onUnregister(Cluster.this);
14301556 for (Host.StateListener listener : listeners)
14311557 listener.onUnregister(Cluster.this);
1558+ for (SchemaChangeListener listener : schemaChangeListeners)
1559+ listener.onUnregister(Cluster.this);
14321560
14331561 // Then we shutdown all connections
14341562 List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
@@ -1479,8 +1607,6 @@
14791607
14801608 // Use triggerOnUp unless you're sure you want to run this on the current thread.
14811609 private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException {
1482- logger.debug("Host {} is UP", host);
1483-
14841610 if (isClosed())
14851611 return;
14861612
@@ -1502,6 +1628,8 @@
15021628 if (host.state == Host.State.UP)
15031629 return;
15041630
1631+ Host.statesLogger.debug("[{}] marking host UP", host);
1632+
15051633 // If there is a reconnection attempt scheduled for that node, cancel it
15061634 Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null);
15071635 if (scheduledAttempt != null) {
@@ -1510,7 +1638,8 @@
15101638 }
15111639
15121640 try {
1513- reusedConnection = prepareAllQueries(host, reusedConnection);
1641+ if (getCluster().getConfiguration().getQueryOptions().isReprepareOnUp())
1642+ reusedConnection = prepareAllQueries(host, reusedConnection);
15141643 } catch (InterruptedException e) {
15151644 Thread.currentThread().interrupt();
15161645 // Don't propagate because we don't want to prevent other listener to run
@@ -1566,14 +1695,14 @@
15661695 // Now, check if there isn't pools to create/remove following the addition.
15671696 // We do that now only so that it's not called before we've set the node up.
15681697 for (SessionManager s : sessions)
1569- s.updateCreatedPools();
1698+ s.updateCreatedPools().get();
15701699
15711700 } finally {
15721701 host.notificationsLock.unlock();
15731702 }
15741703
15751704 } finally {
1576- if (reusedConnection != null && !reusedConnection.hasPool())
1705+ if (reusedConnection != null && !reusedConnection.hasOwner())
15771706 reusedConnection.closeAsync();
15781707 }
15791708 }
@@ -1593,8 +1722,6 @@
15931722
15941723 // Use triggerOnDown unless you're sure you want to run this on the current thread.
15951724 private void onDown(final Host host, final boolean isHostAddition, boolean startReconnection) throws InterruptedException, ExecutionException {
1596- logger.debug("Host {} is DOWN", host);
1597-
15981725 if (isClosed())
15991726 return;
16001727
@@ -1615,6 +1742,8 @@
16151742 return;
16161743 }
16171744
1745+ Host.statesLogger.debug("[{}] marking host DOWN", host);
1746+
16181747 // Remember if we care about this node at all. We must call this before
16191748 // we've signalled the load balancing policy, since most policy will always
16201749 // IGNORE down nodes anyway.
@@ -1640,7 +1769,6 @@
16401769 if (distance == HostDistance.IGNORED || !startReconnection)
16411770 return;
16421771
1643- logger.debug("{} is down, scheduling connection retries", host);
16441772 startPeriodicReconnectionAttempt(host, isHostAddition);
16451773 } finally {
16461774 host.notificationsLock.unlock();
@@ -1648,7 +1776,7 @@
16481776 }
16491777
16501778 void startPeriodicReconnectionAttempt(final Host host, final boolean isHostAddition) {
1651- new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) {
1779+ new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) {
16521780
16531781 protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
16541782 return connectionFactory.open(host);
@@ -1701,7 +1829,7 @@
17011829 logger.debug("Scheduling one-time reconnection to {}", host);
17021830
17031831 // Setting an initial delay of 0 to start immediately, and all the exception handlers return false to prevent further attempts
1704- new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) {
1832+ new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) {
17051833
17061834 protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
17071835 return connectionFactory.open(host);
@@ -1757,8 +1885,6 @@
17571885 if (isClosed())
17581886 return;
17591887
1760- logger.info("New Cassandra host {} added", host);
1761-
17621888 if (!connectionFactory.protocolVersion.isSupportedBy(host)) {
17631889 logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion);
17641890 return;
@@ -1772,6 +1898,7 @@
17721898 return;
17731899 }
17741900 try {
1901+ Host.statesLogger.debug("[{}] adding host", host);
17751902
17761903 // Adds to the load balancing first and foremost, as doing so might change the decision
17771904 // it will make for distance() on that node (not likely but we leave that possibility).
@@ -1807,7 +1934,7 @@
18071934
18081935 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size());
18091936 for (SessionManager s : sessions)
1810- futures.add(s.maybeAddPool(host, reusedConnection));
1937+ futures.add(s.maybeAddPool(host, reusedConnection, false));
18111938
18121939 try {
18131940 // Only mark the node up once all session have added their pool (if the load-balancing
@@ -1837,14 +1964,14 @@
18371964 // Now, check if there isn't pools to create/remove following the addition.
18381965 // We do that now only so that it's not called before we've set the node up.
18391966 for (SessionManager s : sessions)
1840- s.updateCreatedPools();
1967+ s.updateCreatedPools().get();
18411968
18421969 } finally {
18431970 host.notificationsLock.unlock();
18441971 }
18451972
18461973 } finally {
1847- if (reusedConnection != null && !reusedConnection.hasPool())
1974+ if (reusedConnection != null && !reusedConnection.hasOwner())
18481975 reusedConnection.closeAsync();
18491976 }
18501977 }
@@ -1872,7 +1999,8 @@
18721999
18732000 host.setDown();
18742001
1875- logger.debug("Removing host {}", host);
2002+ Host.statesLogger.debug("[{}] removing host", host);
2003+
18762004 loadBalancingPolicy().onRemove(host);
18772005 controlConnection.onRemove(host);
18782006 for (SessionManager s : sessions)
@@ -1885,13 +2013,14 @@
18852013 }
18862014 }
18872015
1888- public boolean signalConnectionFailure(Host host, ConnectionException exception, boolean isHostAddition) {
2016+ public boolean signalConnectionFailure(Host host, ConnectionException exception,
2017+ boolean connectionInitialized, boolean isHostAddition) {
18892018 // Don't signal failure until we've fully initialized the controlConnection as this might mess up with
18902019 // the protocol detection
18912020 if (!isFullyInit || isClosed())
18922021 return true;
18932022
1894- boolean isDown = host.signalConnectionFailure(exception);
2023+ boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized);
18952024 if (isDown)
18962025 triggerOnDown(host, isHostAddition, true);
18972026 return isDown;
@@ -1903,7 +2032,7 @@
19032032
19042033 if (metadata.remove(host)) {
19052034 if (isInitialConnection) {
1906- logger.warn("You listed {} in your contact points, but it could not be reached at startup", host);
2035+ logger.warn("You listed {} in your contact points, but it wasn't found in the control host's system.peers at startup", host);
19072036 } else {
19082037 logger.info("Cassandra host {} removed", host);
19092038 triggerOnRemove(host);
@@ -1952,7 +2081,7 @@
19522081 : reusedConnection;
19532082
19542083 try {
1955- ControlConnection.waitForSchemaAgreement(connection, this);
2084+ controlConnection.waitForSchemaAgreement();
19562085 } catch (ExecutionException e) {
19572086 // As below, just move on
19582087 }
@@ -2016,14 +2145,21 @@
20162145 }
20172146 }
20182147
2019- public void submitSchemaRefresh(final SchemaElement targetType, final String targetKeyspace, final String targetName, final List<String> targetSignature) {
2020- logger.trace("Submitting schema refresh");
2021- executor.submit(new ExceptionCatchingRunnable() {
2022- @Override
2023- public void runMayThrow() throws InterruptedException, ExecutionException {
2024- controlConnection.refreshSchema(targetType, targetKeyspace, targetName, targetSignature);
2025- }
2026- });
2148+ ListenableFuture<Void> submitSchemaRefresh(final SchemaElement targetType, final String targetKeyspace, final String targetName, final List<String> targetSignature) {
2149+ SchemaRefreshRequest request = new SchemaRefreshRequest(targetType, targetKeyspace, targetName, targetSignature);
2150+ logger.trace("Submitting schema refresh: {}", request);
2151+ return schemaRefreshRequestDebouncer.eventReceived(request);
2152+ }
2153+
2154+ void submitNodeListRefresh() {
2155+ logger.trace("Submitting node list and token map refresh");
2156+ nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest());
2157+ }
2158+
2159+ void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) {
2160+ NodeRefreshRequest request = new NodeRefreshRequest(address, eventType);
2161+ logger.trace("Submitting node refresh: {}", request);
2162+ nodeRefreshRequestDebouncer.eventReceived(request);
20272163 }
20282164
20292165 // refresh the schema using the provided connection, and notice the future with the provided resultset once done
@@ -2050,20 +2186,23 @@
20502186 try {
20512187 // Before refreshing the schema, wait for schema agreement so
20522188 // that querying a table just after having created it don't fail.
2053- schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this);
2189+ schemaInAgreement = controlConnection.waitForSchemaAgreement();
20542190 if (!schemaInAgreement)
20552191 logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds());
2056- if (refreshSchema)
2057- ControlConnection.refreshSchema(connection, targetType, targetKeyspace, targetName, targetSignature, Manager.this, false);
2192+
2193+ ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(targetType, targetKeyspace, targetName, targetSignature) : MoreFutures.VOID_SUCCESS;
2194+ final boolean finalSchemaInAgreement = schemaInAgreement;
2195+ schemaReady.addListener(new Runnable() {
2196+ @Override
2197+ public void run() {
2198+ rs.getExecutionInfo().setSchemaInAgreement(finalSchemaInAgreement);
2199+ future.setResult(rs);
2200+ }
2201+ }, MoreExecutors.sameThreadExecutor());
2202+
20582203 } catch (Exception e) {
2059- if (refreshSchema) {
2060- logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage());
2061- submitSchemaRefresh(targetType, targetKeyspace, targetName, targetSignature);
2062- } else {
2063- logger.warn("Error while waiting for schema agreement", e);
2064- }
2065- } finally {
2066- // Always sets the result, but remember if we reached schema agreement
2204+ logger.warn("Error while waiting for schema agreement", e);
2205+ // This is not fatal, complete the future anyway
20672206 rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement);
20682207 future.setResult(rs);
20692208 }
@@ -2089,95 +2228,36 @@
20892228 case TOPOLOGY_CHANGE:
20902229 ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange)event;
20912230 InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress());
2231+ Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change);
20922232 switch (tpc.change) {
20932233 case NEW_NODE:
2094- final Host newHost = metadata.add(tpAddr);
2095- if (newHost != null) {
2096- // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once
2097- // gossip is up, but that is before the client-side server is up), so we add a delay
2098- // (otherwise the connection will likely fail and have to be retry which is wasteful). This
2099- // probably should be fixed C* side, after which we'll be able to remove this.
2100- scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() {
2101- @Override
2102- public void runMayThrow() throws InterruptedException, ExecutionException {
2103- // Make sure we have up-to-date infos on that host before adding it (so we typically
2104- // catch that an upgraded node uses a new cassandra version).
2105- if (controlConnection.refreshNodeInfo(newHost)) {
2106- onAdd(newHost, null);
2107- } else {
2108- logger.debug("Not enough info for {}, ignoring host", newHost);
2109- }
2110- }
2111- }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
2112- }
2234+ submitNodeRefresh(tpAddr, HostEvent.ADDED);
21132235 break;
21142236 case REMOVED_NODE:
2115- removeHost(metadata.getHost(tpAddr), false);
2237+ submitNodeRefresh(tpAddr, HostEvent.REMOVED);
21162238 break;
21172239 case MOVED_NODE:
2118- executor.submit(new ExceptionCatchingRunnable() {
2119- @Override
2120- public void runMayThrow() {
2121- controlConnection.refreshNodeListAndTokenMap();
2122- }
2123- });
2240+ submitNodeListRefresh();
21242241 break;
21252242 }
21262243 break;
21272244 case STATUS_CHANGE:
21282245 ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange)event;
21292246 InetSocketAddress stAddr = translateAddress(stc.node.getAddress());
2247+ Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status);
21302248 switch (stc.status) {
21312249 case UP:
2132- final Host hostUp = metadata.getHost(stAddr);
2133- if (hostUp == null) {
2134- final Host h = metadata.add(stAddr);
2135- // If hostUp is still null, it means we didn't knew about it the line before but
2136- // got beaten at adding it to the metadata by another thread. In that case, it's
2137- // fine to let the other thread win and ignore the notification here
2138- if (h == null)
2139- return;
2140-
2141- // See NEW_NODE above
2142- scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() {
2143- @Override
2144- public void runMayThrow() throws InterruptedException, ExecutionException {
2145- // Make sure we have up-to-date infos on that host before adding it (so we typically
2146- // catch that an upgraded node uses a new cassandra version).
2147- if (controlConnection.refreshNodeInfo(h)) {
2148- onAdd(h, null);
2149- } else {
2150- logger.debug("Not enough info for {}, ignoring host", h);
2151- }
2152- }
2153- }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
2154- } else {
2155- executor.submit(new ExceptionCatchingRunnable() {
2156- @Override
2157- public void runMayThrow() throws InterruptedException, ExecutionException {
2158- // Make sure we have up-to-date infos on that host before adding it (so we typically
2159- // catch that an upgraded node uses a new cassandra version).
2160- if (controlConnection.refreshNodeInfo(hostUp)) {
2161- onUp(hostUp, null);
2162- } else {
2163- logger.debug("Not enough info for {}, ignoring host", hostUp);
2164- }
2165- }
2166- });
2167- }
2250+ submitNodeRefresh(stAddr, HostEvent.UP);
21682251 break;
21692252 case DOWN:
2170- // Note that there is a slight risk we can receive the event late and thus
2171- // mark the host down even though we already had reconnected successfully.
2172- // But it is unlikely, and don't have too much consequence since we'll try reconnecting
2173- // right away, so we favor the detection to make the Host.isUp method more reliable.
2174- Host hostDown = metadata.getHost(stAddr);
2175- if (hostDown != null)
2176- triggerOnDown(hostDown, true);
2253+ submitNodeRefresh(stAddr, HostEvent.DOWN);
21772254 break;
21782255 }
21792256 break;
21802257 case SCHEMA_CHANGE:
2258+ if (!configuration.getQueryOptions().isMetadataEnabled())
2259+ return;
2260+
21812261 ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event;
21822262 switch (scc.change) {
21832263 case CREATED:
@@ -2186,7 +2266,15 @@
21862266 break;
21872267 case DROPPED:
21882268 if (scc.targetType == KEYSPACE) {
2189- manager.metadata.removeKeyspace(scc.targetKeyspace);
2269+ final KeyspaceMetadata removedKeyspace = manager.metadata.removeKeyspace(scc.targetKeyspace);
2270+ if (removedKeyspace != null) {
2271+ executor.submit(new Runnable() {
2272+ @Override
2273+ public void run() {
2274+ manager.metadata.triggerOnKeyspaceRemoved(removedKeyspace);
2275+ }
2276+ });
2277+ }
21902278 } else {
21912279 KeyspaceMetadata keyspace = manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
21922280 if (keyspace == null) {
@@ -2195,16 +2283,48 @@
21952283 } else {
21962284 switch (scc.targetType) {
21972285 case TABLE:
2198- keyspace.removeTable(scc.targetName);
2286+ final TableMetadata removedTable = keyspace.removeTable(scc.targetName);
2287+ if (removedTable != null) {
2288+ executor.submit(new Runnable() {
2289+ @Override
2290+ public void run() {
2291+ manager.metadata.triggerOnTableRemoved(removedTable);
2292+ }
2293+ });
2294+ }
21992295 break;
22002296 case TYPE:
2201- keyspace.removeUserType(scc.targetName);
2297+ final UserType removedType = keyspace.removeUserType(scc.targetName);
2298+ if (removedType != null) {
2299+ executor.submit(new Runnable() {
2300+ @Override
2301+ public void run() {
2302+ manager.metadata.triggerOnUserTypeRemoved(removedType);
2303+ }
2304+ });
2305+ }
22022306 break;
22032307 case FUNCTION:
2204- keyspace.removeFunction(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
2308+ final FunctionMetadata removedFunction = keyspace.removeFunction(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
2309+ if (removedFunction != null) {
2310+ executor.submit(new Runnable() {
2311+ @Override
2312+ public void run() {
2313+ manager.metadata.triggerOnFunctionRemoved(removedFunction);
2314+ }
2315+ });
2316+ }
22052317 break;
22062318 case AGGREGATE:
2207- keyspace.removeAggregate(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
2319+ final AggregateMetadata removedAggregate = keyspace.removeAggregate(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
2320+ if (removedAggregate != null) {
2321+ executor.submit(new Runnable() {
2322+ @Override
2323+ public void run() {
2324+ manager.metadata.triggerOnAggregateRemoved(removedAggregate);
2325+ }
2326+ });
2327+ }
22082328 break;
22092329 }
22102330 }
@@ -2220,17 +2340,21 @@
22202340 // reconnecting (thus letting the loadBalancingPolicy pick a better node)
22212341 Host ccHost = controlConnection.connectedHost();
22222342 if (ccHost == null || loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL)
2223- controlConnection.reconnect();
2343+ controlConnection.triggerReconnect();
22242344
2225- for (SessionManager s : sessions)
2226- s.updateCreatedPools();
2345+ try {
2346+ for (SessionManager s : sessions)
2347+ Uninterruptibles.getUninterruptibly(s.updateCreatedPools());
2348+ } catch (ExecutionException e) {
2349+ throw DriverThrowables.propagateCause(e);
2350+ }
22272351 }
22282352
22292353 void refreshConnectedHost(Host host) {
22302354 // Deal with the control connection if it was using this host
22312355 Host ccHost = controlConnection.connectedHost();
22322356 if (ccHost == null || ccHost.equals(host) && loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL)
2233- controlConnection.reconnect();
2357+ controlConnection.triggerReconnect();
22342358
22352359 for (SessionManager s : sessions)
22362360 s.updateCreatedPools(host);
@@ -2298,6 +2422,262 @@
22982422 }
22992423 }
23002424 }
2425+
2426+ private class SchemaRefreshRequest {
2427+
2428+ private final SchemaElement targetType;
2429+ private final String targetKeyspace;
2430+ private final String targetName;
2431+ private final List<String> targetSignature;
2432+
2433+ public SchemaRefreshRequest(SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature) {
2434+ this.targetType = targetType;
2435+ this.targetKeyspace = Strings.emptyToNull(targetKeyspace);
2436+ this.targetName = Strings.emptyToNull(targetName);
2437+ this.targetSignature = targetSignature;
2438+ }
2439+
2440+ /**
2441+ * Coalesce schema refresh requests.
2442+ * The algorithm is simple: if more than 2 keyspaces
2443+ * need refresh, then refresh the entire schema;
2444+ * otherwise if more than 2 elements in the same keyspace
2445+ * need refresh, then refresh the entire keyspace.
2446+ *
2447+ * @param that the other request to merge with the current one.
2448+ * @return A coalesced request
2449+ */
2450+ SchemaRefreshRequest coalesce(SchemaRefreshRequest that) {
2451+ if (this.targetType == null || that.targetType == null)
2452+ return new SchemaRefreshRequest(null, null, null, null);
2453+ if (!this.targetKeyspace.equals(that.targetKeyspace))
2454+ return new SchemaRefreshRequest(null, null, null, null);
2455+ if (this.targetName == null || that.targetName == null)
2456+ return new SchemaRefreshRequest(KEYSPACE, targetKeyspace, null, null);
2457+ if (!this.targetName.equals(that.targetName))
2458+ return new SchemaRefreshRequest(KEYSPACE, targetKeyspace, null, null);
2459+ return this;
2460+ }
2461+
2462+ @Override
2463+ public String toString() {
2464+ if (this.targetType == null)
2465+ return "Refresh ALL";
2466+ if (this.targetName == null)
2467+ return "Refresh keyspace " + targetKeyspace;
2468+ return String.format("Refresh %s %s.%s", targetType, targetKeyspace, targetName);
2469+ }
2470+ }
2471+
2472+ private class SchemaRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<SchemaRefreshRequest> {
2473+
2474+ @Override
2475+ public ListenableFuture<?> deliver(final List<SchemaRefreshRequest> events) {
2476+ return executor.submit(new ExceptionCatchingRunnable() {
2477+ @Override
2478+ public void runMayThrow() throws InterruptedException, ExecutionException {
2479+ SchemaRefreshRequest coalesced = null;
2480+ for (SchemaRefreshRequest request : events) {
2481+ coalesced = coalesced == null ? request : coalesced.coalesce(request);
2482+ }
2483+ assert coalesced != null;
2484+ logger.trace("Coalesced schema refresh request: {}", coalesced);
2485+ controlConnection.refreshSchema(coalesced.targetType, coalesced.targetKeyspace, coalesced.targetName, coalesced.targetSignature);
2486+ }
2487+ });
2488+ }
2489+
2490+ }
2491+
2492+ private class NodeRefreshRequest {
2493+
2494+ private final InetSocketAddress address;
2495+
2496+ private final HostEvent eventType;
2497+
2498+ private NodeRefreshRequest(InetSocketAddress address, HostEvent eventType) {
2499+ this.address = address;
2500+ this.eventType = eventType;
2501+ }
2502+
2503+ @Override
2504+ public String toString() {
2505+ return address + " " + eventType;
2506+ }
2507+
2508+ }
2509+
2510+ private class NodeRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeRefreshRequest> {
2511+
2512+ @Override
2513+ public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) {
2514+ Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>();
2515+ // only keep the last event for each host
2516+ for (NodeRefreshRequest req : events) {
2517+ hosts.put(req.address, req.eventType);
2518+ }
2519+ List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size());
2520+ for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) {
2521+ InetSocketAddress address = entry.getKey();
2522+ HostEvent eventType = entry.getValue();
2523+ switch (eventType) {
2524+ case UP:
2525+ Host upHost = metadata.getHost(address);
2526+ if (upHost == null) {
2527+ upHost = metadata.add(address);
2528+ // If upHost is still null, it means we didn't know about it the line before but
2529+ // got beaten at adding it to the metadata by another thread. In that case, it's
2530+ // fine to let the other thread win and ignore the notification here
2531+ if (upHost == null)
2532+ continue;
2533+ futures.add(schedule(hostAdded(upHost)));
2534+ } else {
2535+ futures.add(schedule(hostUp(upHost)));
2536+ }
2537+ break;
2538+ case ADDED:
2539+ Host newHost = metadata.add(address);
2540+ if (newHost != null) {
2541+ futures.add(schedule(hostAdded(newHost)));
2542+ } else {
2543+ // If host already existed, retrieve it and check its state, if it's not up schedule a
2544+ // hostUp event.
2545+ Host existingHost = metadata.getHost(address);
2546+ if(!existingHost.isUp())
2547+ futures.add(schedule(hostUp(existingHost)));
2548+ }
2549+ break;
2550+ case DOWN:
2551+ // Note that there is a slight risk we can receive the event late and thus
2552+ // mark the host down even though we already had reconnected successfully.
2553+ // But it is unlikely, and don't have too much consequence since we'll try reconnecting
2554+ // right away, so we favor the detection to make the Host.isUp method more reliable.
2555+ Host downHost = metadata.getHost(address);
2556+ if (downHost != null)
2557+ futures.add(execute(hostDown(downHost)));
2558+ break;
2559+ case REMOVED:
2560+ Host removedHost = metadata.getHost(address);
2561+ if (removedHost != null)
2562+ futures.add(execute(hostRemoved(removedHost)));
2563+ break;
2564+ }
2565+ }
2566+ return Futures.allAsList(futures);
2567+ }
2568+
2569+ private ListenableFuture<?> execute(ExceptionCatchingRunnable task) {
2570+ return executor.submit(task);
2571+ }
2572+
2573+ private ListenableFuture<?> schedule(final ExceptionCatchingRunnable task) {
2574+ // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once
2575+ // gossip is up, but that is before the client-side server is up), so we add a delay
2576+ // (otherwise the connection will likely fail and have to be retry which is wasteful). This
2577+ // probably should be fixed C* side, after which we'll be able to remove this.
2578+ final SettableFuture<?> future = SettableFuture.create();
2579+ scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() {
2580+ public void runMayThrow() throws Exception {
2581+ ListenableFuture<?> f = execute(task);
2582+ Futures.addCallback(f, new FutureCallback<Object>() {
2583+ @Override
2584+ public void onSuccess(Object result) {
2585+ future.set(null);
2586+ }
2587+
2588+ @Override
2589+ public void onFailure(Throwable t) {
2590+ future.setException(t);
2591+ }
2592+ });
2593+ }
2594+ }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
2595+ return future;
2596+ }
2597+
2598+ // Make sure we call controlConnection.refreshNodeInfo(host)
2599+ // so that we have up-to-date infos on that host before adding it (so we typically
2600+ // catch that an upgraded node uses a new cassandra version).
2601+
2602+ private ExceptionCatchingRunnable hostAdded(final Host host) {
2603+ return new ExceptionCatchingRunnable() {
2604+ @Override
2605+ public void runMayThrow() throws Exception {
2606+ if (controlConnection.refreshNodeInfo(host)) {
2607+ onAdd(host, null);
2608+ } else {
2609+ logger.debug("Not enough info for {}, ignoring host", host);
2610+ }
2611+ }
2612+ };
2613+ }
2614+
2615+ private ExceptionCatchingRunnable hostUp(final Host host) {
2616+ return new ExceptionCatchingRunnable() {
2617+ @Override
2618+ public void runMayThrow() throws Exception {
2619+ if (controlConnection.refreshNodeInfo(host)) {
2620+ onUp(host, null);
2621+ } else {
2622+ logger.debug("Not enough info for {}, ignoring host", host);
2623+ }
2624+ }
2625+ };
2626+ }
2627+
2628+ private ExceptionCatchingRunnable hostDown(final Host host) {
2629+ return new ExceptionCatchingRunnable() {
2630+ @Override
2631+ public void runMayThrow() throws Exception {
2632+ if (controlConnection.refreshNodeInfo(host)) {
2633+ onDown(host, false, true);
2634+ } else {
2635+ logger.debug("Not enough info for {}, ignoring host", host);
2636+ }
2637+ }
2638+ };
2639+ }
2640+
2641+ private ExceptionCatchingRunnable hostRemoved(final Host host) {
2642+ return new ExceptionCatchingRunnable() {
2643+ @Override
2644+ public void runMayThrow() throws Exception {
2645+ if (metadata.remove(host)) {
2646+ logger.info("Cassandra host {} removed", host);
2647+ onRemove(host);
2648+ }
2649+ }
2650+ };
2651+ }
2652+
2653+ }
2654+
2655+ private class NodeListRefreshRequest {
2656+ @Override
2657+ public String toString() {
2658+ return "Refresh node list and token map";
2659+ }
2660+ }
2661+
2662+ private class NodeListRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeListRefreshRequest> {
2663+
2664+ @Override
2665+ public ListenableFuture<?> deliver(List<NodeListRefreshRequest> events) {
2666+ // The number of received requests does not matter
2667+ // as long as one request is made, refresh the entire node list
2668+ return executor.submit(new ExceptionCatchingRunnable() {
2669+ @Override
2670+ public void runMayThrow() throws InterruptedException, ExecutionException {
2671+ controlConnection.refreshNodeListAndTokenMap();
2672+ }
2673+ });
2674+ }
2675+ }
2676+
2677+ }
2678+
2679+ private enum HostEvent {
2680+ UP, DOWN, ADDED, REMOVED
23012681 }
23022682
23032683 /**
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +48 −0
@@ -22,6 +22,8 @@
2222 import java.util.Map;
2323 import java.util.Map.Entry;
2424
25+import com.google.common.base.Objects;
26+
2527 /**
2628 * Describes a Column.
2729 */
@@ -107,6 +109,34 @@
107109 return isStatic;
108110 }
109111
112+ @Override
113+ public boolean equals(Object o) {
114+ if (this == o)
115+ return true;
116+ if (o == null || getClass() != o.getClass())
117+ return false;
118+
119+ ColumnMetadata that = (ColumnMetadata)o;
120+
121+ if (isStatic != that.isStatic)
122+ return false;
123+ if (!name.equals(that.name))
124+ return false;
125+ if (!type.equals(that.type))
126+ return false;
127+ return !(index != null ? !index.equals(that.index) : that.index != null);
128+
129+ }
130+
131+ @Override
132+ public int hashCode() {
133+ int result = name.hashCode();
134+ result = 31 * result + type.hashCode();
135+ result = 31 * result + (index != null ? index.hashCode() : 0);
136+ result = 31 * result + (isStatic ? 1 : 0);
137+ return result;
138+ }
139+
110140 /**
111141 * Metadata on a column index.
112142 */
@@ -269,6 +299,24 @@
269299 return colName;
270300 }
271301
302+ @Override
303+ public boolean equals(Object o) {
304+ if (this == o)
305+ return true;
306+ if (o == null || getClass() != o.getClass())
307+ return false;
308+
309+ IndexMetadata that = (IndexMetadata)o;
310+
311+ return this.name.equals(that.name)
312+ && Objects.equal(this.indexOptions, that.indexOptions);
313+ }
314+
315+ @Override
316+ public int hashCode() {
317+ return Objects.hashCode(name, indexOptions);
318+ }
319+
272320 private static IndexMetadata build(ColumnMetadata column, Map<String, String> indexColumns) {
273321 if (indexColumns.isEmpty())
274322 return null;
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +107 −83
@@ -19,14 +19,12 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.HashSet;
2121 import java.util.Iterator;
22-import java.util.List;
2322 import java.util.Queue;
2423 import java.util.concurrent.*;
2524 import java.util.concurrent.atomic.AtomicBoolean;
2625 import java.util.concurrent.atomic.AtomicInteger;
2726 import java.util.concurrent.atomic.AtomicReference;
2827
29-import com.google.common.collect.Lists;
3028 import com.google.common.collect.MapMaker;
3129 import com.google.common.util.concurrent.*;
3230 import io.netty.bootstrap.Bootstrap;
@@ -37,8 +35,8 @@
3735 import io.netty.handler.ssl.SslHandler;
3836 import io.netty.handler.timeout.IdleStateEvent;
3937 import io.netty.handler.timeout.IdleStateHandler;
40-import io.netty.util.HashedWheelTimer;
4138 import io.netty.util.Timeout;
39+import io.netty.util.Timer;
4240 import io.netty.util.TimerTask;
4341 import io.netty.util.concurrent.GlobalEventExecutor;
4442 import javax.net.ssl.SSLEngine;
@@ -50,8 +48,12 @@
5048 import com.datastax.driver.core.exceptions.AuthenticationException;
5149 import com.datastax.driver.core.exceptions.DriverException;
5250 import com.datastax.driver.core.exceptions.DriverInternalError;
51+import com.datastax.driver.core.exceptions.InvalidQueryException;
5352 import com.datastax.driver.core.utils.MoreFutures;
5453
54+import static com.datastax.driver.core.Message.Response.Type.ERROR;
55+import static com.datastax.driver.core.Message.Response.Type.RESULT;
56+
5557 // For LoggingHandler
5658 //import org.jboss.netty.handler.logging.LoggingHandler;
5759 //import org.jboss.netty.logging.InternalLogLevel;
@@ -87,11 +89,11 @@
8789 private volatile String keyspace;
8890
8991 private volatile boolean isInitialized;
90- private volatile boolean isDefunct;
92+ private final AtomicBoolean isDefunct = new AtomicBoolean();
9193
9294 private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>();
9395
94- private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>();
96+ private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>();
9597
9698 /**
9799 /**
@@ -100,15 +102,15 @@
100102 * @param name the connection name
101103 * @param address the remote address
102104 * @param factory the connection factory to use
103- * @param pool the pool this connection belongs to. May be null if this connection does not belong to a pool.
104- * Note that an existing connection can also be associated to a pool later with {@link #setPool(HostConnectionPool)}.
105+ * @param owner the component owning this connection (may be null).
106+ * Note that an existing connection can also be associated to an owner later with {@link #setOwner(Owner)}.
105107 */
106- protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) {
108+ protected Connection(String name, InetSocketAddress address, Factory factory, Owner owner) {
107109 this.address = address;
108110 this.factory = factory;
109111 this.dispatcher = new Dispatcher();
110112 this.name = name;
111- this.poolRef.set(pool);
113+ this.ownerRef.set(owner);
112114 }
113115
114116 /**
@@ -178,8 +180,8 @@
178180 public ListenableFuture<Void> create(Throwable t) throws Exception {
179181 SettableFuture<Void> future = SettableFuture.create();
180182 // Make sure the connection gets properly closed.
181- if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException) {
182- // These exceptions cause the node to be ignored, so just propagate
183+ if (t instanceof ClusterNameMismatchException || t instanceof UnsupportedProtocolVersionException || t instanceof SetKeyspaceException) {
184+ // Just propagate
183185 closeAsync().force();
184186 future.setException(t);
185187 } else {
@@ -199,6 +201,9 @@
199201 Futures.addCallback(initFuture, new FutureCallback<Void>() {
200202 @Override
201203 public void onSuccess(Void result) {
204+ Host host = factory.manager.metadata.getHost(address);
205+ if (host != null)
206+ host.convictionPolicy.signalConnectionCreated();
202207 isInitialized = true;
203208 }
204209
@@ -382,7 +387,7 @@
382387 }
383388
384389 public boolean isDefunct() {
385- return isDefunct;
390+ return isDefunct.get();
386391 }
387392
388393 public int maxAvailableStreams() {
@@ -390,9 +395,13 @@
390395 }
391396
392397 <E extends Exception> E defunct(E e) {
393- if (logger.isDebugEnabled())
394- logger.debug("Defuncting connection to " + address, e);
395- isDefunct = true;
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());
396405
397406 ConnectionException ce = e instanceof ConnectionException
398407 ? (ConnectionException)e
@@ -400,10 +409,12 @@
400409
401410 Host host = factory.manager.metadata.getHost(address);
402411 if (host != null) {
403- // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant.
404- // This is not too much of a problem since calling onDown on a node that is already down has no effect.
405- boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded());
406- notifyOwnerWhenDefunct(isDown);
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
407418 }
408419
409420 // Force the connection to close to make sure the future completes. Otherwise force() might never get called and
@@ -414,20 +425,14 @@
414425 return e;
415426 }
416427
417- protected void notifyOwnerWhenDefunct(boolean hostIsDown) {
428+ private void notifyOwnerWhenDefunct() {
418429 // If an error happens during initialization, the owner will detect it and take appropriate action
419430 if (!isInitialized)
420431 return;
421432
422- HostConnectionPool pool = this.poolRef.get();
423- if (pool == null)
424- return;
425-
426- if (hostIsDown) {
427- pool.closeAsync().force();
428- } else {
429- pool.replaceDefunctConnection(this);
430- }
433+ Owner owner = this.ownerRef.get();
434+ if (owner != null)
435+ owner.onConnectionDefunct(this);
431436 }
432437
433438 public String keyspace() {
@@ -441,46 +446,59 @@
441446 if (this.keyspace != null && this.keyspace.equals(keyspace))
442447 return;
443448
444- Future future = null;
445449 try {
446- logger.trace("{} Setting keyspace {}", this, keyspace);
447- long timeout = factory.getConnectTimeoutMillis();
448- // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
449- future = write(new Requests.Query("USE \"" + keyspace + '"'));
450- Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
451- switch (response.type) {
452- case RESULT:
453- this.keyspace = keyspace;
454- break;
455- default:
456- // The code set the keyspace only when a successful 'use'
457- // has been perform, so there shouldn't be any error here.
458- // It can happen however that the node we're connecting to
459- // is not up on the schema yet. In that case, defuncting
460- // the connection is not a bad choice.
461- String message = String.format("Problem while setting keyspace, got %s as response", response);
462- logger.warn("{} {}", this, message);
463- defunct(new ConnectionException(address, message));
464- break;
465- }
450+ Uninterruptibles.getUninterruptibly(setKeyspaceAsync(keyspace));
466451 } catch (ConnectionException e) {
467452 throw defunct(e);
468- } catch (TimeoutException e) {
469- // We've given up waiting on the future, but it's still running. Cancel to make sure that the request timeout logic
470- // (readTimeout) will not kick in, because that would release the connection. This will work since connectTimeout is
471- // generally lower than readTimeout (and if not, we'll get an ExecutionException and defunct below).
472- future.cancel(true);
473- logger.warn(String.format("Timeout while setting keyspace on connection to %s. This should not happen but is not critical (it will retried)", address));
474- // Rethrow so that the caller will not try to use the connection, but do not defunct as we don't want to mark down
475- throw new ConnectionException(address, "Timeout while setting keyspace on connection");
476453 } catch (BusyConnectionException e) {
477- logger.warn(String.format("Tried to set the keyspace on busy connection to %s. This should not happen but is not critical (it will retried)", address));
454+ logger.warn("Tried to set the keyspace on busy connection to {}. "
455+ + "This should not happen but is not critical (it will be retried)", address);
478456 throw new ConnectionException(address, "Tried to set the keyspace on busy connection");
479457 } catch (ExecutionException e) {
480- throw defunct(new ConnectionException(address, "Error while setting keyspace", e));
458+ Throwable cause = e.getCause();
459+ if (cause instanceof OperationTimedOutException) {
460+ // The timeout logic released the connection, but that's wrong since we did not borrow it in the first place.
461+ // JAVA-901 will fix this, in the meantime make sure the inFlight count is not off by one.
462+ inFlight.incrementAndGet();
463+
464+ // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down
465+ logger.warn("Timeout while setting keyspace on connection to {}. "
466+ + "This should not happen but is not critical (it will be retried)", address);
467+ throw new ConnectionException(address, "Timeout while setting keyspace on connection");
468+ } else {
469+ throw defunct(new ConnectionException(address, "Error while setting keyspace", cause));
470+ }
481471 }
482472 }
483473
474+ ListenableFuture<Void> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException {
475+ logger.trace("{} Setting keyspace {}", this, keyspace);
476+ // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already
477+ Future future = write(new Requests.Query("USE \"" + keyspace + '"'));
478+ return Futures.transform(future, new AsyncFunction<Message.Response, Void>() {
479+ @Override
480+ public ListenableFuture<Void> apply(Message.Response response) throws Exception {
481+ if (response.type == RESULT) {
482+ Connection.this.keyspace = keyspace;
483+ return MoreFutures.VOID_SUCCESS;
484+ } else if (response.type == ERROR) {
485+ closeAsync().force();
486+ 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;
494+ } else {
495+ closeAsync().force();
496+ throw new DriverInternalError("Unexpected response while setting keyspace: " + response);
497+ }
498+ }
499+ }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor());
500+ }
501+
484502 /**
485503 * Write a request on this connection.
486504 *
@@ -514,7 +532,7 @@
514532 * having set the handler, we guarantee that even if we race with defunct/close, we may
515533 * never leave a handler that won't get an answer or be errored out.
516534 */
517- if (isDefunct) {
535+ if (isDefunct.get()) {
518536 dispatcher.removeHandler(handler, true);
519537 throw new ConnectionException(address, "Write attempt on defunct connection");
520538 }
@@ -524,7 +542,7 @@
524542 throw new ConnectionException(address, "Connection has been closed");
525543 }
526544
527- logger.trace("{} writing request {}", this, request);
545+ logger.trace("{}, stream {}, writing request {}", this, request.getStreamId(), request);
528546 writer.incrementAndGet();
529547
530548 if (DISABLE_COALESCING) {
@@ -546,7 +564,7 @@
546564 writer.decrementAndGet();
547565
548566 if (!writeFuture.isSuccess()) {
549- logger.debug("{} Error writing request {}", Connection.this, request);
567+ logger.debug("{}, stream {}, Error writing request {}", Connection.this, request.getStreamId(), request);
550568 // Remove this handler from the dispatcher so it don't get notified of the error
551569 // twice (we will fail that method already)
552570 dispatcher.removeHandler(handler, true);
@@ -570,19 +588,19 @@
570588 }
571589 });
572590 } else {
573- logger.trace("{} request sent successfully", Connection.this);
591+ logger.trace("{}, stream {}, request sent successfully", Connection.this, request.getStreamId());
574592 }
575593 }
576594 };
577595 }
578596
579- boolean hasPool() {
580- return this.poolRef.get() != null;
597+ boolean hasOwner() {
598+ return this.ownerRef.get() != null;
581599 }
582600
583- /** @return whether the connection was already associated with a pool */
584- boolean setPool(HostConnectionPool pool) {
585- return poolRef.compareAndSet(null, pool);
601+ /** @return whether the connection was already associated with an owner */
602+ boolean setOwner(Owner owner) {
603+ return ownerRef.compareAndSet(null, owner);
586604 }
587605
588606 /**
@@ -590,9 +608,9 @@
590608 * The connection should generally not be reused after that.
591609 */
592610 void release() {
593- HostConnectionPool pool = poolRef.get();
594- if (pool != null)
595- pool.returnConnection(this);
611+ Owner owner = ownerRef.get();
612+ if (owner instanceof HostConnectionPool)
613+ ((HostConnectionPool)owner).returnConnection(this);
596614 }
597615
598616 public boolean isClosed() {
@@ -620,6 +638,12 @@
620638
621639 logger.debug("{} closing connection", this);
622640
641+ if (isInitialized && !isDefunct.get()) {
642+ Host host = factory.manager.metadata.getHost(address);
643+ if(host != null)
644+ host.convictionPolicy.signalConnectionClosed();
645+ }
646+
623647 boolean terminated = tryTerminate(false);
624648 if (!terminated) {
625649 // The time by which all pending requests should have normally completed (use twice the read timeout for a generous
@@ -668,7 +692,7 @@
668692
669693 public static class Factory {
670694
671- public final HashedWheelTimer timer;
695+ public final Timer timer;
672696
673697 private final EventLoopGroup eventLoopGroup;
674698 private final Class<? extends Channel> channelClass;
@@ -697,7 +721,7 @@
697721 this.nettyOptions = configuration.getNettyOptions();
698722 this.eventLoopGroup = nettyOptions.eventLoopGroup(manager.threadFactory("nio-worker"));
699723 this.channelClass = nettyOptions.channelClass();
700- this.timer = new HashedWheelTimer(manager.threadFactory("timeouter"));
724+ this.timer = nettyOptions.timer(manager.threadFactory("timeouter"));
701725 }
702726
703727 public int getPort() {
@@ -778,10 +802,6 @@
778802 return g;
779803 }
780804
781- public long getConnectTimeoutMillis() {
782- return configuration.getSocketOptions().getConnectTimeoutMillis();
783- }
784-
785805 public long getReadTimeoutMillis() {
786806 return configuration.getSocketOptions().getReadTimeoutMillis();
787807 }
@@ -826,7 +846,7 @@
826846 allChannels.close().awaitUninterruptibly();
827847
828848 nettyOptions.onClusterClose(eventLoopGroup);
829- timer.stop();
849+ nettyOptions.onClusterClose(timer);
830850 }
831851 }
832852
@@ -877,7 +897,7 @@
877897 }
878898
879899 EventLoop eventLoop = eventLoopRef.get();
880- if(eventLoop != null) {
900+ if (eventLoop != null) {
881901 eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS);
882902 }
883903 }
@@ -923,7 +943,6 @@
923943 if (protocolVersion == null) {
924944 // This happens for the first control connection because the protocol version has not been
925945 // negociated yet.
926- assert !Connection.this.hasPool();
927946 protocolVersion = ProtocolVersion.V2;
928947 }
929948 streamIdHandler = StreamIdGenerator.newInstance(protocolVersion);
@@ -965,7 +984,7 @@
965984 int streamId = response.getStreamId();
966985
967986 if(logger.isTraceEnabled())
968- logger.trace("{} received: {}", Connection.this, asDebugString(response));
987+ logger.trace("{}, stream {}, received: {}", Connection.this, streamId, asDebugString(response));
969988
970989 if (streamId < 0) {
971990 factory.defaultHandler.handle(response);
@@ -1001,7 +1020,7 @@
10011020
10021021 @Override
10031022 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
1004- if (evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
1023+ if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) {
10051024 logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
10061025 write(HEARTBEAT_CALLBACK);
10071026 }
@@ -1323,4 +1342,9 @@
13231342 }
13241343 }
13251344 }
1345+
1346+ /** A component that "owns" a connection, and should be notified when it dies. */
1347+ interface Owner {
1348+ void onConnectionDefunct(Connection connection);
1349+ }
13261350 }
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +94 −95
@@ -19,8 +19,7 @@
1919 import java.net.InetSocketAddress;
2020 import java.net.UnknownHostException;
2121 import java.util.*;
22-import java.util.concurrent.ExecutionException;
23-import java.util.concurrent.TimeUnit;
22+import java.util.concurrent.*;
2423 import java.util.concurrent.atomic.AtomicReference;
2524
2625 import com.google.common.base.Objects;
@@ -34,15 +33,15 @@
3433
3534 import static com.datastax.driver.core.SchemaElement.*;
3635
37-class ControlConnection {
36+class ControlConnection implements Connection.Owner {
3837
3938 private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class);
4039
4140 private static final TypeCodec.ListCodec<String> LIST_OF_TEXT_CODEC = new TypeCodec.ListCodec<String>(TypeCodec.VarcharCodec.instance);
4241
4342 private static final InetAddress bindAllAddress;
44- static
45- {
43+
44+ static {
4645 try {
4746 bindAllAddress = InetAddress.getByAddress(new byte[4]);
4847 } catch (UnknownHostException e) {
@@ -76,15 +75,18 @@
7675 }
7776
7877 // Only for the initial connection. Does not schedule retries if it fails
79- public void connect() throws UnsupportedProtocolVersionException {
78+ void connect() throws UnsupportedProtocolVersionException {
8079 if (isShutdown)
8180 return;
8281
8382 // NB: at this stage, allHosts() only contains the initial contact points
84- setNewConnection(reconnectInternal(cluster.metadata.allHosts().iterator(), true));
83+ List<Host> hosts = new ArrayList<Host>(cluster.metadata.allHosts());
84+ // shuffle so that multiple clients with the same contact points don't all pick the same control host
85+ Collections.shuffle(hosts);
86+ setNewConnection(reconnectInternal(hosts.iterator(), true));
8587 }
8688
87- public CloseFuture closeAsync() {
89+ CloseFuture closeAsync() {
8890 // We don't have to be fancy here. We just set a flag so that we stop trying to reconnect (and thus change the
8991 // connection used) and shutdown the current one.
9092 isShutdown = true;
@@ -100,26 +102,13 @@
100102
101103 Host connectedHost() {
102104 Connection current = connectionRef.get();
103- return cluster.metadata.getHost(current.address);
105+ return (current == null)
106+ ? null
107+ : cluster.metadata.getHost(current.address);
104108 }
105109
106- void reconnect() {
107- if (isShutdown)
108- return;
109-
110- try {
111- setNewConnection(reconnectInternal(queryPlan(), false));
112- } catch (NoHostAvailableException e) {
113- logger.error("[Control connection] Cannot connect to any host, scheduling retry");
114- backgroundReconnect(-1);
115- } catch (UnsupportedProtocolVersionException e) {
116- // reconnectInternal only propagate those if we've not decided on the protocol version yet,
117- // which should only happen on the initial connection and thus in connect() but never here.
118- throw new AssertionError();
119- } catch (Exception e) {
120- logger.error("[Control connection] Unknown error during reconnection, scheduling retry", e);
121- backgroundReconnect(-1);
122- }
110+ void triggerReconnect() {
111+ backgroundReconnect(0);
123112 }
124113
125114 /**
@@ -129,7 +118,14 @@
129118 if (isShutdown)
130119 return;
131120
132- new AbstractReconnectionHandler(cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) {
121+ // Abort if a reconnection is already in progress. This is not thread-safe: two threads might race through this and both
122+ // schedule a reconnection; in that case AbstractReconnectionHandler knows how to deal with it correctly.
123+ // But this cheap check can help us avoid creating the object unnecessarily.
124+ ListenableFuture<?> reconnection = reconnectionAttempt.get();
125+ if (reconnection != null && !reconnection.isDone())
126+ return;
127+
128+ new AbstractReconnectionHandler("Control connection", cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) {
133129 @Override
134130 protected Connection tryReconnect() throws ConnectionException {
135131 try {
@@ -168,17 +164,17 @@
168164
169165 private void signalError() {
170166 Connection connection = connectionRef.get();
171- if (connection != null && connection.isDefunct() && cluster.metadata.getHost(connection.address) != null) {
172- // If the connection was marked as defunct and the host hadn't left, this already reported the
173- // host down, which will trigger a reconnect.
174- return;
175- }
176- // If the connection is not defunct, or the host has left, just reconnect manually
167+ if (connection != null)
168+ connection.closeAsync();
169+
170+ // If the error caused the host to go down, onDown might have already triggered a reconnect.
171+ // But backgroundReconnect knows how to deal with that.
177172 backgroundReconnect(0);
178173 }
179174
180175 private void setNewConnection(Connection newConnection) {
181- logger.debug("[Control connection] Successfully connected to {}", newConnection.address);
176+ Host.statesLogger.debug("[Control connection] established to {}", newConnection.address);
177+ newConnection.setOwner(this);
182178 Connection old = connectionRef.getAndSet(newConnection);
183179 if (old != null && !old.isClosed())
184180 old.closeAsync();
@@ -192,6 +188,8 @@
192188 try {
193189 while (iter.hasNext()) {
194190 host = iter.next();
191+ if (!host.convictionPolicy.canReconnectNow())
192+ continue;
195193 try {
196194 return tryConnect(host, isInitialConnection);
197195 } catch (ConnectionException e) {
@@ -245,8 +243,7 @@
245243 return errors;
246244 }
247245
248- private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException
249- {
246+ private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
250247 Connection connection = cluster.connectionFactory.open(host);
251248
252249 // If no protocol version was specified, set the default as soon as a connection succeeds (it's needed to parse UDTs in refreshSchema)
@@ -266,11 +263,14 @@
266263 // the node we're connecting to.
267264 refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true);
268265
269- // Note that refreshing the schema will trigger refreshNodeListAndTokenMap since table == null
270- // We want that because the token map was not properly initialized by the first call above, since it requires the list of keyspaces
271- // to be loaded.
272266 logger.debug("[Control connection] Refreshing schema");
273- refreshSchema(connection, null, null, null, null, cluster, isInitialConnection);
267+ refreshSchema(connection, null, null, null, null, cluster);
268+
269+ // We need to refresh the node list again;
270+ // We want that because the token map was not properly initialized by the first call above,
271+ // since it requires the list of keyspaces to be loaded.
272+ refreshNodeListAndTokenMap(connection, cluster, false, true);
273+
274274 return connection;
275275 } catch (BusyConnectionException e) {
276276 connection.closeAsync().force();
@@ -297,9 +297,14 @@
297297 try {
298298 Connection c = connectionRef.get();
299299 // At startup, when we add the initial nodes, this will be null, which is ok
300- if (c == null)
300+ if (c == null || c.isClosed())
301301 return;
302- refreshSchema(c, targetType, targetKeyspace, targetName, signature, cluster, false);
302+ refreshSchema(c, targetType, targetKeyspace, targetName, signature, cluster);
303+ // If we rebuild all from scratch or have an updated keyspace, rebuild the token map
304+ // since some replication on some keyspace may have changed
305+ if ((targetType == null || targetType == KEYSPACE)) {
306+ cluster.submitNodeListRefresh();
307+ }
303308 } catch (ConnectionException e) {
304309 logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage());
305310 signalError();
@@ -314,7 +319,7 @@
314319 }
315320 }
316321
317- static void refreshSchema(Connection connection, SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature, Cluster.Manager cluster, boolean isInitialConnection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
322+ static void refreshSchema(Connection connection, SchemaElement targetType, String targetKeyspace, String targetName, List<String> targetSignature, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
318323 Host host = cluster.metadata.getHost(connection.address);
319324 // Neither host, nor it's version should be null. But instead of dying if there is a race or something, we can kind of try to infer
320325 // a Cassandra version from the protocol version (this is not full proof, we can have the protocol 1 against C* 2.0+, but it's worth
@@ -323,7 +328,7 @@
323328 if (host == null || host.getCassandraVersion() == null) {
324329 cassandraVersion = cluster.protocolVersion().minCassandraVersion();
325330 logger.warn("Cannot find Cassandra version for host {} to parse the schema, using {} based on protocol version in use. "
326- + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
331+ + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion);
327332 } else {
328333 cassandraVersion = host.getCassandraVersion();
329334 }
@@ -390,11 +395,6 @@
390395 // So log, but let things go otherwise.
391396 logger.error("Error parsing schema from Cassandra system tables: the schema in Cluster#getMetadata() will appear incomplete or stale", e);
392397 }
393-
394- // If we rebuild all from scratch or have an updated keyspace, rebuild the token map since some replication on some keyspace
395- // may have changed
396- if (isSchemaOrKeyspace)
397- refreshNodeListAndTokenMap(connection, cluster, false, false);
398398 }
399399
400400 private static boolean supportsUdts(VersionNumber cassandraVersion) {
@@ -405,13 +405,12 @@
405405 return cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 2);
406406 }
407407
408- public void refreshNodeListAndTokenMap() {
408+ void refreshNodeListAndTokenMap() {
409409 Connection c = connectionRef.get();
410410 // At startup, when we add the initial nodes, this will be null, which is ok
411- if (c == null)
411+ if (c == null || c.isClosed())
412412 return;
413413
414- logger.debug("[Control connection] Refreshing node list and token map");
415414 try {
416415 refreshNodeListAndTokenMap(c, cluster, false, true);
417416 } catch (ConnectionException e) {
@@ -475,11 +474,11 @@
475474 /**
476475 * @return whether we have enough information to bring the node back up
477476 */
478- public boolean refreshNodeInfo(Host host) {
477+ boolean refreshNodeInfo(Host host) {
479478
480479 Connection c = connectionRef.get();
481480 // At startup, when we add the initial nodes, this will be null, which is ok
482- if (c == null)
481+ if (c == null || c.isClosed())
483482 return true;
484483
485484 logger.debug("[Control connection] Refreshing node info on {}", host);
@@ -537,8 +536,8 @@
537536 String version = row.getString("release_version");
538537 // We don't know if it's a 'local' or a 'peers' row, and only 'peers' rows have the 'peer' field.
539538 InetAddress listenAddress = row.getColumnDefinitions().contains("peer")
540- ? row.getInet("peer")
541- : null;
539+ ? row.getInet("peer")
540+ : null;
542541
543542 host.setVersionAndListenAdress(version, listenAddress);
544543 }
@@ -560,6 +559,8 @@
560559 private static void refreshNodeListAndTokenMap(Connection connection, Cluster.Manager cluster, boolean isInitialConnection, boolean logMissingRpcAddresses) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
561560 logger.debug("[Control connection] Refreshing node list and token map");
562561
562+ boolean metadataEnabled = cluster.configuration.getQueryOptions().isMetadataEnabled();
563+
563564 // Make sure we're up to date on nodes and tokens
564565
565566 DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL));
@@ -588,9 +589,11 @@
588589 logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address);
589590 } else {
590591 updateInfo(host, localRow, cluster, isInitialConnection);
591- Set<String> tokens = localRow.getSet("tokens", String.class);
592- if (partitioner != null && !tokens.isEmpty())
593- tokenMap.put(host, tokens);
592+ if (metadataEnabled) {
593+ Set<String> tokens = localRow.getSet("tokens", String.class);
594+ if (partitioner != null && !tokens.isEmpty())
595+ tokenMap.put(host, tokens);
596+ }
594597 }
595598 }
596599
@@ -611,7 +614,8 @@
611614 racks.add(row.getString("rack"));
612615 cassandraVersions.add(row.getString("release_version"));
613616 listenAddresses.add(row.getInet("peer"));
614- allTokens.add(row.getSet("tokens", String.class));
617+ if (metadataEnabled)
618+ allTokens.add(row.getSet("tokens", String.class));
615619 }
616620
617621 for (int i = 0; i < foundHosts.size(); i++) {
@@ -628,7 +632,7 @@
628632 if (cassandraVersions.get(i) != null)
629633 host.setVersionAndListenAdress(cassandraVersions.get(i), listenAddresses.get(i));
630634
631- if (partitioner != null && !allTokens.get(i).isEmpty())
635+ if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty())
632636 tokenMap.put(host, allTokens.get(i));
633637
634638 if (isNew && !isInitialConnection)
@@ -641,17 +645,17 @@
641645 if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress()))
642646 cluster.removeHost(host, isInitialConnection);
643647
644- cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
648+ if (metadataEnabled)
649+ cluster.metadata.rebuildTokenMap(partitioner, tokenMap);
645650 }
646651
647- static boolean waitForSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
648-
652+ boolean waitForSchemaAgreement() throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException {
649653 long start = System.nanoTime();
650654 long elapsed = 0;
651655 int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds();
652656 while (elapsed < maxSchemaAgreementWaitSeconds * 1000) {
653657
654- if (checkSchemaAgreement(connection, cluster))
658+ if (checkSchemaAgreement())
655659 return true;
656660
657661 // let's not flood the node too much
@@ -663,7 +667,11 @@
663667 return false;
664668 }
665669
666- private static boolean checkSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException {
670+ boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException {
671+ Connection connection = connectionRef.get();
672+ if (connection == null || connection.isClosed())
673+ return false;
674+
667675 DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_PEERS));
668676 DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_LOCAL));
669677 connection.write(peersFuture);
@@ -689,16 +697,6 @@
689697 return versions.size() <= 1;
690698 }
691699
692- boolean checkSchemaAgreement() {
693- Connection c = connectionRef.get();
694- try {
695- return c != null && checkSchemaAgreement(c, cluster);
696- } catch (Exception e) {
697- logger.warn("Error while checking schema agreement", e);
698- return false;
699- }
700- }
701-
702700 boolean isOpen() {
703701 Connection c = connectionRef.get();
704702 return c != null && !c.isClosed();
@@ -708,36 +706,37 @@
708706 }
709707
710708 public void onDown(Host host) {
711- // If that's the host we're connected to, and we haven't yet schedule a reconnection, preemptively start one
709+ onHostGone(host);
710+ }
711+
712+ public void onRemove(Host host) {
713+ onHostGone(host);
714+ cluster.submitNodeListRefresh();
715+ }
716+
717+ private void onHostGone(Host host) {
712718 Connection current = connectionRef.get();
713- if (logger.isDebugEnabled())
714- logger.debug("[Control connection] {} is down, currently connected to {}", host, current == null ? "nobody" : current.address);
715719
716720 if (current != null && current.address.equals(host.getSocketAddress())) {
717- // This starts an AbstractReconnectionHandler, which will take care of checking if another reconnection is
718- // already in progress
721+ logger.debug("[Control connection] {} is down/removed and it was the control host, triggering reconnect",
722+ current.address);
723+ if (!current.isClosed())
724+ current.closeAsync();
719725 backgroundReconnect(0);
720726 }
721727 }
722728
729+ @Override
730+ public void onConnectionDefunct(Connection connection) {
731+ if (connection == connectionRef.get())
732+ backgroundReconnect(0);
733+ }
734+
723735 public void onAdd(Host host) {
724736 // Refresh infos and token map if we didn't knew about that host, i.e. if we either don't have basic infos on it,
725737 // or it's not part of our computed token map
726738 Metadata.TokenMap tkmap = cluster.metadata.tokenMap;
727739 if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host))
728- refreshNodeListAndTokenMap();
729- }
730-
731- public void onRemove(Host host) {
732- Connection current = connectionRef.get();
733- if (logger.isDebugEnabled())
734- logger.debug("[Control connection] {} has been removed, currently connected to {}", host, current == null ? "nobody" : current.address);
735-
736- // Schedule a reconnection if that was our control host
737- if (current != null && current.address.equals(host.getSocketAddress())) {
738- backgroundReconnect(0);
739- }
740-
741- refreshNodeListAndTokenMap();
740+ cluster.submitNodeListRefresh();
742741 }
743742 }
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +95 −17
@@ -15,6 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.concurrent.atomic.AtomicInteger;
19+
20+import static java.util.concurrent.TimeUnit.MILLISECONDS;
21+import static java.util.concurrent.TimeUnit.NANOSECONDS;
22+
23+import com.datastax.driver.core.policies.ReconnectionPolicy;
24+
1825 /**
1926 * The policy with which to decide whether a host should be considered down.
2027 *
@@ -25,24 +32,36 @@
2532 */
2633 abstract class ConvictionPolicy {
2734
35+ /**
36+ * Called when a new connection to the host has been successfully opened.
37+ */
38+ abstract void signalConnectionCreated();
39+
40+ /**
41+ * Called when a connection closed normally.
42+ */
43+ abstract void signalConnectionClosed();
44+
2845 /**
2946 * Called when a connection error occurs on a connection to the host this policy applies to.
3047 *
3148 * @param exception the connection error that occurred.
32- *
33- * @return {@code true} if the host should be considered down.
49+ * @param connectionInitialized whether the connection was initialized.
50+ * @return whether the host should be considered down.
3451 */
35- public abstract boolean addFailure(ConnectionException exception);
52+ abstract boolean signalConnectionFailure(ConnectionException exception, boolean connectionInitialized);
53+
54+ abstract boolean canReconnectNow();
3655
3756 /**
38- * Called when the host has been detected up.
57+ * Called when the host goes down.
3958 */
40- public abstract void reset();
59+ abstract void reset();
4160
4261 /**
4362 * Simple factory interface to allow creating {@link ConvictionPolicy} instances.
4463 */
45- public interface Factory {
64+ interface Factory {
4665
4766 /**
4867 * Creates a new ConvictionPolicy instance for {@code host}.
@@ -50,30 +69,89 @@
5069 * @param host the host this policy applies to
5170 * @return the newly created {@link ConvictionPolicy} instance.
5271 */
53- public ConvictionPolicy create(Host host);
72+ ConvictionPolicy create(Host host, ReconnectionPolicy reconnectionPolicy);
5473 }
5574
56- public static class Simple extends ConvictionPolicy {
57- private Simple(Host host) {
75+ static class DefaultConvictionPolicy extends ConvictionPolicy {
76+ private final Host host;
77+ private final ReconnectionPolicy reconnectionPolicy;
78+ private final AtomicInteger openConnections = new AtomicInteger();
79+
80+ private volatile long nextReconnectionTime = Long.MIN_VALUE;
81+ private ReconnectionPolicy.ReconnectionSchedule reconnectionSchedule;
82+
83+ private DefaultConvictionPolicy(Host host, ReconnectionPolicy reconnectionPolicy) {
84+ this.host = host;
85+ this.reconnectionPolicy = reconnectionPolicy;
86+ }
87+
88+ @Override
89+ void signalConnectionCreated() {
90+ int newCount = openConnections.incrementAndGet();
91+ Host.statesLogger.debug("[{}] new connection created, total = {}", host, newCount);
92+ resetReconnectionTime();
93+ }
94+
95+ @Override
96+ void signalConnectionClosed() {
97+ if (host.state == Host.State.DOWN)
98+ return;
99+ int remaining = openConnections.decrementAndGet();
100+ assert remaining >= 0;
101+ Host.statesLogger.debug("[{}] connection closed, remaining = {}", host, remaining);
58102 }
59103
60104 @Override
61- public boolean addFailure(ConnectionException exception) {
62- return true;
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();
113+
114+ assert remaining >= 0;
115+ Host.statesLogger.debug("[{}] remaining connections = {}", host, remaining);
116+ return remaining == 0;
63117 }
64118
65- public boolean addFailureFromExternalDetector() {
66- return true;
119+ private synchronized void updateReconnectionTime() {
120+ long now = System.nanoTime();
121+ if (nextReconnectionTime > now)
122+ // Someone else updated the time before us
123+ return;
124+
125+ if (reconnectionSchedule == null)
126+ reconnectionSchedule = reconnectionPolicy.newSchedule();
127+
128+ long nextDelayMs = reconnectionSchedule.nextDelayMs();
129+ Host.statesLogger.debug("[{}] preventing new connections for the next {} ms", host, nextDelayMs);
130+ nextReconnectionTime = now + NANOSECONDS.convert(nextDelayMs, MILLISECONDS);
131+ }
132+
133+ private synchronized void resetReconnectionTime() {
134+ reconnectionSchedule = null;
135+ nextReconnectionTime = Long.MIN_VALUE;
67136 }
68137
69138 @Override
70- public void reset() {}
139+ boolean canReconnectNow() {
140+ return nextReconnectionTime == Long.MIN_VALUE ||
141+ System.nanoTime() >= nextReconnectionTime;
142+ }
143+
144+ @Override
145+ synchronized void reset() {
146+ openConnections.set(0);
147+ resetReconnectionTime();
148+ }
71149
72- public static class Factory implements ConvictionPolicy.Factory {
150+ static class Factory implements ConvictionPolicy.Factory {
73151
74152 @Override
75- public ConvictionPolicy create(Host host) {
76- return new Simple(host);
153+ public ConvictionPolicy create(Host host, ReconnectionPolicy reconnectionPolicy) {
154+ return new DefaultConvictionPolicy(host, reconnectionPolicy);
77155 }
78156 }
79157 }
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +85 −48
@@ -71,44 +71,93 @@
7171 set(ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement));
7272 break;
7373 case SCHEMA_CHANGE:
74- Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
75- logger.debug("Applying {}", scc);
7674 ResultSet rs = ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement);
77- switch (scc.change) {
78- case CREATED:
79- case UPDATED:
80- session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.targetType, scc.targetKeyspace, scc.targetName, scc.targetSignature);
81- break;
82- case DROPPED:
83- if (scc.targetType == KEYSPACE) {
84- session.cluster.manager.metadata.removeKeyspace(scc.targetKeyspace);
85- } else {
86- KeyspaceMetadata keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
87- if (keyspace == null) {
88- logger.warn("Received a DROPPED notification for {} {}.{}, but this keyspace is unknown in our metadata",
89- scc.targetType, scc.targetKeyspace, scc.targetName);
75+ final Cluster.Manager cluster = session.cluster.manager;
76+ if (!cluster.configuration.getQueryOptions().isMetadataEnabled()) {
77+ cluster.waitForSchemaAgreementAndSignal(connection, this, rs);
78+ } else {
79+ Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm;
80+ switch (scc.change) {
81+ case CREATED:
82+ case UPDATED:
83+ cluster.refreshSchemaAndSignal(connection, this, rs, scc.targetType, scc.targetKeyspace, scc.targetName, scc.targetSignature);
84+ break;
85+ case DROPPED:
86+ if (scc.targetType == KEYSPACE) {
87+ // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...)
88+ // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements.
89+ // We'll add it back if CASSANDRA-5358 changes that behavior
90+ //if (scc.keyspace.equals(session.poolsState.keyspace))
91+ // session.poolsState.setKeyspace(null);
92+ final KeyspaceMetadata removedKeyspace = cluster.metadata.removeKeyspace(scc.targetKeyspace);
93+ if (removedKeyspace != null) {
94+ cluster.executor.submit(new Runnable() {
95+ @Override
96+ public void run() {
97+ cluster.metadata.triggerOnKeyspaceRemoved(removedKeyspace);
98+ }
99+ });
100+ }
90101 } else {
91- switch (scc.targetType) {
92- case TABLE:
93- keyspace.removeTable(scc.targetName);
94- break;
95- case TYPE:
96- keyspace.removeUserType(scc.targetName);
97- break;
98- case FUNCTION:
99- keyspace.removeFunction(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
100- break;
101- case AGGREGATE:
102- keyspace.removeAggregate(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
103- break;
102+ KeyspaceMetadata keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace);
103+ if (keyspace == null) {
104+ logger.warn("Received a DROPPED notification for {} {}.{}, but this keyspace is unknown in our metadata",
105+ scc.targetType, scc.targetKeyspace, scc.targetName);
106+ } else {
107+ switch (scc.targetType) {
108+ case TABLE:
109+ final TableMetadata removedTable = keyspace.removeTable(scc.targetName);
110+ if (removedTable != null) {
111+ cluster.executor.submit(new Runnable() {
112+ @Override
113+ public void run() {
114+ cluster.metadata.triggerOnTableRemoved(removedTable);
115+ }
116+ });
117+ }
118+ break;
119+ case TYPE:
120+ final UserType removedType = keyspace.removeUserType(scc.targetName);
121+ if (removedType != null) {
122+ cluster.executor.submit(new Runnable() {
123+ @Override
124+ public void run() {
125+ cluster.metadata.triggerOnUserTypeRemoved(removedType);
126+ }
127+ });
128+ }
129+ break;
130+ case FUNCTION:
131+ final FunctionMetadata removedFunction = keyspace.removeFunction(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
132+ if (removedFunction != null) {
133+ cluster.executor.submit(new Runnable() {
134+ @Override
135+ public void run() {
136+ cluster.metadata.triggerOnFunctionRemoved(removedFunction);
137+ }
138+ });
139+ }
140+ break;
141+ case AGGREGATE:
142+ final AggregateMetadata removedAggregate = keyspace.removeAggregate(Metadata.fullFunctionName(scc.targetName, scc.targetSignature));
143+ if (removedAggregate != null) {
144+ cluster.executor.submit(new Runnable() {
145+ @Override
146+ public void run() {
147+ cluster.metadata.triggerOnAggregateRemoved(removedAggregate);
148+ }
149+ });
150+ }
151+ break;
152+ }
104153 }
105154 }
106- }
107- session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs);
108- break;
109- default:
110- logger.info("Ignoring unknown schema change result");
111- break;
155+ session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs);
156+ break;
157+ default:
158+ logger.info("Ignoring unknown schema change result");
159+ break;
160+ }
112161 }
113162 break;
114163 default:
@@ -182,7 +231,7 @@
182231 try {
183232 return Uninterruptibles.getUninterruptibly(this);
184233 } catch (ExecutionException e) {
185- throw extractCauseFromExecutionException(e);
234+ throw DriverThrowables.propagateCause(e);
186235 }
187236 }
188237
@@ -214,7 +263,7 @@
214263 try {
215264 return Uninterruptibles.getUninterruptibly(this, timeout, unit);
216265 } catch (ExecutionException e) {
217- throw extractCauseFromExecutionException(e);
266+ throw DriverThrowables.propagateCause(e);
218267 }
219268 }
220269
@@ -261,18 +310,6 @@
261310 return true;
262311 }
263312
264- static RuntimeException extractCauseFromExecutionException(ExecutionException e) {
265- // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
266- // created on the I/O thread receiving the response. Which means that the stacktrace associated
267- // with said cause will make no mention of the current thread. This is painful for say, finding
268- // out which execute() statement actually raised the exception. So instead, we re-create the
269- // exception.
270- if (e.getCause() instanceof DriverException)
271- throw ((DriverException)e.getCause()).copy();
272- else
273- throw new DriverInternalError("Unexpected exception thrown", e.getCause());
274- }
275-
276313 @Override
277314 public int retryCount() {
278315 // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
modified driver-core/src/main/java/com/datastax/driver/core/DelegatingCluster.java +12 −0
@@ -18,6 +18,8 @@
1818 import java.net.InetSocketAddress;
1919 import java.util.Collections;
2020
21+import com.google.common.util.concurrent.ListenableFuture;
22+
2123 /**
2224 * Base class for custom {@link Cluster} implementations that wrap another instance (delegate / decorator pattern).
2325 */
@@ -74,6 +76,16 @@
7476 return delegate().connect(keyspace);
7577 }
7678
79+ @Override
80+ public ListenableFuture<Session> connectAsync() {
81+ return delegate().connectAsync();
82+ }
83+
84+ @Override
85+ public ListenableFuture<Session> connectAsync(String keyspace) {
86+ return delegate().connectAsync(keyspace);
87+ }
88+
7789 @Override
7890 public Metadata getMetadata() {
7991 return delegate().getMetadata();
added driver-core/src/main/java/com/datastax/driver/core/DriverThrowables.java +41 −0
@@ -0,0 +1,41 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import java.util.concurrent.ExecutionException;
19+
20+import com.datastax.driver.core.exceptions.DriverException;
21+import com.datastax.driver.core.exceptions.DriverInternalError;
22+
23+class DriverThrowables {
24+
25+ static RuntimeException propagateCause(ExecutionException e) {
26+ Throwable cause = e.getCause();
27+
28+ if (cause instanceof Error)
29+ throw ((Error)cause);
30+
31+ // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been
32+ // created on the I/O thread receiving the response. Which means that the stacktrace associated
33+ // with said cause will make no mention of the current thread. This is painful for say, finding
34+ // out which execute() statement actually raised the exception. So instead, we re-create the
35+ // exception.
36+ if (cause instanceof DriverException)
37+ throw ((DriverException)cause).copy();
38+ else
39+ throw new DriverInternalError("Unexpected exception thrown", cause);
40+ }
41+}
added driver-core/src/main/java/com/datastax/driver/core/EventDebouncer.java +289 −0
@@ -0,0 +1,289 @@
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.List;
19+import java.util.Queue;
20+import java.util.concurrent.*;
21+import java.util.concurrent.atomic.AtomicInteger;
22+import java.util.concurrent.atomic.AtomicReference;
23+
24+import static java.util.concurrent.TimeUnit.NANOSECONDS;
25+import static java.util.concurrent.TimeUnit.SECONDS;
26+
27+import com.google.common.collect.Lists;
28+import com.google.common.util.concurrent.FutureCallback;
29+import com.google.common.util.concurrent.Futures;
30+import com.google.common.util.concurrent.ListenableFuture;
31+import com.google.common.util.concurrent.SettableFuture;
32+import org.slf4j.Logger;
33+import org.slf4j.LoggerFactory;
34+
35+import static com.google.common.base.Preconditions.checkNotNull;
36+
37+import com.datastax.driver.core.utils.MoreFutures;
38+
39+/**
40+ * A helper class to debounce events received by the Control Connection.
41+ *
42+ * This class accumulates received events, and delivers them when either:
43+ * - no events have been received for delayMs
44+ * - maxPendingEvents have been received
45+ */
46+class EventDebouncer<T> {
47+
48+ private static final Logger logger = LoggerFactory.getLogger(EventDebouncer.class);
49+
50+ private static final int MAX_QUEUED_EVENTS = 10000;
51+
52+ private final String name;
53+
54+ private final AtomicReference<DeliveryAttempt> immediateDelivery = new AtomicReference<DeliveryAttempt>(null);
55+ private final AtomicReference<DeliveryAttempt> delayedDelivery = new AtomicReference<DeliveryAttempt>(null);
56+
57+ private final ScheduledExecutorService executor;
58+
59+ private final DeliveryCallback<T> callback;
60+
61+ private final long delayMs;
62+ private final int maxPendingEvents;
63+
64+ private final Queue<Entry<T>> events;
65+ private final AtomicInteger eventCount;
66+
67+ private enum State {NEW, RUNNING, STOPPED}
68+
69+ private volatile State state;
70+
71+ private static final long OVERFLOW_WARNING_INTERVAL = NANOSECONDS.convert(5, SECONDS);
72+ private volatile long lastOverflowWarning = Long.MIN_VALUE;
73+
74+ EventDebouncer(String name, ScheduledExecutorService executor, DeliveryCallback<T> callback, long delayMs, int maxPendingEvents) {
75+ this.name = name;
76+ this.executor = executor;
77+ this.callback = callback;
78+ this.delayMs = delayMs;
79+ this.maxPendingEvents = maxPendingEvents;
80+ this.events = new ConcurrentLinkedQueue<Entry<T>>();
81+ this.eventCount = new AtomicInteger();
82+ this.state = State.NEW;
83+ }
84+
85+ void start() {
86+ logger.trace("Starting {} debouncer...", name);
87+ state = State.RUNNING;
88+ if (!events.isEmpty()) {
89+ logger.trace("{} debouncer: {} events were accumulated before the debouncer started: delivering now",
90+ name, eventCount.get());
91+ scheduleImmediateDelivery();
92+ }
93+ }
94+
95+ void stop() {
96+ logger.trace("Stopping {} debouncer...", name);
97+ state = State.STOPPED;
98+ while (true) {
99+ DeliveryAttempt previous = cancelDelayedDelivery();
100+ if (delayedDelivery.compareAndSet(previous, null)) {
101+ break;
102+ }
103+ }
104+
105+ completeAllPendingFutures();
106+
107+ logger.trace("{} debouncer stopped", name);
108+ }
109+
110+ private void completeAllPendingFutures() {
111+ Entry<T> entry;
112+ while ((entry = this.events.poll()) != null) {
113+ entry.future.set(null);
114+ }
115+ }
116+
117+ /** @return a future that will complete once the event has been processed */
118+ ListenableFuture<Void> eventReceived(T event) {
119+ if (state == State.STOPPED) {
120+ logger.trace("{} debouncer is stopped, rejecting event: {}", name, event);
121+ return MoreFutures.VOID_SUCCESS;
122+ }
123+ checkNotNull(event);
124+ logger.trace("{} debouncer: event received {}", name, event);
125+
126+ int count = eventCount.incrementAndGet();
127+
128+ // Safeguard against the queue filling up faster than we can process it
129+ long now;
130+ if (count > MAX_QUEUED_EVENTS && (now = System.nanoTime()) > lastOverflowWarning + OVERFLOW_WARNING_INTERVAL) {
131+ lastOverflowWarning = now;
132+ logger.warn("{} debouncer enqueued more than {} events, rejecting new events. "
133+ + "This should not happen and is likely a sign that something is wrong.",
134+ name, MAX_QUEUED_EVENTS);
135+ return MoreFutures.VOID_SUCCESS;
136+ }
137+
138+ Entry<T> entry = new Entry<T>(event);
139+ try {
140+ events.add(entry);
141+ } catch (RuntimeException e) {
142+ eventCount.decrementAndGet();
143+ throw e;
144+ }
145+
146+ if (state == State.RUNNING) {
147+ if (count < maxPendingEvents) {
148+ scheduleDelayedDelivery();
149+ } else if (count == maxPendingEvents) {
150+ scheduleImmediateDelivery();
151+ }
152+ } else if (state == State.STOPPED) {
153+ // If we race with stop() since the check at the beginning, ensure the future
154+ // gets completed (no-op if the future was already set).
155+ entry.future.set(null);
156+ }
157+ return entry.future;
158+ }
159+
160+ private void scheduleImmediateDelivery() {
161+ cancelDelayedDelivery();
162+
163+ while (state == State.RUNNING) {
164+ DeliveryAttempt previous = immediateDelivery.get();
165+ if (previous != null && !previous.isDone())
166+ return;
167+
168+ DeliveryAttempt current = new DeliveryAttempt();
169+ if (immediateDelivery.compareAndSet(previous, current)) {
170+ current.executeNow();
171+ return;
172+ }
173+ }
174+ }
175+
176+ private void scheduleDelayedDelivery() {
177+ while (state == State.RUNNING) {
178+ DeliveryAttempt previous = cancelDelayedDelivery();
179+ DeliveryAttempt next = new DeliveryAttempt();
180+ if (delayedDelivery.compareAndSet(previous, next)) {
181+ next.scheduleAfterDelay();
182+ break;
183+ }
184+ }
185+ }
186+
187+ private DeliveryAttempt cancelDelayedDelivery() {
188+ DeliveryAttempt previous = delayedDelivery.get();
189+ if (previous != null) {
190+ previous.cancel();
191+ }
192+ return previous;
193+ }
194+
195+ void deliverEvents() {
196+ if (state == State.STOPPED) {
197+ completeAllPendingFutures();
198+ return;
199+ }
200+ final List<T> toDeliver = Lists.newArrayList();
201+ final List<SettableFuture<Void>> futures = Lists.newArrayList();
202+
203+ Entry<T> entry;
204+ // Limit the number of events we dequeue, to avoid an infinite loop if the queue starts filling faster than we can consume it.
205+ int count = 0;
206+ while (++count <= MAX_QUEUED_EVENTS && (entry = this.events.poll()) != null) {
207+ toDeliver.add(entry.event);
208+ futures.add(entry.future);
209+ }
210+ eventCount.addAndGet(-toDeliver.size());
211+
212+ if (toDeliver.isEmpty()) {
213+ logger.trace("{} debouncer: no events to deliver", name);
214+ } else {
215+ logger.trace("{} debouncer: delivering {} events", name, toDeliver.size());
216+ ListenableFuture<?> delivered = callback.deliver(toDeliver);
217+ Futures.addCallback(delivered, new FutureCallback<Object>() {
218+ @Override
219+ public void onSuccess(Object result) {
220+ for (SettableFuture<Void> future : futures)
221+ future.set(null);
222+ }
223+
224+ @Override
225+ public void onFailure(Throwable t) {
226+ for (SettableFuture<Void> future : futures)
227+ future.setException(t);
228+ }
229+ });
230+ }
231+
232+ // If we didn't dequeue all events (or new ones arrived since we did), make sure we eventually
233+ // process the remaining events, because eventReceived might have skipped the delivery
234+ if (!events.isEmpty())
235+ scheduleDelayedDelivery();
236+ }
237+
238+ class DeliveryAttempt extends ExceptionCatchingRunnable {
239+
240+ volatile Future<?> deliveryFuture;
241+
242+ boolean isDone() {
243+ return deliveryFuture != null && deliveryFuture.isDone();
244+ }
245+
246+ void cancel() {
247+ if (deliveryFuture != null)
248+ deliveryFuture.cancel(true);
249+ }
250+
251+ void executeNow() {
252+ if (state != State.STOPPED)
253+ deliveryFuture = executor.submit(this);
254+ }
255+
256+ void scheduleAfterDelay() {
257+ if (state != State.STOPPED)
258+ deliveryFuture = executor.schedule(this, delayMs, TimeUnit.MILLISECONDS);
259+ }
260+
261+ @Override
262+ public void runMayThrow() throws Exception {
263+ deliverEvents();
264+ }
265+ }
266+
267+ interface DeliveryCallback<T> {
268+
269+ /**
270+ * Deliver the given list of events.
271+ * The given list is a private copy and any modification made to it
272+ * has no side-effect; it is also guaranteed not to be null nor empty.
273+ *
274+ * @param events the events to deliver
275+ */
276+ ListenableFuture<?> deliver(List<T> events);
277+
278+ }
279+
280+ static class Entry<T> {
281+ final T event;
282+ final SettableFuture<Void> future;
283+
284+ Entry(T event) {
285+ this.event = event;
286+ this.future = SettableFuture.create();
287+ }
288+ }
289+}
modified driver-core/src/main/java/com/datastax/driver/core/FunctionMetadata.java +21 −0
@@ -20,6 +20,7 @@
2020 import java.util.List;
2121 import java.util.Map;
2222
23+import com.google.common.base.Objects;
2324 import com.google.common.collect.ImmutableMap;
2425 import org.slf4j.Logger;
2526 import org.slf4j.LoggerFactory;
@@ -268,4 +269,24 @@
268269 public DataType getReturnType() {
269270 return returnType;
270271 }
272+
273+ @Override
274+ public boolean equals(Object other) {
275+ if (other instanceof FunctionMetadata) {
276+ FunctionMetadata that = (FunctionMetadata)other;
277+ return this.keyspace.getName().equals(that.keyspace.getName()) &&
278+ this.fullName.equals(that.fullName) &&
279+ this.arguments.equals(that.arguments) &&
280+ this.body.equals(that.body) &&
281+ this.calledOnNullInput == that.calledOnNullInput &&
282+ this.language.equals(that.language) &&
283+ this.returnType.equals(that.returnType);
284+ }
285+ return false;
286+ }
287+
288+ @Override
289+ public int hashCode() {
290+ return Objects.hashCode(keyspace.getName(), fullName, arguments, body, calledOnNullInput, language, returnType);
291+ }
271292 }
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +6 −9
@@ -35,6 +35,7 @@
3535
3636 private static final Logger logger = LoggerFactory.getLogger(Host.class);
3737
38+ static final Logger statesLogger = LoggerFactory.getLogger(Host.class.getName() + ".STATES");
3839
3940 private final InetSocketAddress address;
4041
@@ -43,7 +44,7 @@
4344 /** Ensures state change notifications for that host are handled serially */
4445 final ReentrantLock notificationsLock = new ReentrantLock(true);
4546
46- private final ConvictionPolicy policy;
47+ final ConvictionPolicy convictionPolicy;
4748 private final Cluster.Manager manager;
4849
4950 // Tracks later reconnection attempts to that host so we avoid adding multiple tasks.
@@ -66,12 +67,12 @@
6667 // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely,
6768 // we rely on the fact that we can use Object equality as a valid equality), so don't use
6869 // that constructor but ClusterMetadata.getHost instead.
69- Host(InetSocketAddress address, ConvictionPolicy.Factory policy, Cluster.Manager manager) {
70- if (address == null || policy == null)
70+ Host(InetSocketAddress address, ConvictionPolicy.Factory convictionPolicyFactory, Cluster.Manager manager) {
71+ if (address == null || convictionPolicyFactory == null)
7172 throw new NullPointerException();
7273
7374 this.address = address;
74- this.policy = policy.create(this);
75+ this.convictionPolicy = convictionPolicyFactory.create(this, manager.reconnectionPolicy());
7576 this.manager = manager;
7677 this.defaultExecutionInfo = new ExecutionInfo(ImmutableList.of(this));
7778 this.state = State.ADDED;
@@ -256,17 +257,13 @@
256257
257258 void setDown() {
258259 state = State.DOWN;
260+ convictionPolicy.reset();
259261 }
260262
261263 void setUp() {
262- policy.reset();
263264 state = State.UP;
264265 }
265266
266- boolean signalConnectionFailure(ConnectionException exception) {
267- return policy.addFailure(exception);
268- }
269-
270267 /**
271268 * Interface for listeners that are interested in hosts added, up, down and
272269 * removed events.
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +101 −33
@@ -17,6 +17,7 @@
1717
1818 import java.util.ArrayList;
1919 import java.util.List;
20+import java.util.ListIterator;
2021 import java.util.Set;
2122 import java.util.concurrent.*;
2223 import java.util.concurrent.atomic.AtomicInteger;
@@ -26,6 +27,7 @@
2627 import java.util.concurrent.locks.ReentrantLock;
2728
2829 import com.google.common.annotations.VisibleForTesting;
30+import com.google.common.base.Throwables;
2931 import com.google.common.collect.Lists;
3032 import com.google.common.util.concurrent.*;
3133 import org.slf4j.Logger;
@@ -39,7 +41,7 @@
3941 import static com.datastax.driver.core.Connection.State.RESURRECTING;
4042 import static com.datastax.driver.core.Connection.State.TRASHED;
4143
42-class HostConnectionPool {
44+class HostConnectionPool implements Connection.Owner {
4345
4446 private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class);
4547
@@ -103,15 +105,19 @@
103105 * pool.
104106 */
105107 ListenableFuture<Void> initAsync(Connection reusedConnection) {
108+ String keyspace = manager.poolsState.keyspace;
109+
110+ Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
111+
106112 // Create initial core connections
107- int capacity = options().getCoreConnectionsPerHost(hostDistance);
108- final List<Connection> connections = Lists.newArrayListWithCapacity(capacity);
109- final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(capacity);
110- for (int i = 0; i < capacity; i++) {
113+ final int coreSize = options().getCoreConnectionsPerHost(hostDistance);
114+ final List<Connection> connections = Lists.newArrayListWithCapacity(coreSize);
115+ final List<ListenableFuture<Void>> connectionFutures = Lists.newArrayListWithCapacity(coreSize);
116+ for (int i = 0; i < coreSize; i++) {
111117 Connection connection;
112118 ListenableFuture<Void> connectionFuture;
113119 // reuse the existing connection only once
114- if (reusedConnection != null && reusedConnection.setPool(this)) {
120+ if (reusedConnection != null && reusedConnection.setOwner(this)) {
115121 connection = reusedConnection;
116122 connectionFuture = MoreFutures.VOID_SUCCESS;
117123 } else {
@@ -120,25 +126,32 @@
120126 }
121127 reusedConnection = null;
122128 connections.add(connection);
123- connectionFutures.add(connectionFuture);
129+ connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor));
124130 }
125131
126- Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor();
127-
128132 ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures);
129133
130134 final SettableFuture<Void> initFuture = SettableFuture.create();
131135 Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() {
132136 @Override
133137 public void onSuccess(List<Void> l) {
138+ // Some of the connections might have failed, keep only the successful ones
139+ ListIterator<Connection> it = connections.listIterator();
140+ while (it.hasNext()) {
141+ if (it.next().isClosed())
142+ it.remove();
143+ }
144+
134145 HostConnectionPool.this.connections.addAll(connections);
135- open.set(l.size());
146+ open.set(connections.size());
147+
136148 if (isClosed()) {
137149 initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization"));
138150 // we're not sure if closeAsync() saw the connections, so ensure they get closed
139151 forceClose(connections);
140152 } else {
141- logger.trace("Created connection pool to host {}", host);
153+ logger.debug("Created connection pool to host {} ({} connections needed, {} successfully opened)",
154+ host, coreSize, connections.size());
142155 phase.compareAndSet(Phase.INITIALIZING, Phase.READY);
143156 initFuture.set(null);
144157 }
@@ -154,7 +167,37 @@
154167 return initFuture;
155168 }
156169
157- // Clean up if we got an error at construction time but still created part of the core connections
170+ private ListenableFuture<Void> handleErrors(ListenableFuture<Void> connectionInitFuture, Executor executor) {
171+ return Futures.withFallback(connectionInitFuture, new FutureFallback<Void>() {
172+ @Override
173+ public ListenableFuture<Void> create(Throwable t) throws Exception {
174+ // Propagate these exceptions because they mean no connection will ever succeed. They will be handled
175+ // accordingly in SessionManager#maybeAddPool.
176+ Throwables.propagateIfInstanceOf(t, ClusterNameMismatchException.class);
177+ Throwables.propagateIfInstanceOf(t, UnsupportedProtocolVersionException.class);
178+ Throwables.propagateIfInstanceOf(t, SetKeyspaceException.class);
179+
180+ // We don't want to swallow Errors either as they probably indicate a more serious issue (OOME...)
181+ Throwables.propagateIfInstanceOf(t, Error.class);
182+
183+ // Otherwise, return success. The pool will simply ignore this connection when it sees that it's been closed.
184+ return MoreFutures.VOID_SUCCESS;
185+ }
186+ }, executor);
187+ }
188+
189+ private ListenableFuture<Void> setKeyspaceAsync(ListenableFuture<Void> initFuture, final Connection connection, final String keyspace) {
190+ return (keyspace == null)
191+ ? initFuture
192+ : Futures.transform(initFuture, new AsyncFunction<Void, Void>() {
193+ @Override
194+ public ListenableFuture<Void> apply(Void input) throws Exception {
195+ return connection.setKeyspaceAsync(keyspace);
196+ }
197+ });
198+ }
199+
200+ // Clean up if we got a fatal error at construction time but still created part of the core connections
158201 private void forceClose(List<Connection> connections) {
159202 for (Connection connection : connections) {
160203 connection.closeAsync().force();
@@ -173,16 +216,25 @@
173216 throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase);
174217
175218 if (connections.isEmpty()) {
176- for (int i = 0; i < options().getCoreConnectionsPerHost(hostDistance); i++) {
177- // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
178- // protect against creating connection in excess of core too quickly
179- scheduledForCreation.incrementAndGet();
180- manager.blockingExecutor().submit(newConnectionTask);
219+ if (!host.convictionPolicy.canReconnectNow())
220+ throw new TimeoutException("Connection pool is empty, currently trying to reestablish connections");
221+ else {
222+ int coreSize = options().getCoreConnectionsPerHost(hostDistance);
223+ if (coreSize == 0) {
224+ maybeSpawnNewConnection();
225+ } else {
226+ for (int i = 0; i < coreSize; i++) {
227+ // We don't respect MAX_SIMULTANEOUS_CREATION here because it's only to
228+ // protect against creating connection in excess of core too quickly
229+ scheduledForCreation.incrementAndGet();
230+ manager.blockingExecutor().submit(newConnectionTask);
231+ }
232+ }
233+ Connection c = waitForConnection(timeout, unit);
234+ totalInFlight.incrementAndGet();
235+ c.setKeyspace(manager.poolsState.keyspace);
236+ return c;
181237 }
182- Connection c = waitForConnection(timeout, unit);
183- totalInFlight.incrementAndGet();
184- c.setKeyspace(manager.poolsState.keyspace);
185- return c;
186238 }
187239
188240 int minInFlight = Integer.MAX_VALUE;
@@ -226,7 +278,9 @@
226278 }
227279
228280 int connectionCount = open.get() + scheduledForCreation.get();
229- if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
281+ if (connectionCount < options().getCoreConnectionsPerHost(hostDistance)) {
282+ maybeSpawnNewConnection();
283+ } else if (connectionCount < options().getMaxConnectionsPerHost(hostDistance)) {
230284 // Add a connection if we fill the first n-1 connections and almost fill the last one
231285 int currentCapacity = (connectionCount - 1) * options().getMaxRequestsPerConnection(hostDistance)
232286 + options().getNewConnectionThreshold(hostDistance);
@@ -277,7 +331,7 @@
277331
278332 private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException {
279333 if (timeout == 0)
280- throw new TimeoutException();
334+ throw new TimeoutException("All connections are busy and pool timeout is 0");
281335
282336 long start = System.nanoTime();
283337 long remaining = timeout;
@@ -320,7 +374,7 @@
320374 remaining = timeout - Cluster.timeSince(start, unit);
321375 } while (remaining > 0);
322376
323- throw new TimeoutException();
377+ throw new TimeoutException("All connections are busy");
324378 }
325379
326380 public void returnConnection(Connection connection) {
@@ -405,8 +459,13 @@
405459 try {
406460 Connection newConnection = tryResurrectFromTrash();
407461 if (newConnection == null) {
462+ if (!host.convictionPolicy.canReconnectNow()) {
463+ open.decrementAndGet();
464+ return false;
465+ }
408466 logger.debug("Creating new connection on busy pool to {}", host);
409467 newConnection = manager.connectionFactory().open(this);
468+ newConnection.setKeyspace(manager.poolsState.keyspace);
410469 }
411470 connections.add(newConnection);
412471
@@ -469,6 +528,9 @@
469528 }
470529
471530 private void maybeSpawnNewConnection() {
531+ if (!host.convictionPolicy.canReconnectNow())
532+ return;
533+
472534 while (true) {
473535 int inCreation = scheduledForCreation.get();
474536 if (inCreation >= MAX_SIMULTANEOUS_CREATION)
@@ -480,16 +542,15 @@
480542 manager.blockingExecutor().submit(newConnectionTask);
481543 }
482544
483- void replaceDefunctConnection(final Connection connection) {
545+ @Override
546+ public void onConnectionDefunct(final Connection connection) {
484547 if (connection.state.compareAndSet(OPEN, GONE))
485548 open.decrementAndGet();
486- if (connections.remove(connection))
487- manager.blockingExecutor().submit(new Runnable() {
488- @Override
489- public void run() {
490- addConnectionIfUnderMaximum();
491- }
492- });
549+ connections.remove(connection);
550+
551+ // Don't try to replace the connection now. Connection.defunct already signaled the failure,
552+ // and either the host will be marked DOWN (which destroys all pools), or we want to prevent
553+ // new connections for some time
493554 }
494555
495556 void cleanupIdleConnections(long now) {
@@ -608,6 +669,9 @@
608669 if (isClosed())
609670 return;
610671
672+ if (!host.convictionPolicy.canReconnectNow())
673+ return;
674+
611675 // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create
612676 // more connection than maximum (and if we create more than core connection due to a race but this isn't
613677 // justified by the load, the connection in excess will be quickly trashed anyway)
@@ -623,7 +687,11 @@
623687 static class PoolState {
624688 volatile String keyspace;
625689
626- public void setKeyspace(String keyspace) {
690+ PoolState(String keyspace) {
691+ this.keyspace = keyspace;
692+ }
693+
694+ void setKeyspace(String keyspace) {
627695 this.keyspace = keyspace;
628696 }
629697 }
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +48 −24
@@ -37,10 +37,10 @@
3737 private final ReplicationStrategy strategy;
3838 private final Map<String, String> replication;
3939
40- private final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>();
41- private final Map<String, UserType> userTypes = new ConcurrentHashMap<String, UserType>();
40+ final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>();
41+ final Map<String, UserType> userTypes = new ConcurrentHashMap<String, UserType>();
4242 final Map<String, FunctionMetadata> functions = new ConcurrentHashMap<String, FunctionMetadata>();
43- private final Map<String, AggregateMetadata> aggregates = new ConcurrentHashMap<String, AggregateMetadata>();
43+ final Map<String, AggregateMetadata> aggregates = new ConcurrentHashMap<String, AggregateMetadata>();
4444
4545 @VisibleForTesting
4646 KeyspaceMetadata(String name, boolean durableWrites, Map<String, String> replication) {
@@ -50,7 +50,7 @@
5050 this.strategy = ReplicationStrategy.create(replication);
5151 }
5252
53- static KeyspaceMetadata build(Row row, List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
53+ static KeyspaceMetadata build(Row row, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
5454
5555 String name = row.getString(KS_NAME);
5656 boolean durableWrites = row.getBool(DURABLE_WRITES);
@@ -61,11 +61,6 @@
6161
6262 KeyspaceMetadata ksm = new KeyspaceMetadata(name, durableWrites, replicationOptions);
6363
64- if (udtRows == null)
65- return ksm;
66-
67- ksm.addUserTypes(udtRows, protocolVersion, codecRegistry);
68-
6964 return ksm;
7065 }
7166
@@ -108,8 +103,8 @@
108103 return tables.get(Metadata.handleId(name));
109104 }
110105
111- void removeTable(String table) {
112- tables.remove(table);
106+ TableMetadata removeTable(String table) {
107+ return tables.remove(table);
113108 }
114109
115110 /**
@@ -143,15 +138,8 @@
143138 return Collections.unmodifiableCollection(userTypes.values());
144139 }
145140
146- void addUserTypes(List<Row> udtRows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
147- for (Row r : udtRows) {
148- UserType def = UserType.build(r, protocolVersion, codecRegistry);
149- userTypes.put(def.getTypeName(), def);
150- }
151- }
152-
153- void removeUserType(String userType) {
154- userTypes.remove(userType);
141+ UserType removeUserType(String userType) {
142+ return userTypes.remove(userType);
155143 }
156144
157145 /**
@@ -188,8 +176,8 @@
188176 return Collections.unmodifiableCollection(functions.values());
189177 }
190178
191- void removeFunction(String fullName) {
192- functions.remove(fullName);
179+ FunctionMetadata removeFunction(String fullName) {
180+ return functions.remove(fullName);
193181 }
194182
195183 /**
@@ -226,8 +214,8 @@
226214 return Collections.unmodifiableCollection(aggregates.values());
227215 }
228216
229- void removeAggregate(String fullName) {
230- functions.remove(fullName);
217+ AggregateMetadata removeAggregate(String fullName) {
218+ return aggregates.remove(fullName);
231219 }
232220
233221 /**
@@ -293,6 +281,37 @@
293281 return asCQLQuery();
294282 }
295283
284+ @Override
285+ public boolean equals(Object o) {
286+ if (this == o)
287+ return true;
288+ if (o == null || getClass() != o.getClass())
289+ return false;
290+
291+ KeyspaceMetadata that = (KeyspaceMetadata)o;
292+
293+ if (durableWrites != that.durableWrites)
294+ return false;
295+ if (!name.equals(that.name))
296+ return false;
297+ if (strategy != null ? !strategy.equals(that.strategy) : that.strategy != null)
298+ return false;
299+ if (!replication.equals(that.replication))
300+ return false;
301+ return tables.equals(that.tables);
302+
303+ }
304+
305+ @Override
306+ public int hashCode() {
307+ int result = name.hashCode();
308+ result = 31 * result + (durableWrites ? 1 : 0);
309+ result = 31 * result + (strategy != null ? strategy.hashCode() : 0);
310+ result = 31 * result + replication.hashCode();
311+ result = 31 * result + tables.hashCode();
312+ return result;
313+ }
314+
296315 void add(TableMetadata tm) {
297316 tables.put(tm.getName(), tm);
298317 }
@@ -305,7 +324,12 @@
305324 aggregates.put(aggregate.getFullName(), aggregate);
306325 }
307326
327+ void add(UserType type) {
328+ userTypes.put(type.getTypeName(), type);
329+ }
330+
308331 ReplicationStrategy replicationStrategy() {
309332 return strategy;
310333 }
334+
311335 }
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +447 −144
@@ -29,8 +29,6 @@
2929 import org.slf4j.Logger;
3030 import org.slf4j.LoggerFactory;
3131
32-import com.datastax.driver.core.exceptions.DriverInternalError;
33-
3432 import static com.datastax.driver.core.SchemaElement.KEYSPACE;
3533
3634 /**
@@ -55,163 +53,444 @@
5553 }
5654
5755 // Synchronized to make it easy to detect dropped keyspaces
58- synchronized void rebuildSchema(SchemaElement targetType, String targetKeyspace, String targetName,
56+ synchronized void rebuildSchema(SchemaElement targetType, String targetKeyspace, String targetName,
5957 ResultSet ks, ResultSet udts, ResultSet cfs,
60- ResultSet cols, ResultSet functions, ResultSet aggregates,
58+ ResultSet cols, ResultSet functionsRs, ResultSet aggregatesRs,
6159 VersionNumber cassandraVersion) {
62-
63-
64- Map<String, List<Row>> udtDefs = groupByKeyspace(udts);
65- Map<String, List<Row>> cfDefs = groupByKeyspace(cfs);
66- Map<String, List<Row>> functionDefs = groupByKeyspace(functions);
67- Map<String, List<Row>> aggregateDefs = groupByKeyspace(aggregates);
68-
69- // Gather columns per Cf
70- Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
71- if (cols != null) {
72- for (Row row : cols) {
73- String ksName = row.getString(KeyspaceMetadata.KS_NAME);
74- String cfName = row.getString(TableMetadata.CF_NAME);
75- Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = colsDefs.get(ksName);
76- if (colsByCf == null) {
77- colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>();
78- colsDefs.put(ksName, colsByCf);
79- }
80- Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName);
81- if (l == null) {
82- l = new HashMap<String, ColumnMetadata.Raw>();
83- colsByCf.put(cfName, l);
84- }
85- ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
86- l.put(c.name, c);
87- }
88- }
89-
90- if (targetType == null || targetType == KEYSPACE) { // Refresh one or all keyspaces
60+ Map<String, List<Row>> tableRows = groupByKeyspace(cfs);
61+ Map<String, List<Row>> udtRows = groupByKeyspace(udts);
62+ Map<String, List<Row>> functionRows = groupByKeyspace(functionsRs);
63+ Map<String, List<Row>> aggregateRows = groupByKeyspace(aggregatesRs);
64+ Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = groupByKeyspaceAndTable(cols, cassandraVersion);
65+ if (targetType == null || targetType == KEYSPACE) {
66+ // building the whole schema or a keyspace
9167 assert ks != null;
92- Set<String> addedKs = new HashSet<String>();
93- for (Row ksRow : ks) {
94- String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME);
95- KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow, udtDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
96-
97- if (cfDefs.containsKey(ksName)) {
98- buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion);
99- }
100- if (functionDefs.containsKey(ksName)) {
101- buildFunctionMetadata(ksm, functionDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
102- }
103- if (aggregateDefs.containsKey(ksName)) {
104- buildAggregateMetadata(ksm, aggregateDefs.get(ksName), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
105- }
106- addedKs.add(ksName);
107- keyspaces.put(ksName, ksm);
108- }
109-
110- // If keyspace is null, it means we're rebuilding from scratch, so
111- // remove anything that was not just added as it means it's a dropped keyspace
112- if (targetKeyspace == null) {
113- Iterator<String> iter = keyspaces.keySet().iterator();
114- while (iter.hasNext()) {
115- if (!addedKs.contains(iter.next()))
116- iter.remove();
117- }
118- }
68+ Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(ks, tableRows, colsDefs, udtRows, functionRows, aggregateRows, cassandraVersion);
69+ updateKeyspaces(this.keyspaces, keyspaces, targetKeyspace);
11970 } else {
12071 assert targetKeyspace != null;
121- KeyspaceMetadata ksm = keyspaces.get(targetKeyspace);
122-
72+ KeyspaceMetadata keyspace = this.keyspaces.get(targetKeyspace);
12373 // If we update a keyspace we don't know about, something went
124- // wrong. Log an error an schedule a full schema rebuilt.
125- if (ksm == null) {
126- logger.error(String.format("Asked to rebuild %s %s.%s but I don't know keyspace %s", targetType, targetKeyspace, targetName, targetKeyspace));
74+ // wrong. Log an error and schedule a full schema rebuild.
75+ if (keyspace == null) {
76+ logger.info(String.format("Asked to rebuild %s %s.%s but I don't know keyspace %s",
77+ targetType, targetKeyspace, targetName, targetKeyspace));
12778 cluster.submitSchemaRefresh(null, null, null, null);
128- return;
129- }
130-
131- switch (targetType) {
132- case TABLE:
133- if (cfDefs.containsKey(targetKeyspace))
134- buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion);
135- break;
136- case TYPE:
137- if (udtDefs.containsKey(targetKeyspace))
138- ksm.addUserTypes(udtDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
139- break;
140- case FUNCTION:
141- if (functionDefs.containsKey(targetKeyspace))
142- buildFunctionMetadata(ksm, functionDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
143- break;
144- case AGGREGATE:
145- if (functionDefs.containsKey(targetKeyspace))
146- buildAggregateMetadata(ksm, aggregateDefs.get(targetKeyspace), cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
147- break;
148- default:
149- logger.warn("Unexpected element type to rebuild: {}", targetType);
150- }
151- }
152- }
153-
154- private Map<String, List<Row>> groupByKeyspace(ResultSet rs) {
155- if (rs == null)
79+ } else {
80+ switch (targetType) {
81+ case TABLE:
82+ if (tableRows.containsKey(targetKeyspace)) {
83+ Map<String, TableMetadata> tables = buildTables(keyspace, tableRows.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion);
84+ updateTables(keyspace.tables, tables, targetName);
85+ }
86+ break;
87+ case TYPE:
88+ if (udtRows.containsKey(targetKeyspace)) {
89+ Map<String, UserType> userTypes = buildUserTypes(udtRows.get(targetKeyspace));
90+ updateUserTypes(keyspace.userTypes, userTypes, targetName);
91+ }
92+ break;
93+ case FUNCTION:
94+ if (functionRows.containsKey(targetKeyspace)) {
95+ Map<String, FunctionMetadata> functions = buildFunctions(keyspace, functionRows.get(targetKeyspace));
96+ updateFunctions(keyspace.functions, functions, targetName);
97+ }
98+ break;
99+ case AGGREGATE:
100+ if (aggregateRows.containsKey(targetKeyspace)) {
101+ Map<String, AggregateMetadata> aggregates = buildAggregates(keyspace, aggregateRows.get(targetKeyspace));
102+ updateAggregates(keyspace.aggregates, aggregates, targetName);
103+ }
104+ break;
105+ }
106+ }
107+ }
108+ }
109+
110+ private Map<String, List<Row>> groupByKeyspace(ResultSet rows) {
111+ if (rows == null)
156112 return Collections.emptyMap();
157113
158- Map<String, List<Row>> result = new HashMap<String, List<Row>>();
159- for (Row row : rs) {
114+ Map<String, List<Row>> groupedRows = new HashMap<String, List<Row>>();
115+ for (Row row : rows) {
160116 String ksName = row.getString(KeyspaceMetadata.KS_NAME);
161- List<Row> l = result.get(ksName);
117+ List<Row> l = groupedRows.get(ksName);
162118 if (l == null) {
163119 l = new ArrayList<Row>();
164- result.put(ksName, l);
120+ groupedRows.put(ksName, l);
165121 }
166122 l.add(row);
167123 }
168- return result;
169- }
170-
171- private void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) {
172- for (Row cfRow : cfRows) {
173- String cfName = cfRow.getString(TableMetadata.CF_NAME);
174- try {
175- Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName);
176- if (cols == null || cols.isEmpty()) {
177- if (cassandraVersion.getMajor() >= 2) {
178- // In C* >= 2.0, we should never have no columns metadata because at the very least we should
179- // have the metadata corresponding to the default CQL metadata. So if we don't have any columns,
180- // that can only mean that the table got creating concurrently with our schema queries, and the
181- // query for columns metadata reached the node before the table was persisted while the table
182- // metadata one reached it afterwards. We could make the query to the column metadata sequential
183- // with the table metadata instead of in parallel, but it's probably not worth making it slower
184- // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the
185- // incomplete table here for now and it'll get updated next time with no particular consequence
186- // (if the table creation was concurrent with our querying, we'll get a notifciation later and
187- // will reupdate the schema for it anyway). See JAVA-320 for why we need this.
188- continue;
189- } else {
190- // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thirft
191- // tables). But in that case TableMetadata.build() knows how to handle it.
192- cols = Collections.<String, ColumnMetadata.Raw>emptyMap();
124+ return groupedRows;
125+ }
126+
127+ private Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndTable(ResultSet rows, VersionNumber cassandraVersion) {
128+ if (rows == null)
129+ return Collections.emptyMap();
130+
131+ ProtocolVersion protocolVersion = cluster.protocolVersion();
132+ CodecRegistry codecRegistry = cluster.configuration.getCodecRegistry();
133+
134+ Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupedRows = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>();
135+ for (Row row : rows) {
136+ String ksName = row.getString(KeyspaceMetadata.KS_NAME);
137+ String cfName = row.getString(TableMetadata.CF_NAME);
138+ Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = groupedRows.get(ksName);
139+ if (colsByCf == null) {
140+ colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>();
141+ groupedRows.put(ksName, colsByCf);
142+ }
143+ Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName);
144+ if (l == null) {
145+ l = new HashMap<String, ColumnMetadata.Raw>();
146+ colsByCf.put(cfName, l);
147+ }
148+ ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion, protocolVersion, codecRegistry);
149+ l.put(c.name, c);
150+ }
151+ return groupedRows;
152+ }
153+
154+ private Map<String, KeyspaceMetadata> buildKeyspaces(ResultSet keyspaceRows,
155+ Map<String, List<Row>> tableRows,
156+ Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs,
157+ Map<String, List<Row>> udtRows,
158+ Map<String, List<Row>> functionRows,
159+ Map<String, List<Row>> aggregateRows,
160+ VersionNumber cassandraVersion) {
161+ ProtocolVersion protocolVersion = cluster.protocolVersion();
162+ CodecRegistry codecRegistry = cluster.configuration.getCodecRegistry();
163+
164+ Map<String, KeyspaceMetadata> keyspaces = new LinkedHashMap<String, KeyspaceMetadata>();
165+ for (Row keyspaceRow : keyspaceRows) {
166+ KeyspaceMetadata keyspace = KeyspaceMetadata.build(keyspaceRow, protocolVersion, codecRegistry);
167+ Map<String, TableMetadata> tables = buildTables(keyspace, tableRows.get(keyspace.getName()), colsDefs.get(keyspace.getName()), cassandraVersion);
168+ for (TableMetadata table : tables.values()) {
169+ keyspace.add(table);
170+ }
171+ Map<String, UserType> userTypes = buildUserTypes(udtRows.get(keyspace.getName()));
172+ for (UserType userType : userTypes.values()) {
173+ keyspace.add(userType);
174+ }
175+ Map<String, FunctionMetadata> functions = buildFunctions(keyspace, functionRows.get(keyspace.getName()));
176+ for (FunctionMetadata function : functions.values()) {
177+ keyspace.add(function);
178+ }
179+ Map<String, AggregateMetadata> aggregates = buildAggregates(keyspace, aggregateRows.get(keyspace.getName()));
180+ for (AggregateMetadata aggregate : aggregates.values()) {
181+ keyspace.add(aggregate);
182+ }
183+ keyspaces.put(keyspace.getName(), keyspace);
184+ }
185+ return keyspaces;
186+ }
187+
188+ private Map<String, TableMetadata> buildTables(KeyspaceMetadata keyspace, List<Row> tableRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) {
189+ Map<String, TableMetadata> tables = new LinkedHashMap<String, TableMetadata>();
190+ if (tableRows != null) {
191+ ProtocolVersion protocolVersion = cluster.protocolVersion();
192+ CodecRegistry codecRegistry = cluster.configuration.getCodecRegistry();
193+
194+ for (Row tableDef : tableRows) {
195+ String cfName = tableDef.getString(TableMetadata.CF_NAME);
196+ try {
197+ Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName);
198+ if (cols == null || cols.isEmpty()) {
199+ if (cassandraVersion.getMajor() >= 2) {
200+ // In C* >= 2.0, we should never have no columns metadata because at the very least we should
201+ // have the metadata corresponding to the default CQL metadata. So if we don't have any columns,
202+ // that can only mean that the table got creating concurrently with our schema queries, and the
203+ // query for columns metadata reached the node before the table was persisted while the table
204+ // metadata one reached it afterwards. We could make the query to the column metadata sequential
205+ // with the table metadata instead of in parallel, but it's probably not worth making it slower
206+ // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the
207+ // incomplete table here for now and it'll get updated next time with no particular consequence
208+ // (if the table creation was concurrent with our querying, we'll get a notifciation later and
209+ // will reupdate the schema for it anyway). See JAVA-320 for why we need this.
210+ continue;
211+ } else {
212+ // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thirft
213+ // tables). But in that case TableMetadata.build() knows how to handle it.
214+ cols = Collections.emptyMap();
215+ }
193216 }
217+ TableMetadata table = TableMetadata.build(keyspace, tableDef, cols, cassandraVersion, protocolVersion, codecRegistry);
218+ tables.put(table.getName(), table);
219+ } catch (RuntimeException e) {
220+ // See ControlConnection#refreshSchema for why we'd rather not probably this further
221+ logger.error(String.format("Error parsing schema for table %s.%s: "
222+ + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
223+ keyspace.getName(), cfName, keyspace.getName(), cfName), e);
194224 }
195- TableMetadata.build(ksm, cfRow, cols, cassandraVersion, cluster.protocolVersion(), cluster.configuration.getCodecRegistry());
196- } catch (RuntimeException e) {
197- // See ControlConnection#refreshSchema for why we'd rather not probably this further
198- logger.error(String.format("Error parsing schema for table %s.%s: "
199- + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete",
200- ksm.getName(), cfName, ksm.getName(), cfName), e);
201225 }
202226 }
227+ return tables;
228+ }
229+
230+ private Map<String, UserType> buildUserTypes(List<Row> udtRows) {
231+ Map<String, UserType> userTypes = new LinkedHashMap<String, UserType>();
232+ if (udtRows != null) {
233+ ProtocolVersion protocolVersion = cluster.protocolVersion();
234+ CodecRegistry codecRegistry = cluster.configuration.getCodecRegistry();
235+ for (Row udtRow : udtRows) {
236+ UserType type = UserType.build(udtRow, protocolVersion, codecRegistry);
237+ userTypes.put(type.getTypeName(), type);
238+ }
239+ }
240+ return userTypes;
241+ }
242+
243+ private Map<String, FunctionMetadata> buildFunctions(KeyspaceMetadata keyspace, List<Row> functionRows) {
244+ Map<String, FunctionMetadata> functions = new LinkedHashMap<String, FunctionMetadata>();
245+ if (functionRows != null) {
246+ ProtocolVersion protocolVersion = cluster.protocolVersion();
247+ CodecRegistry codecRegistry = cluster.configuration.getCodecRegistry();
248+ for (Row functionRow : functionRows) {
249+ FunctionMetadata function = FunctionMetadata.build(keyspace, functionRow, protocolVersion, codecRegistry);
250+ if (function != null)
251+ functions.put(function.getFullName(), function);
252+ }
253+ }
254+ return functions;
255+ }
256+
257+ private Map<String, AggregateMetadata> buildAggregates(KeyspaceMetadata keyspace, List<Row> aggregateRows) {
258+ Map<String, AggregateMetadata> aggregates = new LinkedHashMap<String, AggregateMetadata>();
259+ if (aggregateRows != null) {
260+ ProtocolVersion protocolVersion = cluster.protocolVersion();
261+ CodecRegistry codecRegistry = cluster.configuration.getCodecRegistry();
262+ for (Row aggregateRow : aggregateRows) {
263+ AggregateMetadata aggregate = AggregateMetadata.build(keyspace, aggregateRow, protocolVersion, codecRegistry);
264+ if (aggregate != null)
265+ aggregates.put(aggregate.getFullName(), aggregate);
266+ }
267+ }
268+ return aggregates;
269+ }
270+
271+ /**
272+ * Update {@code oldKeyspaces} with the changes contained in {@code newKeyspaces}.
273+ * This method also takes care of triggering the relevant events
274+ * as the updates take place.
275+ *
276+ * @param oldKeyspaces the set of keyspaces to be updated.
277+ * @param newKeyspaces the temporary set of keyspaces built with information gathered
278+ * from schema tables.
279+ * @param keyspaceToRebuild If we are rebuilding just one keyspace, the update operation will be limited
280+ * to this keyspace only (in which case {@code newKeyspaces} shoudl contain only one entry for it)
281+ */
282+ private void updateKeyspaces(Map<String, KeyspaceMetadata> oldKeyspaces, Map<String, KeyspaceMetadata> newKeyspaces, String keyspaceToRebuild) {
283+ Iterator<KeyspaceMetadata> it = oldKeyspaces.values().iterator();
284+ while (it.hasNext()) {
285+ KeyspaceMetadata oldKeyspace = it.next();
286+ String keyspaceName = oldKeyspace.getName();
287+ // If we're rebuilding only a single keyspace, we should only consider that one
288+ // because newKeyspaces will only contain that keyspace.
289+ if ((keyspaceToRebuild == null || keyspaceToRebuild.equals(keyspaceName)) && !newKeyspaces.containsKey(keyspaceName)) {
290+ it.remove();
291+ triggerOnKeyspaceRemoved(oldKeyspace);
292+ }
293+ }
294+ for (KeyspaceMetadata newKeyspace : newKeyspaces.values()) {
295+ KeyspaceMetadata oldKeyspace = oldKeyspaces.put(newKeyspace.getName(), newKeyspace);
296+ if (oldKeyspace == null) {
297+ triggerOnKeyspaceAdded(newKeyspace);
298+ } else if (!oldKeyspace.equals(newKeyspace)) {
299+ triggerOnKeyspaceChanged(newKeyspace, oldKeyspace);
300+ }
301+ Map<String, TableMetadata> oldTables = oldKeyspace == null ? new HashMap<String, TableMetadata>() : oldKeyspace.tables;
302+ updateTables(oldTables, newKeyspace.tables, null);
303+ Map<String, UserType> oldTypes = oldKeyspace == null ? new HashMap<String, UserType>() : oldKeyspace.userTypes;
304+ updateUserTypes(oldTypes, newKeyspace.userTypes, null);
305+ Map<String, FunctionMetadata> oldFunctions = oldKeyspace == null ? new HashMap<String, FunctionMetadata>() : oldKeyspace.functions;
306+ updateFunctions(oldFunctions, newKeyspace.functions, null);
307+ Map<String, AggregateMetadata> oldAggregates = oldKeyspace == null ? new HashMap<String, AggregateMetadata>() : oldKeyspace.aggregates;
308+ updateAggregates(oldAggregates, newKeyspace.aggregates, null);
309+ }
310+ }
311+
312+ /**
313+ * Update {@code oldTables} with the changes contained in {@code newTables}.
314+ * This method also takes care of triggering the relevant events
315+ * as the updates take place.
316+ *
317+ * @param oldTables the set of tables to be updated.
318+ * @param newTables the temporary set of tables built with information gathered
319+ * from schema tables.
320+ * @param tableToRebuild If we are rebuilding just one table, the update operation will be limited
321+ * to this table only (in which case {@code newTables} shoudl contain only one entry for it)
322+ */
323+ private void updateTables(Map<String, TableMetadata> oldTables, Map<String, TableMetadata> newTables, String tableToRebuild) {
324+ Iterator<TableMetadata> it = oldTables.values().iterator();
325+ while (it.hasNext()) {
326+ TableMetadata oldTable = it.next();
327+ String tableName = oldTable.getName();
328+ // If we're rebuilding only a single table, we should only consider that one
329+ // because newTables will only contain that table.
330+ if ((tableToRebuild == null || tableToRebuild.equals(tableName)) && !newTables.containsKey(tableName)) {
331+ it.remove();
332+ triggerOnTableRemoved(oldTable);
333+ }
334+ }
335+ for (TableMetadata newTable : newTables.values()) {
336+ TableMetadata oldTable = oldTables.put(newTable.getName(), newTable);
337+ if (oldTable == null) {
338+ triggerOnTableAdded(newTable);
339+ } else if (!oldTable.equals(newTable)) {
340+ triggerOnTableChanged(newTable, oldTable);
341+ }
342+ }
343+ }
344+
345+ private void updateUserTypes(Map<String, UserType> oldTypes, Map<String, UserType> newTypes, String typeToRebuild) {
346+ Iterator<UserType> it = oldTypes.values().iterator();
347+ while (it.hasNext()) {
348+ UserType oldType = it.next();
349+ String typeName = oldType.getTypeName();
350+ if ((typeToRebuild == null || typeToRebuild.equals(typeName)) && !newTypes.containsKey(typeName)) {
351+ it.remove();
352+ triggerOnUserTypeRemoved(oldType);
353+ }
354+ }
355+ for (UserType newType : newTypes.values()) {
356+ UserType oldType = oldTypes.put(newType.getTypeName(), newType);
357+ if (oldType == null) {
358+ triggerOnUserTypeAdded(newType);
359+ } else if (!newType.equals(oldType)) {
360+ triggerOnUserTypeChanged(newType, oldType);
361+ }
362+ }
363+ }
364+
365+ private void updateFunctions(Map<String, FunctionMetadata> oldFunctions, Map<String, FunctionMetadata> newFunctions, String functionToRebuild) {
366+ Iterator<FunctionMetadata> it = oldFunctions.values().iterator();
367+ while (it.hasNext()) {
368+ FunctionMetadata oldFunction = it.next();
369+ String functionName = oldFunction.getFullName();
370+ if ((functionToRebuild == null || functionToRebuild.equals(functionName)) && !newFunctions.containsKey(functionName)) {
371+ it.remove();
372+ triggerOnFunctionRemoved(oldFunction);
373+ }
374+ }
375+ for (FunctionMetadata newFunction : newFunctions.values()) {
376+ FunctionMetadata oldFunction = oldFunctions.put(newFunction.getFullName(), newFunction);
377+ if (oldFunction == null) {
378+ triggerOnFunctionAdded(newFunction);
379+ } else if (!newFunction.equals(oldFunction)) {
380+ triggerOnFunctionChanged(newFunction, oldFunction);
381+ }
382+ }
383+ }
384+
385+ private void updateAggregates(Map<String, AggregateMetadata> oldAggregates, Map<String, AggregateMetadata> newAggregates, String aggregateToRebuild) {
386+ Iterator<AggregateMetadata> it = oldAggregates.values().iterator();
387+ while (it.hasNext()) {
388+ AggregateMetadata oldAggregate = it.next();
389+ String aggregateName = oldAggregate.getFullName();
390+ if ((aggregateToRebuild == null || aggregateToRebuild.equals(aggregateName)) && !newAggregates.containsKey(aggregateName)) {
391+ it.remove();
392+ triggerOnAggregateRemoved(oldAggregate);
393+ }
394+ }
395+ for (AggregateMetadata newAggregate : newAggregates.values()) {
396+ AggregateMetadata oldAggregate = oldAggregates.put(newAggregate.getFullName(), newAggregate);
397+ if (oldAggregate == null) {
398+ triggerOnAggregateAdded(newAggregate);
399+ } else if (!newAggregate.equals(oldAggregate)) {
400+ triggerOnAggregateChanged(newAggregate, oldAggregate);
401+ }
402+ }
403+ }
404+
405+ void triggerOnKeyspaceAdded(KeyspaceMetadata keyspace) {
406+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
407+ listener.onKeyspaceAdded(keyspace);
408+ }
409+ }
410+
411+ void triggerOnKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous) {
412+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
413+ listener.onKeyspaceChanged(current, previous);
414+ }
415+ }
416+
417+ void triggerOnKeyspaceRemoved(KeyspaceMetadata keyspace) {
418+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
419+ listener.onKeyspaceRemoved(keyspace);
420+ }
421+ }
422+
423+ void triggerOnTableAdded(TableMetadata table) {
424+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
425+ listener.onTableAdded(table);
426+ }
427+ }
428+
429+ void triggerOnTableChanged(TableMetadata current, TableMetadata previous) {
430+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
431+ listener.onTableChanged(current, previous);
432+ }
433+ }
434+
435+ void triggerOnTableRemoved(TableMetadata table) {
436+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
437+ listener.onTableRemoved(table);
438+ }
439+ }
440+
441+ void triggerOnUserTypeAdded(UserType type) {
442+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
443+ listener.onUserTypeAdded(type);
444+ }
445+ }
446+
447+ void triggerOnUserTypeChanged(UserType current, UserType previous) {
448+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
449+ listener.onUserTypeChanged(current, previous);
450+ }
451+ }
452+
453+ void triggerOnUserTypeRemoved(UserType type) {
454+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
455+ listener.onUserTypeRemoved(type);
456+ }
203457 }
204458
205- private void buildFunctionMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
206- for (Row row : rows)
207- FunctionMetadata.build(ksm, row, protocolVersion, codecRegistry);
459+ void triggerOnFunctionAdded(FunctionMetadata function) {
460+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
461+ listener.onFunctionAdded(function);
462+ }
463+ }
464+
465+ void triggerOnFunctionChanged(FunctionMetadata current, FunctionMetadata previous) {
466+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
467+ listener.onFunctionChanged(current, previous);
468+ }
469+ }
470+
471+ void triggerOnFunctionRemoved(FunctionMetadata function) {
472+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
473+ listener.onFunctionRemoved(function);
474+ }
475+ }
476+
477+ void triggerOnAggregateAdded(AggregateMetadata aggregate) {
478+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
479+ listener.onAggregateAdded(aggregate);
480+ }
208481 }
209482
210- private void buildAggregateMetadata(KeyspaceMetadata ksm, List<Row> rows, ProtocolVersion protocolVersion, CodecRegistry codecRegistry) {
211- for (Row row : rows)
212- AggregateMetadata.build(ksm, row, protocolVersion, codecRegistry);
483+ void triggerOnAggregateChanged(AggregateMetadata current, AggregateMetadata previous) {
484+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
485+ listener.onAggregateChanged(current, previous);
486+ }
213487 }
214488
489+ void triggerOnAggregateRemoved(AggregateMetadata aggregate) {
490+ for (SchemaChangeListener listener : cluster.schemaChangeListeners) {
491+ listener.onAggregateRemoved(aggregate);
492+ }
493+ }
215494
216495 synchronized void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) {
217496 if (allTokens.isEmpty())
@@ -306,7 +585,8 @@
306585 * connection, when schema or ring topology changes. It might occasionally
307586 * be stale.
308587 *
309- * @return the token ranges.
588+ * @return the token ranges. Note that the result might be stale or empty if
589+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
310590 */
311591 public Set<TokenRange> getTokenRanges() {
312592 TokenMap current = tokenMap;
@@ -324,7 +604,8 @@
324604 * @param keyspace the name of the keyspace to get token ranges for.
325605 * @param host the host.
326606 * @return the (immutable) set of token ranges for {@code host} as known
327- * by the driver.
607+ * by the driver. Note that the result might be stale or empty if metadata
608+ * was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
328609 */
329610 public Set<TokenRange> getTokenRanges(String keyspace, Host host) {
330611 keyspace = handleId(keyspace);
@@ -353,7 +634,8 @@
353634 * @param partitionKey the partition key for which to find the set of
354635 * replica.
355636 * @return the (immutable) set of replicas for {@code partitionKey} as known
356- * by the driver.
637+ * by the driver. Note that the result might be stale or empty if metadata was
638+ * explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
357639 */
358640 public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) {
359641 keyspace = handleId(keyspace);
@@ -376,6 +658,8 @@
376658 * @param keyspace the name of the keyspace to get replicas for.
377659 * @param range the token range.
378660 * @return the (immutable) set of replicas for {@code range} as known by the driver.
661+ * Note that the result might be stale or empty if metadata was explicitly disabled
662+ * with {@link QueryOptions#setMetadataEnabled(boolean)}.
379663 */
380664 public Set<Host> getReplicas(String keyspace, TokenRange range) {
381665 keyspace = handleId(keyspace);
@@ -425,7 +709,12 @@
425709 * (for example, if the control connection is down).
426710 */
427711 public boolean checkSchemaAgreement() {
428- return cluster.controlConnection.checkSchemaAgreement();
712+ try {
713+ return cluster.controlConnection.checkSchemaAgreement();
714+ } catch (Exception e) {
715+ logger.warn("Error while checking schema agreement", e);
716+ return false;
717+ }
429718 }
430719
431720 /**
@@ -434,7 +723,8 @@
434723 * @param keyspace the name of the keyspace for which metadata should be
435724 * returned.
436725 * @return the metadata of the requested keyspace or {@code null} if {@code
437- * keyspace} is not a known keyspace.
726+ * keyspace} is not a known keyspace. Note that the result might be stale or null if
727+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
438728 */
439729 public KeyspaceMetadata getKeyspace(String keyspace) {
440730 return keyspaces.get(handleId(keyspace));
@@ -448,16 +738,18 @@
448738 return keyspaces.get(keyspace);
449739 }
450740
451- void removeKeyspace(String keyspace) {
452- keyspaces.remove(keyspace);
741+ KeyspaceMetadata removeKeyspace(String keyspace) {
742+ KeyspaceMetadata removed = keyspaces.remove(keyspace);
453743 if (tokenMap != null)
454744 tokenMap.tokenToHosts.remove(keyspace);
745+ return removed;
455746 }
456747
457748 /**
458749 * Returns a list of all the defined keyspaces.
459750 *
460- * @return a list of all the defined keyspaces.
751+ * @return a list of all the defined keyspaces. Note that the result might be stale or empty if
752+ * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}.
461753 */
462754 public List<KeyspaceMetadata> getKeyspaces() {
463755 return new ArrayList<KeyspaceMetadata>(keyspaces.values());
@@ -473,6 +765,9 @@
473765 * Note that the returned String is formatted to be human readable (for
474766 * some definition of human readable at least).
475767 *
768+ * It might be stale or empty if metadata was explicitly disabled with
769+ * {@link QueryOptions#setMetadataEnabled(boolean)}.
770+ *
476771 * @return the CQL queries representing this cluster schema as a {code
477772 * String}.
478773 */
@@ -501,11 +796,15 @@
501796 *
502797 * @param tokenStr the string representation.
503798 * @return the token.
799+ *
800+ * @throws IllegalStateException if the token factory was not initialized. This would typically
801+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
802+ * before startup.
504803 */
505804 public Token newToken(String tokenStr) {
506805 TokenMap current = tokenMap;
507806 if (current == null)
508- throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
807+ throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled");
509808
510809 return current.factory.fromString(tokenStr);
511810 }
@@ -516,11 +815,15 @@
516815 * @param start the start token.
517816 * @param end the end token.
518817 * @return the range.
818+ *
819+ * @throws IllegalStateException if the token factory was not initialized. This would typically
820+ * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}
821+ * before startup.
519822 */
520823 public TokenRange newTokenRange(Token start, Token end) {
521824 TokenMap current = tokenMap;
522825 if (current == null)
523- throw new DriverInternalError("Token factory not set. This should only happen at initialization time");
826+ throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled");
524827
525828 return new TokenRange(start, end, current.factory);
526829 }
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +44 −1
@@ -21,13 +21,14 @@
2121 import static java.util.concurrent.TimeUnit.SECONDS;
2222
2323 import io.netty.bootstrap.Bootstrap;
24-import io.netty.buffer.ByteBufAllocator;
2524 import io.netty.buffer.PooledByteBufAllocator;
2625 import io.netty.channel.ChannelOption;
2726 import io.netty.channel.EventLoopGroup;
2827 import io.netty.channel.nio.NioEventLoopGroup;
2928 import io.netty.channel.socket.SocketChannel;
3029 import io.netty.channel.socket.nio.NioSocketChannel;
30+import io.netty.util.HashedWheelTimer;
31+import io.netty.util.Timer;
3132
3233 /**
3334 * A set of hooks that allow clients to customize the driver's underlying Netty layer.
@@ -199,4 +200,46 @@
199200 // it is safe to reduce the quiet period to 0 seconds
200201 eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly();
201202 }
203+
204+ /**
205+ * Return the {@link Timer} instance used by Read Timeouts and Speculative Execution.
206+ * <p>
207+ * This hook is invoked only once at {@link Cluster} initialization;
208+ * the returned instance will be kept in use throughout the cluster lifecycle.
209+ * <p>
210+ * Typically, implementors would return a newly-created instance;
211+ * it is however possible to re-use a shared instance, but in this
212+ * case implementors should also override {@link #onClusterClose(Timer)}
213+ * to prevent the shared instance to be closed when the cluster is closed.
214+ * <p>
215+ * The default implementation returns a new instance created by {@link HashedWheelTimer#HashedWheelTimer(ThreadFactory)}.
216+ *
217+ * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link HashedWheelTimer} instance;
218+ * The driver will provide its own internal thread factory here.
219+ * It is safe to ignore it and use another thread factory.
220+ * @return the {@link Timer} instance to use.
221+ */
222+ public Timer timer(ThreadFactory threadFactory) {
223+ return new HashedWheelTimer(threadFactory);
224+ }
225+
226+ /**
227+ * Hook invoked when the cluster is shutting down after a call to {@link Cluster#close()}.
228+ * <p>
229+ * This is guaranteed to be called only after all connections have been individually
230+ * closed, and their channels closed, and only once per {@link Timer} instance.
231+ * <p>
232+ * This gives the implementor a chance to close the {@link Timer} properly, if required.
233+ * <p>
234+ * The default implementation calls a {@link Timer#stop()} of the passed {@link Timer} instance.
235+ * <p>
236+ * Implementation note: if the {@link Timer} instance is being shared, or used for other purposes than to
237+ * schedule actions for the current cluster, than it should not be stopped here;
238+ * subclasses would have to override this method accordingly to take the appropriate action.
239+ *
240+ * @param timer the timer used by the cluster being closed
241+ */
242+ public void onClusterClose(Timer timer) {
243+ timer.stop();
244+ }
202245 }
modified driver-core/src/main/java/com/datastax/driver/core/PlainTextAuthProvider.java +25 −4
@@ -15,7 +15,6 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import javax.security.sasl.SaslException;
1918 import java.net.InetSocketAddress;
2019 import java.util.Map;
2120
@@ -28,13 +27,13 @@
2827 * This provider allows to programmatically define authentication
2928 * information that will then apply to all hosts. The
3029 * PlainTextAuthenticator instances it returns support SASL
31- * authentication using the PLAIN mechanism for version 2 of the
30+ * authentication using the PLAIN mechanism for version 2 (or above) of the
3231 * CQL native protocol.
3332 */
3433 public class PlainTextAuthProvider implements AuthProvider {
3534
36- private final String username;
37- private final String password;
35+ private volatile String username;
36+ private volatile String password;
3837
3938 /**
4039 * Creates a new simple authentication information provider with the
@@ -47,6 +46,28 @@
4746 this.password = password;
4847 }
4948
49+ /**
50+ * Changes the user name.
51+ *
52+ * The new credentials will be used for all connections initiated after this method was called.
53+ *
54+ * @param username the new name.
55+ */
56+ public void setUsername(String username) {
57+ this.username = username;
58+ }
59+
60+ /**
61+ * Changes the password.
62+ *
63+ * The new credentials will be used for all connections initiated after this method was called.
64+ *
65+ * @param password the new password.
66+ */
67+ public void setPassword(String password) {
68+ this.password = password;
69+ }
70+
5071 /**
5172 * Uses the supplied credentials and the SASL PLAIN mechanism to login
5273 * to the server.
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +4 −0
@@ -485,6 +485,10 @@
485485 * Requests the driver to re-evaluate the {@link HostDistance} (through the configured
486486 * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known
487487 * hosts and to drop/add connections to each hosts according to the computed distance.
488+ * <p>
489+ * Note that, due to backward compatibility issues, this method is not interruptible. If the
490+ * caller thread gets interrupted, the method will complete and only then re-interrupt the
491+ * thread (which you can check with {@code Thread.currentThread().isInterrupted()}).
488492 */
489493 public void refreshConnectedHosts() {
490494 manager.refreshConnectedHosts();
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java +10 −2
@@ -17,8 +17,16 @@
1717
1818 import java.util.Map;
1919
20-// Not an interface because we don't want to expose it. We only support password authentication
21-// for the protocol V1 similarly to what the driver 1.x branch do.
20+/**
21+ * Parent class for {@link Authenticator} implementations that support native protocol v1 authentication.
22+ *
23+ * Protocol v1 uses simple, credentials-based authentication (as opposed to SASL for later protocol versions).
24+ * In order to support protocol v1, an authenticator must extend this class.
25+ *
26+ * We use an abstract class instead of an interface because we don't want to expose {@link #getCredentials()}.
27+ *
28+ * @see <a href="https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v1.spec">Native protocol v1 specification</a>
29+ */
2230 abstract class ProtocolV1Authenticator {
2331 abstract Map<String, String> getCredentials();
2432 }
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +304 −0
@@ -42,11 +42,36 @@
4242 */
4343 public static final boolean DEFAULT_IDEMPOTENCE = false;
4444
45+ public static final int DEFAULT_MAX_PENDING_REFRESH_NODE_LIST_REQUESTS = 20;
46+
47+ public static final int DEFAULT_MAX_PENDING_REFRESH_NODE_REQUESTS = 20;
48+
49+ public static final int DEFAULT_MAX_PENDING_REFRESH_SCHEMA_REQUESTS = 20;
50+
51+ public static final int DEFAULT_REFRESH_NODE_LIST_INTERVAL_MILLIS = 1000;
52+
53+ public static final int DEFAULT_REFRESH_NODE_INTERVAL_MILLIS = 1000;
54+
55+ public static final int DEFAULT_REFRESH_SCHEMA_INTERVAL_MILLIS = 1000;
56+
4557 private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL;
4658 private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL;
4759 private volatile int fetchSize = DEFAULT_FETCH_SIZE;
4860 private volatile boolean defaultIdempotence = DEFAULT_IDEMPOTENCE;
61+
62+ private volatile boolean metadataEnabled = true;
63+
64+ private volatile int maxPendingRefreshNodeListRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_LIST_REQUESTS;
65+ private volatile int maxPendingRefreshNodeRequests = DEFAULT_MAX_PENDING_REFRESH_NODE_REQUESTS;
66+ private volatile int maxPendingRefreshSchemaRequests = DEFAULT_MAX_PENDING_REFRESH_SCHEMA_REQUESTS;
67+
68+ private volatile int refreshNodeListIntervalMillis = DEFAULT_REFRESH_NODE_LIST_INTERVAL_MILLIS;
69+ private volatile int refreshNodeIntervalMillis = DEFAULT_REFRESH_NODE_INTERVAL_MILLIS;
70+ private volatile int refreshSchemaIntervalMillis = DEFAULT_REFRESH_SCHEMA_INTERVAL_MILLIS;
71+
72+ private volatile boolean reprepareOnUp = true;
4973 private volatile Cluster.Manager manager;
74+ private volatile boolean prepareOnAllHosts = true;
5075
5176 /**
5277 * Creates a new {@link QueryOptions} instance using the {@link #DEFAULT_CONSISTENCY_LEVEL},
@@ -169,4 +194,283 @@
169194 public boolean getDefaultIdempotence() {
170195 return defaultIdempotence;
171196 }
197+
198+ /**
199+ * Set whether the driver should prepare statements on all hosts in the cluster.
200+ * <p>
201+ * A statement is normally prepared in two steps:
202+ * <ol>
203+ * <li>prepare the query on a single host in the cluster;</li>
204+ * <li>if that succeeds, prepare on all other hosts.</li>
205+ * </ol>
206+ * This option controls whether step 2 is executed. It is enabled by default.
207+ * <p>
208+ * The reason why you might want to disable it is to optimize network usage if you
209+ * have a large number of clients preparing the same set of statements at startup.
210+ * If your load balancing policy distributes queries randomly, each client will pick
211+ * a different host to prepare its statements, and on the whole each host has a good
212+ * chance of having been hit by at least one client for each statement.
213+ * <p>
214+ * On the other hand, if that assumption turns out to be wrong and one host hasn't
215+ * prepared a given statement, it needs to be re-prepared on the fly the first time
216+ * it gets executed; this causes a performance penalty (one extra roundtrip to resend
217+ * the query to prepare, and another to retry the execution).
218+ *
219+ * @param prepareOnAllHosts the new value to set to indicate whether to prepare
220+ * statements once or on all nodes.
221+ * @return this {@code QueryOptions} instance.
222+ */
223+ public QueryOptions setPrepareOnAllHosts(boolean prepareOnAllHosts) {
224+ this.prepareOnAllHosts = prepareOnAllHosts;
225+ return this;
226+ }
227+
228+ /**
229+ * Returns whether the driver should prepare statements on all hosts in the cluster.
230+ *
231+ * @return the value.
232+ *
233+ * @see #setPrepareOnAllHosts(boolean)
234+ */
235+ public boolean isPrepareOnAllHosts() {
236+ return this.prepareOnAllHosts;
237+ }
238+
239+ /**
240+ * Set whether the driver should re-prepare all cached prepared statements on a host
241+ * when it marks it back up.
242+ * <p>
243+ * This option is enabled by default.
244+ * <p>
245+ * The reason why you might want to disable it is to optimize reconnection time when
246+ * you believe hosts often get marked down because of temporary network issues, rather
247+ * than the host really crashing. In that case, the host still has prepared statements
248+ * in its cache when the driver reconnects, so re-preparing is redundant.
249+ * <p>
250+ * On the other hand, if that assumption turns out to be wrong and the host had
251+ * really restarted, its prepared statement cache is empty, and statements need to be
252+ * re-prepared on the fly the first time they get executed; this causes a performance
253+ * penalty (one extra roundtrip to resend the query to prepare, and another to retry
254+ * the execution).
255+ *
256+ * @param reprepareOnUp whether the driver should re-prepare when marking a node up.
257+ * @return this {@code QueryOptions} instance.
258+ */
259+ public QueryOptions setReprepareOnUp(boolean reprepareOnUp){
260+ this.reprepareOnUp = reprepareOnUp;
261+ return this;
262+ }
263+
264+ /**
265+ * Whether the driver should re-prepare all cached prepared statements on a host
266+ * when its marks that host back up.
267+ *
268+ * @return the value.
269+ *
270+ * @see #setReprepareOnUp(boolean)
271+ */
272+ public boolean isReprepareOnUp() {
273+ return this.reprepareOnUp;
274+ }
275+
276+ /**
277+ * Toggle client-side token and schema metadata.
278+ * <p>
279+ * This feature is enabled by default. Some applications might wish to disable it
280+ * in order to eliminate the overhead of querying the metadata and building its
281+ * client-side representation. However, take note that doing so will have important
282+ * consequences:
283+ * <ul>
284+ * <li>most schema- or token-related methods in {@link Metadata} will return stale
285+ * or null/empty results (see the javadoc of each method for details);</li>
286+ * <li>{@link Metadata#newToken(String)} and
287+ * {@link Metadata#newTokenRange(Token, Token)} will throw an exception if metadata
288+ * was disabled before startup;</li>
289+ * <li>token-aware routing will not work properly: if metadata was never initialized,
290+ * {@link com.datastax.driver.core.policies.TokenAwarePolicy} will always delegate
291+ * to its child policy. Otherwise, it might not pick the best coordinator (i.e. chose
292+ * a host that is not a replica for the statement's routing key). In addition, statements
293+ * prepared while the metadata was disabled might also be sent to a non-optimal coordinator,
294+ * even if metadata was re-enabled later.</li>
295+ * </ul>
296+ *
297+ * @param enabled whether metadata is enabled.
298+ * @return this {@code QueryOptions} instance.
299+ */
300+ public QueryOptions setMetadataEnabled(boolean enabled) {
301+ boolean wasEnabled = this.metadataEnabled;
302+ this.metadataEnabled = enabled;
303+ if (!wasEnabled && enabled && manager != null) {
304+ manager.submitSchemaRefresh(null, null, null, null); // will also refresh token map
305+ }
306+ return this;
307+ }
308+
309+ /**
310+ * Whether client-side token and schema metadata is enabled.
311+ *
312+ * @return the value.
313+ *
314+ * @see #setMetadataEnabled(boolean)
315+ */
316+ public boolean isMetadataEnabled() {
317+ return metadataEnabled;
318+ }
319+
320+ /**
321+ * Sets the default window size in milliseconds used to debounce node list refresh requests.
322+ * <p>
323+ * When the control connection receives a new schema refresh request,
324+ * it puts it on hold and starts a timer, cancelling any previous running timer;
325+ * when a timer expires, then the pending requests are coalesced and executed
326+ * as a single request.
327+ *
328+ * @param refreshSchemaIntervalMillis The default window size in milliseconds used to debounce schema refresh requests.
329+ */
330+ public QueryOptions setRefreshSchemaIntervalMillis(int refreshSchemaIntervalMillis) {
331+ this.refreshSchemaIntervalMillis = refreshSchemaIntervalMillis;
332+ return this;
333+ }
334+
335+ /**
336+ * The default window size in milliseconds used to debounce schema refresh requests.
337+ *
338+ * @return The default window size in milliseconds used to debounce schema refresh requests.
339+ */
340+ public int getRefreshSchemaIntervalMillis() {
341+ return refreshSchemaIntervalMillis;
342+ }
343+
344+ /**
345+ * Sets the maximum number of schema refresh requests that the control connection can accumulate
346+ * before executing them.
347+ * <p>
348+ * When the control connection receives a new schema refresh request,
349+ * it puts it on hold and starts a timer, cancelling any previous running timer;
350+ * if the control connection receives too many events, is parameter allows to trigger
351+ * execution of pending requests, event if the last timer is still running.
352+ *
353+ * @param maxPendingRefreshSchemaRequests The maximum number of schema refresh requests that the control connection can accumulate
354+ * before executing them.
355+ */
356+ public QueryOptions setMaxPendingRefreshSchemaRequests(int maxPendingRefreshSchemaRequests) {
357+ this.maxPendingRefreshSchemaRequests = maxPendingRefreshSchemaRequests;
358+ return this;
359+ }
360+
361+ /**
362+ * The maximum number of schema refresh requests that the control connection can accumulate
363+ * before executing them.
364+ *
365+ * @return The maximum number of schema refresh requests that the control connection can accumulate
366+ * before executing them.
367+ */
368+ public int getMaxPendingRefreshSchemaRequests() {
369+ return maxPendingRefreshSchemaRequests;
370+ }
371+
372+ /**
373+ * Sets the default window size in milliseconds used to debounce node list refresh requests.
374+ * <p>
375+ * When the control connection receives a new node list refresh request,
376+ * it puts it on hold and starts a timer, cancelling any previous running timer;
377+ * when a timer expires, then the pending requests are coalesced and executed
378+ * as a single request.
379+ *
380+ * @param refreshNodeListIntervalMillis The default window size in milliseconds used to debounce node list refresh requests.
381+ */
382+ public QueryOptions setRefreshNodeListIntervalMillis(int refreshNodeListIntervalMillis) {
383+ this.refreshNodeListIntervalMillis = refreshNodeListIntervalMillis;
384+ return this;
385+ }
386+
387+ /**
388+ * The default window size in milliseconds used to debounce node list refresh requests.
389+ *
390+ * @return The default window size in milliseconds used to debounce node list refresh requests.
391+ */
392+ public int getRefreshNodeListIntervalMillis() {
393+ return refreshNodeListIntervalMillis;
394+ }
395+
396+ /**
397+ * Sets the maximum number of node list refresh requests that the control connection can accumulate
398+ * before executing them.
399+ * <p>
400+ * When the control connection receives a new node list refresh request,
401+ * it puts it on hold and starts a timer, cancelling any previous running timer;
402+ * if the control connection receives too many events, is parameter allows to trigger
403+ * execution of pending requests, event if the last timer is still running.
404+ *
405+ * @param maxPendingRefreshNodeListRequests The maximum number of node list refresh requests that the control connection can accumulate
406+ * before executing them.
407+ */
408+ public QueryOptions setMaxPendingRefreshNodeListRequests(int maxPendingRefreshNodeListRequests) {
409+ this.maxPendingRefreshNodeListRequests = maxPendingRefreshNodeListRequests;
410+ return this;
411+ }
412+
413+ /**
414+ * Sets the maximum number of node list refresh requests that the control connection can accumulate
415+ * before executing them.
416+ *
417+ * @return The maximum number of node list refresh requests that the control connection can accumulate
418+ * before executing them.
419+ */
420+ public int getMaxPendingRefreshNodeListRequests() {
421+ return maxPendingRefreshNodeListRequests;
422+ }
423+
424+ /**
425+ * Sets the default window size in milliseconds used to debounce node refresh requests.
426+ * <p>
427+ * When the control connection receives a new node refresh request,
428+ * it puts it on hold and starts a timer, cancelling any previous running timer;
429+ * when a timer expires, then the pending requests are coalesced and executed
430+ * as a single request.
431+ *
432+ * @param refreshNodeIntervalMillis The default window size in milliseconds used to debounce node refresh requests.
433+ */
434+ public QueryOptions setRefreshNodeIntervalMillis(int refreshNodeIntervalMillis) {
435+ this.refreshNodeIntervalMillis = refreshNodeIntervalMillis;
436+ return this;
437+ }
438+
439+ /**
440+ * The default window size in milliseconds used to debounce node refresh requests.
441+ *
442+ * @return The default window size in milliseconds used to debounce node refresh requests.
443+ */
444+ public int getRefreshNodeIntervalMillis() {
445+ return refreshNodeIntervalMillis;
446+ }
447+
448+ /**
449+ * Sets the maximum number of node refresh requests that the control connection can accumulate
450+ * before executing them.
451+ * <p>
452+ * When the control connection receives a new node refresh request,
453+ * it puts it on hold and starts a timer, cancelling any previous running timer;
454+ * if the control connection receives too many events, is parameter allows to trigger
455+ * execution of pending requests, event if the last timer is still running.
456+ *
457+ * @param maxPendingRefreshNodeRequests The maximum number of node refresh requests that the control connection can accumulate
458+ * before executing them.
459+ */
460+ public QueryOptions setMaxPendingRefreshNodeRequests(int maxPendingRefreshNodeRequests) {
461+ this.maxPendingRefreshNodeRequests = maxPendingRefreshNodeRequests;
462+ return this;
463+ }
464+
465+ /**
466+ * The maximum number of node refresh requests that the control connection can accumulate
467+ * before executing them.
468+ *
469+ * @return The maximum number of node refresh requests that the control connection can accumulate
470+ * before executing them.
471+ */
472+ public int getMaxPendingRefreshNodeRequests() {
473+ return maxPendingRefreshNodeRequests;
474+ }
475+
172476 }
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +55 −8
@@ -18,6 +18,7 @@
1818 import java.util.*;
1919
2020 import com.google.common.collect.ImmutableSet;
21+import com.google.common.collect.Maps;
2122 import com.google.common.collect.Sets;
2223 import org.slf4j.Logger;
2324 import org.slf4j.LoggerFactory;
@@ -87,6 +88,24 @@
8788 }
8889 return replicaMap;
8990 }
91+
92+ @Override
93+ public boolean equals(Object o) {
94+ if (this == o)
95+ return true;
96+ if (o == null || getClass() != o.getClass())
97+ return false;
98+
99+ SimpleStrategy that = (SimpleStrategy)o;
100+
101+ return replicationFactor == that.replicationFactor;
102+
103+ }
104+
105+ @Override
106+ public int hashCode() {
107+ return replicationFactor;
108+ }
90109 }
91110
92111 static class NetworkTopologyStrategy extends ReplicationStrategy {
@@ -103,9 +122,16 @@
103122 // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy
104123 Map<String, Set<String>> racks = getRacksInDcs(tokenToPrimary.values());
105124 Map<Token, Set<Host>> replicaMap = new HashMap<Token, Set<Host>>(tokenToPrimary.size());
106-
125+ Map<String, Integer> dcHostCount = Maps.newHashMapWithExpectedSize(replicationFactors.size());
107126 Set<String> warnedDcs = Sets.newHashSetWithExpectedSize(replicationFactors.size());
108-
127+ // find maximum number of nodes in each DC
128+ for (Host host : Sets.newHashSet(tokenToPrimary.values())) {
129+ String dc = host.getDatacenter();
130+ if(dcHostCount.get(dc) == null) {
131+ dcHostCount.put(dc, 0);
132+ }
133+ dcHostCount.put(dc, dcHostCount.get(dc) + 1);
134+ }
109135 for (int i = 0; i < ring.size(); i++) {
110136 Map<String, Set<Host>> allDcReplicas = new HashMap<String, Set<Host>>();
111137 Map<String, Set<String>> seenRacks = new HashMap<String, Set<String>>();
@@ -118,7 +144,7 @@
118144
119145 // Preserve order - primary replica will be first
120146 Set<Host> replicas = new LinkedHashSet<Host>();
121- for (int j = 0; j < ring.size() && !allDone(allDcReplicas); j++) {
147+ for (int j = 0; j < ring.size() && !allDone(allDcReplicas, dcHostCount); j++) {
122148 Host h = tokenToPrimary.get(getTokenWrapping(i + j, ring));
123149 String dc = h.getDatacenter();
124150 if (dc == null || !allDcReplicas.containsKey(dc))
@@ -165,8 +191,7 @@
165191 if (achievedFactor < expectedFactor && !warnedDcs.contains(dcName)) {
166192 logger.warn("Error while computing token map for datacenter {}: "
167193 + "could not achieve replication factor {} (found {} replicas only), "
168- + "check your keyspace replication settings. "
169- + "Note that this can affect the performance of the driver.",
194+ + "check your keyspace replication settings.",
170195 dcName, expectedFactor, achievedFactor);
171196 // only warn once per DC
172197 warnedDcs.add(dcName);
@@ -178,10 +203,13 @@
178203 return replicaMap;
179204 }
180205
181- private boolean allDone(Map<String, Set<Host>> map) {
182- for (Map.Entry<String, Set<Host>> entry : map.entrySet())
183- if (entry.getValue().size() < replicationFactors.get(entry.getKey()))
206+ private boolean allDone(Map<String, Set<Host>> map, Map<String, Integer> dcHostCount) {
207+ for (Map.Entry<String, Set<Host>> entry : map.entrySet()) {
208+ String dc = entry.getKey();
209+ int dcCount = dcHostCount.get(dc) == null? 0 : dcHostCount.get(dc);
210+ if (entry.getValue().size() < Math.min(replicationFactors.get(dc), dcCount))
184211 return false;
212+ }
185213 return true;
186214 }
187215
@@ -197,5 +225,24 @@
197225 }
198226 return result;
199227 }
228+
229+ @Override
230+ public boolean equals(Object o) {
231+ if (this == o)
232+ return true;
233+ if (o == null || getClass() != o.getClass())
234+ return false;
235+
236+ NetworkTopologyStrategy that = (NetworkTopologyStrategy)o;
237+
238+ return replicationFactors.equals(that.replicationFactors);
239+
240+ }
241+
242+ @Override
243+ public int hashCode() {
244+ return replicationFactors.hashCode();
245+ }
200246 }
247+
201248 }
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +4 −4
@@ -27,7 +27,6 @@
2727
2828 import com.codahale.metrics.Timer;
2929 import com.google.common.collect.Sets;
30-import io.netty.util.HashedWheelTimer;
3130 import io.netty.util.Timeout;
3231 import io.netty.util.TimerTask;
3332 import org.slf4j.Logger;
@@ -56,7 +55,7 @@
5655 private final Set<SpeculativeExecution> runningExecutions = Sets.newCopyOnWriteArraySet();
5756 private final Set<Timeout> scheduledExecutions = Sets.newCopyOnWriteArraySet();
5857 private final Statement statement;
59- private final HashedWheelTimer scheduler;
58+ private final io.netty.util.Timer scheduler;
6059
6160 private volatile List<Host> triedHosts;
6261
@@ -135,7 +134,8 @@
135134 manager.executor().execute(new Runnable() {
136135 @Override
137136 public void run() {
138- metrics().getErrorMetrics().getSpeculativeExecutions().inc();
137+ if (metricsEnabled())
138+ metrics().getErrorMetrics().getSpeculativeExecutions().inc();
139139 startNewExecution();
140140 }
141141 });
@@ -317,7 +317,7 @@
317317 return false;
318318 } catch (TimeoutException e) {
319319 // We timeout, log it but move to the next node.
320- logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)"));
320+ logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)", e));
321321 return false;
322322 } catch (RuntimeException e) {
323323 if (connection != null)
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +14 −14
@@ -107,23 +107,23 @@
107107
108108 public DriverException asException(InetSocketAddress host) {
109109 switch (code) {
110- case SERVER_ERROR: return new DriverInternalError(String.format("An unexpected error occurred server side on %s: %s", host, message));
111- case PROTOCOL_ERROR: return new DriverInternalError("An unexpected protocol error occurred. This is a bug in this library, please report: " + message);
110+ case SERVER_ERROR: return new ServerError(host, message);
111+ case PROTOCOL_ERROR: return new ProtocolError(host, message);
112112 case BAD_CREDENTIALS: return new AuthenticationException(host, message);
113- case UNAVAILABLE: return ((UnavailableException)infos).copy(); // We copy to have a nice stack trace
113+ case UNAVAILABLE: return ((UnavailableException)infos).copy(host); // We copy to have a nice stack trace
114114 case OVERLOADED: return new OverloadedException(host, message);
115115 case IS_BOOTSTRAPPING: return new BootstrappingException(host, message);
116- case TRUNCATE_ERROR: return new TruncateException(message);
117- case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy();
118- case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy();
119- case WRITE_FAILURE: return ((WriteFailureException)infos).copy();
120- case READ_FAILURE: return ((ReadFailureException)infos).copy();
121- case FUNCTION_FAILURE: return new FunctionExecutionException(message);
122- case SYNTAX_ERROR: return new SyntaxError(message);
123- case UNAUTHORIZED: return new UnauthorizedException(message);
124- case INVALID: return new InvalidQueryException(message);
125- case CONFIG_ERROR: return new InvalidConfigurationInQueryException(message);
126- case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy();
116+ case TRUNCATE_ERROR: return new TruncateException(host, message);
117+ case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy(host);
118+ case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy(host);
119+ case WRITE_FAILURE: return ((WriteFailureException)infos).copy(host);
120+ case READ_FAILURE: return ((ReadFailureException)infos).copy(host);
121+ case FUNCTION_FAILURE: return new FunctionExecutionException(host, message);
122+ case SYNTAX_ERROR: return new SyntaxError(host, message);
123+ case UNAUTHORIZED: return new UnauthorizedException(host, message);
124+ case INVALID: return new InvalidQueryException(host, message);
125+ case CONFIG_ERROR: return new InvalidConfigurationInQueryException(host, message);
126+ case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy(host);
127127 case UNPREPARED: return new UnpreparedException(host, message);
128128 default: return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message));
129129 }
added driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +155 −0
@@ -0,0 +1,155 @@
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+/**
19+ * Interface for objects that are interested in tracking schema change events in the cluster.
20+ * <p>
21+ * An implementation of this interface can be registered against a Cluster
22+ * object through the {@link com.datastax.driver.core.Cluster#register(SchemaChangeListener)} method.
23+ * <p>
24+ * Note that the methods defined by this interface will be executed by internal driver threads, and are
25+ * therefore expected to have short execution times. If you need to perform long computations or blocking
26+ * calls in response to schema change events, it is strongly recommended to schedule them asynchronously
27+ * on a separate thread provided by our application code.
28+ */
29+public interface SchemaChangeListener {
30+
31+ /**
32+ * Called when a keyspace has been added.
33+ *
34+ * @param keyspace the keyspace that has been added.
35+ */
36+ void onKeyspaceAdded(KeyspaceMetadata keyspace);
37+
38+ /**
39+ * Called when a keyspace has been removed.
40+ *
41+ * @param keyspace the keyspace that has been removed.
42+ */
43+ void onKeyspaceRemoved(KeyspaceMetadata keyspace);
44+
45+ /**
46+ * Called when a keyspace has changed.
47+ *
48+ * @param current the keyspace that has changed, in its current form (after the change).
49+ * @param previous the keyspace that has changed, in its previous form (before the change).
50+ */
51+ void onKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous);
52+
53+ /**
54+ * Called when a table has been added.
55+ *
56+ * @param table the table that has been newly added.
57+ */
58+ void onTableAdded(TableMetadata table);
59+
60+ /**
61+ * Called when a table has been removed.
62+ *
63+ * @param table the table that has been removed.
64+ */
65+ void onTableRemoved(TableMetadata table);
66+
67+ /**
68+ * Called when a table has changed.
69+ *
70+ * @param current the table that has changed, in its current form (after the change).
71+ * @param previous the table that has changed, in its previous form (before the change).
72+ */
73+ void onTableChanged(TableMetadata current, TableMetadata previous);
74+
75+ /**
76+ * Called when a user-defined type has been added.
77+ *
78+ * @param type the type that has been newly added.
79+ */
80+ void onUserTypeAdded(UserType type);
81+
82+ /**
83+ * Called when a user-defined type has been removed.
84+ *
85+ * @param type the type that has been removed.
86+ */
87+ void onUserTypeRemoved(UserType type);
88+
89+ /**
90+ * Called when a user-defined type has changed.
91+ *
92+ * @param current the type that has changed, in its current form (after the change).
93+ * @param previous the type that has changed, in its previous form (before the change).
94+ */
95+ void onUserTypeChanged(UserType current, UserType previous);
96+
97+ /**
98+ * Called when a user-defined function has been added.
99+ *
100+ * @param function the function that has been newly added.
101+ */
102+ void onFunctionAdded(FunctionMetadata function);
103+
104+ /**
105+ * Called when a user-defined function has been removed.
106+ *
107+ * @param function the function that has been removed.
108+ */
109+ void onFunctionRemoved(FunctionMetadata function);
110+
111+ /**
112+ * Called when a user-defined function has changed.
113+ *
114+ * @param current the function that has changed, in its current form (after the change).
115+ * @param previous the function that has changed, in its previous form (before the change).
116+ */
117+ void onFunctionChanged(FunctionMetadata current, FunctionMetadata previous);
118+
119+ /**
120+ * Called when a user-defined aggregate has been added.
121+ *
122+ * @param aggregate the aggregate that has been newly added.
123+ */
124+ void onAggregateAdded(AggregateMetadata aggregate);
125+
126+ /**
127+ * Called when a user-defined aggregate has been removed.
128+ *
129+ * @param aggregate the aggregate that has been removed.
130+ */
131+ void onAggregateRemoved(AggregateMetadata aggregate);
132+
133+ /**
134+ * Called when a user-defined aggregate has changed.
135+ *
136+ * @param current the aggregate that has changed, in its current form (after the change).
137+ * @param previous the aggregate that has changed, in its previous form (before the change).
138+ */
139+ void onAggregateChanged(AggregateMetadata current, AggregateMetadata previous);
140+
141+ /**
142+ * Gets invoked when the listener is registered with a cluster.
143+ *
144+ * @param cluster the cluster that this tracker is registered with.
145+ */
146+ void onRegister(Cluster cluster);
147+
148+ /**
149+ * Gets invoked when the listener is unregistered from a cluster, or at cluster shutdown if
150+ * the tracker was not unregistered.
151+ *
152+ * @param cluster the cluster that this tracker was registered with.
153+ */
154+ void onUnregister(Cluster cluster);
155+}
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +160 −120
@@ -22,12 +22,15 @@
2222 import java.util.concurrent.atomic.AtomicReference;
2323
2424 import com.google.common.base.Function;
25+import com.google.common.base.Functions;
26+import com.google.common.base.Throwables;
2527 import com.google.common.collect.ImmutableList;
2628 import com.google.common.collect.Lists;
2729 import com.google.common.util.concurrent.*;
2830 import org.slf4j.Logger;
2931 import org.slf4j.LoggerFactory;
3032
33+import com.datastax.driver.core.Message.Response;
3134 import com.datastax.driver.core.exceptions.DriverInternalError;
3235 import com.datastax.driver.core.exceptions.InvalidQueryException;
3336 import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
@@ -46,47 +49,72 @@
4649 final Cluster cluster;
4750 final ConcurrentMap<Host, HostConnectionPool> pools;
4851 final HostConnectionPool.PoolState poolsState;
52+ private final AtomicReference<ListenableFuture<Session>> initFuture = new AtomicReference<ListenableFuture<Session>>();
4953 final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>();
5054
5155 private volatile boolean isInit;
5256 private volatile boolean isClosing;
5357
5458 // Package protected, only Cluster should construct that.
55- SessionManager(Cluster cluster) {
59+ SessionManager(Cluster cluster, String keyspace) {
5660 this.cluster = cluster;
5761 this.pools = new ConcurrentHashMap<Host, HostConnectionPool>();
58- this.poolsState = new HostConnectionPool.PoolState();
62+ this.poolsState = new HostConnectionPool.PoolState(keyspace);
5963 }
6064
61- public synchronized Session init() {
62- if (isInit)
63- return this;
65+ public Session init() {
66+ try {
67+ return Uninterruptibles.getUninterruptibly(initAsync());
68+ } catch (ExecutionException e) {
69+ throw DriverThrowables.propagateCause(e);
70+ }
71+ }
6472
73+ public ListenableFuture<Session> initAsync() {
6574 // If we haven't initialized the cluster, do it now
6675 cluster.init();
6776
68- // Create pools to initial nodes (and wait for them to be created)
77+ ListenableFuture<Session> existing = initFuture.get();
78+ if (existing != null)
79+ return existing;
80+
81+ final SettableFuture<Session> myInitFuture = SettableFuture.create();
82+ if (!initFuture.compareAndSet(null, myInitFuture))
83+ return initFuture.get();
84+
6985 Collection<Host> hosts = cluster.getMetadata().allHosts();
70- createPoolsInParallel(hosts);
71-
72- isInit = true;
73- updateCreatedPools();
74- return this;
86+ ListenableFuture<?> allPoolsCreatedFuture = createPools(hosts);
87+ ListenableFuture<?> allPoolsUpdatedFuture = Futures.transform(allPoolsCreatedFuture,
88+ new AsyncFunction<Object, Object>() {
89+ @Override
90+ @SuppressWarnings("unchecked")
91+ public ListenableFuture<Object> apply(Object input) throws Exception {
92+ isInit = true;
93+ return (ListenableFuture<Object>)updateCreatedPools();
94+ }
95+ });
96+
97+ Futures.addCallback(allPoolsUpdatedFuture, new FutureCallback<Object>() {
98+ @Override
99+ public void onSuccess(Object result) {
100+ myInitFuture.set(SessionManager.this);
101+ }
102+
103+ @Override
104+ public void onFailure(Throwable t) {
105+ SessionManager.this.closeAsync(); // don't leak the session
106+ myInitFuture.setException(t);
107+ }
108+ });
109+ return myInitFuture;
75110 }
76111
77- private void createPoolsInParallel(Collection<Host> hosts) {
112+ private ListenableFuture<?> createPools(Collection<Host> hosts) {
78113 List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size());
79114 for (Host host : hosts)
80115 if (host.state != Host.State.DOWN)
81- futures.add(maybeAddPool(host, null));
82- try {
83- Futures.successfulAsList(futures).get();
84- } catch (ExecutionException e) {
85- // Won't happen because we used successfulAsList
86- // And if a particular pool failed, maybeAddPool already handled it
87- } catch (InterruptedException e) {
88- Thread.currentThread().interrupt();
89- }
116+ futures.add(maybeAddPool(host, null, true));
117+ return Futures.allAsList(futures);
90118 }
91119
92120 public String getLoggedKeyspace() {
@@ -94,8 +122,26 @@
94122 }
95123
96124 @Override
97- public ResultSetFuture executeAsync(Statement statement) {
98- return executeQuery(makeRequestMessage(statement, null), statement);
125+ public ResultSetFuture executeAsync(final Statement statement) {
126+ if (isInit) {
127+ DefaultResultSetFuture future = new DefaultResultSetFuture(this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null));
128+ new RequestHandler(this, future, statement).sendRequest();
129+ return future;
130+ } else {
131+ // If the session is not initialized, we can't call makeRequestMessage() synchronously, because it
132+ // requires internal Cluster state that might not be initialized yet (like the protocol version).
133+ // Because of the way the future is built, we need another 'proxy' future that we can return now.
134+ final ChainedResultSetFuture chainedFuture = new ChainedResultSetFuture();
135+ this.initAsync().addListener(new Runnable() {
136+ @Override
137+ public void run() {
138+ DefaultResultSetFuture actualFuture = new DefaultResultSetFuture(SessionManager.this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null));
139+ execute(actualFuture, statement);
140+ chainedFuture.setSource(actualFuture);
141+ }
142+ }, executor());
143+ return chainedFuture;
144+ }
99145 }
100146
101147 @Override
@@ -139,8 +185,8 @@
139185 }
140186
141187 private ListenableFuture<PreparedStatement> toPreparedStatement(final String query, final Connection.Future future) {
142- return Futures.transform(future, new Function<Message.Response, PreparedStatement>() {
143- public PreparedStatement apply(Message.Response response) {
188+ return Futures.transform(future, new AsyncFunction<Response, PreparedStatement>() {
189+ public ListenableFuture<PreparedStatement> apply(Response response) {
144190 switch (response.type) {
145191 case RESULT:
146192 Responses.Result rm = (Responses.Result)response;
@@ -149,27 +195,26 @@
149195 Responses.Result.Prepared pmsg = (Responses.Result.Prepared)rm;
150196 PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster, query, poolsState.keyspace);
151197 stmt = cluster.manager.addPrepared(stmt);
152- try {
198+ if (cluster.getConfiguration().getQueryOptions().isPrepareOnAllHosts()) {
153199 // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session.
154200 // If that changes, we'll have to make sure this propagate to other sessions too.
155- prepare(stmt.getQueryString(), future.getAddress());
156- } catch (InterruptedException e) {
157- Thread.currentThread().interrupt();
158- // This method doesn't propagate interruption, at least not for now. However, if we've
159- // interrupted preparing queries on other node it's not a problem as we'll re-prepare
160- // later if need be. So just ignore.
201+ return prepare(stmt, future.getAddress());
202+ } else {
203+ return Futures.immediateFuture(stmt);
161204 }
162- return stmt;
163205 default:
164- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind));
206+ return Futures.immediateFailedFuture(
207+ new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind)));
165208 }
166209 case ERROR:
167- throw ((Responses.Error)response).asException(future.getAddress());
210+ return Futures.immediateFailedFuture(
211+ ((Responses.Error)response).asException(future.getAddress()));
168212 default:
169- throw new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type));
213+ return Futures.immediateFailedFuture(
214+ new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type)));
170215 }
171216 }
172- }, executor()); // Since the transformation involves querying other nodes, we should not do that in an I/O thread
217+ });
173218 }
174219
175220 Connection.Factory connectionFactory() {
@@ -287,7 +332,7 @@
287332 }
288333
289334 // Returns whether there was problem creating the pool
290- ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) {
335+ ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) {
291336 final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host);
292337 if (distance == HostDistance.IGNORED)
293338 return Futures.immediateFuture(true);
@@ -320,6 +365,9 @@
320365 ClusterNameMismatchException e = (ClusterNameMismatchException)t;
321366 cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName);
322367 cluster.manager.triggerOnDown(host, false);
368+ } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) {
369+ future.setException(t.getCause());
370+ return;
323371 } else {
324372 logger.error("Error creating pool to " + host, t);
325373 }
@@ -347,54 +395,48 @@
347395 * This method ensures that all hosts for which a pool should exist
348396 * have one, and hosts that shouldn't don't.
349397 */
350- void updateCreatedPools() {
398+ ListenableFuture<?> updateCreatedPools() {
351399 // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if
352400 // we execute the code below we would try to create their pool over and over again.
353401 // It's called explicitly at the end of init(), once isInit has been set to true.
354402 if (!isInit)
355- return;
403+ return MoreFutures.VOID_SUCCESS;
356404
357- try {
358- // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second.
359- // That way, we'll avoid situation where we'll temporarily lose connectivity
360- List<Host> toRemove = new ArrayList<Host>();
361- List<ListenableFuture<?>> poolCreationFutures = new ArrayList<ListenableFuture<?>>();
362-
363- for (Host h : cluster.getMetadata().allHosts()) {
364- HostDistance dist = loadBalancingPolicy().distance(h);
365- HostConnectionPool pool = pools.get(h);
366-
367- if (pool == null) {
368- if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
369- poolCreationFutures.add(maybeAddPool(h, null));
370- } else if (dist != pool.hostDistance) {
371- if (dist == HostDistance.IGNORED) {
372- toRemove.add(h);
373- } else {
374- pool.hostDistance = dist;
375- pool.ensureCoreConnections();
376- }
377- }
378- }
405+ // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second.
406+ // That way, we'll avoid situation where we'll temporarily lose connectivity
407+ final List<Host> toRemove = new ArrayList<Host>();
408+ List<ListenableFuture<Boolean>> poolCreatedFutures = Lists.newArrayList();
379409
380- // Wait pool creation before removing, so we don't lose connectivity
381- try {
382- Futures.successfulAsList(poolCreationFutures).get();
383- } catch (ExecutionException e) {
384- // Won't happen because we used successfulAsList
385- // And if a particular pool failed, maybeAddPool already handled it
410+ for (Host h : cluster.getMetadata().allHosts()) {
411+ HostDistance dist = loadBalancingPolicy().distance(h);
412+ HostConnectionPool pool = pools.get(h);
413+
414+ if (pool == null) {
415+ if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
416+ poolCreatedFutures.add(maybeAddPool(h, null, false));
417+ } else if (dist != pool.hostDistance) {
418+ if (dist == HostDistance.IGNORED) {
419+ toRemove.add(h);
420+ } else {
421+ pool.hostDistance = dist;
422+ pool.ensureCoreConnections();
423+ }
386424 }
425+ }
387426
388- List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size());
389- for (Host h : toRemove)
390- poolRemovalFutures.add(removePool(h));
427+ // Wait pool creation before removing, so we don't lose connectivity
428+ ListenableFuture<?> allPoolsCreatedFuture = Futures.successfulAsList(poolCreatedFutures);
391429
392- Futures.allAsList(poolRemovalFutures).get();
393- } catch (InterruptedException e) {
394- Thread.currentThread().interrupt();
395- } catch (ExecutionException e) {
396- logger.error("Unexpected error while refreshing connection pools", e.getCause());
397- }
430+ return Futures.transform(allPoolsCreatedFuture, new AsyncFunction<Object, List<Void>>() {
431+ @Override
432+ public ListenableFuture<List<Void>> apply(Object input) throws Exception {
433+ List<ListenableFuture<Void>> poolRemovedFuture = Lists.newArrayListWithCapacity(toRemove.size());
434+ for (Host h : toRemove)
435+ poolRemovedFuture.add(removePool(h));
436+
437+ return Futures.successfulAsList(poolRemovedFuture);
438+ }
439+ });
398440 }
399441
400442 void updateCreatedPools(Host h) {
@@ -405,7 +447,7 @@
405447 if (pool == null) {
406448 if (dist != HostDistance.IGNORED && h.state == Host.State.UP)
407449 try {
408- maybeAddPool(h, null).get();
450+ maybeAddPool(h, null, false).get();
409451 } catch (ExecutionException e) {
410452 // Ignore, maybeAddPool has already handled the error
411453 }
@@ -428,26 +470,13 @@
428470 // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary
429471 // since updateCreatedPools should take care of it. But better protect against non well behaving policies.
430472 removePool(host).force().get();
431- updateCreatedPools();
473+ updateCreatedPools().get();
432474 }
433475
434476 void onRemove(Host host) throws InterruptedException, ExecutionException {
435477 onDown(host);
436478 }
437479
438- void setKeyspace(String keyspace) {
439- long timeout = configuration().getSocketOptions().getConnectTimeoutMillis();
440- try {
441- Future<?> future = executeQuery(new Requests.Query("use " + keyspace), Statement.DEFAULT);
442- // Note: using the connection timeout isn't perfectly correct, we should probably change that someday
443- Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
444- } catch (TimeoutException e) {
445- throw new DriverInternalError(String.format("No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout));
446- } catch (ExecutionException e) {
447- throw DefaultResultSetFuture.extractCauseFromExecutionException(e);
448- }
449- }
450-
451480 Message.Request makeRequestMessage(Statement statement, ByteBuffer pagingState) {
452481 // We need the protocol version, which is only available once the cluster has initialized. Initialize the session to ensure this is the case.
453482 // init() locks, so avoid if we know we don't need it.
@@ -558,46 +587,57 @@
558587 * This method will find a suitable node to connect to using the
559588 * {@link LoadBalancingPolicy} and handle host failover.
560589 */
561- void execute(RequestHandler.Callback callback, Statement statement) {
562- // init() locks, so avoid if we know we don't need it.
563- if (!isInit)
564- init();
565- new RequestHandler(this, callback, statement).sendRequest();
590+ void execute(final RequestHandler.Callback callback, final Statement statement) {
591+ if (isInit)
592+ new RequestHandler(this, callback, statement).sendRequest();
593+ else
594+ this.initAsync().addListener(new Runnable() {
595+ @Override
596+ public void run() {
597+ new RequestHandler(SessionManager.this, callback, statement).sendRequest();
598+ }
599+ }, executor());
566600 }
567601
568- private void prepare(String query, InetSocketAddress toExclude) throws InterruptedException {
569- for (Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) {
602+ private ListenableFuture<PreparedStatement> prepare(final PreparedStatement statement, InetSocketAddress toExclude) {
603+ final String query = statement.getQueryString();
604+ List<ListenableFuture<Response>> futures = Lists.newArrayListWithExpectedSize(pools.size());
605+ for (final Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) {
570606 if (entry.getKey().getSocketAddress().equals(toExclude))
571607 continue;
572608
573- // Let's not wait too long if we can't get a connection. Things
574- // will fix themselves once the user tries a query anyway.
575- Connection c = null;
576- boolean timedOut = false;
577609 try {
578- c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
579- c.write(new Requests.Prepare(query)).get();
580- } catch (ConnectionException e) {
610+ // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute
611+ // the prepared query. So don't block if no connection is available, simply abort.
612+ final Connection c = entry.getValue().borrowConnection(0, TimeUnit.MILLISECONDS);
613+ ListenableFuture<Response> future = c.write(new Requests.Prepare(query));
614+ Futures.addCallback(future, new FutureCallback<Response>() {
615+ @Override
616+ public void onSuccess(Response result) {
617+ c.release();
618+ }
619+
620+ @Override
621+ public void onFailure(Throwable t) {
622+ logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t);
623+
624+ // If the query timed out, that already released the connection, otherwise do it now
625+ if (!(t instanceof OperationTimedOutException))
626+ c.release();
627+ }
628+ });
629+ futures.add(future);
630+ } catch (Exception e) {
581631 // Again, not being able to prepare the query right now is no big deal, so just ignore
582- } catch (BusyConnectionException e) {
583- // Same as above
584- } catch (TimeoutException e) {
585- // Same as above
586- } catch (ExecutionException e) {
587- // We shouldn't really get exception while preparing a
588- // query, so log this (but ignore otherwise as it's not a big deal)
589- logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e);
590- // If the query timed out, that already released the connection
591- timedOut = e.getCause() instanceof OperationTimedOutException;
592- } finally {
593- if (c != null && !timedOut)
594- c.release();
595632 }
596633 }
634+ // Return the statement when all futures are done
635+ return Futures.transform(
636+ Futures.successfulAsList(futures),
637+ Functions.constant(statement));
597638 }
598639
599640 ResultSetFuture executeQuery(Message.Request msg, Statement statement) {
600-
601641 DefaultResultSetFuture future = new DefaultResultSetFuture(this, configuration().getProtocolOptions().getProtocolVersion(), msg);
602642 execute(future, statement);
603643 return future;
added driver-core/src/main/java/com/datastax/driver/core/SetKeyspaceException.java +23 −0
@@ -0,0 +1,23 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+@SuppressWarnings("serial")
19+class SetKeyspaceException extends Exception {
20+ SetKeyspaceException(Exception cause) {
21+ super(cause);
22+ }
23+}
modified driver-core/src/main/java/com/datastax/driver/core/SimpleStatement.java +17 −0
@@ -83,6 +83,23 @@
8383 public boolean hasValues() {
8484 return values != null && values.length > 0;
8585 }
86+
87+ /**
88+ * Returns the {@code i}th value as the Java type matching its CQL type.
89+ *
90+ * @param i the index to retrieve.
91+ * @return the value of the {@code i}th value of this statement.
92+ *
93+ * @throws IllegalStateException if this statement does not have values.
94+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
95+ */
96+ public Object getObject(int i) {
97+ if (values == null)
98+ throw new IllegalStateException("This statement does not have values");
99+ if (i < 0 || i >= values.length)
100+ throw new ArrayIndexOutOfBoundsException(i);
101+ return values[i];
102+ }
86103
87104 /**
88105 * Returns the routing key for the query.
modified driver-core/src/main/java/com/datastax/driver/core/SocketOptions.java +3 −5
@@ -85,7 +85,7 @@
8585 * <p>
8686 * Please note that this is not the maximum time a call to {@link Session#execute} may block;
8787 * this is the maximum time that call will wait for one particular
88- * Cassandra host, but other hosts will be tried if one of them timeout. In
88+ * Cassandra host, but other hosts will be tried if one of them times out. In
8989 * other words, a {@link Session#execute} call may theoretically wait up to
9090 * {@code getReadTimeoutMillis() * <number_of_cassandra_hosts>} (though the
9191 * total number of hosts tried for a given query also depends on the
@@ -110,10 +110,8 @@
110110 * <p>
111111 * When setting this value, keep in mind the following:
112112 * <ul>
113- * <li>the timeout settings used on the Cassandra side ({@code *_request_timeout_in_ms}
114- * in {@code cassandra.yaml}) should be taken into account when picking a value for this
115- * read timeout. In particular, if this read timeout option is lower than Cassandra's
116- * timeout, <b>the driver might assume that the host is not responsive and mark it down.</b></li>
113+ * <li>it should be higher than the timeout settings used on the Cassandra side
114+ * ({@code *_request_timeout_in_ms} in {@code cassandra.yaml}).</li>
117115 * <li>the read timeout is only approximate and only control the timeout to one Cassandra
118116 * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a
119117 * high level of precision on the timeout to a request is required, you should use
modified driver-core/src/main/java/com/datastax/driver/core/TableMetadata.java +103 −1
@@ -187,7 +187,6 @@
187187 for (ColumnMetadata c : otherColumns)
188188 columns.put(c.getName(), c);
189189
190- ksm.add(tm);
191190 return tm;
192191 }
193192
@@ -391,6 +390,43 @@
391390 return asCQLQuery(false);
392391 }
393392
393+ @Override
394+ public boolean equals(Object o) {
395+ if (this == o)
396+ return true;
397+ if (o == null || getClass() != o.getClass())
398+ return false;
399+
400+ TableMetadata that = (TableMetadata)o;
401+
402+ if (!name.equals(that.name))
403+ return false;
404+ if (!partitionKey.equals(that.partitionKey))
405+ return false;
406+ if (!clusteringColumns.equals(that.clusteringColumns))
407+ return false;
408+ if (!columns.equals(that.columns))
409+ return false;
410+ if (!options.equals(that.options))
411+ return false;
412+ if (!clusteringOrder.equals(that.clusteringOrder))
413+ return false;
414+ return cassandraVersion.equals(that.cassandraVersion);
415+
416+ }
417+
418+ @Override
419+ public int hashCode() {
420+ int result = name.hashCode();
421+ result = 31 * result + partitionKey.hashCode();
422+ result = 31 * result + clusteringColumns.hashCode();
423+ result = 31 * result + columns.hashCode();
424+ result = 31 * result + options.hashCode();
425+ result = 31 * result + clusteringOrder.hashCode();
426+ result = 31 * result + cassandraVersion.hashCode();
427+ return result;
428+ }
429+
394430 private String asCQLQuery(boolean formatted) {
395431 StringBuilder sb = new StringBuilder();
396432
@@ -783,5 +819,71 @@
783819 public Map<String, String> getCompression() {
784820 return new HashMap<String, String>(compression);
785821 }
822+
823+ @Override
824+ public boolean equals(Object o) {
825+ if (this == o)
826+ return true;
827+ if (o == null || getClass() != o.getClass())
828+ return false;
829+
830+ Options options = (Options)o;
831+
832+ if (isCompactStorage != options.isCompactStorage)
833+ return false;
834+ if (Double.compare(options.readRepair, readRepair) != 0)
835+ return false;
836+ if (Double.compare(options.localReadRepair, localReadRepair) != 0)
837+ return false;
838+ if (replicateOnWrite != options.replicateOnWrite)
839+ return false;
840+ if (gcGrace != options.gcGrace)
841+ return false;
842+ if (Double.compare(options.bfFpChance, bfFpChance) != 0)
843+ return false;
844+ if (populateCacheOnFlush != options.populateCacheOnFlush)
845+ return false;
846+ if (memtableFlushPeriodMs != options.memtableFlushPeriodMs)
847+ return false;
848+ if (defaultTTL != options.defaultTTL)
849+ return false;
850+ if (indexInterval != options.indexInterval)
851+ return false;
852+ if (comment != null ? !comment.equals(options.comment) : options.comment != null)
853+ return false;
854+ if (caching != null ? !caching.equals(options.caching) : options.caching != null)
855+ return false;
856+ if (speculativeRetry != null ? !speculativeRetry.equals(options.speculativeRetry) : options.speculativeRetry != null)
857+ return false;
858+ if (compaction != null ? !compaction.equals(options.compaction) : options.compaction != null)
859+ return false;
860+ return !(compression != null ? !compression.equals(options.compression) : options.compression != null);
861+
862+ }
863+
864+ @Override
865+ public int hashCode() {
866+ int result;
867+ long temp;
868+ result = (isCompactStorage ? 1 : 0);
869+ result = 31 * result + (comment != null ? comment.hashCode() : 0);
870+ temp = Double.doubleToLongBits(readRepair);
871+ result = 31 * result + (int)(temp ^ (temp >>> 32));
872+ temp = Double.doubleToLongBits(localReadRepair);
873+ result = 31 * result + (int)(temp ^ (temp >>> 32));
874+ result = 31 * result + (replicateOnWrite ? 1 : 0);
875+ result = 31 * result + gcGrace;
876+ temp = Double.doubleToLongBits(bfFpChance);
877+ result = 31 * result + (int)(temp ^ (temp >>> 32));
878+ result = 31 * result + (caching != null ? caching.hashCode() : 0);
879+ result = 31 * result + (populateCacheOnFlush ? 1 : 0);
880+ result = 31 * result + memtableFlushPeriodMs;
881+ result = 31 * result + defaultTTL;
882+ result = 31 * result + (speculativeRetry != null ? speculativeRetry.hashCode() : 0);
883+ result = 31 * result + indexInterval;
884+ result = 31 * result + (compaction != null ? compaction.hashCode() : 0);
885+ result = 31 * result + (compression != null ? compression.hashCode() : 0);
886+ return result;
887+ }
786888 }
787889 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/AlreadyExistsException.java +49 −3
@@ -15,24 +15,34 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 /**
1922 * Exception thrown when a query attempts to create a keyspace or table that already exists.
2023 */
21-public class AlreadyExistsException extends QueryValidationException {
24+public class AlreadyExistsException extends QueryValidationException implements CoordinatorException {
2225
2326 private static final long serialVersionUID = 0;
2427
28+ private final InetSocketAddress address;
2529 private final String keyspace;
2630 private final String table;
2731
2832 public AlreadyExistsException(String keyspace, String table) {
33+ this(null, keyspace, table);
34+ }
35+
36+ public AlreadyExistsException(InetSocketAddress address, String keyspace, String table) {
2937 super(makeMsg(keyspace, table));
38+ this.address = address;
3039 this.keyspace = keyspace;
3140 this.table = table;
3241 }
3342
34- private AlreadyExistsException(String msg, Throwable cause, String keyspace, String table) {
43+ private AlreadyExistsException(InetSocketAddress address, String msg, Throwable cause, String keyspace, String table) {
3544 super(msg, cause);
45+ this.address = address;
3646 this.keyspace = keyspace;
3747 this.table = table;
3848 }
@@ -44,6 +54,22 @@
4454 return String.format("Table %s.%s already exists", keyspace, table);
4555 }
4656
57+ /**
58+ * {@inheritDoc}
59+ */
60+ @Override
61+ public InetAddress getHost() {
62+ return address.getAddress();
63+ }
64+
65+ /**
66+ * {@inheritDoc}
67+ */
68+ @Override
69+ public InetSocketAddress getAddress() {
70+ return address;
71+ }
72+
4773 /**
4874 * Returns whether the query yielding this exception was a table creation
4975 * attempt.
@@ -82,6 +108,26 @@
82108
83109 @Override
84110 public DriverException copy() {
85- return new AlreadyExistsException(getMessage(), this, keyspace, table);
111+ return new AlreadyExistsException(getAddress(), getMessage(), this, keyspace, table);
112+ }
113+
114+ /**
115+ * Create a copy of this exception with a nicer stack trace, and including the coordinator
116+ * address that caused this exception to be raised.
117+ * <p>
118+ * This method is mainly intended for internal use by the driver and exists mainly because:
119+ * <ol>
120+ * <li>the original exception was decoded from a response frame
121+ * and at that time, the coordinator address was not available; and</li>
122+ * <li>the newly-created exception will refer to the current thread in its stack trace,
123+ * which generally yields a more user-friendly stack trace that the original one.</li>
124+ * </ol>
125+ *
126+ * @param address The full address of the host that caused this exception to be thrown.
127+ * @return a copy/clone of this exception, but with the given host address instead of the original one.
128+ */
129+ public AlreadyExistsException copy(InetSocketAddress address) {
130+ return new AlreadyExistsException(address, getMessage(), this, keyspace, table);
86131 }
132+
87133 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/AuthenticationException.java +7 −12
@@ -21,7 +21,7 @@
2121 /**
2222 * Indicates an error during the authentication phase while connecting to a node.
2323 */
24-public class AuthenticationException extends DriverException {
24+public class AuthenticationException extends DriverException implements CoordinatorException {
2525
2626 private static final long serialVersionUID = 0;
2727
@@ -32,34 +32,29 @@
3232 this.address = address;
3333 }
3434
35- private AuthenticationException(String message, Throwable cause, InetSocketAddress address)
36- {
35+ private AuthenticationException(InetSocketAddress address, String message, Throwable cause) {
3736 super(message, cause);
3837 this.address = address;
3938 }
4039
4140 /**
42- * The host for which the authentication failed.
43- * <p>
44- * This is a shortcut for {@code getAddress().getAddress()}.
45- *
46- * @return the host for which the authentication failed.
41+ * {@inheritDoc}
4742 */
43+ @Override
4844 public InetAddress getHost() {
4945 return address.getAddress();
5046 }
5147
5248 /**
53- * The full address of the host for which the authentication failed.
54- *
55- * @return the host for which the authentication failed.
49+ * {@inheritDoc}
5650 */
51+ @Override
5752 public InetSocketAddress getAddress() {
5853 return address;
5954 }
6055
6156 @Override
6257 public DriverException copy() {
63- return new AuthenticationException(getMessage(), this, address);
58+ return new AuthenticationException(address, getMessage(), this);
6459 }
6560 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java +12 −4
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
1819 import java.net.InetSocketAddress;
1920
2021 /**
@@ -24,7 +25,7 @@
2425 * because the driver would transparently retry the same query on another host;
2526 * but such exceptions are likely to appear occasionally in the driver logs.
2627 */
27-public class BootstrappingException extends DriverInternalError {
28+public class BootstrappingException extends DriverInternalError implements CoordinatorException {
2829
2930 private static final long serialVersionUID = 0;
3031
@@ -44,10 +45,17 @@
4445 }
4546
4647 /**
47- * The full address of the host that was bootstrapping.
48- *
49- * @return The full address of the host that was bootstrapping.
48+ * {@inheritDoc}
5049 */
50+ @Override
51+ public InetAddress getHost() {
52+ return address.getAddress();
53+ }
54+
55+ /**
56+ * {@inheritDoc}
57+ */
58+ @Override
5159 public InetSocketAddress getAddress() {
5260 return address;
5361 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/CoordinatorException.java +45 −0
@@ -0,0 +1,45 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core.exceptions;
17+
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
21+/**
22+ * An interface for exceptions that are able to report the address of the coordinator host
23+ * that triggered the response error which caused the exception to be raised.
24+ */
25+public interface CoordinatorException {
26+
27+ /**
28+ * The coordinator host that caused this exception to be raised.
29+ * <p>
30+ * This is a shortcut for {@link InetSocketAddress#getAddress() getAddress().getAddress()}.
31+ *
32+ * @return The coordinator host that caused this exception to be raised;
33+ * may be {@code null} if the coordinator is not known.
34+ *
35+ */
36+ InetAddress getHost();
37+
38+ /**
39+ * The full address of the coordinator host that caused this exception to be raised.
40+ *
41+ * @return the full address of the coordinator host that caused this exception to be raised;
42+ * may be {@code null} if the coordinator is not known.
43+ */
44+ InetSocketAddress getAddress();
45+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/DriverException.java +1 −1
@@ -44,7 +44,7 @@
4444 * This return a new exception, equivalent to the original one, except that
4545 * because a new object is created in the current thread, the top-most
4646 * element in the stacktrace of the exception will refer to the current
47- * thread (this mainly use for internal use by the driver). The cause of
47+ * thread (this is mainly intended for internal use by the driver). The cause of
4848 * the copied exception will be the original exception.
4949 *
5050 * @return a copy/clone of this exception.
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/FunctionExecutionException.java +27 −4
@@ -15,23 +15,46 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 /**
1922 * Error during the execution of a function.
2023 */
21-public class FunctionExecutionException extends QueryExecutionException {
24+public class FunctionExecutionException extends QueryExecutionException implements CoordinatorException {
2225
2326 private static final long serialVersionUID = 0;
2427
25- public FunctionExecutionException(String msg) {
28+ private final InetSocketAddress address;
29+
30+ public FunctionExecutionException(InetSocketAddress address, String msg) {
2631 super(msg);
32+ this.address = address;
2733 }
2834
29- private FunctionExecutionException(String msg, Throwable cause) {
35+ private FunctionExecutionException(InetSocketAddress address, String msg, Throwable cause) {
3036 super(msg, cause);
37+ this.address = address;
38+ }
39+
40+ /**
41+ * {@inheritDoc}
42+ */
43+ @Override
44+ public InetAddress getHost() {
45+ return address.getAddress();
46+ }
47+
48+ /**
49+ * {@inheritDoc}
50+ */
51+ @Override
52+ public InetSocketAddress getAddress() {
53+ return address;
3154 }
3255
3356 @Override
3457 public DriverException copy() {
35- return new FunctionExecutionException(getMessage(), this);
58+ return new FunctionExecutionException(address, getMessage(), this);
3659 }
3760 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java +18 −2
@@ -15,6 +15,9 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 /**
1922 * A specific invalid query exception that indicates that the query is invalid
2023 * because of some configuration problem.
@@ -22,11 +25,24 @@
2225 * This is generally throw by query that manipulate the schema (CREATE and
2326 * ALTER) when the required configuration options are invalid.
2427 */
25-public class InvalidConfigurationInQueryException extends InvalidQueryException {
28+public class InvalidConfigurationInQueryException extends InvalidQueryException implements CoordinatorException {
2629
2730 private static final long serialVersionUID = 0;
2831
32+ /**
33+ * @deprecated This constructor is kept for backwards compatibility.
34+ */
35+ @Deprecated
2936 public InvalidConfigurationInQueryException(String msg) {
30- super(msg);
37+ this(null, msg);
38+ }
39+
40+ public InvalidConfigurationInQueryException(InetSocketAddress address, String msg) {
41+ super(address, msg);
42+ }
43+
44+ @Override
45+ public InvalidConfigurationInQueryException copy() {
46+ return new InvalidConfigurationInQueryException(getAddress(), getMessage());
3147 }
3248 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidQueryException.java +28 −3
@@ -15,23 +15,48 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 /**
1922 * Indicates a syntactically correct but invalid query.
2023 */
21-public class InvalidQueryException extends QueryValidationException {
24+public class InvalidQueryException extends QueryValidationException implements CoordinatorException {
2225
2326 private static final long serialVersionUID = 0;
2427
28+ private final InetSocketAddress address;
29+
2530 public InvalidQueryException(String msg) {
31+ this(null, msg);
32+ }
33+
34+ public InvalidQueryException(InetSocketAddress address, String msg) {
2635 super(msg);
36+ this.address = address;
37+ }
38+
39+ public InvalidQueryException(String msg, Throwable cause) {
40+ this(null, msg, cause);
2741 }
2842
29- private InvalidQueryException(String msg, Throwable cause) {
43+ public InvalidQueryException(InetSocketAddress address, String msg, Throwable cause) {
3044 super(msg, cause);
45+ this.address = address;
3146 }
3247
3348 @Override
3449 public DriverException copy() {
35- return new InvalidQueryException(getMessage(), this);
50+ return new InvalidQueryException(getAddress(), getMessage(), this);
51+ }
52+
53+ @Override
54+ public InetAddress getHost() {
55+ return address != null ? address.getAddress() : null;
56+ }
57+
58+ @Override
59+ public InetSocketAddress getAddress() {
60+ return address;
3661 }
3762 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +12 −4
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
1819 import java.net.InetSocketAddress;
1920
2021 /**
@@ -24,7 +25,7 @@
2425 * because the driver would transparently retry the same query on another host;
2526 * but such exceptions are likely to appear occasionally in the driver logs.
2627 */
27-public class OverloadedException extends DriverInternalError {
28+public class OverloadedException extends DriverInternalError implements CoordinatorException {
2829
2930 private static final long serialVersionUID = 0;
3031
@@ -44,10 +45,17 @@
4445 }
4546
4647 /**
47- * The full address of the host that reported itself being overloaded.
48- *
49- * @return The full address of the host that reported itself being overloaded.
48+ * {@inheritDoc}
5049 */
50+ @Override
51+ public InetAddress getHost() {
52+ return address.getAddress();
53+ }
54+
55+ /**
56+ * {@inheritDoc}
57+ */
58+ @Override
5159 public InetSocketAddress getAddress() {
5260 return address;
5361 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/ProtocolError.java +67 −0
@@ -0,0 +1,67 @@
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.exceptions;
17+
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
21+/**
22+ * Indicates that the contacted host reported a protocol error.
23+ * Protocol errors indicate that the client triggered a protocol
24+ * violation (for instance, a QUERY message is sent before a STARTUP one has been sent).
25+ * Protocol errors should be considered as a bug in the driver and reported as such.
26+ */
27+public class ProtocolError extends DriverInternalError implements CoordinatorException {
28+
29+ private static final long serialVersionUID = 0;
30+
31+ private final InetSocketAddress address;
32+
33+ public ProtocolError(InetSocketAddress address, String message) {
34+ super(String.format("An unexpected protocol error occurred on host %s. This is a bug in this library, please report: %s", address, message));
35+ this.address = address;
36+ }
37+
38+ /**
39+ * Private constructor used solely when copying exceptions.
40+ */
41+ private ProtocolError(InetSocketAddress address, String message, ProtocolError cause) {
42+ super(message, cause);
43+ this.address = address;
44+ }
45+
46+
47+ /**
48+ * {@inheritDoc}
49+ */
50+ @Override
51+ public InetAddress getHost() {
52+ return address.getAddress();
53+ }
54+
55+ /**
56+ * {@inheritDoc}
57+ */
58+ @Override
59+ public InetSocketAddress getAddress() {
60+ return address;
61+ }
62+
63+ @Override
64+ public ProtocolError copy() {
65+ return new ProtocolError(address, getMessage(), this);
66+ }
67+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/QueryConsistencyException.java +32 −3
@@ -15,6 +15,9 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 import com.datastax.driver.core.ConsistencyLevel;
1922
2023 /**
@@ -29,21 +32,24 @@
2932 * </ul>.
3033 */
3134 @SuppressWarnings("serial")
32-public abstract class QueryConsistencyException extends QueryExecutionException {
35+public abstract class QueryConsistencyException extends QueryExecutionException implements CoordinatorException {
3336
37+ private final InetSocketAddress address;
3438 private final ConsistencyLevel consistency;
3539 private final int received;
3640 private final int required;
3741
38- protected QueryConsistencyException(String msg, ConsistencyLevel consistency, int received, int required) {
42+ protected QueryConsistencyException(InetSocketAddress address, String msg, ConsistencyLevel consistency, int received, int required) {
3943 super(msg);
44+ this.address = address;
4045 this.consistency = consistency;
4146 this.received = received;
4247 this.required = required;
4348 }
4449
45- protected QueryConsistencyException(String msg, Throwable cause, ConsistencyLevel consistency, int received, int required) {
50+ protected QueryConsistencyException(InetSocketAddress address, String msg, Throwable cause, ConsistencyLevel consistency, int received, int required) {
4651 super(msg, cause);
52+ this.address = address;
4753 this.consistency = consistency;
4854 this.received = received;
4955 this.required = required;
@@ -79,4 +85,27 @@
7985 public int getRequiredAcknowledgements() {
8086 return required;
8187 }
88+
89+ /**
90+ * The coordinator host that caused this exception to be thrown.
91+ * Note that this is the query coordinator host, <em>not</em> the host which timed out.
92+ *
93+ * @return The coordinator host that caused this exception to be thrown, or {@code null} if this exception has been generated driver-side.
94+ */
95+ @Override
96+ public InetAddress getHost() {
97+ return address.getAddress();
98+ }
99+
100+ /**
101+ * The full address of the coordinator host that caused this exception to be thrown.
102+ * Note that this is the query coordinator host, <em>not</em> the host which timed out.
103+ *
104+ * @return the full address of the coordinator host that caused this exception to be thrown,
105+ * or {@code null} if this exception has been generated driver-side.
106+ */
107+ @Override
108+ public InetSocketAddress getAddress() {
109+ return address;
110+ }
82111 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadFailureException.java +26 −4
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetSocketAddress;
19+
1820 import com.datastax.driver.core.ConsistencyLevel;
1921
2022 /**
@@ -28,8 +30,16 @@
2830 private final int failed;
2931 private final boolean dataPresent;
3032
33+ /**
34+ * This constructor should only be used internally by the driver
35+ * when decoding error responses.
36+ */
3137 public ReadFailureException(ConsistencyLevel consistency, int received, int required, int failed, boolean dataPresent) {
32- super(String.format("Cassandra failure during read query at consistency %s "
38+ this(null, consistency, received, required, failed, dataPresent);
39+ }
40+
41+ public ReadFailureException(InetSocketAddress address, ConsistencyLevel consistency, int received, int required, int failed, boolean dataPresent) {
42+ super(address, String.format("Cassandra failure during read query at consistency %s "
3343 + "(%d responses were required but only %d replica responded, %d failed)",
3444 consistency, required, received, failed),
3545 consistency,
@@ -39,8 +49,8 @@
3949 this.dataPresent = dataPresent;
4050 }
4151
42- private ReadFailureException(String msg, Throwable cause, ConsistencyLevel consistency, int received, int required, int failed, boolean dataPresent) {
43- super(msg, cause, consistency, received, required);
52+ private ReadFailureException(InetSocketAddress address, String msg, Throwable cause, ConsistencyLevel consistency, int received, int required, int failed, boolean dataPresent) {
53+ super(address, msg, cause, consistency, received, required);
4454 this.failed = failed;
4555 this.dataPresent = dataPresent;
4656 }
@@ -71,7 +81,19 @@
7181
7282 @Override
7383 public DriverException copy() {
74- return new ReadFailureException(getMessage(), this, getConsistencyLevel(), getReceivedAcknowledgements(),
84+ return new ReadFailureException(getAddress(), getMessage(), this, getConsistencyLevel(), getReceivedAcknowledgements(),
7585 getRequiredAcknowledgements(), getFailures(), wasDataRetrieved());
7686 }
87+
88+ public DriverException copy(InetSocketAddress address) {
89+ return new ReadFailureException(
90+ address,
91+ getMessage(),
92+ this,
93+ getConsistencyLevel(),
94+ getReceivedAcknowledgements(),
95+ getRequiredAcknowledgements(),
96+ failed,
97+ dataPresent);
98+ }
7799 }
No newline at the end of the file
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java +56 −12
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetSocketAddress;
19+
1820 import com.datastax.driver.core.ConsistencyLevel;
1921
2022 /**
@@ -26,16 +28,27 @@
2628
2729 private final boolean dataPresent;
2830
31+ /**
32+ * This constructor should only be used internally by the driver
33+ * when decoding error responses.
34+ */
2935 public ReadTimeoutException(ConsistencyLevel consistency, int received, int required, boolean dataPresent) {
30- super(String.format("Cassandra timeout during read query at consistency %s (%s)", consistency, formatDetails(received, required, dataPresent)),
31- consistency,
32- received,
33- required);
36+ this(null, consistency, received, required, dataPresent);
37+ }
38+
39+ public ReadTimeoutException(InetSocketAddress address, ConsistencyLevel consistency, int received, int required, boolean dataPresent) {
40+ super(
41+ address,
42+ String.format("Cassandra timeout during read query at consistency %s (%s)", consistency, formatDetails(received, required, dataPresent)),
43+ consistency,
44+ received,
45+ required
46+ );
3447 this.dataPresent = dataPresent;
3548 }
3649
37- private ReadTimeoutException(String msg, Throwable cause, ConsistencyLevel consistency, int received, int required, boolean dataPresent) {
38- super(msg, cause, consistency, received, required);
50+ private ReadTimeoutException(InetSocketAddress address, String msg, Throwable cause, ConsistencyLevel consistency, int received, int required, boolean dataPresent) {
51+ super(address, msg, cause, consistency, received, required);
3952 this.dataPresent = dataPresent;
4053 }
4154
@@ -65,11 +78,42 @@
6578
6679 @Override
6780 public DriverException copy() {
68- return new ReadTimeoutException(getMessage(),
69- this,
70- getConsistencyLevel(),
71- getReceivedAcknowledgements(),
72- getRequiredAcknowledgements(),
73- wasDataRetrieved());
81+ return new ReadTimeoutException(
82+ getAddress(),
83+ getMessage(),
84+ this,
85+ getConsistencyLevel(),
86+ getReceivedAcknowledgements(),
87+ getRequiredAcknowledgements(),
88+ wasDataRetrieved()
89+ );
7490 }
91+
92+ /**
93+ * Create a copy of this exception with a nicer stack trace, and including the coordinator
94+ * address that caused this exception to be raised.
95+ * <p>
96+ * This method is mainly intended for internal use by the driver and exists mainly because:
97+ * <ol>
98+ * <li>the original exception was decoded from a response frame
99+ * and at that time, the coordinator address was not available; and</li>
100+ * <li>the newly-created exception will refer to the current thread in its stack trace,
101+ * which generally yields a more user-friendly stack trace that the original one.</li>
102+ * </ol>
103+ *
104+ * @param address The full address of the host that caused this exception to be thrown.
105+ * @return a copy/clone of this exception, but with the given host address instead of the original one.
106+ */
107+ public ReadTimeoutException copy(InetSocketAddress address) {
108+ return new ReadTimeoutException(
109+ address,
110+ getMessage(),
111+ this,
112+ getConsistencyLevel(),
113+ getReceivedAcknowledgements(),
114+ getRequiredAcknowledgements(),
115+ wasDataRetrieved()
116+ );
117+ }
118+
75119 }
added driver-core/src/main/java/com/datastax/driver/core/exceptions/ServerError.java +64 −0
@@ -0,0 +1,64 @@
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.exceptions;
17+
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
21+/**
22+ * Indicates that the contacted host reported un expected error.
23+ */
24+public class ServerError extends DriverInternalError implements CoordinatorException {
25+
26+ private static final long serialVersionUID = 0;
27+
28+ private final InetSocketAddress address;
29+
30+ public ServerError(InetSocketAddress address, String message) {
31+ super(String.format("An unexpected error occurred server side on %s: %s", address, message));
32+ this.address = address;
33+ }
34+
35+ /**
36+ * Private constructor used solely when copying exceptions.
37+ */
38+ private ServerError(InetSocketAddress address, String message, ServerError cause) {
39+ super(message, cause);
40+ this.address = address;
41+ }
42+
43+
44+ /**
45+ * {@inheritDoc}
46+ */
47+ @Override
48+ public InetAddress getHost() {
49+ return address.getAddress();
50+ }
51+
52+ /**
53+ * {@inheritDoc}
54+ */
55+ @Override
56+ public InetSocketAddress getAddress() {
57+ return address;
58+ }
59+
60+ @Override
61+ public ServerError copy() {
62+ return new ServerError(address, getMessage(), this);
63+ }
64+}
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/SyntaxError.java +34 −3
@@ -15,23 +15,54 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 /**
1922 * Indicates a syntax error in a query.
2023 */
21-public class SyntaxError extends QueryValidationException {
24+public class SyntaxError extends QueryValidationException implements CoordinatorException {
2225
2326 private static final long serialVersionUID = 0;
2427
28+ private final InetSocketAddress address;
29+
30+ /**
31+ * @deprecated This constructor is kept for backwards compatibility.
32+ */
33+ @Deprecated
2534 public SyntaxError(String msg) {
35+ this(null, msg);
36+ }
37+
38+ public SyntaxError(InetSocketAddress address, String msg) {
2639 super(msg);
40+ this.address = address;
2741 }
2842
29- private SyntaxError(String msg, Throwable cause) {
43+ private SyntaxError(InetSocketAddress address, String msg, Throwable cause) {
3044 super(msg, cause);
45+ this.address = address;
46+ }
47+
48+ /**
49+ * {@inheritDoc}
50+ */
51+ @Override
52+ public InetAddress getHost() {
53+ return address.getAddress();
54+ }
55+
56+ /**
57+ * {@inheritDoc}
58+ */
59+ @Override
60+ public InetSocketAddress getAddress() {
61+ return address;
3162 }
3263
3364 @Override
3465 public DriverException copy() {
35- return new SyntaxError(getMessage(), this);
66+ return new SyntaxError(getAddress(), getMessage(), this);
3667 }
3768 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java +34 −3
@@ -15,23 +15,54 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 /**
1922 * Error during a truncation operation.
2023 */
21-public class TruncateException extends QueryExecutionException {
24+public class TruncateException extends QueryExecutionException implements CoordinatorException {
2225
2326 private static final long serialVersionUID = 0;
2427
28+ private final InetSocketAddress address;
29+
30+ /**
31+ * @deprecated This constructor is kept for backwards compatibility.
32+ */
33+ @Deprecated
2534 public TruncateException(String msg) {
35+ this(null, msg);
36+ }
37+
38+ public TruncateException(InetSocketAddress address, String msg) {
2639 super(msg);
40+ this.address = address;
2741 }
2842
29- private TruncateException(String msg, Throwable cause) {
43+ private TruncateException(InetSocketAddress address, String msg, Throwable cause) {
3044 super(msg, cause);
45+ this.address = address;
46+ }
47+
48+ /**
49+ * {@inheritDoc}
50+ */
51+ @Override
52+ public InetAddress getHost() {
53+ return address.getAddress();
54+ }
55+
56+ /**
57+ * {@inheritDoc}
58+ */
59+ @Override
60+ public InetSocketAddress getAddress() {
61+ return address;
3162 }
3263
3364 @Override
3465 public DriverException copy() {
35- return new TruncateException(getMessage(), this);
66+ return new TruncateException(getAddress(), getMessage(), this);
3667 }
3768 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java +34 −3
@@ -15,24 +15,55 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 /**
1922 * Indicates that a query cannot be performed due to the authorization
2023 * restrictions of the logged user.
2124 */
22-public class UnauthorizedException extends QueryValidationException {
25+public class UnauthorizedException extends QueryValidationException implements CoordinatorException {
2326
2427 private static final long serialVersionUID = 0;
2528
29+ private final InetSocketAddress address;
30+
31+ /**
32+ * @deprecated This constructor is kept for backwards compatibility.
33+ */
34+ @Deprecated
2635 public UnauthorizedException(String msg) {
36+ this(null, msg);
37+ }
38+
39+ public UnauthorizedException(InetSocketAddress address, String msg) {
2740 super(msg);
41+ this.address = address;
2842 }
2943
30- private UnauthorizedException(String msg, Throwable cause) {
44+ private UnauthorizedException(InetSocketAddress address, String msg, Throwable cause) {
3145 super(msg, cause);
46+ this.address = address;
47+ }
48+
49+ /**
50+ * {@inheritDoc}
51+ */
52+ @Override
53+ public InetAddress getHost() {
54+ return address.getAddress();
55+ }
56+
57+ /**
58+ * {@inheritDoc}
59+ */
60+ @Override
61+ public InetSocketAddress getAddress() {
62+ return address;
3263 }
3364
3465 @Override
3566 public DriverException copy() {
36- return new UnauthorizedException(getMessage(), this);
67+ return new UnauthorizedException(getAddress(), getMessage(), this);
3768 }
3869 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java +53 −4
@@ -15,29 +15,43 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+
1821 import com.datastax.driver.core.ConsistencyLevel;
1922
2023 /**
2124 * Exception thrown when the coordinator knows there is not enough replica
2225 * alive to perform a query with the requested consistency level.
2326 */
24-public class UnavailableException extends QueryExecutionException {
27+public class UnavailableException extends QueryExecutionException implements CoordinatorException {
2528
2629 private static final long serialVersionUID = 0;
2730
31+ private final InetSocketAddress address;
2832 private final ConsistencyLevel consistency;
2933 private final int required;
3034 private final int alive;
3135
36+ /**
37+ * This constructor should only be used internally by the driver
38+ * when decoding error responses.
39+ */
3240 public UnavailableException(ConsistencyLevel consistency, int required, int alive) {
33- super(String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", consistency, required, alive));
41+ this(null, consistency, required, alive);
42+ }
43+
44+ public UnavailableException(InetSocketAddress address, ConsistencyLevel consistency, int required, int alive) {
45+ super(String.format("Not enough replicas available for query at consistency %s (%d required but only %d alive)", consistency, required, alive));
46+ this.address = address;
3447 this.consistency = consistency;
3548 this.required = required;
3649 this.alive = alive;
3750 }
3851
39- private UnavailableException(String message, Throwable cause, ConsistencyLevel consistency, int required, int alive) {
52+ private UnavailableException(InetSocketAddress address, String message, Throwable cause, ConsistencyLevel consistency, int required, int alive) {
4053 super(message, cause);
54+ this.address = address;
4155 this.consistency = consistency;
4256 this.required = required;
4357 this.alive = alive;
@@ -74,8 +88,43 @@
7488 return alive;
7589 }
7690
91+ /**
92+ * {@inheritDoc}
93+ */
94+ @Override
95+ public InetAddress getHost() {
96+ return address.getAddress();
97+ }
98+
99+ /**
100+ * {@inheritDoc}
101+ */
102+ @Override
103+ public InetSocketAddress getAddress() {
104+ return address;
105+ }
106+
77107 @Override
78108 public DriverException copy() {
79- return new UnavailableException(getMessage(), this, consistency, required, alive);
109+ return new UnavailableException(getAddress(), getMessage(), this, consistency, required, alive);
110+ }
111+
112+ /**
113+ * Create a copy of this exception with a nicer stack trace, and including the coordinator
114+ * address that caused this exception to be raised.
115+ * <p>
116+ * This method is mainly intended for internal use by the driver and exists mainly because:
117+ * <ol>
118+ * <li>the original exception was decoded from a response frame
119+ * and at that time, the coordinator address was not available; and</li>
120+ * <li>the newly-created exception will refer to the current thread in its stack trace,
121+ * which generally yields a more user-friendly stack trace that the original one.</li>
122+ * </ol>
123+ *
124+ * @param address The full address of the host that caused this exception to be thrown.
125+ * @return a copy/clone of this exception, but with the given host address instead of the original one.
126+ */
127+ public UnavailableException copy(InetSocketAddress address) {
128+ return new UnavailableException(address, getMessage(), this, consistency, required, alive);
80129 }
81130 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java +12 −4
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetAddress;
1819 import java.net.InetSocketAddress;
1920
2021 /**
@@ -24,7 +25,7 @@
2425 * because the driver would transparently prepare the query and execute it again;
2526 * but such exceptions are likely to appear occasionally in the driver logs.
2627 */
27-public class UnpreparedException extends DriverInternalError {
28+public class UnpreparedException extends DriverInternalError implements CoordinatorException {
2829
2930 private static final long serialVersionUID = 0;
3031
@@ -44,10 +45,17 @@
4445 }
4546
4647 /**
47- * The full address of the host that replied with an UNPREPARED error code.
48- *
49- * @return The full address of the host that replied with an UNPREPARED error code.
48+ * {@inheritDoc}
5049 */
50+ @Override
51+ public InetAddress getHost() {
52+ return address.getAddress();
53+ }
54+
55+ /**
56+ * {@inheritDoc}
57+ */
58+ @Override
5159 public InetSocketAddress getAddress() {
5260 return address;
5361 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteFailureException.java +26 −4
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetSocketAddress;
19+
1820 import com.datastax.driver.core.ConsistencyLevel;
1921 import com.datastax.driver.core.WriteType;
2022
@@ -28,8 +30,16 @@
2830 private final WriteType writeType;
2931 private final int failed;
3032
33+ /**
34+ * This constructor should only be used internally by the driver
35+ * when decoding error responses.
36+ */
3137 public WriteFailureException(ConsistencyLevel consistency, WriteType writeType, int received, int required, int failed) {
32- super(String.format("Cassandra failure during write query at consistency %s "
38+ this(null, consistency, writeType, received, required, failed);
39+ }
40+
41+ public WriteFailureException(InetSocketAddress address, ConsistencyLevel consistency, WriteType writeType, int received, int required, int failed) {
42+ super(address, String.format("Cassandra failure during write query at consistency %s "
3343 + "(%d responses were required but only %d replica responded, %d failed)",
3444 consistency, required, received, failed),
3545 consistency,
@@ -39,9 +49,9 @@
3949 this.failed = failed;
4050 }
4151
42- private WriteFailureException(String msg, Throwable cause,
52+ private WriteFailureException(InetSocketAddress address, String msg, Throwable cause,
4353 ConsistencyLevel consistency, WriteType writeType, int received, int required, int failed) {
44- super(msg, cause, consistency, received, required);
54+ super(address, msg, cause, consistency, received, required);
4555 this.writeType = writeType;
4656 this.failed = failed;
4757 }
@@ -66,7 +76,19 @@
6676
6777 @Override
6878 public DriverException copy() {
69- return new WriteFailureException(getMessage(), this, getConsistencyLevel(), getWriteType(),
79+ return new WriteFailureException(getAddress(), getMessage(), this, getConsistencyLevel(), getWriteType(),
7080 getReceivedAcknowledgements(), getRequiredAcknowledgements(), getFailures());
7181 }
82+
83+ public DriverException copy(InetSocketAddress address) {
84+ return new WriteFailureException(
85+ address,
86+ getMessage(),
87+ this,
88+ getConsistencyLevel(),
89+ getWriteType(),
90+ getReceivedAcknowledgements(),
91+ getRequiredAcknowledgements(),
92+ failed);
93+ }
7294 }
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java +55 −12
@@ -15,6 +15,8 @@
1515 */
1616 package com.datastax.driver.core.exceptions;
1717
18+import java.net.InetSocketAddress;
19+
1820 import com.datastax.driver.core.ConsistencyLevel;
1921 import com.datastax.driver.core.WriteType;
2022
@@ -27,16 +29,26 @@
2729
2830 private final WriteType writeType;
2931
32+ /**
33+ * This constructor should only be used internally by the driver
34+ * when decoding error responses.
35+ */
3036 public WriteTimeoutException(ConsistencyLevel consistency, WriteType writeType, int received, int required) {
31- super(String.format("Cassandra timeout during write query at consistency %s (%d replica were required but only %d acknowledged the write)", consistency, required, received),
32- consistency,
33- received,
34- required);
37+ this(null, consistency, writeType, received, required);
38+ }
39+
40+ public WriteTimeoutException(InetSocketAddress address, ConsistencyLevel consistency, WriteType writeType, int received, int required) {
41+ super(
42+ address,
43+ String.format("Cassandra timeout during write query at consistency %s (%d replica were required but only %d acknowledged the write)", consistency, required, received),
44+ consistency,
45+ received,
46+ required);
3547 this.writeType = writeType;
3648 }
3749
38- private WriteTimeoutException(String msg, Throwable cause, ConsistencyLevel consistency, WriteType writeType, int received, int required) {
39- super(msg, cause, consistency, received, required);
50+ private WriteTimeoutException(InetSocketAddress address, String msg, Throwable cause, ConsistencyLevel consistency, WriteType writeType, int received, int required) {
51+ super(address, msg, cause, consistency, received, required);
4052 this.writeType = writeType;
4153 }
4254
@@ -51,11 +63,42 @@
5163
5264 @Override
5365 public DriverException copy() {
54- return new WriteTimeoutException(getMessage(),
55- this,
56- getConsistencyLevel(),
57- getWriteType(),
58- getReceivedAcknowledgements(),
59- getRequiredAcknowledgements());
66+ return new WriteTimeoutException(
67+ getAddress(),
68+ getMessage(),
69+ this,
70+ getConsistencyLevel(),
71+ getWriteType(),
72+ getReceivedAcknowledgements(),
73+ getRequiredAcknowledgements()
74+ );
6075 }
76+
77+ /**
78+ * Create a copy of this exception with a nicer stack trace, and including the coordinator
79+ * address that caused this exception to be raised.
80+ * <p>
81+ * This method is mainly intended for internal use by the driver and exists mainly because:
82+ * <ol>
83+ * <li>the original exception was decoded from a response frame
84+ * and at that time, the coordinator address was not available; and</li>
85+ * <li>the newly-created exception will refer to the current thread in its stack trace,
86+ * which generally yields a more user-friendly stack trace that the original one.</li>
87+ * </ol>
88+ *
89+ * @param address The full address of the host that caused this exception to be thrown.
90+ * @return a copy/clone of this exception, but with the given host address instead of the original one.
91+ */
92+ public WriteTimeoutException copy(InetSocketAddress address) {
93+ return new WriteTimeoutException(
94+ address,
95+ getMessage(),
96+ this,
97+ getConsistencyLevel(),
98+ getWriteType(),
99+ getReceivedAcknowledgements(),
100+ getRequiredAcknowledgements()
101+ );
102+ }
103+
61104 }
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +3 −0
@@ -208,6 +208,9 @@
208208 String nonLocalHosts = Joiner.on(",").join(notInLocalDC);
209209 logger.warn("Some contact points don't match local data center. Local DC = {}. Non-conforming contact points: {}", localDc, nonLocalHosts);
210210 }
211+
212+ this.index.set(new Random().nextInt(Math.max(hosts.size(), 1)));
213+
211214 }
212215
213216 private String dc(Host host) {
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +18 −0
@@ -79,6 +79,24 @@
7979 return cache;
8080 }
8181
82+ /**
83+ * Returns the {@code i}th value as the Java type matching its CQL type.
84+ *
85+ * @param i the index to retrieve.
86+ * @return the value of the {@code i}th value of this statement.
87+ *
88+ * @throws IllegalStateException if this statement does not have values.
89+ * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object.
90+ */
91+ public Object getObject(int i) {
92+ maybeRebuildCache();
93+ if (values == null || values.isEmpty())
94+ throw new IllegalStateException("This statement does not have values");
95+ if (i < 0 || i >= values.size())
96+ throw new ArrayIndexOutOfBoundsException(i);
97+ return values.get(i);
98+ }
99+
82100 private void maybeRebuildCache() {
83101 if (!dirty && cache != null)
84102 return;
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +37 −0
@@ -34,6 +34,7 @@
3434 private final Where where;
3535 private final Options usings;
3636 private final Conditions conditions;
37+ private boolean ifExists;
3738
3839 Update(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, String keyspace, String table) {
3940 super(keyspace, protocolVersion, codecRegistry);
@@ -42,6 +43,7 @@
4243 this.where = new Where(this);
4344 this.usings = new Options(this);
4445 this.conditions = new Conditions(this);
46+ this.ifExists = false;
4547 }
4648
4749 Update(ProtocolVersion protocolVersion, CodecRegistry codecRegistry, TableMetadata table) {
@@ -51,6 +53,7 @@
5153 this.where = new Where(this);
5254 this.usings = new Options(this);
5355 this.conditions = new Conditions(this);
56+ this.ifExists = false;
5457 }
5558
5659 @Override
@@ -83,6 +86,10 @@
8386 Utils.joinAndAppend(builder, codecRegistry, " AND ", conditions.conditions, variables);
8487 }
8588
89+ if (ifExists) {
90+ builder.append(" IF EXISTS");
91+ }
92+
8693 return builder;
8794 }
8895
@@ -214,6 +221,7 @@
214221 public Conditions onlyIf(Clause condition) {
215222 return statement.onlyIf(condition);
216223 }
224+
217225 }
218226
219227 /**
@@ -269,6 +277,28 @@
269277 public Conditions onlyIf(Clause condition) {
270278 return statement.onlyIf(condition);
271279 }
280+
281+ /**
282+ * Sets the 'IF EXISTS' option for the UPDATE statement this WHERE clause
283+ * is part of.
284+ *
285+ * <p>
286+ * An update with that option will report whether the statement actually
287+ * resulted in data being updated. The existence check and update are
288+ * done transactionally in the sense that if multiple clients attempt to
289+ * update a given row with this option, then at most one may succeed.
290+ * </p>
291+ * <p>
292+ * Please keep in mind that using this option has a non negligible
293+ * performance impact and should be avoided when possible.
294+ * </p>
295+ *
296+ * @return the UPDATE statement this WHERE clause is part of.
297+ */
298+ public IfExists ifExists() {
299+ statement.ifExists = true;
300+ return new IfExists(statement);
301+ }
272302 }
273303
274304 /**
@@ -386,5 +416,12 @@
386416 public Options using(Using using) {
387417 return statement.using(using);
388418 }
419+
420+ }
421+
422+ public static class IfExists extends BuiltStatement.ForwardingStatement<Update> {
423+ IfExists(Update statement) {
424+ super(statement);
425+ }
389426 }
390427 }
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +2 −2
@@ -52,7 +52,7 @@
5252 schedule = new MockReconnectionSchedule();
5353 work = new MockReconnectionWork();
5454 future.set(null);
55- handler = new AbstractReconnectionHandler(executor, schedule, future) {
55+ handler = new AbstractReconnectionHandler("test", executor, schedule, future) {
5656 @Override
5757 protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException {
5858 return work.tryReconnect();
@@ -330,7 +330,7 @@
330330 private void waitForCompletion() {
331331 executor.shutdown();
332332 try {
333- boolean shutdown = executor.awaitTermination(10, TimeUnit.SECONDS);
333+ boolean shutdown = executor.awaitTermination(30, TimeUnit.SECONDS);
334334 if (!shutdown)
335335 fail("executor ran for longer than expected");
336336 } catch (InterruptedException e) {
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +11 −6
@@ -25,8 +25,13 @@
2525
2626 import com.google.common.collect.ImmutableList;
2727 import com.google.common.collect.ImmutableList.Builder;
28+import org.mockito.Mockito;
29+
30+import static org.mockito.Mockito.mock;
2831 import static org.testng.Assert.*;
2932
33+import com.datastax.driver.core.policies.ExponentialReconnectionPolicy;
34+
3035 /**
3136 * Base class for replication strategy tests. Currently only supports testing
3237 * using the default Murmur3Partitioner.
@@ -38,13 +43,13 @@
3843 protected static class HostMock extends Host {
3944 private final String address;
4045
41- private HostMock(String address) throws UnknownHostException {
42- super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.Simple.Factory(), new Cluster("test", null, Configuration.builder().build()).manager);
46+ private HostMock(String address, Cluster.Manager manager) throws UnknownHostException {
47+ super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager);
4348 this.address = address;
4449 }
4550
46- private HostMock(String address, String dc, String rack) throws UnknownHostException {
47- this(address);
51+ private HostMock(String address, String dc, String rack, Cluster.Manager manager) throws UnknownHostException {
52+ this(address, manager);
4853 this.setLocationInfo(dc, rack);
4954 }
5055
@@ -81,7 +86,7 @@
8186 */
8287 protected static HostMock host(String address) {
8388 try {
84- return new HostMock(address);
89+ return new HostMock(address, mock(Cluster.Manager.class));
8590 } catch (UnknownHostException ex) {
8691 throw new RuntimeException(ex); //wrap to avoid declarations
8792 }
@@ -93,7 +98,7 @@
9398 */
9499 protected static HostMock host(String address, String dc, String rack) {
95100 try {
96- return new HostMock(address, dc, rack);
101+ return new HostMock(address, dc, rack, mock(Cluster.Manager.class));
97102 } catch (UnknownHostException ex) {
98103 throw new RuntimeException(ex); //wrap to avoid declarations
99104 }
added driver-core/src/test/java/com/datastax/driver/core/AggregateMetadataAssert.java +41 −0
@@ -0,0 +1,41 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import org.assertj.core.api.AbstractAssert;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+public class AggregateMetadataAssert extends AbstractAssert<AggregateMetadataAssert, AggregateMetadata> {
23+ protected AggregateMetadataAssert(AggregateMetadata actual) {
24+ super(actual, AggregateMetadataAssert.class);
25+ }
26+
27+ public AggregateMetadataAssert hasFullName(String name) {
28+ assertThat(actual.getFullName()).isEqualTo(name);
29+ return this;
30+ }
31+
32+ public AggregateMetadataAssert isInKeyspace(String keyspaceName) {
33+ assertThat(actual.getKeyspace().getName()).isEqualTo(keyspaceName);
34+ return this;
35+ }
36+
37+ public AggregateMetadataAssert hasInitCond(Object initCond) {
38+ assertThat(actual.getInitCond()).isEqualTo(initCond);
39+ return this;
40+ }
41+}
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +12 −0
@@ -45,6 +45,10 @@
4545 return new LocalDateAssert(localDate);
4646 }
4747
48+ public static KeyspaceMetadataAssert assertThat(KeyspaceMetadata metadata) {
49+ return new KeyspaceMetadataAssert(metadata);
50+ }
51+
4852 public static TableMetadataAssert assertThat(TableMetadata table) {
4953 return new TableMetadataAssert(table);
5054 }
@@ -53,6 +57,14 @@
5357 return new ColumnMetadataAssert(column);
5458 }
5559
60+ public static FunctionMetadataAssert assertThat(FunctionMetadata function) {
61+ return new FunctionMetadataAssert(function);
62+ }
63+
64+ public static AggregateMetadataAssert assertThat(AggregateMetadata aggregate) {
65+ return new AggregateMetadataAssert(aggregate);
66+ }
67+
5668 public static TypeCodecAssert assertThat(TypeCodec codec) {
5769 return new TypeCodecAssert(codec);
5870 }
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +78 −3
@@ -16,26 +16,38 @@
1616 package com.datastax.driver.core;
1717
1818 import java.util.Collection;
19+import java.util.concurrent.ExecutionException;
1920 import java.util.concurrent.TimeUnit;
2021
22+import com.google.common.base.Function;
2123 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;
2228 import org.testng.annotations.Test;
2329
30+import static org.assertj.core.api.Assertions.assertThat;
2431 import static org.testng.Assert.assertEquals;
2532 import static org.testng.Assert.assertTrue;
2633
34+import com.datastax.driver.core.exceptions.InvalidQueryException;
35+
2736 public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster {
2837
2938 @Override
3039 protected Collection<String> getTableDefinitions() {
31- return Lists.newArrayList();
40+ return Lists.newArrayList(
41+ "create table foo(k int primary key, v int)",
42+ "insert into foo (k, v) values (1, 1)"
43+ );
3244 }
3345
3446 /**
3547 * Checks that a cancelled query releases the connection (JAVA-407).
3648 */
3749 @Test(groups = "short")
38- public void cancelQueryTest() throws InterruptedException {
50+ public void cancelled_query_should_release_the_connection() throws InterruptedException {
3951 ResultSetFuture future = session.executeAsync("select release_version from system.local");
4052 future.cancel(true);
4153 assertTrue(future.isCancelled());
@@ -48,8 +60,71 @@
4860 }
4961 }
5062
63+ @Test(groups = "short")
64+ public void should_init_cluster_and_session_if_needed() throws Exception {
65+ // For this test we need an uninitialized cluster, so we can't reuse the one provided by the
66+ // parent class. Rebuild a new one with the same (unique) host.
67+ Host host = cluster.getMetadata().allHosts().iterator().next();
68+
69+ Cluster cluster2 = null;
70+ try {
71+ cluster2 = Cluster.builder()
72+ .addContactPointsWithPorts(Lists.newArrayList(host.getSocketAddress()))
73+ .build();
74+ Session session2 = cluster2.newSession();
75+
76+ // Neither cluster2 nor session2 are initialized at this point
77+ assertThat(cluster2.manager.metadata).isNull();
78+
79+ ResultSetFuture future = session2.executeAsync(String.format("select v from %s.foo where k = 1", keyspace));
80+ Row row = Uninterruptibles.getUninterruptibly(future).one();
81+
82+ assertThat(row.getInt(0)).isEqualTo(1);
83+ } finally {
84+ if (cluster2 != null)
85+ cluster2.close();
86+ }
87+ }
88+
89+ @Test(groups = "short")
90+ public void should_chain_query_on_async_session_init() throws Exception {
91+ ListenableFuture<Integer> resultFuture = connectAndQuery(this.keyspace);
92+
93+ Integer result = Uninterruptibles.getUninterruptibly(resultFuture);
94+ assertThat(result).isEqualTo(1);
95+ }
96+
97+ @Test(groups = "short")
98+ public void should_propagate_error_to_chained_query_if_session_init_fails() throws Exception {
99+ ListenableFuture<Integer> resultFuture = connectAndQuery("wrong_keyspace");
100+
101+ try {
102+ Uninterruptibles.getUninterruptibly(resultFuture);
103+ } catch (ExecutionException e) {
104+ assertThat(e.getCause())
105+ .isInstanceOf(InvalidQueryException.class)
106+ .hasMessage("Keyspace 'wrong_keyspace' does not exist");
107+ }
108+ }
109+
110+ private ListenableFuture<Integer> connectAndQuery(String keyspace) {
111+ ListenableFuture<Session> sessionFuture = cluster.connectAsync(keyspace);
112+ ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() {
113+ @Override
114+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
115+ return session.executeAsync("select v from foo where k = 1");
116+ }
117+ });
118+ return Futures.transform(queryFuture, new Function<ResultSet, Integer>() {
119+ @Override
120+ public Integer apply(ResultSet rs) {
121+ return rs.one().getInt(0);
122+ }
123+ });
124+ }
125+
51126 private static HostConnectionPool getPool(Session session) {
52- Collection<HostConnectionPool> pools = ((SessionManager) session).pools.values();
127+ Collection<HostConnectionPool> pools = ((SessionManager)session).pools.values();
53128 assertEquals(pools.size(), 1);
54129 return pools.iterator().next();
55130 }
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +17 −11
@@ -59,36 +59,42 @@
5959
6060 @Test(groups = "short")
6161 public void should_connect_with_credentials() throws InterruptedException {
62+ Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
63+ .withCredentials("cassandra", "cassandra")
64+ .build();
6265 try {
63- Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
64- .withCredentials("cassandra", "cassandra")
65- .build()
66- .connect();
66+ cluster.connect();
6767 } catch (NoHostAvailableException e) {
6868 logger.error(e.getCustomMessage(1, true, true));
69+ } finally {
70+ cluster.close();
6971 }
7072 }
7173
7274 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
7375 public void should_fail_to_connect_with_wrong_credentials() throws InterruptedException {
76+ Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
77+ .withCredentials("bogus", "bogus")
78+ .build();
7479 try {
75- Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
76- .withCredentials("bogus", "bogus")
77- .build()
78- .connect();
80+ cluster.connect();
7981 } catch (NoHostAvailableException e) {
8082 logger.error(e.getCustomMessage(1, true, true));
83+ } finally {
84+ cluster.close();
8185 }
8286 }
8387
8488 @Test(groups = "short", expectedExceptions = AuthenticationException.class)
8589 public void should_fail_to_connect_without_credentials() throws InterruptedException {
90+ Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
91+ .build();
8692 try {
87- Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1')
88- .build()
89- .connect();
93+ cluster.connect();
9094 } catch (NoHostAvailableException e) {
9195 logger.error(e.getCustomMessage(1, true, true));
96+ } finally {
97+ cluster.close();
9298 }
9399 }
94100 }
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +19 −6
@@ -15,12 +15,13 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.util.*;
19-
2018 import org.testng.annotations.Test;
21-import static org.testng.Assert.*;
2219
23-import static com.datastax.driver.core.TestUtils.*;
20+import static org.testng.Assert.assertEquals;
21+import static org.testng.Assert.assertNotNull;
22+import static org.testng.Assert.assertNull;
23+
24+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2425
2526 public class CaseSensitivityTest {
2627
@@ -36,7 +37,13 @@
3637
3738 @Test(groups = "short")
3839 public void testCaseInsensitiveKeyspace() throws Throwable {
39- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder());
40+ CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()
41+ .withQueryOptions(new QueryOptions()
42+ .setRefreshNodeIntervalMillis(0)
43+ .setRefreshNodeListIntervalMillis(0)
44+ .setRefreshSchemaIntervalMillis(0)
45+ )
46+ );
4047 Session s = c.session;
4148 try {
4249 String ksName = "MyKeyspace";
@@ -56,7 +63,13 @@
5663
5764 @Test(groups = "short")
5865 public void testCaseSensitiveKeyspace() throws Throwable {
59- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder());
66+ CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()
67+ .withQueryOptions(new QueryOptions()
68+ .setRefreshNodeIntervalMillis(0)
69+ .setRefreshNodeListIntervalMillis(0)
70+ .setRefreshSchemaIntervalMillis(0)
71+ )
72+ );
6073 Session s = c.session;
6174 try {
6275 String ksName = "\"MyKeyspace\"";
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +11 −2
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetSocketAddress;
1819 import java.util.Iterator;
1920 import java.util.Set;
2021 import java.util.TreeSet;
@@ -44,9 +45,17 @@
4445 public HostAssert host(int hostNumber) {
4546 // TODO at some point this won't work anymore if we have assertions that wait for a node to
4647 // join the cluster, e.g. assertThat(cluster).node(3).comesUp().
47- Host host = TestUtils.findHost(actual, hostNumber);
48+ return new HostAssert(
49+ TestUtils.findHost(actual, hostNumber),
50+ actual);
51+ }
4852
49- return new HostAssert(host, actual);
53+ public HostAssert host(String hostAddress) {
54+ // TODO at some point this won't work anymore if we have assertions that wait for a node to
55+ // join the cluster, e.g. assertThat(cluster).node(3).comesUp().
56+ return new HostAssert(
57+ TestUtils.findHost(actual, hostAddress),
58+ actual);
5059 }
5160
5261 /**
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +105 −65
@@ -17,28 +17,39 @@
1717
1818 import java.net.InetAddress;
1919 import java.net.InetSocketAddress;
20+import java.net.UnknownHostException;
2021 import java.util.Collections;
2122 import java.util.List;
23+import java.util.Map;
2224 import java.util.concurrent.TimeUnit;
2325 import java.util.concurrent.TimeoutException;
2426
27+import com.google.common.collect.ImmutableMap;
28+import com.google.common.collect.ImmutableSet;
2529 import com.google.common.collect.Lists;
30+import org.scassandra.Scassandra;
31+import org.scassandra.http.client.PrimingClient;
32+import org.scassandra.http.client.PrimingRequest;
2633 import org.slf4j.Logger;
2734 import org.slf4j.LoggerFactory;
35+import org.testng.SkipException;
2836 import org.testng.annotations.Test;
2937
30-import static org.assertj.core.api.Assertions.fail;
38+import static org.mockito.Mockito.atLeast;
39+import static org.mockito.Mockito.atMost;
3140 import static org.mockito.Mockito.spy;
32-import static org.mockito.Mockito.times;
3341 import static org.mockito.Mockito.verify;
3442
3543 import com.datastax.driver.core.exceptions.NoHostAvailableException;
3644 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
37-import com.datastax.driver.core.querybuilder.Insert;
38-import com.datastax.driver.core.querybuilder.QueryBuilder;
39-import com.datastax.driver.core.utils.UUIDs;
45+import com.datastax.driver.core.utils.CassandraVersion;
4046
47+import static com.datastax.driver.core.Assertions.*;
4148 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
49+import static com.datastax.driver.core.Host.State.DOWN;
50+import static com.datastax.driver.core.Host.State.UP;
51+import static com.datastax.driver.core.HostDistance.LOCAL;
52+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
4253
4354 public class ClusterInitTest {
4455 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
@@ -47,45 +58,64 @@
4758 * Test for JAVA-522: when the cluster and session initialize, if some contact points are behaving badly and
4859 * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host.
4960 */
50-
5161 @Test(groups = "short")
52- public void should_wait_for_each_contact_point_at_most_once() {
53- CCMBridge ccm = null;
62+ @CassandraVersion(major=2.0, description = "Scassandra currently broken with protocol version 1.")
63+ public void should_handle_failing_or_missing_contact_points() throws UnknownHostException {
64+ if (TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V2) > 0)
65+ throw new SkipException("Scassandra does not yet support protocol >= V3");
66+
5467 Cluster cluster = null;
55- List<FakeHost> fakeHosts = Lists.newArrayList();
68+ Scassandra scassandra = null;
69+ List<FakeHost> failingHosts = Lists.newArrayList();
5670 try {
57- // Obtaining connect timeouts is not trivial: we create a 6-host cluster but only start one of them,
58- // then simulate the other 5.
59- ccm = CCMBridge.builder("test").withNodes(6).notStarted().build();
60- ccm.start(1);
61-
62- for (int i = 0; i < 5; i++) {
63- FakeHost fakeHost = new FakeHost(CCMBridge.ipOfNode(i + 2), 9042, THROWING_CONNECT_TIMEOUTS);
64- fakeHosts.add(fakeHost);
65- fakeHost.start();
71+ // Simulate a cluster of 5 hosts.
72+
73+ // - 1 is an actual Scassandra instance that will accept connections:
74+ scassandra = TestUtils.createScassandraServer();
75+ scassandra.start();
76+ String realHostAddress = "127.0.0.1";
77+ int port = scassandra.getBinaryPort();
78+
79+ // - the remaining 4 are fake servers that will throw connect timeouts:
80+ for (int i = 2; i <= 5; i++) {
81+ FakeHost failingHost = new FakeHost(CCMBridge.ipOfNode(i), port, THROWING_CONNECT_TIMEOUTS);
82+ failingHosts.add(failingHost);
83+ failingHost.start();
6684 }
6785
68- // Our real instance has no rows in its system.peers table. That would cause the driver to ignore our fake
69- // hosts when the control connection refreshes the host list.
70- // So we also insert fake rows in system.peers:
71- fakePeerRowsInNode1();
86+ // - we also have a "missing" contact point, i.e. there's no server listening at this address,
87+ // and the address is not listed in the live host's system.peers
88+ String missingHostAddress = CCMBridge.ipOfNode(6);
89+
90+ primePeerRows(scassandra, failingHosts);
7291
7392 logger.info("Environment is set up, starting test");
7493 long start = System.nanoTime();
7594
76- // We want to count how many connections were attempted. For that, we rely on the fact that SocketOptions.getKeepAlive is called in Connection.Factory.newBoostrap()
77- // each time we prepare to open a new connection. This is a bit of a hack, but this is what we have.
95+ // We want to count how many connections were attempted. For that, we rely on the fact that SocketOptions.getKeepAlive
96+ // is called in Connection.Factory.newBoostrap() each time we prepare to open a new connection.
7897 SocketOptions socketOptions = spy(new SocketOptions());
7998
80- // Set an enormous delay so that reconnection attempts don't pollute our observations
99+ // Set an "infinite" reconnection delay so that reconnection attempts don't pollute our observations
81100 ConstantReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(3600 * 1000);
82101
83- cluster = Cluster.builder().addContactPoints(
84- CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2), CCMBridge.ipOfNode(3),
85- CCMBridge.ipOfNode(4), CCMBridge.ipOfNode(5), CCMBridge.ipOfNode(6))
102+ // Force 1 connection per pool. Otherwise we can't distinguish a failed pool creation from multiple connection
103+ // attempts, because pools create their connections in parallel (so 1 pool failure equals multiple connection failures).
104+ PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(LOCAL, 1, 1);
105+
106+ cluster = Cluster.builder()
107+ .withPort(scassandra.getBinaryPort())
108+ .addContactPoints(
109+ realHostAddress,
110+ failingHosts.get(0).address, failingHosts.get(1).address,
111+ failingHosts.get(2).address, failingHosts.get(3).address,
112+ missingHostAddress
113+ )
86114 .withSocketOptions(socketOptions)
87115 .withReconnectionPolicy(reconnectionPolicy)
116+ .withPoolingOptions(poolingOptions)
88117 .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
118+ .withQueryOptions(nonDebouncingQueryOptions())
89119 .build();
90120 cluster.connect();
91121
@@ -93,69 +123,79 @@
93123 long initTimeMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS);
94124 logger.info("Cluster and session initialized in {} ms", initTimeMs);
95125
96- // We have one live host so 2 successful connections (1 control connection and 1 core connection in the pool).
97- // The other 5 hosts are unreachable, we should attempt to connect to each of them only once.
98- verify(socketOptions, times(1 + TestUtils.numberOfLocalCoreConnections(cluster) + 5)).getKeepAlive();
126+ // Expect :
127+ // - 2 connections for the live host (1 control connection + 1 pooled connection)
128+ // - 1 attempt per failing host (either a control connection attempt or a failed pool creation)
129+ // - 0 or 1 for the missing host. We can't know for sure because contact points are randomized. If it's tried
130+ // before the live host there will be a connection attempt, otherwise it will be removed directly because
131+ // it's not in the live host's system.peers.
132+ verify(socketOptions, atLeast(6)).getKeepAlive();
133+ verify(socketOptions, atMost(7)).getKeepAlive();
134+
135+ assertThat(cluster).host(realHostAddress).isNotNull().hasState(UP);
136+ for (FakeHost failingHost : failingHosts)
137+ assertThat(cluster).host(failingHost.address).hasState(DOWN);
138+ assertThat(cluster).host(missingHostAddress).isNull();
139+
99140 } finally {
100141 if (cluster != null)
101142 cluster.close();
102- for (FakeHost fakeHost : fakeHosts)
143+ for (FakeHost fakeHost : failingHosts)
103144 fakeHost.stop();
104- if (ccm != null)
105- ccm.remove();
145+ if (scassandra != null)
146+ scassandra.stop();
106147 }
107148 }
108149
109150 /**
110- * <p>
111151 * Validates that a Cluster that was never able to successfully establish connection a session can be closed
112152 * properly.
113153 *
114154 * @test_category connection
115155 * @expected_result Cluster closes within 1 second.
116156 */
117- @Test(groups="unit")
157+ @Test(groups = "unit")
118158 public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception {
119159 Cluster cluster = Cluster.builder()
120- .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
121- .build();
160+ .addContactPointsWithPorts(Collections.singleton(new InetSocketAddress("127.0.0.1", 65534)))
161+ .build();
122162 try {
123163 cluster.connect();
124164 fail("Should not have been able to connect.");
125- } catch(NoHostAvailableException e) {} // Expected.
165+ } catch (NoHostAvailableException e) {
166+ } // Expected.
126167 CloseFuture closeFuture = cluster.closeAsync();
127168 try {
128169 closeFuture.get(1, TimeUnit.SECONDS);
129- } catch(TimeoutException e) {
170+ } catch (TimeoutException e) {
130171 fail("Close Future did not complete quickly.");
131172 }
132173 }
133174
134- private void fakePeerRowsInNode1() {
135- Cluster cluster = null;
136- try {
137- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
138- Session session = cluster.connect("system");
139-
140- String releaseVersion = session.execute("SELECT release_version FROM local")
141- .one().getString("release_version");
142-
143- for (int i = 2; i <= 6; i++) {
144- Insert insertStmt = new QueryBuilder(cluster).insertInto("peers")
145- .value("peer", InetAddress.getByName(CCMBridge.ipOfNode(i)))
146- .value("data_center", "datacenter1")
147- .value("host_id", UUIDs.random())
148- .value("rack", "rack1")
149- .value("release_version", releaseVersion)
150- .value("rpc_address", InetAddress.getByName(CCMBridge.ipOfNode(i)))
151- .value("schema_version", UUIDs.random());
152- session.execute(insertStmt);
153- }
154- } catch (Exception e) {
155- fail("Error while inserting fake peer rows", e);
156- } finally {
157- if (cluster != null)
158- cluster.close();
175+ private void primePeerRows(Scassandra scassandra, List<FakeHost> otherHosts) throws UnknownHostException {
176+ PrimingClient primingClient = PrimingClient.builder()
177+ .withHost("localhost").withPort(scassandra.getAdminPort())
178+ .build();
179+
180+ List<Map<String, ?>> rows = Lists.newArrayListWithCapacity(5);
181+
182+ int i = 0;
183+ for (FakeHost otherHost : otherHosts) {
184+ InetAddress address = InetAddress.getByName(otherHost.address);
185+ rows.add(ImmutableMap.<String, Object>builder()
186+ .put("peer", address)
187+ .put("rpc_address", address)
188+ .put("data_center", "datacenter1")
189+ .put("rack", "rack1")
190+ .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++)))
191+ .build());
159192 }
193+
194+ primingClient.prime(
195+ PrimingRequest.queryBuilder()
196+ .withQuery("SELECT * FROM system.peers")
197+ .withColumnTypes(SCassandraCluster.SELECT_PEERS_COLUMN_TYPES)
198+ .withRows(rows)
199+ .build());
160200 }
161201 }
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +70 −3
@@ -15,18 +15,29 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.net.InetAddress;
1819 import java.util.Iterator;
20+import java.util.Map;
1921 import java.util.concurrent.TimeUnit;
2022 import java.util.concurrent.atomic.AtomicInteger;
2123
24+import com.google.common.base.Function;
25+import com.google.common.collect.HashMultiset;
26+import com.google.common.collect.Maps;
27+import org.slf4j.Logger;
28+import org.slf4j.LoggerFactory;
2229 import org.testng.annotations.Test;
2330
24-import static org.assertj.core.api.Assertions.assertThat;
31+import static com.datastax.driver.core.Assertions.assertThat;
32+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
2533
2634 import com.datastax.driver.core.policies.*;
2735 import com.datastax.driver.core.utils.CassandraVersion;
2836
2937 public class ControlConnectionTest {
38+
39+ static final Logger logger = LoggerFactory.getLogger(ControlConnectionTest.class);
40+
3041 @Test(groups = "short")
3142 public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException {
3243 CCMBridge ccm = null;
@@ -122,8 +133,9 @@
122133 ccm = CCMBridge.builder("test").withNodes(3).build();
123134
124135 cluster = Cluster.builder()
125- .addContactPoint(CCMBridge.ipOfNode(1))
126- .build();
136+ .addContactPoint(CCMBridge.ipOfNode(1))
137+ .withQueryOptions(nonDebouncingQueryOptions())
138+ .build();
127139 cluster.init();
128140
129141 // Ensure the control connection host is that of the first node.
@@ -145,6 +157,61 @@
145157 }
146158 }
147159
160+ /**
161+ * <p>
162+ * Ensures that contact points are randomized when determining the initial control connection
163+ * by default. Initializes a cluster with 5 contact points 100 times and ensures that all 5
164+ * were used.
165+ * </p>
166+ *
167+ * @jira_ticket JAVA-618
168+ * @expected_result All 5 hosts were chosen within 100 attempts. There is a very small possibility
169+ * that this may not be the case and this is not actually an error.
170+ * @test_category control_connection
171+ * @since 2.0.11, 2.1.8, 2.2.0
172+ */
173+ @Test(groups = "short")
174+ public void should_randomize_contact_points_when_determining_control_connection() {
175+ int hostCount = 5;
176+ int iterations = 100;
177+ SCassandraCluster scassandras = new SCassandraCluster(hostCount);
178+
179+ try {
180+ final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount);
181+ for(int i = 0; i < iterations; i++) {
182+ Cluster cluster = Cluster.builder()
183+ .addContactPoints(scassandras.addresses())
184+ .build();
185+
186+ try {
187+ cluster.init();
188+ occurrencesByHost.add(cluster.manager.controlConnection.connectedHost().getAddress());
189+ } finally {
190+ cluster.close();
191+ }
192+ }
193+ if(logger.isDebugEnabled()) {
194+ Map<InetAddress, Integer> hostCounts = Maps.toMap(occurrencesByHost.elementSet(), new Function<InetAddress, Integer>() {
195+ @Override
196+ public Integer apply(InetAddress input) {
197+ return occurrencesByHost.count(input);
198+ }
199+ });
200+ logger.debug("Control Connection Use Counts by Host: {}", hostCounts);
201+ }
202+ // There is an incredibly low chance that a host may not be used based on randomness.
203+ // This probability is very low however.
204+ assertThat(occurrencesByHost.elementSet().size())
205+ .as("Not all hosts were used as contact points. There is a very small chance"
206+ + " of this happening based on randomness, investigate whether or not this"
207+ + " is a bug.")
208+ .isEqualTo(hostCount);
209+ } finally {
210+ scassandras.stop();
211+ }
212+
213+ }
214+
148215 static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy {
149216
150217 final AtomicInteger counter = new AtomicInteger();
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +8 −0
@@ -29,6 +29,14 @@
2929 return this;
3030 }
3131
32+ public DataTypeAssert isUserType(String keyspaceName, String userTypeName) {
33+ assertThat(actual).isInstanceOf(UserType.class);
34+ UserType userType = (UserType)this.actual;
35+ assertThat(userType.getKeyspace()).isEqualTo(keyspaceName);
36+ assertThat(userType.getTypeName()).isEqualTo(userTypeName);
37+ return this;
38+ }
39+
3240 public DataTypeAssert isFrozen() {
3341 assertThat(actual.isFrozen()).isTrue();
3442 return this;
added driver-core/src/test/java/com/datastax/driver/core/EventDebouncerIntegrationTest.java +135 −0
@@ -0,0 +1,135 @@
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.Collection;
19+import java.util.concurrent.CountDownLatch;
20+import java.util.concurrent.CyclicBarrier;
21+import java.util.concurrent.TimeUnit;
22+
23+import org.testng.annotations.Test;
24+
25+import static org.assertj.core.api.Assertions.assertThat;
26+import static org.assertj.core.api.Fail.fail;
27+
28+import static com.datastax.driver.core.CCMBridge.ipOfNode;
29+
30+public class EventDebouncerIntegrationTest {
31+
32+ /**
33+ * Tests that DOWN, UP, REMOVE or ADD events will not be delivered to
34+ * load balancing policy nor host state listeners
35+ * before the cluster is fully initialized.
36+ *
37+ * @throws InterruptedException
38+ * @jira_ticket JAVA-784
39+ * @since 2.0.11
40+ */
41+ @Test(groups = "long")
42+ public void should_wait_until_load_balancing_policy_is_fully_initialized() throws InterruptedException {
43+ TestLoadBalancingPolicy policy = new TestLoadBalancingPolicy();
44+ CCMBridge ccm = CCMBridge.builder("main").withNodes(3).build();
45+ final Cluster cluster = new Cluster.Builder()
46+ .addContactPoints(ipOfNode(1))
47+ .withLoadBalancingPolicy(policy)
48+ .withQueryOptions(new QueryOptions()
49+ .setRefreshNodeIntervalMillis(0)
50+ .setRefreshNodeListIntervalMillis(0)
51+ .setRefreshSchemaIntervalMillis(0)
52+ ).build();
53+ try {
54+ new Thread() {
55+ @Override
56+ public void run() {
57+ cluster.init();
58+ }
59+ }.start();
60+ // stop cluster initialization in the middle of LBP initialization
61+ policy.stop();
62+ // generate a DOWN event - will not be delivered immediately
63+ // because the debouncers are not started
64+ // note: a graceful stop notify other nodes which send a topology change event to the driver right away
65+ // while forceStop kills the node so other nodes take much more time to detect node failure
66+ ccm.stop(3);
67+ ccm.waitForDown(3);
68+ // finish cluster initialization and deliver the DOWN event
69+ policy.proceed();
70+ assertThat(policy.onDownCalledBeforeInit).isFalse();
71+ assertThat(policy.onDownCalled()).isTrue();
72+ assertThat(policy.hosts).doesNotContain(TestUtils.findHost(cluster, 3));
73+ } finally {
74+ if (cluster != null)
75+ cluster.close();
76+ ccm.remove("main");
77+ }
78+ }
79+
80+ private class TestLoadBalancingPolicy extends SortingLoadBalancingPolicy {
81+
82+ CyclicBarrier stop = new CyclicBarrier(2);
83+
84+ CyclicBarrier proceed = new CyclicBarrier(2);
85+
86+ CountDownLatch onDownCalled = new CountDownLatch(1);
87+
88+ volatile boolean init = false;
89+
90+ volatile boolean onDownCalledBeforeInit = false;
91+
92+ @Override
93+ public void init(Cluster cluster, Collection<Host> hosts) {
94+ try {
95+ stop.await(1, TimeUnit.MINUTES);
96+ proceed.await(1, TimeUnit.MINUTES);
97+ } catch (Exception e) {
98+ fail(e.getMessage());
99+ }
100+ super.init(cluster, hosts);
101+ init = true;
102+ }
103+
104+ @Override
105+ public void onDown(Host host) {
106+ if (!init)
107+ onDownCalledBeforeInit = true;
108+ super.onDown(host);
109+ if (host.getAddress().toString().contains(ipOfNode(3)))
110+ onDownCalled.countDown();
111+ }
112+
113+ void stop() throws InterruptedException {
114+ try {
115+ stop.await(1, TimeUnit.MINUTES);
116+ } catch (Exception e) {
117+ fail(e.getMessage());
118+ }
119+ }
120+
121+ void proceed() throws InterruptedException {
122+ try {
123+ proceed.await(1, TimeUnit.MINUTES);
124+ } catch (Exception e) {
125+ fail(e.getMessage());
126+ }
127+ }
128+
129+ boolean onDownCalled() throws InterruptedException {
130+ return onDownCalled.await(1, TimeUnit.MINUTES);
131+ }
132+
133+ }
134+
135+}
added driver-core/src/test/java/com/datastax/driver/core/EventDebouncerTest.java +259 −0
@@ -0,0 +1,259 @@
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.ArrayList;
19+import java.util.List;
20+import java.util.concurrent.*;
21+import java.util.concurrent.atomic.AtomicInteger;
22+import java.util.concurrent.locks.Condition;
23+import java.util.concurrent.locks.Lock;
24+import java.util.concurrent.locks.ReentrantLock;
25+
26+import static java.util.concurrent.TimeUnit.MILLISECONDS;
27+import static java.util.concurrent.TimeUnit.SECONDS;
28+
29+import com.google.common.util.concurrent.Futures;
30+import com.google.common.util.concurrent.ListenableFuture;
31+import org.testng.annotations.AfterMethod;
32+import org.testng.annotations.BeforeMethod;
33+import org.testng.annotations.Test;
34+
35+import static org.assertj.core.api.Assertions.assertThat;
36+
37+import com.datastax.driver.core.EventDebouncer.DeliveryCallback;
38+
39+public class EventDebouncerTest {
40+
41+ private ScheduledExecutorService executor;
42+
43+ private MockDeliveryCallback callback;
44+
45+ @BeforeMethod(groups = "unit")
46+ public void setup() {
47+ executor = Executors.newScheduledThreadPool(1);
48+ callback = new MockDeliveryCallback();
49+ }
50+
51+ @AfterMethod(groups = "unit")
52+ public void tearDown() {
53+ executor.shutdownNow();
54+ }
55+
56+ @Test(groups = "unit")
57+ public void should_deliver_single_event() throws InterruptedException {
58+ EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50);
59+ debouncer.start();
60+ MockEvent event = new MockEvent(0);
61+ debouncer.eventReceived(event);
62+ callback.awaitEvents(1);
63+ assertThat(callback.getEvents()).containsOnly(event);
64+ }
65+
66+ @Test(groups = "unit")
67+ public void should_deliver_n_events_in_order() throws InterruptedException {
68+ EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50);
69+ debouncer.start();
70+ List<MockEvent> events = new ArrayList<MockEvent>();
71+ for (int i = 0; i < 50; i++) {
72+ MockEvent event = new MockEvent(i);
73+ events.add(event);
74+ debouncer.eventReceived(event);
75+ }
76+ callback.awaitEvents(50);
77+ assertThat(callback.getEvents()).isEqualTo(events);
78+ assertThat(callback.getInvocations()).isEqualTo(1);
79+ }
80+
81+ @Test(groups = "unit")
82+ public void should_deliver_n_events_in_order_even_if_queue_full() throws InterruptedException {
83+ EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 1);
84+ debouncer.start();
85+ List<MockEvent> events = new ArrayList<MockEvent>();
86+ for (int i = 0; i < 50; i++) {
87+ MockEvent event = new MockEvent(i);
88+ events.add(event);
89+ debouncer.eventReceived(event);
90+ }
91+ callback.awaitEvents(50);
92+ assertThat(callback.getEvents()).isEqualTo(events);
93+ }
94+
95+ @Test(groups = "unit")
96+ public void should_accumulate_events_if_not_ready() throws InterruptedException {
97+ EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50);
98+ List<MockEvent> events = new ArrayList<MockEvent>();
99+ for (int i = 0; i < 50; i++) {
100+ MockEvent event = new MockEvent(i);
101+ events.add(event);
102+ debouncer.eventReceived(event);
103+ }
104+ // simulate late start
105+ debouncer.start();
106+ callback.awaitEvents(50);
107+ assertThat(callback.getEvents()).hasSize(50);
108+ assertThat(callback.getEvents()).isEqualTo(events);
109+ }
110+
111+ @Test(groups = "unit")
112+ public void should_accumulate_all_events_until_start() throws InterruptedException {
113+ final EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 25);
114+ final List<MockEvent> events = new ArrayList<MockEvent>();
115+
116+ for (int i = 0; i < 50; i++) {
117+ MockEvent event = new MockEvent(i);
118+ events.add(event);
119+ debouncer.eventReceived(event);
120+ }
121+
122+ debouncer.start();
123+
124+ callback.awaitEvents(50);
125+ assertThat(callback.getEvents()).isEqualTo(events);
126+ assertThat(callback.getInvocations()).isEqualTo(1);
127+ }
128+
129+ @Test(groups = "unit")
130+ public void should_reset_timer_if_n_events_received_within_same_window() throws InterruptedException {
131+ final EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 50, 50);
132+ debouncer.start();
133+ final CountDownLatch latch = new CountDownLatch(50);
134+ ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
135+ pool.scheduleAtFixedRate(new Runnable() {
136+ @Override
137+ public void run() {
138+ if (latch.getCount() > 0) {
139+ MockEvent event = new MockEvent(0);
140+ debouncer.eventReceived(event);
141+ latch.countDown();
142+ }
143+ }
144+ }, 0, 5, MILLISECONDS);
145+ latch.await();
146+ pool.shutdownNow();
147+ callback.awaitEvents(50);
148+ assertThat(callback.getEvents()).hasSize(50);
149+ assertThat(callback.getInvocations()).isEqualTo(1);
150+ }
151+
152+ @Test(groups = "unit")
153+ public void should_stop_receiving_events() throws InterruptedException {
154+ final EventDebouncer<MockEvent> debouncer = new EventDebouncer<MockEvent>("test", executor, callback, 10, 50);
155+ debouncer.start();
156+ for (int i = 0; i < 50; i++) {
157+ MockEvent event = new MockEvent(i);
158+ debouncer.eventReceived(event);
159+ }
160+ callback.awaitEvents(50);
161+ debouncer.stop();
162+ MockEvent event = new MockEvent(0);
163+ debouncer.eventReceived(event);
164+ assertThat(callback.getEvents()).hasSize(50);
165+ assertThat(callback.getInvocations()).isEqualTo(1);
166+ }
167+
168+ private static class MockDeliveryCallback implements DeliveryCallback<MockEvent> {
169+
170+ final List<MockEvent> events = new CopyOnWriteArrayList<MockEvent>();
171+
172+ final Lock lock = new ReentrantLock();
173+
174+ final Condition cond = lock.newCondition();
175+
176+ final AtomicInteger invocations = new AtomicInteger(0);
177+
178+ @Override
179+ public ListenableFuture<?> deliver(List<MockEvent> events) {
180+ lock.lock();
181+ try {
182+ this.events.addAll(events);
183+ invocations.incrementAndGet();
184+ cond.signal();
185+ } finally {
186+ lock.unlock();
187+ }
188+ return Futures.immediateFuture(null);
189+ }
190+
191+ void awaitEvents(int expected) throws InterruptedException {
192+ long nanos = SECONDS.toNanos(10);
193+ lock.lock();
194+ try {
195+ while (events.size() < expected) {
196+ if (nanos <= 0L)
197+ break; // timeout
198+ nanos = cond.awaitNanos(nanos);
199+ }
200+ } finally {
201+ lock.unlock();
202+ }
203+ }
204+
205+ void awaitInvocations(int expected) throws InterruptedException {
206+ long nanos = SECONDS.toNanos(10);
207+ lock.lock();
208+ try {
209+ while (invocations.get() < expected) {
210+ if (nanos <= 0L)
211+ break; // timeout
212+ nanos = cond.awaitNanos(nanos);
213+ }
214+ } finally {
215+ lock.unlock();
216+ }
217+ }
218+
219+ public List<MockEvent> getEvents() {
220+ return events;
221+ }
222+
223+ public int getInvocations() {
224+ return invocations.get();
225+ }
226+ }
227+
228+ private class MockEvent {
229+
230+ private final int i;
231+
232+ private MockEvent(int i) {
233+ this.i = i;
234+ }
235+
236+ @Override
237+ public boolean equals(Object o) {
238+ if (this == o)
239+ return true;
240+ if (o == null || getClass() != o.getClass())
241+ return false;
242+
243+ MockEvent mockEvent = (MockEvent)o;
244+
245+ return i == mockEvent.i;
246+
247+ }
248+
249+ @Override
250+ public int hashCode() {
251+ return i;
252+ }
253+
254+ @Override
255+ public String toString() {
256+ return "MockEvent" + i;
257+ }
258+ }
259+}
deleted driver-core/src/test/java/com/datastax/driver/core/ExceptionsTest.java +0 −511
@@ -1,511 +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-import java.util.Locale;
19-
20-import com.datastax.driver.core.exceptions.*;
21-import com.datastax.driver.core.policies.Policies;
22-import com.datastax.driver.core.policies.WhiteListPolicy;
23-import com.datastax.driver.core.utils.CassandraVersion;
24-
25-import com.google.common.collect.Lists;
26-import org.testng.annotations.Test;
27-
28-import java.net.InetSocketAddress;
29-
30-import static com.datastax.driver.core.TestUtils.waitForDownWithWait;
31-import static org.assertj.core.api.Assertions.assertThat;
32-import static org.testng.Assert.assertEquals;
33-import static org.testng.Assert.assertTrue;
34-
35-/**
36- * Tests Exception classes with seperate clusters per test, when applicable
37- */
38-public class ExceptionsTest {
39-
40- /**
41- * Tests the AlreadyExistsException.
42- * Create a keyspace twice and a table twice.
43- * Catch and test all the exception methods.
44- */
45- @Test(groups = "short")
46- public void alreadyExistsException() throws Throwable {
47- Cluster.Builder builder = Cluster.builder();
48- CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
49- try {
50- String keyspace = "TestKeyspace";
51- String table = "TestTable";
52-
53- String[] cqlCommands = new String[]{
54- String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
55- "USE " + keyspace,
56- String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)
57- };
58-
59- // Create the schema once
60- c.session.execute(cqlCommands[0]);
61- c.session.execute(cqlCommands[1]);
62- c.session.execute(cqlCommands[2]);
63-
64- // Try creating the keyspace again
65- try {
66- c.session.execute(cqlCommands[0]);
67- } catch (AlreadyExistsException e) {
68- String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase());
69- assertEquals(e.getMessage(), expected);
70- assertEquals(e.getKeyspace(), keyspace.toLowerCase());
71- assertEquals(e.getTable(), null);
72- assertEquals(e.wasTableCreation(), false);
73- }
74-
75- c.session.execute(cqlCommands[1]);
76-
77- // Try creating the table again
78- try {
79- c.session.execute(cqlCommands[2]);
80- } catch (AlreadyExistsException e) {
81- // is released
82- assertEquals(e.getKeyspace(), keyspace.toLowerCase());
83- assertEquals(e.getTable(), table.toLowerCase());
84- assertEquals(e.wasTableCreation(), true);
85- }
86- } catch (Throwable e) {
87- throw e;
88- } finally {
89- c.discard();
90- }
91- }
92-
93- /**
94- * Tests DriverInternalError.
95- * Tests basic message, rethrow, and copy abilities.
96- */
97- @Test(groups = "unit")
98- public void driverInternalError() throws Exception {
99- String errorMessage = "Test Message";
100-
101- try {
102- throw new DriverInternalError(errorMessage);
103- } catch (DriverInternalError e1) {
104- try {
105- throw new DriverInternalError(e1);
106- } catch (DriverInternalError e2) {
107- assertTrue(e2.getMessage().contains(errorMessage));
108-
109- DriverInternalError copy = (DriverInternalError) e2.copy();
110- assertEquals(copy.getMessage(), e2.getMessage());
111- }
112- }
113- }
114-
115- /**
116- * Tests InvalidConfigurationInQueryException.
117- * Tests basic message abilities.
118- */
119- @Test(groups = "unit")
120- public void invalidConfigurationInQueryException() throws Exception {
121- String errorMessage = "Test Message";
122-
123- try {
124- throw new InvalidConfigurationInQueryException(errorMessage);
125- } catch (InvalidConfigurationInQueryException e) {
126- assertEquals(e.getMessage(), errorMessage);
127- }
128- }
129-
130- /**
131- * Tests InvalidQueryException.
132- * Tests basic message and copy abilities.
133- */
134- @Test(groups = "unit")
135- public void invalidQueryException() throws Exception {
136- String errorMessage = "Test Message";
137-
138- try {
139- throw new InvalidQueryException(errorMessage);
140- } catch (InvalidQueryException e) {
141- assertEquals(e.getMessage(), errorMessage);
142-
143- InvalidQueryException copy = (InvalidQueryException) e.copy();
144- assertEquals(copy.getMessage(), e.getMessage());
145- }
146- }
147-
148- /**
149- * Tests InvalidTypeException.
150- * Tests basic message and copy abilities.
151- */
152- @Test(groups = "unit")
153- public void invalidTypeException() throws Exception {
154- String errorMessage = "Test Message";
155-
156- try {
157- throw new InvalidTypeException(errorMessage);
158- } catch (InvalidTypeException e) {
159- assertEquals(e.getMessage(), errorMessage);
160-
161- InvalidTypeException copy = (InvalidTypeException) e.copy();
162- assertEquals(copy.getMessage(), e.getMessage());
163- }
164- }
165-
166- /**
167- * Tests the NoHostAvailableException.
168- * by attempting to build a cluster using the IP address "255.255.255.255"
169- * and test all available exception methods.
170- */
171- @Test(groups = "short")
172- public void noHostAvailableException() throws Exception {
173- try {
174- Cluster.builder().addContactPoints("255.255.255.255").build();
175- } catch (NoHostAvailableException e) {
176- assertEquals(e.getErrors().size(), 1);
177- assertTrue(e.getErrors().values().iterator().next().toString().contains("[/255.255.255.255] Cannot connect"));
178-
179- NoHostAvailableException copy = (NoHostAvailableException) e.copy();
180- assertEquals(copy.getMessage(), e.getMessage());
181- assertEquals(copy.getErrors(), e.getErrors());
182- }
183- }
184-
185- /**
186- * Tests the ReadTimeoutException.
187- * Create a 3 node cluster and write out a single key at CL.ALL.
188- * Then forcibly kill single node and attempt a read of the key at CL.ALL.
189- * Catch and test all available exception methods.
190- */
191- @Test(groups = "long")
192- public void readTimeoutException() throws Throwable {
193- Cluster.Builder builder = Cluster.builder();
194- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
195- try {
196- String keyspace = "TestKeyspace";
197- String table = "TestTable";
198- int replicationFactor = 3;
199- String key = "1";
200-
201- c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor));
202- c.session.execute("USE " + keyspace);
203- c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
204-
205- c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
206- c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
207-
208- c.cassandraCluster.forceStop(2);
209- try{
210- c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
211- } catch (ReadTimeoutException e) {
212- assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL);
213- assertEquals(e.getReceivedAcknowledgements(), 2);
214- assertEquals(e.getRequiredAcknowledgements(), 3);
215- assertEquals(e.wasDataRetrieved(), true);
216-
217- ReadTimeoutException copy = (ReadTimeoutException) e.copy();
218- assertEquals(copy.getMessage(), e.getMessage());
219- assertEquals(copy.wasDataRetrieved(), e.wasDataRetrieved());
220- }
221- } catch (Throwable e) {
222- throw e;
223- } finally {
224- c.discard();
225- }
226- }
227-
228- /**
229- * Tests SyntaxError.
230- * Tests basic message and copy abilities.
231- */
232- @Test(groups = "unit")
233- public void syntaxError() throws Exception {
234- String errorMessage = "Test Message";
235-
236- try {
237- throw new SyntaxError(errorMessage);
238- } catch (SyntaxError e) {
239- assertEquals(e.getMessage(), errorMessage);
240-
241- SyntaxError copy = (SyntaxError) e.copy();
242- assertEquals(copy.getMessage(), e.getMessage());
243- }
244- }
245-
246- /**
247- * Tests TraceRetrievalException.
248- * Tests basic message and copy abilities.
249- */
250- @Test(groups = "unit")
251- public void traceRetrievalException() throws Exception {
252- String errorMessage = "Test Message";
253-
254- try {
255- throw new TraceRetrievalException(errorMessage);
256- } catch (TraceRetrievalException e) {
257- assertEquals(e.getMessage(), errorMessage);
258-
259- TraceRetrievalException copy = (TraceRetrievalException) e.copy();
260- assertEquals(copy.getMessage(), e.getMessage());
261- }
262- }
263-
264- /**
265- * Tests TruncateException.
266- * Tests basic message and copy abilities.
267- */
268- @Test(groups = "unit")
269- public void truncateException() throws Exception {
270- String errorMessage = "Test Message";
271-
272- try {
273- throw new TruncateException(errorMessage);
274- } catch (TruncateException e) {
275- assertEquals(e.getMessage(), errorMessage);
276-
277- TruncateException copy = (TruncateException) e.copy();
278- assertEquals(copy.getMessage(), e.getMessage());
279- }
280- }
281-
282- /**
283- * Tests UnauthorizedException.
284- * Tests basic message and copy abilities.
285- */
286- @Test(groups = "unit")
287- public void unauthorizedException() throws Exception {
288- String errorMessage = "Test Message";
289-
290- try {
291- throw new UnauthorizedException(errorMessage);
292- } catch (UnauthorizedException e) {
293- assertEquals(e.getMessage(), errorMessage);
294-
295- UnauthorizedException copy = (UnauthorizedException) e.copy();
296- assertEquals(copy.getMessage(), e.getMessage());
297- }
298- }
299-
300- /**
301- * Tests the UnavailableException.
302- * Create a 3 node cluster and write out a single key at CL.ALL.
303- * Then kill single node, wait for gossip to propogate the new state,
304- * and attempt to read and write the same key at CL.ALL.
305- * Catch and test all available exception methods.
306- */
307- @Test(groups = "long")
308- public void unavailableException() throws Throwable {
309- Cluster.Builder builder = Cluster.builder();
310- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
311- try {
312- String keyspace = "TestKeyspace";
313- String table = "TestTable";
314- int replicationFactor = 3;
315- String key = "1";
316-
317- c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor));
318- c.session.execute("USE " + keyspace);
319- c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
320-
321- c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
322- c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
323-
324- c.cassandraCluster.stop(2);
325-
326- waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 10);
327-
328- try{
329- c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
330- } catch (UnavailableException e) {
331- String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2);
332- assertEquals(e.getMessage(), expectedError);
333- assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL);
334- assertEquals(e.getRequiredReplicas(), replicationFactor);
335- assertEquals(e.getAliveReplicas(), replicationFactor - 1);
336- }
337-
338- try{
339- c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
340- } catch (UnavailableException e) {
341- String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2);
342- assertEquals(e.getMessage(), expectedError);
343- assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL);
344- assertEquals(e.getRequiredReplicas(), replicationFactor);
345- assertEquals(e.getAliveReplicas(), replicationFactor - 1);
346- }
347- } catch (Throwable e) {
348- throw e;
349- } finally {
350- c.discard();
351- }
352- }
353-
354- /**
355- * Tests the WriteTimeoutException.
356- * Create a 3 node cluster and write out a single key at CL.ALL.
357- * Then forcibly kill single node and attempt to write the same key at CL.ALL.
358- * Catch and test all available exception methods.
359- */
360- @Test(groups = "long")
361- public void writeTimeoutException() throws Throwable {
362- Cluster.Builder builder = Cluster.builder();
363- CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder);
364- try {
365- String keyspace = "TestKeyspace";
366- String table = "TestTable";
367- int replicationFactor = 3;
368- String key = "1";
369-
370- c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor));
371- c.session.execute("USE " + keyspace);
372- c.session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table));
373-
374- c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
375- c.session.execute(c.session.newSimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL));
376-
377- c.cassandraCluster.forceStop(2);
378- try{
379- c.session.execute(c.session.newSimpleStatement(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL));
380- } catch (WriteTimeoutException e) {
381- assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL);
382- assertEquals(e.getReceivedAcknowledgements(), 2);
383- assertEquals(e.getRequiredAcknowledgements(), 3);
384- assertEquals(e.getWriteType(), WriteType.SIMPLE);
385- }
386- } catch (Throwable e) {
387- throw e;
388- } finally {
389- c.discard();
390- }
391- }
392-
393- /**
394- * Validates that a write_failure emitted from a coordinator is properly surfaced as a WriteFailureException.
395- *
396- * Uses JVM argument '-Dcassandra.test.fail_writes_ks=keyspace' in C* to generate write failures for a particular
397- * keyspace to reliably generate write_failure-based errors.
398- *
399- * @since 2.2.0
400- * @jira_ticket JAVA-749
401- * @expected_result WriteFailureException is generated for a failed read.
402- * @test_category queries:basic
403- */
404- @CassandraVersion(major=2.2)
405- @Test(groups = "long", expectedExceptions = WriteFailureException.class)
406- public void should_rethrow_write_failure_when_encountered_on_replica() throws InterruptedException {
407- String keyspace = "writefailureks";
408-
409- CCMBridge ccm = null;
410- Cluster cluster = null;
411-
412- try {
413- ccm = CCMBridge.builder("test").withNodes(2).notStarted().build();
414- // Configure 1 of the nodes to fail writes to the keyspace.
415- ccm.start(1, "-Dcassandra.test.fail_writes_ks=" +keyspace);
416- ccm.start(2);
417-
418- cluster = Cluster.builder()
419- .addContactPoint(CCMBridge.ipOfNode(2))
420- .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
421- Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(2), 9042))))
422- .build();
423-
424- Session session = cluster.connect();
425-
426- session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 2));
427- session.execute("USE " + keyspace);
428- session.execute("CREATE TABLE testtable (k text PRIMARY KEY, t text, i int, f float)");
429-
430- try {
431- // Query with a CL of ALL to hit all replicas.
432- session.execute(session.newSimpleStatement(String.format(Locale.US, "INSERT INTO testtable (k, t, i, f) VALUES ('%s', '%s', %d, %f)", "1", "2", 3, 4.0f))
433- .setConsistencyLevel(ConsistencyLevel.ALL));
434- } catch(WriteFailureException e) {
435- // Expect a failure for node configured to fail writes.
436- assertThat(e.getFailures()).isEqualTo(1);
437- // The one node not configured to fail writes should succeed if response processed quickly enough.
438- assertThat(e.getReceivedAcknowledgements()).isLessThanOrEqualTo(1);
439- // There should be 2 required acknowledgements since CL ALL is used.
440- assertThat(e.getRequiredAcknowledgements()).isEqualTo(2);
441- // A simple query was executed so that should be the write type.
442- assertThat(e.getWriteType()).isEqualTo(WriteType.SIMPLE);
443- // Rethrow to trigger validation on expectedExceptions.
444- throw e;
445- }
446- } finally {
447- if (cluster != null)
448- cluster.close();
449- if (ccm != null)
450- ccm.remove();
451- }
452- }
453-
454- /**
455- * Validates that a read_failure emitted from a coordinator is properly surfaced as a ReadFailureException.
456- *
457- * Configures C* nodes with a 'tombstone_failure_threshold' of 1000 so that whenever of a read of a row scans more
458- * than 1000 tombstones an exception is emitted, which should cause a read_failure.
459- *
460- * @since 2.2.0
461- * @jira_ticket JAVA-749
462- * @expected_result ReadFailureException is generated for a failed read caused by the tombstone_failure_threshold
463- * being exceeded.
464- * @test_category queries:basic
465- */
466- @Test(groups = "short", expectedExceptions = ReadFailureException.class)
467- @CassandraVersion(major = 2.2)
468- public void should_rethrow_read_failure_when_tombstone_overwhelm_on_replica() throws InterruptedException {
469- CCMBridge ccm = null;
470- Cluster cluster = null;
471- try {
472- ccm = CCMBridge.builder("test")
473- .withNodes(2)
474- .withCassandraConfiguration("tombstone_failure_threshold", "1000")
475- .build();
476-
477- // The rest of the test relies on the fact that the PK '1' will be placed on node1
478- // (hard-coding it is reasonable considering that C* shouldn't change its default partitioner too often)
479- cluster = Cluster.builder()
480- .addContactPoint(CCMBridge.ipOfNode(2))
481- .withLoadBalancingPolicy(new WhiteListPolicy(Policies.defaultLoadBalancingPolicy(),
482- Lists.newArrayList(new InetSocketAddress(CCMBridge.ipOfNode(2), 9042))))
483- .build();
484-
485- Session session = cluster.connect();
486- session.execute("create KEYSPACE test WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
487- session.execute("create table test.foo(pk int, cc int, v int, primary key (pk, cc))");
488-
489- // Generate 1001 tombstones on node1
490- for (int i = 0; i < 1001; i++)
491- session.execute("insert into test.foo (pk, cc, v) values (1, ?, null)", i);
492-
493- try {
494- session.execute("select * from test.foo");
495- } catch(ReadFailureException e) {
496- assertThat(e.getFailures()).isEqualTo(1);
497- assertThat(e.wasDataRetrieved()).isFalse();
498- assertThat(e.getReceivedAcknowledgements()).isEqualTo(0);
499- assertThat(e.getRequiredAcknowledgements()).isEqualTo(1);
500- // Rethrow to trigger validation on expectedExceptions.
501- throw e;
502- }
503-
504- } finally {
505- if (cluster != null)
506- cluster.close();
507- if (ccm != null)
508- ccm.remove();
509- }
510- }
511-}
modified driver-core/src/test/java/com/datastax/driver/core/FakeHost.java +1 −1
@@ -31,7 +31,7 @@
3131 public class FakeHost {
3232 public enum Behavior {THROWING_CONNECT_TIMEOUTS, THROWING_OPERATION_TIMEOUTS}
3333
34- private final String address;
34+ final String address;
3535 private final int port;
3636 private final Behavior behavior;
3737 private final ExecutorService executor;
added driver-core/src/test/java/com/datastax/driver/core/FunctionMetadataAssert.java +41 −0
@@ -0,0 +1,41 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import org.assertj.core.api.AbstractAssert;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+public class FunctionMetadataAssert extends AbstractAssert<FunctionMetadataAssert, FunctionMetadata> {
23+ protected FunctionMetadataAssert(FunctionMetadata actual) {
24+ super(actual, FunctionMetadataAssert.class);
25+ }
26+
27+ public FunctionMetadataAssert hasFullName(String name) {
28+ assertThat(actual.getFullName()).isEqualTo(name);
29+ return this;
30+ }
31+
32+ public FunctionMetadataAssert isInKeyspace(String keyspaceName) {
33+ assertThat(actual.getKeyspace().getName()).isEqualTo(keyspaceName);
34+ return this;
35+ }
36+
37+ public FunctionMetadataAssert hasBody(String body) {
38+ assertThat(actual.getBody()).isEqualTo(body);
39+ return this;
40+ }
41+}
added driver-core/src/test/java/com/datastax/driver/core/KeyspaceMetadataAssert.java +41 −0
@@ -0,0 +1,41 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import org.assertj.core.api.AbstractAssert;
19+
20+import static org.assertj.core.api.Assertions.assertThat;
21+
22+public class KeyspaceMetadataAssert extends AbstractAssert<KeyspaceMetadataAssert, KeyspaceMetadata> {
23+ protected KeyspaceMetadataAssert(KeyspaceMetadata actual) {
24+ super(actual, KeyspaceMetadataAssert.class);
25+ }
26+
27+ public KeyspaceMetadataAssert hasName(String name) {
28+ assertThat(actual.getName()).isEqualTo(name);
29+ return this;
30+ }
31+
32+ public KeyspaceMetadataAssert isDurableWrites() {
33+ assertThat(actual.isDurableWrites()).isTrue();
34+ return this;
35+ }
36+
37+ public KeyspaceMetadataAssert isNotDurableWrites() {
38+ assertThat(actual.isDurableWrites()).isFalse();
39+ return this;
40+ }
41+}
modified driver-core/src/test/java/com/datastax/driver/core/MetadataTest.java +2 −0
@@ -21,6 +21,7 @@
2121 import org.testng.annotations.Test;
2222
2323 import static com.datastax.driver.core.Assertions.assertThat;
24+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
2425 import static com.datastax.driver.core.TestUtils.waitFor;
2526
2627 public class MetadataTest {
@@ -58,6 +59,7 @@
5859
5960 cluster = Cluster.builder()
6061 .addContactPoint(CCMBridge.ipOfNode(1))
62+ .withQueryOptions(nonDebouncingQueryOptions())
6163 .build();
6264 Session session = cluster.connect();
6365
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +9 −4
@@ -23,6 +23,8 @@
2323 import io.netty.channel.EventLoopGroup;
2424 import io.netty.channel.nio.NioEventLoopGroup;
2525 import io.netty.channel.socket.SocketChannel;
26+import io.netty.util.HashedWheelTimer;
27+import io.netty.util.Timer;
2628 import org.mockito.ArgumentCaptor;
2729 import org.mockito.invocation.InvocationOnMock;
2830 import org.mockito.stubbing.Answer;
@@ -52,7 +54,9 @@
5254 try {
5355 NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
5456 EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
55- when(nettyOptions.eventLoopGroup(any(ThreadFactory.class))).thenReturn(eventLoopGroup);
57+ Timer timer = new HashedWheelTimer();
58+ doReturn(eventLoopGroup).when(nettyOptions).eventLoopGroup(any(ThreadFactory.class));
59+ doReturn(timer).when(nettyOptions).timer(any(ThreadFactory.class));
5660 final ChannelHandler handler = mock(ChannelHandler.class);
5761 doAnswer(new Answer() {
5862 @Override
@@ -80,17 +84,18 @@
8084
8185 cluster.close();
8286 // then
83- ArgumentCaptor<EventLoopGroup> captor = ArgumentCaptor.forClass(EventLoopGroup.class);
8487 verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
8588 verify(nettyOptions, times(1)).channelClass();
89+ verify(nettyOptions, times(1)).timer(any(ThreadFactory.class));
8690 // per-connection hooks will be called coreConnections * hosts + 1 times:
8791 // the extra call is for the control connection
8892 verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
8993 verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
9094 verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
9195 verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
92- verify(nettyOptions, times(1)).onClusterClose(captor.capture());
93- assertThat(captor.getValue()).isSameAs(eventLoopGroup);
96+ verify(nettyOptions, times(1)).onClusterClose(eventLoopGroup);
97+ verify(nettyOptions, times(1)).onClusterClose(timer);
98+ verifyNoMoreInteractions(nettyOptions);
9499 } finally {
95100 if (cluster != null)
96101 cluster.close();
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +31 −0
@@ -22,6 +22,8 @@
2222 import com.google.common.collect.ImmutableList;
2323 import com.google.common.collect.ImmutableMap;
2424 import com.google.common.collect.ImmutableMap.Builder;
25+import com.google.common.collect.Lists;
26+import com.google.common.collect.Maps;
2527 import org.apache.log4j.Level;
2628 import org.apache.log4j.Logger;
2729 import org.testng.annotations.Test;
@@ -104,6 +106,18 @@
104106
105107 private static final ReplicationStrategy exampleStrategyTooManyReplicas = networkTopologyStrategy(rf(DC1, 4), rf(DC2, 4));
106108
109+ private static final List<Token> largeRing = Lists.newArrayList();
110+ private static final Map<Token, Host> largeRingTokenToPrimary = Maps.newHashMap();
111+ static {
112+ for (int i = 0; i < 100; i++) {
113+ for (int vnodes = 0; vnodes < 256; vnodes++) {
114+ Token token = token("" + ((i * 256) + vnodes));
115+ largeRing.add(token);
116+ largeRingTokenToPrimary.put(token, host("127.0.0." + i, DC1, RACK11));
117+ }
118+ }
119+ }
120+
107121 private static final List<Token> exampleRing = ImmutableList.<Token>builder()
108122 .add(TOKEN01)
109123 .add(TOKEN02)
@@ -570,6 +584,23 @@
570584 assertReplicaPlacement(replicaMap, TOKEN18, IP6, IP1, IP5, IP2);
571585 }
572586
587+ @Test(groups = "unit")
588+ public void networkTopologyStrategyNoNodesInDCTest() {
589+ long t1 = System.currentTimeMillis();
590+ Map<Token, Set<Host>> replicaMap = networkTopologyStrategy(rf(DC1, 2), rf(DC2, 2))
591+ .computeTokenToReplicaMap(largeRingTokenToPrimary, largeRing);
592+ assertThat(System.currentTimeMillis() - t1).isLessThan(10000);
593+
594+ for (int node = 0; node < 99; node++) { // 100th wraps so doesn't match this, check after
595+ for (int vnodes = 0; vnodes < 256; vnodes++) {
596+ Token token = token("" + ((node * 256) + vnodes));
597+ assertReplicaPlacement(replicaMap, token, "127.0.0." + node, "127.0.0." + (node + 1));
598+ }
599+ }
600+ assertReplicaPlacement(replicaMap, token(""+ 99 * 256), "127.0.0.99", "127.0.0.0");
601+ }
602+
603+
573604 @Test(groups = "unit")
574605 public void networkTopologyStrategyExampleTopologyTooManyReplicasTest() {
575606 Map<Token, Set<Host>> replicaMap = exampleStrategyTooManyReplicas.computeTokenToReplicaMap(exampleTokenToPrimary, exampleRing);
added driver-core/src/test/java/com/datastax/driver/core/NodeListRefreshDebouncerTest.java +124 −0
@@ -0,0 +1,124 @@
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.Collection;
19+
20+import org.testng.annotations.*;
21+
22+import static com.google.common.collect.Lists.newArrayList;
23+import static org.mockito.Mockito.reset;
24+import static org.mockito.Mockito.spy;
25+import static org.mockito.Mockito.timeout;
26+import static org.mockito.Mockito.times;
27+import static org.mockito.Mockito.verify;
28+
29+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
30+
31+public class NodeListRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
32+
33+ private static final int DEBOUNCE_TIME = 2000;
34+
35+ QueryOptions queryOptions;
36+
37+ Cluster cluster2;
38+
39+ Session session2;
40+
41+ // Control Connection to be spied.
42+ private ControlConnection controlConnection;
43+
44+ // Keyspaces to drop after test completes.
45+ private Collection<String> keyspaces = newArrayList();
46+
47+ @Override
48+ protected Collection<String> getTableDefinitions() {
49+ return newArrayList();
50+ }
51+
52+ @BeforeClass(groups = "short")
53+ public void setup() {
54+ queryOptions = new QueryOptions();
55+ queryOptions.setRefreshNodeListIntervalMillis(DEBOUNCE_TIME);
56+ queryOptions.setMaxPendingRefreshNodeListRequests(5);
57+ queryOptions.setRefreshSchemaIntervalMillis(0);
58+ // Create a separate cluster that will receive the schema events on its control connection.
59+ cluster2 = this.configure(Cluster.builder())
60+ .addContactPointsWithPorts(newArrayList(hostAddress))
61+ .withQueryOptions(queryOptions)
62+ .build();
63+ session2 = cluster2.connect();
64+
65+ // Create a spy of the Cluster's control connection and replace it with the spy.
66+ controlConnection = spy(cluster2.manager.controlConnection);
67+ cluster2.manager.controlConnection = controlConnection;
68+ reset(controlConnection);
69+ }
70+
71+ @AfterMethod(groups = "short")
72+ public void beforeMethod() {
73+ reset(controlConnection);
74+ }
75+
76+ @AfterClass(groups = "short")
77+ public void teardown() {
78+ cluster2.close();
79+ // drop all keyspaces
80+ for(String keyspace : keyspaces) {
81+ session.execute("DROP KEYSPACE " + keyspace);
82+ }
83+ }
84+
85+ /**
86+ * Ensures that when a keyspace is created that refresh node list request
87+ * is debounced and processed within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
88+ * + {@link QueryOptions#getRefreshNodeListIntervalMillis()}.
89+ *
90+ * @jira_ticket JAVA-657
91+ * @since 2.0.11
92+ */
93+ @Test(groups = "short")
94+ public void should_debounce_refresh_when_keyspace_created() {
95+ String keyspace = "sdrwkc";
96+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
97+ keyspaces.add(keyspace);
98+
99+ verify(controlConnection, timeout(DEBOUNCE_TIME + queryOptions.getRefreshSchemaIntervalMillis())).refreshNodeListAndTokenMap();
100+ }
101+
102+ /**
103+ * Ensures that when enough refreshNodeList requests have been received
104+ * to reach {@link QueryOptions#getMaxPendingRefreshNodeListRequests()} that a
105+ * node list refresh is submitted right away.
106+ *
107+ * @jira_ticket JAVA-657
108+ * @since 2.0.11
109+ */
110+ @Test(groups = "short")
111+ public void should_refresh_when_max_pending_requests_reached() {
112+ // Create keyspaces 5 times to cause
113+ // refreshNodeListAndTokenMap to be called.
114+ String prefix = "srwmprr";
115+ for(int i = 0; i < 5; i++) {
116+ String keyspace = prefix + i;
117+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
118+ keyspaces.add(keyspace);
119+ }
120+
121+ // add a 1 second delay to account for executor submit.
122+ verify(controlConnection, timeout(1000)).refreshNodeListAndTokenMap();
123+ }
124+}
added driver-core/src/test/java/com/datastax/driver/core/NodeRefreshDebouncerTest.java +86 −0
@@ -0,0 +1,86 @@
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.Collection;
19+import java.util.concurrent.TimeUnit;
20+
21+import org.mockito.ArgumentCaptor;
22+import org.mockito.Mockito;
23+import org.testng.annotations.Test;
24+
25+import static com.google.common.collect.Lists.newArrayList;
26+import static org.mockito.ArgumentCaptor.forClass;
27+import static org.mockito.Mockito.mock;
28+import static org.mockito.Mockito.timeout;
29+import static org.mockito.Mockito.verify;
30+import static org.mockito.Mockito.verifyNoMoreInteractions;
31+
32+import static com.datastax.driver.core.Assertions.assertThat;
33+
34+public class NodeRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
35+
36+ @Override
37+ protected Collection<String> getTableDefinitions() {
38+ return newArrayList();
39+ }
40+
41+ /**
42+ * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently
43+ * started within {@link QueryOptions#setRefreshNodeIntervalMillis(int)} that an 'onAdd' event
44+ * event is the only one processed and that the {@link Host} is marked up.
45+ * <p>
46+ * Since NEW_NODE_DELAY_SECONDS is typically configured with a high value (60 seconds default
47+ * in the maven profile) this test can take a very long time.
48+ *
49+ * @jira_ticket JAVA-657
50+ * @since 2.0.11
51+ */
52+ @Test(groups="long")
53+ public void should_call_onAdd_with_bootstrap_stop_start() {
54+ int refreshNodeInterval = 10000;
55+ QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval);
56+ CCMBridge ccm = CCMBridge.builder("test").withNodes(1).build();
57+ Cluster cluster = Cluster.builder()
58+ .addContactPoint(CCMBridge.ipOfNode(1))
59+ .withQueryOptions(queryOptions)
60+ .build();
61+
62+ try {
63+ cluster.connect();
64+ Host.StateListener listener = mock(Host.StateListener.class);
65+ cluster.register(listener);
66+ ccm.bootstrapNode(2);
67+ ccm.stop(2);
68+ ccm.start(2);
69+
70+ ArgumentCaptor<Host> captor = forClass(Host.class);
71+
72+ // Only register and onAdd should be called, since stop and start should be discarded.
73+ verify(listener).onRegister(cluster);
74+ long addDelay = refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS);
75+ verify(listener, timeout(addDelay)).onAdd(captor.capture());
76+ verifyNoMoreInteractions(listener);
77+
78+ // The hosts state should be UP.
79+ assertThat(captor.getValue().getState()).isEqualTo("UP");
80+ assertThat(cluster).host(2).hasState(Host.State.UP);
81+ } finally {
82+ cluster.close();
83+ ccm.remove();
84+ }
85+ }
86+}
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +14 −46
@@ -114,6 +114,11 @@
114114 return defs;
115115 }
116116
117+ @Override
118+ protected Cluster.Builder configure(Cluster.Builder builder) {
119+ return builder.withQueryOptions(TestUtils.nonDebouncingQueryOptions());
120+ }
121+
117122 @Test(groups = "short")
118123 public void preparedNativeTest() {
119124 // Test preparing/bounding for all native types
@@ -300,47 +305,6 @@
300305 }
301306 }
302307
303- private void reprepareOnNewlyUpNodeTest(String ks, Session session) throws Exception {
304-
305- ks = ks == null ? "" : ks + '.';
306-
307- session.execute("INSERT INTO " + ks + "test (k, i) VALUES ('123', 17)");
308- session.execute("INSERT INTO " + ks + "test (k, i) VALUES ('124', 18)");
309-
310- PreparedStatement ps = session.prepare("SELECT * FROM " + ks + "test WHERE k = ?");
311-
312- assertEquals(session.execute(ps.bind("123")).one().getInt("i"), 17);
313-
314- ccmBridge.stop();
315- waitForDown(CCMBridge.IP_PREFIX + '1', cluster);
316-
317- ccmBridge.start();
318- waitFor(CCMBridge.IP_PREFIX + '1', cluster, 120);
319-
320- try
321- {
322- assertEquals(session.execute(ps.bind("124")).one().getInt("i"), 18);
323- }
324- catch (NoHostAvailableException e)
325- {
326- System.out.println(">> " + e.getErrors());
327- throw e;
328- }
329- }
330-
331- @Test(groups = "long")
332- public void reprepareOnNewlyUpNodeTest() throws Exception {
333- reprepareOnNewlyUpNodeTest(null, session);
334- }
335-
336- @Test(groups = "long")
337- public void reprepareOnNewlyUpNodeNoKeyspaceTest() throws Exception {
338-
339- // This is the same test than reprepareOnNewlyUpNodeTest, except that the
340- // prepared statement is prepared while no current keyspace is used
341- reprepareOnNewlyUpNodeTest(keyspace, cluster.connect());
342- }
343-
344308 @Test(groups = "short")
345309 public void prepareWithNullValuesTest() throws Exception {
346310
@@ -448,11 +412,15 @@
448412 Cluster otherCluster = Cluster.builder()
449413 .addContactPointsWithPorts(ImmutableList.of(hostAddress))
450414 .build();
451- PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
452- BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
453-
454- // We expect that the error gets detected without a roundtrip to the server, so use executeAsync
455- session.executeAsync(bs);
415+ try {
416+ PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?");
417+ BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost"));
418+
419+ // We expect that the error gets detected without a roundtrip to the server, so use executeAsync
420+ session.executeAsync(bs);
421+ } finally {
422+ otherCluster.close();
423+ }
456424 }
457425
458426 /**
added driver-core/src/test/java/com/datastax/driver/core/QueryOptionsTest.java +229 −0
@@ -0,0 +1,229 @@
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.List;
19+import java.util.concurrent.TimeUnit;
20+
21+import com.google.common.collect.Lists;
22+import org.scassandra.http.client.PreparedStatementPreparation;
23+import org.testng.annotations.*;
24+
25+import static com.datastax.driver.core.Assertions.assertThat;
26+
27+public class QueryOptionsTest {
28+ SCassandraCluster scassandra;
29+
30+ QueryOptions queryOptions;
31+
32+ SortingLoadBalancingPolicy loadBalancingPolicy;
33+
34+ Cluster cluster = null;
35+ Session session = null;
36+ Host host1, host2, host3;
37+
38+
39+ @BeforeClass(groups = "short")
40+ public void beforeClass() {
41+ scassandra = new SCassandraCluster(CCMBridge.IP_PREFIX, 3);
42+ }
43+
44+ @BeforeMethod(groups = "short")
45+ public void beforeMethod() {
46+ queryOptions = new QueryOptions();
47+ loadBalancingPolicy = new SortingLoadBalancingPolicy();
48+ cluster = Cluster.builder()
49+ .addContactPoint(CCMBridge.ipOfNode(2))
50+ .withLoadBalancingPolicy(loadBalancingPolicy)
51+ .withQueryOptions(queryOptions)
52+ .build();
53+
54+ session = cluster.connect();
55+
56+ host1 = TestUtils.findHost(cluster, 1);
57+ host2 = TestUtils.findHost(cluster, 2);
58+ host3 = TestUtils.findHost(cluster, 3);
59+
60+ // Make sure there are no prepares
61+ for (int host : Lists.newArrayList(1, 2, 3)) {
62+ assertThat(scassandra.retrievePreparedStatementPreparations(host)).hasSize(0);
63+ }
64+ }
65+
66+ public void validatePrepared(boolean expectAll) {
67+ // Prepare the statement
68+ String query = "select sansa_stark from the_known_world";
69+ session.prepare(query);
70+
71+ // Ensure prepared properly based on expectation.
72+ List<PreparedStatementPreparation> preparationOne = scassandra.retrievePreparedStatementPreparations(1);
73+ List<PreparedStatementPreparation> preparationTwo = scassandra.retrievePreparedStatementPreparations(2);
74+ List<PreparedStatementPreparation> preparationThree = scassandra.retrievePreparedStatementPreparations(3);
75+
76+ assertThat(preparationOne).hasSize(1);
77+ assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query);
78+
79+ if (expectAll) {
80+ assertThat(preparationTwo).hasSize(1);
81+ assertThat(preparationTwo.get(0).getPreparedStatementText()).isEqualTo(query);
82+ assertThat(preparationThree).hasSize(1);
83+ assertThat(preparationThree.get(0).getPreparedStatementText()).isEqualTo(query);
84+ } else {
85+ assertThat(preparationTwo).isEmpty();
86+ assertThat(preparationThree).isEmpty();
87+ }
88+ }
89+
90+ /**
91+ * <p>
92+ * Validates that statements are only prepared on one node when
93+ * {@link QueryOptions#setPrepareOnAllHosts(boolean)} is set to false.
94+ * </p>
95+ *
96+ * @test_category prepared_statements:prepared
97+ * @expected_result prepare query only on the first node.
98+ * @jira_ticket JAVA-797
99+ * @since 2.0.11, 2.1.8, 2.2.1
100+ */
101+ @Test(groups = "short")
102+ public void should_prepare_once_when_prepare_on_all_hosts_false() {
103+ queryOptions.setPrepareOnAllHosts(false);
104+ validatePrepared(false);
105+ }
106+
107+ /**
108+ * <p>
109+ * Validates that statements are prepared on one node when
110+ * {@link QueryOptions#setPrepareOnAllHosts(boolean)} is set to true.
111+ * </p>
112+ *
113+ * @test_category prepared_statements:prepared
114+ * @expected_result all nodes prepared the query
115+ * @jira_ticket JAVA-797
116+ * @since 2.0.11, 2.1.8, 2.2.1
117+ */
118+ @Test(groups = "short")
119+ public void should_prepare_everywhere_when_prepare_on_all_hosts_true() {
120+ queryOptions.setPrepareOnAllHosts(true);
121+ validatePrepared(true);
122+ }
123+
124+ /**
125+ * <p>
126+ * Validates that statements are prepared on one node when
127+ * {@link QueryOptions#setPrepareOnAllHosts(boolean)} is not set.
128+ * </p>
129+ *
130+ * @test_category prepared_statements:prepared
131+ * @expected_result all nodes prepared the query.
132+ * @jira_ticket JAVA-797
133+ * @since 2.0.11
134+ */
135+ @Test(groups = "short")
136+ public void should_prepare_everywhere_when_not_configured() {
137+ validatePrepared(true);
138+ }
139+
140+ private void valideReprepareOnUp(boolean expectReprepare) {
141+ String query = "select sansa_stark from the_known_world";
142+ session.prepare(query);
143+
144+ List<PreparedStatementPreparation> preparationOne = scassandra.retrievePreparedStatementPreparations(1);
145+
146+ assertThat(preparationOne).hasSize(1);
147+ assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query);
148+
149+ scassandra.clearAllRecordedActivity();
150+ scassandra.stop(1);
151+ assertThat(cluster).host(1).goesDownWithin(10, TimeUnit.SECONDS);
152+
153+ scassandra.start(1);
154+ assertThat(cluster).host(1).comesUpWithin(60, TimeUnit.SECONDS);
155+
156+ preparationOne = scassandra.retrievePreparedStatementPreparations(1);
157+ if (expectReprepare) {
158+ assertThat(preparationOne).hasSize(1);
159+ assertThat(preparationOne.get(0).getPreparedStatementText()).isEqualTo(query);
160+ } else {
161+ assertThat(preparationOne).isEmpty();
162+ }
163+ }
164+
165+ /**
166+ * <p>
167+ * Validates that statements are reprepared when a node comes back up when
168+ * {@link QueryOptions#setReprepareOnUp(boolean)} is set to true.
169+ * </p>
170+ *
171+ * @test_category prepared_statements:prepared
172+ * @expected_result reprepare query on the restarted node.
173+ * @jira_ticket JAVA-658
174+ * @since 2.0.11, 2.1.8, 2.2.1
175+ */
176+ @Test(groups = "short")
177+ public void should_reprepare_on_up_when_enabled() {
178+ queryOptions.setReprepareOnUp(true);
179+ valideReprepareOnUp(true);
180+ }
181+
182+ /**
183+ * <p>
184+ * Validates that statements are reprepared when a node comes back up with
185+ * the default configuration.
186+ * </p>
187+ *
188+ * @test_category prepared_statements:prepared
189+ * @expected_result reprepare query on the restarted node.
190+ * @jira_ticket JAVA-658
191+ * @since 2.0.11, 2.1.8, 2.2.1
192+ */
193+ @Test(groups = "short")
194+ public void should_reprepare_on_up_by_default() {
195+ valideReprepareOnUp(true);
196+ }
197+
198+ /**
199+ * <p>
200+ * Validates that statements are not reprepared when a node comes back up when
201+ * {@link QueryOptions#setReprepareOnUp(boolean)} is set to false.
202+ * </p>
203+ *
204+ * @test_category prepared_statements:prepared
205+ * @expected_result do not reprepare query on the restarted node.
206+ * @jira_ticket JAVA-658
207+ * @since 2.0.11, 2.1.8, 2.2.1
208+ */
209+ @Test(groups = "short")
210+ public void should_not_reprepare_on_up_when_disabled() {
211+ queryOptions.setReprepareOnUp(false);
212+ valideReprepareOnUp(false);
213+ }
214+
215+ @AfterMethod(groups = "short")
216+ public void afterMethod() {
217+ if (cluster != null)
218+ cluster.close();
219+
220+ scassandra.clearAllPrimes();
221+ scassandra.clearAllRecordedActivity();
222+ }
223+
224+ @AfterClass(groups = "short")
225+ public void afterClass() {
226+ if (scassandra != null)
227+ scassandra.stop();
228+ }
229+}
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +20 −7
@@ -20,6 +20,7 @@
2020 import org.slf4j.Logger;
2121 import org.slf4j.LoggerFactory;
2222 import org.testng.annotations.AfterMethod;
23+import org.testng.annotations.BeforeMethod;
2324 import org.testng.annotations.Test;
2425
2526
@@ -28,7 +29,7 @@
2829 import static com.datastax.driver.core.Assertions.*;
2930 import static com.datastax.driver.core.Host.State.DOWN;
3031 import static com.datastax.driver.core.Host.State.UP;
31-
32+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3233
3334 /**
3435 * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster.
@@ -50,7 +51,8 @@
5051 mainCcm.waitForDown(1);
5152
5253 // Now start the driver that will connect to node2 and node3, and consider node1 down
53- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
54+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
55+ .withQueryOptions(nonDebouncingQueryOptions()).build();
5456 mainCluster.connect();
5557 waitForCountUpHosts(mainCluster, 2);
5658 // From that point, reconnections to node1 have been scheduled.
@@ -72,7 +74,8 @@
7274 mainCcm.waitForDown(1);
7375
7476 // Start the driver, the control connection will be on node2
75- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
77+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
78+ .withQueryOptions(nonDebouncingQueryOptions()).build();
7679 mainCluster.connect();
7780 waitForCountUpHosts(mainCluster, 1);
7881
@@ -99,7 +102,8 @@
99102 otherCcm.waitForUp(1);
100103
101104 // Start the driver, it should only connect to node 2
102- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
105+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
106+ .withQueryOptions(nonDebouncingQueryOptions()).build();
103107
104108 // When we first initialize the Cluster, all hosts are marked UP
105109 assertThat(mainCluster).host(2).hasState(UP);
@@ -127,7 +131,8 @@
127131 otherCcm.waitForUp(1);
128132
129133 // Start the driver, it should only connect to node 2
130- mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2").build();
134+ mainCluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + "2")
135+ .withQueryOptions(nonDebouncingQueryOptions()).build();
131136
132137 // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version.
133138 mainCluster.connect();
@@ -139,6 +144,14 @@
139144 .isNotReconnectingFromDown();
140145 }
141146
147+ @BeforeMethod(groups = "long")
148+ public void clearFields() {
149+ // Clear cluster and ccm instances between tests.
150+ mainCluster = null;
151+ mainCcm = null;
152+ otherCcm = null;
153+ }
154+
142155 @AfterMethod(groups = "long")
143156 public void teardown() {
144157 if (mainCluster != null)
@@ -160,8 +173,8 @@
160173 }
161174
162175 private static void waitForCountUpHosts(Cluster cluster, int expectedCount) throws InterruptedException {
163- int maxRetries = 30;
164- int interval = 10;
176+ int maxRetries = 10;
177+ int interval = 6;
165178
166179 for (int i = 0; i <= maxRetries; i++) {
167180 int actualCount = countUpHosts(cluster);
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +15 −56
@@ -19,7 +19,6 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.Collections;
2121 import java.util.Iterator;
22-import java.util.Map;
2322 import java.util.concurrent.ConcurrentHashMap;
2423 import java.util.concurrent.ConcurrentMap;
2524 import java.util.concurrent.TimeUnit;
@@ -27,8 +26,6 @@
2726
2827 import static java.util.concurrent.TimeUnit.SECONDS;
2928
30-import com.google.common.base.Charsets;
31-import com.google.common.collect.ImmutableMap;
3229 import com.google.common.util.concurrent.ListenableFuture;
3330 import org.testng.annotations.Test;
3431
@@ -72,7 +69,7 @@
7269 ccm.start(2);
7370 ccm.waitForUp(2);
7471
75- assertThat(cluster).host(2).comesUpWithin(120, SECONDS);
72+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
7673
7774 // Give the control connection a few moments to reconnect
7875 TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2);
@@ -96,7 +93,7 @@
9693 .build();
9794 ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0");
9895
99- DynamicPlainTextAuthProvider authProvider = new DynamicPlainTextAuthProvider("cassandra", "cassandra");
96+ CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra");
10097 int reconnectionDelayMs = 1000;
10198 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
10299
@@ -113,7 +110,7 @@
113110 // Stop the server, set wrong credentials and restart
114111 ccm.stop(1);
115112 ccm.waitForDown(1);
116- authProvider.password = "wrongPassword";
113+ authProvider.setPassword("wrongPassword");
117114 ccm.start(1);
118115 ccm.waitForUp(1);
119116
@@ -128,10 +125,10 @@
128125 assertThat(iterations).isLessThan(maxIterations);
129126
130127 // Fix the credentials
131- authProvider.password = "cassandra";
128+ authProvider.setPassword("cassandra");
132129
133130 // The driver should eventually reconnect to the node
134- assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
131+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
135132 } finally {
136133 if (cluster != null)
137134 cluster.close();
@@ -171,7 +168,7 @@
171168 ccm.waitForUp(2);
172169
173170 // The driver should now see the node as UP again
174- assertThat(cluster).host(2).comesUpWithin(120, SECONDS);
171+ assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
175172
176173 } finally {
177174 if (cluster != null)
@@ -232,7 +229,7 @@
232229 // Trigger another one-time reconnection attempt (this will succeed). The
233230 // host should be back up.
234231 host1.tryReconnectOnce();
235- assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
232+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
236233 } finally {
237234 if (cluster != null)
238235 cluster.close();
@@ -290,7 +287,7 @@
290287 // Reset the spy and count the number of connections attempts for 1 reconnect
291288 reset(socketOptions);
292289 host1.tryReconnectOnce();
293- assertThat(cluster).host(1).comesUpWithin(120, SECONDS);
290+ assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS);
294291 // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4
295292 // but the one from the reconnection attempt gets reused).
296293 verify(socketOptions, times(corePoolSize * 2)).getKeepAlive();
@@ -301,57 +298,19 @@
301298 ccm.remove();
302299 }
303300 }
304-
305- /**
306- * An authentication provider that allows changing the credentials at runtime, and tracks how many times they have been requested.
307- */
308- static class DynamicPlainTextAuthProvider implements AuthProvider {
309- volatile String username;
310- volatile String password;
311301
302+ /** Extends the plain text auth provider to track how many times the credentials have been requested */
303+ static class CountingAuthProvider extends PlainTextAuthProvider {
312304 final AtomicInteger count = new AtomicInteger();
313305
314- public DynamicPlainTextAuthProvider(String username, String password) {
315- this.username = username;
316- this.password = password;
306+ CountingAuthProvider(String username, String password) {
307+ super(username, password);
317308 }
318309
310+ @Override
319311 public Authenticator newAuthenticator(InetSocketAddress host) {
320- return new PlainTextAuthenticator();
321- }
322-
323- private class PlainTextAuthenticator extends ProtocolV1Authenticator implements Authenticator {
324-
325- @Override
326- public byte[] initialResponse() {
327- count.incrementAndGet();
328-
329- byte[] usernameBytes = username.getBytes(Charsets.UTF_8);
330- byte[] passwordBytes = password.getBytes(Charsets.UTF_8);
331- byte[] initialToken = new byte[usernameBytes.length + passwordBytes.length + 2];
332- initialToken[0] = 0;
333- System.arraycopy(usernameBytes, 0, initialToken, 1, usernameBytes.length);
334- initialToken[usernameBytes.length + 1] = 0;
335- System.arraycopy(passwordBytes, 0, initialToken, usernameBytes.length + 2, passwordBytes.length);
336- return initialToken;
337- }
338-
339- @Override
340- public byte[] evaluateChallenge(byte[] challenge) {
341- return null;
342- }
343-
344- @Override
345- public void onAuthenticationSuccess(byte[] token) {
346- // no-op, the server should send nothing anyway
347- }
348-
349- @Override
350- Map<String, String> getCredentials() {
351- count.incrementAndGet();
352- return ImmutableMap.of("username", username,
353- "password", password);
354- }
312+ count.incrementAndGet();
313+ return super.newAuthenticator(host);
355314 }
356315 }
357316
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +1 −0
@@ -53,6 +53,7 @@
5353 .withPoolingOptions(poolingOptions)
5454 .withLoadBalancingPolicy(loadBalancingPolicy)
5555 .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
56+ .withQueryOptions(TestUtils.nonDebouncingQueryOptions())
5657 .build();
5758
5859 Session session = cluster.connect();
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +35 −3
@@ -43,6 +43,10 @@
4343 private final List<PrimingClient> primingClients;
4444 private final List<ActivityClient> activityClients;
4545
46+ public SCassandraCluster(int nodeCount) {
47+ this(CCMBridge.IP_PREFIX, nodeCount);
48+ }
49+
4650 public SCassandraCluster(String ipPrefix, int nodeCount) {
4751 scassandras = Lists.newArrayListWithCapacity(nodeCount);
4852 addresses = Lists.newArrayListWithCapacity(nodeCount);
@@ -81,6 +85,16 @@
8185 scassandra.stop();
8286 }
8387
88+ public void start(int node) {
89+ int i = node - 1;
90+ scassandras.get(i).start();
91+ primePeers(primingClients.get(i), scassandras.get(i));
92+ }
93+
94+ public void stop(int node) {
95+ scassandras.get(node - 1).stop();
96+ }
97+
8498 public SCassandraCluster prime(int node, PrimingRequest request) {
8599 primingClients.get(node - 1).prime(request);
86100 return this;
@@ -90,6 +104,14 @@
90104 return activityClients.get(node - 1).retrieveQueries();
91105 }
92106
107+ public List<PreparedStatementExecution> retrievePreparedStatementExecutions(int node){
108+ return activityClients.get(node - 1).retrievePreparedStatementExecutions();
109+ }
110+
111+ public List<PreparedStatementPreparation> retrievePreparedStatementPreparations(int node) {
112+ return activityClients.get(node - 1).retrievePreparedStatementPreparations();
113+ }
114+
93115 public void clearAllPrimes() {
94116 for (PrimingClient primingClient : primingClients)
95117 primingClient.clearAllPrimes();
@@ -113,14 +135,24 @@
113135 if (scassandras.get(i).equals(toIgnore))
114136 continue;
115137 InetAddress address = addresses.get(i);
116- rows.add(ImmutableMap.<String, Object>builder()
138+ Map<String, ?> row = ImmutableMap.<String, Object>builder()
117139 .put("peer", address)
118140 .put("rpc_address", address)
119141 .put("data_center", "datacenter1")
120142 .put("rack", "rack1")
121143 .put("release_version", "2.0.1")
122144 .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i)))
123- .build());
145+ .build();
146+
147+ rows.add(row);
148+
149+ String query = "SELECT * FROM system.peers WHERE peer='" + address.toString().substring(1) + "'";
150+ primingClient.prime(
151+ PrimingRequest.queryBuilder()
152+ .withQuery(query)
153+ .withColumnTypes(SELECT_PEERS_COLUMN_TYPES)
154+ .withRows(row)
155+ .build());
124156 }
125157 primingClient.prime(
126158 PrimingRequest.queryBuilder()
@@ -130,7 +162,7 @@
130162 .build());
131163 }
132164
133- private static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES =
165+ static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES =
134166 ImmutableMap.<String, ColumnTypes>builder()
135167 .put("peer", ColumnTypes.Inet)
136168 .put("rpc_address", ColumnTypes.Inet)
added driver-core/src/test/java/com/datastax/driver/core/SchemaChangesCCTest.java +217 −0
@@ -0,0 +1,217 @@
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.Collections;
19+import java.util.Iterator;
20+import java.util.concurrent.TimeUnit;
21+
22+import com.google.common.util.concurrent.Uninterruptibles;
23+import org.mockito.ArgumentCaptor;
24+import org.testng.annotations.Test;
25+
26+import static org.mockito.Matchers.any;
27+import static org.mockito.Mockito.mock;
28+import static org.mockito.Mockito.reset;
29+import static org.mockito.Mockito.timeout;
30+import static org.mockito.Mockito.verify;
31+import static org.testng.Assert.fail;
32+
33+import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
34+import com.datastax.driver.core.policies.LoadBalancingPolicy;
35+import com.datastax.driver.core.policies.Policies;
36+
37+import static com.datastax.driver.core.Assertions.assertThat;
38+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
39+
40+public class SchemaChangesCCTest {
41+
42+ private static final int NOTIF_TIMEOUT_MS = 5000;
43+
44+ /**
45+ * Validates that any schema change events made while the control connection is down are
46+ * propagated when the control connection is re-established.
47+ * <p>
48+ *
49+ * Note that on control connection recovery not all schema changes are propagated. For example,
50+ * if a table was altered and then dropped only a drop event would be received as that is all
51+ * that can be discerned.
52+ *
53+ * @test_category control_connection, schema
54+ * @expected_result keyspace and table add, drop, and remove events are propagated on control connection reconnect.
55+ * @jira_ticket JAVA-151
56+ * @since 2.0.11, 2.1.8, 2.2.1
57+ */
58+ @Test(groups="long")
59+ public void should_receive_changes_made_while_control_connection_is_down_on_reconnect() throws Exception {
60+ ToggleablePolicy lbPolicy = new ToggleablePolicy(Policies.defaultLoadBalancingPolicy());
61+
62+ CCMBridge ccm = CCMBridge.builder("SchemaChangesCCTest").withNodes(2).build();
63+ Cluster.Builder builder = Cluster.builder()
64+ .withLoadBalancingPolicy(lbPolicy);
65+ Cluster cluster = builder.addContactPoint(CCMBridge.ipOfNode(1)).build();
66+ // Put cluster2 control connection on node 2 so it doesn't go down (to prevent noise for debugging).
67+ Cluster cluster2 = builder.addContactPoint(CCMBridge.ipOfNode(2)).build();
68+ try {
69+ SchemaChangeListener listener = mock(SchemaChangeListener.class);
70+
71+ cluster.init();
72+ cluster.register(listener);
73+
74+ Session session2 = cluster2.connect();
75+ // Create two keyspaces to experiment with.
76+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks1", 1));
77+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks2", 1));
78+ session2.execute("create table ks1.tbl1 (k text primary key, v text)");
79+ session2.execute("create table ks1.tbl2 (k text primary key, v text)");
80+
81+ // Wait for both create events to be received.
82+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onKeyspaceAdded(any(KeyspaceMetadata.class));
83+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(2)).onTableAdded(any(TableMetadata.class));
84+
85+
86+ KeyspaceMetadata prealteredKeyspace = cluster.getMetadata().getKeyspace("ks1");
87+ KeyspaceMetadata predroppedKeyspace = cluster.getMetadata().getKeyspace("ks2");
88+ TableMetadata prealteredTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl1");
89+ TableMetadata predroppedTable = cluster.getMetadata().getKeyspace("ks1").getTable("tbl2");
90+
91+ // Enable returning empty query plan for default statements. This will
92+ // prevent the control connection from being able to reconnect.
93+ lbPolicy.returnEmptyQueryPlan = true;
94+
95+ // Stop node 1, which hosts the control connection.
96+ ccm.stop(1);
97+ assertThat(cluster).host(1).goesDownWithin(20, TimeUnit.SECONDS);
98+
99+ // Ensure control connection is down.
100+ assertThat(cluster.manager.controlConnection.isOpen()).isFalse();
101+
102+ // Perform some schema changes that we'll validate when the control connection comes back.
103+ session2.execute("drop keyspace ks2");
104+ session2.execute("drop table ks1.tbl2");
105+ session2.execute("alter keyspace ks1 with durable_writes=false");
106+ session2.execute("alter table ks1.tbl1 alter v type blob");
107+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, "ks3", 1));
108+ session2.execute("create table ks1.tbl3 (k text primary key, v text)");
109+
110+ // Reset the mock to clear invocations. (sanity check to ensure all events happen after CC comes back up)
111+ reset(listener);
112+
113+ // Switch the flag so the control connection may now be established.
114+ lbPolicy.returnEmptyQueryPlan = false;
115+
116+ // Poll on the control connection and wait for it to be reestablished.
117+ long maxControlConnectionWait = 60000;
118+ long startTime = System.currentTimeMillis();
119+ while(!cluster.manager.controlConnection.isOpen() && System.currentTimeMillis() - startTime < maxControlConnectionWait) {
120+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
121+ }
122+
123+ assertThat(cluster.manager.controlConnection.isOpen())
124+ .as("Control connection was not opened after %dms.", maxControlConnectionWait)
125+ .isTrue();
126+
127+ // Ensure the drop keyspace event shows up.
128+ ArgumentCaptor<KeyspaceMetadata> removedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
129+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(removedKeyspace.capture());
130+ assertThat(removedKeyspace.getValue())
131+ .hasName("ks2")
132+ .isEqualTo(predroppedKeyspace);
133+
134+ // Ensure the drop table event shows up.
135+ ArgumentCaptor<TableMetadata> droppedTable = ArgumentCaptor.forClass(TableMetadata.class);
136+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(droppedTable.capture());
137+
138+ assertThat(droppedTable.getValue())
139+ .isInKeyspace("ks1")
140+ .hasName("tbl2")
141+ .isEqualTo(predroppedTable);
142+
143+ // Ensure that the alter keyspace event shows up.
144+ ArgumentCaptor<KeyspaceMetadata> alteredKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
145+ ArgumentCaptor<KeyspaceMetadata> originalKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
146+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(alteredKeyspace.capture(), originalKeyspace.capture());
147+
148+ // Previous metadata should match the metadata observed before disconnect.
149+ assertThat(originalKeyspace.getValue())
150+ .hasName("ks1")
151+ .isDurableWrites()
152+ .isEqualTo(prealteredKeyspace);
153+
154+ // New metadata should reflect that the durable writes attribute changed.
155+ assertThat(alteredKeyspace.getValue())
156+ .hasName("ks1")
157+ .isNotDurableWrites();
158+
159+ // Ensure the alter table event shows up.
160+ ArgumentCaptor<TableMetadata> alteredTable = ArgumentCaptor.forClass(TableMetadata.class);
161+ ArgumentCaptor<TableMetadata> originalTable = ArgumentCaptor.forClass(TableMetadata.class);
162+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(alteredTable.capture(), originalTable.capture());
163+
164+ // Previous metadata should match the metadata observed before disconnect.
165+ assertThat(originalTable.getValue())
166+ .isInKeyspace("ks1")
167+ .hasName("tbl1")
168+ .hasColumn("v", DataType.text())
169+ .isEqualTo(prealteredTable);
170+
171+ // New metadata should reflect that the column type changed.
172+ assertThat(alteredTable.getValue())
173+ .isInKeyspace("ks1")
174+ .hasName("tbl1")
175+ .hasColumn("v", DataType.blob());
176+
177+ // Ensure the add keyspace event shows up.
178+ ArgumentCaptor<KeyspaceMetadata> addedKeyspace = ArgumentCaptor.forClass(KeyspaceMetadata.class);
179+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(addedKeyspace.capture());
180+
181+ assertThat(addedKeyspace.getValue()).hasName("ks3");
182+
183+ // Ensure the add table event shows up.
184+ ArgumentCaptor<TableMetadata> addedTable = ArgumentCaptor.forClass(TableMetadata.class);
185+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(addedTable.capture());
186+
187+ assertThat(addedTable.getValue())
188+ .isInKeyspace("ks1")
189+ .hasName("tbl3");
190+ } finally {
191+ cluster.close();
192+ ccm.remove();
193+ }
194+ }
195+
196+ /**
197+ * A load balancing policy that can be "disabled" by having its query plan return no hosts when
198+ * given the 'DEFAULT' statement. This statement is used for retrieving query plan
199+ * and for finding what hosts to use for control connection.
200+ */
201+ public static class ToggleablePolicy extends DelegatingLoadBalancingPolicy {
202+
203+ volatile boolean returnEmptyQueryPlan;
204+
205+ public ToggleablePolicy(LoadBalancingPolicy delegate) {
206+ super(delegate);
207+ }
208+
209+ @Override
210+ public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
211+ if (returnEmptyQueryPlan && statement == Statement.DEFAULT)
212+ return Collections.<Host>emptyList().iterator();
213+ else
214+ return super.newQueryPlan(loggedKeyspace, statement);
215+ }
216+ }
217+}
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +389 −83
@@ -15,59 +15,105 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.util.Collection;
19+import java.util.Collections;
1820 import java.util.List;
1921
2022 import com.google.common.collect.Lists;
2123 import com.google.common.util.concurrent.Futures;
2224 import com.google.common.util.concurrent.ListenableFuture;
25+import org.mockito.ArgumentCaptor;
2326 import org.testng.annotations.*;
2427
28+import static org.mockito.Matchers.any;
29+import static org.mockito.Mockito.*;
30+
2531 import com.datastax.driver.core.utils.Bytes;
2632 import com.datastax.driver.core.utils.CassandraVersion;
2733
2834 import static com.datastax.driver.core.Assertions.assertThat;
35+import static com.datastax.driver.core.Metadata.handleId;
36+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
37+
38+public class SchemaChangesTest extends CCMBridge.PerClassSingleNodeCluster {
2939
30-public class SchemaChangesTest {
31- private static final String CREATE_KEYSPACE =
32- "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }";
40+ private static final String CREATE_KEYSPACE = "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }";
41+ private static final String ALTER_KEYSPACE = "ALTER KEYSPACE %s WITH durable_writes = false";
42+ private static final String DROP_KEYSPACE = "DROP KEYSPACE %s";
3343
34- CCMBridge ccm;
35- Cluster cluster;
44+ private static final String CREATE_TABLE = "CREATE TABLE %s.table1(i int primary key)";
45+ private static final String ALTER_TABLE = "ALTER TABLE %s.table1 ADD j int";
46+ private static final String DROP_TABLE = "DROP TABLE %s.table1";
47+
48+ /** The maximum time that the test will wait to check that listeners have been notified */
49+ private static final int NOTIF_TIMEOUT_MS = 5000;
50+
51+ Cluster cluster1;
3652 Cluster cluster2; // a second cluster to check that other clients also get notified
53+ Cluster schemaDisabledCluster; // a cluster with schema metadata disabled.
3754
3855 // The metadatas of the two clusters (we'll test that they're kept in sync)
3956 List<Metadata> metadatas;
4057
41- Session session;
58+ Session session1;
4259
43- @BeforeClass(groups = "short")
44- public void setup() {
45- CCMBridge.Builder builder = CCMBridge.builder("schemaChangesTest")
46- .withNodes(1);
60+ Session schemaDisabledSession;
4761
48- if(TestUtils.getDesiredProtocolVersion().compareTo(ProtocolVersion.V4) >= 0) {
49- builder = builder.withCassandraConfiguration("enable_user_defined_functions", "true");
50- }
51- ccm = builder.build();
62+ SchemaChangeListener listener1;
63+ SchemaChangeListener listener2;
64+ SchemaChangeListener schemaDisabledListener;
65+
66+ List<SchemaChangeListener> listeners;
5267
53- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
54- cluster2 = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
68+ ControlConnection schemaDisabledControlConnection;
5569
56- metadatas = Lists.newArrayList(cluster.getMetadata(), cluster2.getMetadata());
70+ @Override
71+ protected Collection<String> getTableDefinitions() {
72+ return Lists.newArrayList();
73+ }
5774
58- session = cluster.connect();
59- session.execute(String.format(CREATE_KEYSPACE, "lowercase"));
60- session.execute(String.format(CREATE_KEYSPACE, "\"CaseSensitive\""));
75+ @BeforeClass(groups = "short")
76+ public void setup() throws InterruptedException {
77+ Cluster.Builder builder = configure(Cluster.builder())
78+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
79+ .withQueryOptions(nonDebouncingQueryOptions());
80+ cluster1 = builder.build();
81+ cluster2 = builder.build();
82+ schemaDisabledCluster = spy(configure(Cluster.builder())
83+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
84+ .withClusterName("schema-disabled")
85+ .withQueryOptions(nonDebouncingQueryOptions()
86+ .setMetadataEnabled(false)
87+ ).build());
88+
89+ schemaDisabledSession = schemaDisabledCluster.connect();
90+
91+ schemaDisabledControlConnection = spy(schemaDisabledCluster.manager.controlConnection);
92+ schemaDisabledCluster.manager.controlConnection = schemaDisabledControlConnection;
93+
94+ metadatas = Lists.newArrayList(cluster1.getMetadata(), cluster2.getMetadata());
95+
96+ session1 = cluster1.connect();
97+
98+ cluster1.register(listener1 = mock(SchemaChangeListener.class));
99+ cluster1.register(listener2 = mock(SchemaChangeListener.class));
100+ listeners = Lists.newArrayList(listener1, listener2);
101+
102+ schemaDisabledCluster.register(schemaDisabledListener = mock(SchemaChangeListener.class));
103+ verify(schemaDisabledListener, times(1)).onRegister(schemaDisabledCluster);
104+
105+ execute(CREATE_KEYSPACE, "lowercase");
106+ execute(CREATE_KEYSPACE, "\"CaseSensitive\"");
61107 }
62108
63109 @AfterClass(groups = "short")
64110 public void teardown() {
65- if (cluster != null)
66- cluster.close();
111+ if (cluster1 != null)
112+ cluster1.close();
67113 if (cluster2 != null)
68114 cluster2.close();
69- if (ccm != null)
70- ccm.remove();
115+ if (schemaDisabledCluster != null)
116+ schemaDisabledCluster.close();
71117 }
72118
73119
@@ -76,42 +122,110 @@
76122 return new Object[][]{ { "lowercase" }, { "\"CaseSensitive\"" } };
77123 }
78124
79- @Test(groups = "short", dataProvider = "existingKeyspaceName")
80- public void should_notify_of_table_creation(String keyspace) {
81- session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace));
125+ @DataProvider(name = "newKeyspaceName")
126+ public static Object[][] newKeyspaceName() {
127+ return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } };
128+ }
82129
83- for (Metadata m : metadatas)
84- assertThat(m.getKeyspace(keyspace).getTable("table1"))
85- .isNotNull();
130+ @BeforeMethod(groups = "short")
131+ public void resetListeners() {
132+ for (SchemaChangeListener listener : listeners) {
133+ reset(listener);
134+ }
135+ reset(schemaDisabledControlConnection);
136+ }
137+
138+ /**
139+ * Ensures that a listener registered on a Cluster that has schema metadata disabled
140+ * is never invoked with schema change events.
141+ *
142+ * @jira_ticket JAVA-858
143+ * @since 2.0.11
144+ */
145+ @AfterMethod(groups = "short")
146+ public void verifyNoMoreInteractionsWithListener() {
147+ verifyNoMoreInteractions(schemaDisabledListener);
86148 }
87149
88150 @Test(groups = "short", dataProvider = "existingKeyspaceName")
89- public void should_notify_of_table_update(String keyspace) {
90- session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace));
91- session.execute(String.format("ALTER TABLE %s.table1 ADD j int", keyspace));
151+ public void should_notify_of_table_creation(String keyspace) throws InterruptedException {
152+ execute(CREATE_TABLE, keyspace);
153+ for (SchemaChangeListener listener : listeners) {
154+ ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
155+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
156+ assertThat(added.getValue())
157+ .isInKeyspace(handleId(keyspace))
158+ .hasName("table1");
159+ }
92160
93161 for (Metadata m : metadatas)
94- assertThat(m.getKeyspace(keyspace).getTable("table1").getColumn("j"))
95- .isNotNull();
162+ assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull();
96163 }
97164
98165 @Test(groups = "short", dataProvider = "existingKeyspaceName")
99- public void should_notify_of_table_drop(String keyspace) {
100- session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace));
101- session.execute(String.format("DROP TABLE %s.table1", keyspace));
102-
166+ public void should_notify_of_table_update(String keyspace) throws InterruptedException {
167+ execute(CREATE_TABLE, keyspace);
103168 for (Metadata m : metadatas)
104- assertThat(m.getKeyspace(keyspace).getTable("table1"))
105- .isNull();
169+ assertThat(m.getKeyspace(keyspace).getTable("table1")).hasNoColumn("j");
170+ ArgumentCaptor<TableMetadata> added = null;
171+ for (SchemaChangeListener listener : listeners) {
172+ added = ArgumentCaptor.forClass(TableMetadata.class);
173+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
174+ assertThat(added.getValue())
175+ .isInKeyspace(handleId(keyspace))
176+ .hasName("table1");
177+ }
178+ execute(ALTER_TABLE, keyspace);
179+ for (SchemaChangeListener listener : listeners) {
180+ ArgumentCaptor<TableMetadata> current = ArgumentCaptor.forClass(TableMetadata.class);
181+ ArgumentCaptor<TableMetadata> previous = ArgumentCaptor.forClass(TableMetadata.class);
182+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableChanged(current.capture(), previous.capture());
183+ assertThat(previous.getValue())
184+ .isEqualTo(added.getValue())
185+ .hasNoColumn("j");
186+ assertThat(current.getValue())
187+ .isInKeyspace(handleId(keyspace))
188+ .hasName("table1")
189+ .hasColumn("j");
190+ }
191+ for (Metadata m : metadatas)
192+ assertThat(m.getKeyspace(keyspace).getTable("table1")).hasColumn("j");
106193 }
107194
195+ @Test(groups = "short", dataProvider = "existingKeyspaceName")
196+ public void should_notify_of_table_drop(String keyspace) throws InterruptedException {
197+ execute(CREATE_TABLE, keyspace);
198+ for (SchemaChangeListener listener : listeners) {
199+ ArgumentCaptor<TableMetadata> added = ArgumentCaptor.forClass(TableMetadata.class);
200+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableAdded(added.capture());
201+ assertThat(added.getValue())
202+ .hasName("table1")
203+ .isInKeyspace(handleId(keyspace));
204+ }
205+ execute(DROP_TABLE, keyspace);
206+ for (Metadata m : metadatas)
207+ assertThat(m.getKeyspace(keyspace).getTable("table1")).isNull();
208+ for (SchemaChangeListener listener : listeners) {
209+ ArgumentCaptor<TableMetadata> removed = ArgumentCaptor.forClass(TableMetadata.class);
210+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(removed.capture());
211+ assertThat(removed.getValue()).hasName("table1");
212+ }
213+ }
214+
108215 @Test(groups = "short", dataProvider = "existingKeyspaceName")
109216 @CassandraVersion(major = 2.1)
110217 public void should_notify_of_udt_creation(String keyspace) {
111218 session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
112219
220+ for (SchemaChangeListener listener : listeners) {
221+ ArgumentCaptor<UserType> added = ArgumentCaptor.forClass(UserType.class);
222+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeAdded(added.capture());
223+ assertThat((DataType)added.getValue())
224+ .isUserType(handleId(keyspace), "type1");
225+ }
226+
113227 for (Metadata m : metadatas)
114- assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
228+ assertThat((DataType)m.getKeyspace(keyspace).getUserType("type1"))
115229 .isNotNull();
116230 }
117231
@@ -121,6 +235,14 @@
121235 session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
122236 session.execute(String.format("ALTER TYPE %s.type1 ADD j int", keyspace));
123237
238+ for (SchemaChangeListener listener : listeners) {
239+ ArgumentCaptor<UserType> current = ArgumentCaptor.forClass(UserType.class);
240+ ArgumentCaptor<UserType> previous = ArgumentCaptor.forClass(UserType.class);
241+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeChanged(current.capture(), previous.capture());
242+ assertThat(previous.getValue().getFieldNames()).doesNotContain("j");
243+ assertThat(current.getValue().getFieldNames()).contains("j");
244+ }
245+
124246 for (Metadata m : metadatas)
125247 assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j"))
126248 .isNotNull();
@@ -132,6 +254,12 @@
132254 session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace));
133255 session.execute(String.format("DROP TYPE %s.type1", keyspace));
134256
257+ for (SchemaChangeListener listener : listeners) {
258+ ArgumentCaptor<UserType> removed = ArgumentCaptor.forClass(UserType.class);
259+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onUserTypeRemoved(removed.capture());
260+ assertThat((DataType)removed.getValue()).isUserType(handleId(keyspace), "type1");
261+ }
262+
135263 for (Metadata m : metadatas)
136264 assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1"))
137265 .isNull();
@@ -142,6 +270,14 @@
142270 public void should_notify_of_function_creation(String keyspace) {
143271 session.execute(String.format("CREATE FUNCTION %s.id(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
144272
273+ for (SchemaChangeListener listener : listeners) {
274+ ArgumentCaptor<FunctionMetadata> added = ArgumentCaptor.forClass(FunctionMetadata.class);
275+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionAdded(added.capture());
276+ assertThat(added.getValue())
277+ .isInKeyspace(handleId(keyspace))
278+ .hasFullName("id(int)");
279+ }
280+
145281 for (Metadata m : metadatas)
146282 assertThat(m.getKeyspace(keyspace).getFunction("id", DataType.cint()))
147283 .isNotNull();
@@ -160,6 +296,14 @@
160296 session.execute(String.format("CREATE OR REPLACE FUNCTION %s.id(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java "
161297 + "AS 'return i + 1;'", keyspace));
162298
299+ for (SchemaChangeListener listener : listeners) {
300+ ArgumentCaptor<FunctionMetadata> current = ArgumentCaptor.forClass(FunctionMetadata.class);
301+ ArgumentCaptor<FunctionMetadata> previous = ArgumentCaptor.forClass(FunctionMetadata.class);
302+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionChanged(current.capture(), previous.capture());
303+ assertThat(previous.getValue()).hasBody("return i;");
304+ assertThat(current.getValue()).hasBody("return i + 1;");
305+ }
306+
163307 for (Metadata m : metadatas)
164308 assertThat(m.getKeyspace(keyspace).getFunction("id", DataType.cint()).getBody())
165309 .isEqualTo("return i + 1;");
@@ -171,6 +315,14 @@
171315 session.execute(String.format("CREATE FUNCTION %s.id(i int) RETURNS NULL ON NULL INPUT RETURNS int LANGUAGE java AS 'return i;'", keyspace));
172316 session.execute(String.format("DROP FUNCTION %s.id", keyspace));
173317
318+ for (SchemaChangeListener listener : listeners) {
319+ ArgumentCaptor<FunctionMetadata> removed = ArgumentCaptor.forClass(FunctionMetadata.class);
320+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onFunctionRemoved(removed.capture());
321+ assertThat(removed.getValue())
322+ .isInKeyspace(handleId(keyspace))
323+ .hasFullName("id(int)");
324+ }
325+
174326 for (Metadata m : metadatas)
175327 assertThat(m.getKeyspace(keyspace).getFunction("id", DataType.cint()))
176328 .isNull();
@@ -183,6 +335,14 @@
183335 + " AS 'return s+v;'", keyspace));
184336 session.execute(String.format("CREATE AGGREGATE %s.sum(int) SFUNC plus STYPE int INITCOND 0;", keyspace));
185337
338+ for (SchemaChangeListener listener : listeners) {
339+ ArgumentCaptor<AggregateMetadata> added = ArgumentCaptor.forClass(AggregateMetadata.class);
340+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateAdded(added.capture());
341+ assertThat(added.getValue())
342+ .isInKeyspace(handleId(keyspace))
343+ .hasFullName("sum(int)");
344+ }
345+
186346 for (Metadata m : metadatas)
187347 assertThat(m.getKeyspace(keyspace).getAggregate("sum", DataType.cint()))
188348 .isNotNull();
@@ -201,6 +361,14 @@
201361
202362 session.execute(String.format("CREATE OR REPLACE AGGREGATE %s.sum(int) SFUNC plus STYPE int INITCOND 1", keyspace));
203363
364+ for (SchemaChangeListener listener : listeners) {
365+ ArgumentCaptor<AggregateMetadata> current = ArgumentCaptor.forClass(AggregateMetadata.class);
366+ ArgumentCaptor<AggregateMetadata> previous = ArgumentCaptor.forClass(AggregateMetadata.class);
367+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateChanged(current.capture(), previous.capture());
368+ assertThat(previous.getValue()).hasInitCond(0);
369+ assertThat(current.getValue()).hasInitCond(1);
370+ }
371+
204372 for (Metadata m : metadatas)
205373 assertThat(m.getKeyspace(keyspace).getAggregate("sum", DataType.cint()).getInitCond())
206374 .isEqualTo(1);
@@ -214,71 +382,209 @@
214382 session.execute(String.format("CREATE AGGREGATE %s.sum(int) SFUNC plus STYPE int INITCOND 0", keyspace));
215383 session.execute(String.format("DROP AGGREGATE %s.sum", keyspace));
216384
385+ for (SchemaChangeListener listener : listeners) {
386+ ArgumentCaptor<AggregateMetadata> removed = ArgumentCaptor.forClass(AggregateMetadata.class);
387+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onAggregateRemoved(removed.capture());
388+ assertThat(removed.getValue())
389+ .isInKeyspace(handleId(keyspace))
390+ .hasFullName("sum(int)");
391+ }
392+
217393 for (Metadata m : metadatas)
218394 assertThat(m.getKeyspace(keyspace).getAggregate("sum", DataType.cint()))
219395 .isNull();
220396 }
221397
222- @DataProvider(name = "newKeyspaceName")
223- public static Object[][] newKeyspaceName() {
224- return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } };
225- }
226-
227398 @Test(groups = "short", dataProvider = "newKeyspaceName")
228- public void should_notify_of_keyspace_creation(String keyspace) {
229- session.execute(String.format(CREATE_KEYSPACE, keyspace));
230-
399+ public void should_notify_of_keyspace_creation(String keyspace) throws InterruptedException {
400+ execute(CREATE_KEYSPACE, keyspace);
231401 for (Metadata m : metadatas)
232- assertThat(m.getKeyspace(keyspace))
233- .isNotNull();
402+ assertThat(m.getKeyspace(keyspace)).isNotNull();
403+ for (SchemaChangeListener listener : listeners) {
404+ ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
405+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
406+ assertThat(added.getValue()).hasName(handleId(keyspace));
407+ }
234408 }
235409
236410 @Test(groups = "short", dataProvider = "newKeyspaceName")
237- public void should_notify_of_keyspace_update(String keyspace) {
238- session.execute(String.format(CREATE_KEYSPACE, keyspace));
411+ public void should_notify_of_keyspace_update(String keyspace) throws InterruptedException {
412+ execute(CREATE_KEYSPACE, keyspace);
413+ ArgumentCaptor<KeyspaceMetadata> added = null;
414+ for (SchemaChangeListener listener : listeners) {
415+ added = ArgumentCaptor.forClass(KeyspaceMetadata.class);
416+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture());
417+ assertThat(added.getValue()).hasName(handleId(keyspace));
418+ }
239419 for (Metadata m : metadatas)
240- assertThat(m.getKeyspace(keyspace).isDurableWrites())
241- .isTrue();
242-
243- session.execute(String.format("ALTER KEYSPACE %s WITH durable_writes = false", keyspace));
420+ assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue();
421+ execute(ALTER_KEYSPACE, keyspace);
422+ for (SchemaChangeListener listener : listeners) {
423+ ArgumentCaptor<KeyspaceMetadata> current = ArgumentCaptor.forClass(KeyspaceMetadata.class);
424+ ArgumentCaptor<KeyspaceMetadata> previous = ArgumentCaptor.forClass(KeyspaceMetadata.class);
425+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(current.capture(), previous.capture());
426+ assertThat(previous.getValue())
427+ .isEqualTo(added.getValue())
428+ .isDurableWrites();
429+ assertThat(current.getValue())
430+ .hasName(handleId(keyspace))
431+ .isNotDurableWrites();
432+ }
244433 for (Metadata m : metadatas)
245- assertThat(m.getKeyspace(keyspace).isDurableWrites())
246- .isFalse();
434+ assertThat(m.getKeyspace(keyspace)).isNotDurableWrites();
247435 }
248436
249437 @Test(groups = "short", dataProvider = "newKeyspaceName")
250- public void should_notify_of_keyspace_drop(String keyspace) {
251- session.execute(String.format(CREATE_KEYSPACE, keyspace));
438+ public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException {
439+ execute(CREATE_KEYSPACE, keyspace);
252440 for (Metadata m : metadatas)
253- assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE")))
254- .isNotEmpty();
441+ assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty();
442+ execute(CREATE_TABLE, keyspace); // to test table drop notifications
443+ execute(DROP_KEYSPACE, keyspace);
444+ for (SchemaChangeListener listener : listeners) {
445+ ArgumentCaptor<TableMetadata> table = ArgumentCaptor.forClass(TableMetadata.class);
446+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(table.capture());
447+ assertThat(table.getValue())
448+ .hasName("table1")
449+ .isInKeyspace(handleId(keyspace));
450+
451+ ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class);
452+ verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture());
453+ assertThat(ks.getValue())
454+ .hasName(handleId(keyspace));
455+ }
456+ for (Metadata m : metadatas) {
457+ assertThat(m.getKeyspace(keyspace)).isNull();
458+ assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty();
459+ }
460+ }
255461
256- session.execute(String.format("DROP KEYSPACE %s", keyspace));
257462
258- for (Metadata m : metadatas) {
259- assertThat(m.getKeyspace(keyspace))
260- .isNull();
261- assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE")))
262- .isEmpty();
463+ /**
464+ * Ensures that calling {@link Metadata#newToken(String)} on a Cluster that has schema
465+ * metadata disabled will throw a {@link IllegalStateException}.
466+ *
467+ * @jira_ticket JAVA-858
468+ * @since 2.0.11
469+ */
470+ @Test(groups = "short", expectedExceptions = IllegalStateException.class)
471+ public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() {
472+ Cluster cluster = configure(Cluster.builder())
473+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
474+ .withQueryOptions(nonDebouncingQueryOptions()
475+ .setMetadataEnabled(false)
476+ ).build();
477+
478+ try {
479+ cluster.init();
480+ cluster.getMetadata().newToken("0x00");
481+ } finally {
482+ cluster.close();
483+ }
484+ }
485+
486+
487+ /**
488+ * Ensures that calling {@link Metadata#newTokenRange(Token, Token)} on a Cluster that has schema
489+ * metadata disabled will throw a {@link IllegalStateException}.
490+ *
491+ * @jira_ticket JAVA-858
492+ * @since 2.0.11
493+ */
494+ @Test(groups = "short", expectedExceptions = IllegalStateException.class)
495+ public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() {
496+ Cluster cluster = configure(Cluster.builder())
497+ .addContactPointsWithPorts(Collections.singletonList(hostAddress))
498+ .withQueryOptions(nonDebouncingQueryOptions()
499+ .setMetadataEnabled(false)
500+ ).build();
501+
502+ try {
503+ cluster.init();
504+ Token.Factory factory = Token.getFactory("Murmur3Partitioner");
505+ Token token = factory.fromString(Long.toString(1));
506+ cluster.getMetadata().newTokenRange(token, token);
507+ } finally {
508+ cluster.close();
509+ }
510+ }
511+
512+ /**
513+ * Ensures that executing a query causing a schema change with a Cluster that has schema metadata
514+ * disabled will still wait on schema agreement, but not refresh the schema.
515+ *
516+ * @jira_ticket JAVA-858
517+ * @since 2.0.11
518+ */
519+ @Test(groups = "short")
520+ public void should_not_refresh_schema_on_schema_change_response() throws InterruptedException {
521+ ResultSet rs = schemaDisabledSession.execute(String.format(CREATE_TABLE, keyspace));
522+
523+ // Should still wait on schema agreement.
524+ assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue();
525+ assertThat(schemaDisabledCluster.getMetadata().checkSchemaAgreement()).isTrue();
526+
527+ // Wait up to 1 second (since refreshSchema submitted in an executor) and check that refreshSchema never called.
528+ verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(any(SchemaElement.class), any(String.class), any(String.class), anyListOf(String.class));
529+ }
530+
531+ /**
532+ * Ensures that when schema metadata is enabled using {@link QueryOptions#setMetadataEnabled(boolean)}
533+ * that a schema and nodelist refresh is submitted, but only if schema metadata is currently disabled.
534+ *
535+ * @jira_ticket JAVA-858
536+ * @since 2.0.11
537+ */
538+ @Test(groups = "short")
539+ public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled() throws Exception {
540+ try {
541+ schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
542+
543+ verify(schemaDisabledControlConnection, after(1000)).refreshSchema(null, null, null, null);
544+ verify(schemaDisabledControlConnection).refreshNodeListAndTokenMap();
545+
546+ // Ensure that there is schema metadata.
547+ assertThat(schemaDisabledCluster.getMetadata().getKeyspace(keyspace)).isNotNull();
548+ Token token1 = schemaDisabledCluster.getMetadata().newToken("0");
549+ Token token2 = schemaDisabledCluster.getMetadata().newToken("111111");
550+ assertThat(token1).isNotNull();
551+ assertThat(token2).isNotNull();
552+ assertThat(schemaDisabledCluster.getMetadata().newTokenRange(token1, token2)).isNotNull();
553+
554+ assertThat(schemaDisabledCluster.getMetadata().getTokenRanges()).isNotNull().isNotEmpty();
555+
556+ // Try enabling again and ensure schema is not refreshed again.
557+ reset(schemaDisabledControlConnection);
558+ schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true);
559+ verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(null, null, null, null);
560+ verify(schemaDisabledControlConnection, never()).refreshNodeListAndTokenMap();
561+ } finally {
562+ // Reset listener mock to not count it's interactions in this test.
563+ reset(schemaDisabledListener);
564+ schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(false);
263565 }
264566 }
265567
266568 @AfterMethod(groups = "short")
267- public void cleanup() {
569+ public void cleanup() throws InterruptedException {
268570 ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList(
269- session.executeAsync("DROP TABLE lowercase.table1"),
270- session.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
271- session.executeAsync("DROP TYPE lowercase.type1"),
272- session.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
273- session.executeAsync("DROP FUNCTION lowercase.id"),
274- session.executeAsync("DROP FUNCTION \"CaseSensitive\".id"),
275- session.executeAsync("DROP FUNCTION lowercase.plus"),
276- session.executeAsync("DROP FUNCTION \"CaseSensitive\".plus"),
277- session.executeAsync("DROP AGGREGATE lowercase.sum"),
278- session.executeAsync("DROP AGGREGATE \"CaseSensitive\".sum"),
279- session.executeAsync("DROP KEYSPACE lowercase2"),
280- session.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
571+ session1.executeAsync("DROP TABLE lowercase.table1"),
572+ session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"),
573+ session1.executeAsync("DROP TYPE lowercase.type1"),
574+ session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"),
575+ session1.executeAsync("DROP FUNCTION lowercase.id"),
576+ session1.executeAsync("DROP FUNCTION \"CaseSensitive\".id"),
577+ session1.executeAsync("DROP FUNCTION lowercase.plus"),
578+ session1.executeAsync("DROP FUNCTION \"CaseSensitive\".plus"),
579+ session1.executeAsync("DROP AGGREGATE lowercase.sum"),
580+ session1.executeAsync("DROP AGGREGATE \"CaseSensitive\".sum"),
581+ session1.executeAsync("DROP KEYSPACE lowercase2"),
582+ session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"")
281583 ));
282584 Futures.getUnchecked(f);
283585 }
586+
587+ private void execute(String cql, String keyspace) throws InterruptedException {
588+ session1.execute(String.format(cql, keyspace));
589+ }
284590 }
added driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +318 −0
@@ -0,0 +1,318 @@
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.Collection;
19+
20+import org.mockito.ArgumentCaptor;
21+import org.testng.SkipException;
22+import org.testng.annotations.AfterClass;
23+import org.testng.annotations.AfterMethod;
24+import org.testng.annotations.BeforeClass;
25+import org.testng.annotations.Test;
26+
27+import static com.google.common.collect.Lists.newArrayList;
28+import static org.mockito.ArgumentCaptor.forClass;
29+import static org.mockito.Mockito.*;
30+
31+import static com.datastax.driver.core.Assertions.assertThat;
32+import static com.datastax.driver.core.SchemaElement.KEYSPACE;
33+import static com.datastax.driver.core.SchemaElement.TABLE;
34+import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
35+
36+public class SchemaRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster {
37+
38+ // This may need to be tweaked depending on the reliability of the test environment.
39+ private static final int DEBOUNCE_TIME = 5000;
40+
41+ // Control Connection to be spied.
42+ private ControlConnection controlConnection;
43+
44+ // Schema Listener to be mocked.
45+ private SchemaChangeListener listener;
46+
47+ // Separate session/clusters to observe schema events on.
48+ private Session session2;
49+ private Cluster cluster2;
50+
51+ // Keyspaces to drop after test completes.
52+ private Collection<String> keyspaces = newArrayList();
53+
54+ @Override
55+ protected Collection<String> getTableDefinitions() {
56+ return newArrayList();
57+ }
58+
59+ @BeforeClass(groups = "short")
60+ public void setup() {
61+ QueryOptions queryOptions = new QueryOptions();
62+ queryOptions.setRefreshSchemaIntervalMillis(DEBOUNCE_TIME);
63+ queryOptions.setMaxPendingRefreshSchemaRequests(5);
64+ // Create a separate cluster that will receive the schema events on its control connection.
65+ cluster2 = this.configure(Cluster.builder())
66+ .addContactPointsWithPorts(newArrayList(hostAddress))
67+ .withQueryOptions(queryOptions)
68+ .build();
69+ session2 = cluster2.connect();
70+
71+ // Create a spy of the Cluster's control connection and replace it with the spy.
72+ controlConnection = spy(cluster2.manager.controlConnection);
73+ cluster2.manager.controlConnection = controlConnection;
74+
75+ // Create a mock of SchemaChangeListener to use for signalling events.
76+ listener = mock(SchemaChangeListener.class);
77+ cluster2.register(listener);
78+
79+ reset(listener);
80+ reset(controlConnection);
81+ }
82+
83+ @AfterMethod(groups = "short")
84+ public void beforeMethod() {
85+ reset(listener);
86+ reset(controlConnection);
87+ }
88+
89+ @AfterClass(groups = "short")
90+ public void teardown() {
91+ cluster2.close();
92+ // drop all keyspaces
93+ for(String keyspace : keyspaces) {
94+ session.execute("DROP KEYSPACE " + keyspace);
95+ }
96+ }
97+
98+ /**
99+ * Ensures that when a CREATED and UPDATED schema_change events are received on a control
100+ * connection for the same keyspace within {@link QueryOptions#getRefreshSchemaIntervalMillis()}
101+ * that the schema refresh is debounced and coalesced into a single schema refresh for that keyspace only.
102+ *
103+ * @throws Exception
104+ * @jira_ticket JAVA-657
105+ * @since 2.0.11
106+ */
107+ @Test(groups = "short")
108+ public void should_debounce_and_coalesce_create_and_alter_keyspace_into_refresh_keyspace() throws Exception {
109+ String keyspace = "sdaccaak";
110+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
111+ keyspaces.add(keyspace);
112+ session.execute(String.format("ALTER KEYSPACE %s WITH DURABLE_WRITES=false", keyspace));
113+
114+ ArgumentCaptor<KeyspaceMetadata> captor = forClass(KeyspaceMetadata.class);
115+ verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onKeyspaceAdded(captor.capture());
116+ assertThat(captor.getValue()).hasName(keyspace).isNotDurableWrites();
117+
118+ // Verify that the schema refresh was debounced and coalesced when a keyspace creation
119+ // and update event occur for the same keyspace.
120+ verify(controlConnection, times(1)).refreshSchema(KEYSPACE, keyspace, null, null);
121+
122+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
123+ // By ensuring durable writes is false, we know that the single schema refresh occurred
124+ // after the alter event.
125+ assertThat(ksm).isNotNull().hasName(keyspace).isNotDurableWrites();
126+ }
127+
128+
129+ /**
130+ * Ensures that when a CREATED (keyspace) and CREATED (table) schema_change events are received
131+ * on a control connection with that table belonging to that keyspace within
132+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
133+ * and coalesced into a single schema refresh for that keyspace only.
134+ *
135+ * @throws Exception
136+ * @jira_ticket JAVA-657
137+ * @since 2.0.11
138+ */
139+ @Test(groups = "short")
140+ public void should_debounce_and_coalesce_create_keyspace_and_table_into_refresh_keyspace() throws Exception {
141+ String keyspace = "sdacckt";
142+ String table = "tbl1";
143+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
144+ keyspaces.add(keyspace);
145+ session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + table));
146+
147+ ArgumentCaptor<KeyspaceMetadata> keyspaceCaptor = forClass(KeyspaceMetadata.class);
148+ verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onKeyspaceAdded(keyspaceCaptor.capture());
149+ assertThat(keyspaceCaptor.getValue()).hasName(keyspace);
150+
151+ ArgumentCaptor<TableMetadata> tableCaptor = forClass(TableMetadata.class);
152+ verify(listener, times(1)).onTableAdded(tableCaptor.capture());
153+ assertThat(tableCaptor.getValue()).hasName(table);
154+
155+ // Verify the schema refresh was debounced and coalesced when a keyspace event and table event
156+ // in that keyspace is detected.
157+ verify(controlConnection).refreshSchema(KEYSPACE, keyspace, null, null);
158+ verify(controlConnection, never()).refreshSchema(TABLE, keyspace, table, null);
159+
160+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
161+ assertThat(ksm).isNotNull();
162+ assertThat(ksm.getTable(table)).isNotNull();
163+ }
164+
165+ /**
166+ * Ensures that when multiple CREATED schema_change events are received
167+ * on a control connection for tables belonging to the same keyspace within
168+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
169+ * and coalesced into a single schema refresh for that keyspace only.
170+ *
171+ * @throws Exception
172+ * @jira_ticket JAVA-657
173+ * @since 2.0.11
174+ */
175+ @Test(groups = "short")
176+ public void should_debounce_and_coalesce_tables_in_same_keyspace_into_refresh_keyspace() throws Exception {
177+ String keyspace = "sdactisk";
178+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
179+ keyspaces.add(keyspace);
180+ // Reset invocations as creating keyspace causes a keyspace refresh.
181+ reset(controlConnection);
182+ reset(listener);
183+
184+ int tableCount = 3;
185+ for(int i =0 ; i < tableCount; i++) {
186+ session.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + "tbl" + i));
187+ }
188+
189+ verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onTableAdded(any(TableMetadata.class));
190+
191+ // Verify a refresh of the keyspace was executed, but not individually on the
192+ // tables since those events were coalesced.
193+ verify(controlConnection).refreshSchema(KEYSPACE, keyspace, null, null);
194+
195+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
196+ assertThat(ksm).isNotNull();
197+ // metadata is present for each table.
198+ for(int i = 0; i < tableCount; i++) {
199+ String table = "tbl" + i;
200+ // Should have never been a refreshSchema on the table.
201+ verify(controlConnection, never()).refreshSchema(TABLE, keyspace, table, null);
202+ assertThat(ksm.getTable(table)).isNotNull();
203+ }
204+ }
205+
206+ /**
207+ * Ensures that when multiple UPDATED schema_change events are received
208+ * on a control connection for for the same table within
209+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
210+ * and coalesced into a single schema refresh for that table only.
211+ *
212+ * @throws Exception
213+ * @jira_ticket JAVA-657
214+ * @since 2.0.11
215+ */
216+ @Test(groups = "short")
217+ public void should_debounce_and_coalesce_multiple_alter_events_on_same_table_into_refresh_table() throws Exception {
218+ if (cassandraVersion.getMajor() > 2 || cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() > 1)
219+ throw new SkipException("Disabled in Cassandra 2.2+ because of CASSANDRA-9996");
220+
221+ String keyspace = "sdacmaeost";
222+ String table = "tbl1";
223+ String comment = "I am changing this table.";
224+ String columnName = "added_column";
225+ // Execute on session 2 which refreshes schema as part of processing responses.
226+ session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1));
227+ keyspaces.add(keyspace);
228+ session2.execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", keyspace + "." + table));
229+ reset(controlConnection);
230+ reset(listener);
231+
232+ session.execute(String.format("ALTER TABLE %s.%s WITH comment = '%s'", keyspace, table, comment));
233+ session.execute(String.format("ALTER TABLE %s.%s ADD %s int", keyspace, table, columnName));
234+
235+ ArgumentCaptor<TableMetadata> original = forClass(TableMetadata.class);
236+ ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class);
237+ verify(listener, timeout(DEBOUNCE_TIME * 2).times(1)).onTableChanged(captor.capture(), original.capture());
238+ assertThat(captor.getValue())
239+ .hasName(table)
240+ .isInKeyspace(keyspace)
241+ .hasColumn(columnName)
242+ .hasComment(comment);
243+
244+ assertThat(original.getValue())
245+ .hasName(table)
246+ .isInKeyspace(keyspace)
247+ .hasNoColumn(columnName)
248+ .doesNotHaveComment(comment);
249+
250+ // Verify a refresh of the table was executed, but only once.
251+ verify(controlConnection, times(1)).refreshSchema(TABLE, keyspace, table, null);
252+
253+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace);
254+ assertThat(ksm).isNotNull();
255+ TableMetadata tm = ksm.getTable(table);
256+ assertThat(tm)
257+ .hasName(table)
258+ .isInKeyspace(keyspace)
259+ .hasColumn(columnName)
260+ .hasComment(comment);
261+ }
262+
263+ /**
264+ * Ensures that when a CREATED (keyspace) and CREATED (keyspace) schema_change events are received
265+ * on a control connection for different keyspaces within
266+ * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced
267+ * and coalesced into a single full schema refresh.
268+ *
269+ * @throws Exception
270+ * @jira_ticket JAVA-657
271+ * @since 2.0.11
272+ */
273+ @Test(groups = "short")
274+ public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception {
275+ String prefix = "sdacmkc";
276+ for(int i = 0; i < 3; i++) {
277+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
278+ keyspaces.add(prefix + i);
279+ }
280+
281+ verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class));
282+ // Verify a complete schema refresh was executed, but only once.
283+ verify(controlConnection, times(1)).refreshSchema(null, null, null, null);
284+
285+ for(int i = 0; i < 3; i++) {
286+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
287+ assertThat(ksm).isNotNull().hasName(prefix + i);
288+ }
289+ }
290+
291+ /**
292+ * Ensures that when enough schema changes have been received on a control connection to
293+ * reach {@link QueryOptions#getMaxPendingRefreshSchemaRequests()} that a schema refresh
294+ * is submitted right away.
295+ *
296+ * @throws Exception
297+ * @jira_ticket JAVA-657
298+ * @since 2.0.11
299+ */
300+ @Test(groups = "short")
301+ public void should_refresh_when_max_pending_requests_reached() throws Exception {
302+ String prefix = "srwmprr";
303+ for(int i = 0; i < 5; i++) {
304+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1));
305+ keyspaces.add(prefix + i);
306+ }
307+
308+ // Event should be processed immediately as we hit our threshold.
309+ verify(listener, timeout(DEBOUNCE_TIME * 5).times(5)).onKeyspaceAdded(any(KeyspaceMetadata.class));
310+ // Verify a complete schema refresh was executed, but only once.
311+ verify(controlConnection, times(1)).refreshSchema(null, null, null, null);
312+
313+ for(int i = 0; i < 5; i++) {
314+ KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i);
315+ assertThat(ksm).isNotNull().hasName(prefix + i);
316+ }
317+ }
318+}
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +6 −3
@@ -31,6 +31,7 @@
3131 import com.datastax.driver.core.utils.SocketChannelMonitor;
3232
3333 import static com.datastax.driver.core.Assertions.assertThat;
34+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
3435
3536 public class SessionLeakTest {
3637
@@ -49,9 +50,11 @@
4950 channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS);
5051 try {
5152 cluster = Cluster.builder()
52- .addContactPointsWithPorts(Collections.singletonList(
53- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
54- .withNettyOptions(channelMonitor.nettyOptions()).build();
53+ .addContactPointsWithPorts(Collections.singletonList(
54+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042)))
55+ .withNettyOptions(channelMonitor.nettyOptions())
56+ .withQueryOptions(nonDebouncingQueryOptions())
57+ .build();
5558
5659 cluster.init();
5760
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +22 −1
@@ -21,10 +21,13 @@
2121 import org.testng.annotations.BeforeClass;
2222 import org.testng.annotations.Test;
2323
24+import static org.assertj.core.api.Assertions.assertThat;
25+
2426 import static org.mockito.Mockito.mock;
2527 import static org.mockito.Mockito.when;
2628
2729 public class SimpleStatementTest {
30+
2831 Cluster cluster;
2932 CodecRegistry codecRegistry = new CodecRegistry();
3033
@@ -42,4 +45,22 @@
4245 List<Object> args = Collections.nCopies(1 << 16, (Object)1);
4346 new SimpleStatement("mock query", cluster, args.toArray());
4447 }
45-}
No newline at the end of the file
48+
49+ @Test(groups = "unit", expectedExceptions = { IllegalStateException.class })
50+ public void should_throw_ISE_if_getObject_called_on_statement_without_values() {
51+ new SimpleStatement("doesn't matter", cluster).getObject(0);
52+ }
53+
54+
55+ @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
56+ public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
57+ new SimpleStatement("doesn't matter", cluster, new Object()).getObject(1);
58+ }
59+
60+ @Test(groups = "unit")
61+ public void should_return_object_at_ith_index() {
62+ Object expected = new Object();
63+ Object actual = new SimpleStatement("doesn't matter", cluster, expected).getObject(0);
64+ assertThat(actual).isSameAs(expected);
65+ }
66+}
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +8 −1
@@ -39,7 +39,14 @@
3939 .withCassandraConfiguration("initial_token", "1")
4040 .build();
4141
42- cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build();
42+ cluster = Cluster.builder()
43+ .addContactPoint(CCMBridge.ipOfNode(1))
44+ .withQueryOptions(new QueryOptions()
45+ .setRefreshNodeIntervalMillis(0)
46+ .setRefreshNodeListIntervalMillis(0)
47+ .setRefreshSchemaIntervalMillis(0)
48+ )
49+ .build();
4350
4451 Session session = cluster.connect();
4552 session.execute("create keyspace test with replication = {'class': 'SimpleStrategy', 'replication_factor': 1}");
modified driver-core/src/test/java/com/datastax/driver/core/SortingLoadBalancingPolicy.java +1 −1
@@ -31,7 +31,7 @@
3131 */
3232 public class SortingLoadBalancingPolicy implements LoadBalancingPolicy {
3333
34- private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() {
34+ final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() {
3535 @Override
3636 public int compare(Host host1, Host host2) {
3737 byte[] address1 = host1.getAddress().getAddress();
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +33 −3
@@ -17,10 +17,9 @@
1717
1818 import org.assertj.core.api.AbstractAssert;
1919
20-import static com.datastax.driver.core.Assertions.assertThat;
20+import static org.assertj.core.api.Assertions.assertThat;
2121
2222 public class TableMetadataAssert extends AbstractAssert<TableMetadataAssert, TableMetadata> {
23-
2423 protected TableMetadataAssert(TableMetadata actual) {
2524 super(actual, TableMetadataAssert.class);
2625 }
@@ -30,6 +29,38 @@
3029 return this;
3130 }
3231
32+ public TableMetadataAssert isInKeyspace(String keyspaceName) {
33+ assertThat(actual.getKeyspace().getName()).isEqualTo(keyspaceName);
34+ return this;
35+ }
36+
37+ public TableMetadataAssert hasColumn(String columnName) {
38+ assertThat(actual.getColumn(columnName)).isNotNull();
39+ return this;
40+ }
41+
42+ public TableMetadataAssert hasColumn(String columnName, DataType dataType) {
43+ ColumnMetadata column = actual.getColumn(columnName);
44+ assertThat(column).isNotNull();
45+ assertThat(column.getType()).isEqualTo(dataType);
46+ return this;
47+ }
48+
49+ public TableMetadataAssert hasNoColumn(String columnName) {
50+ assertThat(actual.getColumn(columnName)).isNull();
51+ return this;
52+ }
53+
54+ public TableMetadataAssert hasComment(String comment) {
55+ assertThat(actual.getOptions().getComment()).isEqualTo(comment);
56+ return this;
57+ }
58+
59+ public TableMetadataAssert doesNotHaveComment(String comment) {
60+ assertThat(actual.getOptions().getComment()).isNotEqualTo(comment);
61+ return this;
62+ }
63+
3364 public TableMetadataAssert isCompactStorage() {
3465 assertThat(actual.getOptions().isCompactStorage()).isTrue();
3566 return this;
@@ -44,5 +75,4 @@
4475 assertThat(actual.getColumns().size()).isEqualTo(expected);
4576 return this;
4677 }
47-
4878 }
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +14 −7
@@ -28,6 +28,10 @@
2828 import static com.datastax.driver.core.TableMetadata.Order.DESC;
2929
3030 public class TableMetadataTest extends CCMBridge.PerClassSingleNodeCluster {
31+ @Override
32+ protected Collection<String> getTableDefinitions() {
33+ return Collections.emptyList();
34+ }
3135
3236 @Test(groups = "short")
3337 public void should_parse_table_without_clustering_columns() {
@@ -50,6 +54,15 @@
5054 assertThat(table.getColumns().get(3)).isNotNull().hasName("v").isRegularColumn().hasType(cint());
5155 }
5256
57+ @Override
58+ protected Cluster.Builder configure(Cluster.Builder builder) {
59+ return builder.withQueryOptions(new QueryOptions()
60+ .setRefreshNodeIntervalMillis(0)
61+ .setRefreshNodeListIntervalMillis(0)
62+ .setRefreshSchemaIntervalMillis(0)
63+ );
64+ }
65+
5366 @Test(groups = "short")
5467 public void should_parse_table_with_clustering_columns() {
5568 // given
@@ -357,10 +370,4 @@
357370 assertThat(table.getOptions().getComment()).isEqualTo("comment with single quote ' should work");
358371 assertThat(table.asCQLQuery()).contains("comment = 'comment with single quote '' should work'");
359372 }
360-
361- @Override
362- protected Collection<String> getTableDefinitions() {
363- return Collections.emptyList();
364-}
365-
366-}
373+}
No newline at the end of the file
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +22 −9
@@ -24,8 +24,7 @@
2424 import java.nio.ByteBuffer;
2525 import java.util.*;
2626
27-import static org.testng.Assert.fail;
28-
27+import com.google.common.util.concurrent.Futures;
2928 import org.scassandra.Scassandra;
3029 import org.scassandra.ScassandraFactory;
3130 import org.slf4j.Logger;
@@ -362,8 +361,9 @@
362361 // tried doing an actual query, the driver won't realize that last node is dead until
363362 // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force
364363 // the detection by forcing a request.
365- if (waitForDead || waitForOut)
366- cluster.manager.submitSchemaRefresh(null, null, null, null);
364+ if (waitForDead || waitForOut) {
365+ Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null, null, null));
366+ }
367367
368368 InetAddress address;
369369 try {
@@ -419,15 +419,19 @@
419419 }
420420 }
421421
422- /** Utility method to find the {@code Host} object corresponding to a node in a cluster. */
423422 public static Host findHost(Cluster cluster, int hostNumber) {
424- String address = CCMBridge.ipOfNode(hostNumber);
425- for (Host host : cluster.getMetadata().getAllHosts()) {
423+ return findHost(cluster, CCMBridge.ipOfNode(hostNumber));
424+ }
425+
426+ public static Host findHost(Cluster cluster, String address) {
427+ // Note: we can't rely on ProtocolOptions.getPort() to build an InetSocketAddress and call metadata.getHost,
428+ // because the port doesn't have the correct value if addContactPointsWithPorts was used to create the Cluster
429+ // (JAVA-860 will solve that)
430+ for (Host host : cluster.getMetadata().allHosts()) {
426431 if (host.getAddress().getHostAddress().equals(address))
427432 return host;
428433 }
429- fail(address + " not found in cluster metadata");
430- return null; // never reached
434+ return null;
431435 }
432436
433437 public static int numberOfLocalCoreConnections(Cluster cluster) {
@@ -503,4 +507,13 @@
503507 .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress))
504508 .build();
505509 }
510+
511+ /**
512+ * @return a {@QueryOptions} that disables debouncing by setting intervals to 0ms.
513+ */
514+ public static QueryOptions nonDebouncingQueryOptions() {
515+ return new QueryOptions().setRefreshNodeIntervalMillis(0)
516+ .setRefreshNodeListIntervalMillis(0)
517+ .setRefreshSchemaIntervalMillis(0);
518+ }
506519 }
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +13 −6
@@ -16,6 +16,7 @@
1616 package com.datastax.driver.core;
1717
1818 import com.datastax.driver.core.exceptions.NoHostAvailableException;
19+import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
1920 import com.datastax.driver.core.utils.SocketChannelMonitor;
2021 import com.google.common.collect.Lists;
2122 import com.google.common.util.concurrent.FutureCallback;
@@ -36,7 +37,7 @@
3637 import java.util.concurrent.atomic.AtomicBoolean;
3738 import java.util.concurrent.atomic.AtomicInteger;
3839
39-import static org.assertj.core.api.Assertions.assertThat;
40+import static com.datastax.driver.core.Assertions.assertThat;
4041
4142 public class TimeoutStressTest {
4243
@@ -73,9 +74,9 @@
7374 ccmBridge = CCMBridge.builder("test").withNodes(3).build();
7475 channelMonitor = new SocketChannelMonitor();
7576 nodes = Lists.newArrayList(
76- new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
77- new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
78- new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
77+ new InetSocketAddress(CCMBridge.IP_PREFIX + '1', 9042),
78+ new InetSocketAddress(CCMBridge.IP_PREFIX + '2', 9042),
79+ new InetSocketAddress(CCMBridge.IP_PREFIX + '3', 9042)
7980 );
8081
8182 PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8);
@@ -84,6 +85,7 @@
8485 .addContactPointsWithPorts(nodes)
8586 .withPoolingOptions(poolingOptions)
8687 .withNettyOptions(channelMonitor.nettyOptions())
88+ .withReconnectionPolicy(new ConstantReconnectionPolicy(1000))
8789 .build();
8890 }
8991
@@ -177,13 +179,18 @@
177179 .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS);
178180
179181 logger.debug("Sleeping 20 seconds to allow connection reaper to clean up connections " +
180- "and for the pools to recover.");
182+ "and for the pools to recover.");
181183 Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS);
182184
183185 Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes);
184186 assertThat(openChannels.size())
185187 .as("Number of open connections does not meet expected: %s", openChannels)
186- .isEqualTo(maxConnections);
188+ .isLessThanOrEqualTo(maxConnections);
189+
190+ // Each host should be in an up state.
191+ assertThat(cluster).host(1).comesUpWithin(0, TimeUnit.SECONDS);
192+ assertThat(cluster).host(2).comesUpWithin(0, TimeUnit.SECONDS);
193+ assertThat(cluster).host(3).comesUpWithin(0, TimeUnit.SECONDS);
187194
188195 session.close();
189196
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +5 −0
@@ -81,6 +81,11 @@
8181 cluster = Cluster.builder()
8282 .addContactPoints(CCMBridge.ipOfNode(1))
8383 .withLoadBalancingPolicy(lbp)
84+ .withQueryOptions(new QueryOptions()
85+ .setRefreshNodeIntervalMillis(0)
86+ .setRefreshNodeListIntervalMillis(0)
87+ .setRefreshSchemaIntervalMillis(0)
88+ )
8489 .build();
8590 cluster.init();
8691 session = cluster.connect();
added driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsScassandraTest.java +144 −0
@@ -0,0 +1,144 @@
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.exceptions;
17+
18+import java.util.List;
19+import java.util.Map;
20+
21+import com.google.common.collect.ImmutableList;
22+import com.google.common.collect.ImmutableMap;
23+import org.scassandra.http.client.PrimingRequest;
24+import org.testng.annotations.*;
25+
26+import static org.assertj.core.api.Assertions.assertThat;
27+import static org.assertj.core.api.Assertions.fail;
28+import static org.scassandra.http.client.PrimingRequest.Result.read_request_timeout;
29+import static org.scassandra.http.client.PrimingRequest.Result.unavailable;
30+import static org.scassandra.http.client.PrimingRequest.Result.write_request_timeout;
31+
32+import com.datastax.driver.core.*;
33+import com.datastax.driver.core.policies.FallthroughRetryPolicy;
34+
35+import static com.datastax.driver.core.ConsistencyLevel.ONE;
36+
37+public class ExceptionsScassandraTest {
38+
39+ protected SCassandraCluster scassandras;
40+ protected Cluster cluster;
41+ protected Metrics.Errors errors;
42+ protected Host host1;
43+ protected Session session;
44+
45+ @BeforeClass(groups = "short")
46+ public void beforeClass() {
47+ scassandras = new SCassandraCluster(CCMBridge.IP_PREFIX, 1);
48+ }
49+
50+ @BeforeMethod(groups = "short")
51+ public void beforeMethod() {
52+ cluster = Cluster.builder()
53+ .addContactPoint(CCMBridge.ipOfNode(1))
54+ .withRetryPolicy(FallthroughRetryPolicy.INSTANCE)
55+ .build();
56+ session = cluster.connect();
57+ host1 = TestUtils.findHost(cluster, 1);
58+ errors = cluster.getMetrics().getErrorMetrics();
59+ scassandras.clearAllPrimes();
60+ scassandras.clearAllRecordedActivity();
61+ }
62+
63+ @Test(groups = "short")
64+ public void should_throw_proper_unavailable_exception() {
65+ simulateError(1, unavailable);
66+ try {
67+ query();
68+ fail("expected an UnavailableException");
69+ } catch (UnavailableException e) {
70+ assertThat(e.getMessage()).isEqualTo("Not enough replicas available for query at consistency ONE (1 required but only 0 alive)");
71+ assertThat(e.getConsistencyLevel()).isEqualTo(ONE);
72+ assertThat(e.getAliveReplicas()).isEqualTo(0);
73+ assertThat(e.getRequiredReplicas()).isEqualTo(1);
74+ assertThat(e.getAddress()).isEqualTo(host1.getSocketAddress());
75+ assertThat(e.getHost()).isEqualTo(host1.getAddress());
76+ }
77+ }
78+
79+ @Test(groups = "short")
80+ public void should_throw_proper_read_timeout_exception() {
81+ simulateError(1, read_request_timeout);
82+ try {
83+ query();
84+ fail("expected a ReadTimeoutException");
85+ } catch (ReadTimeoutException e) {
86+ assertThat(e.getMessage()).isEqualTo("Cassandra timeout during read query at consistency ONE (1 responses were required but only 0 replica responded)");
87+ assertThat(e.getConsistencyLevel()).isEqualTo(ONE);
88+ assertThat(e.getReceivedAcknowledgements()).isEqualTo(0);
89+ assertThat(e.getRequiredAcknowledgements()).isEqualTo(1);
90+ assertThat(e.getAddress()).isEqualTo(host1.getSocketAddress());
91+ assertThat(e.getHost()).isEqualTo(host1.getAddress());
92+ }
93+ }
94+
95+ @Test(groups = "short")
96+ public void should_throw_proper_write_timeout_exception() {
97+ simulateError(1, write_request_timeout);
98+ try {
99+ query();
100+ fail("expected a WriteTimeoutException");
101+ } catch (WriteTimeoutException e) {
102+ assertThat(e.getMessage()).isEqualTo("Cassandra timeout during write query at consistency ONE (1 replica were required but only 0 acknowledged the write)");
103+ assertThat(e.getConsistencyLevel()).isEqualTo(ONE);
104+ assertThat(e.getReceivedAcknowledgements()).isEqualTo(0);
105+ assertThat(e.getRequiredAcknowledgements()).isEqualTo(1);
106+ assertThat(e.getWriteType()).isEqualTo(WriteType.SIMPLE);
107+ assertThat(e.getAddress()).isEqualTo(host1.getSocketAddress());
108+ assertThat(e.getHost()).isEqualTo(host1.getAddress());
109+ }
110+ }
111+
112+ protected void simulateError(int hostNumber, PrimingRequest.Result result) {
113+ scassandras
114+ .prime(hostNumber, PrimingRequest.queryBuilder()
115+ .withQuery("mock query")
116+ .withResult(result)
117+ .build());
118+ }
119+
120+ private static List<Map<String, ?>> row(String key, String value) {
121+ return ImmutableList.<Map<String, ?>>of(ImmutableMap.of(key, value));
122+ }
123+
124+ protected ResultSet query() {
125+ return query(session);
126+ }
127+
128+ protected ResultSet query(Session session) {
129+ return session.execute("mock query");
130+ }
131+
132+ @AfterMethod(groups = "short")
133+ public void afterMethod() {
134+ scassandras.clearAllPrimes();
135+ if (cluster != null)
136+ cluster.close();
137+ }
138+
139+ @AfterClass(groups = "short")
140+ public void afterClass() {
141+ if (scassandras != null)
142+ scassandras.stop();
143+ }
144+}
added driver-core/src/test/java/com/datastax/driver/core/exceptions/ExceptionsTest.java +334 −0
@@ -0,0 +1,334 @@
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.exceptions;
17+
18+import java.net.InetAddress;
19+import java.net.InetSocketAddress;
20+import java.util.Locale;
21+
22+import org.testng.annotations.Test;
23+
24+import static org.assertj.core.api.Assertions.assertThat;
25+import static org.testng.Assert.assertEquals;
26+import static org.testng.Assert.assertTrue;
27+
28+import com.datastax.driver.core.*;
29+
30+import static com.datastax.driver.core.CCMBridge.ipOfNode;
31+import static com.datastax.driver.core.ConsistencyLevel.LOCAL_QUORUM;
32+import static com.datastax.driver.core.TestUtils.waitForDownWithWait;
33+
34+/**
35+ * Tests Exception classes with separate clusters per test, when applicable
36+ */
37+public class ExceptionsTest {
38+
39+ private InetSocketAddress address1 = new InetSocketAddress("127.0.0.1", 9042);
40+ private InetSocketAddress address2 = new InetSocketAddress("127.0.0.2", 9042);
41+
42+ /**
43+ * Tests the AlreadyExistsException.
44+ * Create a keyspace twice and a table twice.
45+ * Catch and test all the exception methods.
46+ */
47+ @Test(groups = "short")
48+ public void alreadyExistsException() throws Throwable {
49+ Cluster.Builder builder = Cluster.builder();
50+ CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
51+ try {
52+ String keyspace = "TestKeyspace";
53+ String table = "TestTable";
54+
55+ String[] cqlCommands = new String[]{
56+ String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1),
57+ "USE " + keyspace,
58+ String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", table)
59+ };
60+
61+ // Create the schema once
62+ c.session.execute(cqlCommands[0]);
63+ c.session.execute(cqlCommands[1]);
64+ c.session.execute(cqlCommands[2]);
65+
66+ // Try creating the keyspace again
67+ try {
68+ c.session.execute(cqlCommands[0]);
69+ } catch (AlreadyExistsException e) {
70+ String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase());
71+ assertEquals(e.getMessage(), expected);
72+ assertEquals(e.getKeyspace(), keyspace.toLowerCase());
73+ assertEquals(e.getTable(), null);
74+ assertEquals(e.wasTableCreation(), false);
75+ assertEquals(e.getHost(), InetAddress.getByName(ipOfNode(1)));
76+ assertEquals(e.getAddress(), new InetSocketAddress(ipOfNode(1), 9042));
77+ }
78+
79+ c.session.execute(cqlCommands[1]);
80+
81+ // Try creating the table again
82+ try {
83+ c.session.execute(cqlCommands[2]);
84+ } catch (AlreadyExistsException e) {
85+ // is released
86+ assertEquals(e.getKeyspace(), keyspace.toLowerCase());
87+ assertEquals(e.getTable(), table.toLowerCase());
88+ assertEquals(e.wasTableCreation(), true);
89+ assertEquals(e.getHost(), InetAddress.getByName(ipOfNode(1)));
90+ assertEquals(e.getAddress(), new InetSocketAddress(ipOfNode(1), 9042));
91+ }
92+ } catch (Throwable e) {
93+ throw e;
94+ } finally {
95+ c.discard();
96+ }
97+ }
98+
99+ /**
100+ * Tests the NoHostAvailableException.
101+ * by attempting to build a cluster using the IP address "255.255.255.255"
102+ * and test all available exception methods.
103+ */
104+ @Test(groups = "short")
105+ public void noHostAvailableException() throws Exception {
106+ try {
107+ Cluster.builder().addContactPoints("255.255.255.255").build();
108+ } catch (NoHostAvailableException e) {
109+ assertEquals(e.getErrors().size(), 1);
110+ assertTrue(e.getErrors().values().iterator().next().toString().contains("[/255.255.255.255] Cannot connect"));
111+
112+ NoHostAvailableException copy = (NoHostAvailableException) e.copy();
113+ assertEquals(copy.getMessage(), e.getMessage());
114+ assertEquals(copy.getErrors(), e.getErrors());
115+ }
116+ }
117+
118+ /**
119+ * Tests DriverInternalError.
120+ * Tests basic message, rethrow, and copy abilities.
121+ */
122+ @Test(groups = "unit")
123+ public void driverInternalError() throws Exception {
124+ String errorMessage = "Test Message";
125+
126+ try {
127+ throw new DriverInternalError(errorMessage);
128+ } catch (DriverInternalError e1) {
129+ try {
130+ throw new DriverInternalError(e1);
131+ } catch (DriverInternalError e2) {
132+ assertTrue(e2.getMessage().contains(errorMessage));
133+
134+ DriverInternalError copy = (DriverInternalError) e2.copy();
135+ assertEquals(copy.getMessage(), e2.getMessage());
136+ }
137+ }
138+ }
139+
140+ @Test(groups = "unit")
141+ public void should_create_proper_already_exists_exception_for_keyspaces() {
142+ AlreadyExistsException e = new AlreadyExistsException(address1, "keyspace1", "");
143+ assertThat(e.getMessage()).isEqualTo("Keyspace keyspace1 already exists");
144+ assertThat(e.getKeyspace()).isEqualTo("keyspace1");
145+ assertThat(e.getTable()).isNull();
146+ assertThat(e.getAddress()).isEqualTo(address1);
147+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
148+ e = e.copy(address2);
149+ assertThat(e.getMessage()).isEqualTo("Keyspace keyspace1 already exists");
150+ assertThat(e.getKeyspace()).isEqualTo("keyspace1");
151+ assertThat(e.getTable()).isNull();
152+ assertThat(e.getAddress()).isEqualTo(address2);
153+ assertThat(e.getHost()).isEqualTo(address2.getAddress());
154+ }
155+
156+ @Test(groups = "unit")
157+ public void should_create_proper_already_exists_exception_for_tables() {
158+ AlreadyExistsException e = new AlreadyExistsException(address1, "keyspace1", "table1");
159+ assertThat(e.getMessage()).isEqualTo("Table keyspace1.table1 already exists");
160+ assertThat(e.getKeyspace()).isEqualTo("keyspace1");
161+ assertThat(e.getTable()).isEqualTo("table1");
162+ assertThat(e.getAddress()).isEqualTo(address1);
163+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
164+ e = e.copy(address2);
165+ assertThat(e.getMessage()).isEqualTo("Table keyspace1.table1 already exists");
166+ assertThat(e.getKeyspace()).isEqualTo("keyspace1");
167+ assertThat(e.getTable()).isEqualTo("table1");
168+ assertThat(e.getAddress()).isEqualTo(address2);
169+ assertThat(e.getHost()).isEqualTo(address2.getAddress());
170+ }
171+
172+ @Test(groups = "unit")
173+ public void should_create_proper_bootstrapping_exception() {
174+ BootstrappingException e = new BootstrappingException(address1, "Sorry mate");
175+ assertThat(e.getMessage()).isEqualTo("Queried host (" + address1 + ") was bootstrapping: Sorry mate");
176+ assertThat(e.getAddress()).isEqualTo(address1);
177+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
178+ e = e.copy();
179+ assertThat(e.getMessage()).isEqualTo("Queried host (" + address1 + ") was bootstrapping: Sorry mate");
180+ assertThat(e.getAddress()).isEqualTo(address1);
181+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
182+ }
183+
184+ @Test(groups = "unit")
185+ public void should_create_proper_invalid_query_exception() {
186+ InvalidQueryException e = new InvalidQueryException("Bad, really bad");
187+ assertThat(e.getMessage()).isEqualTo("Bad, really bad");
188+ e = (InvalidQueryException)e.copy();
189+ assertThat(e.getMessage()).isEqualTo("Bad, really bad");
190+ }
191+
192+ @Test(groups = "unit")
193+ public void should_create_proper_trace_retrieval_exception() {
194+ TraceRetrievalException e = new TraceRetrievalException("Couldn't find any trace of it");
195+ assertThat(e.getMessage()).isEqualTo("Couldn't find any trace of it");
196+ e = (TraceRetrievalException)e.copy();
197+ assertThat(e.getMessage()).isEqualTo("Couldn't find any trace of it");
198+ }
199+
200+ @Test(groups = "unit")
201+ public void should_create_proper_paging_state_exception() {
202+ PagingStateException e = new PagingStateException("Bad, really bad");
203+ assertThat(e.getMessage()).isEqualTo("Bad, really bad");
204+ // no copy method for this exception
205+ }
206+
207+ @Test(groups = "unit")
208+ public void should_create_proper_invalid_configuration_in_query_exception() {
209+ InvalidConfigurationInQueryException e = new InvalidConfigurationInQueryException(address1, "Bad, really bad");
210+ assertThat(e.getMessage()).isEqualTo("Bad, really bad");
211+ assertThat(e.getAddress()).isEqualTo(address1);
212+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
213+ InvalidQueryException e1 = (InvalidQueryException)e.copy();
214+ assertThat(e1.getMessage()).isEqualTo("Bad, really bad");
215+ }
216+
217+ @Test(groups = "unit")
218+ public void should_create_proper_overloaded_exception() {
219+ OverloadedException e = new OverloadedException(address1, "I'm busy");
220+ assertThat(e.getMessage()).isEqualTo("Queried host (" + address1 + ") was overloaded: I'm busy");
221+ assertThat(e.getAddress()).isEqualTo(address1);
222+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
223+ e = e.copy();
224+ assertThat(e.getMessage()).isEqualTo("Queried host (" + address1 + ") was overloaded: I'm busy");
225+ assertThat(e.getAddress()).isEqualTo(address1);
226+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
227+ }
228+
229+ @Test(groups = "unit")
230+ public void should_create_proper_syntax_error() {
231+ SyntaxError e = new SyntaxError(address1, "Missing ) at EOF");
232+ assertThat(e.getMessage()).isEqualTo("Missing ) at EOF");
233+ assertThat(e.getAddress()).isEqualTo(address1);
234+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
235+ e = (SyntaxError)e.copy();
236+ assertThat(e.getMessage()).isEqualTo("Missing ) at EOF");
237+ assertThat(e.getAddress()).isEqualTo(address1);
238+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
239+ }
240+
241+ @Test(groups = "unit")
242+ public void should_create_proper_truncate_exception() {
243+ TruncateException e = new TruncateException(address1, "I'm running headless now");
244+ assertThat(e.getMessage()).isEqualTo("I'm running headless now");
245+ assertThat(e.getAddress()).isEqualTo(address1);
246+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
247+ e = (TruncateException)e.copy();
248+ assertThat(e.getMessage()).isEqualTo("I'm running headless now");
249+ assertThat(e.getAddress()).isEqualTo(address1);
250+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
251+ }
252+
253+ @Test(groups = "unit")
254+ public void should_create_proper_unauthorized_exception() {
255+ UnauthorizedException e = new UnauthorizedException(address1, "You talking to me?");
256+ assertThat(e.getMessage()).isEqualTo("You talking to me?");
257+ assertThat(e.getAddress()).isEqualTo(address1);
258+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
259+ e = (UnauthorizedException)e.copy();
260+ assertThat(e.getMessage()).isEqualTo("You talking to me?");
261+ assertThat(e.getAddress()).isEqualTo(address1);
262+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
263+ }
264+
265+ @Test(groups = "unit")
266+ public void should_create_proper_unavailable_exception() {
267+ UnavailableException e = new UnavailableException(address1, LOCAL_QUORUM, 3, 2);
268+ assertThat(e.getMessage()).isEqualTo("Not enough replicas available for query at consistency LOCAL_QUORUM (3 required but only 2 alive)");
269+ assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
270+ assertThat(e.getAliveReplicas()).isEqualTo(2);
271+ assertThat(e.getRequiredReplicas()).isEqualTo(3);
272+ assertThat(e.getAddress()).isEqualTo(address1);
273+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
274+ e = e.copy(address2);
275+ assertThat(e.getMessage()).isEqualTo("Not enough replicas available for query at consistency LOCAL_QUORUM (3 required but only 2 alive)");
276+ assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
277+ assertThat(e.getAliveReplicas()).isEqualTo(2);
278+ assertThat(e.getRequiredReplicas()).isEqualTo(3);
279+ assertThat(e.getAddress()).isEqualTo(address2);
280+ assertThat(e.getHost()).isEqualTo(address2.getAddress());
281+ }
282+
283+ @Test(groups = "unit")
284+ public void should_create_proper_unprepared_exception() {
285+ UnpreparedException e = new UnpreparedException(address1, "Caught me unawares");
286+ assertThat(e.getMessage()).isEqualTo("A prepared query was submitted on " + address1 + " but was not known of that node: Caught me unawares");
287+ assertThat(e.getAddress()).isEqualTo(address1);
288+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
289+ e = e.copy();
290+ assertThat(e.getMessage()).isEqualTo("A prepared query was submitted on " + address1 + " but was not known of that node: Caught me unawares");
291+ assertThat(e.getAddress()).isEqualTo(address1);
292+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
293+ }
294+
295+ @Test(groups = "unit")
296+ public void should_create_proper_read_timeout_exception() {
297+ ReadTimeoutException e = new ReadTimeoutException(address1, LOCAL_QUORUM, 2, 3, true);
298+ assertThat(e.getMessage()).isEqualTo("Cassandra timeout during read query at consistency LOCAL_QUORUM (3 responses were required but only 2 replica responded)");
299+ assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
300+ assertThat(e.getReceivedAcknowledgements()).isEqualTo(2);
301+ assertThat(e.getRequiredAcknowledgements()).isEqualTo(3);
302+ assertThat(e.wasDataRetrieved()).isTrue();
303+ assertThat(e.getAddress()).isEqualTo(address1);
304+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
305+ e = e.copy(address2);
306+ assertThat(e.getMessage()).isEqualTo("Cassandra timeout during read query at consistency LOCAL_QUORUM (3 responses were required but only 2 replica responded)");
307+ assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
308+ assertThat(e.getReceivedAcknowledgements()).isEqualTo(2);
309+ assertThat(e.getRequiredAcknowledgements()).isEqualTo(3);
310+ assertThat(e.wasDataRetrieved()).isTrue();
311+ assertThat(e.getAddress()).isEqualTo(address2);
312+ assertThat(e.getHost()).isEqualTo(address2.getAddress());
313+ }
314+
315+ @Test(groups = "unit")
316+ public void should_create_proper_write_timeout_exception() {
317+ WriteTimeoutException e = new WriteTimeoutException(address1, LOCAL_QUORUM, WriteType.BATCH, 2, 3);
318+ assertThat(e.getMessage()).isEqualTo("Cassandra timeout during write query at consistency LOCAL_QUORUM (3 replica were required but only 2 acknowledged the write)");
319+ assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
320+ assertThat(e.getReceivedAcknowledgements()).isEqualTo(2);
321+ assertThat(e.getRequiredAcknowledgements()).isEqualTo(3);
322+ assertThat(e.getWriteType()).isEqualTo(WriteType.BATCH);
323+ assertThat(e.getAddress()).isEqualTo(address1);
324+ assertThat(e.getHost()).isEqualTo(address1.getAddress());
325+ e = e.copy(address2);
326+ assertThat(e.getMessage()).isEqualTo("Cassandra timeout during write query at consistency LOCAL_QUORUM (3 replica were required but only 2 acknowledged the write)");
327+ assertThat(e.getConsistencyLevel()).isEqualTo(LOCAL_QUORUM);
328+ assertThat(e.getReceivedAcknowledgements()).isEqualTo(2);
329+ assertThat(e.getRequiredAcknowledgements()).isEqualTo(3);
330+ assertThat(e.getWriteType()).isEqualTo(WriteType.BATCH);
331+ assertThat(e.getAddress()).isEqualTo(address2);
332+ assertThat(e.getHost()).isEqualTo(address2.getAddress());
333+ }
334+}
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +0 −1
@@ -191,7 +191,6 @@
191191 }
192192
193193 @Override public void init(Cluster cluster, Collection<Host> hosts) {
194- System.out.println("init " + hosts);
195194 initHosts.addAll(hosts);
196195 super.init(cluster, hosts);
197196 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +70 −58
@@ -76,23 +76,27 @@
7676 Cluster.Builder builder = super.createClusterBuilder();
7777 builder.withLoadBalancingPolicy(latencyAwarePolicy);
7878 Cluster cluster = builder.build();
79- cluster.init(); // force initialization of latency aware policy
80- LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
81- cluster.register(barrier); // add barrier to synchronize latency tracker threads with the current thread
82- Session session = cluster.connect();
83- // when
84- session.execute(query);
85- // then
86- // wait until trackers have been notified
87- barrier.await();
88- // make sure the updater is called at least once
89- latencyAwarePolicy.new Updater().run();
90- LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
91- assertThat(snapshot.getAllStats()).hasSize(1);
92- LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
93- assertThat(stats).isNotNull();
94- assertThat(stats.getMeasurementsCount()).isEqualTo(1);
95- assertThat(stats.getLatencyScore()).isNotEqualTo(-1);
79+ try {
80+ cluster.init(); // force initialization of latency aware policy
81+ LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
82+ cluster.register(barrier); // add barrier to synchronize latency tracker threads with the current thread
83+ Session session = cluster.connect();
84+ // when
85+ session.execute(query);
86+ // then
87+ // wait until trackers have been notified
88+ barrier.await();
89+ // make sure the updater is called at least once
90+ latencyAwarePolicy.new Updater().run();
91+ LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
92+ assertThat(snapshot.getAllStats()).hasSize(1);
93+ LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
94+ assertThat(stats).isNotNull();
95+ assertThat(stats.getMeasurementsCount()).isEqualTo(1);
96+ assertThat(stats.getLatencyScore()).isNotEqualTo(-1);
97+ } finally {
98+ cluster.close();
99+ }
96100 }
97101
98102 @Test(groups = "short")
@@ -111,29 +115,33 @@
111115 Cluster.Builder builder = super.createClusterBuilder();
112116 builder.withLoadBalancingPolicy(latencyAwarePolicy);
113117 Cluster cluster = builder.build();
114- cluster.init(); // force initialization of latency aware policy
115- LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
116- cluster.register(barrier);
117- Session session = cluster.connect();
118- // when
119118 try {
120- session.execute(query);
121- fail("Should have thrown NoHostAvailableException");
122- } catch(NoHostAvailableException e) {
123- // ok
124- Throwable error = e.getErrors().get(hostAddress);
125- assertThat(error).isNotNull();
126- assertThat(error).isInstanceOf(UnavailableException.class);
119+ cluster.init(); // force initialization of latency aware policy
120+ LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
121+ cluster.register(barrier);
122+ Session session = cluster.connect();
123+ // when
124+ try {
125+ session.execute(query);
126+ fail("Should have thrown NoHostAvailableException");
127+ } catch (NoHostAvailableException e) {
128+ // ok
129+ Throwable error = e.getErrors().get(hostAddress);
130+ assertThat(error).isNotNull();
131+ assertThat(error).isInstanceOf(UnavailableException.class);
132+ }
133+ // then
134+ // wait until trackers have been notified
135+ barrier.await();
136+ // make sure the updater is called at least once
137+ latencyAwarePolicy.new Updater().run();
138+ LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
139+ assertThat(snapshot.getAllStats()).isEmpty();
140+ LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
141+ assertThat(stats).isNull();
142+ } finally {
143+ cluster.close();
127144 }
128- // then
129- // wait until trackers have been notified
130- barrier.await();
131- // make sure the updater is called at least once
132- latencyAwarePolicy.new Updater().run();
133- LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
134- assertThat(snapshot.getAllStats()).isEmpty();
135- LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
136- assertThat(stats).isNull();
137145 }
138146
139147 @Test(groups= "short")
@@ -153,28 +161,32 @@
153161 builder.withLoadBalancingPolicy(latencyAwarePolicy);
154162 builder.withRetryPolicy(FallthroughRetryPolicy.INSTANCE);
155163 Cluster cluster = builder.build();
156- cluster.init(); // force initialization of latency aware policy
157- LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
158- cluster.register(barrier);
159- Session session = cluster.connect();
160- // when
161164 try {
162- session.execute(query);
163- fail("Should have thrown ReadTimeoutException");
164- } catch(ReadTimeoutException e) {
165- // ok
165+ cluster.init(); // force initialization of latency aware policy
166+ LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1);
167+ cluster.register(barrier);
168+ Session session = cluster.connect();
169+ // when
170+ try {
171+ session.execute(query);
172+ fail("Should have thrown ReadTimeoutException");
173+ } catch (ReadTimeoutException e) {
174+ // ok
175+ }
176+ // then
177+ // wait until trackers have been notified
178+ barrier.await();
179+ // make sure the updater is called at least once
180+ latencyAwarePolicy.new Updater().run();
181+ LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
182+ assertThat(snapshot.getAllStats()).hasSize(1);
183+ LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
184+ assertThat(stats).isNotNull();
185+ assertThat(stats.getMeasurementsCount()).isEqualTo(1);
186+ assertThat(stats.getLatencyScore()).isNotEqualTo(-1);
187+ } finally {
188+ cluster.close();
166189 }
167- // then
168- // wait until trackers have been notified
169- barrier.await();
170- // make sure the updater is called at least once
171- latencyAwarePolicy.new Updater().run();
172- LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot();
173- assertThat(snapshot.getAllStats()).hasSize(1);
174- LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster));
175- assertThat(stats).isNotNull();
176- assertThat(stats.getMeasurementsCount()).isEqualTo(1);
177- assertThat(stats.getLatencyScore()).isNotEqualTo(-1);
178190 }
179191
180192 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +3 −0
@@ -25,6 +25,8 @@
2525 import com.datastax.driver.core.*;
2626 import com.datastax.driver.core.utils.Bytes;
2727
28+import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions;
29+
2830 public class TokenAwarePolicyTest {
2931 @Test(groups = "long")
3032 public void should_shuffle_replicas_when_requested() {
@@ -46,6 +48,7 @@
4648 cluster = Cluster.builder()
4749 .addContactPoint(CCMBridge.ipOfNode(1))
4850 .withLoadBalancingPolicy(loadBalancingPolicy)
51+ .withQueryOptions(nonDebouncingQueryOptions())
4952 .build();
5053
5154 String keyspace = "ks";
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +42 −3
@@ -42,6 +42,15 @@
4242 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4343 }
4444
45+ @Override
46+ protected Cluster.Builder configure(Cluster.Builder builder) {
47+ return builder.withQueryOptions(new QueryOptions()
48+ .setRefreshNodeIntervalMillis(0)
49+ .setRefreshNodeListIntervalMillis(0)
50+ .setRefreshSchemaIntervalMillis(0)
51+ );
52+ }
53+
4554 @BeforeMethod(groups = "short")
4655 public void setUpQueryBuilder() throws Exception {
4756 builder = new QueryBuilder(cluster);
@@ -79,8 +88,6 @@
7988
8089 query = "SELECT * FROM foo WHERE k=?;";
8190 select = builder.select().all().from("foo").where(eq("k", QueryBuilder.bindMarker()));
82- System.out.println(select.toString());
83- System.out.println(session);
8491 ps = session.prepare(select.toString());
8592 bs = ps.bind();
8693 assertEquals(select.toString(), query);
@@ -218,7 +225,7 @@
218225 @CassandraVersion(major=2.0, minor=7, description="DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)")
219226 public void conditionalDeletesTest() throws Exception {
220227 session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace));
221-
228+
222229 Statement delete;
223230 Row row;
224231 delete = builder.delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists();
@@ -239,4 +246,36 @@
239246 row = session.execute(delete).one();
240247 assertTrue(row.getBool("[applied]"));
241248 }
249+
250+ @Test(groups = "short")
251+ @CassandraVersion(major=2.0, minor=13, description="Allow IF EXISTS for UPDATE statements (CASSANDRA-8610)")
252+ public void conditionalUpdatesTest() throws Exception {
253+ session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace));
254+
255+ Statement update;
256+ Row row;
257+ update = builder.update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).ifExists();
258+ row = session.execute(update).one();
259+ assertFalse(row.getBool("[applied]"));
260+
261+ update = builder.update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 1)).ifExists();
262+ row = session.execute(update).one();
263+ assertTrue(row.getBool("[applied]"));
264+
265+ update = builder.update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).onlyIf(eq("a", 1)).and(eq("b", 2));
266+ row = session.execute(update).one();
267+ assertFalse(row.getBool("[applied]"));
268+
269+ update = builder.update(TABLE_INT).with(set("a", 3)).and(set("b", 3)).where(eq("k", 1)).onlyIf(eq("a", 2)).and(eq("b", 2));
270+ row = session.execute(update).one();
271+ assertTrue(row.getBool("[applied]"));
272+
273+ update = builder.update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 2)).and(eq("b", 2)).where(eq("k", 1));
274+ row = session.execute(update).one();
275+ assertFalse(row.getBool("[applied]"));
276+
277+ update = builder.update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 3)).and(eq("b", 3)).where(eq("k", 1));
278+ row = session.execute(update).one();
279+ assertTrue(row.getBool("[applied]"));
280+ }
242281 }
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +9 −0
@@ -39,6 +39,15 @@
3939 String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT));
4040 }
4141
42+ @Override
43+ protected Cluster.Builder configure(Cluster.Builder builder) {
44+ return builder.withQueryOptions(new QueryOptions()
45+ .setRefreshNodeIntervalMillis(0)
46+ .setRefreshNodeListIntervalMillis(0)
47+ .setRefreshSchemaIntervalMillis(0)
48+ );
49+ }
50+
4251 @Test(groups = "short")
4352 public void textRoutingKeyTest() throws Exception {
4453
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +23 −1
@@ -339,8 +339,12 @@
339339 query = "UPDATE foo SET x=4 WHERE k=0 IF x=1;";
340340 update = builder.update("foo").with(set("x", 4)).where(eq("k", 0)).onlyIf(eq("x", 1));
341341 assertEquals(update.toString(), query);
342- }
343342
343+ // IF EXISTS CAS test
344+ update = builder.update("foo").with(set("x", 3)).where(eq("k", 2)).ifExists();
345+ assertThat(update.toString()).isEqualTo("UPDATE foo SET x=3 WHERE k=2 IF EXISTS;");
346+ }
347+
344348 @Test(groups = "unit")
345349 public void deleteTest() throws Exception {
346350
@@ -863,4 +867,22 @@
863867 assertThat(select.getQueryString()).doesNotContain("?");
864868 assertThat(select.getValues()).isNull();
865869 }
870+
871+ @Test(groups = "unit", expectedExceptions = { IllegalStateException.class })
872+ public void should_throw_ISE_if_getObject_called_on_statement_without_values() {
873+ builder.select().from("test").where(eq("foo", 42)).getObject(0); // integers are appended to the CQL string
874+ }
875+
876+ @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class })
877+ public void should_throw_IOOBE_if_getObject_called_with_wrong_index() {
878+ builder.select().from("test").where(eq("foo", new Object())).getObject(1);
879+ }
880+
881+ @Test(groups = "unit")
882+ public void should_return_object_at_ith_index() {
883+ Object expected = new Object();
884+ Object actual = builder.select().from("test").where(eq("foo", expected)).getObject(0);
885+ assertThat(actual).isSameAs(expected);
886+ }
887+
866888 }
modified driver-core/src/test/resources/log4j.properties +3 −2
@@ -17,8 +17,9 @@
1717 # Set root logger level to DEBUG and its only appender to A1.
1818 log4j.rootLogger=INFO, A1
1919
20-# Scassandra's info log is a bit verbose
21-log4j.logger.org.scassandra=WARN
20+# Adjust Scassandra's log level
21+# (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both)
22+log4j.logger.org.scassandra=ERROR
2223
2324 # A1 is set to be a ConsoleAppender.
2425 log4j.appender.A1=org.apache.log4j.ConsoleAppender
added driver-core/src/test/resources/reference.conf +5 −0
@@ -0,0 +1,5 @@
1+# Adjust Scassandra's log level
2+# (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both)
3+akka {
4+ loglevel = "ERROR"
5+}
No newline at the end of the file
added features/async/README.md +102 −0
@@ -0,0 +1,102 @@
1+## Asynchronous programming
2+
3+The driver exposes an asynchronous API that allows you to write programs
4+in a fully-non blocking manner. Asynchronous methods return instances of
5+Guava's [ListenableFuture], that can be conveniently chained and
6+composed.
7+
8+Here is a short example that opens a session and runs a query
9+asynchronously:
10+
11+```java
12+import com.google.common.util.concurrent.*;
13+
14+ListenableFuture<Session> session = cluster.connectAsync();
15+
16+// Use transform with an AsyncFunction to chain an async operation after another:
17+ListenableFuture<ResultSet> resultSet = Futures.transform(session,
18+ new AsyncFunction<Session, ResultSet>() {
19+ public ListenableFuture<ResultSet> apply(Session session) throws Exception {
20+ return session.executeAsync("select release_version from system.local");
21+ }
22+ });
23+
24+// Use transform with a simple Function to apply a synchronous computation on the result:
25+ListenableFuture<String> version = Futures.transform(resultSet,
26+ new Function<ResultSet, String>() {
27+ public String apply(ResultSet rs) {
28+ return rs.one().getString("release_version");
29+ }
30+ });
31+
32+// Use a callback to perform an action once the future is complete:
33+Futures.addCallback(version, new FutureCallback<String>() {
34+ public void onSuccess(String version) {
35+ System.out.printf("Cassandra version: %s%n", version);
36+ }
37+
38+ public void onFailure(Throwable t) {
39+ System.out.printf("Failed to retrieve the version: %s%n",
40+ t.getMessage());
41+ }
42+});
43+```
44+
45+### Good practices
46+
47+If your callback is slow, consider providing a separate executor.
48+Otherwise the callback might run on one of the driver's I/O threads,
49+blocking I/O operations for other requests while it is running:
50+
51+```java
52+ListenableFuture<String> result = Futures.transform(resultSet,
53+ new Function<ResultSet, String>() {
54+ public String apply(ResultSet rs) {
55+ return someVeryLongComputation(rs);
56+ }
57+ }, myCustomExecutor);
58+```
59+
60+Avoid blocking operations in callbacks, especially if you don't provide
61+a separate executor. This could easily lead to deadlock if the thread
62+that's supposed to complete the blocking call is also the thread that's
63+waiting on it:
64+
65+```java
66+ListenableFuture<ResultSet> resultSet = Futures.transform(session,
67+ new Function<Session, ResultSet>() {
68+ public ResultSet apply(Session session) {
69+ // Synchronous operation in a callback.
70+ // DON'T DO THIS! It might deadlock.
71+ return session.execute("select release_version from system.local");
72+ }
73+ });
74+```
75+
76+### Known limitations
77+
78+There are still a few places where the driver will block internally
79+(mainly for historical reasons):
80+
81+* [Cluster#init][init] performs blocking I/O operations. To avoid
82+ issues, you should create your `Cluster` instances while bootstrapping
83+ your application, and call `init` immediately. If you need to create new
84+ instances at runtime, make sure this does not happen on an I/O thread.
85+* if a connection pool is busy, the driver will block until a connection
86+ becomes available. To avoid this, set
87+ [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the
88+ driver will not block, just move to the next host immediately.
89+* if the session is set to a specific keyspace (either at startup or by
90+ issuing a `USE` statement on a running session), the keyspace needs to
91+ be propagated to any newly created connection. This is done when the
92+ connection is first borrowed from the connection pool, and currently
93+ blocks. To avoid any issue, only use a session with no keyspace set
94+ (i.e. created by `Cluster#connect()`). This will be addressed in
95+ [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893).
96+* trying to read fields from a [query trace] will block if the trace
97+ hasn't been fetched already.
98+
99+[ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained
100+[init]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#init()
101+[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis(int)
102+[query trace]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryTrace.html
modified features/metadata/README.md +23 −0
@@ -27,6 +27,29 @@
2727 via a push notification. It refreshes the schema directly (there is no
2828 need to wait for schema agreement since Cassandra has already done it).
2929
30+#### Subscribing to schema changes
31+
32+Users interested in being notified of schema changes can implement the
33+[SchemaChangeListener][SchemaChangeListener] interface.
34+
35+Every listener must [be registered][registerListener] against a `Cluster` instance:
36+
37+```java
38+Cluster cluster = ...
39+SchemaChangeListener myListener = ...
40+cluster.register(myListener);
41+```
42+
43+Once registered, the listener will be notified of all schema changes detected by the driver,
44+regardless of where they originate from.
45+
46+Note that it is preferable to register a listener only *after* the cluster is fully initialized,
47+otherwise the listener could be notified with a great deal of "Added" events as
48+the driver builds the schema metadata from scratch for the first time.
49+
50+[SchemaChangeListener]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SchemaChangeListener.html
51+[registerListener]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Cluster.html#register(com.datastax.driver.core.SchemaChangeListener)
52+
3053 #### Schema agreement
3154
3255 Schema changes need to be propagated to all nodes in the cluster. Once
added features/statements/README.md +54 −0
@@ -0,0 +1,54 @@
1+## Statements
2+
3+To execute a query, you create a [Statement] instance and pass it to
4+`Session#execute()`. The driver provides various implementations:
5+
6+* [SimpleStatement]: a simple implementation built directly from a
7+ character string. Typically used for queries that are executed only
8+ once or a few times.
9+* [BoundStatement]: obtained by binding values to a [prepared
10+ statement](prepared/). Typically used for queries that are executed
11+ often, with different values.
12+* [BuiltStatement]: a statement built with the [QueryBuilder] DSL. It
13+ can be executed directly like a simple statement, or prepared.
14+* [BatchStatement]: a statement that groups multiple statements to be
15+ executed as a batch.
16+
17+`Session` also has a shortcut to build and execute a simple statement in
18+a single call:
19+
20+```java
21+session.execute("select release_version from system.local");
22+
23+// Is equivalent to:
24+Statement s = new SimpleStatement("select release_version from system.local");
25+session.execute(s);
26+```
27+
28+### Customizing execution
29+
30+Before executing a statement, you might want to customize certain
31+aspects of its execution. `Statement` provides a number of methods for
32+this, for example:
33+
34+```java
35+Statement s = new SimpleStatement("select release_version from system.local");
36+s.enableTracing();
37+session.execute(s);
38+```
39+
40+If you use custom policies ([RetryPolicy], [LoadBalancingPolicy],
41+[SpeculativeExecutionPolicy]...), you might also want to have custom
42+properties that influence statement execution. To achieve this, you can
43+wrap your statements in a custom [StatementWrapper] implementation.
44+
45+[Statement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/Statement.html
46+[SimpleStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/SimpleStatement.html
47+[BoundStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/BoundStatement.html
48+[BatchStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/BatchStatement.html
49+[QueryBuilder]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/querybuilder/QueryBuilder.html
50+[BuiltStatement]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/querybuilder/BuiltStatement.html
51+[StatementWrapper]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/StatementWrapper.html
52+[RetryPolicy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/RetryPolicy.html
53+[LoadBalancingPolicy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html
54+[SpeculativeExecutionPolicy]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/policies/SpeculativeExecutionPolicy.html
added features/statements/prepared/README.md +172 −0
@@ -0,0 +1,172 @@
1+## Prepared statements
2+
3+When Cassandra executes a query, the first thing it does is parse the
4+query string to an internal representation. If the same query is used
5+often, you can use a prepared statement, which allows Cassandra to cache
6+that representation, and save time and resources for subsequent
7+executions. Prepared statements are typically parameterized, using
8+different values for each execution:
9+
10+```java
11+PreparedStatement prepared = session.prepare(
12+ "insert into product (sku, description) values (?, ?)");
13+
14+BoundStatement bound;
15+
16+bound = prepared.bind("234827", "Mouse");
17+session.execute(bound);
18+
19+bound = prepared.bind("987274", "Keyboard");
20+session.execute(bound);
21+```
22+
23+Statements should be be prepared only once. If you call `prepare`
24+multiple times with the same query string, the driver will log a
25+warning. So your application should cache the `PreparedStatement` object
26+once it's been created (this can be as simple as storing it as a field
27+in a DAO).
28+
29+### Parameters and binding
30+
31+Parameters can be either anonymous or named (named parameters are only
32+available with [native protocol](../../native_protocol) v2 or above):
33+
34+```java
35+ps1 = session.prepare("insert into product (sku, description) values (?, ?)");
36+ps2 = session.prepare("insert into product (sku, description) values (:s, :d)");
37+```
38+
39+To turn the statement into its executable form, you need to *bind* it
40+and provide values for the parameters. As shown previously, there is a
41+shorthand form to do it all in one call:
42+
43+```java
44+BoundStatement bound = ps1.bind("324378", "LCD screen");
45+```
46+
47+You can also bind first, then use setters, which is slightly more
48+explicit:
49+
50+```java
51+// Positional setters:
52+BoundStatement bound = ps1.bind()
53+ .setString(0, "324378")
54+ .setString(1, "LCD screen");
55+
56+// Named setters:
57+BoundStatement bound = ps2.bind()
58+ .setString("s", "324378")
59+ .setString("d", "LCD screen");
60+```
61+
62+If you don't set a parameter, it is sent as `null` (note that this
63+behavior changes in the 2.1 branch of the driver).
64+
65+You can use named setters even if the query uses anonymous parameters;
66+Cassandra will name the parameters after the column they apply to:
67+
68+```java
69+BoundStatement bound = ps1.bind()
70+ .setString("sku", "324378")
71+ .setString("description", "LCD screen");
72+```
73+
74+This can be ambiguous if the query uses the same column multiple times,
75+for example: `select * from sales where sku = ? and date > ? and date <
76+?`. In these situations, use positional setters or named parameters.
77+
78+A bound statement also has getters to retrieve the values. Note that
79+this has a small performance overhead since values are stored in their
80+serialized form.
81+
82+### How the driver handles prepared statements
83+
84+When the driver prepares a statement, it sends the query string to
85+Cassandra, which caches the statement and returns an identifier. Later,
86+when the driver needs to execute the statement, it just sends the
87+identifier and parameter values. Note that the identifier is
88+deterministic, so it will always be the same for all nodes (it's a
89+actually a hash of the query string).
90+
91+Prepared statements are not replicated across the cluster. It is the
92+driver's responsibility to ensure that each node's cache is up to
93+date. It uses a number of strategies to achieve this:
94+
95+1. When a statement is initially prepared, it is first sent to a single
96+ node in the cluster (this prevents from hitting all nodes in case
97+ the query string is wrong). Once that node replies successfully, the
98+ driver re-prepares on all remaining nodes:
99+
100+ ```ditaa
101+ client driver node1 node2 node3
102+ --+------------------------+----------------+--------------+------+---
103+ | | | | |
104+ | session.prepare(query) | | | |
105+ |----------------------->| | | |
106+ | | PREPARE(query) | | |
107+ | |--------------->| | |
108+ | | | | |
109+ | | PREPARED(id) | | |
110+ | |<---------------| | |
111+ | | | | |
112+ | | | | |
113+ | | PREPARE(query) | |
114+ | |------------------------------>| |
115+ | | | | |
116+ | | PREPARE(query) | |
117+ | |------------------------------------->|
118+ | | | | |
119+ |<-----------------------| | | |
120+ ```
121+
122+2. if a node crashes, it loses all of its prepared statements. So the
123+ driver keeps a client-side cache; anytime a node is marked back up,
124+ the driver re-prepares all statements on it;
125+
126+3. finally, if the driver tries to execute a statement and finds out
127+ that the coordinator doesn't know about it, it will re-prepare the
128+ statement on the fly (this is transparent for the client, but will cost
129+ two extra roundtrips):
130+
131+ ```ditaa
132+ client driver node1
133+ --+-------------------------------+------------------------------+--
134+ | | |
135+ |session.execute(boundStatement)| |
136+ +------------------------------>| |
137+ | | EXECUTE(id, values) |
138+ | |----------------------------->|
139+ | | |
140+ | | UNPREPARED |
141+ | |<-----------------------------|
142+ | | |
143+ | | |
144+ | | PREPARE(query) |
145+ | |----------------------------->|
146+ | | |
147+ | | PREPARED(id) |
148+ | |<-----------------------------|
149+ | | |
150+ | | |
151+ | | EXECUTE(id, values) |
152+ | |----------------------------->|
153+ | | |
154+ | | ROWS |
155+ | |<-----------------------------|
156+ | | |
157+ |<------------------------------| |
158+ ```
159+
160+You can customize these strategies through `QueryOptions`:
161+
162+* [setPrepareOnAllHosts] controls whether statements are initially
163+ re-prepared on other hosts (step 1 above);
164+* [setReprepareOnUp] controls whether statements are re-prepared on a
165+ node that comes back up (step 2 above).
166+
167+Changing the driver's defaults should be done with care and only in
168+specific situations; read each method's Javadoc for detailed
169+explanations.
170+
171+[setPrepareOnAllHosts]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryOptions.html#setPrepareOnAllHosts(boolean)
172+[setReprepareOnUp]: http://docs.datastax.com/en/drivers/java/2.0/com/datastax/driver/core/QueryOptions.html#setReprepareOnUp(boolean)
modified pom.xml +2 −6
@@ -43,7 +43,7 @@
4343
4444 <properties>
4545 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
46- <cassandra.version>2.2.0</cassandra.version>
46+ <cassandra.version>2.2.1</cassandra.version>
4747 <java.version>1.6</java.version>
4848 <log4j.version>1.2.17</log4j.version>
4949 <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version>
@@ -57,11 +57,7 @@
5757 <testng.version>6.8.8</testng.version>
5858 <assertj.version>1.7.0</assertj.version>
5959 <mockito.version>1.10.8</mockito.version>
60- <!--
61- There are more recent versions of Scassandra but they require JDK 7,
62- our build is still using JDK 6.
63- -->
64- <scassandra.version>0.4.1</scassandra.version>
60+ <scassandra.version>0.9.1</scassandra.version>
6561 <main.basedir>${project.basedir}</main.basedir>
6662 </properties>
6763
modified upgrade_guide/README.md +12 −0
@@ -355,6 +355,9 @@
355355
356356 ### 2.0.11
357357
358+2.0.11 preserves binary compatibility with previous versions. There are a few
359+changes in the driver's behavior:
360+
358361 1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable
359362 exception received from a request. The new behaviour will cause the driver to
360363 process a Retry on a different node at most once, otherwise an exception will
@@ -363,11 +366,20 @@
363366 because of a network partition) but can still answer to the client normally.
364367 In this case, trying another node has a chance of success.
365368 The previous behaviour was to always throw an exception.
369+
366370 2. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()`
367371 or `raw()` is used to build a value to be inserted in the database.
368372 If you know that the CQL functions or expressions are safe, use
369373 `setIdempotent(true)` on the statement.
370374
375+3. The list of contact points provided at startup is now shuffled before trying
376+ to open the control connection, so that multiple clients with the same contact
377+ points don't all pick the same control host. As a result, you can't assume that
378+ the driver will try contact points in a deterministic order. In particular, if
379+ you use the `DCAwareRoundRobinPolicy` without specifying a primary datacenter
380+ name, make sure that you only provide local hosts as contact points.
381+
382+
371383 ### <a name="2-0-x-to-2-0-10"></a>2.0.x to 2.0.10
372384
373385 We try to avoid breaking changes within a branch (2.0.x to 2.0.y), but