kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | e0c6a4e0504fa58e4cef3050727938f0636176a355c412477974a1b0651267aa |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-09-15 20:01 +02:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-09-16 15:02 +02:00 |
| Parents | bbc1b7117731, a5f98239766e |
113 files changed
modified .gitignore +2 −0
| @@ -13,3 +13,5 @@ | ||
| 13 | 13 | *.iml |
| 14 | 14 | |
| 15 | 15 | /driver-core/dependency-reduced-pom.xml |
| 16 | +.java-version | |
| 17 | + |
modified changelog/README.md +76 −1
| @@ -1,5 +1,56 @@ | ||
| 1 | 1 | ## Changelog |
| 2 | 2 | |
| 3 | +### 2.1.8 (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 | + | |
| 9 | +- [bug] Fix SpeculativeExecutionPolicy.init() and close() are never called (JAVA-796) | |
| 10 | +- [improvement] Suppress unnecessary warning at shutdown (JAVA-710) | |
| 11 | +- [improvement] Allow DNS name with multiple A-records as contact point (#340) | |
| 12 | +- [bug] Allow tracing across multiple result pages (JAVA-794) | |
| 13 | +- [bug] DowngradingConsistencyRetryPolicy ignores write timeouts (JAVA-737) | |
| 14 | +- [bug] Forbid bind marker in QueryBuilder add/append/prepend (JAVA-736) | |
| 15 | +- [bug] Prevent QueryBuilder.quote() from applying duplicate double quotes (JAVA-712) | |
| 16 | +- [bug] Prevent QueryBuilder from trying to serialize raw string (JAVA-688) | |
| 17 | +- [bug] Support bind marker in QueryBuilder DELETE's list index (JAVA-679) | |
| 18 | +- [improvement] Improve QueryBuilder API for SELECT DISTINCT (JAVA-475) | |
| 19 | +- [improvement] Create values() function for Insert builder using List (JAVA-225) | |
| 20 | +- [improvement] Warn when ReplicationStrategy encounters invalid | |
| 21 | + replication factors (JAVA-702) | |
| 22 | +- [improvement] Add PoolingOptions method to set both core and max | |
| 23 | + connections (JAVA-662). | |
| 24 | +- [improvement] Do not include epoll JAR in binary distribution (JAVA-766) | |
| 25 | +- [improvement] Optimize internal copies of Request objects (JAVA-726) | |
| 26 | +- [bug] Preserve tracing across retries (JAVA-815) | |
| 27 | +- [improvement] New RetryDecision.tryNextHost() (JAVA-709) | |
| 28 | +- [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733) | |
| 29 | +- [improvement] Provide API to retrieve values of a Parameterized SimpleStatement (JAVA-765) | |
| 30 | +- [improvement] implement UPDATE ... IF EXISTS in QueryBuilder (JAVA-827) | |
| 31 | +- [improvement] Randomize contact points list to prevent hotspots (JAVA-618) | |
| 32 | +- [improvement] Surface the coordinator used on query failure (JAVA-720) | |
| 33 | +- [bug] Handle contact points removed during init (JAVA-792) | |
| 34 | +- [improvement] Allow PlainTextAuthProvider to change its credentials at runtime (JAVA-719) | |
| 35 | +- [new feature] Make it possible to register for SchemaChange Events (JAVA-151) | |
| 36 | +- [improvement] Downgrade "Asked to rebuild table" log from ERROR to INFO level (JAVA-861) | |
| 37 | +- [improvement] Provide an option to prepare statements only on one node (JAVA-797) | |
| 38 | +- [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658) | |
| 39 | +- [improvement] Customizable creation of netty timer (JAVA-853) | |
| 40 | +- [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859) | |
| 41 | +- [improvement] Debounce control connection queries (JAVA-657) | |
| 42 | +- [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784) | |
| 43 | +- [new feature] Make driver-side metadata optional (JAVA-828) | |
| 44 | +- [improvement] Allow hosts to remain partially up (JAVA-544) | |
| 45 | +- [improvement] Remove internal blocking calls and expose async session | |
| 46 | + creation (JAVA-821, JAVA-822) | |
| 47 | +- [improvement] Use parallel calls when re-preparing statement on other | |
| 48 | + hosts (JAVA-725) | |
| 49 | +- [bug] Don't use connection timeout for unrelated internal queries (JAVA-629) | |
| 50 | +- [bug] Fix NPE in speculative executions when metrics disabled | |
| 51 | + (JAVA-892) | |
| 52 | + | |
| 53 | + | |
| 3 | 54 | ### 2.1.7.1 |
| 4 | 55 | |
| 5 | 56 | - [bug] Special case check for 'null' string in index_options column (JAVA-834) |
| @@ -262,8 +313,9 @@ | ||
| 262 | 313 | - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391) |
| 263 | 314 | |
| 264 | 315 | |
| 265 | -### 2.0.11 (in progress) | |
| 316 | +### 2.0.11 | |
| 266 | 317 | |
| 318 | +- [improvement] Log streamid at the trace level on sending request and receiving response (JAVA-718) | |
| 267 | 319 | - [bug] Fix SpeculativeExecutionPolicy.init() and close() are never called (JAVA-796) |
| 268 | 320 | - [improvement] Suppress unnecessary warning at shutdown (JAVA-710) |
| 269 | 321 | - [improvement] Allow DNS name with multiple A-records as contact point (#340) |
| @@ -284,6 +336,29 @@ | ||
| 284 | 336 | - [bug] Preserve tracing across retries (JAVA-815) |
| 285 | 337 | - [improvement] New RetryDecision.tryNextHost() (JAVA-709) |
| 286 | 338 | - [bug] Handle function calls and raw strings as non-idempotent in QueryBuilder (JAVA-733) |
| 339 | +- [improvement] Provide API to retrieve values of a Parameterized SimpleStatement (JAVA-765) | |
| 340 | +- [improvement] implement UPDATE ... IF EXISTS in QueryBuilder (JAVA-827) | |
| 341 | +- [improvement] Randomize contact points list to prevent hotspots (JAVA-618) | |
| 342 | +- [improvement] Surface the coordinator used on query failure (JAVA-720) | |
| 343 | +- [bug] Handle contact points removed during init (JAVA-792) | |
| 344 | +- [improvement] Allow PlainTextAuthProvider to change its credentials at runtime (JAVA-719) | |
| 345 | +- [new feature] Make it possible to register for SchemaChange Events (JAVA-151) | |
| 346 | +- [improvement] Downgrade "Asked to rebuild table" log from ERROR to INFO level (JAVA-861) | |
| 347 | +- [improvement] Provide an option to prepare statements only on one node (JAVA-797) | |
| 348 | +- [improvement] Provide an option to not re-prepare all statements in onUp (JAVA-658) | |
| 349 | +- [improvement] Customizable creation of netty timer (JAVA-853) | |
| 350 | +- [bug] Avoid quadratic ring processing with invalid replication factors (JAVA-859) | |
| 351 | +- [improvement] Debounce control connection queries (JAVA-657) | |
| 352 | +- [bug] LoadBalancingPolicy.distance() called before init() (JAVA-784) | |
| 353 | +- [new feature] Make driver-side metadata optional (JAVA-828) | |
| 354 | +- [improvement] Allow hosts to remain partially up (JAVA-544) | |
| 355 | +- [improvement] Remove internal blocking calls and expose async session | |
| 356 | + creation (JAVA-821, JAVA-822) | |
| 357 | +- [improvement] Use parallel calls when re-preparing statement on other | |
| 358 | + hosts (JAVA-725) | |
| 359 | +- [bug] Don't use connection timeout for unrelated internal queries (JAVA-629) | |
| 360 | +- [bug] Fix NPE in speculative executions when metrics disabled | |
| 361 | + (JAVA-892) | |
| 287 | 362 | |
| 288 | 363 | Merged from 2.0.10_fixes branch: |
| 289 | 364 |
modified clirr-ignores.xml +18 −0
| @@ -29,4 +29,22 @@ | ||
| 29 | 29 | <justification>False positive: HostConnectionPool is not exposed to clients</justification> |
| 30 | 30 | </difference> |
| 31 | 31 | |
| 32 | + <difference> | |
| 33 | + <differenceType>1001</differenceType> <!-- decreased visibility --> | |
| 34 | + <className>com/datastax/driver/core/ConvictionPolicy$Factory</className> | |
| 35 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 36 | + </difference> | |
| 37 | + | |
| 38 | + <difference> | |
| 39 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 40 | + <className>com/datastax/driver/core/ConvictionPolicy$Simple</className> | |
| 41 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 42 | + </difference> | |
| 43 | + | |
| 44 | + <difference> | |
| 45 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 46 | + <className>com/datastax/driver/core/ConvictionPolicy$Simple$Factory</className> | |
| 47 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 48 | + </difference> | |
| 49 | + | |
| 32 | 50 | </differences> |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractReconnectionHandler.java +7 −4
| @@ -40,6 +40,7 @@ | ||
| 40 | 40 | |
| 41 | 41 | private static final Logger logger = LoggerFactory.getLogger(AbstractReconnectionHandler.class); |
| 42 | 42 | |
| 43 | + private final String name; | |
| 43 | 44 | private final ScheduledExecutorService executor; |
| 44 | 45 | private final ReconnectionPolicy.ReconnectionSchedule schedule; |
| 45 | 46 | /** |
| @@ -53,11 +54,12 @@ | ||
| 53 | 54 | |
| 54 | 55 | private final CountDownLatch ready = new CountDownLatch(1); |
| 55 | 56 | |
| 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); | |
| 58 | 59 | } |
| 59 | 60 | |
| 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; | |
| 61 | 63 | this.executor = executor; |
| 62 | 64 | this.schedule = schedule; |
| 63 | 65 | this.currentAttempt = currentAttempt; |
| @@ -92,7 +94,7 @@ | ||
| 92 | 94 | break; |
| 93 | 95 | } |
| 94 | 96 | if (currentAttempt.compareAndSet(previous, handlerFuture)) { |
| 95 | - logger.debug("Becoming the active handler"); | |
| 97 | + Host.statesLogger.debug("[{}] starting reconnection attempt", name); | |
| 96 | 98 | break; |
| 97 | 99 | } |
| 98 | 100 | } |
| @@ -176,6 +178,7 @@ | ||
| 176 | 178 | return; |
| 177 | 179 | } |
| 178 | 180 | |
| 181 | + Host.statesLogger.debug("[{}] next reconnection attempt in {} ms", name, nextDelay); | |
| 179 | 182 | handlerFuture.nextTry = executor.schedule(this, nextDelay, TimeUnit.MILLISECONDS); |
| 180 | 183 | } |
| 181 | 184 |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +4 −4
| @@ -26,7 +26,7 @@ | ||
| 26 | 26 | * |
| 27 | 27 | * This is primarly intended to make mocking easier. |
| 28 | 28 | */ |
| 29 | -public abstract class AbstractSession implements Session { | |
| 29 | +public abstract class AbstractSession implements Session, AsyncInitSession { | |
| 30 | 30 | |
| 31 | 31 | /** |
| 32 | 32 | * {@inheritDoc} |
| @@ -76,7 +76,7 @@ | ||
| 76 | 76 | try { |
| 77 | 77 | return Uninterruptibles.getUninterruptibly(prepareAsync(query)); |
| 78 | 78 | } catch (ExecutionException e) { |
| 79 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 79 | + throw DriverThrowables.propagateCause(e); | |
| 80 | 80 | } |
| 81 | 81 | } |
| 82 | 82 | |
| @@ -88,7 +88,7 @@ | ||
| 88 | 88 | try { |
| 89 | 89 | return Uninterruptibles.getUninterruptibly(prepareAsync(statement)); |
| 90 | 90 | } catch (ExecutionException e) { |
| 91 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 91 | + throw DriverThrowables.propagateCause(e); | |
| 92 | 92 | } |
| 93 | 93 | } |
| 94 | 94 | |
| @@ -125,7 +125,7 @@ | ||
| 125 | 125 | try { |
| 126 | 126 | closeAsync().get(); |
| 127 | 127 | } catch (ExecutionException e) { |
| 128 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 128 | + throw DriverThrowables.propagateCause(e); | |
| 129 | 129 | } catch (InterruptedException e) { |
| 130 | 130 | Thread.currentThread().interrupt(); |
| 131 | 131 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −1
| @@ -282,7 +282,7 @@ | ||
| 282 | 282 | try { |
| 283 | 283 | Uninterruptibles.getUninterruptibly(fetchMoreResults()); |
| 284 | 284 | } catch (ExecutionException e) { |
| 285 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 285 | + throw DriverThrowables.propagateCause(e); | |
| 286 | 286 | } |
| 287 | 287 | } |
| 288 | 288 | } |
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 +516 −151
| @@ -26,8 +26,8 @@ | ||
| 26 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 27 | 27 | |
| 28 | 28 | import com.google.common.annotations.VisibleForTesting; |
| 29 | -import com.google.common.base.Objects; | |
| 30 | 29 | import com.google.common.base.Predicates; |
| 30 | +import com.google.common.base.Strings; | |
| 31 | 31 | import com.google.common.collect.*; |
| 32 | 32 | import com.google.common.util.concurrent.*; |
| 33 | 33 | import org.slf4j.Logger; |
| @@ -37,6 +37,7 @@ | ||
| 37 | 37 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 38 | 38 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 39 | 39 | import com.datastax.driver.core.policies.*; |
| 40 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 40 | 41 | |
| 41 | 42 | import static com.datastax.driver.core.SchemaElement.KEYSPACE; |
| 42 | 43 | |
| @@ -221,7 +222,7 @@ | ||
| 221 | 222 | */ |
| 222 | 223 | public Session newSession() { |
| 223 | 224 | checkNotClosed(manager); |
| 224 | - return manager.newSession(); | |
| 225 | + return manager.newSession(null); | |
| 225 | 226 | } |
| 226 | 227 | |
| 227 | 228 | /** |
| @@ -245,11 +246,11 @@ | ||
| 245 | 246 | * Cluster. |
| 246 | 247 | */ |
| 247 | 248 | public Session connect() { |
| 248 | - checkNotClosed(manager); | |
| 249 | - init(); | |
| 250 | - Session session = manager.newSession(); | |
| 251 | - session.init(); | |
| 252 | - return session; | |
| 249 | + try { | |
| 250 | + return Uninterruptibles.getUninterruptibly(connectAsync()); | |
| 251 | + } catch (ExecutionException e) { | |
| 252 | + throw DriverThrowables.propagateCause(e); | |
| 253 | + } | |
| 253 | 254 | } |
| 254 | 255 | |
| 255 | 256 | /** |
| @@ -278,25 +279,67 @@ | ||
| 278 | 279 | * Cluster. |
| 279 | 280 | */ |
| 280 | 281 | public Session connect(String keyspace) { |
| 281 | - long timeout = getConfiguration().getSocketOptions().getConnectTimeoutMillis(); | |
| 282 | - Session session = connect(); | |
| 283 | 282 | try { |
| 284 | - try { | |
| 285 | - ResultSetFuture future = session.executeAsync("USE " + keyspace); | |
| 286 | - // Note: using the connection timeout isn't perfectly correct, we should probably change that someday | |
| 287 | - Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); | |
| 288 | - return session; | |
| 289 | - } catch (TimeoutException e) { | |
| 290 | - 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)); | |
| 291 | - } catch (ExecutionException e) { | |
| 292 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 293 | - } | |
| 294 | - } catch (RuntimeException e) { | |
| 295 | - session.close(); | |
| 296 | - throw e; | |
| 283 | + return Uninterruptibles.getUninterruptibly(connectAsync(keyspace)); | |
| 284 | + } catch (ExecutionException e) { | |
| 285 | + throw DriverThrowables.propagateCause(e); | |
| 297 | 286 | } |
| 298 | 287 | } |
| 299 | 288 | |
| 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 | + | |
| 300 | 343 | /** |
| 301 | 344 | * The name of this cluster object. |
| 302 | 345 | * <p> |
| @@ -437,6 +480,38 @@ | ||
| 437 | 480 | return this; |
| 438 | 481 | } |
| 439 | 482 | |
| 483 | + /** | |
| 484 | + * Registers the provided listener to be updated with schema change events. | |
| 485 | + * <p> | |
| 486 | + * Registering the same listener multiple times is a no-op. | |
| 487 | + * | |
| 488 | + * @param listener the new {@link SchemaChangeListener} to register. | |
| 489 | + * @return this {@code Cluster} object; | |
| 490 | + */ | |
| 491 | + public Cluster register(SchemaChangeListener listener) { | |
| 492 | + checkNotClosed(manager); | |
| 493 | + listener.onRegister(this); | |
| 494 | + manager.schemaChangeListeners.add(listener); | |
| 495 | + return this; | |
| 496 | + } | |
| 497 | + | |
| 498 | + /** | |
| 499 | + * Unregisters the provided schema change listener from being updated | |
| 500 | + * with schema change events. | |
| 501 | + * <p> | |
| 502 | + * This method is a no-op if {@code listener} hadn't previously be | |
| 503 | + * registered against this Cluster. | |
| 504 | + * | |
| 505 | + * @param listener the {@link SchemaChangeListener} to unregister. | |
| 506 | + * @return this {@code Cluster} object; | |
| 507 | + */ | |
| 508 | + public Cluster unregister(SchemaChangeListener listener) { | |
| 509 | + checkNotClosed(manager); | |
| 510 | + listener.onUnregister(this); | |
| 511 | + manager.schemaChangeListeners.remove(listener); | |
| 512 | + return this; | |
| 513 | + } | |
| 514 | + | |
| 440 | 515 | /** |
| 441 | 516 | * Initiates a shutdown of this cluster instance. |
| 442 | 517 | * <p> |
| @@ -469,7 +544,7 @@ | ||
| 469 | 544 | try { |
| 470 | 545 | closeAsync().get(); |
| 471 | 546 | } catch (ExecutionException e) { |
| 472 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 547 | + throw DriverThrowables.propagateCause(e); | |
| 473 | 548 | } catch (InterruptedException e) { |
| 474 | 549 | Thread.currentThread().interrupt(); |
| 475 | 550 | } |
| @@ -1223,7 +1298,7 @@ | ||
| 1223 | 1298 | Connection.Factory connectionFactory; |
| 1224 | 1299 | ControlConnection controlConnection; |
| 1225 | 1300 | |
| 1226 | - final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.Simple.Factory(); | |
| 1301 | + final ConvictionPolicy.Factory convictionPolicyFactory = new ConvictionPolicy.DefaultConvictionPolicy.Factory(); | |
| 1227 | 1302 | |
| 1228 | 1303 | ScheduledThreadPoolExecutor reconnectionExecutor; |
| 1229 | 1304 | ScheduledThreadPoolExecutor scheduledTasksExecutor; |
| @@ -1252,6 +1327,11 @@ | ||
| 1252 | 1327 | |
| 1253 | 1328 | final Set<Host.StateListener> listeners; |
| 1254 | 1329 | final Set<LatencyTracker> trackers = new CopyOnWriteArraySet<LatencyTracker>(); |
| 1330 | + final Set<SchemaChangeListener> schemaChangeListeners = new CopyOnWriteArraySet<SchemaChangeListener>(); | |
| 1331 | + | |
| 1332 | + EventDebouncer<NodeListRefreshRequest> nodeListRefreshRequestDebouncer; | |
| 1333 | + EventDebouncer<NodeRefreshRequest> nodeRefreshRequestDebouncer; | |
| 1334 | + EventDebouncer<SchemaRefreshRequest> schemaRefreshRequestDebouncer; | |
| 1255 | 1335 | |
| 1256 | 1336 | private Manager(String clusterName, List<InetSocketAddress> contactPoints, Configuration configuration, Collection<Host.StateListener> listeners) { |
| 1257 | 1337 | this.clusterName = clusterName == null ? generateClusterName() : clusterName; |
| @@ -1288,8 +1368,28 @@ | ||
| 1288 | 1368 | this.metrics = configuration.getMetricsOptions() == null ? null : new Metrics(this); |
| 1289 | 1369 | this.preparedQueries = new MapMaker().weakValues().makeMap(); |
| 1290 | 1370 | |
| 1291 | - this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1371 | + // create debouncers - at this stage, they are not running yet | |
| 1372 | + QueryOptions queryOptions = configuration.getQueryOptions(); | |
| 1373 | + this.nodeListRefreshRequestDebouncer = new EventDebouncer<NodeListRefreshRequest>( | |
| 1374 | + "Node list refresh", | |
| 1375 | + scheduledTasksExecutor, | |
| 1376 | + new NodeListRefreshRequestDeliveryCallback(), | |
| 1377 | + queryOptions.getRefreshNodeListIntervalMillis(), | |
| 1378 | + queryOptions.getMaxPendingRefreshNodeListRequests()); | |
| 1379 | + this.nodeRefreshRequestDebouncer = new EventDebouncer<NodeRefreshRequest>( | |
| 1380 | + "Node refresh", | |
| 1381 | + scheduledTasksExecutor, | |
| 1382 | + new NodeRefreshRequestDeliveryCallback(), | |
| 1383 | + queryOptions.getRefreshNodeIntervalMillis(), | |
| 1384 | + queryOptions.getMaxPendingRefreshNodeRequests()); | |
| 1385 | + this.schemaRefreshRequestDebouncer = new EventDebouncer<SchemaRefreshRequest>( | |
| 1386 | + "Schema refresh", | |
| 1387 | + scheduledTasksExecutor, | |
| 1388 | + new SchemaRefreshRequestDeliveryCallback(), | |
| 1389 | + queryOptions.getRefreshSchemaIntervalMillis(), | |
| 1390 | + queryOptions.getMaxPendingRefreshSchemaRequests()); | |
| 1292 | 1391 | |
| 1392 | + this.scheduledTasksExecutor.scheduleWithFixedDelay(new CleanupIdleConnectionsTask(), 10, 10, TimeUnit.SECONDS); | |
| 1293 | 1393 | |
| 1294 | 1394 | for (InetSocketAddress address : contactPoints) { |
| 1295 | 1395 | // We don't want to signal -- call onAdd() -- because nothing is ready |
| @@ -1297,10 +1397,12 @@ | ||
| 1297 | 1397 | // create the Host object so we can initialize the control connection. |
| 1298 | 1398 | metadata.add(address); |
| 1299 | 1399 | } |
| 1300 | - | |
| 1400 | + | |
| 1401 | + Collection<Host> allHosts = metadata.allHosts(); | |
| 1402 | + | |
| 1301 | 1403 | // At this stage, metadata.allHosts() only contains the contact points, that's what we want to pass to LBP.init(). |
| 1302 | 1404 | // But the control connection will initialize first and discover more hosts, so make a copy. |
| 1303 | - Set<Host> contactPointHosts = Sets.newHashSet(metadata.allHosts()); | |
| 1405 | + Set<Host> contactPointHosts = Sets.newHashSet(allHosts); | |
| 1304 | 1406 | |
| 1305 | 1407 | try { |
| 1306 | 1408 | try { |
| @@ -1316,17 +1418,29 @@ | ||
| 1316 | 1418 | } |
| 1317 | 1419 | } |
| 1318 | 1420 | |
| 1319 | - // The control connection can mark hosts down if it failed to connect to them, separate them | |
| 1421 | + // The control connection can mark hosts down if it failed to connect to them, or remove them if they weren't found | |
| 1422 | + // in the control host's system.peers. Separate them: | |
| 1320 | 1423 | Set<Host> downContactPointHosts = Sets.newHashSet(); |
| 1321 | - for (Host host : contactPointHosts) | |
| 1322 | - if (host.state == Host.State.DOWN) | |
| 1424 | + Set<Host> removedContactPointHosts = Sets.newHashSet(); | |
| 1425 | + for (Host host : contactPointHosts) { | |
| 1426 | + if (!allHosts.contains(host)) | |
| 1427 | + removedContactPointHosts.add(host); | |
| 1428 | + else if (host.state == Host.State.DOWN) | |
| 1323 | 1429 | downContactPointHosts.add(host); |
| 1430 | + } | |
| 1431 | + contactPointHosts.removeAll(removedContactPointHosts); | |
| 1324 | 1432 | contactPointHosts.removeAll(downContactPointHosts); |
| 1325 | 1433 | |
| 1326 | 1434 | // Now that the control connection is ready, we have all the information we need about the nodes (datacenter, |
| 1327 | 1435 | // rack...) to initialize the load balancing policy |
| 1328 | 1436 | loadBalancingPolicy().init(Cluster.this, contactPointHosts); |
| 1329 | 1437 | speculativeRetryPolicy().init(Cluster.this); |
| 1438 | + | |
| 1439 | + for (Host host : removedContactPointHosts) { | |
| 1440 | + loadBalancingPolicy().onRemove(host); | |
| 1441 | + for (Host.StateListener listener : listeners) | |
| 1442 | + listener.onRemove(host); | |
| 1443 | + } | |
| 1330 | 1444 | for (Host host : downContactPointHosts) { |
| 1331 | 1445 | loadBalancingPolicy().onDown(host); |
| 1332 | 1446 | for (Host.StateListener listener : listeners) |
| @@ -1335,7 +1449,7 @@ | ||
| 1335 | 1449 | |
| 1336 | 1450 | configuration.getPoolingOptions().setProtocolVersion(protocolVersion()); |
| 1337 | 1451 | |
| 1338 | - for (Host host : metadata.allHosts()) { | |
| 1452 | + for (Host host : allHosts) { | |
| 1339 | 1453 | // If the host is down at this stage, it's a contact point that the control connection failed to reach. |
| 1340 | 1454 | // Reconnection attempts are already scheduled, and the LBP and listeners have been notified above. |
| 1341 | 1455 | if (host.state == Host.State.DOWN) continue; |
| @@ -1358,6 +1472,12 @@ | ||
| 1358 | 1472 | for (Host.StateListener listener : listeners) |
| 1359 | 1473 | listener.onAdd(host); |
| 1360 | 1474 | } |
| 1475 | + | |
| 1476 | + // start debouncers | |
| 1477 | + this.nodeListRefreshRequestDebouncer.start(); | |
| 1478 | + this.schemaRefreshRequestDebouncer.start(); | |
| 1479 | + this.nodeRefreshRequestDebouncer.start(); | |
| 1480 | + | |
| 1361 | 1481 | isFullyInit = true; |
| 1362 | 1482 | } catch (NoHostAvailableException e) { |
| 1363 | 1483 | close(); |
| @@ -1407,8 +1527,8 @@ | ||
| 1407 | 1527 | return translated == null ? sa : translated; |
| 1408 | 1528 | } |
| 1409 | 1529 | |
| 1410 | - private Session newSession() { | |
| 1411 | - SessionManager session = new SessionManager(Cluster.this); | |
| 1530 | + private AsyncInitSession newSession(String keyspace) { | |
| 1531 | + SessionManager session = new SessionManager(Cluster.this, keyspace); | |
| 1412 | 1532 | sessions.add(session); |
| 1413 | 1533 | return session; |
| 1414 | 1534 | } |
| @@ -1436,6 +1556,11 @@ | ||
| 1436 | 1556 | if (isInit) { |
| 1437 | 1557 | logger.debug("Shutting down"); |
| 1438 | 1558 | |
| 1559 | + // stop debouncers | |
| 1560 | + nodeListRefreshRequestDebouncer.stop(); | |
| 1561 | + nodeRefreshRequestDebouncer.stop(); | |
| 1562 | + schemaRefreshRequestDebouncer.stop(); | |
| 1563 | + | |
| 1439 | 1564 | // If we're shutting down, there is no point in waiting on scheduled reconnections, nor on notifications |
| 1440 | 1565 | // delivery or blocking tasks so we use shutdownNow |
| 1441 | 1566 | shutdownNow(reconnectionExecutor); |
| @@ -1460,6 +1585,10 @@ | ||
| 1460 | 1585 | if (translater instanceof CloseableAddressTranslater) |
| 1461 | 1586 | ((CloseableAddressTranslater)translater).close(); |
| 1462 | 1587 | |
| 1588 | + for (SchemaChangeListener listener : schemaChangeListeners) { | |
| 1589 | + listener.onUnregister(Cluster.this); | |
| 1590 | + } | |
| 1591 | + | |
| 1463 | 1592 | // Then we shutdown all connections |
| 1464 | 1593 | List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1); |
| 1465 | 1594 | futures.add(controlConnection.closeAsync()); |
| @@ -1509,8 +1638,6 @@ | ||
| 1509 | 1638 | |
| 1510 | 1639 | // Use triggerOnUp unless you're sure you want to run this on the current thread. |
| 1511 | 1640 | private void onUp(final Host host, Connection reusedConnection) throws InterruptedException, ExecutionException { |
| 1512 | - logger.debug("Host {} is UP", host); | |
| 1513 | - | |
| 1514 | 1641 | if (isClosed()) |
| 1515 | 1642 | return; |
| 1516 | 1643 | |
| @@ -1532,6 +1659,8 @@ | ||
| 1532 | 1659 | if (host.state == Host.State.UP) |
| 1533 | 1660 | return; |
| 1534 | 1661 | |
| 1662 | + Host.statesLogger.debug("[{}] marking host UP", host); | |
| 1663 | + | |
| 1535 | 1664 | // If there is a reconnection attempt scheduled for that node, cancel it |
| 1536 | 1665 | Future<?> scheduledAttempt = host.reconnectionAttempt.getAndSet(null); |
| 1537 | 1666 | if (scheduledAttempt != null) { |
| @@ -1540,7 +1669,8 @@ | ||
| 1540 | 1669 | } |
| 1541 | 1670 | |
| 1542 | 1671 | try { |
| 1543 | - reusedConnection = prepareAllQueries(host, reusedConnection); | |
| 1672 | + if (getCluster().getConfiguration().getQueryOptions().isReprepareOnUp()) | |
| 1673 | + reusedConnection = prepareAllQueries(host, reusedConnection); | |
| 1544 | 1674 | } catch (InterruptedException e) { |
| 1545 | 1675 | Thread.currentThread().interrupt(); |
| 1546 | 1676 | // Don't propagate because we don't want to prevent other listener to run |
| @@ -1596,14 +1726,14 @@ | ||
| 1596 | 1726 | // Now, check if there isn't pools to create/remove following the addition. |
| 1597 | 1727 | // We do that now only so that it's not called before we've set the node up. |
| 1598 | 1728 | for (SessionManager s : sessions) |
| 1599 | - s.updateCreatedPools(); | |
| 1729 | + s.updateCreatedPools().get(); | |
| 1600 | 1730 | |
| 1601 | 1731 | } finally { |
| 1602 | 1732 | host.notificationsLock.unlock(); |
| 1603 | 1733 | } |
| 1604 | 1734 | |
| 1605 | 1735 | } finally { |
| 1606 | - if (reusedConnection != null && !reusedConnection.hasPool()) | |
| 1736 | + if (reusedConnection != null && !reusedConnection.hasOwner()) | |
| 1607 | 1737 | reusedConnection.closeAsync(); |
| 1608 | 1738 | } |
| 1609 | 1739 | } |
| @@ -1623,8 +1753,6 @@ | ||
| 1623 | 1753 | |
| 1624 | 1754 | // Use triggerOnDown unless you're sure you want to run this on the current thread. |
| 1625 | 1755 | private void onDown(final Host host, final boolean isHostAddition, boolean startReconnection) throws InterruptedException, ExecutionException { |
| 1626 | - logger.debug("Host {} is DOWN", host); | |
| 1627 | - | |
| 1628 | 1756 | if (isClosed()) |
| 1629 | 1757 | return; |
| 1630 | 1758 | |
| @@ -1645,6 +1773,8 @@ | ||
| 1645 | 1773 | return; |
| 1646 | 1774 | } |
| 1647 | 1775 | |
| 1776 | + Host.statesLogger.debug("[{}] marking host DOWN", host); | |
| 1777 | + | |
| 1648 | 1778 | // Remember if we care about this node at all. We must call this before |
| 1649 | 1779 | // we've signalled the load balancing policy, since most policy will always |
| 1650 | 1780 | // IGNORE down nodes anyway. |
| @@ -1670,7 +1800,6 @@ | ||
| 1670 | 1800 | if (distance == HostDistance.IGNORED || !startReconnection) |
| 1671 | 1801 | return; |
| 1672 | 1802 | |
| 1673 | - logger.debug("{} is down, scheduling connection retries", host); | |
| 1674 | 1803 | startPeriodicReconnectionAttempt(host, isHostAddition); |
| 1675 | 1804 | } finally { |
| 1676 | 1805 | host.notificationsLock.unlock(); |
| @@ -1678,7 +1807,7 @@ | ||
| 1678 | 1807 | } |
| 1679 | 1808 | |
| 1680 | 1809 | void startPeriodicReconnectionAttempt(final Host host, final boolean isHostAddition) { |
| 1681 | - new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) { | |
| 1810 | + new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt) { | |
| 1682 | 1811 | |
| 1683 | 1812 | protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 1684 | 1813 | return connectionFactory.open(host); |
| @@ -1731,7 +1860,7 @@ | ||
| 1731 | 1860 | logger.debug("Scheduling one-time reconnection to {}", host); |
| 1732 | 1861 | |
| 1733 | 1862 | // Setting an initial delay of 0 to start immediately, and all the exception handlers return false to prevent further attempts |
| 1734 | - new AbstractReconnectionHandler(reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) { | |
| 1863 | + new AbstractReconnectionHandler(host.toString(), reconnectionExecutor, reconnectionPolicy().newSchedule(), host.reconnectionAttempt, 0) { | |
| 1735 | 1864 | |
| 1736 | 1865 | protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 1737 | 1866 | return connectionFactory.open(host); |
| @@ -1787,8 +1916,6 @@ | ||
| 1787 | 1916 | if (isClosed()) |
| 1788 | 1917 | return; |
| 1789 | 1918 | |
| 1790 | - logger.info("New Cassandra host {} added", host); | |
| 1791 | - | |
| 1792 | 1919 | if (!connectionFactory.protocolVersion.isSupportedBy(host)) { |
| 1793 | 1920 | logUnsupportedVersionProtocol(host, connectionFactory.protocolVersion); |
| 1794 | 1921 | return; |
| @@ -1802,6 +1929,7 @@ | ||
| 1802 | 1929 | return; |
| 1803 | 1930 | } |
| 1804 | 1931 | try { |
| 1932 | + Host.statesLogger.debug("[{}] adding host", host); | |
| 1805 | 1933 | |
| 1806 | 1934 | // Adds to the load balancing first and foremost, as doing so might change the decision |
| 1807 | 1935 | // it will make for distance() on that node (not likely but we leave that possibility). |
| @@ -1837,7 +1965,7 @@ | ||
| 1837 | 1965 | |
| 1838 | 1966 | List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(sessions.size()); |
| 1839 | 1967 | for (SessionManager s : sessions) |
| 1840 | - futures.add(s.maybeAddPool(host, reusedConnection)); | |
| 1968 | + futures.add(s.maybeAddPool(host, reusedConnection, false)); | |
| 1841 | 1969 | |
| 1842 | 1970 | try { |
| 1843 | 1971 | // Only mark the node up once all session have added their pool (if the load-balancing |
| @@ -1867,14 +1995,14 @@ | ||
| 1867 | 1995 | // Now, check if there isn't pools to create/remove following the addition. |
| 1868 | 1996 | // We do that now only so that it's not called before we've set the node up. |
| 1869 | 1997 | for (SessionManager s : sessions) |
| 1870 | - s.updateCreatedPools(); | |
| 1998 | + s.updateCreatedPools().get(); | |
| 1871 | 1999 | |
| 1872 | 2000 | } finally { |
| 1873 | 2001 | host.notificationsLock.unlock(); |
| 1874 | 2002 | } |
| 1875 | 2003 | |
| 1876 | 2004 | } finally { |
| 1877 | - if (reusedConnection != null && !reusedConnection.hasPool()) | |
| 2005 | + if (reusedConnection != null && !reusedConnection.hasOwner()) | |
| 1878 | 2006 | reusedConnection.closeAsync(); |
| 1879 | 2007 | } |
| 1880 | 2008 | } |
| @@ -1902,7 +2030,8 @@ | ||
| 1902 | 2030 | |
| 1903 | 2031 | host.setDown(); |
| 1904 | 2032 | |
| 1905 | - logger.debug("Removing host {}", host); | |
| 2033 | + Host.statesLogger.debug("[{}] removing host", host); | |
| 2034 | + | |
| 1906 | 2035 | loadBalancingPolicy().onRemove(host); |
| 1907 | 2036 | controlConnection.onRemove(host); |
| 1908 | 2037 | for (SessionManager s : sessions) |
| @@ -1915,13 +2044,14 @@ | ||
| 1915 | 2044 | } |
| 1916 | 2045 | } |
| 1917 | 2046 | |
| 1918 | - public boolean signalConnectionFailure(Host host, ConnectionException exception, boolean isHostAddition) { | |
| 2047 | + public boolean signalConnectionFailure(Host host, ConnectionException exception, | |
| 2048 | + boolean connectionInitialized, boolean isHostAddition) { | |
| 1919 | 2049 | // Don't signal failure until we've fully initialized the controlConnection as this might mess up with |
| 1920 | 2050 | // the protocol detection |
| 1921 | 2051 | if (!isFullyInit || isClosed()) |
| 1922 | 2052 | return true; |
| 1923 | 2053 | |
| 1924 | - boolean isDown = host.signalConnectionFailure(exception); | |
| 2054 | + boolean isDown = host.convictionPolicy.signalConnectionFailure(exception, connectionInitialized); | |
| 1925 | 2055 | if (isDown) |
| 1926 | 2056 | triggerOnDown(host, isHostAddition, true); |
| 1927 | 2057 | return isDown; |
| @@ -1933,7 +2063,7 @@ | ||
| 1933 | 2063 | |
| 1934 | 2064 | if (metadata.remove(host)) { |
| 1935 | 2065 | if (isInitialConnection) { |
| 1936 | - logger.warn("You listed {} in your contact points, but it could not be reached at startup", host); | |
| 2066 | + logger.warn("You listed {} in your contact points, but it wasn't found in the control host's system.peers at startup", host); | |
| 1937 | 2067 | } else { |
| 1938 | 2068 | logger.info("Cassandra host {} removed", host); |
| 1939 | 2069 | triggerOnRemove(host); |
| @@ -1982,7 +2112,7 @@ | ||
| 1982 | 2112 | : reusedConnection; |
| 1983 | 2113 | |
| 1984 | 2114 | try { |
| 1985 | - ControlConnection.waitForSchemaAgreement(connection, this); | |
| 2115 | + controlConnection.waitForSchemaAgreement(); | |
| 1986 | 2116 | } catch (ExecutionException e) { |
| 1987 | 2117 | // As below, just move on |
| 1988 | 2118 | } |
| @@ -2046,14 +2176,21 @@ | ||
| 2046 | 2176 | } |
| 2047 | 2177 | } |
| 2048 | 2178 | |
| 2049 | - public void submitSchemaRefresh(final SchemaElement targetType, final String targetKeyspace, final String targetName) { | |
| 2050 | - logger.trace("Submitting schema refresh"); | |
| 2051 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2052 | - @Override | |
| 2053 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2054 | - controlConnection.refreshSchema(targetType, targetKeyspace, targetName); | |
| 2055 | - } | |
| 2056 | - }); | |
| 2179 | + ListenableFuture<Void> submitSchemaRefresh(final SchemaElement targetType, final String targetKeyspace, final String targetName) { | |
| 2180 | + SchemaRefreshRequest request = new SchemaRefreshRequest(targetType, targetKeyspace, targetName); | |
| 2181 | + logger.trace("Submitting schema refresh: {}", request); | |
| 2182 | + return schemaRefreshRequestDebouncer.eventReceived(request); | |
| 2183 | + } | |
| 2184 | + | |
| 2185 | + void submitNodeListRefresh() { | |
| 2186 | + logger.trace("Submitting node list and token map refresh"); | |
| 2187 | + nodeListRefreshRequestDebouncer.eventReceived(new NodeListRefreshRequest()); | |
| 2188 | + } | |
| 2189 | + | |
| 2190 | + void submitNodeRefresh(InetSocketAddress address, HostEvent eventType) { | |
| 2191 | + NodeRefreshRequest request = new NodeRefreshRequest(address, eventType); | |
| 2192 | + logger.trace("Submitting node refresh: {}", request); | |
| 2193 | + nodeRefreshRequestDebouncer.eventReceived(request); | |
| 2057 | 2194 | } |
| 2058 | 2195 | |
| 2059 | 2196 | // refresh the schema using the provided connection, and notice the future with the provided resultset once done |
| @@ -2080,20 +2217,23 @@ | ||
| 2080 | 2217 | try { |
| 2081 | 2218 | // Before refreshing the schema, wait for schema agreement so |
| 2082 | 2219 | // that querying a table just after having created it don't fail. |
| 2083 | - schemaInAgreement = ControlConnection.waitForSchemaAgreement(connection, Manager.this); | |
| 2220 | + schemaInAgreement = controlConnection.waitForSchemaAgreement(); | |
| 2084 | 2221 | if (!schemaInAgreement) |
| 2085 | 2222 | logger.warn("No schema agreement from live replicas after {} s. The schema may not be up to date on some nodes.", configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds()); |
| 2086 | - if (refreshSchema) | |
| 2087 | - ControlConnection.refreshSchema(connection, targetType, targetKeyspace, targetName, Manager.this, false); | |
| 2223 | + | |
| 2224 | + ListenableFuture<Void> schemaReady = refreshSchema ? submitSchemaRefresh(targetType, targetKeyspace, targetName) : MoreFutures.VOID_SUCCESS; | |
| 2225 | + final boolean finalSchemaInAgreement = schemaInAgreement; | |
| 2226 | + schemaReady.addListener(new Runnable() { | |
| 2227 | + @Override | |
| 2228 | + public void run() { | |
| 2229 | + rs.getExecutionInfo().setSchemaInAgreement(finalSchemaInAgreement); | |
| 2230 | + future.setResult(rs); | |
| 2231 | + } | |
| 2232 | + }, MoreExecutors.sameThreadExecutor()); | |
| 2233 | + | |
| 2088 | 2234 | } catch (Exception e) { |
| 2089 | - if (refreshSchema) { | |
| 2090 | - logger.error("Error during schema refresh ({}). The schema from Cluster.getMetadata() might appear stale. Asynchronously submitting job to fix.", e.getMessage()); | |
| 2091 | - submitSchemaRefresh(targetType, targetKeyspace, targetName); | |
| 2092 | - } else { | |
| 2093 | - logger.warn("Error while waiting for schema agreement", e); | |
| 2094 | - } | |
| 2095 | - } finally { | |
| 2096 | - // Always sets the result, but remember if we reached schema agreement | |
| 2235 | + logger.warn("Error while waiting for schema agreement", e); | |
| 2236 | + // This is not fatal, complete the future anyway | |
| 2097 | 2237 | rs.getExecutionInfo().setSchemaInAgreement(schemaInAgreement); |
| 2098 | 2238 | future.setResult(rs); |
| 2099 | 2239 | } |
| @@ -2119,95 +2259,36 @@ | ||
| 2119 | 2259 | case TOPOLOGY_CHANGE: |
| 2120 | 2260 | ProtocolEvent.TopologyChange tpc = (ProtocolEvent.TopologyChange)event; |
| 2121 | 2261 | InetSocketAddress tpAddr = translateAddress(tpc.node.getAddress()); |
| 2262 | + Host.statesLogger.debug("[{}] received event {}", tpAddr, tpc.change); | |
| 2122 | 2263 | switch (tpc.change) { |
| 2123 | 2264 | case NEW_NODE: |
| 2124 | - final Host newHost = metadata.add(tpAddr); | |
| 2125 | - if (newHost != null) { | |
| 2126 | - // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once | |
| 2127 | - // gossip is up, but that is before the client-side server is up), so we add a delay | |
| 2128 | - // (otherwise the connection will likely fail and have to be retry which is wasteful). This | |
| 2129 | - // probably should be fixed C* side, after which we'll be able to remove this. | |
| 2130 | - scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2131 | - @Override | |
| 2132 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2133 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2134 | - // catch that an upgraded node uses a new cassandra version). | |
| 2135 | - if (controlConnection.refreshNodeInfo(newHost)) { | |
| 2136 | - onAdd(newHost, null); | |
| 2137 | - } else { | |
| 2138 | - logger.debug("Not enough info for {}, ignoring host", newHost); | |
| 2139 | - } | |
| 2140 | - } | |
| 2141 | - }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2142 | - } | |
| 2265 | + submitNodeRefresh(tpAddr, HostEvent.ADDED); | |
| 2143 | 2266 | break; |
| 2144 | 2267 | case REMOVED_NODE: |
| 2145 | - removeHost(metadata.getHost(tpAddr), false); | |
| 2268 | + submitNodeRefresh(tpAddr, HostEvent.REMOVED); | |
| 2146 | 2269 | break; |
| 2147 | 2270 | case MOVED_NODE: |
| 2148 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2149 | - @Override | |
| 2150 | - public void runMayThrow() { | |
| 2151 | - controlConnection.refreshNodeListAndTokenMap(); | |
| 2152 | - } | |
| 2153 | - }); | |
| 2271 | + submitNodeListRefresh(); | |
| 2154 | 2272 | break; |
| 2155 | 2273 | } |
| 2156 | 2274 | break; |
| 2157 | 2275 | case STATUS_CHANGE: |
| 2158 | 2276 | ProtocolEvent.StatusChange stc = (ProtocolEvent.StatusChange)event; |
| 2159 | 2277 | InetSocketAddress stAddr = translateAddress(stc.node.getAddress()); |
| 2278 | + Host.statesLogger.debug("[{}] received event {}", stAddr, stc.status); | |
| 2160 | 2279 | switch (stc.status) { |
| 2161 | 2280 | case UP: |
| 2162 | - final Host hostUp = metadata.getHost(stAddr); | |
| 2163 | - if (hostUp == null) { | |
| 2164 | - final Host h = metadata.add(stAddr); | |
| 2165 | - // If hostUp is still null, it means we didn't knew about it the line before but | |
| 2166 | - // got beaten at adding it to the metadata by another thread. In that case, it's | |
| 2167 | - // fine to let the other thread win and ignore the notification here | |
| 2168 | - if (h == null) | |
| 2169 | - return; | |
| 2170 | - | |
| 2171 | - // See NEW_NODE above | |
| 2172 | - scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2173 | - @Override | |
| 2174 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2175 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2176 | - // catch that an upgraded node uses a new cassandra version). | |
| 2177 | - if (controlConnection.refreshNodeInfo(h)) { | |
| 2178 | - onAdd(h, null); | |
| 2179 | - } else { | |
| 2180 | - logger.debug("Not enough info for {}, ignoring host", h); | |
| 2181 | - } | |
| 2182 | - } | |
| 2183 | - }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2184 | - } else { | |
| 2185 | - executor.submit(new ExceptionCatchingRunnable() { | |
| 2186 | - @Override | |
| 2187 | - public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2188 | - // Make sure we have up-to-date infos on that host before adding it (so we typically | |
| 2189 | - // catch that an upgraded node uses a new cassandra version). | |
| 2190 | - if (controlConnection.refreshNodeInfo(hostUp)) { | |
| 2191 | - onUp(hostUp, null); | |
| 2192 | - } else { | |
| 2193 | - logger.debug("Not enough info for {}, ignoring host", hostUp); | |
| 2194 | - } | |
| 2195 | - } | |
| 2196 | - }); | |
| 2197 | - } | |
| 2281 | + submitNodeRefresh(stAddr, HostEvent.UP); | |
| 2198 | 2282 | break; |
| 2199 | 2283 | case DOWN: |
| 2200 | - // Note that there is a slight risk we can receive the event late and thus | |
| 2201 | - // mark the host down even though we already had reconnected successfully. | |
| 2202 | - // But it is unlikely, and don't have too much consequence since we'll try reconnecting | |
| 2203 | - // right away, so we favor the detection to make the Host.isUp method more reliable. | |
| 2204 | - Host hostDown = metadata.getHost(stAddr); | |
| 2205 | - if (hostDown != null) | |
| 2206 | - triggerOnDown(hostDown, true); | |
| 2284 | + submitNodeRefresh(stAddr, HostEvent.DOWN); | |
| 2207 | 2285 | break; |
| 2208 | 2286 | } |
| 2209 | 2287 | break; |
| 2210 | 2288 | case SCHEMA_CHANGE: |
| 2289 | + if (!configuration.getQueryOptions().isMetadataEnabled()) | |
| 2290 | + return; | |
| 2291 | + | |
| 2211 | 2292 | ProtocolEvent.SchemaChange scc = (ProtocolEvent.SchemaChange)event; |
| 2212 | 2293 | switch (scc.change) { |
| 2213 | 2294 | case CREATED: |
| @@ -2215,26 +2296,52 @@ | ||
| 2215 | 2296 | submitSchemaRefresh(scc.targetType, scc.targetKeyspace, scc.targetName); |
| 2216 | 2297 | break; |
| 2217 | 2298 | case DROPPED: |
| 2218 | - KeyspaceMetadata keyspace; | |
| 2299 | + final KeyspaceMetadata keyspace; | |
| 2219 | 2300 | switch (scc.targetType) { |
| 2220 | 2301 | case KEYSPACE: |
| 2221 | - manager.metadata.removeKeyspace(scc.targetKeyspace); | |
| 2302 | + final KeyspaceMetadata removedKeyspace = manager.metadata.removeKeyspace(scc.targetKeyspace); | |
| 2303 | + if(removedKeyspace != null) { | |
| 2304 | + executor.submit(new Runnable() { | |
| 2305 | + @Override | |
| 2306 | + public void run() { | |
| 2307 | + manager.metadata.triggerOnKeyspaceRemoved(removedKeyspace); | |
| 2308 | + } | |
| 2309 | + }); | |
| 2310 | + } | |
| 2222 | 2311 | break; |
| 2223 | 2312 | case TABLE: |
| 2224 | 2313 | keyspace = manager.metadata.getKeyspaceInternal(scc.targetKeyspace); |
| 2225 | 2314 | if (keyspace == null) |
| 2226 | 2315 | logger.warn("Received a DROPPED notification for table {}.{}, but this keyspace is unknown in our metadata", |
| 2227 | 2316 | scc.targetKeyspace, scc.targetName); |
| 2228 | - else | |
| 2229 | - keyspace.removeTable(scc.targetName); | |
| 2317 | + else { | |
| 2318 | + final TableMetadata removedTable = keyspace.removeTable(scc.targetName); | |
| 2319 | + if (removedTable != null) { | |
| 2320 | + executor.submit(new Runnable() { | |
| 2321 | + @Override | |
| 2322 | + public void run() { | |
| 2323 | + manager.metadata.triggerOnTableRemoved(removedTable); | |
| 2324 | + } | |
| 2325 | + }); | |
| 2326 | + } | |
| 2327 | + } | |
| 2230 | 2328 | break; |
| 2231 | 2329 | case TYPE: |
| 2232 | 2330 | keyspace = manager.metadata.getKeyspaceInternal(scc.targetKeyspace); |
| 2233 | 2331 | if (keyspace == null) |
| 2234 | 2332 | logger.warn("Received a DROPPED notification for UDT {}.{}, but this keyspace is unknown in our metadata", |
| 2235 | 2333 | scc.targetKeyspace, scc.targetName); |
| 2236 | - else | |
| 2237 | - keyspace.removeUserType(scc.targetName); | |
| 2334 | + else { | |
| 2335 | + final UserType removedType = keyspace.removeUserType(scc.targetName); | |
| 2336 | + if (removedType != null) { | |
| 2337 | + executor.submit(new Runnable() { | |
| 2338 | + @Override | |
| 2339 | + public void run() { | |
| 2340 | + manager.metadata.triggerOnUserTypeRemoved(removedType); | |
| 2341 | + } | |
| 2342 | + }); | |
| 2343 | + } | |
| 2344 | + } | |
| 2238 | 2345 | break; |
| 2239 | 2346 | } |
| 2240 | 2347 | break; |
| @@ -2248,17 +2355,21 @@ | ||
| 2248 | 2355 | // reconnecting (thus letting the loadBalancingPolicy pick a better node) |
| 2249 | 2356 | Host ccHost = controlConnection.connectedHost(); |
| 2250 | 2357 | if (ccHost == null || loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL) |
| 2251 | - controlConnection.reconnect(); | |
| 2358 | + controlConnection.triggerReconnect(); | |
| 2252 | 2359 | |
| 2253 | - for (SessionManager s : sessions) | |
| 2254 | - s.updateCreatedPools(); | |
| 2360 | + try { | |
| 2361 | + for (SessionManager s : sessions) | |
| 2362 | + Uninterruptibles.getUninterruptibly(s.updateCreatedPools()); | |
| 2363 | + } catch (ExecutionException e) { | |
| 2364 | + throw DriverThrowables.propagateCause(e); | |
| 2365 | + } | |
| 2255 | 2366 | } |
| 2256 | 2367 | |
| 2257 | 2368 | void refreshConnectedHost(Host host) { |
| 2258 | 2369 | // Deal with the control connection if it was using this host |
| 2259 | 2370 | Host ccHost = controlConnection.connectedHost(); |
| 2260 | 2371 | if (ccHost == null || ccHost.equals(host) && loadBalancingPolicy().distance(ccHost) != HostDistance.LOCAL) |
| 2261 | - controlConnection.reconnect(); | |
| 2372 | + controlConnection.triggerReconnect(); | |
| 2262 | 2373 | |
| 2263 | 2374 | for (SessionManager s : sessions) |
| 2264 | 2375 | s.updateCreatedPools(host); |
| @@ -2326,6 +2437,260 @@ | ||
| 2326 | 2437 | } |
| 2327 | 2438 | } |
| 2328 | 2439 | } |
| 2440 | + | |
| 2441 | + private class SchemaRefreshRequest { | |
| 2442 | + | |
| 2443 | + private final SchemaElement targetType; | |
| 2444 | + private final String targetKeyspace; | |
| 2445 | + private final String targetName; | |
| 2446 | + | |
| 2447 | + public SchemaRefreshRequest(SchemaElement targetType, String targetKeyspace, String targetName) { | |
| 2448 | + this.targetType = targetType; | |
| 2449 | + this.targetKeyspace = Strings.emptyToNull(targetKeyspace); | |
| 2450 | + this.targetName = Strings.emptyToNull(targetName); | |
| 2451 | + } | |
| 2452 | + | |
| 2453 | + /** | |
| 2454 | + * Coalesce schema refresh requests. | |
| 2455 | + * The algorithm is simple: if more than 2 keyspaces | |
| 2456 | + * need refresh, then refresh the entire schema; | |
| 2457 | + * otherwise if more than 2 elements in the same keyspace | |
| 2458 | + * need refresh, then refresh the entire keyspace. | |
| 2459 | + * | |
| 2460 | + * @param that the other request to merge with the current one. | |
| 2461 | + * @return A coalesced request | |
| 2462 | + */ | |
| 2463 | + SchemaRefreshRequest coalesce(SchemaRefreshRequest that) { | |
| 2464 | + if (this.targetType == null || that.targetType == null) | |
| 2465 | + return new SchemaRefreshRequest(null, null, null); | |
| 2466 | + if (!this.targetKeyspace.equals(that.targetKeyspace)) | |
| 2467 | + return new SchemaRefreshRequest(null, null, null); | |
| 2468 | + if (this.targetName == null || that.targetName == null) | |
| 2469 | + return new SchemaRefreshRequest(KEYSPACE, targetKeyspace, null); | |
| 2470 | + if (!this.targetName.equals(that.targetName)) | |
| 2471 | + return new SchemaRefreshRequest(KEYSPACE, targetKeyspace, null); | |
| 2472 | + return this; | |
| 2473 | + } | |
| 2474 | + | |
| 2475 | + @Override | |
| 2476 | + public String toString() { | |
| 2477 | + if (this.targetType == null) | |
| 2478 | + return "Refresh ALL"; | |
| 2479 | + if (this.targetName == null) | |
| 2480 | + return "Refresh keyspace " + targetKeyspace; | |
| 2481 | + return String.format("Refresh %s %s.%s", targetType, targetKeyspace, targetName); | |
| 2482 | + } | |
| 2483 | + } | |
| 2484 | + | |
| 2485 | + private class SchemaRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<SchemaRefreshRequest> { | |
| 2486 | + | |
| 2487 | + @Override | |
| 2488 | + public ListenableFuture<?> deliver(final List<SchemaRefreshRequest> events) { | |
| 2489 | + return executor.submit(new ExceptionCatchingRunnable() { | |
| 2490 | + @Override | |
| 2491 | + public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2492 | + SchemaRefreshRequest coalesced = null; | |
| 2493 | + for (SchemaRefreshRequest request : events) { | |
| 2494 | + coalesced = coalesced == null ? request : coalesced.coalesce(request); | |
| 2495 | + } | |
| 2496 | + assert coalesced != null; | |
| 2497 | + logger.trace("Coalesced schema refresh request: {}", coalesced); | |
| 2498 | + controlConnection.refreshSchema(coalesced.targetType, coalesced.targetKeyspace, coalesced.targetName); | |
| 2499 | + } | |
| 2500 | + }); | |
| 2501 | + } | |
| 2502 | + | |
| 2503 | + } | |
| 2504 | + | |
| 2505 | + private class NodeRefreshRequest { | |
| 2506 | + | |
| 2507 | + private final InetSocketAddress address; | |
| 2508 | + | |
| 2509 | + private final HostEvent eventType; | |
| 2510 | + | |
| 2511 | + private NodeRefreshRequest(InetSocketAddress address, HostEvent eventType) { | |
| 2512 | + this.address = address; | |
| 2513 | + this.eventType = eventType; | |
| 2514 | + } | |
| 2515 | + | |
| 2516 | + @Override | |
| 2517 | + public String toString() { | |
| 2518 | + return address + " " + eventType; | |
| 2519 | + } | |
| 2520 | + | |
| 2521 | + } | |
| 2522 | + | |
| 2523 | + private class NodeRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeRefreshRequest> { | |
| 2524 | + | |
| 2525 | + @Override | |
| 2526 | + public ListenableFuture<?> deliver(List<NodeRefreshRequest> events) { | |
| 2527 | + Map<InetSocketAddress, HostEvent> hosts = new HashMap<InetSocketAddress, HostEvent>(); | |
| 2528 | + // only keep the last event for each host | |
| 2529 | + for (NodeRefreshRequest req : events) { | |
| 2530 | + hosts.put(req.address, req.eventType); | |
| 2531 | + } | |
| 2532 | + List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(hosts.size()); | |
| 2533 | + for (final Entry<InetSocketAddress, HostEvent> entry : hosts.entrySet()) { | |
| 2534 | + InetSocketAddress address = entry.getKey(); | |
| 2535 | + HostEvent eventType = entry.getValue(); | |
| 2536 | + switch (eventType) { | |
| 2537 | + case UP: | |
| 2538 | + Host upHost = metadata.getHost(address); | |
| 2539 | + if (upHost == null) { | |
| 2540 | + upHost = metadata.add(address); | |
| 2541 | + // If upHost is still null, it means we didn't know about it the line before but | |
| 2542 | + // got beaten at adding it to the metadata by another thread. In that case, it's | |
| 2543 | + // fine to let the other thread win and ignore the notification here | |
| 2544 | + if (upHost == null) | |
| 2545 | + continue; | |
| 2546 | + futures.add(schedule(hostAdded(upHost))); | |
| 2547 | + } else { | |
| 2548 | + futures.add(schedule(hostUp(upHost))); | |
| 2549 | + } | |
| 2550 | + break; | |
| 2551 | + case ADDED: | |
| 2552 | + Host newHost = metadata.add(address); | |
| 2553 | + if (newHost != null) { | |
| 2554 | + futures.add(schedule(hostAdded(newHost))); | |
| 2555 | + } else { | |
| 2556 | + // If host already existed, retrieve it and check its state, if it's not up schedule a | |
| 2557 | + // hostUp event. | |
| 2558 | + Host existingHost = metadata.getHost(address); | |
| 2559 | + if(!existingHost.isUp()) | |
| 2560 | + futures.add(schedule(hostUp(existingHost))); | |
| 2561 | + } | |
| 2562 | + break; | |
| 2563 | + case DOWN: | |
| 2564 | + // Note that there is a slight risk we can receive the event late and thus | |
| 2565 | + // mark the host down even though we already had reconnected successfully. | |
| 2566 | + // But it is unlikely, and don't have too much consequence since we'll try reconnecting | |
| 2567 | + // right away, so we favor the detection to make the Host.isUp method more reliable. | |
| 2568 | + Host downHost = metadata.getHost(address); | |
| 2569 | + if (downHost != null) | |
| 2570 | + futures.add(execute(hostDown(downHost))); | |
| 2571 | + break; | |
| 2572 | + case REMOVED: | |
| 2573 | + Host removedHost = metadata.getHost(address); | |
| 2574 | + if (removedHost != null) | |
| 2575 | + futures.add(execute(hostRemoved(removedHost))); | |
| 2576 | + break; | |
| 2577 | + } | |
| 2578 | + } | |
| 2579 | + return Futures.allAsList(futures); | |
| 2580 | + } | |
| 2581 | + | |
| 2582 | + private ListenableFuture<?> execute(ExceptionCatchingRunnable task) { | |
| 2583 | + return executor.submit(task); | |
| 2584 | + } | |
| 2585 | + | |
| 2586 | + private ListenableFuture<?> schedule(final ExceptionCatchingRunnable task) { | |
| 2587 | + // Cassandra tends to send notifications for new/up nodes a bit early (it is triggered once | |
| 2588 | + // gossip is up, but that is before the client-side server is up), so we add a delay | |
| 2589 | + // (otherwise the connection will likely fail and have to be retry which is wasteful). This | |
| 2590 | + // probably should be fixed C* side, after which we'll be able to remove this. | |
| 2591 | + final SettableFuture<?> future = SettableFuture.create(); | |
| 2592 | + scheduledTasksExecutor.schedule(new ExceptionCatchingRunnable() { | |
| 2593 | + public void runMayThrow() throws Exception { | |
| 2594 | + ListenableFuture<?> f = execute(task); | |
| 2595 | + Futures.addCallback(f, new FutureCallback<Object>() { | |
| 2596 | + @Override | |
| 2597 | + public void onSuccess(Object result) { | |
| 2598 | + future.set(null); | |
| 2599 | + } | |
| 2600 | + | |
| 2601 | + @Override | |
| 2602 | + public void onFailure(Throwable t) { | |
| 2603 | + future.setException(t); | |
| 2604 | + } | |
| 2605 | + }); | |
| 2606 | + } | |
| 2607 | + }, NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS); | |
| 2608 | + return future; | |
| 2609 | + } | |
| 2610 | + | |
| 2611 | + // Make sure we call controlConnection.refreshNodeInfo(host) | |
| 2612 | + // so that we have up-to-date infos on that host before adding it (so we typically | |
| 2613 | + // catch that an upgraded node uses a new cassandra version). | |
| 2614 | + | |
| 2615 | + private ExceptionCatchingRunnable hostAdded(final Host host) { | |
| 2616 | + return new ExceptionCatchingRunnable() { | |
| 2617 | + @Override | |
| 2618 | + public void runMayThrow() throws Exception { | |
| 2619 | + if (controlConnection.refreshNodeInfo(host)) { | |
| 2620 | + onAdd(host, null); | |
| 2621 | + } else { | |
| 2622 | + logger.debug("Not enough info for {}, ignoring host", host); | |
| 2623 | + } | |
| 2624 | + } | |
| 2625 | + }; | |
| 2626 | + } | |
| 2627 | + | |
| 2628 | + private ExceptionCatchingRunnable hostUp(final Host host) { | |
| 2629 | + return new ExceptionCatchingRunnable() { | |
| 2630 | + @Override | |
| 2631 | + public void runMayThrow() throws Exception { | |
| 2632 | + if (controlConnection.refreshNodeInfo(host)) { | |
| 2633 | + onUp(host, null); | |
| 2634 | + } else { | |
| 2635 | + logger.debug("Not enough info for {}, ignoring host", host); | |
| 2636 | + } | |
| 2637 | + } | |
| 2638 | + }; | |
| 2639 | + } | |
| 2640 | + | |
| 2641 | + private ExceptionCatchingRunnable hostDown(final Host host) { | |
| 2642 | + return new ExceptionCatchingRunnable() { | |
| 2643 | + @Override | |
| 2644 | + public void runMayThrow() throws Exception { | |
| 2645 | + if (controlConnection.refreshNodeInfo(host)) { | |
| 2646 | + onDown(host, false, true); | |
| 2647 | + } else { | |
| 2648 | + logger.debug("Not enough info for {}, ignoring host", host); | |
| 2649 | + } | |
| 2650 | + } | |
| 2651 | + }; | |
| 2652 | + } | |
| 2653 | + | |
| 2654 | + private ExceptionCatchingRunnable hostRemoved(final Host host) { | |
| 2655 | + return new ExceptionCatchingRunnable() { | |
| 2656 | + @Override | |
| 2657 | + public void runMayThrow() throws Exception { | |
| 2658 | + if (metadata.remove(host)) { | |
| 2659 | + logger.info("Cassandra host {} removed", host); | |
| 2660 | + onRemove(host); | |
| 2661 | + } | |
| 2662 | + } | |
| 2663 | + }; | |
| 2664 | + } | |
| 2665 | + | |
| 2666 | + } | |
| 2667 | + | |
| 2668 | + private class NodeListRefreshRequest { | |
| 2669 | + @Override | |
| 2670 | + public String toString() { | |
| 2671 | + return "Refresh node list and token map"; | |
| 2672 | + } | |
| 2673 | + } | |
| 2674 | + | |
| 2675 | + private class NodeListRefreshRequestDeliveryCallback implements EventDebouncer.DeliveryCallback<NodeListRefreshRequest> { | |
| 2676 | + | |
| 2677 | + @Override | |
| 2678 | + public ListenableFuture<?> deliver(List<NodeListRefreshRequest> events) { | |
| 2679 | + // The number of received requests does not matter | |
| 2680 | + // as long as one request is made, refresh the entire node list | |
| 2681 | + return executor.submit(new ExceptionCatchingRunnable() { | |
| 2682 | + @Override | |
| 2683 | + public void runMayThrow() throws InterruptedException, ExecutionException { | |
| 2684 | + controlConnection.refreshNodeListAndTokenMap(); | |
| 2685 | + } | |
| 2686 | + }); | |
| 2687 | + } | |
| 2688 | + } | |
| 2689 | + | |
| 2690 | + } | |
| 2691 | + | |
| 2692 | + private enum HostEvent { | |
| 2693 | + UP, DOWN, ADDED, REMOVED | |
| 2329 | 2694 | } |
| 2330 | 2695 | |
| 2331 | 2696 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/ColumnMetadata.java +48 −0
| @@ -22,6 +22,8 @@ | ||
| 22 | 22 | import java.util.Map; |
| 23 | 23 | import java.util.Map.Entry; |
| 24 | 24 | |
| 25 | +import com.google.common.base.Objects; | |
| 26 | + | |
| 25 | 27 | /** |
| 26 | 28 | * Describes a Column. |
| 27 | 29 | */ |
| @@ -107,6 +109,34 @@ | ||
| 107 | 109 | return isStatic; |
| 108 | 110 | } |
| 109 | 111 | |
| 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 | + | |
| 110 | 140 | /** |
| 111 | 141 | * Metadata on a column index. |
| 112 | 142 | */ |
| @@ -269,6 +299,24 @@ | ||
| 269 | 299 | return colName; |
| 270 | 300 | } |
| 271 | 301 | |
| 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 | + | |
| 272 | 320 | private static IndexMetadata build(ColumnMetadata column, Map<String, String> indexColumns) { |
| 273 | 321 | if (indexColumns.isEmpty()) |
| 274 | 322 | return null; |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +107 −83
| @@ -19,14 +19,12 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | import java.util.HashSet; |
| 21 | 21 | import java.util.Iterator; |
| 22 | -import java.util.List; | |
| 23 | 22 | import java.util.Queue; |
| 24 | 23 | import java.util.concurrent.*; |
| 25 | 24 | import java.util.concurrent.atomic.AtomicBoolean; |
| 26 | 25 | import java.util.concurrent.atomic.AtomicInteger; |
| 27 | 26 | import java.util.concurrent.atomic.AtomicReference; |
| 28 | 27 | |
| 29 | -import com.google.common.collect.Lists; | |
| 30 | 28 | import com.google.common.collect.MapMaker; |
| 31 | 29 | import com.google.common.util.concurrent.*; |
| 32 | 30 | import io.netty.bootstrap.Bootstrap; |
| @@ -37,8 +35,8 @@ | ||
| 37 | 35 | import io.netty.handler.ssl.SslHandler; |
| 38 | 36 | import io.netty.handler.timeout.IdleStateEvent; |
| 39 | 37 | import io.netty.handler.timeout.IdleStateHandler; |
| 40 | -import io.netty.util.HashedWheelTimer; | |
| 41 | 38 | import io.netty.util.Timeout; |
| 39 | +import io.netty.util.Timer; | |
| 42 | 40 | import io.netty.util.TimerTask; |
| 43 | 41 | import io.netty.util.concurrent.GlobalEventExecutor; |
| 44 | 42 | import javax.net.ssl.SSLEngine; |
| @@ -50,8 +48,12 @@ | ||
| 50 | 48 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 51 | 49 | import com.datastax.driver.core.exceptions.DriverException; |
| 52 | 50 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 51 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 53 | 52 | import com.datastax.driver.core.utils.MoreFutures; |
| 54 | 53 | |
| 54 | +import static com.datastax.driver.core.Message.Response.Type.ERROR; | |
| 55 | +import static com.datastax.driver.core.Message.Response.Type.RESULT; | |
| 56 | + | |
| 55 | 57 | // For LoggingHandler |
| 56 | 58 | //import org.jboss.netty.handler.logging.LoggingHandler; |
| 57 | 59 | //import org.jboss.netty.logging.InternalLogLevel; |
| @@ -87,11 +89,11 @@ | ||
| 87 | 89 | private volatile String keyspace; |
| 88 | 90 | |
| 89 | 91 | private volatile boolean isInitialized; |
| 90 | - private volatile boolean isDefunct; | |
| 92 | + private final AtomicBoolean isDefunct = new AtomicBoolean(); | |
| 91 | 93 | |
| 92 | 94 | private final AtomicReference<ConnectionCloseFuture> closeFuture = new AtomicReference<ConnectionCloseFuture>(); |
| 93 | 95 | |
| 94 | - private final AtomicReference<HostConnectionPool> poolRef = new AtomicReference<HostConnectionPool>(); | |
| 96 | + private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>(); | |
| 95 | 97 | |
| 96 | 98 | /** |
| 97 | 99 | /** |
| @@ -100,15 +102,15 @@ | ||
| 100 | 102 | * @param name the connection name |
| 101 | 103 | * @param address the remote address |
| 102 | 104 | * @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)}. | |
| 105 | 107 | */ |
| 106 | - protected Connection(String name, InetSocketAddress address, Factory factory, HostConnectionPool pool) { | |
| 108 | + protected Connection(String name, InetSocketAddress address, Factory factory, Owner owner) { | |
| 107 | 109 | this.address = address; |
| 108 | 110 | this.factory = factory; |
| 109 | 111 | this.dispatcher = new Dispatcher(); |
| 110 | 112 | this.name = name; |
| 111 | - this.poolRef.set(pool); | |
| 113 | + this.ownerRef.set(owner); | |
| 112 | 114 | } |
| 113 | 115 | |
| 114 | 116 | /** |
| @@ -178,8 +180,8 @@ | ||
| 178 | 180 | public ListenableFuture<Void> create(Throwable t) throws Exception { |
| 179 | 181 | SettableFuture<Void> future = SettableFuture.create(); |
| 180 | 182 | // 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 | |
| 183 | 185 | closeAsync().force(); |
| 184 | 186 | future.setException(t); |
| 185 | 187 | } else { |
| @@ -199,6 +201,9 @@ | ||
| 199 | 201 | Futures.addCallback(initFuture, new FutureCallback<Void>() { |
| 200 | 202 | @Override |
| 201 | 203 | public void onSuccess(Void result) { |
| 204 | + Host host = factory.manager.metadata.getHost(address); | |
| 205 | + if (host != null) | |
| 206 | + host.convictionPolicy.signalConnectionCreated(); | |
| 202 | 207 | isInitialized = true; |
| 203 | 208 | } |
| 204 | 209 | |
| @@ -379,7 +384,7 @@ | ||
| 379 | 384 | } |
| 380 | 385 | |
| 381 | 386 | public boolean isDefunct() { |
| 382 | - return isDefunct; | |
| 387 | + return isDefunct.get(); | |
| 383 | 388 | } |
| 384 | 389 | |
| 385 | 390 | public int maxAvailableStreams() { |
| @@ -387,9 +392,13 @@ | ||
| 387 | 392 | } |
| 388 | 393 | |
| 389 | 394 | <E extends Exception> E defunct(E e) { |
| 390 | - if (logger.isDebugEnabled()) | |
| 391 | - logger.debug("Defuncting connection to " + address, e); | |
| 392 | - isDefunct = true; | |
| 395 | + if (!isDefunct.compareAndSet(false, true)) | |
| 396 | + return e; | |
| 397 | + | |
| 398 | + if (Host.statesLogger.isTraceEnabled()) | |
| 399 | + Host.statesLogger.trace("Defuncting " + this, e); | |
| 400 | + else if (Host.statesLogger.isDebugEnabled()) | |
| 401 | + Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); | |
| 393 | 402 | |
| 394 | 403 | ConnectionException ce = e instanceof ConnectionException |
| 395 | 404 | ? (ConnectionException)e |
| @@ -397,10 +406,12 @@ | ||
| 397 | 406 | |
| 398 | 407 | Host host = factory.manager.metadata.getHost(address); |
| 399 | 408 | if (host != null) { |
| 400 | - // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant. | |
| 401 | - // This is not too much of a problem since calling onDown on a node that is already down has no effect. | |
| 402 | - boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded()); | |
| 403 | - notifyOwnerWhenDefunct(isDown); | |
| 409 | + boolean isDown = factory.manager.signalConnectionFailure(host, ce, isInitialized, host.wasJustAdded()); | |
| 410 | + | |
| 411 | + if (!isDown) | |
| 412 | + notifyOwnerWhenDefunct(); | |
| 413 | + // else the driver will destroy all pools and notify the control connection as part of marking the host down, | |
| 414 | + // so no need to notify | |
| 404 | 415 | } |
| 405 | 416 | |
| 406 | 417 | // Force the connection to close to make sure the future completes. Otherwise force() might never get called and |
| @@ -411,20 +422,14 @@ | ||
| 411 | 422 | return e; |
| 412 | 423 | } |
| 413 | 424 | |
| 414 | - protected void notifyOwnerWhenDefunct(boolean hostIsDown) { | |
| 425 | + private void notifyOwnerWhenDefunct() { | |
| 415 | 426 | // If an error happens during initialization, the owner will detect it and take appropriate action |
| 416 | 427 | if (!isInitialized) |
| 417 | 428 | return; |
| 418 | 429 | |
| 419 | - HostConnectionPool pool = this.poolRef.get(); | |
| 420 | - if (pool == null) | |
| 421 | - return; | |
| 422 | - | |
| 423 | - if (hostIsDown) { | |
| 424 | - pool.closeAsync().force(); | |
| 425 | - } else { | |
| 426 | - pool.replaceDefunctConnection(this); | |
| 427 | - } | |
| 430 | + Owner owner = this.ownerRef.get(); | |
| 431 | + if (owner != null) | |
| 432 | + owner.onConnectionDefunct(this); | |
| 428 | 433 | } |
| 429 | 434 | |
| 430 | 435 | public String keyspace() { |
| @@ -438,46 +443,59 @@ | ||
| 438 | 443 | if (this.keyspace != null && this.keyspace.equals(keyspace)) |
| 439 | 444 | return; |
| 440 | 445 | |
| 441 | - Future future = null; | |
| 442 | 446 | try { |
| 443 | - logger.trace("{} Setting keyspace {}", this, keyspace); | |
| 444 | - long timeout = factory.getConnectTimeoutMillis(); | |
| 445 | - // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already | |
| 446 | - future = write(new Requests.Query("USE \"" + keyspace + '"')); | |
| 447 | - Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); | |
| 448 | - switch (response.type) { | |
| 449 | - case RESULT: | |
| 450 | - this.keyspace = keyspace; | |
| 451 | - break; | |
| 452 | - default: | |
| 453 | - // The code set the keyspace only when a successful 'use' | |
| 454 | - // has been perform, so there shouldn't be any error here. | |
| 455 | - // It can happen however that the node we're connecting to | |
| 456 | - // is not up on the schema yet. In that case, defuncting | |
| 457 | - // the connection is not a bad choice. | |
| 458 | - String message = String.format("Problem while setting keyspace, got %s as response", response); | |
| 459 | - logger.warn("{} {}", this, message); | |
| 460 | - defunct(new ConnectionException(address, message)); | |
| 461 | - break; | |
| 462 | - } | |
| 447 | + Uninterruptibles.getUninterruptibly(setKeyspaceAsync(keyspace)); | |
| 463 | 448 | } catch (ConnectionException e) { |
| 464 | 449 | throw defunct(e); |
| 465 | - } catch (TimeoutException e) { | |
| 466 | - // We've given up waiting on the future, but it's still running. Cancel to make sure that the request timeout logic | |
| 467 | - // (readTimeout) will not kick in, because that would release the connection. This will work since connectTimeout is | |
| 468 | - // generally lower than readTimeout (and if not, we'll get an ExecutionException and defunct below). | |
| 469 | - future.cancel(true); | |
| 470 | - logger.warn(String.format("Timeout while setting keyspace on connection to %s. This should not happen but is not critical (it will retried)", address)); | |
| 471 | - // Rethrow so that the caller will not try to use the connection, but do not defunct as we don't want to mark down | |
| 472 | - throw new ConnectionException(address, "Timeout while setting keyspace on connection"); | |
| 473 | 450 | } catch (BusyConnectionException e) { |
| 474 | - 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)); | |
| 451 | + logger.warn("Tried to set the keyspace on busy connection to {}. " | |
| 452 | + + "This should not happen but is not critical (it will be retried)", address); | |
| 475 | 453 | throw new ConnectionException(address, "Tried to set the keyspace on busy connection"); |
| 476 | 454 | } catch (ExecutionException e) { |
| 477 | - throw defunct(new ConnectionException(address, "Error while setting keyspace", e)); | |
| 455 | + Throwable cause = e.getCause(); | |
| 456 | + if (cause instanceof OperationTimedOutException) { | |
| 457 | + // The timeout logic released the connection, but that's wrong since we did not borrow it in the first place. | |
| 458 | + // JAVA-901 will fix this, in the meantime make sure the inFlight count is not off by one. | |
| 459 | + inFlight.incrementAndGet(); | |
| 460 | + | |
| 461 | + // Rethrow so that the caller doesn't try to use the connection, but do not defunct as we don't want to mark down | |
| 462 | + logger.warn("Timeout while setting keyspace on connection to {}. " | |
| 463 | + + "This should not happen but is not critical (it will be retried)", address); | |
| 464 | + throw new ConnectionException(address, "Timeout while setting keyspace on connection"); | |
| 465 | + } else { | |
| 466 | + throw defunct(new ConnectionException(address, "Error while setting keyspace", cause)); | |
| 467 | + } | |
| 478 | 468 | } |
| 479 | 469 | } |
| 480 | 470 | |
| 471 | + ListenableFuture<Void> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException { | |
| 472 | + logger.trace("{} Setting keyspace {}", this, keyspace); | |
| 473 | + // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already | |
| 474 | + Future future = write(new Requests.Query("USE \"" + keyspace + '"')); | |
| 475 | + return Futures.transform(future, new AsyncFunction<Message.Response, Void>() { | |
| 476 | + @Override | |
| 477 | + public ListenableFuture<Void> apply(Message.Response response) throws Exception { | |
| 478 | + if (response.type == RESULT) { | |
| 479 | + Connection.this.keyspace = keyspace; | |
| 480 | + return MoreFutures.VOID_SUCCESS; | |
| 481 | + } else if (response.type == ERROR) { | |
| 482 | + closeAsync().force(); | |
| 483 | + Responses.Error error = (Responses.Error)response; | |
| 484 | + Exception e = error.asException(address); | |
| 485 | + if (e instanceof InvalidQueryException) { | |
| 486 | + // Most likely means that the keyspace name is wrong. Wrap that in a specific exception, because we want | |
| 487 | + // to treat it specially in case of a Session init. | |
| 488 | + e = new SetKeyspaceException(e); | |
| 489 | + } | |
| 490 | + throw e; | |
| 491 | + } else { | |
| 492 | + closeAsync().force(); | |
| 493 | + throw new DriverInternalError("Unexpected response while setting keyspace: " + response); | |
| 494 | + } | |
| 495 | + } | |
| 496 | + }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor()); | |
| 497 | + } | |
| 498 | + | |
| 481 | 499 | /** |
| 482 | 500 | * Write a request on this connection. |
| 483 | 501 | * |
| @@ -511,7 +529,7 @@ | ||
| 511 | 529 | * having set the handler, we guarantee that even if we race with defunct/close, we may |
| 512 | 530 | * never leave a handler that won't get an answer or be errored out. |
| 513 | 531 | */ |
| 514 | - if (isDefunct) { | |
| 532 | + if (isDefunct.get()) { | |
| 515 | 533 | dispatcher.removeHandler(handler, true); |
| 516 | 534 | throw new ConnectionException(address, "Write attempt on defunct connection"); |
| 517 | 535 | } |
| @@ -521,7 +539,7 @@ | ||
| 521 | 539 | throw new ConnectionException(address, "Connection has been closed"); |
| 522 | 540 | } |
| 523 | 541 | |
| 524 | - logger.trace("{} writing request {}", this, request); | |
| 542 | + logger.trace("{}, stream {}, writing request {}", this, request.getStreamId(), request); | |
| 525 | 543 | writer.incrementAndGet(); |
| 526 | 544 | |
| 527 | 545 | if (DISABLE_COALESCING) { |
| @@ -543,7 +561,7 @@ | ||
| 543 | 561 | writer.decrementAndGet(); |
| 544 | 562 | |
| 545 | 563 | if (!writeFuture.isSuccess()) { |
| 546 | - logger.debug("{} Error writing request {}", Connection.this, request); | |
| 564 | + logger.debug("{}, stream {}, Error writing request {}", Connection.this, request.getStreamId(), request); | |
| 547 | 565 | // Remove this handler from the dispatcher so it don't get notified of the error |
| 548 | 566 | // twice (we will fail that method already) |
| 549 | 567 | dispatcher.removeHandler(handler, true); |
| @@ -567,19 +585,19 @@ | ||
| 567 | 585 | } |
| 568 | 586 | }); |
| 569 | 587 | } else { |
| 570 | - logger.trace("{} request sent successfully", Connection.this); | |
| 588 | + logger.trace("{}, stream {}, request sent successfully", Connection.this, request.getStreamId()); | |
| 571 | 589 | } |
| 572 | 590 | } |
| 573 | 591 | }; |
| 574 | 592 | } |
| 575 | 593 | |
| 576 | - boolean hasPool() { | |
| 577 | - return this.poolRef.get() != null; | |
| 594 | + boolean hasOwner() { | |
| 595 | + return this.ownerRef.get() != null; | |
| 578 | 596 | } |
| 579 | 597 | |
| 580 | - /** @return whether the connection was already associated with a pool */ | |
| 581 | - boolean setPool(HostConnectionPool pool) { | |
| 582 | - return poolRef.compareAndSet(null, pool); | |
| 598 | + /** @return whether the connection was already associated with an owner */ | |
| 599 | + boolean setOwner(Owner owner) { | |
| 600 | + return ownerRef.compareAndSet(null, owner); | |
| 583 | 601 | } |
| 584 | 602 | |
| 585 | 603 | /** |
| @@ -587,9 +605,9 @@ | ||
| 587 | 605 | * The connection should generally not be reused after that. |
| 588 | 606 | */ |
| 589 | 607 | void release() { |
| 590 | - HostConnectionPool pool = poolRef.get(); | |
| 591 | - if (pool != null) | |
| 592 | - pool.returnConnection(this); | |
| 608 | + Owner owner = ownerRef.get(); | |
| 609 | + if (owner instanceof HostConnectionPool) | |
| 610 | + ((HostConnectionPool)owner).returnConnection(this); | |
| 593 | 611 | } |
| 594 | 612 | |
| 595 | 613 | public boolean isClosed() { |
| @@ -617,6 +635,12 @@ | ||
| 617 | 635 | |
| 618 | 636 | logger.debug("{} closing connection", this); |
| 619 | 637 | |
| 638 | + if (isInitialized && !isDefunct.get()) { | |
| 639 | + Host host = factory.manager.metadata.getHost(address); | |
| 640 | + if(host != null) | |
| 641 | + host.convictionPolicy.signalConnectionClosed(); | |
| 642 | + } | |
| 643 | + | |
| 620 | 644 | boolean terminated = tryTerminate(false); |
| 621 | 645 | if (!terminated) { |
| 622 | 646 | // The time by which all pending requests should have normally completed (use twice the read timeout for a generous |
| @@ -665,7 +689,7 @@ | ||
| 665 | 689 | |
| 666 | 690 | public static class Factory { |
| 667 | 691 | |
| 668 | - public final HashedWheelTimer timer; | |
| 692 | + public final Timer timer; | |
| 669 | 693 | |
| 670 | 694 | private final EventLoopGroup eventLoopGroup; |
| 671 | 695 | private final Class<? extends Channel> channelClass; |
| @@ -694,7 +718,7 @@ | ||
| 694 | 718 | this.nettyOptions = configuration.getNettyOptions(); |
| 695 | 719 | this.eventLoopGroup = nettyOptions.eventLoopGroup(manager.threadFactory("nio-worker")); |
| 696 | 720 | this.channelClass = nettyOptions.channelClass(); |
| 697 | - this.timer = new HashedWheelTimer(manager.threadFactory("timeouter")); | |
| 721 | + this.timer = nettyOptions.timer(manager.threadFactory("timeouter")); | |
| 698 | 722 | } |
| 699 | 723 | |
| 700 | 724 | public int getPort() { |
| @@ -775,10 +799,6 @@ | ||
| 775 | 799 | return g; |
| 776 | 800 | } |
| 777 | 801 | |
| 778 | - public long getConnectTimeoutMillis() { | |
| 779 | - return configuration.getSocketOptions().getConnectTimeoutMillis(); | |
| 780 | - } | |
| 781 | - | |
| 782 | 802 | public long getReadTimeoutMillis() { |
| 783 | 803 | return configuration.getSocketOptions().getReadTimeoutMillis(); |
| 784 | 804 | } |
| @@ -823,7 +843,7 @@ | ||
| 823 | 843 | allChannels.close().awaitUninterruptibly(); |
| 824 | 844 | |
| 825 | 845 | nettyOptions.onClusterClose(eventLoopGroup); |
| 826 | - timer.stop(); | |
| 846 | + nettyOptions.onClusterClose(timer); | |
| 827 | 847 | } |
| 828 | 848 | } |
| 829 | 849 | |
| @@ -874,7 +894,7 @@ | ||
| 874 | 894 | } |
| 875 | 895 | |
| 876 | 896 | EventLoop eventLoop = eventLoopRef.get(); |
| 877 | - if(eventLoop != null) { | |
| 897 | + if (eventLoop != null) { | |
| 878 | 898 | eventLoop.schedule(this, 10000, TimeUnit.NANOSECONDS); |
| 879 | 899 | } |
| 880 | 900 | } |
| @@ -920,7 +940,6 @@ | ||
| 920 | 940 | if (protocolVersion == null) { |
| 921 | 941 | // This happens for the first control connection because the protocol version has not been |
| 922 | 942 | // negociated yet. |
| 923 | - assert !Connection.this.hasPool(); | |
| 924 | 943 | protocolVersion = ProtocolVersion.V2; |
| 925 | 944 | } |
| 926 | 945 | streamIdHandler = StreamIdGenerator.newInstance(protocolVersion); |
| @@ -962,7 +981,7 @@ | ||
| 962 | 981 | int streamId = response.getStreamId(); |
| 963 | 982 | |
| 964 | 983 | if(logger.isTraceEnabled()) |
| 965 | - logger.trace("{} received: {}", Connection.this, asDebugString(response)); | |
| 984 | + logger.trace("{}, stream {}, received: {}", Connection.this, streamId, asDebugString(response)); | |
| 966 | 985 | |
| 967 | 986 | if (streamId < 0) { |
| 968 | 987 | factory.defaultHandler.handle(response); |
| @@ -998,7 +1017,7 @@ | ||
| 998 | 1017 | |
| 999 | 1018 | @Override |
| 1000 | 1019 | public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { |
| 1001 | - if (evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) { | |
| 1020 | + if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent)evt).state() == ALL_IDLE) { | |
| 1002 | 1021 | logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds()); |
| 1003 | 1022 | write(HEARTBEAT_CALLBACK); |
| 1004 | 1023 | } |
| @@ -1317,4 +1336,9 @@ | ||
| 1317 | 1336 | } |
| 1318 | 1337 | } |
| 1319 | 1338 | } |
| 1339 | + | |
| 1340 | + /** A component that "owns" a connection, and should be notified when it dies. */ | |
| 1341 | + interface Owner { | |
| 1342 | + void onConnectionDefunct(Connection connection); | |
| 1343 | + } | |
| 1320 | 1344 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +95 −96
| @@ -19,8 +19,7 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | import java.net.UnknownHostException; |
| 21 | 21 | import java.util.*; |
| 22 | -import java.util.concurrent.ExecutionException; | |
| 23 | -import java.util.concurrent.TimeUnit; | |
| 22 | +import java.util.concurrent.*; | |
| 24 | 23 | import java.util.concurrent.atomic.AtomicReference; |
| 25 | 24 | |
| 26 | 25 | import com.google.common.base.Objects; |
| @@ -36,13 +35,13 @@ | ||
| 36 | 35 | import static com.datastax.driver.core.SchemaElement.TABLE; |
| 37 | 36 | import static com.datastax.driver.core.SchemaElement.TYPE; |
| 38 | 37 | |
| 39 | -class ControlConnection implements Host.StateListener { | |
| 38 | +class ControlConnection implements Host.StateListener, Connection.Owner { | |
| 40 | 39 | |
| 41 | 40 | private static final Logger logger = LoggerFactory.getLogger(ControlConnection.class); |
| 42 | 41 | |
| 43 | 42 | private static final InetAddress bindAllAddress; |
| 44 | - static | |
| 45 | - { | |
| 43 | + | |
| 44 | + static { | |
| 46 | 45 | try { |
| 47 | 46 | bindAllAddress = InetAddress.getByAddress(new byte[4]); |
| 48 | 47 | } catch (UnknownHostException e) { |
| @@ -74,15 +73,18 @@ | ||
| 74 | 73 | } |
| 75 | 74 | |
| 76 | 75 | // Only for the initial connection. Does not schedule retries if it fails |
| 77 | - public void connect() throws UnsupportedProtocolVersionException { | |
| 76 | + void connect() throws UnsupportedProtocolVersionException { | |
| 78 | 77 | if (isShutdown) |
| 79 | 78 | return; |
| 80 | 79 | |
| 81 | 80 | // NB: at this stage, allHosts() only contains the initial contact points |
| 82 | - setNewConnection(reconnectInternal(cluster.metadata.allHosts().iterator(), true)); | |
| 81 | + List<Host> hosts = new ArrayList<Host>(cluster.metadata.allHosts()); | |
| 82 | + // shuffle so that multiple clients with the same contact points don't all pick the same control host | |
| 83 | + Collections.shuffle(hosts); | |
| 84 | + setNewConnection(reconnectInternal(hosts.iterator(), true)); | |
| 83 | 85 | } |
| 84 | 86 | |
| 85 | - public CloseFuture closeAsync() { | |
| 87 | + CloseFuture closeAsync() { | |
| 86 | 88 | // We don't have to be fancy here. We just set a flag so that we stop trying to reconnect (and thus change the |
| 87 | 89 | // connection used) and shutdown the current one. |
| 88 | 90 | isShutdown = true; |
| @@ -98,26 +100,13 @@ | ||
| 98 | 100 | |
| 99 | 101 | Host connectedHost() { |
| 100 | 102 | Connection current = connectionRef.get(); |
| 101 | - return cluster.metadata.getHost(current.address); | |
| 103 | + return (current == null) | |
| 104 | + ? null | |
| 105 | + : cluster.metadata.getHost(current.address); | |
| 102 | 106 | } |
| 103 | 107 | |
| 104 | - void reconnect() { | |
| 105 | - if (isShutdown) | |
| 106 | - return; | |
| 107 | - | |
| 108 | - try { | |
| 109 | - setNewConnection(reconnectInternal(queryPlan(), false)); | |
| 110 | - } catch (NoHostAvailableException e) { | |
| 111 | - logger.error("[Control connection] Cannot connect to any host, scheduling retry"); | |
| 112 | - backgroundReconnect(-1); | |
| 113 | - } catch (UnsupportedProtocolVersionException e) { | |
| 114 | - // reconnectInternal only propagate those if we've not decided on the protocol version yet, | |
| 115 | - // which should only happen on the initial connection and thus in connect() but never here. | |
| 116 | - throw new AssertionError(); | |
| 117 | - } catch (Exception e) { | |
| 118 | - logger.error("[Control connection] Unknown error during reconnection, scheduling retry", e); | |
| 119 | - backgroundReconnect(-1); | |
| 120 | - } | |
| 108 | + void triggerReconnect() { | |
| 109 | + backgroundReconnect(0); | |
| 121 | 110 | } |
| 122 | 111 | |
| 123 | 112 | /** |
| @@ -127,7 +116,14 @@ | ||
| 127 | 116 | if (isShutdown) |
| 128 | 117 | return; |
| 129 | 118 | |
| 130 | - new AbstractReconnectionHandler(cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) { | |
| 119 | + // Abort if a reconnection is already in progress. This is not thread-safe: two threads might race through this and both | |
| 120 | + // schedule a reconnection; in that case AbstractReconnectionHandler knows how to deal with it correctly. | |
| 121 | + // But this cheap check can help us avoid creating the object unnecessarily. | |
| 122 | + ListenableFuture<?> reconnection = reconnectionAttempt.get(); | |
| 123 | + if (reconnection != null && !reconnection.isDone()) | |
| 124 | + return; | |
| 125 | + | |
| 126 | + new AbstractReconnectionHandler("Control connection", cluster.reconnectionExecutor, cluster.reconnectionPolicy().newSchedule(), reconnectionAttempt, initialDelayMs) { | |
| 131 | 127 | @Override |
| 132 | 128 | protected Connection tryReconnect() throws ConnectionException { |
| 133 | 129 | try { |
| @@ -166,17 +162,17 @@ | ||
| 166 | 162 | |
| 167 | 163 | private void signalError() { |
| 168 | 164 | Connection connection = connectionRef.get(); |
| 169 | - if (connection != null && connection.isDefunct() && cluster.metadata.getHost(connection.address) != null) { | |
| 170 | - // If the connection was marked as defunct and the host hadn't left, this already reported the | |
| 171 | - // host down, which will trigger a reconnect. | |
| 172 | - return; | |
| 173 | - } | |
| 174 | - // If the connection is not defunct, or the host has left, just reconnect manually | |
| 165 | + if (connection != null) | |
| 166 | + connection.closeAsync(); | |
| 167 | + | |
| 168 | + // If the error caused the host to go down, onDown might have already triggered a reconnect. | |
| 169 | + // But backgroundReconnect knows how to deal with that. | |
| 175 | 170 | backgroundReconnect(0); |
| 176 | 171 | } |
| 177 | 172 | |
| 178 | 173 | private void setNewConnection(Connection newConnection) { |
| 179 | - logger.debug("[Control connection] Successfully connected to {}", newConnection.address); | |
| 174 | + Host.statesLogger.debug("[Control connection] established to {}", newConnection.address); | |
| 175 | + newConnection.setOwner(this); | |
| 180 | 176 | Connection old = connectionRef.getAndSet(newConnection); |
| 181 | 177 | if (old != null && !old.isClosed()) |
| 182 | 178 | old.closeAsync(); |
| @@ -190,6 +186,8 @@ | ||
| 190 | 186 | try { |
| 191 | 187 | while (iter.hasNext()) { |
| 192 | 188 | host = iter.next(); |
| 189 | + if (!host.convictionPolicy.canReconnectNow()) | |
| 190 | + continue; | |
| 193 | 191 | try { |
| 194 | 192 | return tryConnect(host, isInitialConnection); |
| 195 | 193 | } catch (ConnectionException e) { |
| @@ -243,8 +241,7 @@ | ||
| 243 | 241 | return errors; |
| 244 | 242 | } |
| 245 | 243 | |
| 246 | - private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException | |
| 247 | - { | |
| 244 | + private Connection tryConnect(Host host, boolean isInitialConnection) throws ConnectionException, ExecutionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { | |
| 248 | 245 | Connection connection = cluster.connectionFactory.open(host); |
| 249 | 246 | |
| 250 | 247 | // If no protocol version was specified, set the default as soon as a connection succeeds (it's needed to parse UDTs in refreshSchema) |
| @@ -264,11 +261,14 @@ | ||
| 264 | 261 | // the node we're connecting to. |
| 265 | 262 | refreshNodeListAndTokenMap(connection, cluster, isInitialConnection, true); |
| 266 | 263 | |
| 267 | - // Note that refreshing the schema will trigger refreshNodeListAndTokenMap since table == null | |
| 268 | - // We want that because the token map was not properly initialized by the first call above, since it requires the list of keyspaces | |
| 269 | - // to be loaded. | |
| 270 | 264 | logger.debug("[Control connection] Refreshing schema"); |
| 271 | - refreshSchema(connection, null, null, null, cluster, isInitialConnection); | |
| 265 | + refreshSchema(connection, null, null, null, cluster); | |
| 266 | + | |
| 267 | + // We need to refresh the node list again; | |
| 268 | + // We want that because the token map was not properly initialized by the first call above, | |
| 269 | + // since it requires the list of keyspaces to be loaded. | |
| 270 | + refreshNodeListAndTokenMap(connection, cluster, false, true); | |
| 271 | + | |
| 272 | 272 | return connection; |
| 273 | 273 | } catch (BusyConnectionException e) { |
| 274 | 274 | connection.closeAsync().force(); |
| @@ -295,9 +295,14 @@ | ||
| 295 | 295 | try { |
| 296 | 296 | Connection c = connectionRef.get(); |
| 297 | 297 | // At startup, when we add the initial nodes, this will be null, which is ok |
| 298 | - if (c == null) | |
| 298 | + if (c == null || c.isClosed()) | |
| 299 | 299 | return; |
| 300 | - refreshSchema(c, targetType, targetKeyspace, targetName, cluster, false); | |
| 300 | + refreshSchema(c, targetType, targetKeyspace, targetName, cluster); | |
| 301 | + // If we rebuild all from scratch or have an updated keyspace, rebuild the token map | |
| 302 | + // since some replication on some keyspace may have changed | |
| 303 | + if ((targetType == null || targetType == KEYSPACE)) { | |
| 304 | + cluster.submitNodeListRefresh(); | |
| 305 | + } | |
| 301 | 306 | } catch (ConnectionException e) { |
| 302 | 307 | logger.debug("[Control connection] Connection error while refreshing schema ({})", e.getMessage()); |
| 303 | 308 | signalError(); |
| @@ -312,7 +317,7 @@ | ||
| 312 | 317 | } |
| 313 | 318 | } |
| 314 | 319 | |
| 315 | - static void refreshSchema(Connection connection, SchemaElement targetType, String targetKeyspace, String targetName, Cluster.Manager cluster, boolean isInitialConnection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 320 | + static void refreshSchema(Connection connection, SchemaElement targetType, String targetKeyspace, String targetName, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 316 | 321 | Host host = cluster.metadata.getHost(connection.address); |
| 317 | 322 | // 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 |
| 318 | 323 | // 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 |
| @@ -321,7 +326,7 @@ | ||
| 321 | 326 | if (host == null || host.getCassandraVersion() == null) { |
| 322 | 327 | cassandraVersion = cluster.protocolVersion().minCassandraVersion(); |
| 323 | 328 | logger.warn("Cannot find Cassandra version for host {} to parse the schema, using {} based on protocol version in use. " |
| 324 | - + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion); | |
| 329 | + + "If parsing the schema fails, this could be the cause", connection.address, cassandraVersion); | |
| 325 | 330 | } else { |
| 326 | 331 | cassandraVersion = host.getCassandraVersion(); |
| 327 | 332 | } |
| @@ -372,24 +377,18 @@ | ||
| 372 | 377 | // So log, but let things go otherwise. |
| 373 | 378 | logger.error("Error parsing schema from Cassandra system tables: the schema in Cluster#getMetadata() will appear incomplete or stale", e); |
| 374 | 379 | } |
| 375 | - | |
| 376 | - // If we rebuild all from scratch or have an updated keyspace, rebuild the token map since some replication on some keyspace | |
| 377 | - // may have changed | |
| 378 | - if (isSchemaOrKeyspace) | |
| 379 | - refreshNodeListAndTokenMap(connection, cluster, false, false); | |
| 380 | 380 | } |
| 381 | 381 | |
| 382 | 382 | private static boolean supportsUdts(VersionNumber cassandraVersion) { |
| 383 | 383 | return cassandraVersion.getMajor() > 2 || (cassandraVersion.getMajor() == 2 && cassandraVersion.getMinor() >= 1); |
| 384 | 384 | } |
| 385 | 385 | |
| 386 | - public void refreshNodeListAndTokenMap() { | |
| 386 | + void refreshNodeListAndTokenMap() { | |
| 387 | 387 | Connection c = connectionRef.get(); |
| 388 | 388 | // At startup, when we add the initial nodes, this will be null, which is ok |
| 389 | - if (c == null) | |
| 389 | + if (c == null || c.isClosed()) | |
| 390 | 390 | return; |
| 391 | 391 | |
| 392 | - logger.debug("[Control connection] Refreshing node list and token map"); | |
| 393 | 392 | try { |
| 394 | 393 | refreshNodeListAndTokenMap(c, cluster, false, true); |
| 395 | 394 | } catch (ConnectionException e) { |
| @@ -453,11 +452,11 @@ | ||
| 453 | 452 | /** |
| 454 | 453 | * @return whether we have enough information to bring the node back up |
| 455 | 454 | */ |
| 456 | - public boolean refreshNodeInfo(Host host) { | |
| 455 | + boolean refreshNodeInfo(Host host) { | |
| 457 | 456 | |
| 458 | 457 | Connection c = connectionRef.get(); |
| 459 | 458 | // At startup, when we add the initial nodes, this will be null, which is ok |
| 460 | - if (c == null) | |
| 459 | + if (c == null || c.isClosed()) | |
| 461 | 460 | return true; |
| 462 | 461 | |
| 463 | 462 | logger.debug("[Control connection] Refreshing node info on {}", host); |
| @@ -515,8 +514,8 @@ | ||
| 515 | 514 | String version = row.getString("release_version"); |
| 516 | 515 | // We don't know if it's a 'local' or a 'peers' row, and only 'peers' rows have the 'peer' field. |
| 517 | 516 | InetAddress listenAddress = row.getColumnDefinitions().contains("peer") |
| 518 | - ? row.getInet("peer") | |
| 519 | - : null; | |
| 517 | + ? row.getInet("peer") | |
| 518 | + : null; | |
| 520 | 519 | |
| 521 | 520 | host.setVersionAndListenAdress(version, listenAddress); |
| 522 | 521 | } |
| @@ -538,6 +537,8 @@ | ||
| 538 | 537 | private static void refreshNodeListAndTokenMap(Connection connection, Cluster.Manager cluster, boolean isInitialConnection, boolean logMissingRpcAddresses) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { |
| 539 | 538 | logger.debug("[Control connection] Refreshing node list and token map"); |
| 540 | 539 | |
| 540 | + boolean metadataEnabled = cluster.configuration.getQueryOptions().isMetadataEnabled(); | |
| 541 | + | |
| 541 | 542 | // Make sure we're up to date on nodes and tokens |
| 542 | 543 | |
| 543 | 544 | DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_LOCAL)); |
| @@ -566,9 +567,11 @@ | ||
| 566 | 567 | logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address); |
| 567 | 568 | } else { |
| 568 | 569 | updateInfo(host, localRow, cluster, isInitialConnection); |
| 569 | - Set<String> tokens = localRow.getSet("tokens", String.class); | |
| 570 | - if (partitioner != null && !tokens.isEmpty()) | |
| 571 | - tokenMap.put(host, tokens); | |
| 570 | + if (metadataEnabled) { | |
| 571 | + Set<String> tokens = localRow.getSet("tokens", String.class); | |
| 572 | + if (partitioner != null && !tokens.isEmpty()) | |
| 573 | + tokenMap.put(host, tokens); | |
| 574 | + } | |
| 572 | 575 | } |
| 573 | 576 | } |
| 574 | 577 | |
| @@ -589,7 +592,8 @@ | ||
| 589 | 592 | racks.add(row.getString("rack")); |
| 590 | 593 | cassandraVersions.add(row.getString("release_version")); |
| 591 | 594 | listenAddresses.add(row.getInet("peer")); |
| 592 | - allTokens.add(row.getSet("tokens", String.class)); | |
| 595 | + if (metadataEnabled) | |
| 596 | + allTokens.add(row.getSet("tokens", String.class)); | |
| 593 | 597 | } |
| 594 | 598 | |
| 595 | 599 | for (int i = 0; i < foundHosts.size(); i++) { |
| @@ -606,7 +610,7 @@ | ||
| 606 | 610 | if (cassandraVersions.get(i) != null) |
| 607 | 611 | host.setVersionAndListenAdress(cassandraVersions.get(i), listenAddresses.get(i)); |
| 608 | 612 | |
| 609 | - if (partitioner != null && !allTokens.get(i).isEmpty()) | |
| 613 | + if (metadataEnabled && partitioner != null && !allTokens.get(i).isEmpty()) | |
| 610 | 614 | tokenMap.put(host, allTokens.get(i)); |
| 611 | 615 | |
| 612 | 616 | if (isNew && !isInitialConnection) |
| @@ -619,17 +623,17 @@ | ||
| 619 | 623 | if (!host.getSocketAddress().equals(connection.address) && !foundHostsSet.contains(host.getSocketAddress())) |
| 620 | 624 | cluster.removeHost(host, isInitialConnection); |
| 621 | 625 | |
| 622 | - cluster.metadata.rebuildTokenMap(partitioner, tokenMap); | |
| 626 | + if (metadataEnabled) | |
| 627 | + cluster.metadata.rebuildTokenMap(partitioner, tokenMap); | |
| 623 | 628 | } |
| 624 | 629 | |
| 625 | - static boolean waitForSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 626 | - | |
| 630 | + boolean waitForSchemaAgreement() throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { | |
| 627 | 631 | long start = System.nanoTime(); |
| 628 | 632 | long elapsed = 0; |
| 629 | 633 | int maxSchemaAgreementWaitSeconds = cluster.configuration.getProtocolOptions().getMaxSchemaAgreementWaitSeconds(); |
| 630 | 634 | while (elapsed < maxSchemaAgreementWaitSeconds * 1000) { |
| 631 | 635 | |
| 632 | - if (checkSchemaAgreement(connection, cluster)) | |
| 636 | + if (checkSchemaAgreement()) | |
| 633 | 637 | return true; |
| 634 | 638 | |
| 635 | 639 | // let's not flood the node too much |
| @@ -641,7 +645,11 @@ | ||
| 641 | 645 | return false; |
| 642 | 646 | } |
| 643 | 647 | |
| 644 | - private static boolean checkSchemaAgreement(Connection connection, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { | |
| 648 | + boolean checkSchemaAgreement() throws ConnectionException, BusyConnectionException, InterruptedException, ExecutionException { | |
| 649 | + Connection connection = connectionRef.get(); | |
| 650 | + if (connection == null || connection.isClosed()) | |
| 651 | + return false; | |
| 652 | + | |
| 645 | 653 | DefaultResultSetFuture peersFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_PEERS)); |
| 646 | 654 | DefaultResultSetFuture localFuture = new DefaultResultSetFuture(null, cluster.protocolVersion(), new Requests.Query(SELECT_SCHEMA_LOCAL)); |
| 647 | 655 | connection.write(peersFuture); |
| @@ -667,16 +675,6 @@ | ||
| 667 | 675 | return versions.size() <= 1; |
| 668 | 676 | } |
| 669 | 677 | |
| 670 | - boolean checkSchemaAgreement() { | |
| 671 | - Connection c = connectionRef.get(); | |
| 672 | - try { | |
| 673 | - return c != null && checkSchemaAgreement(c, cluster); | |
| 674 | - } catch (Exception e) { | |
| 675 | - logger.warn("Error while checking schema agreement", e); | |
| 676 | - return false; | |
| 677 | - } | |
| 678 | - } | |
| 679 | - | |
| 680 | 678 | boolean isOpen() { |
| 681 | 679 | Connection c = connectionRef.get(); |
| 682 | 680 | return c != null && !c.isClosed(); |
| @@ -688,18 +686,33 @@ | ||
| 688 | 686 | |
| 689 | 687 | @Override |
| 690 | 688 | public void onDown(Host host) { |
| 691 | - // If that's the host we're connected to, and we haven't yet schedule a reconnection, preemptively start one | |
| 689 | + onHostGone(host); | |
| 690 | + } | |
| 691 | + | |
| 692 | + @Override | |
| 693 | + public void onRemove(Host host) { | |
| 694 | + onHostGone(host); | |
| 695 | + cluster.submitNodeListRefresh(); | |
| 696 | + } | |
| 697 | + | |
| 698 | + private void onHostGone(Host host) { | |
| 692 | 699 | Connection current = connectionRef.get(); |
| 693 | - if (logger.isDebugEnabled()) | |
| 694 | - logger.debug("[Control connection] {} is down, currently connected to {}", host, current == null ? "nobody" : current.address); | |
| 695 | 700 | |
| 696 | 701 | if (current != null && current.address.equals(host.getSocketAddress())) { |
| 697 | - // This starts an AbstractReconnectionHandler, which will take care of checking if another reconnection is | |
| 698 | - // already in progress | |
| 702 | + logger.debug("[Control connection] {} is down/removed and it was the control host, triggering reconnect", | |
| 703 | + current.address); | |
| 704 | + if (!current.isClosed()) | |
| 705 | + current.closeAsync(); | |
| 699 | 706 | backgroundReconnect(0); |
| 700 | 707 | } |
| 701 | 708 | } |
| 702 | 709 | |
| 710 | + @Override | |
| 711 | + public void onConnectionDefunct(Connection connection) { | |
| 712 | + if (connection == connectionRef.get()) | |
| 713 | + backgroundReconnect(0); | |
| 714 | + } | |
| 715 | + | |
| 703 | 716 | @Override |
| 704 | 717 | public void onSuspected(Host host) { |
| 705 | 718 | } |
| @@ -710,20 +723,6 @@ | ||
| 710 | 723 | // or it's not part of our computed token map |
| 711 | 724 | Metadata.TokenMap tkmap = cluster.metadata.tokenMap; |
| 712 | 725 | if (host.getCassandraVersion() == null || tkmap == null || !tkmap.hosts.contains(host)) |
| 713 | - refreshNodeListAndTokenMap(); | |
| 714 | - } | |
| 715 | - | |
| 716 | - @Override | |
| 717 | - public void onRemove(Host host) { | |
| 718 | - Connection current = connectionRef.get(); | |
| 719 | - if (logger.isDebugEnabled()) | |
| 720 | - logger.debug("[Control connection] {} has been removed, currently connected to {}", host, current == null ? "nobody" : current.address); | |
| 721 | - | |
| 722 | - // Schedule a reconnection if that was our control host | |
| 723 | - if (current != null && current.address.equals(host.getSocketAddress())) { | |
| 724 | - backgroundReconnect(0); | |
| 725 | - } | |
| 726 | - | |
| 727 | - refreshNodeListAndTokenMap(); | |
| 726 | + cluster.submitNodeListRefresh(); | |
| 728 | 727 | } |
| 729 | 728 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ConvictionPolicy.java +95 −17
| @@ -15,6 +15,13 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 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 | + | |
| 18 | 25 | /** |
| 19 | 26 | * The policy with which to decide whether a host should be considered down. |
| 20 | 27 | * |
| @@ -25,24 +32,36 @@ | ||
| 25 | 32 | */ |
| 26 | 33 | abstract class ConvictionPolicy { |
| 27 | 34 | |
| 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 | + | |
| 28 | 45 | /** |
| 29 | 46 | * Called when a connection error occurs on a connection to the host this policy applies to. |
| 30 | 47 | * |
| 31 | 48 | * @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. | |
| 34 | 51 | */ |
| 35 | - public abstract boolean addFailure(ConnectionException exception); | |
| 52 | + abstract boolean signalConnectionFailure(ConnectionException exception, boolean connectionInitialized); | |
| 53 | + | |
| 54 | + abstract boolean canReconnectNow(); | |
| 36 | 55 | |
| 37 | 56 | /** |
| 38 | - * Called when the host has been detected up. | |
| 57 | + * Called when the host goes down. | |
| 39 | 58 | */ |
| 40 | - public abstract void reset(); | |
| 59 | + abstract void reset(); | |
| 41 | 60 | |
| 42 | 61 | /** |
| 43 | 62 | * Simple factory interface to allow creating {@link ConvictionPolicy} instances. |
| 44 | 63 | */ |
| 45 | - public interface Factory { | |
| 64 | + interface Factory { | |
| 46 | 65 | |
| 47 | 66 | /** |
| 48 | 67 | * Creates a new ConvictionPolicy instance for {@code host}. |
| @@ -50,30 +69,89 @@ | ||
| 50 | 69 | * @param host the host this policy applies to |
| 51 | 70 | * @return the newly created {@link ConvictionPolicy} instance. |
| 52 | 71 | */ |
| 53 | - public ConvictionPolicy create(Host host); | |
| 72 | + ConvictionPolicy create(Host host, ReconnectionPolicy reconnectionPolicy); | |
| 54 | 73 | } |
| 55 | 74 | |
| 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); | |
| 58 | 102 | } |
| 59 | 103 | |
| 60 | 104 | @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; | |
| 63 | 117 | } |
| 64 | 118 | |
| 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; | |
| 67 | 136 | } |
| 68 | 137 | |
| 69 | 138 | @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 | + } | |
| 71 | 149 | |
| 72 | - public static class Factory implements ConvictionPolicy.Factory { | |
| 150 | + static class Factory implements ConvictionPolicy.Factory { | |
| 73 | 151 | |
| 74 | 152 | @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); | |
| 77 | 155 | } |
| 78 | 156 | } |
| 79 | 157 | } |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +72 −53
| @@ -67,46 +67,77 @@ | ||
| 67 | 67 | set(ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement)); |
| 68 | 68 | break; |
| 69 | 69 | case SCHEMA_CHANGE: |
| 70 | - Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm; | |
| 71 | 70 | ResultSet rs = ArrayBackedResultSet.fromMessage(rm, session, protocolVersion, info, statement); |
| 72 | - switch (scc.change) { | |
| 73 | - case CREATED: | |
| 74 | - case UPDATED: | |
| 75 | - session.cluster.manager.refreshSchemaAndSignal(connection, this, rs, scc.targetType, scc.targetKeyspace, scc.targetName); | |
| 76 | - break; | |
| 77 | - case DROPPED: | |
| 78 | - KeyspaceMetadata keyspace; | |
| 79 | - switch (scc.targetType) { | |
| 80 | - case KEYSPACE: | |
| 81 | - // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...) | |
| 82 | - // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements. | |
| 83 | - // We'll add it back if CASSANDRA-5358 changes that behavior | |
| 84 | - //if (scc.keyspace.equals(session.poolsState.keyspace)) | |
| 85 | - // session.poolsState.setKeyspace(null); | |
| 86 | - session.cluster.manager.metadata.removeKeyspace(scc.targetKeyspace); | |
| 87 | - break; | |
| 88 | - case TABLE: | |
| 89 | - keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace); | |
| 90 | - if (keyspace == null) | |
| 91 | - logger.warn("Received a DROPPED notification for table {}.{}, but this keyspace is unknown in our metadata", | |
| 92 | - scc.targetKeyspace, scc.targetName); | |
| 93 | - else | |
| 94 | - keyspace.removeTable(scc.targetName); | |
| 95 | - break; | |
| 96 | - case TYPE: | |
| 97 | - keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace); | |
| 98 | - if (keyspace == null) | |
| 99 | - logger.warn("Received a DROPPED notification for UDT {}.{}, but this keyspace is unknown in our metadata", | |
| 100 | - scc.targetKeyspace, scc.targetName); | |
| 101 | - else | |
| 102 | - keyspace.removeUserType(scc.targetName); | |
| 103 | - break; | |
| 104 | - } | |
| 105 | - session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs); | |
| 106 | - break; | |
| 107 | - default: | |
| 108 | - logger.info("Ignoring unknown schema change result"); | |
| 109 | - break; | |
| 71 | + final Cluster.Manager cluster = session.cluster.manager; | |
| 72 | + if (!cluster.configuration.getQueryOptions().isMetadataEnabled()) { | |
| 73 | + cluster.waitForSchemaAgreementAndSignal(connection, this, rs); | |
| 74 | + } else { | |
| 75 | + Responses.Result.SchemaChange scc = (Responses.Result.SchemaChange)rm; | |
| 76 | + switch (scc.change) { | |
| 77 | + case CREATED: | |
| 78 | + case UPDATED: | |
| 79 | + cluster.refreshSchemaAndSignal(connection, this, rs, scc.targetType, scc.targetKeyspace, scc.targetName); | |
| 80 | + break; | |
| 81 | + case DROPPED: | |
| 82 | + KeyspaceMetadata keyspace; | |
| 83 | + switch (scc.targetType) { | |
| 84 | + case KEYSPACE: | |
| 85 | + // If that the one keyspace we are logged in, reset to null (it shouldn't really happen but ...) | |
| 86 | + // Note: Actually, Cassandra doesn't do that so we don't either as this could confuse prepared statements. | |
| 87 | + // We'll add it back if CASSANDRA-5358 changes that behavior | |
| 88 | + //if (scc.keyspace.equals(session.poolsState.keyspace)) | |
| 89 | + // session.poolsState.setKeyspace(null); | |
| 90 | + final KeyspaceMetadata removedKeyspace = cluster.metadata.removeKeyspace(scc.targetKeyspace); | |
| 91 | + if (removedKeyspace != null) { | |
| 92 | + cluster.executor.submit(new Runnable() { | |
| 93 | + @Override | |
| 94 | + public void run() { | |
| 95 | + cluster.metadata.triggerOnKeyspaceRemoved(removedKeyspace); | |
| 96 | + } | |
| 97 | + }); | |
| 98 | + } | |
| 99 | + break; | |
| 100 | + case TABLE: | |
| 101 | + keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace); | |
| 102 | + if (keyspace == null) | |
| 103 | + logger.warn("Received a DROPPED notification for table {}.{}, but this keyspace is unknown in our metadata", | |
| 104 | + scc.targetKeyspace, scc.targetName); | |
| 105 | + else { | |
| 106 | + final TableMetadata removedTable = keyspace.removeTable(scc.targetName); | |
| 107 | + if (removedTable != null) { | |
| 108 | + cluster.executor.submit(new Runnable() { | |
| 109 | + @Override | |
| 110 | + public void run() { | |
| 111 | + cluster.metadata.triggerOnTableRemoved(removedTable); | |
| 112 | + } | |
| 113 | + }); | |
| 114 | + } | |
| 115 | + } | |
| 116 | + break; | |
| 117 | + case TYPE: | |
| 118 | + keyspace = session.cluster.manager.metadata.getKeyspaceInternal(scc.targetKeyspace); | |
| 119 | + if (keyspace == null) | |
| 120 | + logger.warn("Received a DROPPED notification for UDT {}.{}, but this keyspace is unknown in our metadata", | |
| 121 | + scc.targetKeyspace, scc.targetName); | |
| 122 | + else { | |
| 123 | + final UserType removedType = keyspace.removeUserType(scc.targetName); | |
| 124 | + if (removedType != null) { | |
| 125 | + cluster.executor.submit(new Runnable() { | |
| 126 | + @Override | |
| 127 | + public void run() { | |
| 128 | + cluster.metadata.triggerOnUserTypeRemoved(removedType); | |
| 129 | + } | |
| 130 | + }); | |
| 131 | + } | |
| 132 | + } | |
| 133 | + break; | |
| 134 | + } | |
| 135 | + session.cluster.manager.waitForSchemaAgreementAndSignal(connection, this, rs); | |
| 136 | + break; | |
| 137 | + default: | |
| 138 | + logger.info("Ignoring unknown schema change result"); | |
| 139 | + break; | |
| 140 | + } | |
| 110 | 141 | } |
| 111 | 142 | break; |
| 112 | 143 | default: |
| @@ -180,7 +211,7 @@ | ||
| 180 | 211 | try { |
| 181 | 212 | return Uninterruptibles.getUninterruptibly(this); |
| 182 | 213 | } catch (ExecutionException e) { |
| 183 | - throw extractCauseFromExecutionException(e); | |
| 214 | + throw DriverThrowables.propagateCause(e); | |
| 184 | 215 | } |
| 185 | 216 | } |
| 186 | 217 | |
| @@ -212,7 +243,7 @@ | ||
| 212 | 243 | try { |
| 213 | 244 | return Uninterruptibles.getUninterruptibly(this, timeout, unit); |
| 214 | 245 | } catch (ExecutionException e) { |
| 215 | - throw extractCauseFromExecutionException(e); | |
| 246 | + throw DriverThrowables.propagateCause(e); | |
| 216 | 247 | } |
| 217 | 248 | } |
| 218 | 249 | |
| @@ -259,18 +290,6 @@ | ||
| 259 | 290 | return true; |
| 260 | 291 | } |
| 261 | 292 | |
| 262 | - static RuntimeException extractCauseFromExecutionException(ExecutionException e) { | |
| 263 | - // We could just rethrow e.getCause(). However, the cause of the ExecutionException has likely been | |
| 264 | - // created on the I/O thread receiving the response. Which means that the stacktrace associated | |
| 265 | - // with said cause will make no mention of the current thread. This is painful for say, finding | |
| 266 | - // out which execute() statement actually raised the exception. So instead, we re-create the | |
| 267 | - // exception. | |
| 268 | - if (e.getCause() instanceof DriverException) | |
| 269 | - throw ((DriverException)e.getCause()).copy(); | |
| 270 | - else | |
| 271 | - throw new DriverInternalError("Unexpected exception thrown", e.getCause()); | |
| 272 | - } | |
| 273 | - | |
| 274 | 293 | @Override |
| 275 | 294 | public int retryCount() { |
| 276 | 295 | // 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 @@ | ||
| 18 | 18 | import java.net.InetSocketAddress; |
| 19 | 19 | import java.util.Collections; |
| 20 | 20 | |
| 21 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 22 | + | |
| 21 | 23 | /** |
| 22 | 24 | * Base class for custom {@link Cluster} implementations that wrap another instance (delegate / decorator pattern). |
| 23 | 25 | */ |
| @@ -74,6 +76,16 @@ | ||
| 74 | 76 | return delegate().connect(keyspace); |
| 75 | 77 | } |
| 76 | 78 | |
| 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 | + | |
| 77 | 89 | @Override |
| 78 | 90 | public Metadata getMetadata() { |
| 79 | 91 | 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/Host.java +7 −29
| @@ -36,6 +36,7 @@ | ||
| 36 | 36 | |
| 37 | 37 | private static final Logger logger = LoggerFactory.getLogger(Host.class); |
| 38 | 38 | |
| 39 | + static final Logger statesLogger = LoggerFactory.getLogger(Host.class.getName() + ".STATES"); | |
| 39 | 40 | |
| 40 | 41 | private final InetSocketAddress address; |
| 41 | 42 | |
| @@ -44,7 +45,7 @@ | ||
| 44 | 45 | /** Ensures state change notifications for that host are handled serially */ |
| 45 | 46 | final ReentrantLock notificationsLock = new ReentrantLock(true); |
| 46 | 47 | |
| 47 | - private final ConvictionPolicy policy; | |
| 48 | + final ConvictionPolicy convictionPolicy; | |
| 48 | 49 | private final Cluster.Manager manager; |
| 49 | 50 | |
| 50 | 51 | // Tracks later reconnection attempts to that host so we avoid adding multiple tasks. |
| @@ -67,12 +68,12 @@ | ||
| 67 | 68 | // ClusterMetadata keeps one Host object per inet address and we rely on this (more precisely, |
| 68 | 69 | // we rely on the fact that we can use Object equality as a valid equality), so don't use |
| 69 | 70 | // that constructor but ClusterMetadata.getHost instead. |
| 70 | - Host(InetSocketAddress address, ConvictionPolicy.Factory policy, Cluster.Manager manager) { | |
| 71 | - if (address == null || policy == null) | |
| 71 | + Host(InetSocketAddress address, ConvictionPolicy.Factory convictionPolicyFactory, Cluster.Manager manager) { | |
| 72 | + if (address == null || convictionPolicyFactory == null) | |
| 72 | 73 | throw new NullPointerException(); |
| 73 | 74 | |
| 74 | 75 | this.address = address; |
| 75 | - this.policy = policy.create(this); | |
| 76 | + this.convictionPolicy = convictionPolicyFactory.create(this, manager.reconnectionPolicy()); | |
| 76 | 77 | this.manager = manager; |
| 77 | 78 | this.defaultExecutionInfo = new ExecutionInfo(ImmutableList.of(this)); |
| 78 | 79 | this.state = State.ADDED; |
| @@ -274,17 +275,13 @@ | ||
| 274 | 275 | |
| 275 | 276 | void setDown() { |
| 276 | 277 | state = State.DOWN; |
| 278 | + convictionPolicy.reset(); | |
| 277 | 279 | } |
| 278 | 280 | |
| 279 | 281 | void setUp() { |
| 280 | - policy.reset(); | |
| 281 | 282 | state = State.UP; |
| 282 | 283 | } |
| 283 | 284 | |
| 284 | - boolean signalConnectionFailure(ConnectionException exception) { | |
| 285 | - return policy.addFailure(exception); | |
| 286 | - } | |
| 287 | - | |
| 288 | 285 | /** |
| 289 | 286 | * Interface for listeners that are interested in hosts added, up, down and |
| 290 | 287 | * removed events. |
| @@ -312,26 +309,7 @@ | ||
| 312 | 309 | public void onUp(Host host); |
| 313 | 310 | |
| 314 | 311 | /** |
| 315 | - * Called when a node is suspected to be dead. | |
| 316 | - * <p> | |
| 317 | - * A node is suspected to be dead when an error occurs on one of it's | |
| 318 | - * opened connection. As soon as an host is suspected, a connection attempt | |
| 319 | - * to that host is immediately tried. If this succeed, then it means that | |
| 320 | - * the connection was disfunctional but that the node was not really down. | |
| 321 | - * If this fails however, this means the node is truly dead, onDown() is | |
| 322 | - * called and further reconnection attempts are scheduled according to the | |
| 323 | - * {@link com.datastax.driver.core.policies.ReconnectionPolicy} in place. | |
| 324 | - * <p> | |
| 325 | - * When this event is triggered, it is possible to call the host | |
| 326 | - * {@link #getInitialReconnectionAttemptFuture} method to wait until the | |
| 327 | - * initial and immediate reconnection attempt succeed or fail. | |
| 328 | - * <p> | |
| 329 | - * Note that some StateListener may ignore that event. If a node that | |
| 330 | - * that is suspected down turns out to be truly down (that is, the driver | |
| 331 | - * cannot successfully connect to it right away), then {@link #onDown} will | |
| 332 | - * be called. | |
| 333 | - * | |
| 334 | - * @deprecated the suspicion mechanism has been disabled. This will never | |
| 312 | + * @deprecated the "suspicion" mechanism has been deprecated. This will never | |
| 335 | 313 | * get called. |
| 336 | 314 | */ |
| 337 | 315 | @Deprecated |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +101 −33
| @@ -17,6 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.ArrayList; |
| 19 | 19 | import java.util.List; |
| 20 | +import java.util.ListIterator; | |
| 20 | 21 | import java.util.Set; |
| 21 | 22 | import java.util.concurrent.*; |
| 22 | 23 | import java.util.concurrent.atomic.AtomicInteger; |
| @@ -26,6 +27,7 @@ | ||
| 26 | 27 | import java.util.concurrent.locks.ReentrantLock; |
| 27 | 28 | |
| 28 | 29 | import com.google.common.annotations.VisibleForTesting; |
| 30 | +import com.google.common.base.Throwables; | |
| 29 | 31 | import com.google.common.collect.Lists; |
| 30 | 32 | import com.google.common.util.concurrent.*; |
| 31 | 33 | import org.slf4j.Logger; |
| @@ -39,7 +41,7 @@ | ||
| 39 | 41 | import static com.datastax.driver.core.Connection.State.RESURRECTING; |
| 40 | 42 | import static com.datastax.driver.core.Connection.State.TRASHED; |
| 41 | 43 | |
| 42 | -class HostConnectionPool { | |
| 44 | +class HostConnectionPool implements Connection.Owner { | |
| 43 | 45 | |
| 44 | 46 | private static final Logger logger = LoggerFactory.getLogger(HostConnectionPool.class); |
| 45 | 47 | |
| @@ -103,15 +105,19 @@ | ||
| 103 | 105 | * pool. |
| 104 | 106 | */ |
| 105 | 107 | ListenableFuture<Void> initAsync(Connection reusedConnection) { |
| 108 | + String keyspace = manager.poolsState.keyspace; | |
| 109 | + | |
| 110 | + Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 111 | + | |
| 106 | 112 | // 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++) { | |
| 111 | 117 | Connection connection; |
| 112 | 118 | ListenableFuture<Void> connectionFuture; |
| 113 | 119 | // reuse the existing connection only once |
| 114 | - if (reusedConnection != null && reusedConnection.setPool(this)) { | |
| 120 | + if (reusedConnection != null && reusedConnection.setOwner(this)) { | |
| 115 | 121 | connection = reusedConnection; |
| 116 | 122 | connectionFuture = MoreFutures.VOID_SUCCESS; |
| 117 | 123 | } else { |
| @@ -120,25 +126,32 @@ | ||
| 120 | 126 | } |
| 121 | 127 | reusedConnection = null; |
| 122 | 128 | connections.add(connection); |
| 123 | - connectionFutures.add(connectionFuture); | |
| 129 | + connectionFutures.add(handleErrors(setKeyspaceAsync(connectionFuture, connection, keyspace), initExecutor)); | |
| 124 | 130 | } |
| 125 | 131 | |
| 126 | - Executor initExecutor = manager.cluster.manager.configuration.getPoolingOptions().getInitializationExecutor(); | |
| 127 | - | |
| 128 | 132 | ListenableFuture<List<Void>> allConnectionsFuture = Futures.allAsList(connectionFutures); |
| 129 | 133 | |
| 130 | 134 | final SettableFuture<Void> initFuture = SettableFuture.create(); |
| 131 | 135 | Futures.addCallback(allConnectionsFuture, new FutureCallback<List<Void>>() { |
| 132 | 136 | @Override |
| 133 | 137 | 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 | + | |
| 134 | 145 | HostConnectionPool.this.connections.addAll(connections); |
| 135 | - open.set(l.size()); | |
| 146 | + open.set(connections.size()); | |
| 147 | + | |
| 136 | 148 | if (isClosed()) { |
| 137 | 149 | initFuture.setException(new ConnectionException(host.getSocketAddress(), "Pool was closed during initialization")); |
| 138 | 150 | // we're not sure if closeAsync() saw the connections, so ensure they get closed |
| 139 | 151 | forceClose(connections); |
| 140 | 152 | } 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()); | |
| 142 | 155 | phase.compareAndSet(Phase.INITIALIZING, Phase.READY); |
| 143 | 156 | initFuture.set(null); |
| 144 | 157 | } |
| @@ -154,7 +167,37 @@ | ||
| 154 | 167 | return initFuture; |
| 155 | 168 | } |
| 156 | 169 | |
| 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 | |
| 158 | 201 | private void forceClose(List<Connection> connections) { |
| 159 | 202 | for (Connection connection : connections) { |
| 160 | 203 | connection.closeAsync().force(); |
| @@ -173,16 +216,25 @@ | ||
| 173 | 216 | throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase); |
| 174 | 217 | |
| 175 | 218 | 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; | |
| 181 | 237 | } |
| 182 | - Connection c = waitForConnection(timeout, unit); | |
| 183 | - totalInFlight.incrementAndGet(); | |
| 184 | - c.setKeyspace(manager.poolsState.keyspace); | |
| 185 | - return c; | |
| 186 | 238 | } |
| 187 | 239 | |
| 188 | 240 | int minInFlight = Integer.MAX_VALUE; |
| @@ -226,7 +278,9 @@ | ||
| 226 | 278 | } |
| 227 | 279 | |
| 228 | 280 | 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)) { | |
| 230 | 284 | // Add a connection if we fill the first n-1 connections and almost fill the last one |
| 231 | 285 | int currentCapacity = (connectionCount - 1) * options().getMaxRequestsPerConnection(hostDistance) |
| 232 | 286 | + options().getNewConnectionThreshold(hostDistance); |
| @@ -277,7 +331,7 @@ | ||
| 277 | 331 | |
| 278 | 332 | private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { |
| 279 | 333 | if (timeout == 0) |
| 280 | - throw new TimeoutException(); | |
| 334 | + throw new TimeoutException("All connections are busy and pool timeout is 0"); | |
| 281 | 335 | |
| 282 | 336 | long start = System.nanoTime(); |
| 283 | 337 | long remaining = timeout; |
| @@ -320,7 +374,7 @@ | ||
| 320 | 374 | remaining = timeout - Cluster.timeSince(start, unit); |
| 321 | 375 | } while (remaining > 0); |
| 322 | 376 | |
| 323 | - throw new TimeoutException(); | |
| 377 | + throw new TimeoutException("All connections are busy"); | |
| 324 | 378 | } |
| 325 | 379 | |
| 326 | 380 | public void returnConnection(Connection connection) { |
| @@ -405,8 +459,13 @@ | ||
| 405 | 459 | try { |
| 406 | 460 | Connection newConnection = tryResurrectFromTrash(); |
| 407 | 461 | if (newConnection == null) { |
| 462 | + if (!host.convictionPolicy.canReconnectNow()) { | |
| 463 | + open.decrementAndGet(); | |
| 464 | + return false; | |
| 465 | + } | |
| 408 | 466 | logger.debug("Creating new connection on busy pool to {}", host); |
| 409 | 467 | newConnection = manager.connectionFactory().open(this); |
| 468 | + newConnection.setKeyspace(manager.poolsState.keyspace); | |
| 410 | 469 | } |
| 411 | 470 | connections.add(newConnection); |
| 412 | 471 | |
| @@ -469,6 +528,9 @@ | ||
| 469 | 528 | } |
| 470 | 529 | |
| 471 | 530 | private void maybeSpawnNewConnection() { |
| 531 | + if (!host.convictionPolicy.canReconnectNow()) | |
| 532 | + return; | |
| 533 | + | |
| 472 | 534 | while (true) { |
| 473 | 535 | int inCreation = scheduledForCreation.get(); |
| 474 | 536 | if (inCreation >= MAX_SIMULTANEOUS_CREATION) |
| @@ -480,16 +542,15 @@ | ||
| 480 | 542 | manager.blockingExecutor().submit(newConnectionTask); |
| 481 | 543 | } |
| 482 | 544 | |
| 483 | - void replaceDefunctConnection(final Connection connection) { | |
| 545 | + @Override | |
| 546 | + public void onConnectionDefunct(final Connection connection) { | |
| 484 | 547 | if (connection.state.compareAndSet(OPEN, GONE)) |
| 485 | 548 | 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 | |
| 493 | 554 | } |
| 494 | 555 | |
| 495 | 556 | void cleanupIdleConnections(long now) { |
| @@ -608,6 +669,9 @@ | ||
| 608 | 669 | if (isClosed()) |
| 609 | 670 | return; |
| 610 | 671 | |
| 672 | + if (!host.convictionPolicy.canReconnectNow()) | |
| 673 | + return; | |
| 674 | + | |
| 611 | 675 | // Note: this process is a bit racy, but it doesn't matter since we're still guaranteed to not create |
| 612 | 676 | // more connection than maximum (and if we create more than core connection due to a race but this isn't |
| 613 | 677 | // justified by the load, the connection in excess will be quickly trashed anyway) |
| @@ -623,7 +687,11 @@ | ||
| 623 | 687 | static class PoolState { |
| 624 | 688 | volatile String keyspace; |
| 625 | 689 | |
| 626 | - public void setKeyspace(String keyspace) { | |
| 690 | + PoolState(String keyspace) { | |
| 691 | + this.keyspace = keyspace; | |
| 692 | + } | |
| 693 | + | |
| 694 | + void setKeyspace(String keyspace) { | |
| 627 | 695 | this.keyspace = keyspace; |
| 628 | 696 | } |
| 629 | 697 | } |
modified driver-core/src/main/java/com/datastax/driver/core/KeyspaceMetadata.java +43 −21
| @@ -34,10 +34,8 @@ | ||
| 34 | 34 | private final ReplicationStrategy strategy; |
| 35 | 35 | private final Map<String, String> replication; |
| 36 | 36 | |
| 37 | - // TODO: I don't think we change those, so there is probably no need for ConcurrentHashMap. Check if | |
| 38 | - // that's the case. | |
| 39 | - private final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>(); | |
| 40 | - private final Map<String, UserType> userTypes = new ConcurrentHashMap<String, UserType>(); | |
| 37 | + final Map<String, TableMetadata> tables = new ConcurrentHashMap<String, TableMetadata>(); | |
| 38 | + final Map<String, UserType> userTypes = new ConcurrentHashMap<String, UserType>(); | |
| 41 | 39 | |
| 42 | 40 | private KeyspaceMetadata(String name, boolean durableWrites, Map<String, String> replication) { |
| 43 | 41 | this.name = name; |
| @@ -46,7 +44,7 @@ | ||
| 46 | 44 | this.strategy = ReplicationStrategy.create(replication); |
| 47 | 45 | } |
| 48 | 46 | |
| 49 | - static KeyspaceMetadata build(Row row, List<Row> udtRows) { | |
| 47 | + static KeyspaceMetadata build(Row row) { | |
| 50 | 48 | |
| 51 | 49 | String name = row.getString(KS_NAME); |
| 52 | 50 | boolean durableWrites = row.getBool(DURABLE_WRITES); |
| @@ -57,11 +55,6 @@ | ||
| 57 | 55 | |
| 58 | 56 | KeyspaceMetadata ksm = new KeyspaceMetadata(name, durableWrites, replicationOptions); |
| 59 | 57 | |
| 60 | - if (udtRows == null) | |
| 61 | - return ksm; | |
| 62 | - | |
| 63 | - ksm.addUserTypes(udtRows); | |
| 64 | - | |
| 65 | 58 | return ksm; |
| 66 | 59 | } |
| 67 | 60 | |
| @@ -104,8 +97,8 @@ | ||
| 104 | 97 | return tables.get(Metadata.handleId(name)); |
| 105 | 98 | } |
| 106 | 99 | |
| 107 | - void removeTable(String table) { | |
| 108 | - tables.remove(table); | |
| 100 | + TableMetadata removeTable(String table) { | |
| 101 | + return tables.remove(table); | |
| 109 | 102 | } |
| 110 | 103 | |
| 111 | 104 | /** |
| @@ -139,15 +132,8 @@ | ||
| 139 | 132 | return Collections.<UserType>unmodifiableCollection(userTypes.values()); |
| 140 | 133 | } |
| 141 | 134 | |
| 142 | - void addUserTypes(List<Row> udtRows) { | |
| 143 | - for (Row r : udtRows) { | |
| 144 | - UserType def = UserType.build(r); | |
| 145 | - userTypes.put(def.getTypeName(), def); | |
| 146 | - } | |
| 147 | - } | |
| 148 | - | |
| 149 | - void removeUserType(String userType) { | |
| 150 | - userTypes.remove(userType); | |
| 135 | + UserType removeUserType(String userType) { | |
| 136 | + return userTypes.remove(userType); | |
| 151 | 137 | } |
| 152 | 138 | |
| 153 | 139 | /** |
| @@ -207,11 +193,47 @@ | ||
| 207 | 193 | return asCQLQuery(); |
| 208 | 194 | } |
| 209 | 195 | |
| 196 | + @Override | |
| 197 | + public boolean equals(Object o) { | |
| 198 | + if (this == o) | |
| 199 | + return true; | |
| 200 | + if (o == null || getClass() != o.getClass()) | |
| 201 | + return false; | |
| 202 | + | |
| 203 | + KeyspaceMetadata that = (KeyspaceMetadata)o; | |
| 204 | + | |
| 205 | + if (durableWrites != that.durableWrites) | |
| 206 | + return false; | |
| 207 | + if (!name.equals(that.name)) | |
| 208 | + return false; | |
| 209 | + if (strategy != null ? !strategy.equals(that.strategy) : that.strategy != null) | |
| 210 | + return false; | |
| 211 | + if (!replication.equals(that.replication)) | |
| 212 | + return false; | |
| 213 | + return tables.equals(that.tables); | |
| 214 | + | |
| 215 | + } | |
| 216 | + | |
| 217 | + @Override | |
| 218 | + public int hashCode() { | |
| 219 | + int result = name.hashCode(); | |
| 220 | + result = 31 * result + (durableWrites ? 1 : 0); | |
| 221 | + result = 31 * result + (strategy != null ? strategy.hashCode() : 0); | |
| 222 | + result = 31 * result + replication.hashCode(); | |
| 223 | + result = 31 * result + tables.hashCode(); | |
| 224 | + return result; | |
| 225 | + } | |
| 226 | + | |
| 210 | 227 | void add(TableMetadata tm) { |
| 211 | 228 | tables.put(tm.getName(), tm); |
| 212 | 229 | } |
| 213 | 230 | |
| 231 | + void add(UserType type) { | |
| 232 | + userTypes.put(type.getTypeName(), type); | |
| 233 | + } | |
| 234 | + | |
| 214 | 235 | ReplicationStrategy replicationStrategy() { |
| 215 | 236 | return strategy; |
| 216 | 237 | } |
| 238 | + | |
| 217 | 239 | } |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +305 −126
| @@ -57,141 +57,296 @@ | ||
| 57 | 57 | |
| 58 | 58 | // Synchronized to make it easy to detect dropped keyspaces |
| 59 | 59 | synchronized void rebuildSchema(SchemaElement targetType, String targetKeyspace, String targetName, ResultSet ks, ResultSet udts, ResultSet cfs, ResultSet cols, VersionNumber cassandraVersion) { |
| 60 | - | |
| 61 | - Map<String, List<Row>> cfDefs = new HashMap<String, List<Row>>(); | |
| 62 | - Map<String, List<Row>> udtDefs = new HashMap<String, List<Row>>(); | |
| 63 | - Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>(); | |
| 64 | - | |
| 65 | - // Gather cf defs | |
| 66 | - if (cfs != null) { | |
| 67 | - for (Row row : cfs) { | |
| 68 | - String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 69 | - List<Row> l = cfDefs.get(ksName); | |
| 70 | - if (l == null) { | |
| 71 | - l = new ArrayList<Row>(); | |
| 72 | - cfDefs.put(ksName, l); | |
| 73 | - } | |
| 74 | - l.add(row); | |
| 75 | - } | |
| 76 | - } | |
| 77 | - | |
| 78 | - // Gather udt defs | |
| 79 | - if (udts != null) { | |
| 80 | - for (Row row : udts) { | |
| 81 | - String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 82 | - List<Row> l = udtDefs.get(ksName); | |
| 83 | - if (l == null) { | |
| 84 | - l = new ArrayList<Row>(); | |
| 85 | - udtDefs.put(ksName, l); | |
| 86 | - } | |
| 87 | - l.add(row); | |
| 88 | - } | |
| 89 | - } | |
| 90 | - | |
| 91 | - // Gather columns per Cf | |
| 92 | - if (cols != null) { | |
| 93 | - for (Row row : cols) { | |
| 94 | - String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 95 | - String cfName = row.getString(TableMetadata.CF_NAME); | |
| 96 | - Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = colsDefs.get(ksName); | |
| 97 | - if (colsByCf == null) { | |
| 98 | - colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>(); | |
| 99 | - colsDefs.put(ksName, colsByCf); | |
| 100 | - } | |
| 101 | - Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName); | |
| 102 | - if (l == null) { | |
| 103 | - l = new HashMap<String, ColumnMetadata.Raw>(); | |
| 104 | - colsByCf.put(cfName, l); | |
| 105 | - } | |
| 106 | - ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion); | |
| 107 | - l.put(c.name, c); | |
| 108 | - } | |
| 109 | - } | |
| 110 | - | |
| 111 | - 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, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs = groupByKeyspaceAndTable(cols, cassandraVersion); | |
| 63 | + if (targetType == null || targetType == KEYSPACE) { | |
| 64 | + // building the whole schema or a keyspace | |
| 112 | 65 | assert ks != null; |
| 113 | - Set<String> addedKs = new HashSet<String>(); | |
| 114 | - for (Row ksRow : ks) { | |
| 115 | - String ksName = ksRow.getString(KeyspaceMetadata.KS_NAME); | |
| 116 | - KeyspaceMetadata ksm = KeyspaceMetadata.build(ksRow, udtDefs.get(ksName)); | |
| 117 | - | |
| 118 | - if (cfDefs.containsKey(ksName)) { | |
| 119 | - buildTableMetadata(ksm, cfDefs.get(ksName), colsDefs.get(ksName), cassandraVersion); | |
| 120 | - } | |
| 121 | - addedKs.add(ksName); | |
| 122 | - keyspaces.put(ksName, ksm); | |
| 123 | - } | |
| 124 | - | |
| 125 | - // If keyspace is null, it means we're rebuilding from scratch, so | |
| 126 | - // remove anything that was not just added as it means it's a dropped keyspace | |
| 127 | - if (targetKeyspace == null) { | |
| 128 | - Iterator<String> iter = keyspaces.keySet().iterator(); | |
| 129 | - while (iter.hasNext()) { | |
| 130 | - if (!addedKs.contains(iter.next())) | |
| 131 | - iter.remove(); | |
| 132 | - } | |
| 133 | - } | |
| 66 | + Map<String, KeyspaceMetadata> keyspaces = buildKeyspaces(ks, tableRows, colsDefs, udtRows, cassandraVersion); | |
| 67 | + updateKeyspaces(this.keyspaces, keyspaces, targetKeyspace); | |
| 134 | 68 | } else if (targetType == TABLE) { |
| 135 | 69 | assert targetKeyspace != null; |
| 136 | - KeyspaceMetadata ksm = keyspaces.get(targetKeyspace); | |
| 137 | - | |
| 70 | + KeyspaceMetadata keyspace = this.keyspaces.get(targetKeyspace); | |
| 138 | 71 | // If we update a keyspace we don't know about, something went |
| 139 | - // wrong. Log an error an schedule a full schema rebuilt. | |
| 140 | - if (ksm == null) { | |
| 141 | - logger.error(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s", targetKeyspace, targetName, targetKeyspace)); | |
| 72 | + // wrong. Log an error and schedule a full schema rebuild. | |
| 73 | + if (keyspace == null) { | |
| 74 | + logger.info(String.format("Asked to rebuild table %s.%s but I don't know keyspace %s", targetKeyspace, targetName, targetKeyspace)); | |
| 142 | 75 | cluster.submitSchemaRefresh(null, null, null); |
| 143 | 76 | return; |
| 144 | 77 | } |
| 145 | - | |
| 146 | - if (cfDefs.containsKey(targetKeyspace)) | |
| 147 | - buildTableMetadata(ksm, cfDefs.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion); | |
| 78 | + if (tableRows.containsKey(targetKeyspace)) { | |
| 79 | + Map<String, TableMetadata> tables = buildTables(keyspace, tableRows.get(targetKeyspace), colsDefs.get(targetKeyspace), cassandraVersion); | |
| 80 | + updateTables(keyspace.tables, tables, targetName); | |
| 81 | + } | |
| 148 | 82 | } else if (targetType == TYPE) { |
| 149 | 83 | assert targetKeyspace != null; |
| 150 | - KeyspaceMetadata ksm = keyspaces.get(targetKeyspace); | |
| 151 | - | |
| 152 | - if (ksm == null) { | |
| 153 | - logger.error(String.format("Asked to rebuild type %s.%s but I don't know keyspace %s", targetKeyspace, targetName, targetKeyspace)); | |
| 84 | + KeyspaceMetadata keyspace = this.keyspaces.get(targetKeyspace); | |
| 85 | + if (keyspace == null) { | |
| 86 | + logger.info(String.format("Asked to rebuild UDT %s.%s but I don't know keyspace %s", targetKeyspace, targetName, targetKeyspace)); | |
| 154 | 87 | cluster.submitSchemaRefresh(null, null, null); |
| 155 | 88 | return; |
| 156 | 89 | } |
| 90 | + if (udtRows.containsKey(targetKeyspace)) { | |
| 91 | + Map<String, UserType> userTypes = buildUserTypes(keyspace, udtRows.get(targetKeyspace), cassandraVersion); | |
| 92 | + updateUserTypes(keyspace.userTypes, userTypes, targetName); | |
| 93 | + } | |
| 94 | + } | |
| 95 | + } | |
| 96 | + | |
| 97 | + private Map<String, List<Row>> groupByKeyspace(ResultSet rows) { | |
| 98 | + if (rows == null) | |
| 99 | + return Collections.emptyMap(); | |
| 100 | + | |
| 101 | + Map<String, List<Row>> groupedRows = new HashMap<String, List<Row>>(); | |
| 102 | + for (Row row : rows) { | |
| 103 | + String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 104 | + List<Row> l = groupedRows.get(ksName); | |
| 105 | + if (l == null) { | |
| 106 | + l = new ArrayList<Row>(); | |
| 107 | + groupedRows.put(ksName, l); | |
| 108 | + } | |
| 109 | + l.add(row); | |
| 110 | + } | |
| 111 | + return groupedRows; | |
| 112 | + } | |
| 113 | + | |
| 114 | + private Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupByKeyspaceAndTable(ResultSet rows, VersionNumber cassandraVersion) { | |
| 115 | + if (rows == null) | |
| 116 | + return Collections.emptyMap(); | |
| 117 | + | |
| 118 | + Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> groupedRows = new HashMap<String, Map<String, Map<String, ColumnMetadata.Raw>>>(); | |
| 119 | + for (Row row : rows) { | |
| 120 | + String ksName = row.getString(KeyspaceMetadata.KS_NAME); | |
| 121 | + String cfName = row.getString(TableMetadata.CF_NAME); | |
| 122 | + Map<String, Map<String, ColumnMetadata.Raw>> colsByCf = groupedRows.get(ksName); | |
| 123 | + if (colsByCf == null) { | |
| 124 | + colsByCf = new HashMap<String, Map<String, ColumnMetadata.Raw>>(); | |
| 125 | + groupedRows.put(ksName, colsByCf); | |
| 126 | + } | |
| 127 | + Map<String, ColumnMetadata.Raw> l = colsByCf.get(cfName); | |
| 128 | + if (l == null) { | |
| 129 | + l = new HashMap<String, ColumnMetadata.Raw>(); | |
| 130 | + colsByCf.put(cfName, l); | |
| 131 | + } | |
| 132 | + ColumnMetadata.Raw c = ColumnMetadata.Raw.fromRow(row, cassandraVersion); | |
| 133 | + l.put(c.name, c); | |
| 134 | + } | |
| 135 | + return groupedRows; | |
| 136 | + } | |
| 157 | 137 | |
| 158 | - if (udtDefs.containsKey(targetKeyspace)) | |
| 159 | - ksm.addUserTypes(udtDefs.get(targetKeyspace)); | |
| 160 | - } | |
| 138 | + private Map<String, KeyspaceMetadata> buildKeyspaces(ResultSet keyspaceRows, | |
| 139 | + Map<String, List<Row>> tableRows, | |
| 140 | + Map<String, Map<String, Map<String, ColumnMetadata.Raw>>> colsDefs, | |
| 141 | + Map<String, List<Row>> udtRows, | |
| 142 | + VersionNumber cassandraVersion) { | |
| 143 | + Map<String, KeyspaceMetadata> keyspaces = new LinkedHashMap<String, KeyspaceMetadata>(); | |
| 144 | + for (Row keyspaceRow : keyspaceRows) { | |
| 145 | + KeyspaceMetadata keyspace = KeyspaceMetadata.build(keyspaceRow); | |
| 146 | + Map<String, TableMetadata> tables = buildTables(keyspace, tableRows.get(keyspace.getName()), colsDefs.get(keyspace.getName()), cassandraVersion); | |
| 147 | + for (TableMetadata table : tables.values()) { | |
| 148 | + keyspace.add(table); | |
| 149 | + } | |
| 150 | + Map<String, UserType> userTypes = buildUserTypes(keyspace, udtRows.get(keyspace.getName()), cassandraVersion); | |
| 151 | + for (UserType userType : userTypes.values()) { | |
| 152 | + keyspace.add(userType); | |
| 153 | + } | |
| 154 | + keyspaces.put(keyspace.getName(), keyspace); | |
| 155 | + } | |
| 156 | + return keyspaces; | |
| 161 | 157 | } |
| 162 | 158 | |
| 163 | - private void buildTableMetadata(KeyspaceMetadata ksm, List<Row> cfRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) { | |
| 164 | - for (Row cfRow : cfRows) { | |
| 165 | - String cfName = cfRow.getString(TableMetadata.CF_NAME); | |
| 166 | - try { | |
| 167 | - Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName); | |
| 168 | - if (cols == null || cols.isEmpty()) { | |
| 169 | - if (cassandraVersion.getMajor() >= 2) { | |
| 170 | - // In C* >= 2.0, we should never have no columns metadata because at the very least we should | |
| 171 | - // have the metadata corresponding to the default CQL metadata. So if we don't have any columns, | |
| 172 | - // that can only mean that the table got creating concurrently with our schema queries, and the | |
| 173 | - // query for columns metadata reached the node before the table was persisted while the table | |
| 174 | - // metadata one reached it afterwards. We could make the query to the column metadata sequential | |
| 175 | - // with the table metadata instead of in parallel, but it's probably not worth making it slower | |
| 176 | - // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the | |
| 177 | - // incomplete table here for now and it'll get updated next time with no particular consequence | |
| 178 | - // (if the table creation was concurrent with our querying, we'll get a notifciation later and | |
| 179 | - // will reupdate the schema for it anyway). See JAVA-320 for why we need this. | |
| 180 | - continue; | |
| 181 | - } else { | |
| 182 | - // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thirft | |
| 183 | - // tables). But in that case TableMetadata.build() knows how to handle it. | |
| 184 | - cols = Collections.<String, ColumnMetadata.Raw>emptyMap(); | |
| 159 | + private Map<String, TableMetadata> buildTables(KeyspaceMetadata keyspace, List<Row> tableRows, Map<String, Map<String, ColumnMetadata.Raw>> colsDefs, VersionNumber cassandraVersion) { | |
| 160 | + Map<String, TableMetadata> tables = new LinkedHashMap<String, TableMetadata>(); | |
| 161 | + if(tableRows != null) { | |
| 162 | + for (Row tableDef : tableRows) { | |
| 163 | + String cfName = tableDef.getString(TableMetadata.CF_NAME); | |
| 164 | + try { | |
| 165 | + Map<String, ColumnMetadata.Raw> cols = colsDefs == null ? null : colsDefs.get(cfName); | |
| 166 | + if (cols == null || cols.isEmpty()) { | |
| 167 | + if (cassandraVersion.getMajor() >= 2) { | |
| 168 | + // In C* >= 2.0, we should never have no columns metadata because at the very least we should | |
| 169 | + // have the metadata corresponding to the default CQL metadata. So if we don't have any columns, | |
| 170 | + // that can only mean that the table got creating concurrently with our schema queries, and the | |
| 171 | + // query for columns metadata reached the node before the table was persisted while the table | |
| 172 | + // metadata one reached it afterwards. We could make the query to the column metadata sequential | |
| 173 | + // with the table metadata instead of in parallel, but it's probably not worth making it slower | |
| 174 | + // all the time to avoid this race since 1) it's very very uncommon and 2) we can just ignore the | |
| 175 | + // incomplete table here for now and it'll get updated next time with no particular consequence | |
| 176 | + // (if the table creation was concurrent with our querying, we'll get a notifciation later and | |
| 177 | + // will reupdate the schema for it anyway). See JAVA-320 for why we need this. | |
| 178 | + continue; | |
| 179 | + } else { | |
| 180 | + // C* 1.2 don't persists default CQL metadata, so it's possible not to have columns (for thirft | |
| 181 | + // tables). But in that case TableMetadata.build() knows how to handle it. | |
| 182 | + cols = Collections.emptyMap(); | |
| 183 | + } | |
| 185 | 184 | } |
| 185 | + TableMetadata table = TableMetadata.build(keyspace, tableDef, cols, cassandraVersion); | |
| 186 | + tables.put(table.getName(), table); | |
| 187 | + } catch (RuntimeException e) { | |
| 188 | + // See ControlConnection#refreshSchema for why we'd rather not probably this further | |
| 189 | + logger.error(String.format("Error parsing schema for table %s.%s: " | |
| 190 | + + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete", | |
| 191 | + keyspace.getName(), cfName, keyspace.getName(), cfName), e); | |
| 186 | 192 | } |
| 187 | - TableMetadata.build(ksm, cfRow, cols, cassandraVersion); | |
| 188 | - } catch (RuntimeException e) { | |
| 189 | - // See ControlConnection#refreshSchema for why we'd rather not probably this further | |
| 190 | - logger.error(String.format("Error parsing schema for table %s.%s: " | |
| 191 | - + "Cluster.getMetadata().getKeyspace(\"%s\").getTable(\"%s\") will be missing or incomplete", | |
| 192 | - ksm.getName(), cfName, ksm.getName(), cfName), e); | |
| 193 | 193 | } |
| 194 | 194 | } |
| 195 | + return tables; | |
| 196 | + } | |
| 197 | + | |
| 198 | + private Map<String, UserType> buildUserTypes(KeyspaceMetadata keyspace, List<Row> udtRows, VersionNumber cassandraVersion) { | |
| 199 | + Map<String, UserType> userTypes = new LinkedHashMap<String, UserType>(); | |
| 200 | + if (udtRows != null) { | |
| 201 | + for (Row udtRow : udtRows) { | |
| 202 | + UserType type = UserType.build(udtRow); | |
| 203 | + userTypes.put(type.getTypeName(), type); | |
| 204 | + } | |
| 205 | + } | |
| 206 | + return userTypes; | |
| 207 | + } | |
| 208 | + | |
| 209 | + /** | |
| 210 | + * Update {@code oldKeyspaces} with the changes contained in {@code newKeyspaces}. | |
| 211 | + * This method also takes care of triggering the relevant events | |
| 212 | + * as the updates take place. | |
| 213 | + * | |
| 214 | + * @param oldKeyspaces the set of keyspaces to be updated. | |
| 215 | + * @param newKeyspaces the temporary set of keyspaces built with information gathered | |
| 216 | + * from schema tables. | |
| 217 | + * @param keyspaceToRebuild If we are rebuilding just one keyspace, the update operation will be limited | |
| 218 | + * to this keyspace only (in which case {@code newKeyspaces} shoudl contain only one entry for it) | |
| 219 | + */ | |
| 220 | + private void updateKeyspaces(Map<String, KeyspaceMetadata> oldKeyspaces, Map<String, KeyspaceMetadata> newKeyspaces, String keyspaceToRebuild) { | |
| 221 | + Iterator<KeyspaceMetadata> it = oldKeyspaces.values().iterator(); | |
| 222 | + while (it.hasNext()) { | |
| 223 | + KeyspaceMetadata oldKeyspace = it.next(); | |
| 224 | + String keyspaceName = oldKeyspace.getName(); | |
| 225 | + // If we're rebuilding only a single keyspace, we should only consider that one | |
| 226 | + // because newKeyspaces will only contain that keyspace. | |
| 227 | + if ((keyspaceToRebuild == null || keyspaceToRebuild.equals(keyspaceName)) && !newKeyspaces.containsKey(keyspaceName)) { | |
| 228 | + it.remove(); | |
| 229 | + triggerOnKeyspaceRemoved(oldKeyspace); | |
| 230 | + } | |
| 231 | + } | |
| 232 | + for (KeyspaceMetadata newKeyspace : newKeyspaces.values()) { | |
| 233 | + KeyspaceMetadata oldKeyspace = oldKeyspaces.put(newKeyspace.getName(), newKeyspace); | |
| 234 | + if (oldKeyspace == null) { | |
| 235 | + triggerOnKeyspaceAdded(newKeyspace); | |
| 236 | + } else if (!oldKeyspace.equals(newKeyspace)) { | |
| 237 | + triggerOnKeyspaceChanged(newKeyspace, oldKeyspace); | |
| 238 | + } | |
| 239 | + Map<String, TableMetadata> oldTables = oldKeyspace == null ? new HashMap<String, TableMetadata>() : oldKeyspace.tables; | |
| 240 | + Map<String, TableMetadata> newTables = newKeyspace.tables; | |
| 241 | + updateTables(oldTables, newTables, null); | |
| 242 | + } | |
| 243 | + } | |
| 244 | + | |
| 245 | + /** | |
| 246 | + * Update {@code oldTables} with the changes contained in {@code newTables}. | |
| 247 | + * This method also takes care of triggering the relevant events | |
| 248 | + * as the updates take place. | |
| 249 | + * | |
| 250 | + * @param oldTables the set of tables to be updated. | |
| 251 | + * @param newTables the temporary set of tables built with information gathered | |
| 252 | + * from schema tables. | |
| 253 | + * @param tableToRebuild If we are rebuilding just one table, the update operation will be limited | |
| 254 | + * to this table only (in which case {@code newTables} shoudl contain only one entry for it) | |
| 255 | + */ | |
| 256 | + private void updateTables(Map<String, TableMetadata> oldTables, Map<String, TableMetadata> newTables, String tableToRebuild) { | |
| 257 | + Iterator<TableMetadata> it = oldTables.values().iterator(); | |
| 258 | + while (it.hasNext()) { | |
| 259 | + TableMetadata oldTable = it.next(); | |
| 260 | + String tableName = oldTable.getName(); | |
| 261 | + // If we're rebuilding only a single table, we should only consider that one | |
| 262 | + // because newTables will only contain that table. | |
| 263 | + if ((tableToRebuild == null || tableToRebuild.equals(tableName)) && !newTables.containsKey(tableName)) { | |
| 264 | + it.remove(); | |
| 265 | + triggerOnTableRemoved(oldTable); | |
| 266 | + } | |
| 267 | + } | |
| 268 | + for (TableMetadata newTable : newTables.values()) { | |
| 269 | + TableMetadata oldTable = oldTables.put(newTable.getName(), newTable); | |
| 270 | + if (oldTable == null) { | |
| 271 | + triggerOnTableAdded(newTable); | |
| 272 | + } else if (!oldTable.equals(newTable)) { | |
| 273 | + triggerOnTableChanged(newTable, oldTable); | |
| 274 | + } | |
| 275 | + } | |
| 276 | + } | |
| 277 | + | |
| 278 | + private void updateUserTypes(Map<String, UserType> oldTypes, Map<String, UserType> newTypes, String typeToRebuild) { | |
| 279 | + Iterator<UserType> it = oldTypes.values().iterator(); | |
| 280 | + while (it.hasNext()) { | |
| 281 | + UserType oldType = it.next(); | |
| 282 | + String typeName = oldType.getTypeName(); | |
| 283 | + if ((typeToRebuild == null || typeToRebuild.equals(typeName)) && !newTypes.containsKey(typeName)) { | |
| 284 | + it.remove(); | |
| 285 | + triggerOnUserTypeRemoved(oldType); | |
| 286 | + } | |
| 287 | + } | |
| 288 | + for (UserType newType : newTypes.values()) { | |
| 289 | + UserType oldType = oldTypes.put(newType.getTypeName(), newType); | |
| 290 | + if (oldType == null) { | |
| 291 | + triggerOnUserTypeAdded(newType); | |
| 292 | + } else if (!newType.equals(oldType)) { | |
| 293 | + triggerOnUserTypeChanged(newType, oldType); | |
| 294 | + } | |
| 295 | + } | |
| 296 | + } | |
| 297 | + | |
| 298 | + void triggerOnKeyspaceAdded(KeyspaceMetadata keyspace) { | |
| 299 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 300 | + listener.onKeyspaceAdded(keyspace); | |
| 301 | + } | |
| 302 | + } | |
| 303 | + | |
| 304 | + void triggerOnKeyspaceChanged(KeyspaceMetadata current, KeyspaceMetadata previous) { | |
| 305 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 306 | + listener.onKeyspaceChanged(current, previous); | |
| 307 | + } | |
| 308 | + } | |
| 309 | + | |
| 310 | + void triggerOnKeyspaceRemoved(KeyspaceMetadata keyspace) { | |
| 311 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 312 | + listener.onKeyspaceRemoved(keyspace); | |
| 313 | + } | |
| 314 | + } | |
| 315 | + | |
| 316 | + void triggerOnTableAdded(TableMetadata table) { | |
| 317 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 318 | + listener.onTableAdded(table); | |
| 319 | + } | |
| 320 | + } | |
| 321 | + | |
| 322 | + void triggerOnTableChanged(TableMetadata current, TableMetadata previous) { | |
| 323 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 324 | + listener.onTableChanged(current, previous); | |
| 325 | + } | |
| 326 | + } | |
| 327 | + | |
| 328 | + void triggerOnTableRemoved(TableMetadata table) { | |
| 329 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 330 | + listener.onTableRemoved(table); | |
| 331 | + } | |
| 332 | + } | |
| 333 | + | |
| 334 | + void triggerOnUserTypeAdded(UserType type) { | |
| 335 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 336 | + listener.onUserTypeAdded(type); | |
| 337 | + } | |
| 338 | + } | |
| 339 | + | |
| 340 | + void triggerOnUserTypeChanged(UserType current, UserType previous) { | |
| 341 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 342 | + listener.onUserTypeChanged(current, previous); | |
| 343 | + } | |
| 344 | + } | |
| 345 | + | |
| 346 | + void triggerOnUserTypeRemoved(UserType type) { | |
| 347 | + for (SchemaChangeListener listener : cluster.schemaChangeListeners) { | |
| 348 | + listener.onUserTypeRemoved(type); | |
| 349 | + } | |
| 195 | 350 | } |
| 196 | 351 | |
| 197 | 352 | synchronized void rebuildTokenMap(String partitioner, Map<Host, Collection<String>> allTokens) { |
| @@ -278,7 +433,8 @@ | ||
| 278 | 433 | * connection, when schema or ring topology changes. It might occasionally |
| 279 | 434 | * be stale. |
| 280 | 435 | * |
| 281 | - * @return the token ranges. | |
| 436 | + * @return the token ranges. Note that the result might be stale or empty if | |
| 437 | + * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 282 | 438 | */ |
| 283 | 439 | public Set<TokenRange> getTokenRanges() { |
| 284 | 440 | TokenMap current = tokenMap; |
| @@ -296,7 +452,8 @@ | ||
| 296 | 452 | * @param keyspace the name of the keyspace to get token ranges for. |
| 297 | 453 | * @param host the host. |
| 298 | 454 | * @return the (immutable) set of token ranges for {@code host} as known |
| 299 | - * by the driver. | |
| 455 | + * by the driver. Note that the result might be stale or empty if metadata | |
| 456 | + * was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 300 | 457 | */ |
| 301 | 458 | public Set<TokenRange> getTokenRanges(String keyspace, Host host) { |
| 302 | 459 | keyspace = handleId(keyspace); |
| @@ -325,7 +482,8 @@ | ||
| 325 | 482 | * @param partitionKey the partition key for which to find the set of |
| 326 | 483 | * replica. |
| 327 | 484 | * @return the (immutable) set of replicas for {@code partitionKey} as known |
| 328 | - * by the driver. | |
| 485 | + * by the driver. Note that the result might be stale or empty if metadata was | |
| 486 | + * explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 329 | 487 | */ |
| 330 | 488 | public Set<Host> getReplicas(String keyspace, ByteBuffer partitionKey) { |
| 331 | 489 | keyspace = handleId(keyspace); |
| @@ -348,6 +506,8 @@ | ||
| 348 | 506 | * @param keyspace the name of the keyspace to get replicas for. |
| 349 | 507 | * @param range the token range. |
| 350 | 508 | * @return the (immutable) set of replicas for {@code range} as known by the driver. |
| 509 | + * Note that the result might be stale or empty if metadata was explicitly disabled | |
| 510 | + * with {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 351 | 511 | */ |
| 352 | 512 | public Set<Host> getReplicas(String keyspace, TokenRange range) { |
| 353 | 513 | keyspace = handleId(keyspace); |
| @@ -397,7 +557,12 @@ | ||
| 397 | 557 | * (for example, if the control connection is down). |
| 398 | 558 | */ |
| 399 | 559 | public boolean checkSchemaAgreement() { |
| 400 | - return cluster.controlConnection.checkSchemaAgreement(); | |
| 560 | + try { | |
| 561 | + return cluster.controlConnection.checkSchemaAgreement(); | |
| 562 | + } catch (Exception e) { | |
| 563 | + logger.warn("Error while checking schema agreement", e); | |
| 564 | + return false; | |
| 565 | + } | |
| 401 | 566 | } |
| 402 | 567 | |
| 403 | 568 | /** |
| @@ -406,7 +571,8 @@ | ||
| 406 | 571 | * @param keyspace the name of the keyspace for which metadata should be |
| 407 | 572 | * returned. |
| 408 | 573 | * @return the metadata of the requested keyspace or {@code null} if {@code |
| 409 | - * keyspace} is not a known keyspace. | |
| 574 | + * keyspace} is not a known keyspace. Note that the result might be stale or null if | |
| 575 | + * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 410 | 576 | */ |
| 411 | 577 | public KeyspaceMetadata getKeyspace(String keyspace) { |
| 412 | 578 | return keyspaces.get(handleId(keyspace)); |
| @@ -420,16 +586,18 @@ | ||
| 420 | 586 | return keyspaces.get(keyspace); |
| 421 | 587 | } |
| 422 | 588 | |
| 423 | - void removeKeyspace(String keyspace) { | |
| 424 | - keyspaces.remove(keyspace); | |
| 589 | + KeyspaceMetadata removeKeyspace(String keyspace) { | |
| 590 | + KeyspaceMetadata removed = keyspaces.remove(keyspace); | |
| 425 | 591 | if (tokenMap != null) |
| 426 | 592 | tokenMap.tokenToHosts.remove(keyspace); |
| 593 | + return removed; | |
| 427 | 594 | } |
| 428 | 595 | |
| 429 | 596 | /** |
| 430 | 597 | * Returns a list of all the defined keyspaces. |
| 431 | 598 | * |
| 432 | - * @return a list of all the defined keyspaces. | |
| 599 | + * @return a list of all the defined keyspaces. Note that the result might be stale or empty if | |
| 600 | + * metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 433 | 601 | */ |
| 434 | 602 | public List<KeyspaceMetadata> getKeyspaces() { |
| 435 | 603 | return new ArrayList<KeyspaceMetadata>(keyspaces.values()); |
| @@ -445,6 +613,9 @@ | ||
| 445 | 613 | * Note that the returned String is formatted to be human readable (for |
| 446 | 614 | * some definition of human readable at least). |
| 447 | 615 | * |
| 616 | + * It might be stale or empty if metadata was explicitly disabled with | |
| 617 | + * {@link QueryOptions#setMetadataEnabled(boolean)}. | |
| 618 | + * | |
| 448 | 619 | * @return the CQL queries representing this cluster schema as a {code |
| 449 | 620 | * String}. |
| 450 | 621 | */ |
| @@ -463,11 +634,15 @@ | ||
| 463 | 634 | * |
| 464 | 635 | * @param tokenStr the string representation. |
| 465 | 636 | * @return the token. |
| 637 | + * | |
| 638 | + * @throws IllegalStateException if the token factory was not initialized. This would typically | |
| 639 | + * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)} | |
| 640 | + * before startup. | |
| 466 | 641 | */ |
| 467 | 642 | public Token newToken(String tokenStr) { |
| 468 | 643 | TokenMap current = tokenMap; |
| 469 | 644 | if (current == null) |
| 470 | - throw new DriverInternalError("Token factory not set. This should only happen at initialization time"); | |
| 645 | + throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled"); | |
| 471 | 646 | |
| 472 | 647 | return current.factory.fromString(tokenStr); |
| 473 | 648 | } |
| @@ -478,11 +653,15 @@ | ||
| 478 | 653 | * @param start the start token. |
| 479 | 654 | * @param end the end token. |
| 480 | 655 | * @return the range. |
| 656 | + * | |
| 657 | + * @throws IllegalStateException if the token factory was not initialized. This would typically | |
| 658 | + * happen if metadata was explicitly disabled with {@link QueryOptions#setMetadataEnabled(boolean)} | |
| 659 | + * before startup. | |
| 481 | 660 | */ |
| 482 | 661 | public TokenRange newTokenRange(Token start, Token end) { |
| 483 | 662 | TokenMap current = tokenMap; |
| 484 | 663 | if (current == null) |
| 485 | - throw new DriverInternalError("Token factory not set. This should only happen at initialization time"); | |
| 664 | + throw new IllegalStateException("Token factory not set. This should only happen if metadata was explicitly disabled"); | |
| 486 | 665 | |
| 487 | 666 | return new TokenRange(start, end, current.factory); |
| 488 | 667 | } |
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +44 −1
| @@ -21,13 +21,14 @@ | ||
| 21 | 21 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 22 | 22 | |
| 23 | 23 | import io.netty.bootstrap.Bootstrap; |
| 24 | -import io.netty.buffer.ByteBufAllocator; | |
| 25 | 24 | import io.netty.buffer.PooledByteBufAllocator; |
| 26 | 25 | import io.netty.channel.ChannelOption; |
| 27 | 26 | import io.netty.channel.EventLoopGroup; |
| 28 | 27 | import io.netty.channel.nio.NioEventLoopGroup; |
| 29 | 28 | import io.netty.channel.socket.SocketChannel; |
| 30 | 29 | import io.netty.channel.socket.nio.NioSocketChannel; |
| 30 | +import io.netty.util.HashedWheelTimer; | |
| 31 | +import io.netty.util.Timer; | |
| 31 | 32 | |
| 32 | 33 | /** |
| 33 | 34 | * A set of hooks that allow clients to customize the driver's underlying Netty layer. |
| @@ -199,4 +200,46 @@ | ||
| 199 | 200 | // it is safe to reduce the quiet period to 0 seconds |
| 200 | 201 | eventLoopGroup.shutdownGracefully(0, 15, SECONDS).syncUninterruptibly(); |
| 201 | 202 | } |
| 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 | + } | |
| 202 | 245 | } |
modified driver-core/src/main/java/com/datastax/driver/core/PlainTextAuthProvider.java +25 −4
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import javax.security.sasl.SaslException; | |
| 19 | 18 | import java.net.InetSocketAddress; |
| 20 | 19 | import java.util.Map; |
| 21 | 20 | |
| @@ -28,13 +27,13 @@ | ||
| 28 | 27 | * This provider allows to programmatically define authentication |
| 29 | 28 | * information that will then apply to all hosts. The |
| 30 | 29 | * 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 | |
| 32 | 31 | * CQL native protocol. |
| 33 | 32 | */ |
| 34 | 33 | public class PlainTextAuthProvider implements AuthProvider { |
| 35 | 34 | |
| 36 | - private final String username; | |
| 37 | - private final String password; | |
| 35 | + private volatile String username; | |
| 36 | + private volatile String password; | |
| 38 | 37 | |
| 39 | 38 | /** |
| 40 | 39 | * Creates a new simple authentication information provider with the |
| @@ -47,6 +46,28 @@ | ||
| 47 | 46 | this.password = password; |
| 48 | 47 | } |
| 49 | 48 | |
| 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 | + | |
| 50 | 71 | /** |
| 51 | 72 | * Uses the supplied credentials and the SASL PLAIN mechanism to login |
| 52 | 73 | * to the server. |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +4 −0
| @@ -485,6 +485,10 @@ | ||
| 485 | 485 | * Requests the driver to re-evaluate the {@link HostDistance} (through the configured |
| 486 | 486 | * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#distance}) for every known |
| 487 | 487 | * 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()}). | |
| 488 | 492 | */ |
| 489 | 493 | public void refreshConnectedHosts() { |
| 490 | 494 | manager.refreshConnectedHosts(); |
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolV1Authenticator.java +10 −2
| @@ -17,8 +17,16 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.util.Map; |
| 19 | 19 | |
| 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 | + */ | |
| 22 | 30 | abstract class ProtocolV1Authenticator { |
| 23 | 31 | abstract Map<String, String> getCredentials(); |
| 24 | 32 | } |
modified driver-core/src/main/java/com/datastax/driver/core/QueryOptions.java +304 −0
| @@ -42,11 +42,36 @@ | ||
| 42 | 42 | */ |
| 43 | 43 | public static final boolean DEFAULT_IDEMPOTENCE = false; |
| 44 | 44 | |
| 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 | + | |
| 45 | 57 | private volatile ConsistencyLevel consistency = DEFAULT_CONSISTENCY_LEVEL; |
| 46 | 58 | private volatile ConsistencyLevel serialConsistency = DEFAULT_SERIAL_CONSISTENCY_LEVEL; |
| 47 | 59 | private volatile int fetchSize = DEFAULT_FETCH_SIZE; |
| 48 | 60 | 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; | |
| 49 | 73 | private volatile Cluster.Manager manager; |
| 74 | + private volatile boolean prepareOnAllHosts = true; | |
| 50 | 75 | |
| 51 | 76 | /** |
| 52 | 77 | * Creates a new {@link QueryOptions} instance using the {@link #DEFAULT_CONSISTENCY_LEVEL}, |
| @@ -169,4 +194,283 @@ | ||
| 169 | 194 | public boolean getDefaultIdempotence() { |
| 170 | 195 | return defaultIdempotence; |
| 171 | 196 | } |
| 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); // 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 | + | |
| 172 | 476 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +55 −8
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import java.util.*; |
| 19 | 19 | |
| 20 | 20 | import com.google.common.collect.ImmutableSet; |
| 21 | +import com.google.common.collect.Maps; | |
| 21 | 22 | import com.google.common.collect.Sets; |
| 22 | 23 | import org.slf4j.Logger; |
| 23 | 24 | import org.slf4j.LoggerFactory; |
| @@ -87,6 +88,24 @@ | ||
| 87 | 88 | } |
| 88 | 89 | return replicaMap; |
| 89 | 90 | } |
| 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 | + } | |
| 90 | 109 | } |
| 91 | 110 | |
| 92 | 111 | static class NetworkTopologyStrategy extends ReplicationStrategy { |
| @@ -103,9 +122,16 @@ | ||
| 103 | 122 | // This is essentially a copy of org.apache.cassandra.locator.NetworkTopologyStrategy |
| 104 | 123 | Map<String, Set<String>> racks = getRacksInDcs(tokenToPrimary.values()); |
| 105 | 124 | Map<Token, Set<Host>> replicaMap = new HashMap<Token, Set<Host>>(tokenToPrimary.size()); |
| 106 | - | |
| 125 | + Map<String, Integer> dcHostCount = Maps.newHashMapWithExpectedSize(replicationFactors.size()); | |
| 107 | 126 | 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 | + } | |
| 109 | 135 | for (int i = 0; i < ring.size(); i++) { |
| 110 | 136 | Map<String, Set<Host>> allDcReplicas = new HashMap<String, Set<Host>>(); |
| 111 | 137 | Map<String, Set<String>> seenRacks = new HashMap<String, Set<String>>(); |
| @@ -118,7 +144,7 @@ | ||
| 118 | 144 | |
| 119 | 145 | // Preserve order - primary replica will be first |
| 120 | 146 | 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++) { | |
| 122 | 148 | Host h = tokenToPrimary.get(getTokenWrapping(i + j, ring)); |
| 123 | 149 | String dc = h.getDatacenter(); |
| 124 | 150 | if (dc == null || !allDcReplicas.containsKey(dc)) |
| @@ -165,8 +191,7 @@ | ||
| 165 | 191 | if (achievedFactor < expectedFactor && !warnedDcs.contains(dcName)) { |
| 166 | 192 | logger.warn("Error while computing token map for datacenter {}: " |
| 167 | 193 | + "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.", | |
| 170 | 195 | dcName, expectedFactor, achievedFactor); |
| 171 | 196 | // only warn once per DC |
| 172 | 197 | warnedDcs.add(dcName); |
| @@ -178,10 +203,13 @@ | ||
| 178 | 203 | return replicaMap; |
| 179 | 204 | } |
| 180 | 205 | |
| 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)) | |
| 184 | 211 | return false; |
| 212 | + } | |
| 185 | 213 | return true; |
| 186 | 214 | } |
| 187 | 215 | |
| @@ -197,5 +225,24 @@ | ||
| 197 | 225 | } |
| 198 | 226 | return result; |
| 199 | 227 | } |
| 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 | + } | |
| 200 | 246 | } |
| 247 | + | |
| 201 | 248 | } |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +4 −4
| @@ -27,7 +27,6 @@ | ||
| 27 | 27 | |
| 28 | 28 | import com.codahale.metrics.Timer; |
| 29 | 29 | import com.google.common.collect.Sets; |
| 30 | -import io.netty.util.HashedWheelTimer; | |
| 31 | 30 | import io.netty.util.Timeout; |
| 32 | 31 | import io.netty.util.TimerTask; |
| 33 | 32 | import org.slf4j.Logger; |
| @@ -56,7 +55,7 @@ | ||
| 56 | 55 | private final Set<SpeculativeExecution> runningExecutions = Sets.newCopyOnWriteArraySet(); |
| 57 | 56 | private final Set<Timeout> scheduledExecutions = Sets.newCopyOnWriteArraySet(); |
| 58 | 57 | private final Statement statement; |
| 59 | - private final HashedWheelTimer scheduler; | |
| 58 | + private final io.netty.util.Timer scheduler; | |
| 60 | 59 | |
| 61 | 60 | private volatile List<Host> triedHosts; |
| 62 | 61 | |
| @@ -135,7 +134,8 @@ | ||
| 135 | 134 | manager.executor().execute(new Runnable() { |
| 136 | 135 | @Override |
| 137 | 136 | public void run() { |
| 138 | - metrics().getErrorMetrics().getSpeculativeExecutions().inc(); | |
| 137 | + if (metricsEnabled()) | |
| 138 | + metrics().getErrorMetrics().getSpeculativeExecutions().inc(); | |
| 139 | 139 | startNewExecution(); |
| 140 | 140 | } |
| 141 | 141 | }); |
| @@ -314,7 +314,7 @@ | ||
| 314 | 314 | return false; |
| 315 | 315 | } catch (TimeoutException e) { |
| 316 | 316 | // We timeout, log it but move to the next node. |
| 317 | - logError(host.getSocketAddress(), new DriverException("Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)")); | |
| 317 | + 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)); | |
| 318 | 318 | return false; |
| 319 | 319 | } catch (RuntimeException e) { |
| 320 | 320 | if (connection != null) |
modified driver-core/src/main/java/com/datastax/driver/core/Responses.java +11 −11
| @@ -88,20 +88,20 @@ | ||
| 88 | 88 | |
| 89 | 89 | public DriverException asException(InetSocketAddress host) { |
| 90 | 90 | switch (code) { |
| 91 | - case SERVER_ERROR: return new DriverInternalError(String.format("An unexpected error occurred server side on %s: %s", host, message)); | |
| 92 | - case PROTOCOL_ERROR: return new DriverInternalError("An unexpected protocol error occurred. This is a bug in this library, please report: " + message); | |
| 91 | + case SERVER_ERROR: return new ServerError(host, message); | |
| 92 | + case PROTOCOL_ERROR: return new ProtocolError(host, message); | |
| 93 | 93 | case BAD_CREDENTIALS: return new AuthenticationException(host, message); |
| 94 | - case UNAVAILABLE: return ((UnavailableException)infos).copy(); // We copy to have a nice stack trace | |
| 94 | + case UNAVAILABLE: return ((UnavailableException)infos).copy(host); // We copy to have a nice stack trace | |
| 95 | 95 | case OVERLOADED: return new OverloadedException(host, message); |
| 96 | 96 | case IS_BOOTSTRAPPING: return new BootstrappingException(host, message); |
| 97 | - case TRUNCATE_ERROR: return new TruncateException(message); | |
| 98 | - case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy(); | |
| 99 | - case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy(); | |
| 100 | - case SYNTAX_ERROR: return new SyntaxError(message); | |
| 101 | - case UNAUTHORIZED: return new UnauthorizedException(message); | |
| 102 | - case INVALID: return new InvalidQueryException(message); | |
| 103 | - case CONFIG_ERROR: return new InvalidConfigurationInQueryException(message); | |
| 104 | - case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy(); | |
| 97 | + case TRUNCATE_ERROR: return new TruncateException(host, message); | |
| 98 | + case WRITE_TIMEOUT: return ((WriteTimeoutException)infos).copy(host); | |
| 99 | + case READ_TIMEOUT: return ((ReadTimeoutException)infos).copy(host); | |
| 100 | + case SYNTAX_ERROR: return new SyntaxError(host, message); | |
| 101 | + case UNAUTHORIZED: return new UnauthorizedException(host, message); | |
| 102 | + case INVALID: return new InvalidQueryException(host, message); | |
| 103 | + case CONFIG_ERROR: return new InvalidConfigurationInQueryException(host, message); | |
| 104 | + case ALREADY_EXISTS: return ((AlreadyExistsException)infos).copy(host); | |
| 105 | 105 | case UNPREPARED: return new UnpreparedException(host, message); |
| 106 | 106 | default: return new DriverInternalError(String.format("Unknown protocol error code %s returned by %s. The error message was: %s", code, host, message)); |
| 107 | 107 | } |
added driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +111 −0
| @@ -0,0 +1,111 @@ | ||
| 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 | + * Gets invoked when the listener is registered with a cluster. | |
| 99 | + * | |
| 100 | + * @param cluster the cluster that this tracker is registered with. | |
| 101 | + */ | |
| 102 | + void onRegister(Cluster cluster); | |
| 103 | + | |
| 104 | + /** | |
| 105 | + * Gets invoked when the listener is unregistered from a cluster, or at cluster shutdown if | |
| 106 | + * the tracker was not unregistered. | |
| 107 | + * | |
| 108 | + * @param cluster the cluster that this tracker was registered with. | |
| 109 | + */ | |
| 110 | + void onUnregister(Cluster cluster); | |
| 111 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +160 −120
| @@ -22,12 +22,15 @@ | ||
| 22 | 22 | import java.util.concurrent.atomic.AtomicReference; |
| 23 | 23 | |
| 24 | 24 | import com.google.common.base.Function; |
| 25 | +import com.google.common.base.Functions; | |
| 26 | +import com.google.common.base.Throwables; | |
| 25 | 27 | import com.google.common.collect.ImmutableList; |
| 26 | 28 | import com.google.common.collect.Lists; |
| 27 | 29 | import com.google.common.util.concurrent.*; |
| 28 | 30 | import org.slf4j.Logger; |
| 29 | 31 | import org.slf4j.LoggerFactory; |
| 30 | 32 | |
| 33 | +import com.datastax.driver.core.Message.Response; | |
| 31 | 34 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 32 | 35 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 33 | 36 | import com.datastax.driver.core.exceptions.UnsupportedFeatureException; |
| @@ -46,55 +49,98 @@ | ||
| 46 | 49 | final Cluster cluster; |
| 47 | 50 | final ConcurrentMap<Host, HostConnectionPool> pools; |
| 48 | 51 | final HostConnectionPool.PoolState poolsState; |
| 52 | + private final AtomicReference<ListenableFuture<Session>> initFuture = new AtomicReference<ListenableFuture<Session>>(); | |
| 49 | 53 | final AtomicReference<CloseFuture> closeFuture = new AtomicReference<CloseFuture>(); |
| 50 | 54 | |
| 51 | 55 | private volatile boolean isInit; |
| 52 | 56 | private volatile boolean isClosing; |
| 53 | 57 | |
| 54 | 58 | // Package protected, only Cluster should construct that. |
| 55 | - SessionManager(Cluster cluster) { | |
| 59 | + SessionManager(Cluster cluster, String keyspace) { | |
| 56 | 60 | this.cluster = cluster; |
| 57 | 61 | this.pools = new ConcurrentHashMap<Host, HostConnectionPool>(); |
| 58 | - this.poolsState = new HostConnectionPool.PoolState(); | |
| 62 | + this.poolsState = new HostConnectionPool.PoolState(keyspace); | |
| 59 | 63 | } |
| 60 | 64 | |
| 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 | + } | |
| 64 | 72 | |
| 73 | + public ListenableFuture<Session> initAsync() { | |
| 65 | 74 | // If we haven't initialized the cluster, do it now |
| 66 | 75 | cluster.init(); |
| 67 | 76 | |
| 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 | + | |
| 69 | 85 | 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; | |
| 75 | 110 | } |
| 76 | 111 | |
| 77 | - private void createPoolsInParallel(Collection<Host> hosts) { | |
| 112 | + private ListenableFuture<?> createPools(Collection<Host> hosts) { | |
| 78 | 113 | List<ListenableFuture<Boolean>> futures = Lists.newArrayListWithCapacity(hosts.size()); |
| 79 | 114 | for (Host host : hosts) |
| 80 | 115 | 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); | |
| 90 | 118 | } |
| 91 | 119 | |
| 92 | 120 | public String getLoggedKeyspace() { |
| 93 | 121 | return poolsState.keyspace; |
| 94 | 122 | } |
| 95 | 123 | |
| 96 | - public ResultSetFuture executeAsync(Statement statement) { | |
| 97 | - return executeQuery(makeRequestMessage(statement, null), statement); | |
| 124 | + public ResultSetFuture executeAsync(final Statement statement) { | |
| 125 | + if (isInit) { | |
| 126 | + DefaultResultSetFuture future = new DefaultResultSetFuture(this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null)); | |
| 127 | + new RequestHandler(this, future, statement).sendRequest(); | |
| 128 | + return future; | |
| 129 | + } else { | |
| 130 | + // If the session is not initialized, we can't call makeRequestMessage() synchronously, because it | |
| 131 | + // requires internal Cluster state that might not be initialized yet (like the protocol version). | |
| 132 | + // Because of the way the future is built, we need another 'proxy' future that we can return now. | |
| 133 | + final ChainedResultSetFuture chainedFuture = new ChainedResultSetFuture(); | |
| 134 | + this.initAsync().addListener(new Runnable() { | |
| 135 | + @Override | |
| 136 | + public void run() { | |
| 137 | + DefaultResultSetFuture actualFuture = new DefaultResultSetFuture(SessionManager.this, cluster.manager.protocolVersion(), makeRequestMessage(statement, null)); | |
| 138 | + execute(actualFuture, statement); | |
| 139 | + chainedFuture.setSource(actualFuture); | |
| 140 | + } | |
| 141 | + }, executor()); | |
| 142 | + return chainedFuture; | |
| 143 | + } | |
| 98 | 144 | } |
| 99 | 145 | |
| 100 | 146 | public ListenableFuture<PreparedStatement> prepareAsync(String query) { |
| @@ -135,8 +181,8 @@ | ||
| 135 | 181 | } |
| 136 | 182 | |
| 137 | 183 | private ListenableFuture<PreparedStatement> toPreparedStatement(final String query, final Connection.Future future) { |
| 138 | - return Futures.transform(future, new Function<Message.Response, PreparedStatement>() { | |
| 139 | - public PreparedStatement apply(Message.Response response) { | |
| 184 | + return Futures.transform(future, new AsyncFunction<Response, PreparedStatement>() { | |
| 185 | + public ListenableFuture<PreparedStatement> apply(Response response) { | |
| 140 | 186 | switch (response.type) { |
| 141 | 187 | case RESULT: |
| 142 | 188 | Responses.Result rm = (Responses.Result)response; |
| @@ -145,27 +191,26 @@ | ||
| 145 | 191 | Responses.Result.Prepared pmsg = (Responses.Result.Prepared)rm; |
| 146 | 192 | PreparedStatement stmt = DefaultPreparedStatement.fromMessage(pmsg, cluster.getMetadata(), cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(), query, poolsState.keyspace); |
| 147 | 193 | stmt = cluster.manager.addPrepared(stmt); |
| 148 | - try { | |
| 194 | + if (cluster.getConfiguration().getQueryOptions().isPrepareOnAllHosts()) { | |
| 149 | 195 | // All Sessions are connected to the same nodes so it's enough to prepare only the nodes of this session. |
| 150 | 196 | // If that changes, we'll have to make sure this propagate to other sessions too. |
| 151 | - prepare(stmt.getQueryString(), future.getAddress()); | |
| 152 | - } catch (InterruptedException e) { | |
| 153 | - Thread.currentThread().interrupt(); | |
| 154 | - // This method doesn't propagate interruption, at least not for now. However, if we've | |
| 155 | - // interrupted preparing queries on other node it's not a problem as we'll re-prepare | |
| 156 | - // later if need be. So just ignore. | |
| 197 | + return prepare(stmt, future.getAddress()); | |
| 198 | + } else { | |
| 199 | + return Futures.immediateFuture(stmt); | |
| 157 | 200 | } |
| 158 | - return stmt; | |
| 159 | 201 | default: |
| 160 | - throw new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind)); | |
| 202 | + return Futures.immediateFailedFuture( | |
| 203 | + new DriverInternalError(String.format("%s response received when prepared statement was expected", rm.kind))); | |
| 161 | 204 | } |
| 162 | 205 | case ERROR: |
| 163 | - throw ((Responses.Error)response).asException(future.getAddress()); | |
| 206 | + return Futures.immediateFailedFuture( | |
| 207 | + ((Responses.Error)response).asException(future.getAddress())); | |
| 164 | 208 | default: |
| 165 | - throw new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type)); | |
| 209 | + return Futures.immediateFailedFuture( | |
| 210 | + new DriverInternalError(String.format("%s response received when prepared statement was expected", response.type))); | |
| 166 | 211 | } |
| 167 | 212 | } |
| 168 | - }, executor()); // Since the transformation involves querying other nodes, we should not do that in an I/O thread | |
| 213 | + }); | |
| 169 | 214 | } |
| 170 | 215 | |
| 171 | 216 | Connection.Factory connectionFactory() { |
| @@ -283,7 +328,7 @@ | ||
| 283 | 328 | } |
| 284 | 329 | |
| 285 | 330 | // Returns whether there was problem creating the pool |
| 286 | - ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection) { | |
| 331 | + ListenableFuture<Boolean> maybeAddPool(final Host host, Connection reusedConnection, final boolean failOnKeyspaceError) { | |
| 287 | 332 | final HostDistance distance = cluster.manager.loadBalancingPolicy().distance(host); |
| 288 | 333 | if (distance == HostDistance.IGNORED) |
| 289 | 334 | return Futures.immediateFuture(true); |
| @@ -316,6 +361,9 @@ | ||
| 316 | 361 | ClusterNameMismatchException e = (ClusterNameMismatchException)t; |
| 317 | 362 | cluster.manager.logClusterNameMismatch(host, e.expectedClusterName, e.actualClusterName); |
| 318 | 363 | cluster.manager.triggerOnDown(host, false); |
| 364 | + } else if ((t instanceof SetKeyspaceException) && failOnKeyspaceError) { | |
| 365 | + future.setException(t.getCause()); | |
| 366 | + return; | |
| 319 | 367 | } else { |
| 320 | 368 | logger.error("Error creating pool to " + host, t); |
| 321 | 369 | } |
| @@ -343,54 +391,48 @@ | ||
| 343 | 391 | * This method ensures that all hosts for which a pool should exist |
| 344 | 392 | * have one, and hosts that shouldn't don't. |
| 345 | 393 | */ |
| 346 | - void updateCreatedPools() { | |
| 394 | + ListenableFuture<?> updateCreatedPools() { | |
| 347 | 395 | // This method does nothing during initialization. Some hosts may be non-responsive but not yet marked DOWN; if |
| 348 | 396 | // we execute the code below we would try to create their pool over and over again. |
| 349 | 397 | // It's called explicitly at the end of init(), once isInit has been set to true. |
| 350 | 398 | if (!isInit) |
| 351 | - return; | |
| 399 | + return MoreFutures.VOID_SUCCESS; | |
| 352 | 400 | |
| 353 | - try { | |
| 354 | - // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second. | |
| 355 | - // That way, we'll avoid situation where we'll temporarily lose connectivity | |
| 356 | - List<Host> toRemove = new ArrayList<Host>(); | |
| 357 | - List<ListenableFuture<?>> poolCreationFutures = new ArrayList<ListenableFuture<?>>(); | |
| 358 | - | |
| 359 | - for (Host h : cluster.getMetadata().allHosts()) { | |
| 360 | - HostDistance dist = loadBalancingPolicy().distance(h); | |
| 361 | - HostConnectionPool pool = pools.get(h); | |
| 362 | - | |
| 363 | - if (pool == null) { | |
| 364 | - if (dist != HostDistance.IGNORED && h.state == Host.State.UP) | |
| 365 | - poolCreationFutures.add(maybeAddPool(h, null)); | |
| 366 | - } else if (dist != pool.hostDistance) { | |
| 367 | - if (dist == HostDistance.IGNORED) { | |
| 368 | - toRemove.add(h); | |
| 369 | - } else { | |
| 370 | - pool.hostDistance = dist; | |
| 371 | - pool.ensureCoreConnections(); | |
| 372 | - } | |
| 373 | - } | |
| 374 | - } | |
| 401 | + // We do 2 iterations, so that we add missing pools first, and them remove all unecessary pool second. | |
| 402 | + // That way, we'll avoid situation where we'll temporarily lose connectivity | |
| 403 | + final List<Host> toRemove = new ArrayList<Host>(); | |
| 404 | + List<ListenableFuture<Boolean>> poolCreatedFutures = Lists.newArrayList(); | |
| 375 | 405 | |
| 376 | - // Wait pool creation before removing, so we don't lose connectivity | |
| 377 | - try { | |
| 378 | - Futures.successfulAsList(poolCreationFutures).get(); | |
| 379 | - } catch (ExecutionException e) { | |
| 380 | - // Won't happen because we used successfulAsList | |
| 381 | - // And if a particular pool failed, maybeAddPool already handled it | |
| 406 | + for (Host h : cluster.getMetadata().allHosts()) { | |
| 407 | + HostDistance dist = loadBalancingPolicy().distance(h); | |
| 408 | + HostConnectionPool pool = pools.get(h); | |
| 409 | + | |
| 410 | + if (pool == null) { | |
| 411 | + if (dist != HostDistance.IGNORED && h.state == Host.State.UP) | |
| 412 | + poolCreatedFutures.add(maybeAddPool(h, null, false)); | |
| 413 | + } else if (dist != pool.hostDistance) { | |
| 414 | + if (dist == HostDistance.IGNORED) { | |
| 415 | + toRemove.add(h); | |
| 416 | + } else { | |
| 417 | + pool.hostDistance = dist; | |
| 418 | + pool.ensureCoreConnections(); | |
| 419 | + } | |
| 382 | 420 | } |
| 421 | + } | |
| 383 | 422 | |
| 384 | - List<ListenableFuture<?>> poolRemovalFutures = new ArrayList<ListenableFuture<?>>(toRemove.size()); | |
| 385 | - for (Host h : toRemove) | |
| 386 | - poolRemovalFutures.add(removePool(h)); | |
| 423 | + // Wait pool creation before removing, so we don't lose connectivity | |
| 424 | + ListenableFuture<?> allPoolsCreatedFuture = Futures.successfulAsList(poolCreatedFutures); | |
| 387 | 425 | |
| 388 | - Futures.allAsList(poolRemovalFutures).get(); | |
| 389 | - } catch (InterruptedException e) { | |
| 390 | - Thread.currentThread().interrupt(); | |
| 391 | - } catch (ExecutionException e) { | |
| 392 | - logger.error("Unexpected error while refreshing connection pools", e.getCause()); | |
| 393 | - } | |
| 426 | + return Futures.transform(allPoolsCreatedFuture, new AsyncFunction<Object, List<Void>>() { | |
| 427 | + @Override | |
| 428 | + public ListenableFuture<List<Void>> apply(Object input) throws Exception { | |
| 429 | + List<ListenableFuture<Void>> poolRemovedFuture = Lists.newArrayListWithCapacity(toRemove.size()); | |
| 430 | + for (Host h : toRemove) | |
| 431 | + poolRemovedFuture.add(removePool(h)); | |
| 432 | + | |
| 433 | + return Futures.successfulAsList(poolRemovedFuture); | |
| 434 | + } | |
| 435 | + }); | |
| 394 | 436 | } |
| 395 | 437 | |
| 396 | 438 | void updateCreatedPools(Host h) { |
| @@ -401,7 +443,7 @@ | ||
| 401 | 443 | if (pool == null) { |
| 402 | 444 | if (dist != HostDistance.IGNORED && h.state == Host.State.UP) |
| 403 | 445 | try { |
| 404 | - maybeAddPool(h, null).get(); | |
| 446 | + maybeAddPool(h, null, false).get(); | |
| 405 | 447 | } catch (ExecutionException e) { |
| 406 | 448 | // Ignore, maybeAddPool has already handled the error |
| 407 | 449 | } |
| @@ -424,26 +466,13 @@ | ||
| 424 | 466 | // Note that with well behaved balancing policy (that ignore dead nodes), the removePool call is not necessary |
| 425 | 467 | // since updateCreatedPools should take care of it. But better protect against non well behaving policies. |
| 426 | 468 | removePool(host).force().get(); |
| 427 | - updateCreatedPools(); | |
| 469 | + updateCreatedPools().get(); | |
| 428 | 470 | } |
| 429 | 471 | |
| 430 | 472 | void onRemove(Host host) throws InterruptedException, ExecutionException { |
| 431 | 473 | onDown(host); |
| 432 | 474 | } |
| 433 | 475 | |
| 434 | - void setKeyspace(String keyspace) { | |
| 435 | - long timeout = configuration().getSocketOptions().getConnectTimeoutMillis(); | |
| 436 | - try { | |
| 437 | - Future<?> future = executeQuery(new Requests.Query("use " + keyspace), Statement.DEFAULT); | |
| 438 | - // Note: using the connection timeout isn't perfectly correct, we should probably change that someday | |
| 439 | - Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); | |
| 440 | - } catch (TimeoutException e) { | |
| 441 | - 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)); | |
| 442 | - } catch (ExecutionException e) { | |
| 443 | - throw DefaultResultSetFuture.extractCauseFromExecutionException(e); | |
| 444 | - } | |
| 445 | - } | |
| 446 | - | |
| 447 | 476 | Message.Request makeRequestMessage(Statement statement, ByteBuffer pagingState) { |
| 448 | 477 | // We need the protocol version, which is only available once the cluster has initialized. Initialize the session to ensure this is the case. |
| 449 | 478 | // init() locks, so avoid if we know we don't need it. |
| @@ -545,46 +574,57 @@ | ||
| 545 | 574 | * This method will find a suitable node to connect to using the |
| 546 | 575 | * {@link LoadBalancingPolicy} and handle host failover. |
| 547 | 576 | */ |
| 548 | - void execute(RequestHandler.Callback callback, Statement statement) { | |
| 549 | - // init() locks, so avoid if we know we don't need it. | |
| 550 | - if (!isInit) | |
| 551 | - init(); | |
| 552 | - new RequestHandler(this, callback, statement).sendRequest(); | |
| 577 | + void execute(final RequestHandler.Callback callback, final Statement statement) { | |
| 578 | + if (isInit) | |
| 579 | + new RequestHandler(this, callback, statement).sendRequest(); | |
| 580 | + else | |
| 581 | + this.initAsync().addListener(new Runnable() { | |
| 582 | + @Override | |
| 583 | + public void run() { | |
| 584 | + new RequestHandler(SessionManager.this, callback, statement).sendRequest(); | |
| 585 | + } | |
| 586 | + }, executor()); | |
| 553 | 587 | } |
| 554 | 588 | |
| 555 | - private void prepare(String query, InetSocketAddress toExclude) throws InterruptedException { | |
| 556 | - for (Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) { | |
| 589 | + private ListenableFuture<PreparedStatement> prepare(final PreparedStatement statement, InetSocketAddress toExclude) { | |
| 590 | + final String query = statement.getQueryString(); | |
| 591 | + List<ListenableFuture<Response>> futures = Lists.newArrayListWithExpectedSize(pools.size()); | |
| 592 | + for (final Map.Entry<Host, HostConnectionPool> entry : pools.entrySet()) { | |
| 557 | 593 | if (entry.getKey().getSocketAddress().equals(toExclude)) |
| 558 | 594 | continue; |
| 559 | 595 | |
| 560 | - // Let's not wait too long if we can't get a connection. Things | |
| 561 | - // will fix themselves once the user tries a query anyway. | |
| 562 | - Connection c = null; | |
| 563 | - boolean timedOut = false; | |
| 564 | 596 | try { |
| 565 | - c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS); | |
| 566 | - c.write(new Requests.Prepare(query)).get(); | |
| 567 | - } catch (ConnectionException e) { | |
| 597 | + // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute | |
| 598 | + // the prepared query. So don't block if no connection is available, simply abort. | |
| 599 | + final Connection c = entry.getValue().borrowConnection(0, TimeUnit.MILLISECONDS); | |
| 600 | + ListenableFuture<Response> future = c.write(new Requests.Prepare(query)); | |
| 601 | + Futures.addCallback(future, new FutureCallback<Response>() { | |
| 602 | + @Override | |
| 603 | + public void onSuccess(Response result) { | |
| 604 | + c.release(); | |
| 605 | + } | |
| 606 | + | |
| 607 | + @Override | |
| 608 | + public void onFailure(Throwable t) { | |
| 609 | + logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t); | |
| 610 | + | |
| 611 | + // If the query timed out, that already released the connection, otherwise do it now | |
| 612 | + if (!(t instanceof OperationTimedOutException)) | |
| 613 | + c.release(); | |
| 614 | + } | |
| 615 | + }); | |
| 616 | + futures.add(future); | |
| 617 | + } catch (Exception e) { | |
| 568 | 618 | // Again, not being able to prepare the query right now is no big deal, so just ignore |
| 569 | - } catch (BusyConnectionException e) { | |
| 570 | - // Same as above | |
| 571 | - } catch (TimeoutException e) { | |
| 572 | - // Same as above | |
| 573 | - } catch (ExecutionException e) { | |
| 574 | - // We shouldn't really get exception while preparing a | |
| 575 | - // query, so log this (but ignore otherwise as it's not a big deal) | |
| 576 | - logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e); | |
| 577 | - // If the query timed out, that already released the connection | |
| 578 | - timedOut = e.getCause() instanceof OperationTimedOutException; | |
| 579 | - } finally { | |
| 580 | - if (c != null && !timedOut) | |
| 581 | - c.release(); | |
| 582 | 619 | } |
| 583 | 620 | } |
| 621 | + // Return the statement when all futures are done | |
| 622 | + return Futures.transform( | |
| 623 | + Futures.successfulAsList(futures), | |
| 624 | + Functions.constant(statement)); | |
| 584 | 625 | } |
| 585 | 626 | |
| 586 | 627 | ResultSetFuture executeQuery(Message.Request msg, Statement statement) { |
| 587 | - | |
| 588 | 628 | DefaultResultSetFuture future = new DefaultResultSetFuture(this, configuration().getProtocolOptions().getProtocolVersionEnum(), msg); |
| 589 | 629 | execute(future, statement); |
| 590 | 630 | 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 +18 −4
| @@ -77,10 +77,7 @@ | ||
| 77 | 77 | * |
| 78 | 78 | * @param query the query string. |
| 79 | 79 | * @param values values required for the execution of {@code query}. |
| 80 | - * | |
| 81 | - * @throws IllegalArgumentException if one of {@code values} is not of a type | |
| 82 | - * corresponding to a CQL3 type, i.e. is not a Class that could be returned | |
| 83 | - * by {@link DataType#asJavaClass}. | |
| 80 | + * @throws IllegalArgumentException if the number of values is greater than 65535. | |
| 84 | 81 | */ |
| 85 | 82 | public SimpleStatement(String query, Object... values) { |
| 86 | 83 | if (values.length > 65535) |
| @@ -134,6 +131,23 @@ | ||
| 134 | 131 | public boolean hasValues() { |
| 135 | 132 | return values != null && values.length > 0; |
| 136 | 133 | } |
| 134 | + | |
| 135 | + /** | |
| 136 | + * Returns the {@code i}th value as the Java type matching its CQL type. | |
| 137 | + * | |
| 138 | + * @param i the index to retrieve. | |
| 139 | + * @return the value of the {@code i}th value of this statement. | |
| 140 | + * | |
| 141 | + * @throws IllegalStateException if this statement does not have values. | |
| 142 | + * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. | |
| 143 | + */ | |
| 144 | + public Object getObject(int i) { | |
| 145 | + if (values == null) | |
| 146 | + throw new IllegalStateException("This statement does not have values"); | |
| 147 | + if (i < 0 || i >= values.length) | |
| 148 | + throw new ArrayIndexOutOfBoundsException(i); | |
| 149 | + return values[i]; | |
| 150 | + } | |
| 137 | 151 | |
| 138 | 152 | /** |
| 139 | 153 | * 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 @@ | ||
| 85 | 85 | * <p> |
| 86 | 86 | * Please note that this is not the maximum time a call to {@link Session#execute} may block; |
| 87 | 87 | * 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 | |
| 89 | 89 | * other words, a {@link Session#execute} call may theoretically wait up to |
| 90 | 90 | * {@code getReadTimeoutMillis() * <number_of_cassandra_hosts>} (though the |
| 91 | 91 | * total number of hosts tried for a given query also depends on the |
| @@ -110,10 +110,8 @@ | ||
| 110 | 110 | * <p> |
| 111 | 111 | * When setting this value, keep in mind the following: |
| 112 | 112 | * <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> | |
| 117 | 115 | * <li>the read timeout is only approximate and only control the timeout to one Cassandra |
| 118 | 116 | * host, not the full query (see {@link #getReadTimeoutMillis} for more details). If a |
| 119 | 117 | * 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 @@ | ||
| 187 | 187 | for (ColumnMetadata c : otherColumns) |
| 188 | 188 | columns.put(c.getName(), c); |
| 189 | 189 | |
| 190 | - ksm.add(tm); | |
| 191 | 190 | return tm; |
| 192 | 191 | } |
| 193 | 192 | |
| @@ -391,6 +390,43 @@ | ||
| 391 | 390 | return asCQLQuery(false); |
| 392 | 391 | } |
| 393 | 392 | |
| 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 | + | |
| 394 | 430 | private String asCQLQuery(boolean formatted) { |
| 395 | 431 | StringBuilder sb = new StringBuilder(); |
| 396 | 432 | |
| @@ -778,5 +814,71 @@ | ||
| 778 | 814 | public Map<String, String> getCompression() { |
| 779 | 815 | return new HashMap<String, String>(compression); |
| 780 | 816 | } |
| 817 | + | |
| 818 | + @Override | |
| 819 | + public boolean equals(Object o) { | |
| 820 | + if (this == o) | |
| 821 | + return true; | |
| 822 | + if (o == null || getClass() != o.getClass()) | |
| 823 | + return false; | |
| 824 | + | |
| 825 | + Options options = (Options)o; | |
| 826 | + | |
| 827 | + if (isCompactStorage != options.isCompactStorage) | |
| 828 | + return false; | |
| 829 | + if (Double.compare(options.readRepair, readRepair) != 0) | |
| 830 | + return false; | |
| 831 | + if (Double.compare(options.localReadRepair, localReadRepair) != 0) | |
| 832 | + return false; | |
| 833 | + if (replicateOnWrite != options.replicateOnWrite) | |
| 834 | + return false; | |
| 835 | + if (gcGrace != options.gcGrace) | |
| 836 | + return false; | |
| 837 | + if (Double.compare(options.bfFpChance, bfFpChance) != 0) | |
| 838 | + return false; | |
| 839 | + if (populateCacheOnFlush != options.populateCacheOnFlush) | |
| 840 | + return false; | |
| 841 | + if (memtableFlushPeriodMs != options.memtableFlushPeriodMs) | |
| 842 | + return false; | |
| 843 | + if (defaultTTL != options.defaultTTL) | |
| 844 | + return false; | |
| 845 | + if (indexInterval != options.indexInterval) | |
| 846 | + return false; | |
| 847 | + if (comment != null ? !comment.equals(options.comment) : options.comment != null) | |
| 848 | + return false; | |
| 849 | + if (caching != null ? !caching.equals(options.caching) : options.caching != null) | |
| 850 | + return false; | |
| 851 | + if (speculativeRetry != null ? !speculativeRetry.equals(options.speculativeRetry) : options.speculativeRetry != null) | |
| 852 | + return false; | |
| 853 | + if (compaction != null ? !compaction.equals(options.compaction) : options.compaction != null) | |
| 854 | + return false; | |
| 855 | + return !(compression != null ? !compression.equals(options.compression) : options.compression != null); | |
| 856 | + | |
| 857 | + } | |
| 858 | + | |
| 859 | + @Override | |
| 860 | + public int hashCode() { | |
| 861 | + int result; | |
| 862 | + long temp; | |
| 863 | + result = (isCompactStorage ? 1 : 0); | |
| 864 | + result = 31 * result + (comment != null ? comment.hashCode() : 0); | |
| 865 | + temp = Double.doubleToLongBits(readRepair); | |
| 866 | + result = 31 * result + (int)(temp ^ (temp >>> 32)); | |
| 867 | + temp = Double.doubleToLongBits(localReadRepair); | |
| 868 | + result = 31 * result + (int)(temp ^ (temp >>> 32)); | |
| 869 | + result = 31 * result + (replicateOnWrite ? 1 : 0); | |
| 870 | + result = 31 * result + gcGrace; | |
| 871 | + temp = Double.doubleToLongBits(bfFpChance); | |
| 872 | + result = 31 * result + (int)(temp ^ (temp >>> 32)); | |
| 873 | + result = 31 * result + (caching != null ? caching.hashCode() : 0); | |
| 874 | + result = 31 * result + (populateCacheOnFlush ? 1 : 0); | |
| 875 | + result = 31 * result + memtableFlushPeriodMs; | |
| 876 | + result = 31 * result + defaultTTL; | |
| 877 | + result = 31 * result + (speculativeRetry != null ? speculativeRetry.hashCode() : 0); | |
| 878 | + result = 31 * result + indexInterval; | |
| 879 | + result = 31 * result + (compaction != null ? compaction.hashCode() : 0); | |
| 880 | + result = 31 * result + (compression != null ? compression.hashCode() : 0); | |
| 881 | + return result; | |
| 882 | + } | |
| 781 | 883 | } |
| 782 | 884 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/AlreadyExistsException.java +49 −3
| @@ -15,24 +15,34 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | /** |
| 19 | 22 | * Exception thrown when a query attempts to create a keyspace or table that already exists. |
| 20 | 23 | */ |
| 21 | -public class AlreadyExistsException extends QueryValidationException { | |
| 24 | +public class AlreadyExistsException extends QueryValidationException implements CoordinatorException { | |
| 22 | 25 | |
| 23 | 26 | private static final long serialVersionUID = 0; |
| 24 | 27 | |
| 28 | + private final InetSocketAddress address; | |
| 25 | 29 | private final String keyspace; |
| 26 | 30 | private final String table; |
| 27 | 31 | |
| 28 | 32 | public AlreadyExistsException(String keyspace, String table) { |
| 33 | + this(null, keyspace, table); | |
| 34 | + } | |
| 35 | + | |
| 36 | + public AlreadyExistsException(InetSocketAddress address, String keyspace, String table) { | |
| 29 | 37 | super(makeMsg(keyspace, table)); |
| 38 | + this.address = address; | |
| 30 | 39 | this.keyspace = keyspace; |
| 31 | 40 | this.table = table; |
| 32 | 41 | } |
| 33 | 42 | |
| 34 | - private AlreadyExistsException(String msg, Throwable cause, String keyspace, String table) { | |
| 43 | + private AlreadyExistsException(InetSocketAddress address, String msg, Throwable cause, String keyspace, String table) { | |
| 35 | 44 | super(msg, cause); |
| 45 | + this.address = address; | |
| 36 | 46 | this.keyspace = keyspace; |
| 37 | 47 | this.table = table; |
| 38 | 48 | } |
| @@ -44,6 +54,22 @@ | ||
| 44 | 54 | return String.format("Table %s.%s already exists", keyspace, table); |
| 45 | 55 | } |
| 46 | 56 | |
| 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 | + | |
| 47 | 73 | /** |
| 48 | 74 | * Returns whether the query yielding this exception was a table creation |
| 49 | 75 | * attempt. |
| @@ -82,6 +108,26 @@ | ||
| 82 | 108 | |
| 83 | 109 | @Override |
| 84 | 110 | 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); | |
| 86 | 131 | } |
| 132 | + | |
| 87 | 133 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/AuthenticationException.java +7 −12
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | /** |
| 22 | 22 | * Indicates an error during the authentication phase while connecting to a node. |
| 23 | 23 | */ |
| 24 | -public class AuthenticationException extends DriverException { | |
| 24 | +public class AuthenticationException extends DriverException implements CoordinatorException { | |
| 25 | 25 | |
| 26 | 26 | private static final long serialVersionUID = 0; |
| 27 | 27 | |
| @@ -32,34 +32,29 @@ | ||
| 32 | 32 | this.address = address; |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | - private AuthenticationException(String message, Throwable cause, InetSocketAddress address) | |
| 36 | - { | |
| 35 | + private AuthenticationException(InetSocketAddress address, String message, Throwable cause) { | |
| 37 | 36 | super(message, cause); |
| 38 | 37 | this.address = address; |
| 39 | 38 | } |
| 40 | 39 | |
| 41 | 40 | /** |
| 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} | |
| 47 | 42 | */ |
| 43 | + @Override | |
| 48 | 44 | public InetAddress getHost() { |
| 49 | 45 | return address.getAddress(); |
| 50 | 46 | } |
| 51 | 47 | |
| 52 | 48 | /** |
| 53 | - * The full address of the host for which the authentication failed. | |
| 54 | - * | |
| 55 | - * @return the host for which the authentication failed. | |
| 49 | + * {@inheritDoc} | |
| 56 | 50 | */ |
| 51 | + @Override | |
| 57 | 52 | public InetSocketAddress getAddress() { |
| 58 | 53 | return address; |
| 59 | 54 | } |
| 60 | 55 | |
| 61 | 56 | @Override |
| 62 | 57 | public DriverException copy() { |
| 63 | - return new AuthenticationException(getMessage(), this, address); | |
| 58 | + return new AuthenticationException(address, getMessage(), this); | |
| 64 | 59 | } |
| 65 | 60 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/BootstrappingException.java +12 −4
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 18 | 19 | import java.net.InetSocketAddress; |
| 19 | 20 | |
| 20 | 21 | /** |
| @@ -24,7 +25,7 @@ | ||
| 24 | 25 | * because the driver would transparently retry the same query on another host; |
| 25 | 26 | * but such exceptions are likely to appear occasionally in the driver logs. |
| 26 | 27 | */ |
| 27 | -public class BootstrappingException extends DriverInternalError { | |
| 28 | +public class BootstrappingException extends DriverInternalError implements CoordinatorException { | |
| 28 | 29 | |
| 29 | 30 | private static final long serialVersionUID = 0; |
| 30 | 31 | |
| @@ -44,10 +45,17 @@ | ||
| 44 | 45 | } |
| 45 | 46 | |
| 46 | 47 | /** |
| 47 | - * The full address of the host that was bootstrapping. | |
| 48 | - * | |
| 49 | - * @return The full address of the host that was bootstrapping. | |
| 48 | + * {@inheritDoc} | |
| 50 | 49 | */ |
| 50 | + @Override | |
| 51 | + public InetAddress getHost() { | |
| 52 | + return address.getAddress(); | |
| 53 | + } | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * {@inheritDoc} | |
| 57 | + */ | |
| 58 | + @Override | |
| 51 | 59 | public InetSocketAddress getAddress() { |
| 52 | 60 | return address; |
| 53 | 61 | } |
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 @@ | ||
| 44 | 44 | * This return a new exception, equivalent to the original one, except that |
| 45 | 45 | * because a new object is created in the current thread, the top-most |
| 46 | 46 | * 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 | |
| 48 | 48 | * the copied exception will be the original exception. |
| 49 | 49 | * |
| 50 | 50 | * @return a copy/clone of this exception. |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidConfigurationInQueryException.java +18 −2
| @@ -15,6 +15,9 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | /** |
| 19 | 22 | * A specific invalid query exception that indicates that the query is invalid |
| 20 | 23 | * because of some configuration problem. |
| @@ -22,11 +25,24 @@ | ||
| 22 | 25 | * This is generally throw by query that manipulate the schema (CREATE and |
| 23 | 26 | * ALTER) when the required configuration options are invalid. |
| 24 | 27 | */ |
| 25 | -public class InvalidConfigurationInQueryException extends InvalidQueryException { | |
| 28 | +public class InvalidConfigurationInQueryException extends InvalidQueryException implements CoordinatorException { | |
| 26 | 29 | |
| 27 | 30 | private static final long serialVersionUID = 0; |
| 28 | 31 | |
| 32 | + /** | |
| 33 | + * @deprecated This constructor is kept for backwards compatibility. | |
| 34 | + */ | |
| 35 | + @Deprecated | |
| 29 | 36 | 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()); | |
| 31 | 47 | } |
| 32 | 48 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/InvalidQueryException.java +28 −3
| @@ -15,23 +15,48 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | /** |
| 19 | 22 | * Indicates a syntactically correct but invalid query. |
| 20 | 23 | */ |
| 21 | -public class InvalidQueryException extends QueryValidationException { | |
| 24 | +public class InvalidQueryException extends QueryValidationException implements CoordinatorException { | |
| 22 | 25 | |
| 23 | 26 | private static final long serialVersionUID = 0; |
| 24 | 27 | |
| 28 | + private final InetSocketAddress address; | |
| 29 | + | |
| 25 | 30 | public InvalidQueryException(String msg) { |
| 31 | + this(null, msg); | |
| 32 | + } | |
| 33 | + | |
| 34 | + public InvalidQueryException(InetSocketAddress address, String msg) { | |
| 26 | 35 | super(msg); |
| 36 | + this.address = address; | |
| 37 | + } | |
| 38 | + | |
| 39 | + public InvalidQueryException(String msg, Throwable cause) { | |
| 40 | + this(null, msg, cause); | |
| 27 | 41 | } |
| 28 | 42 | |
| 29 | - private InvalidQueryException(String msg, Throwable cause) { | |
| 43 | + public InvalidQueryException(InetSocketAddress address, String msg, Throwable cause) { | |
| 30 | 44 | super(msg, cause); |
| 45 | + this.address = address; | |
| 31 | 46 | } |
| 32 | 47 | |
| 33 | 48 | @Override |
| 34 | 49 | 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; | |
| 36 | 61 | } |
| 37 | 62 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/OverloadedException.java +12 −4
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 18 | 19 | import java.net.InetSocketAddress; |
| 19 | 20 | |
| 20 | 21 | /** |
| @@ -24,7 +25,7 @@ | ||
| 24 | 25 | * because the driver would transparently retry the same query on another host; |
| 25 | 26 | * but such exceptions are likely to appear occasionally in the driver logs. |
| 26 | 27 | */ |
| 27 | -public class OverloadedException extends DriverInternalError { | |
| 28 | +public class OverloadedException extends DriverInternalError implements CoordinatorException { | |
| 28 | 29 | |
| 29 | 30 | private static final long serialVersionUID = 0; |
| 30 | 31 | |
| @@ -44,10 +45,17 @@ | ||
| 44 | 45 | } |
| 45 | 46 | |
| 46 | 47 | /** |
| 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} | |
| 50 | 49 | */ |
| 50 | + @Override | |
| 51 | + public InetAddress getHost() { | |
| 52 | + return address.getAddress(); | |
| 53 | + } | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * {@inheritDoc} | |
| 57 | + */ | |
| 58 | + @Override | |
| 51 | 59 | public InetSocketAddress getAddress() { |
| 52 | 60 | return address; |
| 53 | 61 | } |
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/QueryTimeoutException.java +47 −2
| @@ -15,6 +15,9 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | 22 | |
| 20 | 23 | /** |
| @@ -25,21 +28,40 @@ | ||
| 25 | 28 | * timeout set for Cassandra. |
| 26 | 29 | */ |
| 27 | 30 | @SuppressWarnings("serial") |
| 28 | -public abstract class QueryTimeoutException extends QueryExecutionException { | |
| 31 | +public abstract class QueryTimeoutException extends QueryExecutionException implements CoordinatorException { | |
| 29 | 32 | |
| 33 | + private final InetSocketAddress address; | |
| 30 | 34 | private final ConsistencyLevel consistency; |
| 31 | 35 | private final int received; |
| 32 | 36 | private final int required; |
| 33 | 37 | |
| 38 | + /** | |
| 39 | + * @deprecated This constructor is kept for backwards compatibility. | |
| 40 | + */ | |
| 41 | + @Deprecated | |
| 34 | 42 | protected QueryTimeoutException(String msg, ConsistencyLevel consistency, int received, int required) { |
| 43 | + this(null, msg, consistency, received, required); | |
| 44 | + } | |
| 45 | + | |
| 46 | + /** | |
| 47 | + * @deprecated This constructor is kept for backwards compatibility. | |
| 48 | + */ | |
| 49 | + @Deprecated | |
| 50 | + protected QueryTimeoutException(String msg, Throwable cause, ConsistencyLevel consistency, int received, int required) { | |
| 51 | + this(null, msg, cause, consistency, received, required); | |
| 52 | + } | |
| 53 | + | |
| 54 | + protected QueryTimeoutException(InetSocketAddress address, String msg, ConsistencyLevel consistency, int received, int required) { | |
| 35 | 55 | super(msg); |
| 56 | + this.address = address; | |
| 36 | 57 | this.consistency = consistency; |
| 37 | 58 | this.received = received; |
| 38 | 59 | this.required = required; |
| 39 | 60 | } |
| 40 | 61 | |
| 41 | - protected QueryTimeoutException(String msg, Throwable cause, ConsistencyLevel consistency, int received, int required) { | |
| 62 | + protected QueryTimeoutException(InetSocketAddress address, String msg, Throwable cause, ConsistencyLevel consistency, int received, int required) { | |
| 42 | 63 | super(msg, cause); |
| 64 | + this.address = address; | |
| 43 | 65 | this.consistency = consistency; |
| 44 | 66 | this.received = received; |
| 45 | 67 | this.required = required; |
| @@ -75,4 +97,27 @@ | ||
| 75 | 97 | public int getRequiredAcknowledgements() { |
| 76 | 98 | return required; |
| 77 | 99 | } |
| 100 | + | |
| 101 | + /** | |
| 102 | + * The coordinator host that caused this exception to be thrown. | |
| 103 | + * Note that this is the query coordinator host, <em>not</em> the host which timed out. | |
| 104 | + * | |
| 105 | + * @return The coordinator host that caused this exception to be thrown, or {@code null} if this exception has been generated driver-side. | |
| 106 | + */ | |
| 107 | + @Override | |
| 108 | + public InetAddress getHost() { | |
| 109 | + return address.getAddress(); | |
| 110 | + } | |
| 111 | + | |
| 112 | + /** | |
| 113 | + * The full address of the coordinator host that caused this exception to be thrown. | |
| 114 | + * Note that this is the query coordinator host, <em>not</em> the host which timed out. | |
| 115 | + * | |
| 116 | + * @return the full address of the coordinator host that caused this exception to be thrown, | |
| 117 | + * or {@code null} if this exception has been generated driver-side. | |
| 118 | + */ | |
| 119 | + @Override | |
| 120 | + public InetSocketAddress getAddress() { | |
| 121 | + return address; | |
| 122 | + } | |
| 78 | 123 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/ReadTimeoutException.java +56 −12
| @@ -15,6 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetSocketAddress; | |
| 19 | + | |
| 18 | 20 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | 21 | |
| 20 | 22 | /** |
| @@ -26,16 +28,27 @@ | ||
| 26 | 28 | |
| 27 | 29 | private final boolean dataPresent; |
| 28 | 30 | |
| 31 | + /** | |
| 32 | + * This constructor should only be used internally by the driver | |
| 33 | + * when decoding error responses. | |
| 34 | + */ | |
| 29 | 35 | 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 | + ); | |
| 34 | 47 | this.dataPresent = dataPresent; |
| 35 | 48 | } |
| 36 | 49 | |
| 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); | |
| 39 | 52 | this.dataPresent = dataPresent; |
| 40 | 53 | } |
| 41 | 54 | |
| @@ -66,11 +79,42 @@ | ||
| 66 | 79 | |
| 67 | 80 | @Override |
| 68 | 81 | public DriverException copy() { |
| 69 | - return new ReadTimeoutException(getMessage(), | |
| 70 | - this, | |
| 71 | - getConsistencyLevel(), | |
| 72 | - getReceivedAcknowledgements(), | |
| 73 | - getRequiredAcknowledgements(), | |
| 74 | - wasDataRetrieved()); | |
| 82 | + return new ReadTimeoutException( | |
| 83 | + getAddress(), | |
| 84 | + getMessage(), | |
| 85 | + this, | |
| 86 | + getConsistencyLevel(), | |
| 87 | + getReceivedAcknowledgements(), | |
| 88 | + getRequiredAcknowledgements(), | |
| 89 | + wasDataRetrieved() | |
| 90 | + ); | |
| 75 | 91 | } |
| 92 | + | |
| 93 | + /** | |
| 94 | + * Create a copy of this exception with a nicer stack trace, and including the coordinator | |
| 95 | + * address that caused this exception to be raised. | |
| 96 | + * <p> | |
| 97 | + * This method is mainly intended for internal use by the driver and exists mainly because: | |
| 98 | + * <ol> | |
| 99 | + * <li>the original exception was decoded from a response frame | |
| 100 | + * and at that time, the coordinator address was not available; and</li> | |
| 101 | + * <li>the newly-created exception will refer to the current thread in its stack trace, | |
| 102 | + * which generally yields a more user-friendly stack trace that the original one.</li> | |
| 103 | + * </ol> | |
| 104 | + * | |
| 105 | + * @param address The full address of the host that caused this exception to be thrown. | |
| 106 | + * @return a copy/clone of this exception, but with the given host address instead of the original one. | |
| 107 | + */ | |
| 108 | + public ReadTimeoutException copy(InetSocketAddress address) { | |
| 109 | + return new ReadTimeoutException( | |
| 110 | + address, | |
| 111 | + getMessage(), | |
| 112 | + this, | |
| 113 | + getConsistencyLevel(), | |
| 114 | + getReceivedAcknowledgements(), | |
| 115 | + getRequiredAcknowledgements(), | |
| 116 | + wasDataRetrieved() | |
| 117 | + ); | |
| 118 | + } | |
| 119 | + | |
| 76 | 120 | } |
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 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | /** |
| 19 | 22 | * Indicates a syntax error in a query. |
| 20 | 23 | */ |
| 21 | -public class SyntaxError extends QueryValidationException { | |
| 24 | +public class SyntaxError extends QueryValidationException implements CoordinatorException { | |
| 22 | 25 | |
| 23 | 26 | private static final long serialVersionUID = 0; |
| 24 | 27 | |
| 28 | + private final InetSocketAddress address; | |
| 29 | + | |
| 30 | + /** | |
| 31 | + * @deprecated This constructor is kept for backwards compatibility. | |
| 32 | + */ | |
| 33 | + @Deprecated | |
| 25 | 34 | public SyntaxError(String msg) { |
| 35 | + this(null, msg); | |
| 36 | + } | |
| 37 | + | |
| 38 | + public SyntaxError(InetSocketAddress address, String msg) { | |
| 26 | 39 | super(msg); |
| 40 | + this.address = address; | |
| 27 | 41 | } |
| 28 | 42 | |
| 29 | - private SyntaxError(String msg, Throwable cause) { | |
| 43 | + private SyntaxError(InetSocketAddress address, String msg, Throwable cause) { | |
| 30 | 44 | 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; | |
| 31 | 62 | } |
| 32 | 63 | |
| 33 | 64 | @Override |
| 34 | 65 | public DriverException copy() { |
| 35 | - return new SyntaxError(getMessage(), this); | |
| 66 | + return new SyntaxError(getAddress(), getMessage(), this); | |
| 36 | 67 | } |
| 37 | 68 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/TruncateException.java +34 −3
| @@ -15,23 +15,54 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | /** |
| 19 | 22 | * Error during a truncation operation. |
| 20 | 23 | */ |
| 21 | -public class TruncateException extends QueryExecutionException { | |
| 24 | +public class TruncateException extends QueryExecutionException implements CoordinatorException { | |
| 22 | 25 | |
| 23 | 26 | private static final long serialVersionUID = 0; |
| 24 | 27 | |
| 28 | + private final InetSocketAddress address; | |
| 29 | + | |
| 30 | + /** | |
| 31 | + * @deprecated This constructor is kept for backwards compatibility. | |
| 32 | + */ | |
| 33 | + @Deprecated | |
| 25 | 34 | public TruncateException(String msg) { |
| 35 | + this(null, msg); | |
| 36 | + } | |
| 37 | + | |
| 38 | + public TruncateException(InetSocketAddress address, String msg) { | |
| 26 | 39 | super(msg); |
| 40 | + this.address = address; | |
| 27 | 41 | } |
| 28 | 42 | |
| 29 | - private TruncateException(String msg, Throwable cause) { | |
| 43 | + private TruncateException(InetSocketAddress address, String msg, Throwable cause) { | |
| 30 | 44 | 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; | |
| 31 | 62 | } |
| 32 | 63 | |
| 33 | 64 | @Override |
| 34 | 65 | public DriverException copy() { |
| 35 | - return new TruncateException(getMessage(), this); | |
| 66 | + return new TruncateException(getAddress(), getMessage(), this); | |
| 36 | 67 | } |
| 37 | 68 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnauthorizedException.java +34 −3
| @@ -15,24 +15,55 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | /** |
| 19 | 22 | * Indicates that a query cannot be performed due to the authorization |
| 20 | 23 | * restrictions of the logged user. |
| 21 | 24 | */ |
| 22 | -public class UnauthorizedException extends QueryValidationException { | |
| 25 | +public class UnauthorizedException extends QueryValidationException implements CoordinatorException { | |
| 23 | 26 | |
| 24 | 27 | private static final long serialVersionUID = 0; |
| 25 | 28 | |
| 29 | + private final InetSocketAddress address; | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * @deprecated This constructor is kept for backwards compatibility. | |
| 33 | + */ | |
| 34 | + @Deprecated | |
| 26 | 35 | public UnauthorizedException(String msg) { |
| 36 | + this(null, msg); | |
| 37 | + } | |
| 38 | + | |
| 39 | + public UnauthorizedException(InetSocketAddress address, String msg) { | |
| 27 | 40 | super(msg); |
| 41 | + this.address = address; | |
| 28 | 42 | } |
| 29 | 43 | |
| 30 | - private UnauthorizedException(String msg, Throwable cause) { | |
| 44 | + private UnauthorizedException(InetSocketAddress address, String msg, Throwable cause) { | |
| 31 | 45 | 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; | |
| 32 | 63 | } |
| 33 | 64 | |
| 34 | 65 | @Override |
| 35 | 66 | public DriverException copy() { |
| 36 | - return new UnauthorizedException(getMessage(), this); | |
| 67 | + return new UnauthorizedException(getAddress(), getMessage(), this); | |
| 37 | 68 | } |
| 38 | 69 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnavailableException.java +53 −4
| @@ -15,29 +15,43 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | + | |
| 18 | 21 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | 22 | |
| 20 | 23 | /** |
| 21 | 24 | * Exception thrown when the coordinator knows there is not enough replica |
| 22 | 25 | * alive to perform a query with the requested consistency level. |
| 23 | 26 | */ |
| 24 | -public class UnavailableException extends QueryExecutionException { | |
| 27 | +public class UnavailableException extends QueryExecutionException implements CoordinatorException { | |
| 25 | 28 | |
| 26 | 29 | private static final long serialVersionUID = 0; |
| 27 | 30 | |
| 31 | + private final InetSocketAddress address; | |
| 28 | 32 | private final ConsistencyLevel consistency; |
| 29 | 33 | private final int required; |
| 30 | 34 | private final int alive; |
| 31 | 35 | |
| 36 | + /** | |
| 37 | + * This constructor should only be used internally by the driver | |
| 38 | + * when decoding error responses. | |
| 39 | + */ | |
| 32 | 40 | 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; | |
| 34 | 47 | this.consistency = consistency; |
| 35 | 48 | this.required = required; |
| 36 | 49 | this.alive = alive; |
| 37 | 50 | } |
| 38 | 51 | |
| 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) { | |
| 40 | 53 | super(message, cause); |
| 54 | + this.address = address; | |
| 41 | 55 | this.consistency = consistency; |
| 42 | 56 | this.required = required; |
| 43 | 57 | this.alive = alive; |
| @@ -74,8 +88,43 @@ | ||
| 74 | 88 | return alive; |
| 75 | 89 | } |
| 76 | 90 | |
| 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 | + | |
| 77 | 107 | @Override |
| 78 | 108 | 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); | |
| 80 | 129 | } |
| 81 | 130 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/UnpreparedException.java +12 −4
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 18 | 19 | import java.net.InetSocketAddress; |
| 19 | 20 | |
| 20 | 21 | /** |
| @@ -24,7 +25,7 @@ | ||
| 24 | 25 | * because the driver would transparently prepare the query and execute it again; |
| 25 | 26 | * but such exceptions are likely to appear occasionally in the driver logs. |
| 26 | 27 | */ |
| 27 | -public class UnpreparedException extends DriverInternalError { | |
| 28 | +public class UnpreparedException extends DriverInternalError implements CoordinatorException { | |
| 28 | 29 | |
| 29 | 30 | private static final long serialVersionUID = 0; |
| 30 | 31 | |
| @@ -44,10 +45,17 @@ | ||
| 44 | 45 | } |
| 45 | 46 | |
| 46 | 47 | /** |
| 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} | |
| 50 | 49 | */ |
| 50 | + @Override | |
| 51 | + public InetAddress getHost() { | |
| 52 | + return address.getAddress(); | |
| 53 | + } | |
| 54 | + | |
| 55 | + /** | |
| 56 | + * {@inheritDoc} | |
| 57 | + */ | |
| 58 | + @Override | |
| 51 | 59 | public InetSocketAddress getAddress() { |
| 52 | 60 | return address; |
| 53 | 61 | } |
modified driver-core/src/main/java/com/datastax/driver/core/exceptions/WriteTimeoutException.java +55 −12
| @@ -15,6 +15,8 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.exceptions; |
| 17 | 17 | |
| 18 | +import java.net.InetSocketAddress; | |
| 19 | + | |
| 18 | 20 | import com.datastax.driver.core.ConsistencyLevel; |
| 19 | 21 | import com.datastax.driver.core.WriteType; |
| 20 | 22 | |
| @@ -27,16 +29,26 @@ | ||
| 27 | 29 | |
| 28 | 30 | private final WriteType writeType; |
| 29 | 31 | |
| 32 | + /** | |
| 33 | + * This constructor should only be used internally by the driver | |
| 34 | + * when decoding error responses. | |
| 35 | + */ | |
| 30 | 36 | 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); | |
| 35 | 47 | this.writeType = writeType; |
| 36 | 48 | } |
| 37 | 49 | |
| 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); | |
| 40 | 52 | this.writeType = writeType; |
| 41 | 53 | } |
| 42 | 54 | |
| @@ -51,11 +63,42 @@ | ||
| 51 | 63 | |
| 52 | 64 | @Override |
| 53 | 65 | 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 | + ); | |
| 60 | 75 | } |
| 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 | + | |
| 61 | 104 | } |
modified driver-core/src/main/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicy.java +3 −3
| @@ -19,9 +19,6 @@ | ||
| 19 | 19 | import java.util.concurrent.ConcurrentHashMap; |
| 20 | 20 | import java.util.concurrent.ConcurrentMap; |
| 21 | 21 | import java.util.concurrent.CopyOnWriteArrayList; |
| 22 | -import java.util.concurrent.ExecutionException; | |
| 23 | -import java.util.concurrent.TimeUnit; | |
| 24 | -import java.util.concurrent.TimeoutException; | |
| 25 | 22 | import java.util.concurrent.atomic.AtomicInteger; |
| 26 | 23 | |
| 27 | 24 | import com.google.common.base.Joiner; |
| @@ -211,6 +208,9 @@ | ||
| 211 | 208 | String nonLocalHosts = Joiner.on(",").join(notInLocalDC); |
| 212 | 209 | logger.warn("Some contact points don't match local data center. Local DC = {}. Non-conforming contact points: {}", localDc, nonLocalHosts); |
| 213 | 210 | } |
| 211 | + | |
| 212 | + this.index.set(new Random().nextInt(Math.max(hosts.size(), 1))); | |
| 213 | + | |
| 214 | 214 | } |
| 215 | 215 | |
| 216 | 216 | private String dc(Host host) { |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Assignment.java +0 −1
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.List; |
| 20 | 19 | |
| 21 | 20 | import static com.datastax.driver.core.querybuilder.Utils.appendName; |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +18 −0
| @@ -70,6 +70,24 @@ | ||
| 70 | 70 | return cache; |
| 71 | 71 | } |
| 72 | 72 | |
| 73 | + /** | |
| 74 | + * Returns the {@code i}th value as the Java type matching its CQL type. | |
| 75 | + * | |
| 76 | + * @param i the index to retrieve. | |
| 77 | + * @return the value of the {@code i}th value of this statement. | |
| 78 | + * | |
| 79 | + * @throws IllegalStateException if this statement does not have values. | |
| 80 | + * @throws IndexOutOfBoundsException if {@code i} is not a valid index for this object. | |
| 81 | + */ | |
| 82 | + public Object getObject(int i) { | |
| 83 | + maybeRebuildCache(); | |
| 84 | + if (values == null || values.isEmpty()) | |
| 85 | + throw new IllegalStateException("This statement does not have values"); | |
| 86 | + if (i < 0 || i >= values.size()) | |
| 87 | + throw new ArrayIndexOutOfBoundsException(i); | |
| 88 | + return values.get(i); | |
| 89 | + } | |
| 90 | + | |
| 73 | 91 | private void maybeRebuildCache() { |
| 74 | 92 | if (!dirty && cache != null) |
| 75 | 93 | return; |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Select.java +0 −1
| @@ -15,7 +15,6 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import java.nio.ByteBuffer; | |
| 19 | 18 | import java.util.ArrayList; |
| 20 | 19 | import java.util.Arrays; |
| 21 | 20 | import java.util.Collections; |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Update.java +37 −0
| @@ -32,6 +32,7 @@ | ||
| 32 | 32 | private final Where where; |
| 33 | 33 | private final Options usings; |
| 34 | 34 | private final Conditions conditions; |
| 35 | + private boolean ifExists; | |
| 35 | 36 | |
| 36 | 37 | Update(String keyspace, String table) { |
| 37 | 38 | super(keyspace); |
| @@ -40,6 +41,7 @@ | ||
| 40 | 41 | this.where = new Where(this); |
| 41 | 42 | this.usings = new Options(this); |
| 42 | 43 | this.conditions = new Conditions(this); |
| 44 | + this.ifExists = false; | |
| 43 | 45 | } |
| 44 | 46 | |
| 45 | 47 | Update(TableMetadata table) { |
| @@ -49,6 +51,7 @@ | ||
| 49 | 51 | this.where = new Where(this); |
| 50 | 52 | this.usings = new Options(this); |
| 51 | 53 | this.conditions = new Conditions(this); |
| 54 | + this.ifExists = false; | |
| 52 | 55 | } |
| 53 | 56 | |
| 54 | 57 | @Override |
| @@ -80,6 +83,10 @@ | ||
| 80 | 83 | Utils.joinAndAppend(builder, " AND ", conditions.conditions, variables); |
| 81 | 84 | } |
| 82 | 85 | |
| 86 | + if (ifExists) { | |
| 87 | + builder.append(" IF EXISTS"); | |
| 88 | + } | |
| 89 | + | |
| 83 | 90 | return builder; |
| 84 | 91 | } |
| 85 | 92 | |
| @@ -211,6 +218,7 @@ | ||
| 211 | 218 | public Conditions onlyIf(Clause condition) { |
| 212 | 219 | return statement.onlyIf(condition); |
| 213 | 220 | } |
| 221 | + | |
| 214 | 222 | } |
| 215 | 223 | |
| 216 | 224 | /** |
| @@ -266,6 +274,28 @@ | ||
| 266 | 274 | public Conditions onlyIf(Clause condition) { |
| 267 | 275 | return statement.onlyIf(condition); |
| 268 | 276 | } |
| 277 | + | |
| 278 | + /** | |
| 279 | + * Sets the 'IF EXISTS' option for the UPDATE statement this WHERE clause | |
| 280 | + * is part of. | |
| 281 | + * | |
| 282 | + * <p> | |
| 283 | + * An update with that option will report whether the statement actually | |
| 284 | + * resulted in data being updated. The existence check and update are | |
| 285 | + * done transactionally in the sense that if multiple clients attempt to | |
| 286 | + * update a given row with this option, then at most one may succeed. | |
| 287 | + * </p> | |
| 288 | + * <p> | |
| 289 | + * Please keep in mind that using this option has a non negligible | |
| 290 | + * performance impact and should be avoided when possible. | |
| 291 | + * </p> | |
| 292 | + * | |
| 293 | + * @return the UPDATE statement this WHERE clause is part of. | |
| 294 | + */ | |
| 295 | + public IfExists ifExists() { | |
| 296 | + statement.ifExists = true; | |
| 297 | + return new IfExists(statement); | |
| 298 | + } | |
| 269 | 299 | } |
| 270 | 300 | |
| 271 | 301 | /** |
| @@ -383,5 +413,12 @@ | ||
| 383 | 413 | public Options using(Using using) { |
| 384 | 414 | return statement.using(using); |
| 385 | 415 | } |
| 416 | + | |
| 417 | + } | |
| 418 | + | |
| 419 | + public static class IfExists extends BuiltStatement.ForwardingStatement<Update> { | |
| 420 | + IfExists(Update statement) { | |
| 421 | + super(statement); | |
| 422 | + } | |
| 386 | 423 | } |
| 387 | 424 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReconnectionHandlerTest.java +2 −2
| @@ -52,7 +52,7 @@ | ||
| 52 | 52 | schedule = new MockReconnectionSchedule(); |
| 53 | 53 | work = new MockReconnectionWork(); |
| 54 | 54 | future.set(null); |
| 55 | - handler = new AbstractReconnectionHandler(executor, schedule, future) { | |
| 55 | + handler = new AbstractReconnectionHandler("test", executor, schedule, future) { | |
| 56 | 56 | @Override |
| 57 | 57 | protected Connection tryReconnect() throws ConnectionException, InterruptedException, UnsupportedProtocolVersionException, ClusterNameMismatchException { |
| 58 | 58 | return work.tryReconnect(); |
| @@ -330,7 +330,7 @@ | ||
| 330 | 330 | private void waitForCompletion() { |
| 331 | 331 | executor.shutdown(); |
| 332 | 332 | try { |
| 333 | - boolean shutdown = executor.awaitTermination(10, TimeUnit.SECONDS); | |
| 333 | + boolean shutdown = executor.awaitTermination(30, TimeUnit.SECONDS); | |
| 334 | 334 | if (!shutdown) |
| 335 | 335 | fail("executor ran for longer than expected"); |
| 336 | 336 | } catch (InterruptedException e) { |
modified driver-core/src/test/java/com/datastax/driver/core/AbstractReplicationStrategyTest.java +11 −6
| @@ -25,8 +25,13 @@ | ||
| 25 | 25 | |
| 26 | 26 | import com.google.common.collect.ImmutableList; |
| 27 | 27 | import com.google.common.collect.ImmutableList.Builder; |
| 28 | +import org.mockito.Mockito; | |
| 29 | + | |
| 30 | +import static org.mockito.Mockito.mock; | |
| 28 | 31 | import static org.testng.Assert.*; |
| 29 | 32 | |
| 33 | +import com.datastax.driver.core.policies.ExponentialReconnectionPolicy; | |
| 34 | + | |
| 30 | 35 | /** |
| 31 | 36 | * Base class for replication strategy tests. Currently only supports testing |
| 32 | 37 | * using the default Murmur3Partitioner. |
| @@ -38,13 +43,13 @@ | ||
| 38 | 43 | protected static class HostMock extends Host { |
| 39 | 44 | private final String address; |
| 40 | 45 | |
| 41 | - private HostMock(String address) throws UnknownHostException { | |
| 42 | - super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.Simple.Factory(), null); | |
| 46 | + private HostMock(String address, Cluster.Manager manager) throws UnknownHostException { | |
| 47 | + super(new InetSocketAddress(InetAddress.getByName(address), 9042), new ConvictionPolicy.DefaultConvictionPolicy.Factory(), manager); | |
| 43 | 48 | this.address = address; |
| 44 | 49 | } |
| 45 | 50 | |
| 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); | |
| 48 | 53 | this.setLocationInfo(dc, rack); |
| 49 | 54 | } |
| 50 | 55 | |
| @@ -81,7 +86,7 @@ | ||
| 81 | 86 | */ |
| 82 | 87 | protected static HostMock host(String address) { |
| 83 | 88 | try { |
| 84 | - return new HostMock(address); | |
| 89 | + return new HostMock(address, mock(Cluster.Manager.class)); | |
| 85 | 90 | } catch (UnknownHostException ex) { |
| 86 | 91 | throw new RuntimeException(ex); //wrap to avoid declarations |
| 87 | 92 | } |
| @@ -93,7 +98,7 @@ | ||
| 93 | 98 | */ |
| 94 | 99 | protected static HostMock host(String address, String dc, String rack) { |
| 95 | 100 | try { |
| 96 | - return new HostMock(address, dc, rack); | |
| 101 | + return new HostMock(address, dc, rack, mock(Cluster.Manager.class)); | |
| 97 | 102 | } catch (UnknownHostException ex) { |
| 98 | 103 | throw new RuntimeException(ex); //wrap to avoid declarations |
| 99 | 104 | } |
modified driver-core/src/test/java/com/datastax/driver/core/Assertions.java +8 −0
| @@ -40,4 +40,12 @@ | ||
| 40 | 40 | public static IndexMetadataAssert assertThat(IndexMetadata indexMetadata) { |
| 41 | 41 | return new IndexMetadataAssert(indexMetadata); |
| 42 | 42 | } |
| 43 | + | |
| 44 | + public static KeyspaceMetadataAssert assertThat(KeyspaceMetadata metadata) { | |
| 45 | + return new KeyspaceMetadataAssert(metadata); | |
| 46 | + } | |
| 47 | + | |
| 48 | + public static TableMetadataAssert assertThat(TableMetadata metadata) { | |
| 49 | + return new TableMetadataAssert(metadata); | |
| 50 | + } | |
| 43 | 51 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +78 −3
| @@ -16,26 +16,38 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import java.util.Collection; |
| 19 | +import java.util.concurrent.ExecutionException; | |
| 19 | 20 | import java.util.concurrent.TimeUnit; |
| 20 | 21 | |
| 22 | +import com.google.common.base.Function; | |
| 21 | 23 | import com.google.common.collect.Lists; |
| 24 | +import com.google.common.util.concurrent.AsyncFunction; | |
| 25 | +import com.google.common.util.concurrent.Futures; | |
| 26 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 27 | +import com.google.common.util.concurrent.Uninterruptibles; | |
| 22 | 28 | import org.testng.annotations.Test; |
| 23 | 29 | |
| 30 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 24 | 31 | import static org.testng.Assert.assertEquals; |
| 25 | 32 | import static org.testng.Assert.assertTrue; |
| 26 | 33 | |
| 34 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 35 | + | |
| 27 | 36 | public class AsyncQueryTest extends CCMBridge.PerClassSingleNodeCluster { |
| 28 | 37 | |
| 29 | 38 | @Override |
| 30 | 39 | 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 | + ); | |
| 32 | 44 | } |
| 33 | 45 | |
| 34 | 46 | /** |
| 35 | 47 | * Checks that a cancelled query releases the connection (JAVA-407). |
| 36 | 48 | */ |
| 37 | 49 | @Test(groups = "short") |
| 38 | - public void cancelQueryTest() throws InterruptedException { | |
| 50 | + public void cancelled_query_should_release_the_connection() throws InterruptedException { | |
| 39 | 51 | ResultSetFuture future = session.executeAsync("select release_version from system.local"); |
| 40 | 52 | future.cancel(true); |
| 41 | 53 | assertTrue(future.isCancelled()); |
| @@ -48,8 +60,71 @@ | ||
| 48 | 60 | } |
| 49 | 61 | } |
| 50 | 62 | |
| 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 | + | |
| 51 | 126 | private static HostConnectionPool getPool(Session session) { |
| 52 | - Collection<HostConnectionPool> pools = ((SessionManager) session).pools.values(); | |
| 127 | + Collection<HostConnectionPool> pools = ((SessionManager)session).pools.values(); | |
| 53 | 128 | assertEquals(pools.size(), 1); |
| 54 | 129 | return pools.iterator().next(); |
| 55 | 130 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +17 −11
| @@ -59,36 +59,42 @@ | ||
| 59 | 59 | |
| 60 | 60 | @Test(groups = "short") |
| 61 | 61 | public void should_connect_with_credentials() throws InterruptedException { |
| 62 | + Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 63 | + .withCredentials("cassandra", "cassandra") | |
| 64 | + .build(); | |
| 62 | 65 | try { |
| 63 | - Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 64 | - .withCredentials("cassandra", "cassandra") | |
| 65 | - .build() | |
| 66 | - .connect(); | |
| 66 | + cluster.connect(); | |
| 67 | 67 | } catch (NoHostAvailableException e) { |
| 68 | 68 | logger.error(e.getCustomMessage(1, true, true)); |
| 69 | + } finally { | |
| 70 | + cluster.close(); | |
| 69 | 71 | } |
| 70 | 72 | } |
| 71 | 73 | |
| 72 | 74 | @Test(groups = "short", expectedExceptions = AuthenticationException.class) |
| 73 | 75 | 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(); | |
| 74 | 79 | try { |
| 75 | - Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 76 | - .withCredentials("bogus", "bogus") | |
| 77 | - .build() | |
| 78 | - .connect(); | |
| 80 | + cluster.connect(); | |
| 79 | 81 | } catch (NoHostAvailableException e) { |
| 80 | 82 | logger.error(e.getCustomMessage(1, true, true)); |
| 83 | + } finally { | |
| 84 | + cluster.close(); | |
| 81 | 85 | } |
| 82 | 86 | } |
| 83 | 87 | |
| 84 | 88 | @Test(groups = "short", expectedExceptions = AuthenticationException.class) |
| 85 | 89 | public void should_fail_to_connect_without_credentials() throws InterruptedException { |
| 90 | + Cluster cluster = Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 91 | + .build(); | |
| 86 | 92 | try { |
| 87 | - Cluster.builder().addContactPoint(CCMBridge.IP_PREFIX + '1') | |
| 88 | - .build() | |
| 89 | - .connect(); | |
| 93 | + cluster.connect(); | |
| 90 | 94 | } catch (NoHostAvailableException e) { |
| 91 | 95 | logger.error(e.getCustomMessage(1, true, true)); |
| 96 | + } finally { | |
| 97 | + cluster.close(); | |
| 92 | 98 | } |
| 93 | 99 | } |
| 94 | 100 | } |
modified driver-core/src/test/java/com/datastax/driver/core/CaseSensitivityTest.java +19 −6
| @@ -15,12 +15,13 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.util.*; | |
| 19 | - | |
| 20 | 18 | import org.testng.annotations.Test; |
| 21 | -import static org.testng.Assert.*; | |
| 22 | 19 | |
| 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; | |
| 24 | 25 | |
| 25 | 26 | public class CaseSensitivityTest { |
| 26 | 27 | |
| @@ -36,7 +37,13 @@ | ||
| 36 | 37 | |
| 37 | 38 | @Test(groups = "short") |
| 38 | 39 | 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 | + ); | |
| 40 | 47 | Session s = c.session; |
| 41 | 48 | try { |
| 42 | 49 | String ksName = "MyKeyspace"; |
| @@ -56,7 +63,13 @@ | ||
| 56 | 63 | |
| 57 | 64 | @Test(groups = "short") |
| 58 | 65 | 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 | + ); | |
| 60 | 73 | Session s = c.session; |
| 61 | 74 | try { |
| 62 | 75 | String ksName = "\"MyKeyspace\""; |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterAssert.java +11 −2
| @@ -15,6 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.net.InetSocketAddress; | |
| 18 | 19 | import java.util.Iterator; |
| 19 | 20 | import java.util.Set; |
| 20 | 21 | import java.util.TreeSet; |
| @@ -44,9 +45,17 @@ | ||
| 44 | 45 | public HostAssert host(int hostNumber) { |
| 45 | 46 | // TODO at some point this won't work anymore if we have assertions that wait for a node to |
| 46 | 47 | // 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 | + } | |
| 48 | 52 | |
| 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); | |
| 50 | 59 | } |
| 51 | 60 | |
| 52 | 61 | /** |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +106 −65
| @@ -17,28 +17,39 @@ | ||
| 17 | 17 | |
| 18 | 18 | import java.net.InetAddress; |
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | +import java.net.UnknownHostException; | |
| 20 | 21 | import java.util.Collections; |
| 21 | 22 | import java.util.List; |
| 23 | +import java.util.Map; | |
| 22 | 24 | import java.util.concurrent.TimeUnit; |
| 23 | 25 | import java.util.concurrent.TimeoutException; |
| 24 | 26 | |
| 27 | +import com.google.common.collect.ImmutableMap; | |
| 28 | +import com.google.common.collect.ImmutableSet; | |
| 25 | 29 | 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; | |
| 26 | 33 | import org.slf4j.Logger; |
| 27 | 34 | import org.slf4j.LoggerFactory; |
| 35 | +import org.testng.SkipException; | |
| 28 | 36 | import org.testng.annotations.Test; |
| 29 | 37 | |
| 30 | -import static org.assertj.core.api.Assertions.fail; | |
| 38 | +import static org.mockito.Mockito.atLeast; | |
| 39 | +import static org.mockito.Mockito.atMost; | |
| 31 | 40 | import static org.mockito.Mockito.spy; |
| 32 | -import static org.mockito.Mockito.times; | |
| 33 | 41 | import static org.mockito.Mockito.verify; |
| 34 | 42 | |
| 35 | 43 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 36 | 44 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 37 | -import com.datastax.driver.core.querybuilder.Insert; | |
| 38 | -import com.datastax.driver.core.utils.UUIDs; | |
| 45 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 39 | 46 | |
| 47 | +import static com.datastax.driver.core.Assertions.*; | |
| 40 | 48 | import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS; |
| 41 | -import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto; | |
| 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; | |
| 42 | 53 | |
| 43 | 54 | public class ClusterInitTest { |
| 44 | 55 | private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class); |
| @@ -47,45 +58,64 @@ | ||
| 47 | 58 | * Test for JAVA-522: when the cluster and session initialize, if some contact points are behaving badly and |
| 48 | 59 | * causing timeouts, we want to ensure that the driver does not wait multiple times on the same host. |
| 49 | 60 | */ |
| 50 | - | |
| 51 | 61 | @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 | + | |
| 54 | 67 | Cluster cluster = null; |
| 55 | - List<FakeHost> fakeHosts = Lists.newArrayList(); | |
| 68 | + Scassandra scassandra = null; | |
| 69 | + List<FakeHost> failingHosts = Lists.newArrayList(); | |
| 56 | 70 | 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(); | |
| 66 | 84 | } |
| 67 | 85 | |
| 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); | |
| 72 | 91 | |
| 73 | 92 | logger.info("Environment is set up, starting test"); |
| 74 | 93 | long start = System.nanoTime(); |
| 75 | 94 | |
| 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. | |
| 78 | 97 | SocketOptions socketOptions = spy(new SocketOptions()); |
| 79 | 98 | |
| 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 | |
| 81 | 100 | ConstantReconnectionPolicy reconnectionPolicy = new ConstantReconnectionPolicy(3600 * 1000); |
| 82 | 101 | |
| 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 | + ) | |
| 86 | 114 | .withSocketOptions(socketOptions) |
| 87 | 115 | .withReconnectionPolicy(reconnectionPolicy) |
| 116 | + .withPoolingOptions(poolingOptions) | |
| 88 | 117 | .withProtocolVersion(TestUtils.getDesiredProtocolVersion()) |
| 118 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 89 | 119 | .build(); |
| 90 | 120 | cluster.connect(); |
| 91 | 121 | |
| @@ -93,69 +123,80 @@ | ||
| 93 | 123 | long initTimeMs = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS); |
| 94 | 124 | logger.info("Cluster and session initialized in {} ms", initTimeMs); |
| 95 | 125 | |
| 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 | + | |
| 99 | 140 | } finally { |
| 100 | 141 | if (cluster != null) |
| 101 | 142 | cluster.close(); |
| 102 | - for (FakeHost fakeHost : fakeHosts) | |
| 143 | + for (FakeHost fakeHost : failingHosts) | |
| 103 | 144 | fakeHost.stop(); |
| 104 | - if (ccm != null) | |
| 105 | - ccm.remove(); | |
| 145 | + if (scassandra != null) | |
| 146 | + scassandra.stop(); | |
| 106 | 147 | } |
| 107 | 148 | } |
| 108 | 149 | |
| 109 | 150 | /** |
| 110 | - * <p> | |
| 111 | 151 | * Validates that a Cluster that was never able to successfully establish connection a session can be closed |
| 112 | 152 | * properly. |
| 113 | 153 | * |
| 114 | 154 | * @test_category connection |
| 115 | 155 | * @expected_result Cluster closes within 1 second. |
| 116 | 156 | */ |
| 117 | - @Test(groups="unit") | |
| 157 | + @Test(groups = "unit") | |
| 118 | 158 | public void should_be_able_to_close_cluster_that_never_successfully_connected() throws Exception { |
| 119 | 159 | 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(); | |
| 122 | 162 | try { |
| 123 | 163 | cluster.connect(); |
| 124 | 164 | fail("Should not have been able to connect."); |
| 125 | - } catch(NoHostAvailableException e) {} // Expected. | |
| 165 | + } catch (NoHostAvailableException e) { | |
| 166 | + } // Expected. | |
| 126 | 167 | CloseFuture closeFuture = cluster.closeAsync(); |
| 127 | 168 | try { |
| 128 | 169 | closeFuture.get(1, TimeUnit.SECONDS); |
| 129 | - } catch(TimeoutException e) { | |
| 170 | + } catch (TimeoutException e) { | |
| 130 | 171 | fail("Close Future did not complete quickly."); |
| 131 | 172 | } |
| 132 | 173 | } |
| 133 | 174 | |
| 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 = 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("release_version", "2.0.1") | |
| 191 | + .put("tokens", ImmutableSet.of(Long.toString(Long.MIN_VALUE + i++))) | |
| 192 | + .build()); | |
| 159 | 193 | } |
| 194 | + | |
| 195 | + primingClient.prime( | |
| 196 | + PrimingRequest.queryBuilder() | |
| 197 | + .withQuery("SELECT * FROM system.peers") | |
| 198 | + .withColumnTypes(SCassandraCluster.SELECT_PEERS_COLUMN_TYPES) | |
| 199 | + .withRows(rows) | |
| 200 | + .build()); | |
| 160 | 201 | } |
| 161 | 202 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ControlConnectionTest.java +70 −3
| @@ -15,13 +15,21 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.net.InetAddress; | |
| 18 | 19 | import java.util.Iterator; |
| 20 | +import java.util.Map; | |
| 19 | 21 | import java.util.concurrent.TimeUnit; |
| 20 | 22 | import java.util.concurrent.atomic.AtomicInteger; |
| 21 | 23 | |
| 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; | |
| 22 | 29 | import org.testng.annotations.Test; |
| 23 | 30 | |
| 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; | |
| 25 | 33 | |
| 26 | 34 | import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy; |
| 27 | 35 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| @@ -30,6 +38,9 @@ | ||
| 30 | 38 | import com.datastax.driver.core.utils.CassandraVersion; |
| 31 | 39 | |
| 32 | 40 | public class ControlConnectionTest { |
| 41 | + | |
| 42 | + static final Logger logger = LoggerFactory.getLogger(ControlConnectionTest.class); | |
| 43 | + | |
| 33 | 44 | @Test(groups = "short") |
| 34 | 45 | public void should_prevent_simultaneous_reconnection_attempts() throws InterruptedException { |
| 35 | 46 | CCMBridge ccm = null; |
| @@ -135,8 +146,9 @@ | ||
| 135 | 146 | ccm = CCMBridge.builder("test").withNodes(3).build(); |
| 136 | 147 | |
| 137 | 148 | cluster = Cluster.builder() |
| 138 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 139 | - .build(); | |
| 149 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 150 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 151 | + .build(); | |
| 140 | 152 | cluster.init(); |
| 141 | 153 | |
| 142 | 154 | // Ensure the control connection host is that of the first node. |
| @@ -158,6 +170,61 @@ | ||
| 158 | 170 | } |
| 159 | 171 | } |
| 160 | 172 | |
| 173 | + /** | |
| 174 | + * <p> | |
| 175 | + * Ensures that contact points are randomized when determining the initial control connection | |
| 176 | + * by default. Initializes a cluster with 5 contact points 100 times and ensures that all 5 | |
| 177 | + * were used. | |
| 178 | + * </p> | |
| 179 | + * | |
| 180 | + * @jira_ticket JAVA-618 | |
| 181 | + * @expected_result All 5 hosts were chosen within 100 attempts. There is a very small possibility | |
| 182 | + * that this may not be the case and this is not actually an error. | |
| 183 | + * @test_category control_connection | |
| 184 | + * @since 2.0.11, 2.1.8, 2.2.0 | |
| 185 | + */ | |
| 186 | + @Test(groups = "short") | |
| 187 | + public void should_randomize_contact_points_when_determining_control_connection() { | |
| 188 | + int hostCount = 5; | |
| 189 | + int iterations = 100; | |
| 190 | + SCassandraCluster scassandras = new SCassandraCluster(hostCount); | |
| 191 | + | |
| 192 | + try { | |
| 193 | + final HashMultiset<InetAddress> occurrencesByHost = HashMultiset.create(hostCount); | |
| 194 | + for(int i = 0; i < iterations; i++) { | |
| 195 | + Cluster cluster = Cluster.builder() | |
| 196 | + .addContactPoints(scassandras.addresses()) | |
| 197 | + .build(); | |
| 198 | + | |
| 199 | + try { | |
| 200 | + cluster.init(); | |
| 201 | + occurrencesByHost.add(cluster.manager.controlConnection.connectedHost().getAddress()); | |
| 202 | + } finally { | |
| 203 | + cluster.close(); | |
| 204 | + } | |
| 205 | + } | |
| 206 | + if(logger.isDebugEnabled()) { | |
| 207 | + Map<InetAddress, Integer> hostCounts = Maps.toMap(occurrencesByHost.elementSet(), new Function<InetAddress, Integer>() { | |
| 208 | + @Override | |
| 209 | + public Integer apply(InetAddress input) { | |
| 210 | + return occurrencesByHost.count(input); | |
| 211 | + } | |
| 212 | + }); | |
| 213 | + logger.debug("Control Connection Use Counts by Host: {}", hostCounts); | |
| 214 | + } | |
| 215 | + // There is an incredibly low chance that a host may not be used based on randomness. | |
| 216 | + // This probability is very low however. | |
| 217 | + assertThat(occurrencesByHost.elementSet().size()) | |
| 218 | + .as("Not all hosts were used as contact points. There is a very small chance" | |
| 219 | + + " of this happening based on randomness, investigate whether or not this" | |
| 220 | + + " is a bug.") | |
| 221 | + .isEqualTo(hostCount); | |
| 222 | + } finally { | |
| 223 | + scassandras.stop(); | |
| 224 | + } | |
| 225 | + | |
| 226 | + } | |
| 227 | + | |
| 161 | 228 | static class QueryPlanCountingPolicy extends DelegatingLoadBalancingPolicy { |
| 162 | 229 | |
| 163 | 230 | final AtomicInteger counter = new AtomicInteger(); |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeAssert.java +8 −0
| @@ -30,6 +30,14 @@ | ||
| 30 | 30 | return this; |
| 31 | 31 | } |
| 32 | 32 | |
| 33 | + public DataTypeAssert isUserType(String keyspaceName, String userTypeName) { | |
| 34 | + assertThat(actual).isInstanceOf(UserType.class); | |
| 35 | + UserType userType = (UserType)this.actual; | |
| 36 | + assertThat(userType.getKeyspace()).isEqualTo(keyspaceName); | |
| 37 | + assertThat(userType.getTypeName()).isEqualTo(userTypeName); | |
| 38 | + return this; | |
| 39 | + } | |
| 40 | + | |
| 33 | 41 | public DataTypeAssert isFrozen() { |
| 34 | 42 | assertThat(actual.isFrozen()).isTrue(); |
| 35 | 43 | 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 −384
| @@ -1,384 +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 org.testng.annotations.Test; | |
| 22 | - | |
| 23 | -import static com.datastax.driver.core.TestUtils.waitForDownWithWait; | |
| 24 | -import static org.testng.Assert.assertEquals; | |
| 25 | -import static org.testng.Assert.assertTrue; | |
| 26 | - | |
| 27 | -/** | |
| 28 | - * Tests Exception classes with seperate clusters per test, when applicable | |
| 29 | - */ | |
| 30 | -public class ExceptionsTest { | |
| 31 | - | |
| 32 | - /** | |
| 33 | - * Tests the AlreadyExistsException. | |
| 34 | - * Create a keyspace twice and a table twice. | |
| 35 | - * Catch and test all the exception methods. | |
| 36 | - */ | |
| 37 | - @Test(groups = "short") | |
| 38 | - public void alreadyExistsException() throws Throwable { | |
| 39 | - Cluster.Builder builder = Cluster.builder(); | |
| 40 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); | |
| 41 | - try { | |
| 42 | - String keyspace = "TestKeyspace"; | |
| 43 | - String table = "TestTable"; | |
| 44 | - | |
| 45 | - String[] cqlCommands = new String[]{ | |
| 46 | - String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1), | |
| 47 | - "USE " + keyspace, | |
| 48 | - String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table) | |
| 49 | - }; | |
| 50 | - | |
| 51 | - // Create the schema once | |
| 52 | - c.session.execute(cqlCommands[0]); | |
| 53 | - c.session.execute(cqlCommands[1]); | |
| 54 | - c.session.execute(cqlCommands[2]); | |
| 55 | - | |
| 56 | - // Try creating the keyspace again | |
| 57 | - try { | |
| 58 | - c.session.execute(cqlCommands[0]); | |
| 59 | - } catch (AlreadyExistsException e) { | |
| 60 | - String expected = String.format("Keyspace %s already exists", keyspace.toLowerCase()); | |
| 61 | - assertEquals(e.getMessage(), expected); | |
| 62 | - assertEquals(e.getKeyspace(), keyspace.toLowerCase()); | |
| 63 | - assertEquals(e.getTable(), null); | |
| 64 | - assertEquals(e.wasTableCreation(), false); | |
| 65 | - } | |
| 66 | - | |
| 67 | - c.session.execute(cqlCommands[1]); | |
| 68 | - | |
| 69 | - // Try creating the table again | |
| 70 | - try { | |
| 71 | - c.session.execute(cqlCommands[2]); | |
| 72 | - } catch (AlreadyExistsException e) { | |
| 73 | - // is released | |
| 74 | - assertEquals(e.getKeyspace(), keyspace.toLowerCase()); | |
| 75 | - assertEquals(e.getTable(), table.toLowerCase()); | |
| 76 | - assertEquals(e.wasTableCreation(), true); | |
| 77 | - } | |
| 78 | - } catch (Throwable e) { | |
| 79 | - throw e; | |
| 80 | - } finally { | |
| 81 | - c.discard(); | |
| 82 | - } | |
| 83 | - } | |
| 84 | - | |
| 85 | - /** | |
| 86 | - * Tests DriverInternalError. | |
| 87 | - * Tests basic message, rethrow, and copy abilities. | |
| 88 | - */ | |
| 89 | - @Test(groups = "unit") | |
| 90 | - public void driverInternalError() throws Exception { | |
| 91 | - String errorMessage = "Test Message"; | |
| 92 | - | |
| 93 | - try { | |
| 94 | - throw new DriverInternalError(errorMessage); | |
| 95 | - } catch (DriverInternalError e1) { | |
| 96 | - try { | |
| 97 | - throw new DriverInternalError(e1); | |
| 98 | - } catch (DriverInternalError e2) { | |
| 99 | - assertTrue(e2.getMessage().contains(errorMessage)); | |
| 100 | - | |
| 101 | - DriverInternalError copy = (DriverInternalError) e2.copy(); | |
| 102 | - assertEquals(copy.getMessage(), e2.getMessage()); | |
| 103 | - } | |
| 104 | - } | |
| 105 | - } | |
| 106 | - | |
| 107 | - /** | |
| 108 | - * Tests InvalidConfigurationInQueryException. | |
| 109 | - * Tests basic message abilities. | |
| 110 | - */ | |
| 111 | - @Test(groups = "unit") | |
| 112 | - public void invalidConfigurationInQueryException() throws Exception { | |
| 113 | - String errorMessage = "Test Message"; | |
| 114 | - | |
| 115 | - try { | |
| 116 | - throw new InvalidConfigurationInQueryException(errorMessage); | |
| 117 | - } catch (InvalidConfigurationInQueryException e) { | |
| 118 | - assertEquals(e.getMessage(), errorMessage); | |
| 119 | - } | |
| 120 | - } | |
| 121 | - | |
| 122 | - /** | |
| 123 | - * Tests InvalidQueryException. | |
| 124 | - * Tests basic message and copy abilities. | |
| 125 | - */ | |
| 126 | - @Test(groups = "unit") | |
| 127 | - public void invalidQueryException() throws Exception { | |
| 128 | - String errorMessage = "Test Message"; | |
| 129 | - | |
| 130 | - try { | |
| 131 | - throw new InvalidQueryException(errorMessage); | |
| 132 | - } catch (InvalidQueryException e) { | |
| 133 | - assertEquals(e.getMessage(), errorMessage); | |
| 134 | - | |
| 135 | - InvalidQueryException copy = (InvalidQueryException) e.copy(); | |
| 136 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 137 | - } | |
| 138 | - } | |
| 139 | - | |
| 140 | - /** | |
| 141 | - * Tests InvalidTypeException. | |
| 142 | - * Tests basic message and copy abilities. | |
| 143 | - */ | |
| 144 | - @Test(groups = "unit") | |
| 145 | - public void invalidTypeException() throws Exception { | |
| 146 | - String errorMessage = "Test Message"; | |
| 147 | - | |
| 148 | - try { | |
| 149 | - throw new InvalidTypeException(errorMessage); | |
| 150 | - } catch (InvalidTypeException e) { | |
| 151 | - assertEquals(e.getMessage(), errorMessage); | |
| 152 | - | |
| 153 | - InvalidTypeException copy = (InvalidTypeException) e.copy(); | |
| 154 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 155 | - } | |
| 156 | - } | |
| 157 | - | |
| 158 | - /** | |
| 159 | - * Tests the NoHostAvailableException. | |
| 160 | - * by attempting to build a cluster using the IP address "255.255.255.255" | |
| 161 | - * and test all available exception methods. | |
| 162 | - */ | |
| 163 | - @Test(groups = "short") | |
| 164 | - public void noHostAvailableException() throws Exception { | |
| 165 | - try { | |
| 166 | - Cluster.builder().addContactPoints("255.255.255.255").build(); | |
| 167 | - } catch (NoHostAvailableException e) { | |
| 168 | - assertEquals(e.getErrors().size(), 1); | |
| 169 | - assertTrue(e.getErrors().values().iterator().next().toString().contains("[/255.255.255.255] Cannot connect")); | |
| 170 | - | |
| 171 | - NoHostAvailableException copy = (NoHostAvailableException) e.copy(); | |
| 172 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 173 | - assertEquals(copy.getErrors(), e.getErrors()); | |
| 174 | - } | |
| 175 | - } | |
| 176 | - | |
| 177 | - /** | |
| 178 | - * Tests the ReadTimeoutException. | |
| 179 | - * Create a 3 node cluster and write out a single key at CL.ALL. | |
| 180 | - * Then forcibly kill single node and attempt a read of the key at CL.ALL. | |
| 181 | - * Catch and test all available exception methods. | |
| 182 | - */ | |
| 183 | - @Test(groups = "long") | |
| 184 | - public void readTimeoutException() throws Throwable { | |
| 185 | - Cluster.Builder builder = Cluster.builder(); | |
| 186 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 187 | - try { | |
| 188 | - String keyspace = "TestKeyspace"; | |
| 189 | - String table = "TestTable"; | |
| 190 | - int replicationFactor = 3; | |
| 191 | - String key = "1"; | |
| 192 | - | |
| 193 | - c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor)); | |
| 194 | - c.session.execute("USE " + keyspace); | |
| 195 | - c.session.execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table)); | |
| 196 | - | |
| 197 | - c.session.execute(new SimpleStatement(String.format(Locale.US, TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 198 | - c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 199 | - | |
| 200 | - c.cassandraCluster.forceStop(2); | |
| 201 | - try{ | |
| 202 | - c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 203 | - } catch (ReadTimeoutException e) { | |
| 204 | - assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL); | |
| 205 | - assertEquals(e.getReceivedAcknowledgements(), 2); | |
| 206 | - assertEquals(e.getRequiredAcknowledgements(), 3); | |
| 207 | - assertEquals(e.wasDataRetrieved(), true); | |
| 208 | - | |
| 209 | - ReadTimeoutException copy = (ReadTimeoutException) e.copy(); | |
| 210 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 211 | - assertEquals(copy.wasDataRetrieved(), e.wasDataRetrieved()); | |
| 212 | - } | |
| 213 | - } catch (Throwable e) { | |
| 214 | - throw e; | |
| 215 | - } finally { | |
| 216 | - c.discard(); | |
| 217 | - } | |
| 218 | - } | |
| 219 | - | |
| 220 | - /** | |
| 221 | - * Tests SyntaxError. | |
| 222 | - * Tests basic message and copy abilities. | |
| 223 | - */ | |
| 224 | - @Test(groups = "unit") | |
| 225 | - public void syntaxError() throws Exception { | |
| 226 | - String errorMessage = "Test Message"; | |
| 227 | - | |
| 228 | - try { | |
| 229 | - throw new SyntaxError(errorMessage); | |
| 230 | - } catch (SyntaxError e) { | |
| 231 | - assertEquals(e.getMessage(), errorMessage); | |
| 232 | - | |
| 233 | - SyntaxError copy = (SyntaxError) e.copy(); | |
| 234 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 235 | - } | |
| 236 | - } | |
| 237 | - | |
| 238 | - /** | |
| 239 | - * Tests TraceRetrievalException. | |
| 240 | - * Tests basic message and copy abilities. | |
| 241 | - */ | |
| 242 | - @Test(groups = "unit") | |
| 243 | - public void traceRetrievalException() throws Exception { | |
| 244 | - String errorMessage = "Test Message"; | |
| 245 | - | |
| 246 | - try { | |
| 247 | - throw new TraceRetrievalException(errorMessage); | |
| 248 | - } catch (TraceRetrievalException e) { | |
| 249 | - assertEquals(e.getMessage(), errorMessage); | |
| 250 | - | |
| 251 | - TraceRetrievalException copy = (TraceRetrievalException) e.copy(); | |
| 252 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 253 | - } | |
| 254 | - } | |
| 255 | - | |
| 256 | - /** | |
| 257 | - * Tests TruncateException. | |
| 258 | - * Tests basic message and copy abilities. | |
| 259 | - */ | |
| 260 | - @Test(groups = "unit") | |
| 261 | - public void truncateException() throws Exception { | |
| 262 | - String errorMessage = "Test Message"; | |
| 263 | - | |
| 264 | - try { | |
| 265 | - throw new TruncateException(errorMessage); | |
| 266 | - } catch (TruncateException e) { | |
| 267 | - assertEquals(e.getMessage(), errorMessage); | |
| 268 | - | |
| 269 | - TruncateException copy = (TruncateException) e.copy(); | |
| 270 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 271 | - } | |
| 272 | - } | |
| 273 | - | |
| 274 | - /** | |
| 275 | - * Tests UnauthorizedException. | |
| 276 | - * Tests basic message and copy abilities. | |
| 277 | - */ | |
| 278 | - @Test(groups = "unit") | |
| 279 | - public void unauthorizedException() throws Exception { | |
| 280 | - String errorMessage = "Test Message"; | |
| 281 | - | |
| 282 | - try { | |
| 283 | - throw new UnauthorizedException(errorMessage); | |
| 284 | - } catch (UnauthorizedException e) { | |
| 285 | - assertEquals(e.getMessage(), errorMessage); | |
| 286 | - | |
| 287 | - UnauthorizedException copy = (UnauthorizedException) e.copy(); | |
| 288 | - assertEquals(copy.getMessage(), e.getMessage()); | |
| 289 | - } | |
| 290 | - } | |
| 291 | - | |
| 292 | - /** | |
| 293 | - * Tests the UnavailableException. | |
| 294 | - * Create a 3 node cluster and write out a single key at CL.ALL. | |
| 295 | - * Then kill single node, wait for gossip to propogate the new state, | |
| 296 | - * and attempt to read and write the same key at CL.ALL. | |
| 297 | - * Catch and test all available exception methods. | |
| 298 | - */ | |
| 299 | - @Test(groups = "long") | |
| 300 | - public void unavailableException() throws Throwable { | |
| 301 | - Cluster.Builder builder = Cluster.builder(); | |
| 302 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 303 | - try { | |
| 304 | - String keyspace = "TestKeyspace"; | |
| 305 | - String table = "TestTable"; | |
| 306 | - int replicationFactor = 3; | |
| 307 | - String key = "1"; | |
| 308 | - | |
| 309 | - c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor)); | |
| 310 | - c.session.execute("USE " + keyspace); | |
| 311 | - c.session.execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table)); | |
| 312 | - | |
| 313 | - c.session.execute(new SimpleStatement(String.format(Locale.US, TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 314 | - c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 315 | - | |
| 316 | - c.cassandraCluster.stop(2); | |
| 317 | - | |
| 318 | - waitForDownWithWait(CCMBridge.IP_PREFIX + '2', c.cluster, 10); | |
| 319 | - | |
| 320 | - try{ | |
| 321 | - c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 322 | - } catch (UnavailableException e) { | |
| 323 | - String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2); | |
| 324 | - assertEquals(e.getMessage(), expectedError); | |
| 325 | - assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL); | |
| 326 | - assertEquals(e.getRequiredReplicas(), replicationFactor); | |
| 327 | - assertEquals(e.getAliveReplicas(), replicationFactor - 1); | |
| 328 | - } | |
| 329 | - | |
| 330 | - try{ | |
| 331 | - c.session.execute(new SimpleStatement(String.format(Locale.US, TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 332 | - } catch (UnavailableException e) { | |
| 333 | - String expectedError = String.format("Not enough replica available for query at consistency %s (%d required but only %d alive)", "ALL", 3, 2); | |
| 334 | - assertEquals(e.getMessage(), expectedError); | |
| 335 | - assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL); | |
| 336 | - assertEquals(e.getRequiredReplicas(), replicationFactor); | |
| 337 | - assertEquals(e.getAliveReplicas(), replicationFactor - 1); | |
| 338 | - } | |
| 339 | - } catch (Throwable e) { | |
| 340 | - throw e; | |
| 341 | - } finally { | |
| 342 | - c.discard(); | |
| 343 | - } | |
| 344 | - } | |
| 345 | - | |
| 346 | - /** | |
| 347 | - * Tests the WriteTimeoutException. | |
| 348 | - * Create a 3 node cluster and write out a single key at CL.ALL. | |
| 349 | - * Then forcibly kill single node and attempt to write the same key at CL.ALL. | |
| 350 | - * Catch and test all available exception methods. | |
| 351 | - */ | |
| 352 | - @Test(groups = "long") | |
| 353 | - public void writeTimeoutException() throws Throwable { | |
| 354 | - Cluster.Builder builder = Cluster.builder(); | |
| 355 | - CCMBridge.CCMCluster c = CCMBridge.buildCluster(3, builder); | |
| 356 | - try { | |
| 357 | - String keyspace = "TestKeyspace"; | |
| 358 | - String table = "TestTable"; | |
| 359 | - int replicationFactor = 3; | |
| 360 | - String key = "1"; | |
| 361 | - | |
| 362 | - c.session.execute(String.format(TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, replicationFactor)); | |
| 363 | - c.session.execute("USE " + keyspace); | |
| 364 | - c.session.execute(String.format(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, table)); | |
| 365 | - | |
| 366 | - c.session.execute(new SimpleStatement(String.format(Locale.US, TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 367 | - c.session.execute(new SimpleStatement(String.format(TestUtils.SELECT_ALL_FORMAT, table)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 368 | - | |
| 369 | - c.cassandraCluster.forceStop(2); | |
| 370 | - try{ | |
| 371 | - c.session.execute(new SimpleStatement(String.format(Locale.US, TestUtils.INSERT_FORMAT, table, key, "foo", 42, 24.03f)).setConsistencyLevel(ConsistencyLevel.ALL)); | |
| 372 | - } catch (WriteTimeoutException e) { | |
| 373 | - assertEquals(e.getConsistencyLevel(), ConsistencyLevel.ALL); | |
| 374 | - assertEquals(e.getReceivedAcknowledgements(), 2); | |
| 375 | - assertEquals(e.getRequiredAcknowledgements(), 3); | |
| 376 | - assertEquals(e.getWriteType(), WriteType.SIMPLE); | |
| 377 | - } | |
| 378 | - } catch (Throwable e) { | |
| 379 | - throw e; | |
| 380 | - } finally { | |
| 381 | - c.discard(); | |
| 382 | - } | |
| 383 | - } | |
| 384 | -} |
modified driver-core/src/test/java/com/datastax/driver/core/FakeHost.java +1 −1
| @@ -31,7 +31,7 @@ | ||
| 31 | 31 | public class FakeHost { |
| 32 | 32 | public enum Behavior {THROWING_CONNECT_TIMEOUTS, THROWING_OPERATION_TIMEOUTS} |
| 33 | 33 | |
| 34 | - private final String address; | |
| 34 | + final String address; | |
| 35 | 35 | private final int port; |
| 36 | 36 | private final Behavior behavior; |
| 37 | 37 | private final ExecutorService executor; |
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 @@ | ||
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| 23 | 23 | import static com.datastax.driver.core.Assertions.assertThat; |
| 24 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 24 | 25 | import static com.datastax.driver.core.TestUtils.waitFor; |
| 25 | 26 | |
| 26 | 27 | public class MetadataTest { |
| @@ -58,6 +59,7 @@ | ||
| 58 | 59 | |
| 59 | 60 | cluster = Cluster.builder() |
| 60 | 61 | .addContactPoint(CCMBridge.ipOfNode(1)) |
| 62 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 61 | 63 | .build(); |
| 62 | 64 | Session session = cluster.connect(); |
| 63 | 65 |
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +9 −4
| @@ -23,6 +23,8 @@ | ||
| 23 | 23 | import io.netty.channel.EventLoopGroup; |
| 24 | 24 | import io.netty.channel.nio.NioEventLoopGroup; |
| 25 | 25 | import io.netty.channel.socket.SocketChannel; |
| 26 | +import io.netty.util.HashedWheelTimer; | |
| 27 | +import io.netty.util.Timer; | |
| 26 | 28 | import org.mockito.ArgumentCaptor; |
| 27 | 29 | import org.mockito.invocation.InvocationOnMock; |
| 28 | 30 | import org.mockito.stubbing.Answer; |
| @@ -52,7 +54,9 @@ | ||
| 52 | 54 | try { |
| 53 | 55 | NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get()); |
| 54 | 56 | 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)); | |
| 56 | 60 | final ChannelHandler handler = mock(ChannelHandler.class); |
| 57 | 61 | doAnswer(new Answer() { |
| 58 | 62 | @Override |
| @@ -80,17 +84,18 @@ | ||
| 80 | 84 | |
| 81 | 85 | cluster.close(); |
| 82 | 86 | // then |
| 83 | - ArgumentCaptor<EventLoopGroup> captor = ArgumentCaptor.forClass(EventLoopGroup.class); | |
| 84 | 87 | verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class)); |
| 85 | 88 | verify(nettyOptions, times(1)).channelClass(); |
| 89 | + verify(nettyOptions, times(1)).timer(any(ThreadFactory.class)); | |
| 86 | 90 | // per-connection hooks will be called coreConnections * hosts + 1 times: |
| 87 | 91 | // the extra call is for the control connection |
| 88 | 92 | verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class)); |
| 89 | 93 | verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class)); |
| 90 | 94 | verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class)); |
| 91 | 95 | 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); | |
| 94 | 99 | } finally { |
| 95 | 100 | if (cluster != null) |
| 96 | 101 | cluster.close(); |
modified driver-core/src/test/java/com/datastax/driver/core/NetworkTopologyStrategyTest.java +31 −0
| @@ -22,6 +22,8 @@ | ||
| 22 | 22 | import com.google.common.collect.ImmutableList; |
| 23 | 23 | import com.google.common.collect.ImmutableMap; |
| 24 | 24 | import com.google.common.collect.ImmutableMap.Builder; |
| 25 | +import com.google.common.collect.Lists; | |
| 26 | +import com.google.common.collect.Maps; | |
| 25 | 27 | import org.apache.log4j.Level; |
| 26 | 28 | import org.apache.log4j.Logger; |
| 27 | 29 | import org.testng.annotations.Test; |
| @@ -104,6 +106,18 @@ | ||
| 104 | 106 | |
| 105 | 107 | private static final ReplicationStrategy exampleStrategyTooManyReplicas = networkTopologyStrategy(rf(DC1, 4), rf(DC2, 4)); |
| 106 | 108 | |
| 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 | + | |
| 107 | 121 | private static final List<Token> exampleRing = ImmutableList.<Token>builder() |
| 108 | 122 | .add(TOKEN01) |
| 109 | 123 | .add(TOKEN02) |
| @@ -570,6 +584,23 @@ | ||
| 570 | 584 | assertReplicaPlacement(replicaMap, TOKEN18, IP6, IP1, IP5, IP2); |
| 571 | 585 | } |
| 572 | 586 | |
| 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 | + | |
| 573 | 604 | @Test(groups = "unit") |
| 574 | 605 | public void networkTopologyStrategyExampleTopologyTooManyReplicasTest() { |
| 575 | 606 | 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 +81 −0
| @@ -0,0 +1,81 @@ | ||
| 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.testng.annotations.Test; | |
| 23 | + | |
| 24 | +import static com.google.common.collect.Lists.newArrayList; | |
| 25 | +import static org.mockito.ArgumentCaptor.forClass; | |
| 26 | +import static org.mockito.Mockito.mock; | |
| 27 | +import static org.mockito.Mockito.timeout; | |
| 28 | +import static org.mockito.Mockito.verify; | |
| 29 | + | |
| 30 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 31 | + | |
| 32 | +public class NodeRefreshDebouncerTest extends CCMBridge.PerClassSingleNodeCluster { | |
| 33 | + | |
| 34 | + @Override | |
| 35 | + protected Collection<String> getTableDefinitions() { | |
| 36 | + return newArrayList(); | |
| 37 | + } | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * Ensures that when a new node is bootstrapped into the cluster, stopped, and then subsequently | |
| 41 | + * started within {@link QueryOptions#setRefreshNodeIntervalMillis(int)} that an 'onAdd' event | |
| 42 | + * event is the only one processed and that the {@link Host} is marked up. | |
| 43 | + * <p> | |
| 44 | + * Since NEW_NODE_DELAY_SECONDS is typically configured with a high value (60 seconds default | |
| 45 | + * in the maven profile) this test can take a very long time. | |
| 46 | + * | |
| 47 | + * @jira_ticket JAVA-657 | |
| 48 | + * @since 2.0.11 | |
| 49 | + */ | |
| 50 | + @Test(groups="long") | |
| 51 | + public void should_call_onAdd_with_bootstrap_stop_start() { | |
| 52 | + int refreshNodeInterval = 10000; | |
| 53 | + QueryOptions queryOptions = new QueryOptions().setRefreshNodeIntervalMillis(refreshNodeInterval); | |
| 54 | + CCMBridge ccm = CCMBridge.builder("test").withNodes(1).build(); | |
| 55 | + Cluster cluster = Cluster.builder() | |
| 56 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 57 | + .withQueryOptions(queryOptions) | |
| 58 | + .build(); | |
| 59 | + | |
| 60 | + try { | |
| 61 | + cluster.connect(); | |
| 62 | + Host.StateListener listener = mock(Host.StateListener.class); | |
| 63 | + cluster.register(listener); | |
| 64 | + ccm.bootstrapNode(2); | |
| 65 | + ccm.stop(2); | |
| 66 | + ccm.start(2); | |
| 67 | + | |
| 68 | + ArgumentCaptor<Host> captor = forClass(Host.class); | |
| 69 | + | |
| 70 | + // Only onAdd should be called, since stop and start should be discarded. | |
| 71 | + verify(listener, timeout(refreshNodeInterval + TimeUnit.MILLISECONDS.convert(Cluster.NEW_NODE_DELAY_SECONDS, TimeUnit.SECONDS)).only()).onAdd(captor.capture()); | |
| 72 | + | |
| 73 | + // The hosts state should be UP. | |
| 74 | + assertThat(captor.getValue().getState()).isEqualTo("UP"); | |
| 75 | + assertThat(cluster).host(2).hasState(Host.State.UP); | |
| 76 | + } finally { | |
| 77 | + cluster.close(); | |
| 78 | + ccm.remove(); | |
| 79 | + } | |
| 80 | + } | |
| 81 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/PreparedStatementTest.java +14 −46
| @@ -110,6 +110,11 @@ | ||
| 110 | 110 | return defs; |
| 111 | 111 | } |
| 112 | 112 | |
| 113 | + @Override | |
| 114 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 115 | + return builder.withQueryOptions(TestUtils.nonDebouncingQueryOptions()); | |
| 116 | + } | |
| 117 | + | |
| 113 | 118 | @Test(groups = "short") |
| 114 | 119 | public void preparedNativeTest() { |
| 115 | 120 | // Test preparing/bounding for all native types |
| @@ -296,47 +301,6 @@ | ||
| 296 | 301 | } |
| 297 | 302 | } |
| 298 | 303 | |
| 299 | - private void reprepareOnNewlyUpNodeTest(String ks, Session session) throws Exception { | |
| 300 | - | |
| 301 | - ks = ks == null ? "" : ks + '.'; | |
| 302 | - | |
| 303 | - session.execute("INSERT INTO " + ks + "test (k, i) VALUES ('123', 17)"); | |
| 304 | - session.execute("INSERT INTO " + ks + "test (k, i) VALUES ('124', 18)"); | |
| 305 | - | |
| 306 | - PreparedStatement ps = session.prepare("SELECT * FROM " + ks + "test WHERE k = ?"); | |
| 307 | - | |
| 308 | - assertEquals(session.execute(ps.bind("123")).one().getInt("i"), 17); | |
| 309 | - | |
| 310 | - ccmBridge.stop(); | |
| 311 | - waitForDown(CCMBridge.IP_PREFIX + '1', cluster); | |
| 312 | - | |
| 313 | - ccmBridge.start(); | |
| 314 | - waitFor(CCMBridge.IP_PREFIX + '1', cluster, 120); | |
| 315 | - | |
| 316 | - try | |
| 317 | - { | |
| 318 | - assertEquals(session.execute(ps.bind("124")).one().getInt("i"), 18); | |
| 319 | - } | |
| 320 | - catch (NoHostAvailableException e) | |
| 321 | - { | |
| 322 | - System.out.println(">> " + e.getErrors()); | |
| 323 | - throw e; | |
| 324 | - } | |
| 325 | - } | |
| 326 | - | |
| 327 | - @Test(groups = "long") | |
| 328 | - public void reprepareOnNewlyUpNodeTest() throws Exception { | |
| 329 | - reprepareOnNewlyUpNodeTest(null, session); | |
| 330 | - } | |
| 331 | - | |
| 332 | - @Test(groups = "long") | |
| 333 | - public void reprepareOnNewlyUpNodeNoKeyspaceTest() throws Exception { | |
| 334 | - | |
| 335 | - // This is the same test than reprepareOnNewlyUpNodeTest, except that the | |
| 336 | - // prepared statement is prepared while no current keyspace is used | |
| 337 | - reprepareOnNewlyUpNodeTest(keyspace, cluster.connect()); | |
| 338 | - } | |
| 339 | - | |
| 340 | 304 | @Test(groups = "short") |
| 341 | 305 | public void prepareWithNullValuesTest() throws Exception { |
| 342 | 306 | |
| @@ -461,10 +425,14 @@ | ||
| 461 | 425 | Cluster otherCluster = Cluster.builder() |
| 462 | 426 | .addContactPointsWithPorts(ImmutableList.of(hostAddress)) |
| 463 | 427 | .build(); |
| 464 | - PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?"); | |
| 465 | - BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost")); | |
| 466 | - | |
| 467 | - // We expect that the error gets detected without a roundtrip to the server, so use executeAsync | |
| 468 | - session.executeAsync(bs); | |
| 428 | + try { | |
| 429 | + PreparedStatement pst = otherCluster.connect().prepare("select * from system.peers where inet = ?"); | |
| 430 | + BoundStatement bs = pst.bind().setInet(0, InetAddress.getByName("localhost")); | |
| 431 | + | |
| 432 | + // We expect that the error gets detected without a roundtrip to the server, so use executeAsync | |
| 433 | + session.executeAsync(bs); | |
| 434 | + } finally { | |
| 435 | + otherCluster.close(); | |
| 436 | + } | |
| 469 | 437 | } |
| 470 | 438 | } |
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 @@ | ||
| 20 | 20 | import org.slf4j.Logger; |
| 21 | 21 | import org.slf4j.LoggerFactory; |
| 22 | 22 | import org.testng.annotations.AfterMethod; |
| 23 | +import org.testng.annotations.BeforeMethod; | |
| 23 | 24 | import org.testng.annotations.Test; |
| 24 | 25 | |
| 25 | 26 | |
| @@ -28,7 +29,7 @@ | ||
| 28 | 29 | import static com.datastax.driver.core.Assertions.*; |
| 29 | 30 | import static com.datastax.driver.core.Host.State.DOWN; |
| 30 | 31 | import static com.datastax.driver.core.Host.State.UP; |
| 31 | - | |
| 32 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 32 | 33 | |
| 33 | 34 | /** |
| 34 | 35 | * Due to C* gossip bugs, system.peers may report nodes that are gone from the cluster. |
| @@ -50,7 +51,8 @@ | ||
| 50 | 51 | mainCcm.waitForDown(1); |
| 51 | 52 | |
| 52 | 53 | // 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(); | |
| 54 | 56 | mainCluster.connect(); |
| 55 | 57 | waitForCountUpHosts(mainCluster, 2); |
| 56 | 58 | // From that point, reconnections to node1 have been scheduled. |
| @@ -72,7 +74,8 @@ | ||
| 72 | 74 | mainCcm.waitForDown(1); |
| 73 | 75 | |
| 74 | 76 | // 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(); | |
| 76 | 79 | mainCluster.connect(); |
| 77 | 80 | waitForCountUpHosts(mainCluster, 1); |
| 78 | 81 | |
| @@ -99,7 +102,8 @@ | ||
| 99 | 102 | otherCcm.waitForUp(1); |
| 100 | 103 | |
| 101 | 104 | // 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(); | |
| 103 | 107 | |
| 104 | 108 | // When we first initialize the Cluster, all hosts are marked UP |
| 105 | 109 | assertThat(mainCluster).host(2).hasState(UP); |
| @@ -127,7 +131,8 @@ | ||
| 127 | 131 | otherCcm.waitForUp(1); |
| 128 | 132 | |
| 129 | 133 | // 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(); | |
| 131 | 136 | |
| 132 | 137 | // Create a session. This will try to open a pool to node 1 and find that it doesn't support protocol version. |
| 133 | 138 | mainCluster.connect(); |
| @@ -139,6 +144,14 @@ | ||
| 139 | 144 | .isNotReconnectingFromDown(); |
| 140 | 145 | } |
| 141 | 146 | |
| 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 | + | |
| 142 | 155 | @AfterMethod(groups = "long") |
| 143 | 156 | public void teardown() { |
| 144 | 157 | if (mainCluster != null) |
| @@ -160,8 +173,8 @@ | ||
| 160 | 173 | } |
| 161 | 174 | |
| 162 | 175 | 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; | |
| 165 | 178 | |
| 166 | 179 | for (int i = 0; i <= maxRetries; i++) { |
| 167 | 180 | int actualCount = countUpHosts(cluster); |
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +15 −56
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | import java.util.Collections; |
| 21 | 21 | import java.util.Iterator; |
| 22 | -import java.util.Map; | |
| 23 | 22 | import java.util.concurrent.ConcurrentHashMap; |
| 24 | 23 | import java.util.concurrent.ConcurrentMap; |
| 25 | 24 | import java.util.concurrent.TimeUnit; |
| @@ -27,8 +26,6 @@ | ||
| 27 | 26 | |
| 28 | 27 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 29 | 28 | |
| 30 | -import com.google.common.base.Charsets; | |
| 31 | -import com.google.common.collect.ImmutableMap; | |
| 32 | 29 | import com.google.common.util.concurrent.ListenableFuture; |
| 33 | 30 | import org.testng.annotations.Test; |
| 34 | 31 | |
| @@ -72,7 +69,7 @@ | ||
| 72 | 69 | ccm.start(2); |
| 73 | 70 | ccm.waitForUp(2); |
| 74 | 71 | |
| 75 | - assertThat(cluster).host(2).comesUpWithin(120, SECONDS); | |
| 72 | + assertThat(cluster).host(2).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS); | |
| 76 | 73 | |
| 77 | 74 | // Give the control connection a few moments to reconnect |
| 78 | 75 | TimeUnit.MILLISECONDS.sleep(reconnectionDelay * 2); |
| @@ -96,7 +93,7 @@ | ||
| 96 | 93 | .build(); |
| 97 | 94 | ccm.start(1, "-Dcassandra.superuser_setup_delay_ms=0"); |
| 98 | 95 | |
| 99 | - DynamicPlainTextAuthProvider authProvider = new DynamicPlainTextAuthProvider("cassandra", "cassandra"); | |
| 96 | + CountingAuthProvider authProvider = new CountingAuthProvider("cassandra", "cassandra"); | |
| 100 | 97 | int reconnectionDelayMs = 1000; |
| 101 | 98 | CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs)); |
| 102 | 99 | |
| @@ -113,7 +110,7 @@ | ||
| 113 | 110 | // Stop the server, set wrong credentials and restart |
| 114 | 111 | ccm.stop(1); |
| 115 | 112 | ccm.waitForDown(1); |
| 116 | - authProvider.password = "wrongPassword"; | |
| 113 | + authProvider.setPassword("wrongPassword"); | |
| 117 | 114 | ccm.start(1); |
| 118 | 115 | ccm.waitForUp(1); |
| 119 | 116 | |
| @@ -128,10 +125,10 @@ | ||
| 128 | 125 | assertThat(iterations).isLessThan(maxIterations); |
| 129 | 126 | |
| 130 | 127 | // Fix the credentials |
| 131 | - authProvider.password = "cassandra"; | |
| 128 | + authProvider.setPassword("cassandra"); | |
| 132 | 129 | |
| 133 | 130 | // 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); | |
| 135 | 132 | } finally { |
| 136 | 133 | if (cluster != null) |
| 137 | 134 | cluster.close(); |
| @@ -171,7 +168,7 @@ | ||
| 171 | 168 | ccm.waitForUp(2); |
| 172 | 169 | |
| 173 | 170 | // 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); | |
| 175 | 172 | |
| 176 | 173 | } finally { |
| 177 | 174 | if (cluster != null) |
| @@ -232,7 +229,7 @@ | ||
| 232 | 229 | // Trigger another one-time reconnection attempt (this will succeed). The |
| 233 | 230 | // host should be back up. |
| 234 | 231 | host1.tryReconnectOnce(); |
| 235 | - assertThat(cluster).host(1).comesUpWithin(120, SECONDS); | |
| 232 | + assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS); | |
| 236 | 233 | } finally { |
| 237 | 234 | if (cluster != null) |
| 238 | 235 | cluster.close(); |
| @@ -290,7 +287,7 @@ | ||
| 290 | 287 | // Reset the spy and count the number of connections attempts for 1 reconnect |
| 291 | 288 | reset(socketOptions); |
| 292 | 289 | host1.tryReconnectOnce(); |
| 293 | - assertThat(cluster).host(1).comesUpWithin(120, SECONDS); | |
| 290 | + assertThat(cluster).host(1).comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS*2, SECONDS); | |
| 294 | 291 | // Expect 1 connection from the reconnection attempt 3 for the pools (we need 4 |
| 295 | 292 | // but the one from the reconnection attempt gets reused). |
| 296 | 293 | verify(socketOptions, times(corePoolSize * 2)).getKeepAlive(); |
| @@ -301,57 +298,19 @@ | ||
| 301 | 298 | ccm.remove(); |
| 302 | 299 | } |
| 303 | 300 | } |
| 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; | |
| 311 | 301 | |
| 302 | + /** Extends the plain text auth provider to track how many times the credentials have been requested */ | |
| 303 | + static class CountingAuthProvider extends PlainTextAuthProvider { | |
| 312 | 304 | final AtomicInteger count = new AtomicInteger(); |
| 313 | 305 | |
| 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); | |
| 317 | 308 | } |
| 318 | 309 | |
| 310 | + @Override | |
| 319 | 311 | 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); | |
| 355 | 314 | } |
| 356 | 315 | } |
| 357 | 316 |
modified driver-core/src/test/java/com/datastax/driver/core/RefreshConnectedHostTest.java +1 −0
| @@ -53,6 +53,7 @@ | ||
| 53 | 53 | .withPoolingOptions(poolingOptions) |
| 54 | 54 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 55 | 55 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) |
| 56 | + .withQueryOptions(TestUtils.nonDebouncingQueryOptions()) | |
| 56 | 57 | .build(); |
| 57 | 58 | |
| 58 | 59 | Session session = cluster.connect(); |
modified driver-core/src/test/java/com/datastax/driver/core/SCassandraCluster.java +35 −3
| @@ -43,6 +43,10 @@ | ||
| 43 | 43 | private final List<PrimingClient> primingClients; |
| 44 | 44 | private final List<ActivityClient> activityClients; |
| 45 | 45 | |
| 46 | + public SCassandraCluster(int nodeCount) { | |
| 47 | + this(CCMBridge.IP_PREFIX, nodeCount); | |
| 48 | + } | |
| 49 | + | |
| 46 | 50 | public SCassandraCluster(String ipPrefix, int nodeCount) { |
| 47 | 51 | scassandras = Lists.newArrayListWithCapacity(nodeCount); |
| 48 | 52 | addresses = Lists.newArrayListWithCapacity(nodeCount); |
| @@ -81,6 +85,16 @@ | ||
| 81 | 85 | scassandra.stop(); |
| 82 | 86 | } |
| 83 | 87 | |
| 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 | + | |
| 84 | 98 | public SCassandraCluster prime(int node, PrimingRequest request) { |
| 85 | 99 | primingClients.get(node - 1).prime(request); |
| 86 | 100 | return this; |
| @@ -90,6 +104,14 @@ | ||
| 90 | 104 | return activityClients.get(node - 1).retrieveQueries(); |
| 91 | 105 | } |
| 92 | 106 | |
| 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 | + | |
| 93 | 115 | public void clearAllPrimes() { |
| 94 | 116 | for (PrimingClient primingClient : primingClients) |
| 95 | 117 | primingClient.clearAllPrimes(); |
| @@ -113,14 +135,24 @@ | ||
| 113 | 135 | if (scassandras.get(i).equals(toIgnore)) |
| 114 | 136 | continue; |
| 115 | 137 | InetAddress address = addresses.get(i); |
| 116 | - rows.add(ImmutableMap.<String, Object>builder() | |
| 138 | + Map<String, ?> row = ImmutableMap.<String, Object>builder() | |
| 117 | 139 | .put("peer", address) |
| 118 | 140 | .put("rpc_address", address) |
| 119 | 141 | .put("data_center", "datacenter1") |
| 120 | 142 | .put("rack", "rack1") |
| 121 | 143 | .put("release_version", "2.0.1") |
| 122 | 144 | .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()); | |
| 124 | 156 | } |
| 125 | 157 | primingClient.prime( |
| 126 | 158 | PrimingRequest.queryBuilder() |
| @@ -130,7 +162,7 @@ | ||
| 130 | 162 | .build()); |
| 131 | 163 | } |
| 132 | 164 | |
| 133 | - private static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES = | |
| 165 | + static final ImmutableMap<String, ColumnTypes> SELECT_PEERS_COLUMN_TYPES = | |
| 134 | 166 | ImmutableMap.<String, ColumnTypes>builder() |
| 135 | 167 | .put("peer", ColumnTypes.Inet) |
| 136 | 168 | .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 +336 −72
| @@ -15,53 +15,105 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.util.Collection; | |
| 19 | +import java.util.Collections; | |
| 18 | 20 | import java.util.List; |
| 19 | 21 | |
| 20 | 22 | import com.google.common.collect.Lists; |
| 21 | 23 | import com.google.common.util.concurrent.Futures; |
| 22 | 24 | import com.google.common.util.concurrent.ListenableFuture; |
| 25 | +import org.mockito.ArgumentCaptor; | |
| 23 | 26 | import org.testng.annotations.*; |
| 24 | 27 | |
| 28 | +import static org.mockito.Matchers.any; | |
| 29 | +import static org.mockito.Mockito.*; | |
| 30 | + | |
| 25 | 31 | import com.datastax.driver.core.utils.Bytes; |
| 26 | 32 | import com.datastax.driver.core.utils.CassandraVersion; |
| 27 | 33 | |
| 28 | 34 | 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 { | |
| 39 | + | |
| 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"; | |
| 43 | + | |
| 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"; | |
| 29 | 47 | |
| 30 | -public class SchemaChangesTest { | |
| 31 | - private static final String CREATE_KEYSPACE = | |
| 32 | - "CREATE KEYSPACE %s WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor': '1' }"; | |
| 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; | |
| 33 | 50 | |
| 34 | - CCMBridge ccm; | |
| 35 | - Cluster cluster; | |
| 51 | + Cluster cluster1; | |
| 36 | 52 | Cluster cluster2; // a second cluster to check that other clients also get notified |
| 53 | + Cluster schemaDisabledCluster; // a cluster with schema metadata disabled. | |
| 37 | 54 | |
| 38 | 55 | // The metadatas of the two clusters (we'll test that they're kept in sync) |
| 39 | 56 | List<Metadata> metadatas; |
| 40 | 57 | |
| 41 | - Session session; | |
| 58 | + Session session1; | |
| 42 | 59 | |
| 43 | - @BeforeClass(groups = "short") | |
| 44 | - public void setup() { | |
| 45 | - ccm = CCMBridge.builder("schemaChangesTest").withNodes(1).build(); | |
| 60 | + Session schemaDisabledSession; | |
| 61 | + | |
| 62 | + SchemaChangeListener listener1; | |
| 63 | + SchemaChangeListener listener2; | |
| 64 | + SchemaChangeListener schemaDisabledListener; | |
| 46 | 65 | |
| 47 | - cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 48 | - cluster2 = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)).build(); | |
| 66 | + List<SchemaChangeListener> listeners; | |
| 49 | 67 | |
| 50 | - metadatas = Lists.newArrayList(cluster.getMetadata(), cluster2.getMetadata()); | |
| 68 | + ControlConnection schemaDisabledControlConnection; | |
| 69 | + | |
| 70 | + @Override | |
| 71 | + protected Collection<String> getTableDefinitions() { | |
| 72 | + return Lists.newArrayList(); | |
| 73 | + } | |
| 51 | 74 | |
| 52 | - session = cluster.connect(); | |
| 53 | - session.execute(String.format(CREATE_KEYSPACE, "lowercase")); | |
| 54 | - 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\""); | |
| 55 | 107 | } |
| 56 | 108 | |
| 57 | 109 | @AfterClass(groups = "short") |
| 58 | 110 | public void teardown() { |
| 59 | - if (cluster != null) | |
| 60 | - cluster.close(); | |
| 111 | + if (cluster1 != null) | |
| 112 | + cluster1.close(); | |
| 61 | 113 | if (cluster2 != null) |
| 62 | 114 | cluster2.close(); |
| 63 | - if (ccm != null) | |
| 64 | - ccm.remove(); | |
| 115 | + if (schemaDisabledCluster != null) | |
| 116 | + schemaDisabledCluster.close(); | |
| 65 | 117 | } |
| 66 | 118 | |
| 67 | 119 | |
| @@ -70,42 +122,110 @@ | ||
| 70 | 122 | return new Object[][]{ { "lowercase" }, { "\"CaseSensitive\"" } }; |
| 71 | 123 | } |
| 72 | 124 | |
| 73 | - @Test(groups = "short", dataProvider = "existingKeyspaceName") | |
| 74 | - public void should_notify_of_table_creation(String keyspace) { | |
| 75 | - 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 | + } | |
| 76 | 129 | |
| 77 | - for (Metadata m : metadatas) | |
| 78 | - assertThat(m.getKeyspace(keyspace).getTable("table1")) | |
| 79 | - .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); | |
| 80 | 148 | } |
| 81 | 149 | |
| 82 | 150 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 83 | - public void should_notify_of_table_update(String keyspace) { | |
| 84 | - session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace)); | |
| 85 | - 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 | + } | |
| 86 | 160 | |
| 87 | 161 | for (Metadata m : metadatas) |
| 88 | - assertThat(m.getKeyspace(keyspace).getTable("table1").getColumn("j")) | |
| 89 | - .isNotNull(); | |
| 162 | + assertThat(m.getKeyspace(keyspace).getTable("table1")).isNotNull(); | |
| 90 | 163 | } |
| 91 | 164 | |
| 92 | 165 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 93 | - public void should_notify_of_table_drop(String keyspace) { | |
| 94 | - session.execute(String.format("CREATE TABLE %s.table1(i int primary key)", keyspace)); | |
| 95 | - session.execute(String.format("DROP TABLE %s.table1", keyspace)); | |
| 96 | - | |
| 166 | + public void should_notify_of_table_update(String keyspace) throws InterruptedException { | |
| 167 | + execute(CREATE_TABLE, keyspace); | |
| 97 | 168 | for (Metadata m : metadatas) |
| 98 | - assertThat(m.getKeyspace(keyspace).getTable("table1")) | |
| 99 | - .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"); | |
| 100 | 193 | } |
| 101 | 194 | |
| 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 | + | |
| 102 | 215 | @Test(groups = "short", dataProvider = "existingKeyspaceName") |
| 103 | 216 | @CassandraVersion(major = 2.1) |
| 104 | 217 | public void should_notify_of_udt_creation(String keyspace) { |
| 105 | 218 | session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); |
| 106 | 219 | |
| 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 | + | |
| 107 | 227 | for (Metadata m : metadatas) |
| 108 | - assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")) | |
| 228 | + assertThat((DataType)m.getKeyspace(keyspace).getUserType("type1")) | |
| 109 | 229 | .isNotNull(); |
| 110 | 230 | } |
| 111 | 231 | |
| @@ -115,6 +235,14 @@ | ||
| 115 | 235 | session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); |
| 116 | 236 | session.execute(String.format("ALTER TYPE %s.type1 ADD j int", keyspace)); |
| 117 | 237 | |
| 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 | + | |
| 118 | 246 | for (Metadata m : metadatas) |
| 119 | 247 | assertThat(m.getKeyspace(keyspace).getUserType("type1").getFieldType("j")) |
| 120 | 248 | .isNotNull(); |
| @@ -126,65 +254,201 @@ | ||
| 126 | 254 | session.execute(String.format("CREATE TYPE %s.type1(i int)", keyspace)); |
| 127 | 255 | session.execute(String.format("DROP TYPE %s.type1", keyspace)); |
| 128 | 256 | |
| 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 | + | |
| 129 | 263 | for (Metadata m : metadatas) |
| 130 | 264 | assertThat((DataType) m.getKeyspace(keyspace).getUserType("type1")) |
| 131 | 265 | .isNull(); |
| 132 | 266 | } |
| 133 | 267 | |
| 134 | - @DataProvider(name = "newKeyspaceName") | |
| 135 | - public static Object[][] newKeyspaceName() { | |
| 136 | - return new Object[][]{ { "lowercase2" }, { "\"CaseSensitive2\"" } }; | |
| 137 | - } | |
| 138 | - | |
| 139 | 268 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 140 | - public void should_notify_of_keyspace_creation(String keyspace) { | |
| 141 | - session.execute(String.format(CREATE_KEYSPACE, keyspace)); | |
| 142 | - | |
| 269 | + public void should_notify_of_keyspace_creation(String keyspace) throws InterruptedException { | |
| 270 | + execute(CREATE_KEYSPACE, keyspace); | |
| 143 | 271 | for (Metadata m : metadatas) |
| 144 | - assertThat(m.getKeyspace(keyspace)) | |
| 145 | - .isNotNull(); | |
| 272 | + assertThat(m.getKeyspace(keyspace)).isNotNull(); | |
| 273 | + for (SchemaChangeListener listener : listeners) { | |
| 274 | + ArgumentCaptor<KeyspaceMetadata> added = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 275 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); | |
| 276 | + assertThat(added.getValue()).hasName(handleId(keyspace)); | |
| 277 | + } | |
| 146 | 278 | } |
| 147 | 279 | |
| 148 | 280 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 149 | - public void should_notify_of_keyspace_update(String keyspace) { | |
| 150 | - session.execute(String.format(CREATE_KEYSPACE, keyspace)); | |
| 281 | + public void should_notify_of_keyspace_update(String keyspace) throws InterruptedException { | |
| 282 | + execute(CREATE_KEYSPACE, keyspace); | |
| 283 | + ArgumentCaptor<KeyspaceMetadata> added = null; | |
| 284 | + for (SchemaChangeListener listener : listeners) { | |
| 285 | + added = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 286 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceAdded(added.capture()); | |
| 287 | + assertThat(added.getValue()).hasName(handleId(keyspace)); | |
| 288 | + } | |
| 151 | 289 | for (Metadata m : metadatas) |
| 152 | - assertThat(m.getKeyspace(keyspace).isDurableWrites()) | |
| 153 | - .isTrue(); | |
| 154 | - | |
| 155 | - session.execute(String.format("ALTER KEYSPACE %s WITH durable_writes = false", keyspace)); | |
| 290 | + assertThat(m.getKeyspace(keyspace).isDurableWrites()).isTrue(); | |
| 291 | + execute(ALTER_KEYSPACE, keyspace); | |
| 292 | + for (SchemaChangeListener listener : listeners) { | |
| 293 | + ArgumentCaptor<KeyspaceMetadata> current = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 294 | + ArgumentCaptor<KeyspaceMetadata> previous = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 295 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceChanged(current.capture(), previous.capture()); | |
| 296 | + assertThat(previous.getValue()) | |
| 297 | + .isEqualTo(added.getValue()) | |
| 298 | + .isDurableWrites(); | |
| 299 | + assertThat(current.getValue()) | |
| 300 | + .hasName(handleId(keyspace)) | |
| 301 | + .isNotDurableWrites(); | |
| 302 | + } | |
| 156 | 303 | for (Metadata m : metadatas) |
| 157 | - assertThat(m.getKeyspace(keyspace).isDurableWrites()) | |
| 158 | - .isFalse(); | |
| 304 | + assertThat(m.getKeyspace(keyspace)).isNotDurableWrites(); | |
| 159 | 305 | } |
| 160 | 306 | |
| 161 | 307 | @Test(groups = "short", dataProvider = "newKeyspaceName") |
| 162 | - public void should_notify_of_keyspace_drop(String keyspace) { | |
| 163 | - session.execute(String.format(CREATE_KEYSPACE, keyspace)); | |
| 308 | + public void should_notify_of_keyspace_drop(String keyspace) throws InterruptedException { | |
| 309 | + execute(CREATE_KEYSPACE, keyspace); | |
| 164 | 310 | for (Metadata m : metadatas) |
| 165 | - assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))) | |
| 166 | - .isNotEmpty(); | |
| 311 | + assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isNotEmpty(); | |
| 312 | + execute(CREATE_TABLE, keyspace); // to test table drop notifications | |
| 313 | + execute(DROP_KEYSPACE, keyspace); | |
| 314 | + for (SchemaChangeListener listener : listeners) { | |
| 315 | + ArgumentCaptor<TableMetadata> table = ArgumentCaptor.forClass(TableMetadata.class); | |
| 316 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onTableRemoved(table.capture()); | |
| 317 | + assertThat(table.getValue()) | |
| 318 | + .hasName("table1") | |
| 319 | + .isInKeyspace(handleId(keyspace)); | |
| 320 | + | |
| 321 | + ArgumentCaptor<KeyspaceMetadata> ks = ArgumentCaptor.forClass(KeyspaceMetadata.class); | |
| 322 | + verify(listener, timeout(NOTIF_TIMEOUT_MS).times(1)).onKeyspaceRemoved(ks.capture()); | |
| 323 | + assertThat(ks.getValue()) | |
| 324 | + .hasName(handleId(keyspace)); | |
| 325 | + } | |
| 326 | + for (Metadata m : metadatas) { | |
| 327 | + assertThat(m.getKeyspace(keyspace)).isNull(); | |
| 328 | + assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))).isEmpty(); | |
| 329 | + } | |
| 330 | + } | |
| 167 | 331 | |
| 168 | - session.execute(String.format("DROP KEYSPACE %s", keyspace)); | |
| 169 | 332 | |
| 170 | - for (Metadata m : metadatas) { | |
| 171 | - assertThat(m.getKeyspace(keyspace)) | |
| 172 | - .isNull(); | |
| 173 | - assertThat(m.getReplicas(keyspace, Bytes.fromHexString("0xCAFEBABE"))) | |
| 174 | - .isEmpty(); | |
| 333 | + /** | |
| 334 | + * Ensures that calling {@link Metadata#newToken(String)} on a Cluster that has schema | |
| 335 | + * metadata disabled will throw a {@link IllegalStateException}. | |
| 336 | + * | |
| 337 | + * @jira_ticket JAVA-858 | |
| 338 | + * @since 2.0.11 | |
| 339 | + */ | |
| 340 | + @Test(groups = "short", expectedExceptions = IllegalStateException.class) | |
| 341 | + public void should_throw_illegal_state_exception_on_newToken_with_metadata_disabled() { | |
| 342 | + Cluster cluster = configure(Cluster.builder()) | |
| 343 | + .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 344 | + .withQueryOptions(nonDebouncingQueryOptions() | |
| 345 | + .setMetadataEnabled(false) | |
| 346 | + ).build(); | |
| 347 | + | |
| 348 | + try { | |
| 349 | + cluster.init(); | |
| 350 | + cluster.getMetadata().newToken("0x00"); | |
| 351 | + } finally { | |
| 352 | + cluster.close(); | |
| 353 | + } | |
| 354 | + } | |
| 355 | + | |
| 356 | + | |
| 357 | + /** | |
| 358 | + * Ensures that calling {@link Metadata#newTokenRange(Token, Token)} on a Cluster that has schema | |
| 359 | + * metadata disabled will throw a {@link IllegalStateException}. | |
| 360 | + * | |
| 361 | + * @jira_ticket JAVA-858 | |
| 362 | + * @since 2.0.11 | |
| 363 | + */ | |
| 364 | + @Test(groups = "short", expectedExceptions = IllegalStateException.class) | |
| 365 | + public void should_throw_illegal_state_exception_on_newTokenRange_with_metadata_disabled() { | |
| 366 | + Cluster cluster = configure(Cluster.builder()) | |
| 367 | + .addContactPointsWithPorts(Collections.singletonList(hostAddress)) | |
| 368 | + .withQueryOptions(nonDebouncingQueryOptions() | |
| 369 | + .setMetadataEnabled(false) | |
| 370 | + ).build(); | |
| 371 | + | |
| 372 | + try { | |
| 373 | + cluster.init(); | |
| 374 | + Token.Factory factory = Token.getFactory("Murmur3Partitioner"); | |
| 375 | + Token token = factory.fromString(Long.toString(1)); | |
| 376 | + cluster.getMetadata().newTokenRange(token, token); | |
| 377 | + } finally { | |
| 378 | + cluster.close(); | |
| 379 | + } | |
| 380 | + } | |
| 381 | + | |
| 382 | + /** | |
| 383 | + * Ensures that executing a query causing a schema change with a Cluster that has schema metadata | |
| 384 | + * disabled will still wait on schema agreement, but not refresh the schema. | |
| 385 | + * | |
| 386 | + * @jira_ticket JAVA-858 | |
| 387 | + * @since 2.0.11 | |
| 388 | + */ | |
| 389 | + @Test(groups = "short") | |
| 390 | + public void should_not_refresh_schema_on_schema_change_response() throws InterruptedException { | |
| 391 | + ResultSet rs = schemaDisabledSession.execute(String.format(CREATE_TABLE, keyspace)); | |
| 392 | + | |
| 393 | + // Should still wait on schema agreement. | |
| 394 | + assertThat(rs.getExecutionInfo().isSchemaInAgreement()).isTrue(); | |
| 395 | + assertThat(schemaDisabledCluster.getMetadata().checkSchemaAgreement()).isTrue(); | |
| 396 | + | |
| 397 | + // Wait up to 1 second (since refreshSchema submitted in an executor) and check that refreshSchema never called. | |
| 398 | + verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(any(SchemaElement.class), any(String.class), any(String.class)); | |
| 399 | + } | |
| 400 | + | |
| 401 | + /** | |
| 402 | + * Ensures that when schema metadata is enabled using {@link QueryOptions#setMetadataEnabled(boolean)} | |
| 403 | + * that a schema and nodelist refresh is submitted, but only if schema metadata is currently disabled. | |
| 404 | + * | |
| 405 | + * @jira_ticket JAVA-858 | |
| 406 | + * @since 2.0.11 | |
| 407 | + */ | |
| 408 | + @Test(groups = "short") | |
| 409 | + public void should_refresh_schema_and_token_map_if_schema_metadata_reenabled() throws Exception { | |
| 410 | + try { | |
| 411 | + schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true); | |
| 412 | + | |
| 413 | + verify(schemaDisabledControlConnection, after(1000)).refreshSchema(null, null, null); | |
| 414 | + verify(schemaDisabledControlConnection).refreshNodeListAndTokenMap(); | |
| 415 | + | |
| 416 | + // Ensure that there is schema metadata. | |
| 417 | + assertThat(schemaDisabledCluster.getMetadata().getKeyspace(keyspace)).isNotNull(); | |
| 418 | + Token token1 = schemaDisabledCluster.getMetadata().newToken("0"); | |
| 419 | + Token token2 = schemaDisabledCluster.getMetadata().newToken("111111"); | |
| 420 | + assertThat(token1).isNotNull(); | |
| 421 | + assertThat(token2).isNotNull(); | |
| 422 | + assertThat(schemaDisabledCluster.getMetadata().newTokenRange(token1, token2)).isNotNull(); | |
| 423 | + | |
| 424 | + assertThat(schemaDisabledCluster.getMetadata().getTokenRanges()).isNotNull().isNotEmpty(); | |
| 425 | + | |
| 426 | + // Try enabling again and ensure schema is not refreshed again. | |
| 427 | + reset(schemaDisabledControlConnection); | |
| 428 | + schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(true); | |
| 429 | + verify(schemaDisabledControlConnection, after(1000).never()).refreshSchema(null, null, null); | |
| 430 | + verify(schemaDisabledControlConnection, never()).refreshNodeListAndTokenMap(); | |
| 431 | + } finally { | |
| 432 | + // Reset listener mock to not count it's interactions in this test. | |
| 433 | + reset(schemaDisabledListener); | |
| 434 | + schemaDisabledCluster.getConfiguration().getQueryOptions().setMetadataEnabled(false); | |
| 175 | 435 | } |
| 176 | 436 | } |
| 177 | 437 | |
| 178 | 438 | @AfterMethod(groups = "short") |
| 179 | - public void cleanup() { | |
| 439 | + public void cleanup() throws InterruptedException { | |
| 180 | 440 | ListenableFuture<List<ResultSet>> f = Futures.successfulAsList(Lists.newArrayList( |
| 181 | - session.executeAsync("DROP TABLE lowercase.table1"), | |
| 182 | - session.executeAsync("DROP TABLE \"CaseSensitive\".table1"), | |
| 183 | - session.executeAsync("DROP TYPE lowercase.type1"), | |
| 184 | - session.executeAsync("DROP TYPE \"CaseSensitive\".type1"), | |
| 185 | - session.executeAsync("DROP KEYSPACE lowercase2"), | |
| 186 | - session.executeAsync("DROP KEYSPACE \"CaseSensitive2\"") | |
| 441 | + session1.executeAsync("DROP TABLE lowercase.table1"), | |
| 442 | + session1.executeAsync("DROP TABLE \"CaseSensitive\".table1"), | |
| 443 | + session1.executeAsync("DROP TYPE lowercase.type1"), | |
| 444 | + session1.executeAsync("DROP TYPE \"CaseSensitive\".type1"), | |
| 445 | + session1.executeAsync("DROP KEYSPACE lowercase2"), | |
| 446 | + session1.executeAsync("DROP KEYSPACE \"CaseSensitive2\"") | |
| 187 | 447 | )); |
| 188 | 448 | Futures.getUnchecked(f); |
| 189 | 449 | } |
| 450 | + | |
| 451 | + private void execute(String cql, String keyspace) throws InterruptedException { | |
| 452 | + session1.execute(String.format(cql, keyspace)); | |
| 453 | + } | |
| 190 | 454 | } |
added driver-core/src/test/java/com/datastax/driver/core/SchemaRefreshDebouncerTest.java +315 −0
| @@ -0,0 +1,315 @@ | ||
| 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.annotations.AfterClass; | |
| 22 | +import org.testng.annotations.AfterMethod; | |
| 23 | +import org.testng.annotations.BeforeClass; | |
| 24 | +import org.testng.annotations.Test; | |
| 25 | + | |
| 26 | +import static com.google.common.collect.Lists.newArrayList; | |
| 27 | +import static org.mockito.ArgumentCaptor.forClass; | |
| 28 | +import static org.mockito.Mockito.*; | |
| 29 | + | |
| 30 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 31 | +import static com.datastax.driver.core.SchemaElement.KEYSPACE; | |
| 32 | +import static com.datastax.driver.core.SchemaElement.TABLE; | |
| 33 | +import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; | |
| 34 | +import static com.datastax.driver.core.TestUtils.CREATE_TABLE_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); | |
| 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_SIMPLE_FORMAT, 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); | |
| 158 | + verify(controlConnection, never()).refreshSchema(TABLE, keyspace, table); | |
| 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_SIMPLE_FORMAT, 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); | |
| 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); | |
| 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 | + String keyspace = "sdacmaeost"; | |
| 219 | + String table = "tbl1"; | |
| 220 | + String comment = "I am changing this table."; | |
| 221 | + String columnName = "added_column"; | |
| 222 | + // Execute on session 2 which refreshes schema as part of processing responses. | |
| 223 | + session2.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, keyspace, 1)); | |
| 224 | + keyspaces.add(keyspace); | |
| 225 | + session2.execute(String.format(CREATE_TABLE_SIMPLE_FORMAT, keyspace + "." + table)); | |
| 226 | + reset(controlConnection); | |
| 227 | + reset(listener); | |
| 228 | + | |
| 229 | + session.execute(String.format("ALTER TABLE %s.%s WITH comment = '%s'", keyspace, table, comment)); | |
| 230 | + session.execute(String.format("ALTER TABLE %s.%s ADD %s int", keyspace, table, columnName)); | |
| 231 | + | |
| 232 | + ArgumentCaptor<TableMetadata> original = forClass(TableMetadata.class); | |
| 233 | + ArgumentCaptor<TableMetadata> captor = forClass(TableMetadata.class); | |
| 234 | + verify(listener, timeout(DEBOUNCE_TIME * 2).only()).onTableChanged(captor.capture(), original.capture()); | |
| 235 | + assertThat(captor.getValue()) | |
| 236 | + .hasName(table) | |
| 237 | + .isInKeyspace(keyspace) | |
| 238 | + .hasColumn(columnName) | |
| 239 | + .hasComment(comment); | |
| 240 | + | |
| 241 | + assertThat(original.getValue()) | |
| 242 | + .hasName(table) | |
| 243 | + .isInKeyspace(keyspace) | |
| 244 | + .hasNoColumn(columnName) | |
| 245 | + .doesNotHaveComment(comment); | |
| 246 | + | |
| 247 | + // Verify a refresh of the table was executed, but only once. | |
| 248 | + verify(controlConnection, times(1)).refreshSchema(TABLE, keyspace, table); | |
| 249 | + | |
| 250 | + KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(keyspace); | |
| 251 | + assertThat(ksm).isNotNull(); | |
| 252 | + TableMetadata tm = ksm.getTable(table); | |
| 253 | + assertThat(tm) | |
| 254 | + .hasName(table) | |
| 255 | + .isInKeyspace(keyspace) | |
| 256 | + .hasColumn(columnName) | |
| 257 | + .hasComment(comment); | |
| 258 | + } | |
| 259 | + | |
| 260 | + /** | |
| 261 | + * Ensures that when a CREATED (keyspace) and CREATED (keyspace) schema_change events are received | |
| 262 | + * on a control connection for different keyspaces within | |
| 263 | + * {@link QueryOptions#getRefreshSchemaIntervalMillis()} that the schema refresh is debounced | |
| 264 | + * and coalesced into a single full schema refresh. | |
| 265 | + * | |
| 266 | + * @throws Exception | |
| 267 | + * @jira_ticket JAVA-657 | |
| 268 | + * @since 2.0.11 | |
| 269 | + */ | |
| 270 | + @Test(groups = "short") | |
| 271 | + public void should_debounce_and_coalesce_multiple_keyspace_creates_into_refresh_entire_schema() throws Exception { | |
| 272 | + String prefix = "sdacmkc"; | |
| 273 | + for(int i = 0; i < 3; i++) { | |
| 274 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1)); | |
| 275 | + keyspaces.add(prefix + i); | |
| 276 | + } | |
| 277 | + | |
| 278 | + verify(listener, timeout(DEBOUNCE_TIME * 3).times(3)).onKeyspaceAdded(any(KeyspaceMetadata.class)); | |
| 279 | + // Verify a complete schema refresh was executed, but only once. | |
| 280 | + verify(controlConnection, times(1)).refreshSchema(null, null, null); | |
| 281 | + | |
| 282 | + for(int i = 0; i < 3; i++) { | |
| 283 | + KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i); | |
| 284 | + assertThat(ksm).isNotNull().hasName(prefix + i); | |
| 285 | + } | |
| 286 | + } | |
| 287 | + | |
| 288 | + /** | |
| 289 | + * Ensures that when enough schema changes have been received on a control connection to | |
| 290 | + * reach {@link QueryOptions#getMaxPendingRefreshSchemaRequests()} that a schema refresh | |
| 291 | + * is submitted right away. | |
| 292 | + * | |
| 293 | + * @throws Exception | |
| 294 | + * @jira_ticket JAVA-657 | |
| 295 | + * @since 2.0.11 | |
| 296 | + */ | |
| 297 | + @Test(groups = "short") | |
| 298 | + public void should_refresh_when_max_pending_requests_reached() throws Exception { | |
| 299 | + String prefix = "srwmprr"; | |
| 300 | + for(int i = 0; i < 5; i++) { | |
| 301 | + session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, prefix + i, 1)); | |
| 302 | + keyspaces.add(prefix + i); | |
| 303 | + } | |
| 304 | + | |
| 305 | + // Event should be processed immediately as we hit our threshold. | |
| 306 | + verify(listener, times(5)).onKeyspaceAdded(any(KeyspaceMetadata.class)); | |
| 307 | + // Verify a complete schema refresh was executed, but only once. | |
| 308 | + verify(controlConnection, times(1)).refreshSchema(null, null, null); | |
| 309 | + | |
| 310 | + for(int i = 0; i < 5; i++) { | |
| 311 | + KeyspaceMetadata ksm = cluster2.getMetadata().getKeyspace(prefix + i); | |
| 312 | + assertThat(ksm).isNotNull().hasName(prefix + i); | |
| 313 | + } | |
| 314 | + } | |
| 315 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaTest.java +9 −0
| @@ -31,6 +31,15 @@ | ||
| 31 | 31 | |
| 32 | 32 | private static String withOptions; |
| 33 | 33 | |
| 34 | + @Override | |
| 35 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 36 | + return builder.withQueryOptions(new QueryOptions() | |
| 37 | + .setRefreshNodeIntervalMillis(0) | |
| 38 | + .setRefreshNodeListIntervalMillis(0) | |
| 39 | + .setRefreshSchemaIntervalMillis(0) | |
| 40 | + ); | |
| 41 | + } | |
| 42 | + | |
| 34 | 43 | @Override |
| 35 | 44 | protected Collection<String> getTableDefinitions() { |
| 36 | 45 |
modified driver-core/src/test/java/com/datastax/driver/core/SessionLeakTest.java +6 −3
| @@ -31,6 +31,7 @@ | ||
| 31 | 31 | import com.datastax.driver.core.utils.SocketChannelMonitor; |
| 32 | 32 | |
| 33 | 33 | import static com.datastax.driver.core.Assertions.assertThat; |
| 34 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 34 | 35 | |
| 35 | 36 | public class SessionLeakTest { |
| 36 | 37 | |
| @@ -49,9 +50,11 @@ | ||
| 49 | 50 | channelMonitor.reportAtFixedInterval(1, TimeUnit.SECONDS); |
| 50 | 51 | try { |
| 51 | 52 | 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(); | |
| 55 | 58 | |
| 56 | 59 | cluster.init(); |
| 57 | 60 |
modified driver-core/src/test/java/com/datastax/driver/core/SimpleStatementTest.java +23 −1
| @@ -20,10 +20,32 @@ | ||
| 20 | 20 | |
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| 23 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 24 | + | |
| 23 | 25 | public class SimpleStatementTest { |
| 26 | + | |
| 24 | 27 | @Test(groups = "unit", expectedExceptions = { IllegalArgumentException.class }) |
| 25 | 28 | public void should_fail_if_too_many_variables() { |
| 26 | 29 | List<Object> args = Collections.nCopies(1 << 16, (Object)1); |
| 27 | 30 | new SimpleStatement("mock query", args.toArray()); |
| 28 | 31 | } |
| 29 | -} | |
| No newline at the end of the file | ||
| 32 | + | |
| 33 | + @Test(groups = "unit", expectedExceptions = { IllegalStateException.class }) | |
| 34 | + public void should_throw_ISE_if_getObject_called_on_statement_without_values() { | |
| 35 | + new SimpleStatement("doesn't matter").getObject(0); | |
| 36 | + } | |
| 37 | + | |
| 38 | + | |
| 39 | + @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class }) | |
| 40 | + public void should_throw_IOOBE_if_getObject_called_with_wrong_index() { | |
| 41 | + new SimpleStatement("doesn't matter", new Object()).getObject(1); | |
| 42 | + } | |
| 43 | + | |
| 44 | + @Test(groups = "unit") | |
| 45 | + public void should_return_object_at_ith_index() { | |
| 46 | + Object expected = new Object(); | |
| 47 | + Object actual = new SimpleStatement("doesn't matter", expected).getObject(0); | |
| 48 | + assertThat(actual).isSameAs(expected); | |
| 49 | + } | |
| 50 | + | |
| 51 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SingleTokenIntegrationTest.java +8 −1
| @@ -39,7 +39,14 @@ | ||
| 39 | 39 | .withCassandraConfiguration("initial_token", "1") |
| 40 | 40 | .build(); |
| 41 | 41 | |
| 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(); | |
| 43 | 50 | |
| 44 | 51 | Session session = cluster.connect(); |
| 45 | 52 | 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 @@ | ||
| 31 | 31 | */ |
| 32 | 32 | public class SortingLoadBalancingPolicy implements LoadBalancingPolicy { |
| 33 | 33 | |
| 34 | - private final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() { | |
| 34 | + final SortedSet<Host> hosts = new ConcurrentSkipListSet<Host>(new Comparator<Host>() { | |
| 35 | 35 | @Override |
| 36 | 36 | public int compare(Host host1, Host host2) { |
| 37 | 37 | byte[] address1 = host1.getAddress().getAddress(); |
added driver-core/src/test/java/com/datastax/driver/core/TableMetadataAssert.java +63 −0
| @@ -0,0 +1,63 @@ | ||
| 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 TableMetadataAssert extends AbstractAssert<TableMetadataAssert, TableMetadata> { | |
| 23 | + protected TableMetadataAssert(TableMetadata actual) { | |
| 24 | + super(actual, TableMetadataAssert.class); | |
| 25 | + } | |
| 26 | + | |
| 27 | + public TableMetadataAssert hasName(String name) { | |
| 28 | + assertThat(actual.getName()).isEqualTo(name); | |
| 29 | + return this; | |
| 30 | + } | |
| 31 | + | |
| 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 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/TableMetadataTest.java +10 −1
| @@ -32,9 +32,18 @@ | ||
| 32 | 32 | ); |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | + @Override | |
| 36 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 37 | + return builder.withQueryOptions(new QueryOptions() | |
| 38 | + .setRefreshNodeIntervalMillis(0) | |
| 39 | + .setRefreshNodeListIntervalMillis(0) | |
| 40 | + .setRefreshSchemaIntervalMillis(0) | |
| 41 | + ); | |
| 42 | + } | |
| 43 | + | |
| 35 | 44 | @Test(groups = "short") |
| 36 | 45 | public void should_escape_single_quote_table_comment() { |
| 37 | 46 | TableMetadata table = cluster.getMetadata().getKeyspace(keyspace).getTable("single_quote"); |
| 38 | 47 | assertThat(table.asCQLQuery()).contains("comment with single quote '' should work"); |
| 39 | 48 | } |
| 40 | -} | |
| No newline at the end of the file | ||
| 49 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +22 −9
| @@ -24,8 +24,7 @@ | ||
| 24 | 24 | import java.nio.ByteBuffer; |
| 25 | 25 | import java.util.*; |
| 26 | 26 | |
| 27 | -import static org.testng.Assert.fail; | |
| 28 | - | |
| 27 | +import com.google.common.util.concurrent.Futures; | |
| 29 | 28 | import org.scassandra.Scassandra; |
| 30 | 29 | import org.scassandra.ScassandraFactory; |
| 31 | 30 | import org.slf4j.Logger; |
| @@ -325,8 +324,9 @@ | ||
| 325 | 324 | // tried doing an actual query, the driver won't realize that last node is dead until |
| 326 | 325 | // keep alive kicks in, but that's a fairly long time. So we cheat and trigger a force |
| 327 | 326 | // the detection by forcing a request. |
| 328 | - if (waitForDead || waitForOut) | |
| 329 | - cluster.manager.submitSchemaRefresh(null, null, null); | |
| 327 | + if (waitForDead || waitForOut) { | |
| 328 | + Futures.getUnchecked(cluster.manager.submitSchemaRefresh(null, null, null)); | |
| 329 | + } | |
| 330 | 330 | |
| 331 | 331 | InetAddress address; |
| 332 | 332 | try { |
| @@ -382,15 +382,19 @@ | ||
| 382 | 382 | } |
| 383 | 383 | } |
| 384 | 384 | |
| 385 | - /** Utility method to find the {@code Host} object corresponding to a node in a cluster. */ | |
| 386 | 385 | public static Host findHost(Cluster cluster, int hostNumber) { |
| 387 | - String address = CCMBridge.ipOfNode(hostNumber); | |
| 388 | - for (Host host : cluster.getMetadata().getAllHosts()) { | |
| 386 | + return findHost(cluster, CCMBridge.ipOfNode(hostNumber)); | |
| 387 | + } | |
| 388 | + | |
| 389 | + public static Host findHost(Cluster cluster, String address) { | |
| 390 | + // Note: we can't rely on ProtocolOptions.getPort() to build an InetSocketAddress and call metadata.getHost, | |
| 391 | + // because the port doesn't have the correct value if addContactPointsWithPorts was used to create the Cluster | |
| 392 | + // (JAVA-860 will solve that) | |
| 393 | + for (Host host : cluster.getMetadata().allHosts()) { | |
| 389 | 394 | if (host.getAddress().getHostAddress().equals(address)) |
| 390 | 395 | return host; |
| 391 | 396 | } |
| 392 | - fail(address + " not found in cluster metadata"); | |
| 393 | - return null; // never reached | |
| 397 | + return null; | |
| 394 | 398 | } |
| 395 | 399 | |
| 396 | 400 | public static int numberOfLocalCoreConnections(Cluster cluster) { |
| @@ -455,4 +459,13 @@ | ||
| 455 | 459 | .withLoadBalancingPolicy(new WhiteListPolicy(new RoundRobinPolicy(), singleAddress)) |
| 456 | 460 | .build(); |
| 457 | 461 | } |
| 462 | + | |
| 463 | + /** | |
| 464 | + * @return a {@QueryOptions} that disables debouncing by setting intervals to 0ms. | |
| 465 | + */ | |
| 466 | + public static QueryOptions nonDebouncingQueryOptions() { | |
| 467 | + return new QueryOptions().setRefreshNodeIntervalMillis(0) | |
| 468 | + .setRefreshNodeListIntervalMillis(0) | |
| 469 | + .setRefreshSchemaIntervalMillis(0); | |
| 470 | + } | |
| 458 | 471 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TimeoutStressTest.java +13 −6
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.NoHostAvailableException; |
| 19 | +import com.datastax.driver.core.policies.ConstantReconnectionPolicy; | |
| 19 | 20 | import com.datastax.driver.core.utils.SocketChannelMonitor; |
| 20 | 21 | import com.google.common.collect.Lists; |
| 21 | 22 | import com.google.common.util.concurrent.FutureCallback; |
| @@ -36,7 +37,7 @@ | ||
| 36 | 37 | import java.util.concurrent.atomic.AtomicBoolean; |
| 37 | 38 | import java.util.concurrent.atomic.AtomicInteger; |
| 38 | 39 | |
| 39 | -import static org.assertj.core.api.Assertions.assertThat; | |
| 40 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 40 | 41 | |
| 41 | 42 | public class TimeoutStressTest { |
| 42 | 43 | |
| @@ -73,9 +74,9 @@ | ||
| 73 | 74 | ccmBridge = CCMBridge.builder("test").withNodes(3).build(); |
| 74 | 75 | channelMonitor = new SocketChannelMonitor(); |
| 75 | 76 | 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) | |
| 79 | 80 | ); |
| 80 | 81 | |
| 81 | 82 | PoolingOptions poolingOptions = new PoolingOptions().setConnectionsPerHost(HostDistance.LOCAL, 8, 8); |
| @@ -84,6 +85,7 @@ | ||
| 84 | 85 | .addContactPointsWithPorts(nodes) |
| 85 | 86 | .withPoolingOptions(poolingOptions) |
| 86 | 87 | .withNettyOptions(channelMonitor.nettyOptions()) |
| 88 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)) | |
| 87 | 89 | .build(); |
| 88 | 90 | } |
| 89 | 91 | |
| @@ -177,13 +179,18 @@ | ||
| 177 | 179 | .setReadTimeoutMillis(SocketOptions.DEFAULT_READ_TIMEOUT_MILLIS); |
| 178 | 180 | |
| 179 | 181 | 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."); | |
| 181 | 183 | Uninterruptibles.sleepUninterruptibly(20, TimeUnit.SECONDS); |
| 182 | 184 | |
| 183 | 185 | Collection<SocketChannel> openChannels = channelMonitor.openChannels(nodes); |
| 184 | 186 | assertThat(openChannels.size()) |
| 185 | 187 | .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); | |
| 187 | 194 | |
| 188 | 195 | session.close(); |
| 189 | 196 |
modified driver-core/src/test/java/com/datastax/driver/core/TokenIntegrationTest.java +5 −0
| @@ -81,6 +81,11 @@ | ||
| 81 | 81 | cluster = Cluster.builder() |
| 82 | 82 | .addContactPoints(CCMBridge.ipOfNode(1)) |
| 83 | 83 | .withLoadBalancingPolicy(lbp) |
| 84 | + .withQueryOptions(new QueryOptions() | |
| 85 | + .setRefreshNodeIntervalMillis(0) | |
| 86 | + .setRefreshNodeListIntervalMillis(0) | |
| 87 | + .setRefreshSchemaIntervalMillis(0) | |
| 88 | + ) | |
| 84 | 89 | .build(); |
| 85 | 90 | cluster.init(); |
| 86 | 91 | 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(TestUtils.CREATE_TABLE_SIMPLE_FORMAT, 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 @@ | ||
| 191 | 191 | } |
| 192 | 192 | |
| 193 | 193 | @Override public void init(Cluster cluster, Collection<Host> hosts) { |
| 194 | - System.out.println("init " + hosts); | |
| 195 | 194 | initHosts.addAll(hosts); |
| 196 | 195 | super.init(cluster, hosts); |
| 197 | 196 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/LatencyAwarePolicyTest.java +70 −58
| @@ -70,23 +70,27 @@ | ||
| 70 | 70 | Cluster.Builder builder = super.createClusterBuilder(); |
| 71 | 71 | builder.withLoadBalancingPolicy(latencyAwarePolicy); |
| 72 | 72 | Cluster cluster = builder.build(); |
| 73 | - cluster.init(); // force initialization of latency aware policy | |
| 74 | - LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1); | |
| 75 | - cluster.register(barrier); // add barrier to synchronize latency tracker threads with the current thread | |
| 76 | - Session session = cluster.connect(); | |
| 77 | - // when | |
| 78 | - session.execute(query); | |
| 79 | - // then | |
| 80 | - // wait until trackers have been notified | |
| 81 | - barrier.await(); | |
| 82 | - // make sure the updater is called at least once | |
| 83 | - latencyAwarePolicy.new Updater().run(); | |
| 84 | - LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot(); | |
| 85 | - assertThat(snapshot.getAllStats()).hasSize(1); | |
| 86 | - LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster)); | |
| 87 | - assertThat(stats).isNotNull(); | |
| 88 | - assertThat(stats.getMeasurementsCount()).isEqualTo(1); | |
| 89 | - assertThat(stats.getLatencyScore()).isNotEqualTo(-1); | |
| 73 | + try { | |
| 74 | + cluster.init(); // force initialization of latency aware policy | |
| 75 | + LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1); | |
| 76 | + cluster.register(barrier); // add barrier to synchronize latency tracker threads with the current thread | |
| 77 | + Session session = cluster.connect(); | |
| 78 | + // when | |
| 79 | + session.execute(query); | |
| 80 | + // then | |
| 81 | + // wait until trackers have been notified | |
| 82 | + barrier.await(); | |
| 83 | + // make sure the updater is called at least once | |
| 84 | + latencyAwarePolicy.new Updater().run(); | |
| 85 | + LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot(); | |
| 86 | + assertThat(snapshot.getAllStats()).hasSize(1); | |
| 87 | + LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster)); | |
| 88 | + assertThat(stats).isNotNull(); | |
| 89 | + assertThat(stats.getMeasurementsCount()).isEqualTo(1); | |
| 90 | + assertThat(stats.getLatencyScore()).isNotEqualTo(-1); | |
| 91 | + } finally { | |
| 92 | + cluster.close(); | |
| 93 | + } | |
| 90 | 94 | } |
| 91 | 95 | |
| 92 | 96 | @Test(groups = "short") |
| @@ -105,29 +109,33 @@ | ||
| 105 | 109 | Cluster.Builder builder = super.createClusterBuilder(); |
| 106 | 110 | builder.withLoadBalancingPolicy(latencyAwarePolicy); |
| 107 | 111 | Cluster cluster = builder.build(); |
| 108 | - cluster.init(); // force initialization of latency aware policy | |
| 109 | - LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1); | |
| 110 | - cluster.register(barrier); | |
| 111 | - Session session = cluster.connect(); | |
| 112 | - // when | |
| 113 | 112 | try { |
| 114 | - session.execute(query); | |
| 115 | - fail("Should have thrown NoHostAvailableException"); | |
| 116 | - } catch(NoHostAvailableException e) { | |
| 117 | - // ok | |
| 118 | - Throwable error = e.getErrors().get(hostAddress); | |
| 119 | - assertThat(error).isNotNull(); | |
| 120 | - assertThat(error).isInstanceOf(UnavailableException.class); | |
| 113 | + cluster.init(); // force initialization of latency aware policy | |
| 114 | + LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1); | |
| 115 | + cluster.register(barrier); | |
| 116 | + Session session = cluster.connect(); | |
| 117 | + // when | |
| 118 | + try { | |
| 119 | + session.execute(query); | |
| 120 | + fail("Should have thrown NoHostAvailableException"); | |
| 121 | + } catch (NoHostAvailableException e) { | |
| 122 | + // ok | |
| 123 | + Throwable error = e.getErrors().get(hostAddress); | |
| 124 | + assertThat(error).isNotNull(); | |
| 125 | + assertThat(error).isInstanceOf(UnavailableException.class); | |
| 126 | + } | |
| 127 | + // then | |
| 128 | + // wait until trackers have been notified | |
| 129 | + barrier.await(); | |
| 130 | + // make sure the updater is called at least once | |
| 131 | + latencyAwarePolicy.new Updater().run(); | |
| 132 | + LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot(); | |
| 133 | + assertThat(snapshot.getAllStats()).isEmpty(); | |
| 134 | + LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster)); | |
| 135 | + assertThat(stats).isNull(); | |
| 136 | + } finally { | |
| 137 | + cluster.close(); | |
| 121 | 138 | } |
| 122 | - // then | |
| 123 | - // wait until trackers have been notified | |
| 124 | - barrier.await(); | |
| 125 | - // make sure the updater is called at least once | |
| 126 | - latencyAwarePolicy.new Updater().run(); | |
| 127 | - LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot(); | |
| 128 | - assertThat(snapshot.getAllStats()).isEmpty(); | |
| 129 | - LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster)); | |
| 130 | - assertThat(stats).isNull(); | |
| 131 | 139 | } |
| 132 | 140 | |
| 133 | 141 | @Test(groups= "short") |
| @@ -147,28 +155,32 @@ | ||
| 147 | 155 | builder.withLoadBalancingPolicy(latencyAwarePolicy); |
| 148 | 156 | builder.withRetryPolicy(FallthroughRetryPolicy.INSTANCE); |
| 149 | 157 | Cluster cluster = builder.build(); |
| 150 | - cluster.init(); // force initialization of latency aware policy | |
| 151 | - LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1); | |
| 152 | - cluster.register(barrier); | |
| 153 | - Session session = cluster.connect(); | |
| 154 | - // when | |
| 155 | 158 | try { |
| 156 | - session.execute(query); | |
| 157 | - fail("Should have thrown ReadTimeoutException"); | |
| 158 | - } catch(ReadTimeoutException e) { | |
| 159 | - // ok | |
| 159 | + cluster.init(); // force initialization of latency aware policy | |
| 160 | + LatencyTrackerBarrier barrier = new LatencyTrackerBarrier(1); | |
| 161 | + cluster.register(barrier); | |
| 162 | + Session session = cluster.connect(); | |
| 163 | + // when | |
| 164 | + try { | |
| 165 | + session.execute(query); | |
| 166 | + fail("Should have thrown ReadTimeoutException"); | |
| 167 | + } catch (ReadTimeoutException e) { | |
| 168 | + // ok | |
| 169 | + } | |
| 170 | + // then | |
| 171 | + // wait until trackers have been notified | |
| 172 | + barrier.await(); | |
| 173 | + // make sure the updater is called at least once | |
| 174 | + latencyAwarePolicy.new Updater().run(); | |
| 175 | + LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot(); | |
| 176 | + assertThat(snapshot.getAllStats()).hasSize(1); | |
| 177 | + LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster)); | |
| 178 | + assertThat(stats).isNotNull(); | |
| 179 | + assertThat(stats.getMeasurementsCount()).isEqualTo(1); | |
| 180 | + assertThat(stats.getLatencyScore()).isNotEqualTo(-1); | |
| 181 | + } finally { | |
| 182 | + cluster.close(); | |
| 160 | 183 | } |
| 161 | - // then | |
| 162 | - // wait until trackers have been notified | |
| 163 | - barrier.await(); | |
| 164 | - // make sure the updater is called at least once | |
| 165 | - latencyAwarePolicy.new Updater().run(); | |
| 166 | - LatencyAwarePolicy.Snapshot snapshot = latencyAwarePolicy.getScoresSnapshot(); | |
| 167 | - assertThat(snapshot.getAllStats()).hasSize(1); | |
| 168 | - LatencyAwarePolicy.Snapshot.Stats stats = snapshot.getStats(retrieveSingleHost(cluster)); | |
| 169 | - assertThat(stats).isNotNull(); | |
| 170 | - assertThat(stats.getMeasurementsCount()).isEqualTo(1); | |
| 171 | - assertThat(stats.getLatencyScore()).isNotEqualTo(-1); | |
| 172 | 184 | } |
| 173 | 185 | |
| 174 | 186 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +3 −0
| @@ -25,6 +25,8 @@ | ||
| 25 | 25 | import com.datastax.driver.core.*; |
| 26 | 26 | import com.datastax.driver.core.utils.Bytes; |
| 27 | 27 | |
| 28 | +import static com.datastax.driver.core.TestUtils.nonDebouncingQueryOptions; | |
| 29 | + | |
| 28 | 30 | public class TokenAwarePolicyTest { |
| 29 | 31 | @Test(groups = "long") |
| 30 | 32 | public void should_shuffle_replicas_when_requested() { |
| @@ -46,6 +48,7 @@ | ||
| 46 | 48 | cluster = Cluster.builder() |
| 47 | 49 | .addContactPoint(CCMBridge.ipOfNode(1)) |
| 48 | 50 | .withLoadBalancingPolicy(loadBalancingPolicy) |
| 51 | + .withQueryOptions(nonDebouncingQueryOptions()) | |
| 49 | 52 | .build(); |
| 50 | 53 | |
| 51 | 54 | String keyspace = "ks"; |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +44 −5
| @@ -40,6 +40,15 @@ | ||
| 40 | 40 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 41 | 41 | } |
| 42 | 42 | |
| 43 | + @Override | |
| 44 | + protected Cluster.Builder configure(Cluster.Builder builder) { | |
| 45 | + return builder.withQueryOptions(new QueryOptions() | |
| 46 | + .setRefreshNodeIntervalMillis(0) | |
| 47 | + .setRefreshNodeListIntervalMillis(0) | |
| 48 | + .setRefreshSchemaIntervalMillis(0) | |
| 49 | + ); | |
| 50 | + } | |
| 51 | + | |
| 43 | 52 | @Test(groups = "short") |
| 44 | 53 | public void remainingDeleteTests() throws Exception { |
| 45 | 54 | |
| @@ -72,8 +81,6 @@ | ||
| 72 | 81 | |
| 73 | 82 | query = "SELECT * FROM foo WHERE k=?;"; |
| 74 | 83 | select = select().all().from("foo").where(eq("k", QueryBuilder.bindMarker())); |
| 75 | - System.out.println(select.toString()); | |
| 76 | - System.out.println(session); | |
| 77 | 84 | ps = session.prepare(select.toString()); |
| 78 | 85 | bs = ps.bind(); |
| 79 | 86 | assertEquals(select.toString(), query); |
| @@ -211,13 +218,13 @@ | ||
| 211 | 218 | @CassandraVersion(major=2.0, minor=7, description="DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)") |
| 212 | 219 | public void conditionalDeletesTest() throws Exception { |
| 213 | 220 | session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace)); |
| 214 | - | |
| 221 | + | |
| 215 | 222 | Statement delete; |
| 216 | 223 | Row row; |
| 217 | 224 | delete = delete().from(keyspace, TABLE_INT).where(eq("k", 2)).ifExists(); |
| 218 | 225 | row = session.execute(delete).one(); |
| 219 | 226 | assertFalse(row.getBool("[applied]")); |
| 220 | - | |
| 227 | + | |
| 221 | 228 | delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).ifExists(); |
| 222 | 229 | row = session.execute(delete).one(); |
| 223 | 230 | assertTrue(row.getBool("[applied]")); |
| @@ -227,9 +234,41 @@ | ||
| 227 | 234 | delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 2)); |
| 228 | 235 | row = session.execute(delete).one(); |
| 229 | 236 | assertFalse(row.getBool("[applied]")); |
| 230 | - | |
| 237 | + | |
| 231 | 238 | delete = delete().from(keyspace, TABLE_INT).where(eq("k", 1)).onlyIf(eq("a", 1)).and(eq("b", 1)); |
| 232 | 239 | row = session.execute(delete).one(); |
| 233 | 240 | assertTrue(row.getBool("[applied]")); |
| 234 | 241 | } |
| 242 | + | |
| 243 | + @Test(groups = "short") | |
| 244 | + @CassandraVersion(major=2.0, minor=13, description="Allow IF EXISTS for UPDATE statements (CASSANDRA-8610)") | |
| 245 | + public void conditionalUpdatesTest() throws Exception { | |
| 246 | + session.execute(String.format("INSERT INTO %s.test_int (k, a, b) VALUES (1, 1, 1)",keyspace)); | |
| 247 | + | |
| 248 | + Statement update; | |
| 249 | + Row row; | |
| 250 | + update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).ifExists(); | |
| 251 | + row = session.execute(update).one(); | |
| 252 | + assertFalse(row.getBool("[applied]")); | |
| 253 | + | |
| 254 | + update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 1)).ifExists(); | |
| 255 | + row = session.execute(update).one(); | |
| 256 | + assertTrue(row.getBool("[applied]")); | |
| 257 | + | |
| 258 | + update = update(TABLE_INT).with(set("a", 2)).and(set("b", 2)).where(eq("k", 2)).onlyIf(eq("a", 1)).and(eq("b", 2)); | |
| 259 | + row = session.execute(update).one(); | |
| 260 | + assertFalse(row.getBool("[applied]")); | |
| 261 | + | |
| 262 | + update = update(TABLE_INT).with(set("a", 3)).and(set("b", 3)).where(eq("k", 1)).onlyIf(eq("a", 2)).and(eq("b", 2)); | |
| 263 | + row = session.execute(update).one(); | |
| 264 | + assertTrue(row.getBool("[applied]")); | |
| 265 | + | |
| 266 | + update = update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 2)).and(eq("b", 2)).where(eq("k", 1)); | |
| 267 | + row = session.execute(update).one(); | |
| 268 | + assertFalse(row.getBool("[applied]")); | |
| 269 | + | |
| 270 | + update = update(TABLE_INT).with(set("a", 4)).and(set("b", 4)).onlyIf(eq("a", 3)).and(eq("b", 3)).where(eq("k", 1)); | |
| 271 | + row = session.execute(update).one(); | |
| 272 | + assertTrue(row.getBool("[applied]")); | |
| 273 | + } | |
| 235 | 274 | } |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +9 −0
| @@ -39,6 +39,15 @@ | ||
| 39 | 39 | String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); |
| 40 | 40 | } |
| 41 | 41 | |
| 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 | + | |
| 42 | 51 | @Test(groups = "short") |
| 43 | 52 | public void textRoutingKeyTest() throws Exception { |
| 44 | 53 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +23 −1
| @@ -338,8 +338,12 @@ | ||
| 338 | 338 | query = "UPDATE foo SET x=4 WHERE k=0 IF x=1;"; |
| 339 | 339 | update = update("foo").with(set("x", 4)).where(eq("k", 0)).onlyIf(eq("x", 1)); |
| 340 | 340 | assertEquals(update.toString(), query); |
| 341 | - } | |
| 342 | 341 | |
| 342 | + // IF EXISTS CAS test | |
| 343 | + update = update("foo").with(set("x", 3)).where(eq("k", 2)).ifExists(); | |
| 344 | + assertThat(update.toString()).isEqualTo("UPDATE foo SET x=3 WHERE k=2 IF EXISTS;"); | |
| 345 | + } | |
| 346 | + | |
| 343 | 347 | @Test(groups = "unit") |
| 344 | 348 | public void deleteTest() throws Exception { |
| 345 | 349 | |
| @@ -874,4 +878,22 @@ | ||
| 874 | 878 | assertThat(select.getQueryString()).doesNotContain("?"); |
| 875 | 879 | assertThat(select.getValues(ProtocolVersion.V3)).isNull(); |
| 876 | 880 | } |
| 881 | + | |
| 882 | + @Test(groups = "unit", expectedExceptions = { IllegalStateException.class }) | |
| 883 | + public void should_throw_ISE_if_getObject_called_on_statement_without_values() { | |
| 884 | + select().from("test").where(eq("foo", 42)).getObject(0); // integers are appended to the CQL string | |
| 885 | + } | |
| 886 | + | |
| 887 | + @Test(groups = "unit", expectedExceptions = { IndexOutOfBoundsException.class }) | |
| 888 | + public void should_throw_IOOBE_if_getObject_called_with_wrong_index() { | |
| 889 | + select().from("test").where(eq("foo", new Object())).getObject(1); | |
| 890 | + } | |
| 891 | + | |
| 892 | + @Test(groups = "unit") | |
| 893 | + public void should_return_object_at_ith_index() { | |
| 894 | + Object expected = new Object(); | |
| 895 | + Object actual = select().from("test").where(eq("foo", expected)).getObject(0); | |
| 896 | + assertThat(actual).isSameAs(expected); | |
| 897 | + } | |
| 898 | + | |
| 877 | 899 | } |
modified driver-core/src/test/resources/log4j.properties +4 −2
| @@ -16,9 +16,11 @@ | ||
| 16 | 16 | |
| 17 | 17 | # Set root logger level to DEBUG and its only appender to A1. |
| 18 | 18 | log4j.rootLogger=INFO, A1 |
| 19 | +log4j.logger.com.datastax.driver.core.Host.STATES=DEBUG | |
| 19 | 20 | |
| 20 | -# Scassandra's info log is a bit verbose | |
| 21 | -log4j.logger.org.scassandra=WARN | |
| 21 | +# Adjust Scassandra's log level | |
| 22 | +# (it seems some messages are conditioned by log4j.properties and others by reference.conf, so we need both) | |
| 23 | +log4j.logger.org.scassandra=ERROR | |
| 22 | 24 | |
| 23 | 25 | # A1 is set to be a ConsoleAppender. |
| 24 | 26 | 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 @@ | ||
| 27 | 27 | via a push notification. It refreshes the schema directly (there is no |
| 28 | 28 | need to wait for schema agreement since Cassandra has already done it). |
| 29 | 29 | |
| 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 | + | |
| 30 | 53 | #### Schema agreement |
| 31 | 54 | |
| 32 | 55 | 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 @@ | ||
| 43 | 43 | |
| 44 | 44 | <properties> |
| 45 | 45 | <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> |
| 46 | - <cassandra.version>2.1.3</cassandra.version> | |
| 46 | + <cassandra.version>2.1.9</cassandra.version> | |
| 47 | 47 | <java.version>1.6</java.version> |
| 48 | 48 | <log4j.version>1.2.17</log4j.version> |
| 49 | 49 | <slf4j-log4j12.version>1.7.6</slf4j-log4j12.version> |
| @@ -61,11 +61,7 @@ | ||
| 61 | 61 | <testng.version>6.8.8</testng.version> |
| 62 | 62 | <assertj.version>1.7.0</assertj.version> |
| 63 | 63 | <mockito.version>1.10.8</mockito.version> |
| 64 | - <!-- | |
| 65 | - There are more recent versions of Scassandra but they require JDK 7, | |
| 66 | - our build is still using JDK 6. | |
| 67 | - --> | |
| 68 | - <scassandra.version>0.4.1</scassandra.version> | |
| 64 | + <scassandra.version>0.9.1</scassandra.version> | |
| 69 | 65 | <main.basedir>${project.basedir}</main.basedir> |
| 70 | 66 | </properties> |
| 71 | 67 |
modified upgrade_guide/README.md +12 −0
| @@ -160,6 +160,9 @@ | ||
| 160 | 160 | |
| 161 | 161 | ### 2.0.11 |
| 162 | 162 | |
| 163 | +2.0.11 preserves binary compatibility with previous versions. There are a few | |
| 164 | +changes in the driver's behavior: | |
| 165 | + | |
| 163 | 166 | 1. The `DefaultRetryPolicy`'s behaviour has changed in the case of an Unavailable |
| 164 | 167 | exception received from a request. The new behaviour will cause the driver to |
| 165 | 168 | process a Retry on a different node at most once, otherwise an exception will |
| @@ -168,11 +171,20 @@ | ||
| 168 | 171 | because of a network partition) but can still answer to the client normally. |
| 169 | 172 | In this case, trying another node has a chance of success. |
| 170 | 173 | The previous behaviour was to always throw an exception. |
| 174 | + | |
| 171 | 175 | 2. A `BuiltStatement` is now considered non-idempotent whenever a `fcall()` |
| 172 | 176 | or `raw()` is used to build a value to be inserted in the database. |
| 173 | 177 | If you know that the CQL functions or expressions are safe, use |
| 174 | 178 | `setIdempotent(true)` on the statement. |
| 175 | 179 | |
| 180 | +3. The list of contact points provided at startup is now shuffled before trying | |
| 181 | + to open the control connection, so that multiple clients with the same contact | |
| 182 | + points don't all pick the same control host. As a result, you can't assume that | |
| 183 | + the driver will try contact points in a deterministic order. In particular, if | |
| 184 | + you use the `DCAwareRoundRobinPolicy` without specifying a primary datacenter | |
| 185 | + name, make sure that you only provide local hosts as contact points. | |
| 186 | + | |
| 187 | + | |
| 176 | 188 | ### <a name="2-0-x-to-2-0-10"></a>2.0.x to 2.0.10 |
| 177 | 189 | |
| 178 | 190 | We try to avoid breaking changes within a branch (2.0.x to 2.0.y), but |