kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | abdd6dc3f2811d5cd7395c439650c0b931d0eb305b995ee9dfa4a0887e8442b8 |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2016-09-30 10:08 -07:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2016-09-30 10:10 -07:00 |
| Parents | 1918c7803ffc, 9504c653c731 |
67 files changed
modified changelog/README.md +21 −0
| @@ -1,5 +1,26 @@ | ||
| 1 | 1 | ## Changelog |
| 2 | 2 | |
| 3 | +### 3.1.1 | |
| 4 | + | |
| 5 | +Merged from 3.0.x: | |
| 6 | + | |
| 7 | +- [improvement] JAVA-1246: Driver swallows the real exception in a few cases | |
| 8 | +- [improvement] JAVA-1261: Throw error when attempting to page in I/O thread. | |
| 9 | +- [bug] JAVA-1258: Regression: Mapper cannot map a materialized view after JAVA-1126. | |
| 10 | +- [bug] JAVA-1101: Batch and BatchStatement should consider inner statements to determine query idempotence | |
| 11 | +- [improvement] JAVA-1262: Use ParseUtils for quoting & unquoting. | |
| 12 | +- [improvement] JAVA-1275: Use Netty's default thread factory | |
| 13 | +- [bug] JAVA-1285: QueryBuilder routing key auto-discovery should handle case-sensitive column names. | |
| 14 | +- [bug] JAVA-1283: Don't cache failed query preparations in the mapper. | |
| 15 | +- [improvement] JAVA-1277: Expose AbstractSession.checkNotInEventLoop. | |
| 16 | +- [bug] JAVA-1272: BuiltStatement not able to print its query string if it contains mapped UDTs. | |
| 17 | +- [bug] JAVA-1292: 'Adjusted frame length' error breaks driver's ability to read data. | |
| 18 | +- [improvement] JAVA-1293: Make DecoderForStreamIdSize.MAX_FRAME_LENGTH configurable. | |
| 19 | +- [improvement] JAVA-1053: Add a metric for authentication errors | |
| 20 | +- [improvement] JAVA-1263: Eliminate unnecessary memory copies in FrameCompressor implementations. | |
| 21 | +- [improvement] JAVA-893: Make connection pool non-blocking | |
| 22 | + | |
| 23 | + | |
| 3 | 24 | ### 3.1.0 |
| 4 | 25 | |
| 5 | 26 | - [new feature] JAVA-1153: Add PER PARTITION LIMIT to Select QueryBuilder. |
modified clirr-ignores.xml +12 −1
| @@ -19,7 +19,6 @@ | ||
| 19 | 19 | <justification>False positive, the enclosing class is package-private so this was never exposed</justification> |
| 20 | 20 | </difference> |
| 21 | 21 | |
| 22 | - | |
| 23 | 22 | <difference> |
| 24 | 23 | <differenceType>1001</differenceType> <!-- decreased visibility --> |
| 25 | 24 | <className>com/datastax/driver/mapping/ColumnMapper$Kind</className> |
| @@ -136,4 +135,16 @@ | ||
| 136 | 135 | <justification>Introduced more generic parent type PercentileTracker (API was marked as beta and still subject to change)</justification> |
| 137 | 136 | </difference> |
| 138 | 137 | |
| 138 | + <difference> | |
| 139 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 140 | + <className>com/datastax/driver/core/FrameCompressor$SnappyCompressor</className> | |
| 141 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 142 | + </difference> | |
| 143 | + | |
| 144 | + <difference> | |
| 145 | + <differenceType>8001</differenceType> <!-- class removed --> | |
| 146 | + <className>com/datastax/driver/core/FrameCompressor$LZ4Compressor</className> | |
| 147 | + <justification>False positive, the enclosing class is package-private so this was never exposed</justification> | |
| 148 | + </difference> | |
| 149 | + | |
| 139 | 150 | </differences> |
modified driver-core/pom.xml +2 −0
| @@ -342,6 +342,8 @@ | ||
| 342 | 342 | <include>**/ControlConnectionTest.java</include> |
| 343 | 343 | <include>**/ExtendedPeerCheckDisabledTest.java</include> |
| 344 | 344 | <include>**/UUIDsPID*.java</include> |
| 345 | + <include>**/FrameLengthTest.java</include> | |
| 346 | + <include>**/HeapCompressionTest.java</include> | |
| 345 | 347 | </includes> |
| 346 | 348 | </configuration> |
| 347 | 349 | </plugin> |
modified driver-core/src/main/java/com/datastax/driver/core/AbstractSession.java +30 −5
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import com.google.common.util.concurrent.Futures; |
| 20 | 20 | import com.google.common.util.concurrent.ListenableFuture; |
| 21 | 21 | import com.google.common.util.concurrent.Uninterruptibles; |
| 22 | +import io.netty.util.concurrent.EventExecutor; | |
| 22 | 23 | |
| 23 | 24 | import java.nio.ByteBuffer; |
| 24 | 25 | import java.util.Map; |
| @@ -31,6 +32,9 @@ | ||
| 31 | 32 | */ |
| 32 | 33 | public abstract class AbstractSession implements Session { |
| 33 | 34 | |
| 35 | + private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean( | |
| 36 | + "com.datastax.driver.CHECK_IO_DEADLOCKS", true); | |
| 37 | + | |
| 34 | 38 | /** |
| 35 | 39 | * {@inheritDoc} |
| 36 | 40 | */ |
| @@ -131,12 +135,12 @@ | ||
| 131 | 135 | if (statement.hasValues()) |
| 132 | 136 | throw new IllegalArgumentException("A statement to prepare should not have values"); |
| 133 | 137 | |
| 134 | - ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(), statement.getOutgoingPayload()); | |
| 138 | + final CodecRegistry codecRegistry = getCluster().getConfiguration().getCodecRegistry(); | |
| 139 | + ListenableFuture<PreparedStatement> prepared = prepareAsync(statement.getQueryString(codecRegistry), statement.getOutgoingPayload()); | |
| 135 | 140 | return Futures.transform(prepared, new Function<PreparedStatement, PreparedStatement>() { |
| 136 | 141 | @Override |
| 137 | 142 | public PreparedStatement apply(PreparedStatement prepared) { |
| 138 | 143 | ProtocolVersion protocolVersion = getCluster().getConfiguration().getProtocolOptions().getProtocolVersion(); |
| 139 | - CodecRegistry codecRegistry = getCluster().getConfiguration().getCodecRegistry(); | |
| 140 | 144 | ByteBuffer routingKey = statement.getRoutingKey(protocolVersion, codecRegistry); |
| 141 | 145 | if (routingKey != null) |
| 142 | 146 | prepared.setRoutingKey(routingKey); |
| @@ -179,9 +183,30 @@ | ||
| 179 | 183 | /** |
| 180 | 184 | * Checks that the current thread is not one of the Netty I/O threads used by the driver. |
| 181 | 185 | * <p/> |
| 182 | - * This is called from the synchronous methods of this class to prevent deadlock issues. | |
| 186 | + * This method is called from all the synchronous methods of this class to prevent deadlock issues. | |
| 187 | + * <p/> | |
| 188 | + * User code extending this class can also call this method at any time to check if any code | |
| 189 | + * making blocking calls is being wrongly executed on a Netty I/O thread. | |
| 190 | + * <p/> | |
| 191 | + * Note that the check performed by this method has a small overhead; if | |
| 192 | + * that is an issue, checks can be disabled by setting the System property | |
| 193 | + * {@code com.datastax.driver.CHECK_IO_DEADLOCKS} to {@code false}. | |
| 194 | + * | |
| 195 | + * @throws IllegalStateException if the current thread is one of the Netty I/O thread used by the driver. | |
| 183 | 196 | */ |
| 184 | - protected void checkNotInEventLoop() { | |
| 185 | - // This method is concrete only to avoid a breaking change. See subclass for the actual implementation. | |
| 197 | + public void checkNotInEventLoop() { | |
| 198 | + Connection.Factory connectionFactory = getCluster().manager.connectionFactory; | |
| 199 | + if (!CHECK_IO_DEADLOCKS || connectionFactory == null) | |
| 200 | + return; | |
| 201 | + for (EventExecutor executor : connectionFactory.eventLoopGroup) { | |
| 202 | + if (executor.inEventLoop()) { | |
| 203 | + throw new IllegalStateException( | |
| 204 | + "Detected a synchronous call on an I/O thread, this can cause deadlocks or unpredictable " + | |
| 205 | + "behavior. This generally happens when a Future callback calls a synchronous Session " + | |
| 206 | + "method (execute() or prepare()), or iterates a result set past the fetch size " + | |
| 207 | + "(causing an internal synchronous fetch of the next page of results). " + | |
| 208 | + "Avoid this in your callbacks, or schedule them on a different executor."); | |
| 209 | + } | |
| 210 | + } | |
| 186 | 211 | } |
| 187 | 212 | } |
modified driver-core/src/main/java/com/datastax/driver/core/ArrayBackedResultSet.java +1 −0
| @@ -307,6 +307,7 @@ | ||
| 307 | 307 | // We need to know if there is more result, so fetch the next page and |
| 308 | 308 | // wait on it. |
| 309 | 309 | try { |
| 310 | + session.checkNotInEventLoop(); | |
| 310 | 311 | Uninterruptibles.getUninterruptibly(fetchMoreResults()); |
| 311 | 312 | } catch (ExecutionException e) { |
| 312 | 313 | throw DriverThrowables.propagateCause(e); |
modified driver-core/src/main/java/com/datastax/driver/core/BatchStatement.java +9 −1
| @@ -90,7 +90,7 @@ | ||
| 90 | 90 | if (statement instanceof RegularStatement) { |
| 91 | 91 | RegularStatement st = (RegularStatement) statement; |
| 92 | 92 | ByteBuffer[] vals = st.getValues(protocolVersion, codecRegistry); |
| 93 | - String query = st.getQueryString(); | |
| 93 | + String query = st.getQueryString(codecRegistry); | |
| 94 | 94 | idAndVals.ids.add(query); |
| 95 | 95 | idAndVals.values.add(vals == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(vals)); |
| 96 | 96 | } else { |
| @@ -243,6 +243,14 @@ | ||
| 243 | 243 | return null; |
| 244 | 244 | } |
| 245 | 245 | |
| 246 | + @Override | |
| 247 | + public Boolean isIdempotent() { | |
| 248 | + if (idempotent != null) { | |
| 249 | + return idempotent; | |
| 250 | + } | |
| 251 | + return isBatchIdempotent(statements); | |
| 252 | + } | |
| 253 | + | |
| 246 | 254 | void ensureAllSet() { |
| 247 | 255 | for (Statement statement : statements) |
| 248 | 256 | if (statement instanceof BoundStatement) |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +10 −2
| @@ -25,6 +25,7 @@ | ||
| 25 | 25 | import com.google.common.base.Throwables; |
| 26 | 26 | import com.google.common.collect.*; |
| 27 | 27 | import com.google.common.util.concurrent.*; |
| 28 | +import io.netty.util.concurrent.DefaultThreadFactory; | |
| 28 | 29 | import org.slf4j.Logger; |
| 29 | 30 | import org.slf4j.LoggerFactory; |
| 30 | 31 | |
| @@ -852,7 +853,7 @@ | ||
| 852 | 853 | addContactPoints(InetAddress.getAllByName(address)); |
| 853 | 854 | return this; |
| 854 | 855 | } catch (UnknownHostException e) { |
| 855 | - throw new IllegalArgumentException(e.getMessage()); | |
| 856 | + throw new IllegalArgumentException("Failed to add contact point: " + address, e); | |
| 856 | 857 | } |
| 857 | 858 | } |
| 858 | 859 | |
| @@ -1544,7 +1545,14 @@ | ||
| 1544 | 1545 | } |
| 1545 | 1546 | |
| 1546 | 1547 | ThreadFactory threadFactory(String name) { |
| 1547 | - return new ThreadFactoryBuilder().setNameFormat(clusterName + "-" + name + "-%d").build(); | |
| 1548 | + return new ThreadFactoryBuilder() | |
| 1549 | + .setNameFormat(clusterName + "-" + name + "-%d") | |
| 1550 | + // Back with Netty's thread factory in order to create FastThreadLocalThread instances. This allows | |
| 1551 | + // an optimization around ThreadLocals (we could use DefaultThreadFactory directly but it creates | |
| 1552 | + // slightly different thread names, so keep we keep a ThreadFactoryBuilder wrapper for backward | |
| 1553 | + // compatibility). | |
| 1554 | + .setThreadFactory(new DefaultThreadFactory("ignored name")) | |
| 1555 | + .build(); | |
| 1548 | 1556 | } |
| 1549 | 1557 | |
| 1550 | 1558 | private ListeningExecutorService makeExecutor(int threads, String name, LinkedBlockingQueue<Runnable> workQueue) { |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +130 −25
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import com.datastax.driver.core.exceptions.*; |
| 20 | 20 | import com.datastax.driver.core.utils.MoreFutures; |
| 21 | 21 | import com.google.common.annotations.VisibleForTesting; |
| 22 | +import com.google.common.base.Objects; | |
| 22 | 23 | import com.google.common.collect.Lists; |
| 23 | 24 | import com.google.common.collect.MapMaker; |
| 24 | 25 | import com.google.common.util.concurrent.*; |
| @@ -27,6 +28,7 @@ | ||
| 27 | 28 | import io.netty.channel.group.ChannelGroup; |
| 28 | 29 | import io.netty.channel.group.DefaultChannelGroup; |
| 29 | 30 | import io.netty.channel.socket.SocketChannel; |
| 31 | +import io.netty.handler.codec.DecoderException; | |
| 30 | 32 | import io.netty.handler.timeout.IdleStateEvent; |
| 31 | 33 | import io.netty.handler.timeout.IdleStateHandler; |
| 32 | 34 | import io.netty.util.Timeout; |
| @@ -84,7 +86,9 @@ | ||
| 84 | 86 | final AtomicInteger inFlight = new AtomicInteger(0); |
| 85 | 87 | |
| 86 | 88 | private final AtomicInteger writer = new AtomicInteger(0); |
| 87 | - private volatile String keyspace; | |
| 89 | + | |
| 90 | + private final AtomicReference<SetKeyspaceAttempt> targetKeyspace; | |
| 91 | + private final SetKeyspaceAttempt defaultKeyspaceAttempt; | |
| 88 | 92 | |
| 89 | 93 | private volatile boolean isInitialized; |
| 90 | 94 | private final AtomicBoolean isDefunct = new AtomicBoolean(); |
| @@ -94,8 +98,9 @@ | ||
| 94 | 98 | |
| 95 | 99 | private final AtomicReference<Owner> ownerRef = new AtomicReference<Owner>(); |
| 96 | 100 | |
| 101 | + private final ListenableFuture<Connection> thisFuture; | |
| 102 | + | |
| 97 | 103 | /** |
| 98 | - * /** | |
| 99 | 104 | * Create a new connection to a Cassandra node and associate it with the given pool. |
| 100 | 105 | * |
| 101 | 106 | * @param name the connection name |
| @@ -110,6 +115,9 @@ | ||
| 110 | 115 | this.dispatcher = new Dispatcher(); |
| 111 | 116 | this.name = name; |
| 112 | 117 | this.ownerRef.set(owner); |
| 118 | + this.thisFuture = Futures.immediateFuture(this); | |
| 119 | + this.defaultKeyspaceAttempt = new SetKeyspaceAttempt(null, thisFuture); | |
| 120 | + this.targetKeyspace = new AtomicReference<SetKeyspaceAttempt>(defaultKeyspaceAttempt); | |
| 113 | 121 | } |
| 114 | 122 | |
| 115 | 123 | /** |
| @@ -248,7 +256,13 @@ | ||
| 248 | 256 | throw new TransportException(address, String.format("Error initializing connection: %s", error.message)); |
| 249 | 257 | case AUTHENTICATE: |
| 250 | 258 | Responses.Authenticate authenticate = (Responses.Authenticate) response; |
| 251 | - Authenticator authenticator = factory.authProvider.newAuthenticator(address, authenticate.authenticator); | |
| 259 | + Authenticator authenticator; | |
| 260 | + try { | |
| 261 | + authenticator = factory.authProvider.newAuthenticator(address, authenticate.authenticator); | |
| 262 | + } catch (AuthenticationException e) { | |
| 263 | + incrementAuthErrorMetric(); | |
| 264 | + throw e; | |
| 265 | + } | |
| 252 | 266 | switch (protocolVersion) { |
| 253 | 267 | case V1: |
| 254 | 268 | if (authenticator instanceof ProtocolV1Authenticator) |
| @@ -319,6 +333,7 @@ | ||
| 319 | 333 | case READY: |
| 320 | 334 | return checkClusterName(protocolVersion, executor); |
| 321 | 335 | case ERROR: |
| 336 | + incrementAuthErrorMetric(); | |
| 322 | 337 | throw new AuthenticationException(address, ((Responses.Error) authResponse).message); |
| 323 | 338 | default: |
| 324 | 339 | throw new TransportException(address, String.format("Unexpected %s response message from server to a CREDENTIALS message", authResponse.type)); |
| @@ -374,6 +389,7 @@ | ||
| 374 | 389 | if (message.startsWith("java.lang.ArrayIndexOutOfBoundsException: 15")) |
| 375 | 390 | message = String.format("Cannot use authenticator %s with protocol version 1, " |
| 376 | 391 | + "only plain text authentication is supported with this protocol version", authenticator); |
| 392 | + incrementAuthErrorMetric(); | |
| 377 | 393 | throw new AuthenticationException(address, message); |
| 378 | 394 | default: |
| 379 | 395 | throw new TransportException(address, String.format("Unexpected %s response message from server to authentication message", authResponse.type)); |
| @@ -382,6 +398,12 @@ | ||
| 382 | 398 | }; |
| 383 | 399 | } |
| 384 | 400 | |
| 401 | + private void incrementAuthErrorMetric() { | |
| 402 | + if (factory.manager.configuration.getMetricsOptions().isEnabled()) { | |
| 403 | + factory.manager.metrics.getErrorMetrics().getAuthenticationErrors().inc(); | |
| 404 | + } | |
| 405 | + } | |
| 406 | + | |
| 385 | 407 | private UnsupportedProtocolVersionException unsupportedProtocolVersionException(ProtocolVersion triedVersion, ProtocolVersion serverProtocolVersion) { |
| 386 | 408 | logger.debug("Got unsupported protocol version error from {} for version {} server supports version {}", address, triedVersion, serverProtocolVersion); |
| 387 | 409 | return new UnsupportedProtocolVersionException(address, triedVersion, serverProtocolVersion); |
| @@ -403,7 +425,6 @@ | ||
| 403 | 425 | else if (Host.statesLogger.isDebugEnabled()) |
| 404 | 426 | Host.statesLogger.debug("Defuncting {} because: {}", this, e.getMessage()); |
| 405 | 427 | |
| 406 | - | |
| 407 | 428 | Host host = factory.manager.metadata.getHost(address); |
| 408 | 429 | if (host != null) { |
| 409 | 430 | // Sometimes close() can be called before defunct(); avoid decrementing the connection count twice, but |
| @@ -437,14 +458,14 @@ | ||
| 437 | 458 | } |
| 438 | 459 | |
| 439 | 460 | String keyspace() { |
| 440 | - return keyspace; | |
| 461 | + return targetKeyspace.get().keyspace; | |
| 441 | 462 | } |
| 442 | 463 | |
| 443 | 464 | void setKeyspace(String keyspace) throws ConnectionException { |
| 444 | 465 | if (keyspace == null) |
| 445 | 466 | return; |
| 446 | 467 | |
| 447 | - if (this.keyspace != null && this.keyspace.equals(keyspace)) | |
| 468 | + if (Objects.equal(keyspace(), keyspace)) | |
| 448 | 469 | return; |
| 449 | 470 | |
| 450 | 471 | try { |
| @@ -468,24 +489,59 @@ | ||
| 468 | 489 | } |
| 469 | 490 | } |
| 470 | 491 | |
| 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 instanceof SetKeyspace) { | |
| 479 | - Connection.this.keyspace = ((SetKeyspace) response).keyspace; | |
| 480 | - return MoreFutures.VOID_SUCCESS; | |
| 481 | - } else if (response.type == ERROR) { | |
| 482 | - Responses.Error error = (Responses.Error) response; | |
| 483 | - throw defunct(error.asException(address)); | |
| 484 | - } else { | |
| 485 | - throw defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response)); | |
| 486 | - } | |
| 492 | + ListenableFuture<Connection> setKeyspaceAsync(final String keyspace) throws ConnectionException, BusyConnectionException { | |
| 493 | + SetKeyspaceAttempt existingAttempt = targetKeyspace.get(); | |
| 494 | + if (Objects.equal(existingAttempt.keyspace, keyspace)) | |
| 495 | + return existingAttempt.future; | |
| 496 | + | |
| 497 | + final SettableFuture<Connection> ksFuture = SettableFuture.create(); | |
| 498 | + final SetKeyspaceAttempt attempt = new SetKeyspaceAttempt(keyspace, ksFuture); | |
| 499 | + | |
| 500 | + // Check for an existing keyspace attempt. | |
| 501 | + while (true) { | |
| 502 | + existingAttempt = targetKeyspace.get(); | |
| 503 | + // if existing attempts' keyspace matches what we are trying to set, use it. | |
| 504 | + if (attempt.equals(existingAttempt)) { | |
| 505 | + return existingAttempt.future; | |
| 506 | + } else if (!existingAttempt.future.isDone()) { | |
| 507 | + // If the existing attempt is still in flight, fail this attempt immediately. | |
| 508 | + ksFuture.setException(new DriverException("Aborting attempt to set keyspace to '" + keyspace + "' since there is already an in flight attempt to set keyspace to '" + existingAttempt.keyspace + "'. " | |
| 509 | + + "This can happen if you try to USE different keyspaces from the same session simultaneously.")); | |
| 510 | + return ksFuture; | |
| 511 | + } else if (targetKeyspace.compareAndSet(existingAttempt, attempt)) { | |
| 512 | + // Otherwise, if the existing attempt is done, start a new set keyspace attempt for the new keyspace. | |
| 513 | + logger.debug("{} Setting keyspace {}", this, keyspace); | |
| 514 | + // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already | |
| 515 | + Future future = write(new Requests.Query("USE \"" + keyspace + '"')); | |
| 516 | + Futures.addCallback(future, new FutureCallback<Message.Response>() { | |
| 517 | + | |
| 518 | + @Override | |
| 519 | + public void onSuccess(Message.Response response) { | |
| 520 | + if (response instanceof SetKeyspace) { | |
| 521 | + logger.debug("{} Keyspace set to {}", Connection.this, keyspace); | |
| 522 | + ksFuture.set(Connection.this); | |
| 523 | + } else { | |
| 524 | + // Unset this attempt so new attempts may be made for the same keyspace. | |
| 525 | + targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt); | |
| 526 | + if (response.type == ERROR) { | |
| 527 | + Responses.Error error = (Responses.Error) response; | |
| 528 | + ksFuture.setException(defunct(error.asException(address))); | |
| 529 | + } else { | |
| 530 | + ksFuture.setException(defunct(new DriverInternalError("Unexpected response while setting keyspace: " + response))); | |
| 531 | + } | |
| 532 | + } | |
| 533 | + } | |
| 534 | + | |
| 535 | + @Override | |
| 536 | + public void onFailure(Throwable t) { | |
| 537 | + targetKeyspace.compareAndSet(attempt, defaultKeyspaceAttempt); | |
| 538 | + ksFuture.setException(t); | |
| 539 | + } | |
| 540 | + }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor()); | |
| 541 | + | |
| 542 | + return ksFuture; | |
| 487 | 543 | } |
| 488 | - }, factory.manager.configuration.getPoolingOptions().getInitializationExecutor()); | |
| 544 | + } | |
| 489 | 545 | } |
| 490 | 546 | |
| 491 | 547 | /** |
| @@ -993,7 +1049,7 @@ | ||
| 993 | 1049 | ResponseHandler handler = pending.remove(streamId); |
| 994 | 1050 | streamIdHandler.release(streamId); |
| 995 | 1051 | if (handler == null) { |
| 996 | - /** | |
| 1052 | + /* | |
| 997 | 1053 | * During normal operation, we should not receive responses for which we don't have a handler. There is |
| 998 | 1054 | * two cases however where this can happen: |
| 999 | 1055 | * 1) The connection has been defuncted due to some internal error and we've raced between removing the |
| @@ -1046,6 +1102,27 @@ | ||
| 1046 | 1102 | if (writer.get() > 0) |
| 1047 | 1103 | return; |
| 1048 | 1104 | |
| 1105 | + if (cause instanceof DecoderException) { | |
| 1106 | + Throwable error = cause.getCause(); | |
| 1107 | + // Special case, if we encountered a FrameTooLongException, raise exception on handler and don't defunct it since | |
| 1108 | + // the connection is in an ok state. | |
| 1109 | + if (error != null && error instanceof FrameTooLongException) { | |
| 1110 | + FrameTooLongException ftle = (FrameTooLongException) error; | |
| 1111 | + int streamId = ftle.getStreamId(); | |
| 1112 | + ResponseHandler handler = pending.remove(streamId); | |
| 1113 | + streamIdHandler.release(streamId); | |
| 1114 | + if (handler == null) { | |
| 1115 | + streamIdHandler.unmark(streamId); | |
| 1116 | + if (logger.isDebugEnabled()) | |
| 1117 | + logger.debug("{} FrameTooLongException received on stream {} but no handler set anymore (either the request has " | |
| 1118 | + + "timed out or it was closed due to another error).", Connection.this, streamId); | |
| 1119 | + return; | |
| 1120 | + } | |
| 1121 | + handler.cancelTimeout(); | |
| 1122 | + handler.callback.onException(Connection.this, ftle, System.nanoTime() - handler.startTime, handler.retryCount); | |
| 1123 | + return; | |
| 1124 | + } | |
| 1125 | + } | |
| 1049 | 1126 | defunct(new TransportException(address, String.format("Unexpected exception triggered (%s)", cause), cause)); |
| 1050 | 1127 | } |
| 1051 | 1128 | |
| @@ -1145,6 +1222,34 @@ | ||
| 1145 | 1222 | } |
| 1146 | 1223 | } |
| 1147 | 1224 | |
| 1225 | + private class SetKeyspaceAttempt { | |
| 1226 | + private final String keyspace; | |
| 1227 | + private final ListenableFuture<Connection> future; | |
| 1228 | + | |
| 1229 | + SetKeyspaceAttempt(String keyspace, ListenableFuture<Connection> future) { | |
| 1230 | + this.keyspace = keyspace; | |
| 1231 | + this.future = future; | |
| 1232 | + } | |
| 1233 | + | |
| 1234 | + @Override | |
| 1235 | + public boolean equals(Object o) { | |
| 1236 | + if (this == o) | |
| 1237 | + return true; | |
| 1238 | + if (!(o instanceof SetKeyspaceAttempt)) | |
| 1239 | + return false; | |
| 1240 | + | |
| 1241 | + SetKeyspaceAttempt that = (SetKeyspaceAttempt) o; | |
| 1242 | + | |
| 1243 | + return keyspace != null ? keyspace.equals(that.keyspace) : that.keyspace == null; | |
| 1244 | + | |
| 1245 | + } | |
| 1246 | + | |
| 1247 | + @Override | |
| 1248 | + public int hashCode() { | |
| 1249 | + return keyspace != null ? keyspace.hashCode() : 0; | |
| 1250 | + } | |
| 1251 | + } | |
| 1252 | + | |
| 1148 | 1253 | static class Future extends AbstractFuture<Message.Response> implements RequestHandler.Callback { |
| 1149 | 1254 | |
| 1150 | 1255 | private final Message.Request request; |
| @@ -1314,7 +1419,7 @@ | ||
| 1314 | 1419 | pipeline.addLast("ssl", sslOptions.newSSLHandler(channel)); |
| 1315 | 1420 | } |
| 1316 | 1421 | |
| 1317 | -// pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO)); | |
| 1422 | + // pipeline.addLast("debug", new LoggingHandler(LogLevel.INFO)); | |
| 1318 | 1423 | |
| 1319 | 1424 | pipeline.addLast("frameDecoder", new Frame.Decoder()); |
| 1320 | 1425 | pipeline.addLast("frameEncoder", frameEncoder); |
modified driver-core/src/main/java/com/datastax/driver/core/Frame.java +29 −20
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.DriverInternalError; |
| 19 | +import com.datastax.driver.core.exceptions.FrameTooLongException; | |
| 19 | 20 | import io.netty.buffer.ByteBuf; |
| 20 | 21 | import io.netty.channel.ChannelHandler; |
| 21 | 22 | import io.netty.channel.ChannelHandlerContext; |
| @@ -189,42 +190,44 @@ | ||
| 189 | 190 | } |
| 190 | 191 | |
| 191 | 192 | static final class Decoder extends ByteToMessageDecoder { |
| 192 | - static final DecoderForStreamIdSize decoderV1 = new DecoderForStreamIdSize(1); | |
| 193 | - static final DecoderForStreamIdSize decoderV3 = new DecoderForStreamIdSize(2); | |
| 193 | + private DecoderForStreamIdSize decoder; | |
| 194 | 194 | |
| 195 | 195 | @Override |
| 196 | 196 | protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { |
| 197 | 197 | if (buffer.readableBytes() < 1) |
| 198 | 198 | return; |
| 199 | 199 | |
| 200 | - int version = buffer.getByte(0); | |
| 201 | - // version first bit is the "direction" of the frame (request or response) | |
| 202 | - version = version & 0x7F; | |
| 200 | + // Initialize sub decoder on first message. No synchronization needed as | |
| 201 | + // decode is always called from same thread. | |
| 202 | + if (decoder == null) { | |
| 203 | + int version = buffer.getByte(buffer.readerIndex()); | |
| 204 | + // version first bit is the "direction" of the frame (request or response) | |
| 205 | + version = version & 0x7F; | |
| 206 | + decoder = new DecoderForStreamIdSize(version, version >= 3 ? 2 : 1); | |
| 207 | + } | |
| 203 | 208 | |
| 204 | - DecoderForStreamIdSize decoder = (version >= 3) ? decoderV3 : decoderV1; | |
| 205 | 209 | Object frame = decoder.decode(ctx, buffer); |
| 206 | 210 | if (frame != null) |
| 207 | 211 | out.add(frame); |
| 208 | 212 | } |
| 209 | 213 | |
| 210 | 214 | static class DecoderForStreamIdSize extends LengthFieldBasedFrameDecoder { |
| 211 | - private static final int MAX_FRAME_LENGTH = 256 * 1024 * 1024; // 256 MB | |
| 212 | - private final int opcodeOffset; | |
| 213 | - | |
| 214 | - DecoderForStreamIdSize(int streamIdSize) { | |
| 215 | + // The maximum response frame length allowed. Note that C* does not currently restrict the length of its responses (CASSANDRA-12630). | |
| 216 | + private static final int MAX_FRAME_LENGTH = SystemProperties.getInt("com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB", 256) * 1024 * 1024; // 256 MB | |
| 217 | + private final int protocolVersion; | |
| 218 | + | |
| 219 | + DecoderForStreamIdSize(int protocolVersion, int streamIdSize) { | |
| 215 | 220 | super(MAX_FRAME_LENGTH, /*lengthOffset=*/ 3 + streamIdSize, 4, 0, 0, true); |
| 216 | - this.opcodeOffset = 2 + streamIdSize; | |
| 221 | + this.protocolVersion = protocolVersion; | |
| 217 | 222 | } |
| 218 | 223 | |
| 219 | 224 | @Override |
| 220 | 225 | protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { |
| 226 | + // Capture current index in case we need to get the stream id. | |
| 227 | + // If a TooLongFrameException is thrown the readerIndex will advance to the end of | |
| 228 | + // the buffer (or past the frame) so we need the position as we entered this method. | |
| 229 | + int curIndex = buffer.readerIndex(); | |
| 221 | 230 | try { |
| 222 | - if (buffer.readableBytes() < opcodeOffset + 1) | |
| 223 | - return null; | |
| 224 | - | |
| 225 | - // Validate the opcode (this will throw if it's not a response) | |
| 226 | - Message.Response.Type.fromOpcode(buffer.getByte(opcodeOffset)); | |
| 227 | - | |
| 228 | 231 | ByteBuf frame = (ByteBuf) super.decode(ctx, buffer); |
| 229 | 232 | if (frame == null) { |
| 230 | 233 | return null; |
| @@ -232,11 +235,17 @@ | ||
| 232 | 235 | // Do not deallocate `frame` just yet, because it is stored as Frame.body and will be used |
| 233 | 236 | // in Message.ProtocolDecoder or Frame.Decompressor if compression is enabled (we deallocate |
| 234 | 237 | // it there). |
| 235 | - return Frame.create(frame); | |
| 238 | + Frame theFrame = Frame.create(frame); | |
| 239 | + // Validate the opcode (this will throw if it's not a response) | |
| 240 | + Message.Response.Type.fromOpcode(theFrame.header.opcode); | |
| 241 | + return theFrame; | |
| 236 | 242 | } catch (CorruptedFrameException e) { |
| 237 | - throw new DriverInternalError(e.getMessage()); | |
| 243 | + throw new DriverInternalError(e); | |
| 238 | 244 | } catch (TooLongFrameException e) { |
| 239 | - throw new DriverInternalError(e.getMessage()); | |
| 245 | + int streamId = protocolVersion > 2 ? | |
| 246 | + buffer.getShort(curIndex + 2) : | |
| 247 | + buffer.getByte(curIndex + 2); | |
| 248 | + throw new FrameTooLongException(streamId); | |
| 240 | 249 | } |
| 241 | 250 | } |
| 242 | 251 | } |
modified driver-core/src/main/java/com/datastax/driver/core/FrameCompressor.java +14 −124
| @@ -15,138 +15,28 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.exceptions.DriverInternalError; | |
| 19 | -import io.netty.buffer.Unpooled; | |
| 20 | -import net.jpountz.lz4.LZ4Factory; | |
| 21 | -import org.slf4j.Logger; | |
| 22 | -import org.slf4j.LoggerFactory; | |
| 23 | -import org.xerial.snappy.Snappy; | |
| 18 | +import io.netty.buffer.ByteBuf; | |
| 24 | 19 | |
| 25 | 20 | import java.io.IOException; |
| 21 | +import java.nio.ByteBuffer; | |
| 26 | 22 | |
| 27 | 23 | abstract class FrameCompressor { |
| 28 | 24 | |
| 29 | - private static final Logger logger = LoggerFactory.getLogger(FrameCompressor.class); | |
| 25 | + abstract Frame compress(Frame frame) throws IOException; | |
| 30 | 26 | |
| 31 | - public abstract Frame compress(Frame frame) throws IOException; | |
| 27 | + abstract Frame decompress(Frame frame) throws IOException; | |
| 32 | 28 | |
| 33 | - public abstract Frame decompress(Frame frame) throws IOException; | |
| 34 | - | |
| 35 | - public static class SnappyCompressor extends FrameCompressor { | |
| 36 | - | |
| 37 | - public static final SnappyCompressor instance; | |
| 38 | - | |
| 39 | - static { | |
| 40 | - SnappyCompressor i; | |
| 41 | - try { | |
| 42 | - i = new SnappyCompressor(); | |
| 43 | - } catch (NoClassDefFoundError e) { | |
| 44 | - i = null; | |
| 45 | - logger.warn("Cannot find Snappy class, you should make sure the Snappy library is in the classpath if you intend to use it. Snappy compression will not be available for the protocol."); | |
| 46 | - } catch (Throwable e) { | |
| 47 | - i = null; | |
| 48 | - logger.warn("Error loading Snappy library ({}). Snappy compression will not be available for the protocol.", e.toString()); | |
| 49 | - } | |
| 50 | - instance = i; | |
| 51 | - } | |
| 52 | - | |
| 53 | - private SnappyCompressor() { | |
| 54 | - // this would throw java.lang.NoClassDefFoundError if Snappy class | |
| 55 | - // wasn't found at runtime which should be processed by the calling method | |
| 56 | - Snappy.getNativeLibraryVersion(); | |
| 57 | - } | |
| 58 | - | |
| 59 | - @Override | |
| 60 | - public Frame compress(Frame frame) throws IOException { | |
| 61 | - byte[] input = CBUtil.readRawBytes(frame.body); | |
| 62 | - byte[] output = new byte[Snappy.maxCompressedLength(input.length)]; | |
| 63 | - | |
| 64 | - int written = Snappy.compress(input, 0, input.length, output, 0); | |
| 65 | - return frame.with(Unpooled.wrappedBuffer(output, 0, written)); | |
| 66 | - } | |
| 67 | - | |
| 68 | - @Override | |
| 69 | - public Frame decompress(Frame frame) throws IOException { | |
| 70 | - byte[] input = CBUtil.readRawBytes(frame.body); | |
| 71 | - | |
| 72 | - if (!Snappy.isValidCompressedBuffer(input, 0, input.length)) | |
| 73 | - throw new DriverInternalError("Provided frame does not appear to be Snappy compressed"); | |
| 74 | - | |
| 75 | - byte[] output = new byte[Snappy.uncompressedLength(input)]; | |
| 76 | - int size = Snappy.uncompress(input, 0, input.length, output, 0); | |
| 77 | - return frame.with(Unpooled.wrappedBuffer(output, 0, size)); | |
| 78 | - } | |
| 29 | + protected static ByteBuffer inputNioBuffer(ByteBuf buf) { | |
| 30 | + // Using internalNioBuffer(...) as we only hold the reference in this method and so can | |
| 31 | + // reduce Object allocations. | |
| 32 | + int index = buf.readerIndex(); | |
| 33 | + int len = buf.readableBytes(); | |
| 34 | + return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len); | |
| 79 | 35 | } |
| 80 | 36 | |
| 81 | - public static class LZ4Compressor extends FrameCompressor { | |
| 82 | - | |
| 83 | - public static final LZ4Compressor instance; | |
| 84 | - | |
| 85 | - static { | |
| 86 | - LZ4Compressor i; | |
| 87 | - try { | |
| 88 | - i = new LZ4Compressor(); | |
| 89 | - } catch (NoClassDefFoundError e) { | |
| 90 | - i = null; | |
| 91 | - logger.warn("Cannot find LZ4 class, you should make sure the LZ4 library is in the classpath if you intend to use it. LZ4 compression will not be available for the protocol."); | |
| 92 | - } catch (Throwable e) { | |
| 93 | - i = null; | |
| 94 | - logger.warn("Error loading LZ4 library ({}). LZ4 compression will not be available for the protocol.", e.toString()); | |
| 95 | - } | |
| 96 | - instance = i; | |
| 97 | - } | |
| 98 | - | |
| 99 | - private static final int INTEGER_BYTES = 4; | |
| 100 | - private final net.jpountz.lz4.LZ4Compressor compressor; | |
| 101 | - private final net.jpountz.lz4.LZ4FastDecompressor decompressor; | |
| 102 | - | |
| 103 | - private LZ4Compressor() { | |
| 104 | - final LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); | |
| 105 | - logger.info("Using {}", lz4Factory.toString()); | |
| 106 | - compressor = lz4Factory.fastCompressor(); | |
| 107 | - decompressor = lz4Factory.fastDecompressor(); | |
| 108 | - } | |
| 109 | - | |
| 110 | - @Override | |
| 111 | - public Frame compress(Frame frame) throws IOException { | |
| 112 | - byte[] input = CBUtil.readRawBytes(frame.body); | |
| 113 | - | |
| 114 | - int maxCompressedLength = compressor.maxCompressedLength(input.length); | |
| 115 | - byte[] output = new byte[INTEGER_BYTES + maxCompressedLength]; | |
| 116 | - | |
| 117 | - output[0] = (byte) (input.length >>> 24); | |
| 118 | - output[1] = (byte) (input.length >>> 16); | |
| 119 | - output[2] = (byte) (input.length >>> 8); | |
| 120 | - output[3] = (byte) (input.length); | |
| 121 | - | |
| 122 | - try { | |
| 123 | - int written = compressor.compress(input, 0, input.length, output, INTEGER_BYTES, maxCompressedLength); | |
| 124 | - return frame.with(Unpooled.wrappedBuffer(output, 0, INTEGER_BYTES + written)); | |
| 125 | - } catch (Exception e) { | |
| 126 | - throw new IOException(e); | |
| 127 | - } | |
| 128 | - } | |
| 129 | - | |
| 130 | - @Override | |
| 131 | - public Frame decompress(Frame frame) throws IOException { | |
| 132 | - byte[] input = CBUtil.readRawBytes(frame.body); | |
| 133 | - | |
| 134 | - int uncompressedLength = ((input[0] & 0xFF) << 24) | |
| 135 | - | ((input[1] & 0xFF) << 16) | |
| 136 | - | ((input[2] & 0xFF) << 8) | |
| 137 | - | ((input[3] & 0xFF)); | |
| 138 | - | |
| 139 | - byte[] output = new byte[uncompressedLength]; | |
| 140 | - | |
| 141 | - try { | |
| 142 | - int read = decompressor.decompress(input, INTEGER_BYTES, output, 0, uncompressedLength); | |
| 143 | - if (read != input.length - INTEGER_BYTES) | |
| 144 | - throw new IOException("Compressed lengths mismatch"); | |
| 145 | - | |
| 146 | - return frame.with(Unpooled.wrappedBuffer(output)); | |
| 147 | - } catch (Exception e) { | |
| 148 | - throw new IOException(e); | |
| 149 | - } | |
| 150 | - } | |
| 37 | + protected static ByteBuffer outputNioBuffer(ByteBuf buf) { | |
| 38 | + int index = buf.writerIndex(); | |
| 39 | + int len = buf.writableBytes(); | |
| 40 | + return buf.nioBufferCount() == 1 ? buf.internalNioBuffer(index, len) : buf.nioBuffer(index, len); | |
| 151 | 41 | } |
| 152 | 42 | } |
modified driver-core/src/main/java/com/datastax/driver/core/HostConnectionPool.java +95 −113
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.AuthenticationException; |
| 19 | +import com.datastax.driver.core.exceptions.BusyPoolException; | |
| 19 | 20 | import com.datastax.driver.core.exceptions.ConnectionException; |
| 20 | 21 | import com.datastax.driver.core.exceptions.UnsupportedProtocolVersionException; |
| 21 | 22 | import com.datastax.driver.core.utils.MoreFutures; |
| @@ -26,16 +27,10 @@ | ||
| 26 | 27 | import org.slf4j.Logger; |
| 27 | 28 | import org.slf4j.LoggerFactory; |
| 28 | 29 | |
| 29 | -import java.util.ArrayList; | |
| 30 | -import java.util.List; | |
| 31 | -import java.util.ListIterator; | |
| 32 | -import java.util.Set; | |
| 30 | +import java.util.*; | |
| 33 | 31 | import java.util.concurrent.*; |
| 34 | 32 | import java.util.concurrent.atomic.AtomicInteger; |
| 35 | 33 | import java.util.concurrent.atomic.AtomicReference; |
| 36 | -import java.util.concurrent.locks.Condition; | |
| 37 | -import java.util.concurrent.locks.Lock; | |
| 38 | -import java.util.concurrent.locks.ReentrantLock; | |
| 39 | 34 | |
| 40 | 35 | import static com.datastax.driver.core.Connection.State.*; |
| 41 | 36 | |
| @@ -62,9 +57,8 @@ | ||
| 62 | 57 | @VisibleForTesting |
| 63 | 58 | final Set<Connection> trash = new CopyOnWriteArraySet<Connection>(); |
| 64 | 59 | |
| 65 | - private volatile int waiter = 0; | |
| 66 | - private final Lock waitLock = new ReentrantLock(true); | |
| 67 | - private final Condition hasAvailableConnection = waitLock.newCondition(); | |
| 60 | + private final Queue<SettableFuture<Connection>> pendingBorrows = new ConcurrentLinkedQueue<SettableFuture<Connection>>(); | |
| 61 | + private final AtomicInteger pendingBorrowCount = new AtomicInteger(); | |
| 68 | 62 | |
| 69 | 63 | private final Runnable newConnectionTask; |
| 70 | 64 | |
| @@ -81,7 +75,7 @@ | ||
| 81 | 75 | // following threshold, we just replace the connection by a new one. |
| 82 | 76 | private final int minAllowedStreams; |
| 83 | 77 | |
| 84 | - public HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) { | |
| 78 | + HostConnectionPool(Host host, HostDistance hostDistance, SessionManager manager) { | |
| 85 | 79 | assert hostDistance != HostDistance.IGNORED; |
| 86 | 80 | this.host = host; |
| 87 | 81 | this.hostDistance = hostDistance; |
| @@ -196,17 +190,13 @@ | ||
| 196 | 190 | return manager.configuration().getPoolingOptions(); |
| 197 | 191 | } |
| 198 | 192 | |
| 199 | - public Connection borrowConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 193 | + ListenableFuture<Connection> borrowConnection(int maxQueueSize) { | |
| 200 | 194 | Phase phase = this.phase.get(); |
| 201 | 195 | if (phase != Phase.READY) |
| 202 | - // Note: throwing a ConnectionException is probably fine in practice as it will trigger the creation of a new host. | |
| 203 | - // That being said, maybe having a specific exception could be cleaner. | |
| 204 | - throw new ConnectionException(host.getSocketAddress(), "Pool is " + phase); | |
| 196 | + return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is " + phase)); | |
| 205 | 197 | |
| 206 | 198 | if (connections.isEmpty()) { |
| 207 | - if (!host.convictionPolicy.canReconnectNow()) | |
| 208 | - throw new TimeoutException("Connection pool is empty, currently trying to reestablish connections"); | |
| 209 | - else { | |
| 199 | + if (host.convictionPolicy.canReconnectNow()) { | |
| 210 | 200 | int coreSize = options().getCoreConnectionsPerHost(hostDistance); |
| 211 | 201 | if (coreSize == 0) { |
| 212 | 202 | maybeSpawnNewConnection(); |
| @@ -218,10 +208,7 @@ | ||
| 218 | 208 | manager.blockingExecutor().submit(newConnectionTask); |
| 219 | 209 | } |
| 220 | 210 | } |
| 221 | - Connection c = waitForConnection(timeout, unit); | |
| 222 | - totalInFlight.incrementAndGet(); | |
| 223 | - c.setKeyspace(manager.poolsState.keyspace); | |
| 224 | - return c; | |
| 211 | + return enqueue(maxQueueSize); | |
| 225 | 212 | } |
| 226 | 213 | } |
| 227 | 214 | |
| @@ -238,18 +225,17 @@ | ||
| 238 | 225 | if (leastBusy == null) { |
| 239 | 226 | // We could have raced with a shutdown since the last check |
| 240 | 227 | if (isClosed()) |
| 241 | - throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); | |
| 228 | + return Futures.immediateFailedFuture(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); | |
| 242 | 229 | // This might maybe happen if the number of core connections per host is 0 and a connection was trashed between |
| 243 | 230 | // the previous check to connections and now. But in that case, the line above will have trigger the creation of |
| 244 | 231 | // a new connection, so just wait that connection and move on |
| 245 | - leastBusy = waitForConnection(timeout, unit); | |
| 232 | + return enqueue(maxQueueSize); | |
| 246 | 233 | } else { |
| 247 | 234 | while (true) { |
| 248 | 235 | int inFlight = leastBusy.inFlight.get(); |
| 249 | 236 | |
| 250 | 237 | if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) { |
| 251 | - leastBusy = waitForConnection(timeout, unit); | |
| 252 | - break; | |
| 238 | + return enqueue(maxQueueSize); | |
| 253 | 239 | } |
| 254 | 240 | |
| 255 | 241 | if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) |
| @@ -276,96 +262,37 @@ | ||
| 276 | 262 | maybeSpawnNewConnection(); |
| 277 | 263 | } |
| 278 | 264 | |
| 279 | - leastBusy.setKeyspace(manager.poolsState.keyspace); | |
| 280 | - return leastBusy; | |
| 281 | - } | |
| 282 | - | |
| 283 | - private void awaitAvailableConnection(long timeout, TimeUnit unit) throws InterruptedException { | |
| 284 | - waitLock.lock(); | |
| 285 | - waiter++; | |
| 286 | - try { | |
| 287 | - hasAvailableConnection.await(timeout, unit); | |
| 288 | - } finally { | |
| 289 | - waiter--; | |
| 290 | - waitLock.unlock(); | |
| 291 | - } | |
| 292 | - } | |
| 293 | - | |
| 294 | - private void signalAvailableConnection() { | |
| 295 | - // Quick check if it's worth signaling to avoid locking | |
| 296 | - if (waiter == 0) | |
| 297 | - return; | |
| 298 | - | |
| 299 | - waitLock.lock(); | |
| 300 | - try { | |
| 301 | - hasAvailableConnection.signal(); | |
| 302 | - } finally { | |
| 303 | - waitLock.unlock(); | |
| 304 | - } | |
| 265 | + return leastBusy.setKeyspaceAsync(manager.poolsState.keyspace); | |
| 305 | 266 | } |
| 306 | 267 | |
| 307 | - private void signalAllAvailableConnection() { | |
| 308 | - // Quick check if it's worth signaling to avoid locking | |
| 309 | - if (waiter == 0) | |
| 310 | - return; | |
| 311 | - | |
| 312 | - waitLock.lock(); | |
| 313 | - try { | |
| 314 | - hasAvailableConnection.signalAll(); | |
| 315 | - } finally { | |
| 316 | - waitLock.unlock(); | |
| 268 | + private ListenableFuture<Connection> enqueue(int maxQueueSize) { | |
| 269 | + if (maxQueueSize == 0) { | |
| 270 | + return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), 0)); | |
| 317 | 271 | } |
| 318 | - } | |
| 319 | 272 | |
| 320 | - private Connection waitForConnection(long timeout, TimeUnit unit) throws ConnectionException, TimeoutException { | |
| 321 | - if (timeout == 0) | |
| 322 | - throw new TimeoutException("All connections are busy and pool timeout is 0"); | |
| 323 | - | |
| 324 | - long start = System.nanoTime(); | |
| 325 | - long remaining = timeout; | |
| 326 | - do { | |
| 327 | - try { | |
| 328 | - awaitAvailableConnection(remaining, unit); | |
| 329 | - } catch (InterruptedException e) { | |
| 330 | - Thread.currentThread().interrupt(); | |
| 331 | - // If we're interrupted fine, check if there is a connection available but stop waiting otherwise | |
| 332 | - timeout = 0; // this will make us stop the loop if we don't get a connection right away | |
| 273 | + while (true) { | |
| 274 | + int count = pendingBorrowCount.get(); | |
| 275 | + if (count >= maxQueueSize) { | |
| 276 | + return Futures.immediateFailedFuture(new BusyPoolException(host.getSocketAddress(), maxQueueSize)); | |
| 333 | 277 | } |
| 334 | - | |
| 335 | - if (isClosed()) | |
| 336 | - throw new ConnectionException(host.getSocketAddress(), "Pool is shutdown"); | |
| 337 | - | |
| 338 | - int minInFlight = Integer.MAX_VALUE; | |
| 339 | - Connection leastBusy = null; | |
| 340 | - for (Connection connection : connections) { | |
| 341 | - int inFlight = connection.inFlight.get(); | |
| 342 | - if (inFlight < minInFlight) { | |
| 343 | - minInFlight = inFlight; | |
| 344 | - leastBusy = connection; | |
| 345 | - } | |
| 278 | + if (pendingBorrowCount.compareAndSet(count, count + 1)) { | |
| 279 | + break; | |
| 346 | 280 | } |
| 281 | + } | |
| 347 | 282 | |
| 348 | - // If we race with shutdown, leastBusy could be null. In that case we just loop and we'll throw on the next | |
| 349 | - // iteration anyway | |
| 350 | - if (leastBusy != null) { | |
| 351 | - while (true) { | |
| 352 | - int inFlight = leastBusy.inFlight.get(); | |
| 353 | - | |
| 354 | - if (inFlight >= Math.min(leastBusy.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) | |
| 355 | - break; | |
| 356 | - | |
| 357 | - if (leastBusy.inFlight.compareAndSet(inFlight, inFlight + 1)) | |
| 358 | - return leastBusy; | |
| 359 | - } | |
| 360 | - } | |
| 283 | + SettableFuture<Connection> future = SettableFuture.create(); | |
| 284 | + pendingBorrows.add(future); | |
| 361 | 285 | |
| 362 | - remaining = timeout - Cluster.timeSince(start, unit); | |
| 363 | - } while (remaining > 0); | |
| 286 | + // If we raced with shutdown, make sure the future will be completed. This has no effect if it was properly | |
| 287 | + // handled in closeAsync. | |
| 288 | + if (phase.get() == Phase.CLOSING) { | |
| 289 | + future.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); | |
| 290 | + } | |
| 364 | 291 | |
| 365 | - throw new TimeoutException("All connections are busy"); | |
| 292 | + return future; | |
| 366 | 293 | } |
| 367 | 294 | |
| 368 | - public void returnConnection(Connection connection) { | |
| 295 | + void returnConnection(Connection connection) { | |
| 369 | 296 | connection.inFlight.decrementAndGet(); |
| 370 | 297 | totalInFlight.decrementAndGet(); |
| 371 | 298 | |
| @@ -384,7 +311,60 @@ | ||
| 384 | 311 | if (connection.maxAvailableStreams() < minAllowedStreams) { |
| 385 | 312 | replaceConnection(connection); |
| 386 | 313 | } else { |
| 387 | - signalAvailableConnection(); | |
| 314 | + dequeue(connection); | |
| 315 | + } | |
| 316 | + } | |
| 317 | + } | |
| 318 | + | |
| 319 | + // When a connection gets returned to the pool, check if there are pending borrows that can be completed with it. | |
| 320 | + private void dequeue(Connection connection) { | |
| 321 | + while (!pendingBorrows.isEmpty()) { | |
| 322 | + | |
| 323 | + // We can only reuse the connection if it's under its maximum number of inFlight requests. | |
| 324 | + // Do this atomically, as we could be competing with other borrowConnection or dequeue calls. | |
| 325 | + while (true) { | |
| 326 | + int inFlight = connection.inFlight.get(); | |
| 327 | + if (inFlight >= Math.min(connection.maxAvailableStreams(), options().getMaxRequestsPerConnection(hostDistance))) { | |
| 328 | + // Connection is full again, stop dequeuing | |
| 329 | + return; | |
| 330 | + } | |
| 331 | + if (connection.inFlight.compareAndSet(inFlight, inFlight + 1)) { | |
| 332 | + // We acquired the right to reuse the connection for one request, proceed | |
| 333 | + break; | |
| 334 | + } | |
| 335 | + } | |
| 336 | + | |
| 337 | + final SettableFuture<Connection> pendingBorrow = pendingBorrows.poll(); | |
| 338 | + if (pendingBorrow == null) { | |
| 339 | + // Another thread has emptied the queue since our last check, restore the count | |
| 340 | + connection.inFlight.decrementAndGet(); | |
| 341 | + } else { | |
| 342 | + totalInFlight.incrementAndGet(); | |
| 343 | + pendingBorrowCount.decrementAndGet(); | |
| 344 | + // Ensure that the keyspace set on the connection is the one set on the pool state, in the general case it will be. | |
| 345 | + ListenableFuture<Connection> setKeyspaceFuture = connection.setKeyspaceAsync(manager.poolsState.keyspace); | |
| 346 | + // Slight optimization, if the keyspace was already correct the future will be complete, so simply complete it here. | |
| 347 | + if (setKeyspaceFuture.isDone()) { | |
| 348 | + try { | |
| 349 | + pendingBorrow.set(Uninterruptibles.getUninterruptibly(setKeyspaceFuture)); | |
| 350 | + } catch (ExecutionException e) { | |
| 351 | + pendingBorrow.setException(e.getCause()); | |
| 352 | + } | |
| 353 | + } else { | |
| 354 | + // Otherwise the keyspace did need to be set, tie the pendingBorrow future to the set keyspace completion. | |
| 355 | + Futures.addCallback(setKeyspaceFuture, new FutureCallback<Connection>() { | |
| 356 | + | |
| 357 | + @Override | |
| 358 | + public void onSuccess(Connection c) { | |
| 359 | + pendingBorrow.set(c); | |
| 360 | + } | |
| 361 | + | |
| 362 | + @Override | |
| 363 | + public void onFailure(Throwable t) { | |
| 364 | + pendingBorrow.setException(t); | |
| 365 | + } | |
| 366 | + }); | |
| 367 | + } | |
| 388 | 368 | } |
| 389 | 369 | } |
| 390 | 370 | } |
| @@ -453,6 +433,7 @@ | ||
| 453 | 433 | } |
| 454 | 434 | logger.debug("Creating new connection on busy pool to {}", host); |
| 455 | 435 | newConnection = manager.connectionFactory().open(this); |
| 436 | + newConnection.setKeyspace(manager.poolsState.keyspace); | |
| 456 | 437 | } |
| 457 | 438 | connections.add(newConnection); |
| 458 | 439 | |
| @@ -465,7 +446,7 @@ | ||
| 465 | 446 | return false; |
| 466 | 447 | } |
| 467 | 448 | |
| 468 | - signalAvailableConnection(); | |
| 449 | + dequeue(newConnection); | |
| 469 | 450 | return true; |
| 470 | 451 | } catch (InterruptedException e) { |
| 471 | 452 | Thread.currentThread().interrupt(); |
| @@ -600,11 +581,11 @@ | ||
| 600 | 581 | connection.closeAsync(); |
| 601 | 582 | } |
| 602 | 583 | |
| 603 | - public final boolean isClosed() { | |
| 584 | + final boolean isClosed() { | |
| 604 | 585 | return closeFuture.get() != null; |
| 605 | 586 | } |
| 606 | 587 | |
| 607 | - public final CloseFuture closeAsync() { | |
| 588 | + final CloseFuture closeAsync() { | |
| 608 | 589 | |
| 609 | 590 | CloseFuture future = closeFuture.get(); |
| 610 | 591 | if (future != null) |
| @@ -612,8 +593,9 @@ | ||
| 612 | 593 | |
| 613 | 594 | phase.set(Phase.CLOSING); |
| 614 | 595 | |
| 615 | - // Wake up all threads that wait | |
| 616 | - signalAllAvailableConnection(); | |
| 596 | + for (SettableFuture<Connection> pendingBorrow : pendingBorrows) { | |
| 597 | + pendingBorrow.setException(new ConnectionException(host.getSocketAddress(), "Pool is shutdown")); | |
| 598 | + } | |
| 617 | 599 | |
| 618 | 600 | future = new CloseFuture.Forwarding(discardAvailableConnections()); |
| 619 | 601 | |
| @@ -622,7 +604,7 @@ | ||
| 622 | 604 | : closeFuture.get(); // We raced, it's ok, return the future that was actually set |
| 623 | 605 | } |
| 624 | 606 | |
| 625 | - public int opened() { | |
| 607 | + int opened() { | |
| 626 | 608 | return open.get(); |
| 627 | 609 | } |
| 628 | 610 | |
| @@ -657,7 +639,7 @@ | ||
| 657 | 639 | |
| 658 | 640 | // This creates connections if we have less than core connections (if we |
| 659 | 641 | // have more than core, connection will just get trash when we can). |
| 660 | - public void ensureCoreConnections() { | |
| 642 | + void ensureCoreConnections() { | |
| 661 | 643 | if (isClosed()) |
| 662 | 644 | return; |
| 663 | 645 |
added driver-core/src/main/java/com/datastax/driver/core/LZ4Compressor.java +182 −0
| @@ -0,0 +1,182 @@ | ||
| 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 io.netty.buffer.ByteBuf; | |
| 19 | +import net.jpountz.lz4.LZ4Factory; | |
| 20 | +import org.slf4j.Logger; | |
| 21 | +import org.slf4j.LoggerFactory; | |
| 22 | + | |
| 23 | +import java.io.IOException; | |
| 24 | +import java.nio.ByteBuffer; | |
| 25 | + | |
| 26 | +class LZ4Compressor extends FrameCompressor { | |
| 27 | + | |
| 28 | + private static final Logger logger = LoggerFactory.getLogger(LZ4Compressor.class); | |
| 29 | + | |
| 30 | + static final LZ4Compressor instance; | |
| 31 | + | |
| 32 | + static { | |
| 33 | + LZ4Compressor i; | |
| 34 | + try { | |
| 35 | + i = new LZ4Compressor(); | |
| 36 | + } catch (NoClassDefFoundError e) { | |
| 37 | + i = null; | |
| 38 | + logger.warn("Cannot find LZ4 class, you should make sure the LZ4 library is in the classpath if you intend to use it. LZ4 compression will not be available for the protocol."); | |
| 39 | + } catch (Throwable e) { | |
| 40 | + i = null; | |
| 41 | + logger.warn("Error loading LZ4 library ({}). LZ4 compression will not be available for the protocol.", e.toString()); | |
| 42 | + } | |
| 43 | + instance = i; | |
| 44 | + } | |
| 45 | + | |
| 46 | + private static final int INTEGER_BYTES = 4; | |
| 47 | + private final net.jpountz.lz4.LZ4Compressor compressor; | |
| 48 | + private final net.jpountz.lz4.LZ4FastDecompressor decompressor; | |
| 49 | + | |
| 50 | + private LZ4Compressor() { | |
| 51 | + final LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); | |
| 52 | + logger.info("Using {}", lz4Factory.toString()); | |
| 53 | + compressor = lz4Factory.fastCompressor(); | |
| 54 | + decompressor = lz4Factory.fastDecompressor(); | |
| 55 | + } | |
| 56 | + | |
| 57 | + @Override | |
| 58 | + Frame compress(Frame frame) throws IOException { | |
| 59 | + ByteBuf input = frame.body; | |
| 60 | + | |
| 61 | + // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated. | |
| 62 | + ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input); | |
| 63 | + return frame.with(frameBody); | |
| 64 | + } | |
| 65 | + | |
| 66 | + private ByteBuf compressDirect(ByteBuf input) throws IOException { | |
| 67 | + int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes()); | |
| 68 | + // If the input is direct we will allocate a direct output buffer as well as this will allow us to use | |
| 69 | + // LZ4Compressor.compress and so eliminate memory copies. | |
| 70 | + ByteBuf output = input.alloc().directBuffer(INTEGER_BYTES + maxCompressedLength); | |
| 71 | + try { | |
| 72 | + ByteBuffer in = inputNioBuffer(input); | |
| 73 | + // Increase reader index. | |
| 74 | + input.readerIndex(input.writerIndex()); | |
| 75 | + | |
| 76 | + output.writeInt(in.remaining()); | |
| 77 | + | |
| 78 | + ByteBuffer out = outputNioBuffer(output); | |
| 79 | + int written = compressor.compress(in, in.position(), in.remaining(), out, out.position(), out.remaining()); | |
| 80 | + // Set the writer index so the amount of written bytes is reflected | |
| 81 | + output.writerIndex(output.writerIndex() + written); | |
| 82 | + } catch (Exception e) { | |
| 83 | + // release output buffer so we not leak and rethrow exception. | |
| 84 | + output.release(); | |
| 85 | + throw new IOException(e); | |
| 86 | + } | |
| 87 | + return output; | |
| 88 | + } | |
| 89 | + | |
| 90 | + private ByteBuf compressHeap(ByteBuf input) throws IOException { | |
| 91 | + int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes()); | |
| 92 | + | |
| 93 | + // Not a direct buffer so use byte arrays... | |
| 94 | + int inOffset = input.arrayOffset() + input.readerIndex(); | |
| 95 | + byte[] in = input.array(); | |
| 96 | + int len = input.readableBytes(); | |
| 97 | + // Increase reader index. | |
| 98 | + input.readerIndex(input.writerIndex()); | |
| 99 | + | |
| 100 | + // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so | |
| 101 | + // can eliminate the overhead of allocate a new byte[]. | |
| 102 | + ByteBuf output = input.alloc().heapBuffer(INTEGER_BYTES + maxCompressedLength); | |
| 103 | + try { | |
| 104 | + output.writeInt(len); | |
| 105 | + // calculate the correct offset. | |
| 106 | + int offset = output.arrayOffset() + output.writerIndex(); | |
| 107 | + byte[] out = output.array(); | |
| 108 | + int written = compressor.compress(in, inOffset, len, out, offset); | |
| 109 | + | |
| 110 | + // Set the writer index so the amount of written bytes is reflected | |
| 111 | + output.writerIndex(output.writerIndex() + written); | |
| 112 | + } catch (Exception e) { | |
| 113 | + // release output buffer so we not leak and rethrow exception. | |
| 114 | + output.release(); | |
| 115 | + throw new IOException(e); | |
| 116 | + } | |
| 117 | + return output; | |
| 118 | + } | |
| 119 | + | |
| 120 | + @Override | |
| 121 | + Frame decompress(Frame frame) throws IOException { | |
| 122 | + ByteBuf input = frame.body; | |
| 123 | + | |
| 124 | + // TODO: JAVA-1306: Use the same API calls for direct and heap buffers when LZ4 updated. | |
| 125 | + ByteBuf frameBody = input.isDirect() ? decompressDirect(input) : decompressHeap(input); | |
| 126 | + return frame.with(frameBody); | |
| 127 | + } | |
| 128 | + | |
| 129 | + private ByteBuf decompressDirect(ByteBuf input) throws IOException { | |
| 130 | + // If the input is direct we will allocate a direct output buffer as well as this will allow us to use | |
| 131 | + // LZ4Compressor.decompress and so eliminate memory copies. | |
| 132 | + int readable = input.readableBytes(); | |
| 133 | + int uncompressedLength = input.readInt(); | |
| 134 | + ByteBuffer in = inputNioBuffer(input); | |
| 135 | + // Increase reader index. | |
| 136 | + input.readerIndex(input.writerIndex()); | |
| 137 | + ByteBuf output = input.alloc().directBuffer(uncompressedLength); | |
| 138 | + try { | |
| 139 | + ByteBuffer out = outputNioBuffer(output); | |
| 140 | + int read = decompressor.decompress(in, in.position(), out, out.position(), out.remaining()); | |
| 141 | + if (read != readable - INTEGER_BYTES) | |
| 142 | + throw new IOException("Compressed lengths mismatch"); | |
| 143 | + | |
| 144 | + // Set the writer index so the amount of written bytes is reflected | |
| 145 | + output.writerIndex(output.writerIndex() + uncompressedLength); | |
| 146 | + } catch (Exception e) { | |
| 147 | + // release output buffer so we not leak and rethrow exception. | |
| 148 | + output.release(); | |
| 149 | + throw new IOException(e); | |
| 150 | + } | |
| 151 | + return output; | |
| 152 | + } | |
| 153 | + | |
| 154 | + private ByteBuf decompressHeap(ByteBuf input) throws IOException { | |
| 155 | + // Not a direct buffer so use byte arrays... | |
| 156 | + byte[] in = input.array(); | |
| 157 | + int len = input.readableBytes(); | |
| 158 | + int uncompressedLength = input.readInt(); | |
| 159 | + int inOffset = input.arrayOffset() + input.readerIndex(); | |
| 160 | + // Increase reader index. | |
| 161 | + input.readerIndex(input.writerIndex()); | |
| 162 | + | |
| 163 | + // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so | |
| 164 | + // can eliminate the overhead of allocate a new byte[]. | |
| 165 | + ByteBuf output = input.alloc().heapBuffer(uncompressedLength); | |
| 166 | + try { | |
| 167 | + int offset = output.arrayOffset() + output.writerIndex(); | |
| 168 | + byte out[] = output.array(); | |
| 169 | + int read = decompressor.decompress(in, inOffset, out, offset, uncompressedLength); | |
| 170 | + if (read != len - INTEGER_BYTES) | |
| 171 | + throw new IOException("Compressed lengths mismatch"); | |
| 172 | + | |
| 173 | + // Set the writer index so the amount of written bytes is reflected | |
| 174 | + output.writerIndex(output.writerIndex() + uncompressedLength); | |
| 175 | + } catch (Exception e) { | |
| 176 | + // release output buffer so we not leak and rethrow exception. | |
| 177 | + output.release(); | |
| 178 | + throw new IOException(e); | |
| 179 | + } | |
| 180 | + return output; | |
| 181 | + } | |
| 182 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/Metadata.java +2 −9
| @@ -135,14 +135,7 @@ | ||
| 135 | 135 | return id.toLowerCase(); |
| 136 | 136 | |
| 137 | 137 | // Check if it's enclosed in quotes. If it is, remove them and unescape internal double quotes |
| 138 | - if (!id.isEmpty() && id.charAt(0) == '"' && id.charAt(id.length() - 1) == '"') | |
| 139 | - return id.substring(1, id.length() - 1).replaceAll("\"\"", "\""); | |
| 140 | - | |
| 141 | - // Otherwise, just return the id. | |
| 142 | - // Note that this is a bit at odds with the rules explained above, because the client can pass an | |
| 143 | - // identifier that contains special characters, without the need to quote it. | |
| 144 | - // Still it's better to be lenient here rather than throwing an exception. | |
| 145 | - return id; | |
| 138 | + return ParseUtils.unDoubleQuote(id); | |
| 146 | 139 | } |
| 147 | 140 | |
| 148 | 141 | // Escape a CQL3 identifier based on its value as read from the schema |
| @@ -217,7 +210,7 @@ | ||
| 217 | 210 | * or even {@link Cluster#connect(String)}. |
| 218 | 211 | */ |
| 219 | 212 | public static String quote(String id) { |
| 220 | - return '"' + id.replace("\"", "\"\"") + '"'; | |
| 213 | + return ParseUtils.doubleQuote(id); | |
| 221 | 214 | } |
| 222 | 215 | |
| 223 | 216 | /** |
modified driver-core/src/main/java/com/datastax/driver/core/Metrics.java +10 −0
| @@ -268,6 +268,7 @@ | ||
| 268 | 268 | public class Errors { |
| 269 | 269 | |
| 270 | 270 | private final Counter connectionErrors = registry.counter("connection-errors"); |
| 271 | + private final Counter authenticationErrors = registry.counter("authentication-errors"); | |
| 271 | 272 | |
| 272 | 273 | private final Counter writeTimeouts = registry.counter("write-timeouts"); |
| 273 | 274 | private final Counter readTimeouts = registry.counter("read-timeouts"); |
| @@ -311,6 +312,15 @@ | ||
| 311 | 312 | return connectionErrors; |
| 312 | 313 | } |
| 313 | 314 | |
| 315 | + /** | |
| 316 | + * Returns the number of authentication errors while connecting to Cassandra nodes. | |
| 317 | + * | |
| 318 | + * @return the number of errors. | |
| 319 | + */ | |
| 320 | + public Counter getAuthenticationErrors() { | |
| 321 | + return authenticationErrors; | |
| 322 | + } | |
| 323 | + | |
| 314 | 324 | /** |
| 315 | 325 | * Returns the number of write requests that returned a timeout (independently |
| 316 | 326 | * of the final decision taken by the {@link com.datastax.driver.core.policies.RetryPolicy}). |
modified driver-core/src/main/java/com/datastax/driver/core/NettyOptions.java +8 −2
| @@ -89,7 +89,10 @@ | ||
| 89 | 89 | * |
| 90 | 90 | * @param threadFactory The {@link ThreadFactory} to use when creating a new {@code EventLoopGroup} instance; |
| 91 | 91 | * The driver will provide its own internal thread factory here. |
| 92 | - * It is safe to ignore it and use another thread factory. | |
| 92 | + * It is safe to ignore it and use another thread factory. Note however that for optimal | |
| 93 | + * performance it is recommended to use a factory that returns | |
| 94 | + * {@link io.netty.util.concurrent.FastThreadLocalThread} instances (such as Netty's | |
| 95 | + * {@link java.util.concurrent.Executors.DefaultThreadFactory}). | |
| 93 | 96 | * @return the {@code EventLoopGroup} instance to use. |
| 94 | 97 | */ |
| 95 | 98 | public EventLoopGroup eventLoopGroup(ThreadFactory threadFactory) { |
| @@ -205,7 +208,10 @@ | ||
| 205 | 208 | * |
| 206 | 209 | * @param threadFactory The {@link ThreadFactory} to use when creating a new {@link HashedWheelTimer} instance; |
| 207 | 210 | * The driver will provide its own internal thread factory here. |
| 208 | - * It is safe to ignore it and use another thread factory. | |
| 211 | + * It is safe to ignore it and use another thread factory. Note however that for optimal | |
| 212 | + * performance it is recommended to use a factory that returns | |
| 213 | + * {@link io.netty.util.concurrent.FastThreadLocalThread} instances (such as Netty's | |
| 214 | + * {@link java.util.concurrent.Executors.DefaultThreadFactory}). | |
| 209 | 215 | * @return the {@link Timer} instance to use. |
| 210 | 216 | */ |
| 211 | 217 | public Timer timer(ThreadFactory threadFactory) { |
modified driver-core/src/main/java/com/datastax/driver/core/ParseUtils.java +141 −25
| @@ -232,7 +232,7 @@ | ||
| 232 | 232 | * by single quotes, and {@code false} otherwise. |
| 233 | 233 | */ |
| 234 | 234 | public static boolean isQuoted(String value) { |
| 235 | - return value != null && value.length() > 1 && value.charAt(0) == '\'' && value.charAt(value.length() - 1) == '\''; | |
| 235 | + return isQuoted(value, '\''); | |
| 236 | 236 | } |
| 237 | 237 | |
| 238 | 238 | /** |
| @@ -243,7 +243,7 @@ | ||
| 243 | 243 | * @return The quoted string. |
| 244 | 244 | */ |
| 245 | 245 | public static String quote(String value) { |
| 246 | - return '\'' + replaceChar(value, '\'', "''") + '\''; | |
| 246 | + return quote(value, '\''); | |
| 247 | 247 | } |
| 248 | 248 | |
| 249 | 249 | /** |
| @@ -254,9 +254,41 @@ | ||
| 254 | 254 | * @return The unquoted string. |
| 255 | 255 | */ |
| 256 | 256 | public static String unquote(String value) { |
| 257 | - if (!isQuoted(value)) | |
| 258 | - return value; | |
| 259 | - return value.substring(1, value.length() - 1).replace("''", "'"); | |
| 257 | + return unquote(value, '\''); | |
| 258 | + } | |
| 259 | + | |
| 260 | + /** | |
| 261 | + * Return {@code true} if the given string is surrounded | |
| 262 | + * by double quotes, and {@code false} otherwise. | |
| 263 | + * | |
| 264 | + * @param value The string to inspect. | |
| 265 | + * @return {@code true} if the given string is surrounded | |
| 266 | + * by double quotes, and {@code false} otherwise. | |
| 267 | + */ | |
| 268 | + public static boolean isDoubleQuoted(String value) { | |
| 269 | + return isQuoted(value, '\"'); | |
| 270 | + } | |
| 271 | + | |
| 272 | + /** | |
| 273 | + * Double quote the given string; double quotes are escaped. | |
| 274 | + * If the given string is null, this method returns a quoted empty string ({@code ""}). | |
| 275 | + * | |
| 276 | + * @param value The value to double quote. | |
| 277 | + * @return The double quoted string. | |
| 278 | + */ | |
| 279 | + public static String doubleQuote(String value) { | |
| 280 | + return quote(value, '"'); | |
| 281 | + } | |
| 282 | + | |
| 283 | + /** | |
| 284 | + * Unquote the given string if it is double quoted; double quotes are unescaped. | |
| 285 | + * If the given string is not double quoted, it is returned without any modification. | |
| 286 | + * | |
| 287 | + * @param value The string to un-double quote. | |
| 288 | + * @return The un-double quoted string. | |
| 289 | + */ | |
| 290 | + public static String unDoubleQuote(String value) { | |
| 291 | + return unquote(value, '"'); | |
| 260 | 292 | } |
| 261 | 293 | |
| 262 | 294 | /** |
| @@ -428,45 +460,129 @@ | ||
| 428 | 460 | } |
| 429 | 461 | |
| 430 | 462 | /** |
| 431 | - * Simple method to replace a single character. | |
| 432 | - * {@code String.replace()} is a bit too inefficient (see JAVA-67). | |
| 433 | - * This methods is specially useful for escaping single quotes | |
| 434 | - * in CQL strings: | |
| 435 | - * <p/> | |
| 436 | - * <pre>{@code | |
| 437 | - * ParseUtils.replaceChar(value, '\'', "''"); | |
| 438 | - * }</pre> | |
| 463 | + * Return {@code true} if the given string is surrounded | |
| 464 | + * by the quote character given, and {@code false} otherwise. | |
| 465 | + * | |
| 466 | + * @param value The string to inspect. | |
| 467 | + * @return {@code true} if the given string is surrounded | |
| 468 | + * by the quote character, and {@code false} otherwise. | |
| 469 | + */ | |
| 470 | + private static boolean isQuoted(String value, char quoteChar) { | |
| 471 | + return value != null && value.length() > 1 | |
| 472 | + && value.charAt(0) == quoteChar && value.charAt(value.length() - 1) == quoteChar; | |
| 473 | + } | |
| 474 | + | |
| 475 | + /** | |
| 476 | + * @param quoteChar " or ' | |
| 477 | + * @return A quoted empty string. | |
| 478 | + */ | |
| 479 | + private static String emptyQuoted(char quoteChar) { | |
| 480 | + // don't handle non quote characters, this is done so that these are interned and don't create | |
| 481 | + // repeated empty quoted strings. | |
| 482 | + assert quoteChar == '"' || quoteChar == '\''; | |
| 483 | + if (quoteChar == '"') | |
| 484 | + return "\"\""; | |
| 485 | + else | |
| 486 | + return "''"; | |
| 487 | + } | |
| 488 | + | |
| 489 | + | |
| 490 | + /** | |
| 491 | + * Quotes text and escapes any existing quotes in the text. | |
| 492 | + * {@code String.replace()} is a bit too inefficient (see JAVA-67, JAVA-1262). | |
| 439 | 493 | * |
| 440 | - * @param text The text. | |
| 441 | - * @param search The character to search for. | |
| 442 | - * @param replacement The replacement. | |
| 443 | - * @return The text with all occurrences of {@code search} replaced with {@code replacement}. | |
| 494 | + * @param text The text. | |
| 495 | + * @param quoteChar The character to use as a quote. | |
| 496 | + * @return The text with surrounded in quotes with all existing quotes escaped with (i.e. ' becomes '') | |
| 444 | 497 | */ |
| 445 | - private static String replaceChar(String text, char search, String replacement) { | |
| 498 | + private static String quote(String text, char quoteChar) { | |
| 446 | 499 | if (text == null || text.isEmpty()) |
| 447 | - return ""; | |
| 500 | + return emptyQuoted(quoteChar); | |
| 448 | 501 | |
| 449 | 502 | int nbMatch = 0; |
| 450 | 503 | int start = -1; |
| 451 | 504 | do { |
| 452 | - start = text.indexOf(search, start + 1); | |
| 505 | + start = text.indexOf(quoteChar, start + 1); | |
| 453 | 506 | if (start != -1) |
| 454 | 507 | ++nbMatch; |
| 455 | 508 | } while (start != -1); |
| 456 | 509 | |
| 510 | + // no quotes found that need to be escaped, simply surround in quotes and return. | |
| 457 | 511 | if (nbMatch == 0) |
| 512 | + return quoteChar + text + quoteChar; | |
| 513 | + | |
| 514 | + // 2 for beginning and end quotes. | |
| 515 | + // length for original text | |
| 516 | + // nbMatch for escape characters to add to quotes to be escaped. | |
| 517 | + int newLength = 2 + text.length() + nbMatch; | |
| 518 | + char[] result = new char[newLength]; | |
| 519 | + result[0] = quoteChar; | |
| 520 | + result[newLength - 1] = quoteChar; | |
| 521 | + int newIdx = 1; | |
| 522 | + for (int i = 0; i < text.length(); i++) { | |
| 523 | + char c = text.charAt(i); | |
| 524 | + if (c == quoteChar) { | |
| 525 | + // escape quote with another occurrence. | |
| 526 | + result[newIdx++] = c; | |
| 527 | + result[newIdx++] = c; | |
| 528 | + } else { | |
| 529 | + result[newIdx++] = c; | |
| 530 | + } | |
| 531 | + } | |
| 532 | + return new String(result); | |
| 533 | + } | |
| 534 | + | |
| 535 | + /** | |
| 536 | + * Unquotes text and unescapes non surrounding quotes. | |
| 537 | + * {@code String.replace()} is a bit too inefficient (see JAVA-67, JAVA-1262). | |
| 538 | + * | |
| 539 | + * @param text The text | |
| 540 | + * @param quoteChar The character to use as a quote. | |
| 541 | + * @return The text with surrounding quotes removed and non surrounding quotes unescaped (i.e. '' becomes ') | |
| 542 | + */ | |
| 543 | + private static String unquote(String text, char quoteChar) { | |
| 544 | + if (!isQuoted(text, quoteChar)) | |
| 458 | 545 | return text; |
| 459 | 546 | |
| 460 | - int newLength = text.length() + nbMatch * (replacement.length() - 1); | |
| 547 | + if (text.length() == 2) | |
| 548 | + return ""; | |
| 549 | + | |
| 550 | + String search = emptyQuoted(quoteChar); | |
| 551 | + int nbMatch = 0; | |
| 552 | + int start = -1; | |
| 553 | + do { | |
| 554 | + start = text.indexOf(search, start + 2); | |
| 555 | + // ignore the second to last character occurrence, as the last character is a quote. | |
| 556 | + if (start != -1 && start != text.length() - 2) | |
| 557 | + ++nbMatch; | |
| 558 | + } while (start != -1); | |
| 559 | + | |
| 560 | + // no escaped quotes found, simply remove surrounding quotes and return. | |
| 561 | + if (nbMatch == 0) | |
| 562 | + return text.substring(1, text.length() - 1); | |
| 563 | + | |
| 564 | + // length of the new string will be its current length - the number of occurrences. | |
| 565 | + int newLength = text.length() - nbMatch - 2; | |
| 461 | 566 | char[] result = new char[newLength]; |
| 462 | 567 | int newIdx = 0; |
| 463 | - for (int i = 0; i < text.length(); i++) { | |
| 568 | + // track whenever a quoteChar is encountered and the previous character is not a quoteChar. | |
| 569 | + boolean firstFound = false; | |
| 570 | + for (int i = 1; i < text.length() - 1; i++) { | |
| 464 | 571 | char c = text.charAt(i); |
| 465 | - if (c == search) { | |
| 466 | - for (int r = 0; r < replacement.length(); r++) | |
| 467 | - result[newIdx++] = replacement.charAt(r); | |
| 572 | + if (c == quoteChar) { | |
| 573 | + if (firstFound) { | |
| 574 | + // The previous character was a quoteChar, don't add this to result, this action in | |
| 575 | + // effect removes consecutive quotes. | |
| 576 | + firstFound = false; | |
| 577 | + } else { | |
| 578 | + // found a quoteChar and the previous character was not a quoteChar, include in result. | |
| 579 | + firstFound = true; | |
| 580 | + result[newIdx++] = c; | |
| 581 | + } | |
| 468 | 582 | } else { |
| 583 | + // non quoteChar encountered, include in result. | |
| 469 | 584 | result[newIdx++] = c; |
| 585 | + firstFound = false; | |
| 470 | 586 | } |
| 471 | 587 | } |
| 472 | 588 | return new String(result); |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +40 −16
| @@ -128,10 +128,16 @@ | ||
| 128 | 128 | public static final int DEFAULT_IDLE_TIMEOUT_SECONDS = 120; |
| 129 | 129 | |
| 130 | 130 | /** |
| 131 | - * The default value for {@link #getPoolTimeoutMillis()} ({@value}). | |
| 131 | + * @deprecated see {@link #setPoolTimeoutMillis(int)} | |
| 132 | 132 | */ |
| 133 | + @Deprecated | |
| 133 | 134 | public static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; |
| 134 | 135 | |
| 136 | + /** | |
| 137 | + * The default value for {@link #getMaxQueueSize()} ({@value}). | |
| 138 | + */ | |
| 139 | + public static final int DEFAULT_MAX_QUEUE_SIZE = 256; | |
| 140 | + | |
| 135 | 141 | /** |
| 136 | 142 | * The default value for {@link #getHeartbeatIntervalSeconds()} ({@value}). |
| 137 | 143 | */ |
| @@ -151,7 +157,7 @@ | ||
| 151 | 157 | private volatile int maxRequestsPerConnectionRemote = UNSET; |
| 152 | 158 | |
| 153 | 159 | private volatile int idleTimeoutSeconds = DEFAULT_IDLE_TIMEOUT_SECONDS; |
| 154 | - private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS; | |
| 160 | + private volatile int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE; | |
| 155 | 161 | private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS; |
| 156 | 162 | |
| 157 | 163 | private volatile Executor initializationExecutor = DEFAULT_INITIALIZATION_EXECUTOR; |
| @@ -400,30 +406,48 @@ | ||
| 400 | 406 | } |
| 401 | 407 | |
| 402 | 408 | /** |
| 403 | - * Returns the timeout when trying to acquire a connection from a host's pool. | |
| 404 | - * | |
| 405 | - * @return the timeout. | |
| 409 | + * @deprecated see {@link #setPoolTimeoutMillis(int)}. This method always returns 0. | |
| 406 | 410 | */ |
| 411 | + @Deprecated | |
| 407 | 412 | public int getPoolTimeoutMillis() { |
| 408 | - return poolTimeoutMillis; | |
| 413 | + return 0; | |
| 414 | + } | |
| 415 | + | |
| 416 | + /** | |
| 417 | + * @deprecated the connection pool does not use a timeout anymore, incoming requests are now throttled with a | |
| 418 | + * threshold on the {@link #setMaxQueueSize(int) queue size}. This method has no effect. | |
| 419 | + */ | |
| 420 | + @Deprecated | |
| 421 | + public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) { | |
| 422 | + return this; | |
| 423 | + } | |
| 424 | + | |
| 425 | + /** | |
| 426 | + * Returns the maximum number of requests that get enqueued if no connection is available. | |
| 427 | + * | |
| 428 | + * @return the maximum queue size. | |
| 429 | + */ | |
| 430 | + public int getMaxQueueSize() { | |
| 431 | + return maxQueueSize; | |
| 409 | 432 | } |
| 410 | 433 | |
| 411 | 434 | /** |
| 412 | - * Sets the timeout when trying to acquire a connection from a host's pool. | |
| 435 | + * Sets the maximum number of requests that get enqueued if no connection is available. | |
| 413 | 436 | * <p/> |
| 414 | - * If no connection is available within that time, the driver will try the | |
| 415 | - * next host from the query plan. | |
| 437 | + * If the queue grows past this value, new requests will be rejected immediately (and the driver will move to the | |
| 438 | + * next host in the query plan). This limit is per connection pool, not global to the driver. | |
| 416 | 439 | * <p/> |
| 417 | - * The default is 5 seconds. If this option is set to zero, the driver won't wait at all. | |
| 440 | + * The default value is {@value DEFAULT_MAX_QUEUE_SIZE}. If this option is set to zero, the driver will never | |
| 441 | + * enqueue requests. | |
| 418 | 442 | * |
| 419 | - * @param poolTimeoutMillis the new value in milliseconds. | |
| 443 | + * @param maxQueueSize the new value. | |
| 420 | 444 | * @return this {@code PoolingOptions} |
| 421 | - * @throws IllegalArgumentException if the timeout is negative. | |
| 445 | + * @throws IllegalArgumentException if the value is negative. | |
| 422 | 446 | */ |
| 423 | - public PoolingOptions setPoolTimeoutMillis(int poolTimeoutMillis) { | |
| 424 | - if (poolTimeoutMillis < 0) | |
| 425 | - throw new IllegalArgumentException("Pool timeout must be positive"); | |
| 426 | - this.poolTimeoutMillis = poolTimeoutMillis; | |
| 447 | + public PoolingOptions setMaxQueueSize(int maxQueueSize) { | |
| 448 | + if (maxQueueSize < 0) | |
| 449 | + throw new IllegalArgumentException("Max queue size must be positive"); | |
| 450 | + this.maxQueueSize = maxQueueSize; | |
| 427 | 451 | return this; |
| 428 | 452 | } |
| 429 | 453 |
modified driver-core/src/main/java/com/datastax/driver/core/ProtocolOptions.java +2 −2
| @@ -41,7 +41,7 @@ | ||
| 41 | 41 | SNAPPY("snappy") { |
| 42 | 42 | @Override |
| 43 | 43 | FrameCompressor compressor() { |
| 44 | - return FrameCompressor.SnappyCompressor.instance; | |
| 44 | + return SnappyCompressor.instance; | |
| 45 | 45 | } |
| 46 | 46 | }, |
| 47 | 47 | /** |
| @@ -50,7 +50,7 @@ | ||
| 50 | 50 | LZ4("lz4") { |
| 51 | 51 | @Override |
| 52 | 52 | FrameCompressor compressor() { |
| 53 | - return FrameCompressor.LZ4Compressor.instance; | |
| 53 | + return LZ4Compressor.instance; | |
| 54 | 54 | } |
| 55 | 55 | }; |
| 56 | 56 |
modified driver-core/src/main/java/com/datastax/driver/core/ReplicationStategy.java +2 −0
| @@ -29,6 +29,7 @@ | ||
| 29 | 29 | * Note: it's not an interface mainly because we don't want to expose it. |
| 30 | 30 | */ |
| 31 | 31 | abstract class ReplicationStrategy { |
| 32 | + private static final Logger logger = LoggerFactory.getLogger(ReplicationStrategy.class); | |
| 32 | 33 | |
| 33 | 34 | static ReplicationStrategy create(Map<String, String> replicationOptions) { |
| 34 | 35 | |
| @@ -55,6 +56,7 @@ | ||
| 55 | 56 | } |
| 56 | 57 | } catch (NumberFormatException e) { |
| 57 | 58 | // Cassandra wouldn't let that pass in the first place so this really should never happen |
| 59 | + logger.error("Failed to parse replication options: " + replicationOptions, e); | |
| 58 | 60 | return null; |
| 59 | 61 | } |
| 60 | 62 | } |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +61 −57
| @@ -21,6 +21,9 @@ | ||
| 21 | 21 | import com.datastax.driver.core.policies.RetryPolicy.RetryDecision.Type; |
| 22 | 22 | import com.datastax.driver.core.policies.SpeculativeExecutionPolicy.SpeculativeExecutionPlan; |
| 23 | 23 | import com.google.common.collect.Sets; |
| 24 | +import com.google.common.util.concurrent.FutureCallback; | |
| 25 | +import com.google.common.util.concurrent.Futures; | |
| 26 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 24 | 27 | import io.netty.util.Timeout; |
| 25 | 28 | import io.netty.util.TimerTask; |
| 26 | 29 | import org.slf4j.Logger; |
| @@ -109,7 +112,7 @@ | ||
| 109 | 112 | |
| 110 | 113 | SpeculativeExecution execution = new SpeculativeExecution(request, position); |
| 111 | 114 | runningExecutions.add(execution); |
| 112 | - execution.sendRequest(); | |
| 115 | + execution.findNextHostAndQuery(); | |
| 113 | 116 | } |
| 114 | 117 | |
| 115 | 118 | private void scheduleExecution(long delayMillis) { |
| @@ -262,12 +265,10 @@ | ||
| 262 | 265 | logger.trace("[{}] Starting", id); |
| 263 | 266 | } |
| 264 | 267 | |
| 265 | - void sendRequest() { | |
| 268 | + void findNextHostAndQuery() { | |
| 266 | 269 | try { |
| 267 | 270 | Host host; |
| 268 | 271 | while (!isDone.get() && (host = queryPlan.next()) != null && !queryStateRef.get().isCancelled()) { |
| 269 | - if (logger.isTraceEnabled()) | |
| 270 | - logger.trace("[{}] Querying node {}", id, host); | |
| 271 | 272 | if (query(host)) |
| 272 | 273 | return; |
| 273 | 274 | } |
| @@ -279,48 +280,63 @@ | ||
| 279 | 280 | } |
| 280 | 281 | |
| 281 | 282 | private boolean query(final Host host) { |
| 282 | - HostConnectionPool currentPool = manager.pools.get(host); | |
| 283 | - if (currentPool == null || currentPool.isClosed()) | |
| 283 | + HostConnectionPool pool = manager.pools.get(host); | |
| 284 | + if (pool == null || pool.isClosed()) | |
| 284 | 285 | return false; |
| 285 | 286 | |
| 287 | + if (logger.isTraceEnabled()) | |
| 288 | + logger.trace("[{}] Querying node {}", id, host); | |
| 289 | + | |
| 286 | 290 | if (allowSpeculativeExecutions && nextExecutionScheduled.compareAndSet(false, true)) |
| 287 | 291 | scheduleExecution(speculativeExecutionPlan.nextExecution(host)); |
| 288 | 292 | |
| 289 | - Connection connection = null; | |
| 290 | - try { | |
| 291 | - connection = currentPool.borrowConnection(manager.configuration().getPoolingOptions().getPoolTimeoutMillis(), TimeUnit.MILLISECONDS); | |
| 292 | - if (current != null) { | |
| 293 | - if (triedHosts == null) | |
| 294 | - triedHosts = new CopyOnWriteArrayList<Host>(); | |
| 295 | - triedHosts.add(current); | |
| 293 | + ListenableFuture<Connection> connectionFuture = pool.borrowConnection( | |
| 294 | + manager.configuration().getPoolingOptions().getMaxQueueSize()); | |
| 295 | + Futures.addCallback(connectionFuture, new FutureCallback<Connection>() { | |
| 296 | + @Override | |
| 297 | + public void onSuccess(Connection connection) { | |
| 298 | + if (current != null) { | |
| 299 | + if (triedHosts == null) | |
| 300 | + triedHosts = new CopyOnWriteArrayList<Host>(); | |
| 301 | + triedHosts.add(current); | |
| 302 | + } | |
| 303 | + current = host; | |
| 304 | + try { | |
| 305 | + write(connection, SpeculativeExecution.this); | |
| 306 | + } catch (ConnectionException e) { | |
| 307 | + // If we have any problem with the connection, move to the next node. | |
| 308 | + if (metricsEnabled()) | |
| 309 | + metrics().getErrorMetrics().getConnectionErrors().inc(); | |
| 310 | + if (connection != null) | |
| 311 | + connection.release(); | |
| 312 | + logError(host.getSocketAddress(), e); | |
| 313 | + findNextHostAndQuery(); | |
| 314 | + } catch (BusyConnectionException e) { | |
| 315 | + // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host. | |
| 316 | + connection.release(); | |
| 317 | + logError(host.getSocketAddress(), e); | |
| 318 | + findNextHostAndQuery(); | |
| 319 | + } catch (RuntimeException e) { | |
| 320 | + if (connection != null) | |
| 321 | + connection.release(); | |
| 322 | + logger.error("Unexpected error while querying " + host.getAddress(), e); | |
| 323 | + logError(host.getSocketAddress(), e); | |
| 324 | + findNextHostAndQuery(); | |
| 325 | + } | |
| 296 | 326 | } |
| 297 | - current = host; | |
| 298 | - write(connection, this); | |
| 299 | - return true; | |
| 300 | - } catch (ConnectionException e) { | |
| 301 | - // If we have any problem with the connection, move to the next node. | |
| 302 | - if (metricsEnabled()) | |
| 303 | - metrics().getErrorMetrics().getConnectionErrors().inc(); | |
| 304 | - if (connection != null) | |
| 305 | - connection.release(); | |
| 306 | - logError(host.getSocketAddress(), e); | |
| 307 | - return false; | |
| 308 | - } catch (BusyConnectionException e) { | |
| 309 | - // The pool shouldn't have give us a busy connection unless we've maxed up the pool, so move on to the next host. | |
| 310 | - connection.release(); | |
| 311 | - logError(host.getSocketAddress(), e); | |
| 312 | - return false; | |
| 313 | - } catch (TimeoutException e) { | |
| 314 | - // We timeout, log it but move to the next node. | |
| 315 | - 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)); | |
| 316 | - return false; | |
| 317 | - } catch (RuntimeException e) { | |
| 318 | - if (connection != null) | |
| 319 | - connection.release(); | |
| 320 | - logger.error("Unexpected error while querying " + host.getAddress(), e); | |
| 321 | - logError(host.getSocketAddress(), e); | |
| 322 | - return false; | |
| 323 | - } | |
| 327 | + | |
| 328 | + @Override | |
| 329 | + public void onFailure(Throwable t) { | |
| 330 | + if (t instanceof BusyPoolException) { | |
| 331 | + logError(host.getSocketAddress(), t); | |
| 332 | + } else { | |
| 333 | + logger.error("Unexpected error while querying " + host.getAddress(), t); | |
| 334 | + logError(host.getSocketAddress(), t); | |
| 335 | + } | |
| 336 | + findNextHostAndQuery(); | |
| 337 | + } | |
| 338 | + }); | |
| 339 | + return true; | |
| 324 | 340 | } |
| 325 | 341 | |
| 326 | 342 | private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException { |
| @@ -415,23 +431,11 @@ | ||
| 415 | 431 | if (newConsistencyLevel != null) |
| 416 | 432 | this.retryConsistencyLevel = newConsistencyLevel; |
| 417 | 433 | |
| 418 | - // We should not retry on the current thread as this will be an IO thread. | |
| 419 | - manager.executor().execute(new Runnable() { | |
| 420 | - @Override | |
| 421 | - public void run() { | |
| 422 | - if (queryStateRef.get().isCancelled()) | |
| 423 | - return; | |
| 424 | - try { | |
| 425 | - if (retryCurrent) { | |
| 426 | - if (query(h)) | |
| 427 | - return; | |
| 428 | - } | |
| 429 | - sendRequest(); | |
| 430 | - } catch (Exception e) { | |
| 431 | - setFinalException(null, new DriverInternalError("Unexpected exception while retrying query", e)); | |
| 432 | - } | |
| 433 | - } | |
| 434 | - }); | |
| 434 | + if (queryStateRef.get().isCancelled()) | |
| 435 | + return; | |
| 436 | + | |
| 437 | + if (!retryCurrent || !query(h)) | |
| 438 | + findNextHostAndQuery(); | |
| 435 | 439 | } |
| 436 | 440 | |
| 437 | 441 | private void logError(InetSocketAddress address, Throwable exception) { |
modified driver-core/src/main/java/com/datastax/driver/core/SchemaChangeListener.java +1 −1
| @@ -24,7 +24,7 @@ | ||
| 24 | 24 | * Note that the methods defined by this interface will be executed by internal driver threads, and are |
| 25 | 25 | * therefore expected to have short execution times. If you need to perform long computations or blocking |
| 26 | 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. | |
| 27 | + * on a separate thread provided by your application code. | |
| 28 | 28 | */ |
| 29 | 29 | public interface SchemaChangeListener { |
| 30 | 30 |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +25 −37
| @@ -28,7 +28,6 @@ | ||
| 28 | 28 | import com.google.common.collect.ImmutableList; |
| 29 | 29 | import com.google.common.collect.Lists; |
| 30 | 30 | import com.google.common.util.concurrent.*; |
| 31 | -import io.netty.util.concurrent.EventExecutor; | |
| 32 | 31 | import org.slf4j.Logger; |
| 33 | 32 | import org.slf4j.LoggerFactory; |
| 34 | 33 | |
| @@ -48,9 +47,6 @@ | ||
| 48 | 47 | |
| 49 | 48 | private static final Logger logger = LoggerFactory.getLogger(Session.class); |
| 50 | 49 | |
| 51 | - private static final boolean CHECK_IO_DEADLOCKS = SystemProperties.getBoolean( | |
| 52 | - "com.datastax.driver.CHECK_IO_DEADLOCKS", true); | |
| 53 | - | |
| 54 | 50 | final Cluster cluster; |
| 55 | 51 | final ConcurrentMap<Host, HostConnectionPool> pools; |
| 56 | 52 | final HostConnectionPool.PoolState poolsState; |
| @@ -564,7 +560,7 @@ | ||
| 564 | 560 | List<ByteBuffer> positionalValues = rawPositionalValues == null ? Collections.<ByteBuffer>emptyList() : Arrays.asList(rawPositionalValues); |
| 565 | 561 | Map<String, ByteBuffer> namedValues = rawNamedValues == null ? Collections.<String, ByteBuffer>emptyMap() : rawNamedValues; |
| 566 | 562 | |
| 567 | - String qString = rs.getQueryString(); | |
| 563 | + String qString = rs.getQueryString(codecRegistry); | |
| 568 | 564 | |
| 569 | 565 | Requests.QueryProtocolOptions options = new Requests.QueryProtocolOptions(Message.Request.Type.QUERY, consistency, positionalValues, namedValues, |
| 570 | 566 | false, fetchSize, usedPagingState, serialConsistency, defaultTimestamp); |
| @@ -627,22 +623,30 @@ | ||
| 627 | 623 | |
| 628 | 624 | try { |
| 629 | 625 | // Preparing is not critical: if it fails, it will fix itself later when the user tries to execute |
| 630 | - // the prepared query. So don't block if no connection is available, simply abort. | |
| 631 | - final Connection c = entry.getValue().borrowConnection(0, TimeUnit.MILLISECONDS); | |
| 632 | - ListenableFuture<Response> future = c.write(new Requests.Prepare(query)); | |
| 633 | - Futures.addCallback(future, new FutureCallback<Response>() { | |
| 634 | - @Override | |
| 635 | - public void onSuccess(Response result) { | |
| 636 | - c.release(); | |
| 637 | - } | |
| 638 | - | |
| 639 | - @Override | |
| 640 | - public void onFailure(Throwable t) { | |
| 641 | - logger.debug(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), t); | |
| 642 | - c.release(); | |
| 643 | - } | |
| 644 | - }); | |
| 645 | - futures.add(future); | |
| 626 | + // the prepared query. So don't wait if no connection is available, simply abort. | |
| 627 | + ListenableFuture<Connection> connectionFuture = entry.getValue().borrowConnection(0); | |
| 628 | + ListenableFuture<Response> prepareFuture = Futures.transform(connectionFuture, | |
| 629 | + new AsyncFunction<Connection, Response>() { | |
| 630 | + @Override | |
| 631 | + public ListenableFuture<Response> apply(final Connection c) throws Exception { | |
| 632 | + Connection.Future responseFuture = c.write(new Requests.Prepare(query)); | |
| 633 | + Futures.addCallback(responseFuture, new FutureCallback<Response>() { | |
| 634 | + @Override | |
| 635 | + public void onSuccess(Response result) { | |
| 636 | + c.release(); | |
| 637 | + } | |
| 638 | + | |
| 639 | + @Override | |
| 640 | + public void onFailure(Throwable t) { | |
| 641 | + logger.debug(String.format("Unexpected error while preparing query (%s) on %s", | |
| 642 | + query, entry.getKey()), t); | |
| 643 | + c.release(); | |
| 644 | + } | |
| 645 | + }); | |
| 646 | + return responseFuture; | |
| 647 | + } | |
| 648 | + }); | |
| 649 | + futures.add(prepareFuture); | |
| 646 | 650 | } catch (Exception e) { |
| 647 | 651 | // Again, not being able to prepare the query right now is no big deal, so just ignore |
| 648 | 652 | } |
| @@ -665,22 +669,6 @@ | ||
| 665 | 669 | } |
| 666 | 670 | } |
| 667 | 671 | |
| 668 | - @Override | |
| 669 | - protected void checkNotInEventLoop() { | |
| 670 | - Connection.Factory connectionFactory = cluster.manager.connectionFactory; | |
| 671 | - if (!CHECK_IO_DEADLOCKS || connectionFactory == null) | |
| 672 | - return; | |
| 673 | - for (EventExecutor executor : connectionFactory.eventLoopGroup) { | |
| 674 | - if (executor.inEventLoop()) { | |
| 675 | - throw new IllegalStateException( | |
| 676 | - "Detected a synchronous Session call (execute() or prepare()) on an I/O thread, " + | |
| 677 | - "this can cause deadlocks or unpredictable behavior. " + | |
| 678 | - "Make sure your Future callbacks only use async calls, or schedule them on a " + | |
| 679 | - "different executor."); | |
| 680 | - } | |
| 681 | - } | |
| 682 | - } | |
| 683 | - | |
| 684 | 672 | private static class State implements Session.State { |
| 685 | 673 | |
| 686 | 674 | private final SessionManager session; |
added driver-core/src/main/java/com/datastax/driver/core/SnappyCompressor.java +170 −0
| @@ -0,0 +1,170 @@ | ||
| 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.datastax.driver.core.exceptions.DriverInternalError; | |
| 19 | +import io.netty.buffer.ByteBuf; | |
| 20 | +import org.slf4j.Logger; | |
| 21 | +import org.slf4j.LoggerFactory; | |
| 22 | +import org.xerial.snappy.Snappy; | |
| 23 | + | |
| 24 | +import java.io.IOException; | |
| 25 | +import java.nio.ByteBuffer; | |
| 26 | + | |
| 27 | +class SnappyCompressor extends FrameCompressor { | |
| 28 | + | |
| 29 | + private static final Logger logger = LoggerFactory.getLogger(SnappyCompressor.class); | |
| 30 | + | |
| 31 | + static final SnappyCompressor instance; | |
| 32 | + | |
| 33 | + static { | |
| 34 | + SnappyCompressor i; | |
| 35 | + try { | |
| 36 | + i = new SnappyCompressor(); | |
| 37 | + } catch (NoClassDefFoundError e) { | |
| 38 | + i = null; | |
| 39 | + logger.warn("Cannot find Snappy class, you should make sure the Snappy library is in the classpath if you intend to use it. Snappy compression will not be available for the protocol."); | |
| 40 | + } catch (Throwable e) { | |
| 41 | + i = null; | |
| 42 | + logger.warn("Error loading Snappy library ({}). Snappy compression will not be available for the protocol.", e.toString()); | |
| 43 | + } | |
| 44 | + instance = i; | |
| 45 | + } | |
| 46 | + | |
| 47 | + private SnappyCompressor() { | |
| 48 | + // this would throw java.lang.NoClassDefFoundError if Snappy class | |
| 49 | + // wasn't found at runtime which should be processed by the calling method | |
| 50 | + Snappy.getNativeLibraryVersion(); | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Override | |
| 54 | + Frame compress(Frame frame) throws IOException { | |
| 55 | + ByteBuf input = frame.body; | |
| 56 | + ByteBuf frameBody = input.isDirect() ? compressDirect(input) : compressHeap(input); | |
| 57 | + return frame.with(frameBody); | |
| 58 | + } | |
| 59 | + | |
| 60 | + private ByteBuf compressDirect(ByteBuf input) throws IOException { | |
| 61 | + int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes()); | |
| 62 | + // If the input is direct we will allocate a direct output buffer as well as this will allow us to use | |
| 63 | + // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies. | |
| 64 | + ByteBuf output = input.alloc().directBuffer(maxCompressedLength); | |
| 65 | + try { | |
| 66 | + ByteBuffer in = inputNioBuffer(input); | |
| 67 | + // Increase reader index. | |
| 68 | + input.readerIndex(input.writerIndex()); | |
| 69 | + | |
| 70 | + ByteBuffer out = outputNioBuffer(output); | |
| 71 | + int written = Snappy.compress(in, out); | |
| 72 | + // Set the writer index so the amount of written bytes is reflected | |
| 73 | + output.writerIndex(output.writerIndex() + written); | |
| 74 | + } catch (IOException e) { | |
| 75 | + // release output buffer so we not leak and rethrow exception. | |
| 76 | + output.release(); | |
| 77 | + throw e; | |
| 78 | + } | |
| 79 | + return output; | |
| 80 | + } | |
| 81 | + | |
| 82 | + private ByteBuf compressHeap(ByteBuf input) throws IOException { | |
| 83 | + int maxCompressedLength = Snappy.maxCompressedLength(input.readableBytes()); | |
| 84 | + int inOffset = input.arrayOffset() + input.readerIndex(); | |
| 85 | + byte[] in = input.array(); | |
| 86 | + int len = input.readableBytes(); | |
| 87 | + // Increase reader index. | |
| 88 | + input.readerIndex(input.writerIndex()); | |
| 89 | + | |
| 90 | + // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so | |
| 91 | + // can eliminate the overhead of allocate a new byte[]. | |
| 92 | + ByteBuf output = input.alloc().heapBuffer(maxCompressedLength); | |
| 93 | + try { | |
| 94 | + // Calculate the correct offset. | |
| 95 | + int offset = output.arrayOffset() + output.writerIndex(); | |
| 96 | + byte[] out = output.array(); | |
| 97 | + int written = Snappy.compress(in, inOffset, len, out, offset); | |
| 98 | + | |
| 99 | + // Increase the writerIndex with the written bytes. | |
| 100 | + output.writerIndex(output.writerIndex() + written); | |
| 101 | + } catch (IOException e) { | |
| 102 | + // release output buffer so we not leak and rethrow exception. | |
| 103 | + output.release(); | |
| 104 | + throw e; | |
| 105 | + } | |
| 106 | + return output; | |
| 107 | + } | |
| 108 | + | |
| 109 | + @Override | |
| 110 | + Frame decompress(Frame frame) throws IOException { | |
| 111 | + ByteBuf input = frame.body; | |
| 112 | + ByteBuf frameBody = input.isDirect() ? decompressDirect(input) : decompressHeap(input); | |
| 113 | + return frame.with(frameBody); | |
| 114 | + } | |
| 115 | + | |
| 116 | + private ByteBuf decompressDirect(ByteBuf input) throws IOException { | |
| 117 | + ByteBuffer in = inputNioBuffer(input); | |
| 118 | + // Increase reader index. | |
| 119 | + input.readerIndex(input.writerIndex()); | |
| 120 | + | |
| 121 | + if (!Snappy.isValidCompressedBuffer(in)) | |
| 122 | + throw new DriverInternalError("Provided frame does not appear to be Snappy compressed"); | |
| 123 | + | |
| 124 | + // If the input is direct we will allocate a direct output buffer as well as this will allow us to use | |
| 125 | + // Snappy.compress(ByteBuffer, ByteBuffer) and so eliminate memory copies. | |
| 126 | + ByteBuf output = input.alloc().directBuffer(Snappy.uncompressedLength(in)); | |
| 127 | + try { | |
| 128 | + ByteBuffer out = outputNioBuffer(output); | |
| 129 | + | |
| 130 | + int size = Snappy.uncompress(in, out); | |
| 131 | + // Set the writer index so the amount of written bytes is reflected | |
| 132 | + output.writerIndex(output.writerIndex() + size); | |
| 133 | + } catch (IOException e) { | |
| 134 | + // release output buffer so we not leak and rethrow exception. | |
| 135 | + output.release(); | |
| 136 | + throw e; | |
| 137 | + } | |
| 138 | + return output; | |
| 139 | + } | |
| 140 | + | |
| 141 | + private ByteBuf decompressHeap(ByteBuf input) throws IOException { | |
| 142 | + // Not a direct buffer so use byte arrays... | |
| 143 | + int inOffset = input.arrayOffset() + input.readerIndex(); | |
| 144 | + byte[] in = input.array(); | |
| 145 | + int len = input.readableBytes(); | |
| 146 | + // Increase reader index. | |
| 147 | + input.readerIndex(input.writerIndex()); | |
| 148 | + | |
| 149 | + if (!Snappy.isValidCompressedBuffer(in, inOffset, len)) | |
| 150 | + throw new DriverInternalError("Provided frame does not appear to be Snappy compressed"); | |
| 151 | + | |
| 152 | + // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so | |
| 153 | + // can eliminate the overhead of allocate a new byte[]. | |
| 154 | + ByteBuf output = input.alloc().heapBuffer(Snappy.uncompressedLength(in, inOffset, len)); | |
| 155 | + try { | |
| 156 | + // Calculate the correct offset. | |
| 157 | + int offset = output.arrayOffset() + output.writerIndex(); | |
| 158 | + byte[] out = output.array(); | |
| 159 | + int written = Snappy.uncompress(in, inOffset, len, out, offset); | |
| 160 | + | |
| 161 | + // Increase the writerIndex with the written bytes. | |
| 162 | + output.writerIndex(output.writerIndex() + written); | |
| 163 | + } catch (IOException e) { | |
| 164 | + // release output buffer so we not leak and rethrow exception. | |
| 165 | + output.release(); | |
| 166 | + throw e; | |
| 167 | + } | |
| 168 | + return output; | |
| 169 | + } | |
| 170 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/Statement.java +28 −3
| @@ -23,6 +23,7 @@ | ||
| 23 | 23 | import com.google.common.collect.ImmutableMap; |
| 24 | 24 | |
| 25 | 25 | import java.nio.ByteBuffer; |
| 26 | +import java.util.Collection; | |
| 26 | 27 | import java.util.Map; |
| 27 | 28 | |
| 28 | 29 | /** |
| @@ -503,11 +504,22 @@ | ||
| 503 | 504 | * {@link QueryOptions#getDefaultIdempotence()}. |
| 504 | 505 | * <p/> |
| 505 | 506 | * By default, this method returns {@code null} for all statements, except for |
| 506 | - * {@link BuiltStatement}s, where the value will be inferred from the query: if it updates | |
| 507 | - * counters, prepends/appends to a list, or uses a function call or | |
| 507 | + * <ul> | |
| 508 | + * <li>{@link BuiltStatement} - value will be inferred from the query: if it updates counters, | |
| 509 | + * prepends/appends to a list, or uses a function call or | |
| 508 | 510 | * {@link com.datastax.driver.core.querybuilder.QueryBuilder#raw(String)} anywhere in an inserted value, |
| 509 | 511 | * the result will be {@code false}; otherwise it will be {@code true}. |
| 510 | - * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides every other mechanism. | |
| 512 | + * </li> | |
| 513 | + * <li> | |
| 514 | + * {@link com.datastax.driver.core.querybuilder.Batch} and {@link BatchStatement}: | |
| 515 | + * <ol> | |
| 516 | + * <li>If any statement in batch has isIdempotent() false - return false</li> | |
| 517 | + * <li>If no statements with isIdempotent() false, but some have isIdempotent() null - return null</li> | |
| 518 | + * <li>Otherwise - return true</li> | |
| 519 | + * </ol> | |
| 520 | + * </li> | |
| 521 | + * </ul> | |
| 522 | + * In all cases, calling {@link #setIdempotent(boolean)} forces a value that overrides calculated value. | |
| 511 | 523 | * <p/> |
| 512 | 524 | * Note that when a statement is prepared ({@link Session#prepare(String)}), its idempotence flag will be propagated |
| 513 | 525 | * to all {@link PreparedStatement}s created from it. |
| @@ -571,4 +583,17 @@ | ||
| 571 | 583 | this.outgoingPayload = payload == null ? null : ImmutableMap.copyOf(payload); |
| 572 | 584 | return this; |
| 573 | 585 | } |
| 586 | + | |
| 587 | + protected static Boolean isBatchIdempotent(Collection<? extends Statement> statements) { | |
| 588 | + boolean hasNullIdempotentStatements = false; | |
| 589 | + for (Statement statement : statements) { | |
| 590 | + Boolean innerIdempotent = statement.isIdempotent(); | |
| 591 | + if (innerIdempotent == null) { | |
| 592 | + hasNullIdempotentStatements = true; | |
| 593 | + } else if (!innerIdempotent) { | |
| 594 | + return false; | |
| 595 | + } | |
| 596 | + } | |
| 597 | + return (hasNullIdempotentStatements) ? null : true; | |
| 598 | + } | |
| 574 | 599 | } |
modified driver-core/src/main/java/com/datastax/driver/core/TypeCodec.java +2 −2
| @@ -533,8 +533,8 @@ | ||
| 533 | 533 | * {@link TupleValue}, and the internal representation of a {@code ROWS} response), |
| 534 | 534 | * which may appear in driver logs.</li> |
| 535 | 535 | * </ol> |
| 536 | - * If choose not to implement this method, you can return a constant string (for example | |
| 537 | - * "XxxCodec.format not implemented"). | |
| 536 | + * If you choose not to implement this method, you should not throw an exception but | |
| 537 | + * instead return a constant string (for example "XxxCodec.format not implemented"). | |
| 538 | 538 | * |
| 539 | 539 | * @param value An instance of T; may be {@code null}. |
| 540 | 540 | * @return CQL string |
added driver-core/src/main/java/com/datastax/driver/core/exceptions/BusyPoolException.java +80 −0
| @@ -0,0 +1,80 @@ | ||
| 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 com.datastax.driver.core.HostDistance; | |
| 19 | +import com.datastax.driver.core.Statement; | |
| 20 | + | |
| 21 | +import java.net.InetAddress; | |
| 22 | +import java.net.InetSocketAddress; | |
| 23 | + | |
| 24 | +/** | |
| 25 | + * Indicates that a connection pool has run out of available connections. | |
| 26 | + * <p/> | |
| 27 | + * This happens if the pool has no connections (for example if it's currently reconnecting to its host), or if all | |
| 28 | + * connections have reached their maximum number of in flight queries. The query will be retried on the next host in the | |
| 29 | + * {@link com.datastax.driver.core.policies.LoadBalancingPolicy#newQueryPlan(String, Statement) query plan}. | |
| 30 | + * <p/> | |
| 31 | + * This exception is a symptom that the driver is experiencing a high workload. If it happens regularly on all hosts, | |
| 32 | + * you should consider tuning one (or a combination of) the following pooling options: | |
| 33 | + * <ul> | |
| 34 | + * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxRequestsPerConnection(HostDistance, int)}: maximum number of | |
| 35 | + * requests per connection;</li> | |
| 36 | + * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxConnectionsPerHost(HostDistance, int)}: maximum number of | |
| 37 | + * connections in the pool;</li> | |
| 38 | + * <li>{@link com.datastax.driver.core.PoolingOptions#setMaxQueueSize(int)}: maximum number of enqueued requests before | |
| 39 | + * this exception is thrown.</li> | |
| 40 | + * </ul> | |
| 41 | + */ | |
| 42 | +public class BusyPoolException extends DriverException implements CoordinatorException { | |
| 43 | + | |
| 44 | + private static final long serialVersionUID = 0; | |
| 45 | + | |
| 46 | + private final InetSocketAddress address; | |
| 47 | + private final int queueSize; | |
| 48 | + | |
| 49 | + public BusyPoolException(InetSocketAddress address, int queueSize) { | |
| 50 | + this(address, queueSize, null); | |
| 51 | + } | |
| 52 | + | |
| 53 | + private BusyPoolException(InetSocketAddress address, int queueSize, Throwable cause) { | |
| 54 | + super(buildMessage(address, queueSize), cause); | |
| 55 | + this.address = address; | |
| 56 | + this.queueSize = queueSize; | |
| 57 | + } | |
| 58 | + | |
| 59 | + private static String buildMessage(InetSocketAddress address, int queueSize) { | |
| 60 | + return String.format("[%s] Pool is busy (no available connection and the queue has reached its max size %d)", | |
| 61 | + address.getAddress(), | |
| 62 | + queueSize); | |
| 63 | + } | |
| 64 | + | |
| 65 | + @Override | |
| 66 | + public InetAddress getHost() { | |
| 67 | + return address.getAddress(); | |
| 68 | + } | |
| 69 | + | |
| 70 | + @Override | |
| 71 | + public InetSocketAddress getAddress() { | |
| 72 | + return address; | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Override | |
| 76 | + public BusyPoolException copy() { | |
| 77 | + return new BusyPoolException(address, queueSize, this); | |
| 78 | + } | |
| 79 | + | |
| 80 | +} |
added driver-core/src/main/java/com/datastax/driver/core/exceptions/FrameTooLongException.java +50 −0
| @@ -0,0 +1,50 @@ | ||
| 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 | +/** | |
| 19 | + * Indicates that the response frame for a request exceeded | |
| 20 | + * {@link com.datastax.driver.core.Frame.Decoder.DecoderForStreamIdSize#MAX_FRAME_LENGTH} | |
| 21 | + * (default: 256MB, configurable via com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB | |
| 22 | + * system property) and thus was not parsed. | |
| 23 | + */ | |
| 24 | +public class FrameTooLongException extends DriverException { | |
| 25 | + | |
| 26 | + private static final long serialVersionUID = 0; | |
| 27 | + | |
| 28 | + private final int streamId; | |
| 29 | + | |
| 30 | + public FrameTooLongException(int streamId) { | |
| 31 | + this(streamId, null); | |
| 32 | + } | |
| 33 | + | |
| 34 | + private FrameTooLongException(int streamId, Throwable cause) { | |
| 35 | + super("Response frame exceeded maximum allowed length", cause); | |
| 36 | + this.streamId = streamId; | |
| 37 | + } | |
| 38 | + | |
| 39 | + /** | |
| 40 | + * @return The stream id associated with the frame that caused this exception. | |
| 41 | + */ | |
| 42 | + public int getStreamId() { | |
| 43 | + return streamId; | |
| 44 | + } | |
| 45 | + | |
| 46 | + @Override | |
| 47 | + public FrameTooLongException copy() { | |
| 48 | + return new FrameTooLongException(streamId, this); | |
| 49 | + } | |
| 50 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Batch.java +10 −5
| @@ -15,10 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core.querybuilder; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.CodecRegistry; | |
| 19 | -import com.datastax.driver.core.ProtocolVersion; | |
| 20 | -import com.datastax.driver.core.RegularStatement; | |
| 21 | -import com.datastax.driver.core.SimpleStatement; | |
| 18 | +import com.datastax.driver.core.*; | |
| 22 | 19 | |
| 23 | 20 | import java.nio.ByteBuffer; |
| 24 | 21 | import java.util.ArrayList; |
| @@ -69,7 +66,7 @@ | ||
| 69 | 66 | builder.append(maybeAddSemicolon(bst.buildQueryString(variables, codecRegistry))); |
| 70 | 67 | |
| 71 | 68 | } else { |
| 72 | - String str = stmt.getQueryString(); | |
| 69 | + String str = stmt.getQueryString(codecRegistry); | |
| 73 | 70 | builder.append(str); |
| 74 | 71 | if (!str.trim().endsWith(";")) |
| 75 | 72 | builder.append(';'); |
| @@ -175,6 +172,14 @@ | ||
| 175 | 172 | return statements.isEmpty() ? null : statements.get(0).getKeyspace(); |
| 176 | 173 | } |
| 177 | 174 | |
| 175 | + @Override | |
| 176 | + public Boolean isIdempotent() { | |
| 177 | + if (idempotent != null) { | |
| 178 | + return idempotent; | |
| 179 | + } | |
| 180 | + return isBatchIdempotent(statements); | |
| 181 | + } | |
| 182 | + | |
| 178 | 183 | /** |
| 179 | 184 | * The options of a BATCH statement. |
| 180 | 185 | */ |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/BuiltStatement.java +11 −10
| @@ -231,7 +231,7 @@ | ||
| 231 | 231 | return; |
| 232 | 232 | |
| 233 | 233 | for (int i = 0; i < partitionKey.size(); i++) { |
| 234 | - if (name.equals(partitionKey.get(i).getName())) { | |
| 234 | + if (Utils.handleId(name).equals(partitionKey.get(i).getName())) { | |
| 235 | 235 | routingKeyValues.set(i, value); |
| 236 | 236 | return; |
| 237 | 237 | } |
| @@ -296,18 +296,19 @@ | ||
| 296 | 296 | @Override |
| 297 | 297 | public String toString() { |
| 298 | 298 | try { |
| 299 | + if (forceNoValues) | |
| 300 | + return getQueryString(); | |
| 301 | + // 1) try first with all values inlined (will not work if some values require custom codecs, | |
| 302 | + // or if the required codecs are registered in a different CodecRegistry instance than the default one) | |
| 303 | + return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString(); | |
| 304 | + } catch (RuntimeException e1) { | |
| 305 | + // 2) try next with bind markers for all values to avoid usage of custom codecs | |
| 299 | 306 | try { |
| 300 | - if (forceNoValues) | |
| 301 | - return getQueryString(); | |
| 302 | - // 1) try first with all values inlined (will not work if some values require custom codecs) | |
| 303 | - return maybeAddSemicolon(buildQueryString(null, CodecRegistry.DEFAULT_INSTANCE)).toString(); | |
| 304 | - } catch (CodecNotFoundException e) { | |
| 305 | - // 2) try next with bind markers for all values to avoid usage of custom codecs | |
| 306 | 307 | return maybeAddSemicolon(buildQueryString(new ArrayList<Object>(), CodecRegistry.DEFAULT_INSTANCE)).toString(); |
| 308 | + } catch (RuntimeException e2) { | |
| 309 | + // Ugly but we have absolutely no context to get the registry from | |
| 310 | + return String.format("built query (could not generate with default codec registry: %s)", e2.getMessage()); | |
| 307 | 311 | } |
| 308 | - } catch (RuntimeException e) { | |
| 309 | - // Ugly but we have absolutely no context to get the registry from | |
| 310 | - return String.format("built query (could not generate with default codec registry: %s)", e.getMessage()); | |
| 311 | 312 | } |
| 312 | 313 | } |
| 313 | 314 |
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Utils.java +32 −0
| @@ -32,8 +32,40 @@ | ||
| 32 | 32 | // Static utilities private to the query builder |
| 33 | 33 | abstract class Utils { |
| 34 | 34 | |
| 35 | + private static final Pattern alphanumeric = Pattern.compile("\\w+"); // this includes _ | |
| 35 | 36 | private static final Pattern cnamePattern = Pattern.compile("\\w+(?:\\[.+\\])?"); |
| 36 | 37 | |
| 38 | + /** | |
| 39 | + * Deal with case sensitivity for a given element id (keyspace, table, column, etc.) | |
| 40 | + * | |
| 41 | + * This method is used to convert identifiers provided by the client (through methods such as getKeyspace(String)), | |
| 42 | + * to the format used internally by the driver. | |
| 43 | + * | |
| 44 | + * We expect client-facing APIs to behave like cqlsh, that is: | |
| 45 | + * - identifiers that are mixed-case or contain special characters should be quoted. | |
| 46 | + * - unquoted identifiers will be lowercased: getKeyspace("Foo") will look for a keyspace named "foo" | |
| 47 | + * | |
| 48 | + * Copied from {@link Metadata#handleId(String)} to avoid making it public. | |
| 49 | + */ | |
| 50 | + static String handleId(String id) { | |
| 51 | + // Shouldn't really happen for this method, but no reason to fail here | |
| 52 | + if (id == null) | |
| 53 | + return null; | |
| 54 | + | |
| 55 | + if (alphanumeric.matcher(id).matches()) | |
| 56 | + return id.toLowerCase(); | |
| 57 | + | |
| 58 | + // Check if it's enclosed in quotes. If it is, remove them and unescape internal double quotes | |
| 59 | + if (!id.isEmpty() && id.charAt(0) == '"' && id.charAt(id.length() - 1) == '"') | |
| 60 | + return id.substring(1, id.length() - 1).replaceAll("\"\"", "\""); | |
| 61 | + | |
| 62 | + // Otherwise, just return the id. | |
| 63 | + // Note that this is a bit at odds with the rules explained above, because the client can pass an | |
| 64 | + // identifier that contains special characters, without the need to quote it. | |
| 65 | + // Still it's better to be lenient here rather than throwing an exception. | |
| 66 | + return id; | |
| 67 | + } | |
| 68 | + | |
| 37 | 69 | static StringBuilder joinAndAppend(StringBuilder sb, CodecRegistry codecRegistry, String separator, List<? extends Appendeable> values, List<Object> variables) { |
| 38 | 70 | for (int i = 0; i < values.size(); i++) { |
| 39 | 71 | if (i > 0) |
added driver-core/src/test/java/com/datastax/driver/core/AbstractBatchIdempotencyTest.java +177 −0
| @@ -0,0 +1,177 @@ | ||
| 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.testng.annotations.Test; | |
| 19 | + | |
| 20 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 21 | + | |
| 22 | +public abstract class AbstractBatchIdempotencyTest { | |
| 23 | + | |
| 24 | + protected abstract TestBatch createBatch(); | |
| 25 | + | |
| 26 | + /** | |
| 27 | + * Unify Batch and BatchStatement to avoid duplicating all tests | |
| 28 | + */ | |
| 29 | + protected interface TestBatch { | |
| 30 | + //Batch only accepts RegularStatement, so we use it for common interface | |
| 31 | + void add(RegularStatement statement); | |
| 32 | + | |
| 33 | + Boolean isIdempotent(); | |
| 34 | + | |
| 35 | + void setIdempotent(boolean idempotent); | |
| 36 | + } | |
| 37 | + | |
| 38 | + @Test(groups = "unit") | |
| 39 | + public void isIdempotent_should_return_true_if_no_statements_added() { | |
| 40 | + TestBatch batch = createBatch(); | |
| 41 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 42 | + } | |
| 43 | + | |
| 44 | + @Test(groups = "unit") | |
| 45 | + public void isIdempotent_should_return_true_if_all_statements_are_idempotent() { | |
| 46 | + TestBatch batch = createBatch(); | |
| 47 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 48 | + | |
| 49 | + batch.add(statementWithIdempotency(true)); | |
| 50 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 51 | + | |
| 52 | + batch.add(statementWithIdempotency(true)); | |
| 53 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 54 | + } | |
| 55 | + | |
| 56 | + @Test(groups = "unit") | |
| 57 | + public void isIdempotent_should_return_false_if_any_statements_is_nonidempotent() { | |
| 58 | + TestBatch batch = createBatch(); | |
| 59 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 60 | + | |
| 61 | + batch.add(statementWithIdempotency(true)); | |
| 62 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 63 | + | |
| 64 | + batch.add(statementWithIdempotency(false)); | |
| 65 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 66 | + | |
| 67 | + batch.add(statementWithIdempotency(true)); | |
| 68 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 69 | + } | |
| 70 | + | |
| 71 | + @Test(groups = "unit") | |
| 72 | + public void isIdempotent_should_return_null_if_no_nonidempotent_statements_and_some_are_nullidempotent() { | |
| 73 | + TestBatch batch = createBatch(); | |
| 74 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 75 | + | |
| 76 | + batch.add(statementWithIdempotency(true)); | |
| 77 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 78 | + | |
| 79 | + batch.add(statementWithIdempotency(null)); | |
| 80 | + assertThat(batch.isIdempotent()).isNull(); | |
| 81 | + | |
| 82 | + batch.add(statementWithIdempotency(true)); | |
| 83 | + assertThat(batch.isIdempotent()).isNull(); | |
| 84 | + } | |
| 85 | + | |
| 86 | + @Test(groups = "unit") | |
| 87 | + public void isIdempotent_should_return_false_if_both_nonidempotent_and_nullidempotent_statements_present() { | |
| 88 | + TestBatch batch = createBatch(); | |
| 89 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 90 | + | |
| 91 | + batch.add(statementWithIdempotency(true)); | |
| 92 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 93 | + | |
| 94 | + batch.add(statementWithIdempotency(null)); | |
| 95 | + assertThat(batch.isIdempotent()).isNull(); | |
| 96 | + | |
| 97 | + batch.add(statementWithIdempotency(false)); | |
| 98 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 99 | + | |
| 100 | + batch.add(statementWithIdempotency(true)); | |
| 101 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 102 | + | |
| 103 | + batch.add(statementWithIdempotency(null)); | |
| 104 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 105 | + | |
| 106 | + batch.add(statementWithIdempotency(false)); | |
| 107 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 108 | + } | |
| 109 | + | |
| 110 | + @Test(groups = "unit") | |
| 111 | + public void isIdempotent_should_return_override_flag_if_no_statements_added() { | |
| 112 | + TestBatch batch = createBatch(); | |
| 113 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 114 | + | |
| 115 | + batch.setIdempotent(false); | |
| 116 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 117 | + } | |
| 118 | + | |
| 119 | + @Test(groups = "unit") | |
| 120 | + public void isIdempotent_should_return_override_flag_if_calculated_idempotency_true() { | |
| 121 | + TestBatch batch = createBatch(); | |
| 122 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 123 | + | |
| 124 | + batch.add(statementWithIdempotency(true)); | |
| 125 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 126 | + | |
| 127 | + batch.setIdempotent(false); | |
| 128 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 129 | + } | |
| 130 | + | |
| 131 | + @Test(groups = "unit") | |
| 132 | + public void isIdempotent_should_return_override_flag_if_calculated_idempotency_null() { | |
| 133 | + TestBatch batch = createBatch(); | |
| 134 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 135 | + | |
| 136 | + batch.add(statementWithIdempotency(null)); | |
| 137 | + assertThat(batch.isIdempotent()).isNull(); | |
| 138 | + | |
| 139 | + batch.setIdempotent(false); | |
| 140 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 141 | + } | |
| 142 | + | |
| 143 | + @Test(groups = "unit") | |
| 144 | + public void isIdempotent_should_return_override_flag_if_calculated_idempotency_false() { | |
| 145 | + TestBatch batch = createBatch(); | |
| 146 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 147 | + | |
| 148 | + batch.add(statementWithIdempotency(false)); | |
| 149 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 150 | + | |
| 151 | + batch.setIdempotent(true); | |
| 152 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 153 | + } | |
| 154 | + | |
| 155 | + @Test(groups = "unit") | |
| 156 | + public void isIdempotent_should_return_override_flag_if_calculated_idempotency_equals_override_value() { | |
| 157 | + TestBatch batch = createBatch(); | |
| 158 | + assertThat(batch.isIdempotent()).isTrue(); | |
| 159 | + | |
| 160 | + batch.add(statementWithIdempotency(false)); | |
| 161 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 162 | + | |
| 163 | + batch.setIdempotent(false); | |
| 164 | + assertThat(batch.isIdempotent()).isFalse(); | |
| 165 | + } | |
| 166 | + | |
| 167 | + private RegularStatement statementWithIdempotency(Boolean idempotency) { | |
| 168 | + RegularStatement statement = new SimpleStatement("fake statement"); | |
| 169 | + if (idempotency != null) { | |
| 170 | + statement.setIdempotent(idempotency); | |
| 171 | + assertThat(statement.isIdempotent()).isEqualTo(idempotency); | |
| 172 | + } else { | |
| 173 | + assertThat(statement.isIdempotent()).isNull(); | |
| 174 | + } | |
| 175 | + return statement; | |
| 176 | + } | |
| 177 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/AsyncQueryTest.java +128 −17
| @@ -16,6 +16,7 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 19 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 19 | 20 | import com.google.common.base.Function; |
| 20 | 21 | import com.google.common.base.Throwables; |
| 21 | 22 | import com.google.common.collect.Lists; |
| @@ -25,7 +26,9 @@ | ||
| 25 | 26 | import org.testng.annotations.DataProvider; |
| 26 | 27 | import org.testng.annotations.Test; |
| 27 | 28 | |
| 29 | +import java.nio.ByteBuffer; | |
| 28 | 30 | import java.util.Collection; |
| 31 | +import java.util.Map; | |
| 29 | 32 | import java.util.concurrent.*; |
| 30 | 33 | |
| 31 | 34 | import static org.assertj.core.api.Assertions.assertThat; |
| @@ -48,9 +51,9 @@ | ||
| 48 | 51 | String keyspace = (String) objects[0]; |
| 49 | 52 | execute( |
| 50 | 53 | String.format("create keyspace %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}", keyspace), |
| 51 | - String.format("create table %s.foo(k int primary key, v int)", keyspace), | |
| 52 | - String.format("insert into %s.foo (k, v) values (1, 1)", keyspace) | |
| 53 | - ); | |
| 54 | + String.format("create table %s.foo(k int, v int, primary key (k, v))", keyspace)); | |
| 55 | + for (int v = 1; v <= 100; v++) | |
| 56 | + execute(String.format("insert into %s.foo (k, v) values (1, %d)", keyspace, v)); | |
| 54 | 57 | } |
| 55 | 58 | } |
| 56 | 59 | |
| @@ -127,7 +130,6 @@ | ||
| 127 | 130 | |
| 128 | 131 | @Test(groups = "short") |
| 129 | 132 | public void should_fail_when_synchronous_call_on_io_thread() throws Exception { |
| 130 | - final Thread sameThread = Thread.currentThread(); | |
| 131 | 133 | for (int i = 0; i < 1000; i++) { |
| 132 | 134 | ResultSetFuture f = session().executeAsync("select release_version from system.local"); |
| 133 | 135 | ListenableFuture<Thread> f2 = Futures.transform(f, new Function<ResultSet, Thread>() { |
| @@ -137,26 +139,74 @@ | ||
| 137 | 139 | return Thread.currentThread(); |
| 138 | 140 | } |
| 139 | 141 | }); |
| 140 | - try { | |
| 141 | - Thread executedThread = f2.get(); | |
| 142 | - if(executedThread != sameThread) { | |
| 143 | - fail("Expected a failed future, callback was executed on " + executedThread); | |
| 144 | - } else { | |
| 145 | - // Callback was invoked on the same thread, which indicates that the future completed | |
| 146 | - // before the transform callback was registered. Try again to produce case where callback | |
| 147 | - // is called on io thread. | |
| 148 | - logger.warn("Future completed before transform callback registered, will try again."); | |
| 142 | + if (isFailed(f2, IllegalStateException.class, "Detected a synchronous call on an I/O thread")) { | |
| 143 | + return; | |
| 144 | + } | |
| 145 | + } | |
| 146 | + fail("callback was not executed on io thread in 1000 attempts, something may be wrong."); | |
| 147 | + } | |
| 148 | + | |
| 149 | + @Test(groups = "short") | |
| 150 | + public void should_fail_when_synchronous_call_on_io_thread_with_session_wrapper() throws Exception { | |
| 151 | + final Session session = new SessionWrapper(session()); | |
| 152 | + for (int i = 0; i < 1000; i++) { | |
| 153 | + ResultSetFuture f = session.executeAsync("select release_version from system.local"); | |
| 154 | + ListenableFuture<Thread> f2 = Futures.transform(f, new Function<ResultSet, Thread>() { | |
| 155 | + @Override | |
| 156 | + public Thread apply(ResultSet input) { | |
| 157 | + session.execute("select release_version from system.local"); | |
| 158 | + return Thread.currentThread(); | |
| 159 | + } | |
| 160 | + }); | |
| 161 | + if (isFailed(f2, IllegalStateException.class, "Detected a synchronous call on an I/O thread")) { | |
| 162 | + return; | |
| 163 | + } | |
| 164 | + } | |
| 165 | + fail("callback was not executed on io thread in 1000 attempts, something may be wrong."); | |
| 166 | + } | |
| 167 | + | |
| 168 | + @Test(groups = "short") | |
| 169 | + @CassandraVersion(major = 2.0, description = "Paging is not supported until 2.0") | |
| 170 | + public void should_fail_when_auto_paging_on_io_thread() throws Exception { | |
| 171 | + for (int i = 0; i < 1000; i++) { | |
| 172 | + Statement statement = new SimpleStatement("select v from asyncquerytest.foo where k = 1"); | |
| 173 | + // Ensure results will be paged (there are 100 rows in the test table) | |
| 174 | + statement.setFetchSize(10); | |
| 175 | + ResultSetFuture f = session().executeAsync(statement); | |
| 176 | + ListenableFuture<Thread> f2 = Futures.transform(f, new Function<ResultSet, Thread>() { | |
| 177 | + @Override | |
| 178 | + public Thread apply(ResultSet rs) { | |
| 179 | + rs.all(); // Consume the whole result set | |
| 180 | + return Thread.currentThread(); | |
| 149 | 181 | } |
| 150 | - } catch (Exception e) { | |
| 151 | - assertThat(Throwables.getRootCause(e)) | |
| 152 | - .isInstanceOf(IllegalStateException.class) | |
| 153 | - .hasMessageContaining("Detected a synchronous Session call"); | |
| 182 | + }); | |
| 183 | + if (isFailed(f2, IllegalStateException.class, "Detected a synchronous call on an I/O thread")) { | |
| 154 | 184 | return; |
| 155 | 185 | } |
| 156 | 186 | } |
| 157 | 187 | fail("callback was not executed on io thread in 1000 attempts, something may be wrong."); |
| 158 | 188 | } |
| 159 | 189 | |
| 190 | + private boolean isFailed(ListenableFuture<Thread> future, Class<?> expectedException, String expectedMessage) { | |
| 191 | + try { | |
| 192 | + Thread executedThread = future.get(); | |
| 193 | + if (executedThread != Thread.currentThread()) { | |
| 194 | + fail("Expected a failed future, callback was executed on " + executedThread); | |
| 195 | + } else { | |
| 196 | + // Callback was invoked on the same thread, which indicates that the future completed | |
| 197 | + // before the transform callback was registered. Try again to produce case where callback | |
| 198 | + // is called on io thread. | |
| 199 | + logger.warn("Future completed before transform callback registered, will try again."); | |
| 200 | + } | |
| 201 | + } catch (Exception e) { | |
| 202 | + assertThat(Throwables.getRootCause(e)) | |
| 203 | + .isInstanceOf(expectedException) | |
| 204 | + .hasMessageContaining(expectedMessage); | |
| 205 | + return true; | |
| 206 | + } | |
| 207 | + return false; | |
| 208 | + } | |
| 209 | + | |
| 160 | 210 | private ListenableFuture<Integer> connectAndQuery(String keyspace, Executor executor) { |
| 161 | 211 | ListenableFuture<Session> sessionFuture = cluster().connectAsync(keyspace); |
| 162 | 212 | ListenableFuture<ResultSet> queryFuture = Futures.transform(sessionFuture, new AsyncFunction<Session, ResultSet>() { |
| @@ -178,4 +228,65 @@ | ||
| 178 | 228 | assertEquals(pools.size(), 1); |
| 179 | 229 | return pools.iterator().next(); |
| 180 | 230 | } |
| 231 | + | |
| 232 | + private static class SessionWrapper extends AbstractSession { | |
| 233 | + | |
| 234 | + private final Session session; | |
| 235 | + | |
| 236 | + public SessionWrapper(Session session) { | |
| 237 | + this.session = session; | |
| 238 | + } | |
| 239 | + | |
| 240 | + @Override | |
| 241 | + public ResultSet execute(Statement statement) { | |
| 242 | + // test a custom call to checkNotInEventLoop() | |
| 243 | + checkNotInEventLoop(); | |
| 244 | + return executeAsync(statement).getUninterruptibly(); | |
| 245 | + } | |
| 246 | + | |
| 247 | + @Override | |
| 248 | + public String getLoggedKeyspace() { | |
| 249 | + return session.getLoggedKeyspace(); | |
| 250 | + } | |
| 251 | + | |
| 252 | + @Override | |
| 253 | + public Session init() { | |
| 254 | + return session.init(); | |
| 255 | + } | |
| 256 | + | |
| 257 | + @Override | |
| 258 | + public ListenableFuture<Session> initAsync() { | |
| 259 | + return session.initAsync(); | |
| 260 | + } | |
| 261 | + | |
| 262 | + @Override | |
| 263 | + public ResultSetFuture executeAsync(Statement statement) { | |
| 264 | + return session.executeAsync(statement); | |
| 265 | + } | |
| 266 | + | |
| 267 | + @Override | |
| 268 | + public CloseFuture closeAsync() { | |
| 269 | + return session.closeAsync(); | |
| 270 | + } | |
| 271 | + | |
| 272 | + @Override | |
| 273 | + public boolean isClosed() { | |
| 274 | + return session.isClosed(); | |
| 275 | + } | |
| 276 | + | |
| 277 | + @Override | |
| 278 | + public Cluster getCluster() { | |
| 279 | + return session.getCluster(); | |
| 280 | + } | |
| 281 | + | |
| 282 | + @Override | |
| 283 | + public State getState() { | |
| 284 | + return session.getState(); | |
| 285 | + } | |
| 286 | + | |
| 287 | + @Override | |
| 288 | + protected ListenableFuture<PreparedStatement> prepareAsync(String query, Map<String, ByteBuffer> customPayload) { | |
| 289 | + return ((SessionManager) session).prepareAsync(query, customPayload); | |
| 290 | + } | |
| 291 | + } | |
| 181 | 292 | } |
modified driver-core/src/test/java/com/datastax/driver/core/AuthenticationTest.java +12 −2
| @@ -24,6 +24,7 @@ | ||
| 24 | 24 | |
| 25 | 25 | import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; |
| 26 | 26 | import static com.datastax.driver.core.TestUtils.findHost; |
| 27 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 27 | 28 | import static org.mockito.Mockito.*; |
| 28 | 29 | |
| 29 | 30 | /** |
| @@ -55,6 +56,7 @@ | ||
| 55 | 56 | .build(); |
| 56 | 57 | cluster.connect(); |
| 57 | 58 | verify(authProvider, atLeastOnce()).newAuthenticator(findHost(cluster, 1).getSocketAddress(), "org.apache.cassandra.auth.PasswordAuthenticator"); |
| 59 | + assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()).isEqualTo(0); | |
| 58 | 60 | } |
| 59 | 61 | |
| 60 | 62 | @Test(groups = "short", expectedExceptions = AuthenticationException.class) |
| @@ -64,7 +66,11 @@ | ||
| 64 | 66 | .withPort(ccm().getBinaryPort()) |
| 65 | 67 | .withCredentials("bogus", "bogus") |
| 66 | 68 | .build()); |
| 67 | - cluster.connect(); | |
| 69 | + try { | |
| 70 | + cluster.connect(); | |
| 71 | + } finally { | |
| 72 | + assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()).isEqualTo(1); | |
| 73 | + } | |
| 68 | 74 | } |
| 69 | 75 | |
| 70 | 76 | @Test(groups = "short", expectedExceptions = AuthenticationException.class) |
| @@ -73,7 +79,11 @@ | ||
| 73 | 79 | .addContactPoints(getContactPoints()) |
| 74 | 80 | .withPort(ccm().getBinaryPort()) |
| 75 | 81 | .build()); |
| 76 | - cluster.connect(); | |
| 82 | + try { | |
| 83 | + cluster.connect(); | |
| 84 | + } finally { | |
| 85 | + assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()).isEqualTo(1); | |
| 86 | + } | |
| 77 | 87 | } |
| 78 | 88 | |
| 79 | 89 | } |
added driver-core/src/test/java/com/datastax/driver/core/BatchStatementIdempotencyTest.java +44 −0
| @@ -0,0 +1,44 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2015 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core; | |
| 17 | + | |
| 18 | +public class BatchStatementIdempotencyTest extends AbstractBatchIdempotencyTest { | |
| 19 | + | |
| 20 | + @Override | |
| 21 | + protected TestBatch createBatch() { | |
| 22 | + return new TestBatchStatementWrapper(); | |
| 23 | + } | |
| 24 | + | |
| 25 | + static class TestBatchStatementWrapper implements TestBatch { | |
| 26 | + | |
| 27 | + private final BatchStatement batch = new BatchStatement(); | |
| 28 | + | |
| 29 | + @Override | |
| 30 | + public void add(RegularStatement statement) { | |
| 31 | + batch.add(statement); | |
| 32 | + } | |
| 33 | + | |
| 34 | + @Override | |
| 35 | + public Boolean isIdempotent() { | |
| 36 | + return batch.isIdempotent(); | |
| 37 | + } | |
| 38 | + | |
| 39 | + @Override | |
| 40 | + public void setIdempotent(boolean idempotent) { | |
| 41 | + batch.setIdempotent(idempotent); | |
| 42 | + } | |
| 43 | + } | |
| 44 | +} |
added driver-core/src/test/java/com/datastax/driver/core/CompressionTest.java +55 −0
| @@ -0,0 +1,55 @@ | ||
| 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 static com.datastax.driver.core.SessionTest.checkExecuteResultSet; | |
| 21 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 22 | + | |
| 23 | +public class CompressionTest extends CCMTestsSupport { | |
| 24 | + | |
| 25 | + private static String TABLE = "test"; | |
| 26 | + | |
| 27 | + public void onTestContextInitialized() { | |
| 28 | + execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, t text, i int, f float)", TABLE)); | |
| 29 | + } | |
| 30 | + | |
| 31 | + void compressionTest(ProtocolOptions.Compression compression) { | |
| 32 | + cluster().getConfiguration().getProtocolOptions().setCompression(compression); | |
| 33 | + try { | |
| 34 | + Session compressedSession = cluster().connect(keyspace); | |
| 35 | + | |
| 36 | + // Simple calls to all versions of the execute/executeAsync methods | |
| 37 | + String key = "execute_compressed_test_" + compression; | |
| 38 | + ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE, key, "foo", 42, 24.03f)); | |
| 39 | + assertThat(rs.isExhausted()).isTrue(); | |
| 40 | + | |
| 41 | + String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE, key); | |
| 42 | + | |
| 43 | + // execute | |
| 44 | + checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key); | |
| 45 | + checkExecuteResultSet(compressedSession.execute(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key); | |
| 46 | + | |
| 47 | + // executeAsync | |
| 48 | + checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key); | |
| 49 | + checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key); | |
| 50 | + | |
| 51 | + } finally { | |
| 52 | + cluster().getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE); | |
| 53 | + } | |
| 54 | + } | |
| 55 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/ConnectionReleaseTest.java +1 −3
| @@ -110,9 +110,7 @@ | ||
| 110 | 110 | } |
| 111 | 111 | }); |
| 112 | 112 | |
| 113 | - // Wait for up to pool timeout for response. If future is not complete by then, we can assume | |
| 114 | - // that it is likely that the execute is hung because the connection wasn't released yet. | |
| 115 | - long waitTimeInMs = cluster.getConfiguration().getPoolingOptions().getPoolTimeoutMillis(); | |
| 113 | + long waitTimeInMs = 2000; | |
| 116 | 114 | try { |
| 117 | 115 | ResultSet result = future.get(waitTimeInMs, TimeUnit.MILLISECONDS); |
| 118 | 116 | assertThat(result.one().getString("n")).isEqualTo("world"); |
added driver-core/src/test/java/com/datastax/driver/core/DirectCompressionTest.java +47 −0
| @@ -0,0 +1,47 @@ | ||
| 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.datastax.driver.core.utils.CassandraVersion; | |
| 19 | +import org.testng.annotations.Test; | |
| 20 | + | |
| 21 | +public class DirectCompressionTest extends CompressionTest { | |
| 22 | + | |
| 23 | + /** | |
| 24 | + * Validates that a session can be established using snappy compression and executes some queries that inserts and | |
| 25 | + * retrieves data using that session(). | |
| 26 | + * | |
| 27 | + * @test_category connection:compression | |
| 28 | + * @expected_result session established and queries made successfully using it. | |
| 29 | + */ | |
| 30 | + @Test(groups = "short") | |
| 31 | + public void should_function_with_snappy_compression() throws Exception { | |
| 32 | + compressionTest(ProtocolOptions.Compression.SNAPPY); | |
| 33 | + } | |
| 34 | + | |
| 35 | + /** | |
| 36 | + * Validates that a session can be established using lz4 compression and executes some queries that inserts and | |
| 37 | + * retrieves data using that session(). | |
| 38 | + * | |
| 39 | + * @test_category connection:compression | |
| 40 | + * @expected_result session established and queries made successfully using it. | |
| 41 | + */ | |
| 42 | + @Test(groups = "short") | |
| 43 | + @CassandraVersion(major = 2.0) | |
| 44 | + public void should_function_with_lz4_compression() throws Exception { | |
| 45 | + compressionTest(ProtocolOptions.Compression.LZ4); | |
| 46 | + } | |
| 47 | +} |
added driver-core/src/test/java/com/datastax/driver/core/FrameLengthTest.java +121 −0
| @@ -0,0 +1,121 @@ | ||
| 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.datastax.driver.core.exceptions.FrameTooLongException; | |
| 19 | +import com.datastax.driver.core.querybuilder.Insert; | |
| 20 | +import com.datastax.driver.core.schemabuilder.Create; | |
| 21 | +import com.datastax.driver.core.schemabuilder.SchemaBuilder; | |
| 22 | +import org.slf4j.Logger; | |
| 23 | +import org.slf4j.LoggerFactory; | |
| 24 | +import org.testng.annotations.BeforeClass; | |
| 25 | +import org.testng.annotations.Test; | |
| 26 | + | |
| 27 | +import java.nio.ByteBuffer; | |
| 28 | +import java.util.Collection; | |
| 29 | +import java.util.Random; | |
| 30 | + | |
| 31 | +import static com.datastax.driver.core.querybuilder.QueryBuilder.*; | |
| 32 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 33 | +import static org.assertj.core.api.Fail.fail; | |
| 34 | + | |
| 35 | +@CCMConfig(numberOfNodes = 2) | |
| 36 | +public class FrameLengthTest extends CCMTestsSupport { | |
| 37 | + | |
| 38 | + Logger logger = LoggerFactory.getLogger(FrameLengthTest.class); | |
| 39 | + | |
| 40 | + private static final String tableName = "blob_table"; | |
| 41 | + private static final int colCount = 256; | |
| 42 | + private static final int rowsPerPartitionCount = 4; | |
| 43 | + private static final int partitionCount = 1; | |
| 44 | + private static final int bytesPerCol = 1024; | |
| 45 | + | |
| 46 | + @BeforeClass(groups = {"isolated"}) | |
| 47 | + public void beforeTestClass() throws Exception { | |
| 48 | + // Set max frame size to 1MB to make it easier to manifest frame length error. | |
| 49 | + System.setProperty("com.datastax.driver.NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB", "1"); | |
| 50 | + super.beforeTestClass(); | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Override | |
| 54 | + public void onTestContextInitialized() { | |
| 55 | + logger.info("Creating table {} with {} {}-byte blob columns", tableName, colCount, bytesPerCol); | |
| 56 | + Random random = new Random(); | |
| 57 | + // Create table | |
| 58 | + Create create = SchemaBuilder.createTable(tableName).addPartitionKey("k", DataType.cint()).addClusteringColumn("c", DataType.cint()); | |
| 59 | + for (int i = 0; i < colCount; i++) { | |
| 60 | + create.addColumn("col" + i, DataType.blob()); | |
| 61 | + } | |
| 62 | + execute(create.getQueryString()); | |
| 63 | + | |
| 64 | + // build prepared statement. | |
| 65 | + Insert insert = insertInto(tableName).value("k", bindMarker()).value("c", bindMarker()); | |
| 66 | + for (int i = 0; i < colCount; i++) { | |
| 67 | + insert = insert.value("col" + i, bindMarker()); | |
| 68 | + } | |
| 69 | + | |
| 70 | + PreparedStatement prepared = session().prepare(insert); | |
| 71 | + | |
| 72 | + // Insert rows. | |
| 73 | + logger.info("Inserting data for {} partitions.", partitionCount); | |
| 74 | + for (int i = 0; i < partitionCount; i++) { | |
| 75 | + logger.info("Inserting {} rows in partition {}", rowsPerPartitionCount, i); | |
| 76 | + for (int r = 0; r < rowsPerPartitionCount; r++) { | |
| 77 | + BoundStatement stmt = prepared.bind(); | |
| 78 | + stmt.setInt("k", i); | |
| 79 | + stmt.setInt("c", r); | |
| 80 | + for (int c = 0; c < colCount; c++) { | |
| 81 | + byte[] b = new byte[bytesPerCol]; | |
| 82 | + random.nextBytes(b); | |
| 83 | + ByteBuffer in = ByteBuffer.wrap(b); | |
| 84 | + stmt.setBytes("col" + c, in); | |
| 85 | + } | |
| 86 | + session().execute(stmt); | |
| 87 | + } | |
| 88 | + } | |
| 89 | + logger.info("Done loading {}", tableName); | |
| 90 | + } | |
| 91 | + | |
| 92 | + /** | |
| 93 | + * Validates that if a frame is received that exceeds NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB that | |
| 94 | + * the driver is able to recover, not lose host connectivity and make further queries. It | |
| 95 | + * configures NATIVE_TRANSPORT_MAX_FRAME_SIZE_IN_MB to 1 MB to make the error easier to reproduce. | |
| 96 | + * | |
| 97 | + * @jira_ticket JAVA-1292 | |
| 98 | + * @jira_ticket JAVA-1293 | |
| 99 | + * @test_category connection | |
| 100 | + */ | |
| 101 | + @Test(groups = "isolated") | |
| 102 | + public void should_throw_exception_when_frame_exceeds_configured_max() { | |
| 103 | + try { | |
| 104 | + session().execute(select().from(tableName).where(eq("k", 0))); | |
| 105 | + fail("Exception expected"); | |
| 106 | + } catch (FrameTooLongException ftle) { | |
| 107 | + // Expected. | |
| 108 | + } | |
| 109 | + | |
| 110 | + // Both hosts should remain up. | |
| 111 | + Collection<Host> hosts = session().getState().getConnectedHosts(); | |
| 112 | + assertThat(hosts).hasSize(2).extractingResultOf("isUp").containsOnly(true); | |
| 113 | + | |
| 114 | + // Should be able to make a query that is less than the max frame size. | |
| 115 | + // Execute multiple time to exercise all hosts. | |
| 116 | + for (int i = 0; i < 10; i++) { | |
| 117 | + ResultSet result = session().execute(select().from(tableName).where(eq("k", 0)).and(eq("c", 0))); | |
| 118 | + assertThat(result.getAvailableWithoutFetching()).isEqualTo(1); | |
| 119 | + } | |
| 120 | + } | |
| 121 | +} |
added driver-core/src/test/java/com/datastax/driver/core/HeapCompressionTest.java +54 −0
| @@ -0,0 +1,54 @@ | ||
| 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.datastax.driver.core.utils.CassandraVersion; | |
| 19 | +import org.testng.annotations.BeforeClass; | |
| 20 | +import org.testng.annotations.Test; | |
| 21 | + | |
| 22 | +public class HeapCompressionTest extends CompressionTest { | |
| 23 | + | |
| 24 | + @BeforeClass(groups = "isolated") | |
| 25 | + public void beforeTestClass() throws Exception { | |
| 26 | + // Configure with noPreferDirect and noUnsafe to force heap buffers. | |
| 27 | + System.setProperty("io.netty.noPreferDirect", "true"); | |
| 28 | + System.setProperty("io.netty.noUnsafe", "true"); | |
| 29 | + super.beforeTestClass(); | |
| 30 | + } | |
| 31 | + | |
| 32 | + /** | |
| 33 | + * Validates that snappy compression still works when using heap buffers. | |
| 34 | + * | |
| 35 | + * @test_category connection:compression | |
| 36 | + * @expected_result session established and queries made successfully using it. | |
| 37 | + */ | |
| 38 | + @Test(groups = "isolated") | |
| 39 | + public void should_function_with_snappy_compression() throws Exception { | |
| 40 | + compressionTest(ProtocolOptions.Compression.SNAPPY); | |
| 41 | + } | |
| 42 | + | |
| 43 | + /** | |
| 44 | + * Validates that lz4 compression still works when using heap buffers. | |
| 45 | + * | |
| 46 | + * @test_category connection:compression | |
| 47 | + * @expected_result session established and queries made successfully using it. | |
| 48 | + */ | |
| 49 | + @Test(groups = "isolated") | |
| 50 | + @CassandraVersion(major = 2.0) | |
| 51 | + public void should_function_with_lz4_compression() throws Exception { | |
| 52 | + compressionTest(ProtocolOptions.Compression.LZ4); | |
| 53 | + } | |
| 54 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/HostConnectionPoolTest.java +421 −144
| @@ -16,10 +16,11 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.codahale.metrics.Gauge; |
| 19 | -import com.datastax.driver.core.exceptions.BusyConnectionException; | |
| 20 | -import com.datastax.driver.core.exceptions.ConnectionException; | |
| 19 | +import com.datastax.driver.core.exceptions.*; | |
| 21 | 20 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 21 | +import com.datastax.driver.core.utils.MoreFutures; | |
| 22 | 22 | import com.google.common.base.Predicate; |
| 23 | +import com.google.common.base.Throwables; | |
| 23 | 24 | import com.google.common.util.concurrent.*; |
| 24 | 25 | import org.scassandra.cql.PrimitiveType; |
| 25 | 26 | import org.scassandra.http.client.PrimingRequest; |
| @@ -27,6 +28,7 @@ | ||
| 27 | 28 | import org.testng.annotations.Test; |
| 28 | 29 | |
| 29 | 30 | import java.net.InetSocketAddress; |
| 31 | +import java.util.Collections; | |
| 30 | 32 | import java.util.Iterator; |
| 31 | 33 | import java.util.List; |
| 32 | 34 | import java.util.concurrent.*; |
| @@ -35,8 +37,8 @@ | ||
| 35 | 37 | |
| 36 | 38 | import static com.datastax.driver.core.Assertions.assertThat; |
| 37 | 39 | import static com.datastax.driver.core.ConditionChecker.check; |
| 40 | +import static com.datastax.driver.core.PoolingOptions.NEW_CONNECTION_THRESHOLD_LOCAL_KEY; | |
| 38 | 41 | import static com.google.common.collect.Lists.newArrayList; |
| 39 | -import static java.util.Collections.singletonList; | |
| 40 | 42 | import static java.util.concurrent.TimeUnit.SECONDS; |
| 41 | 43 | import static org.mockito.Mockito.*; |
| 42 | 44 | import static org.scassandra.http.client.ClosedConnectionReport.CloseType.CLOSE; |
| @@ -45,6 +47,9 @@ | ||
| 45 | 47 | |
| 46 | 48 | public class HostConnectionPoolTest extends ScassandraTestBase.PerClassCluster { |
| 47 | 49 | |
| 50 | + static final Integer NEW_CONNECTION_THRESHOLD = PoolingOptions.DEFAULTS.get(ProtocolVersion.V1) | |
| 51 | + .get(NEW_CONNECTION_THRESHOLD_LOCAL_KEY); | |
| 52 | + | |
| 48 | 53 | @BeforeClass(groups = {"short", "long"}) |
| 49 | 54 | public void reinitializeCluster() { |
| 50 | 55 | // Don't use the provided cluster, each test will create its own instead. |
| @@ -67,136 +72,317 @@ | ||
| 67 | 72 | }).becomesTrue(); |
| 68 | 73 | } |
| 69 | 74 | |
| 70 | - /** | |
| 71 | - * Sends 101 requests on pool, asserting that the connection used is in expectedConnections, except for the last request. | |
| 72 | - */ | |
| 73 | - private List<MockRequest> fillConnectionToThreshold(HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException { | |
| 74 | - List<MockRequest> requests = sendRequests(100, pool, expectedConnections); | |
| 75 | - requests.add(MockRequest.send(pool)); | |
| 76 | - return requests; | |
| 75 | + private void assertBorrowedConnections(Iterable<MockRequest> requests, List<Connection> expectedConnections) { | |
| 76 | + for (MockRequest request : requests) { | |
| 77 | + assertThat(expectedConnections).contains(request.getConnection()); | |
| 78 | + } | |
| 79 | + } | |
| 80 | + | |
| 81 | + private void assertBorrowedConnection(Iterable<MockRequest> requests, Connection expectedConnection) { | |
| 82 | + assertBorrowedConnections(requests, Collections.singletonList(expectedConnection)); | |
| 77 | 83 | } |
| 78 | 84 | |
| 79 | 85 | /** |
| 80 | - * Sends count requests on pool. | |
| 86 | + * Ensures that if a fixed-sized pool has filled its core connections and reached its maximum number of enqueued | |
| 87 | + * requests, then borrowConnection will fail instead of creating a new connection. | |
| 88 | + * | |
| 89 | + * @jira_ticket JAVA-419 | |
| 90 | + * @test_category connection:connection_pool | |
| 91 | + * @since 2.0.10, 2.1.6 | |
| 81 | 92 | */ |
| 82 | - private List<MockRequest> sendRequests(int count, HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException { | |
| 83 | - return sendRequests(count, pool, null); | |
| 93 | + @Test(groups = "short") | |
| 94 | + public void fixed_size_pool_should_fill_its_core_connections_and_queue_and_then_reject() { | |
| 95 | + Cluster cluster = createClusterBuilder().build(); | |
| 96 | + List<MockRequest> allRequests = newArrayList(); | |
| 97 | + try { | |
| 98 | + HostConnectionPool pool = createPool(cluster, 2, 2); | |
| 99 | + int maxQueueSize = 256; | |
| 100 | + | |
| 101 | + assertThat(pool.connections.size()).isEqualTo(2); | |
| 102 | + List<Connection> coreConnections = newArrayList(pool.connections); | |
| 103 | + // fill connections | |
| 104 | + List<MockRequest> requests = MockRequest.sendMany(2 * 128, pool); | |
| 105 | + assertBorrowedConnections(requests, coreConnections); | |
| 106 | + allRequests.addAll(requests); | |
| 107 | + // fill queue | |
| 108 | + allRequests.addAll(MockRequest.sendMany(maxQueueSize, pool, maxQueueSize)); | |
| 109 | + | |
| 110 | + // add one more request, it should be rejected because the queue is full | |
| 111 | + MockRequest failedBorrow = MockRequest.send(pool, maxQueueSize); | |
| 112 | + try { | |
| 113 | + failedBorrow.getConnection(); | |
| 114 | + fail("Expected a BusyPoolException"); | |
| 115 | + } catch (BusyPoolException e) {/*expected*/} | |
| 116 | + } finally { | |
| 117 | + MockRequest.completeAll(allRequests); | |
| 118 | + cluster.close(); | |
| 119 | + } | |
| 84 | 120 | } |
| 85 | 121 | |
| 86 | 122 | /** |
| 87 | - * Sends count requests on pool, asserting that the connection used is in expectedConnections. | |
| 123 | + * Ensures that any enqueued connection borrow requests are failed when their associated connection pool closes. | |
| 124 | + * | |
| 125 | + * @jira_ticket JAVA-839 | |
| 126 | + * @test_category connection:connection_pool | |
| 127 | + * @since 3.0.4, 3.1.1 | |
| 88 | 128 | */ |
| 89 | - private List<MockRequest> sendRequests(int count, HostConnectionPool pool, List<Connection> expectedConnections) throws ConnectionException, BusyConnectionException, TimeoutException { | |
| 129 | + @Test(groups = "short") | |
| 130 | + public void requests_with_enqueued_borrow_requests_should_be_failed_when_pool_closes() { | |
| 131 | + Cluster cluster = createClusterBuilder().build(); | |
| 90 | 132 | List<MockRequest> requests = newArrayList(); |
| 91 | - for (int i = 0; i < count; i++) { | |
| 92 | - MockRequest request = MockRequest.send(pool); | |
| 93 | - requests.add(request); | |
| 94 | - if (expectedConnections != null) | |
| 95 | - assertThat(expectedConnections).contains(request.connection); | |
| 96 | - } | |
| 97 | - return requests; | |
| 133 | + try { | |
| 134 | + HostConnectionPool pool = createPool(cluster, 2, 2); | |
| 135 | + int maxQueueSize = 256; | |
| 136 | + | |
| 137 | + assertThat(pool.connections.size()).isEqualTo(2); | |
| 138 | + List<Connection> coreConnections = newArrayList(pool.connections); | |
| 139 | + // fill connections | |
| 140 | + requests = MockRequest.sendMany(2 * 128, pool); | |
| 141 | + assertBorrowedConnections(requests, coreConnections); | |
| 142 | + // fill queue | |
| 143 | + List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize); | |
| 144 | + | |
| 145 | + // Closing the pool should fail all queued connections. | |
| 146 | + pool.closeAsync(); | |
| 147 | + | |
| 148 | + for (MockRequest queuedRequest : queuedRequests) { | |
| 149 | + // Future should be completed. | |
| 150 | + assertThat(queuedRequest.connectionFuture.isDone()).isTrue(); | |
| 151 | + try { | |
| 152 | + // Future should fail as result of the pool closing. | |
| 153 | + queuedRequest.getConnection(); | |
| 154 | + fail("Expected a ConnectionException"); | |
| 155 | + } catch (ConnectionException e) {/*expected*/} | |
| 156 | + } | |
| 157 | + } finally { | |
| 158 | + MockRequest.completeAll(requests); | |
| 159 | + cluster.close(); | |
| 160 | + } | |
| 98 | 161 | } |
| 99 | 162 | |
| 100 | 163 | /** |
| 101 | - * Completes count requests by simulating a successful response. | |
| 164 | + * Validates that if the keyspace tied to the Session's pool state is different than the keyspace on the connection | |
| 165 | + * being used in dequeue that {@link Connection#setKeyspaceAsync(String)} is set on that connection and that | |
| 166 | + * "USE keyspace" is only called once since setKeyspaceAsync should not attempt setting the keyspace if there is | |
| 167 | + * already a request inflight that is doing this. | |
| 168 | + * | |
| 169 | + * @jira_ticket JAVA-839 | |
| 170 | + * @test_category connection:connection_pool | |
| 171 | + * @since 3.0.4, 3.1.1 | |
| 102 | 172 | */ |
| 103 | - private void completeRequests(int count, List<MockRequest> requests) { | |
| 104 | - Iterator<MockRequest> requestIt = requests.iterator(); | |
| 105 | - for (int i = 0; i < count; i++) { | |
| 106 | - if (requestIt.hasNext()) { | |
| 107 | - MockRequest request = requestIt.next(); | |
| 108 | - request.simulateSuccessResponse(); | |
| 109 | - requestIt.remove(); | |
| 110 | - } else { | |
| 111 | - break; | |
| 173 | + @Test(groups = "short") | |
| 174 | + public void should_adjust_connection_keyspace_on_dequeue_if_pool_state_is_different() throws TimeoutException, ExecutionException { | |
| 175 | + Cluster cluster = createClusterBuilder().build(); | |
| 176 | + List<MockRequest> requests = newArrayList(); | |
| 177 | + try { | |
| 178 | + HostConnectionPool pool = createPool(cluster, 1, 1); | |
| 179 | + int maxQueueSize = 256; | |
| 180 | + | |
| 181 | + assertThat(pool.connections.size()).isEqualTo(1); | |
| 182 | + List<Connection> coreConnections = newArrayList(pool.connections); | |
| 183 | + // fill connections | |
| 184 | + requests = MockRequest.sendMany(128, pool); | |
| 185 | + assertBorrowedConnections(requests, coreConnections); | |
| 186 | + // fill queue | |
| 187 | + List<MockRequest> queuedRequests = MockRequest.sendMany(maxQueueSize, pool, maxQueueSize); | |
| 188 | + | |
| 189 | + // Wait for connections to be borrowed before changing keyspace. | |
| 190 | + for (MockRequest request : requests) { | |
| 191 | + Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS); | |
| 192 | + } | |
| 193 | + // Simulate change of keyspace on pool. Prime a delay so existing requests can complete beforehand. | |
| 194 | + primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"newkeyspace\"").withThen(PrimingRequest.then().withFixedDelay(2000L))); | |
| 195 | + pool.manager.poolsState.setKeyspace("newkeyspace"); | |
| 196 | + | |
| 197 | + // Complete all requests, this should cause dequeue on connection. | |
| 198 | + MockRequest.completeAll(requests); | |
| 199 | + | |
| 200 | + // Check the status on queued request's connection futures. We expect that dequeue should | |
| 201 | + // be called when connection is released by previous requests completing, and that one set | |
| 202 | + // keyspace attempt should be tried. | |
| 203 | + | |
| 204 | + // Because Scassandra currently returns a 'ROWS' response for set keyspace, the attempt | |
| 205 | + // will fail, and thus the enqueued connection futures will fail in the following ways: | |
| 206 | + // 1. DriverInternalError for set keyspace returning 'ROWS' response | |
| 207 | + // 2. TransportException for connection being closed, when this happens we stop checking these futures. | |
| 208 | + // 3. Never completing because no connections are available. | |
| 209 | + boolean timeoutAcceptable = false; | |
| 210 | + for (MockRequest queuedRequest : queuedRequests) { | |
| 211 | + try { | |
| 212 | + Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS); | |
| 213 | + fail("Expected an exception (because Scassandra doesn't support 'USE keyspace'"); | |
| 214 | + } catch (ExecutionException e) { | |
| 215 | + try { | |
| 216 | + throw e.getCause(); | |
| 217 | + } catch (DriverInternalError die) { | |
| 218 | + assertThat(die.getMessage()).contains("Unexpected response while setting keyspace"); | |
| 219 | + // Subsequent futures may timeout because the connection is closed. | |
| 220 | + timeoutAcceptable = true; | |
| 221 | + } catch (TransportException ce) { | |
| 222 | + /* expected, Scassandra returning a ROWS response for 'USE keyspace' should defunct and close the connection */ | |
| 223 | + // all remaining futures will timeout since there are no remaining connections. | |
| 224 | + break; | |
| 225 | + } catch (Throwable t) { | |
| 226 | + fail("Unexpected cause of future failing", t); | |
| 227 | + } | |
| 228 | + } catch (TimeoutException te) { | |
| 229 | + assertThat(timeoutAcceptable).isTrue(); | |
| 230 | + break; | |
| 231 | + } | |
| 112 | 232 | } |
| 233 | + | |
| 234 | + // We should only have gotten one 'USE newkeyspace' query since Connection#setKeyspaceAsync should only do | |
| 235 | + // this once if there is already a request in flight. | |
| 236 | + assertThat(activityClient.retrieveQueries()).extractingResultOf("getQuery").containsOnlyOnce("USE \"newkeyspace\""); | |
| 237 | + } finally { | |
| 238 | + MockRequest.completeAll(requests); | |
| 239 | + cluster.close(); | |
| 113 | 240 | } |
| 114 | 241 | } |
| 115 | 242 | |
| 116 | 243 | /** |
| 117 | - * Completes all requests by simulating a successful response. | |
| 244 | + * Ensures that on borrowConnection if a set keyspace attempt is in progress on that connection for a different keyspace than the | |
| 245 | + * pool state that the borrowConnection future returned is failed. | |
| 246 | + * | |
| 247 | + * @jira_ticket JAVA-839 | |
| 248 | + * @test_category connection:connection_pool | |
| 249 | + * @since 3.0.4, 3.1.1 | |
| 118 | 250 | */ |
| 119 | - private void completeRequests(List<MockRequest> requests) { | |
| 120 | - for (MockRequest request : requests) { | |
| 121 | - request.simulateSuccessResponse(); | |
| 251 | + @Test(groups = "short") | |
| 252 | + public void should_fail_in_borrowConnection_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws TimeoutException { | |
| 253 | + Cluster cluster = createClusterBuilder().build(); | |
| 254 | + try { | |
| 255 | + HostConnectionPool pool = createPool(cluster, 1, 1); | |
| 256 | + | |
| 257 | + // Respond to setting as slowks very slowly. | |
| 258 | + primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L))); | |
| 259 | + | |
| 260 | + Connection connection = pool.connections.get(0); | |
| 261 | + | |
| 262 | + connection.setKeyspaceAsync("slowks"); | |
| 263 | + | |
| 264 | + // Simulate change of keyspace on pool. | |
| 265 | + pool.manager.poolsState.setKeyspace("newks"); | |
| 266 | + | |
| 267 | + MockRequest request = MockRequest.send(pool); | |
| 268 | + | |
| 269 | + try { | |
| 270 | + Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS); | |
| 271 | + fail("Should have thrown exception"); | |
| 272 | + } catch (ExecutionException e) { | |
| 273 | + assertThat(e.getCause()).isInstanceOf(DriverException.class); | |
| 274 | + assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newks' since there is already an in flight attempt to set keyspace to 'slowks'."); | |
| 275 | + } | |
| 276 | + } finally { | |
| 277 | + cluster.close(); | |
| 122 | 278 | } |
| 123 | 279 | } |
| 124 | 280 | |
| 125 | 281 | /** |
| 126 | - * Ensures that if a fixed-sized pool has filled its core connections that borrowConnection will timeout instead | |
| 127 | - * of creating a new connection. | |
| 282 | + * Ensures that while dequeuing borrow connection requests that if a set keyspace attempt is in progress on that connection for a difference | |
| 283 | + * keyspace than the pool state that the future for that borrow attempt is failed. | |
| 128 | 284 | * |
| 129 | - * @jira_ticket JAVA-419 | |
| 285 | + * @jira_ticket JAVA-839 | |
| 130 | 286 | * @test_category connection:connection_pool |
| 131 | - * @since 2.0.10, 2.1.6 | |
| 287 | + * @since 3.0.4, 3.1.1 | |
| 132 | 288 | */ |
| 133 | 289 | @Test(groups = "short") |
| 134 | - public void fixed_size_pool_should_fill_its_core_connections_and_then_timeout() throws ConnectionException, TimeoutException, BusyConnectionException { | |
| 290 | + public void should_fail_in_dequeue_when_setting_keyspace_and_another_set_keyspace_attempt_is_in_flight() throws ExecutionException, TimeoutException { | |
| 135 | 291 | Cluster cluster = createClusterBuilder().build(); |
| 136 | 292 | List<MockRequest> requests = newArrayList(); |
| 137 | 293 | try { |
| 138 | - HostConnectionPool pool = createPool(cluster, 2, 2); | |
| 294 | + // Limit requests per connection to 100 so we don't exhaust stream ids. | |
| 295 | + cluster.getConfiguration().getPoolingOptions().setMaxRequestsPerConnection(HostDistance.LOCAL, 100); | |
| 296 | + HostConnectionPool pool = createPool(cluster, 1, 1); | |
| 297 | + int maxQueueSize = 256; | |
| 139 | 298 | |
| 140 | - assertThat(pool.connections.size()).isEqualTo(2); | |
| 299 | + assertThat(pool.connections.size()).isEqualTo(1); | |
| 141 | 300 | List<Connection> coreConnections = newArrayList(pool.connections); |
| 142 | - requests.addAll(sendRequests(256, pool, coreConnections)); | |
| 301 | + | |
| 302 | + // fill connections | |
| 303 | + requests = MockRequest.sendMany(100, pool); | |
| 304 | + assertBorrowedConnections(requests, coreConnections); | |
| 305 | + | |
| 306 | + // send a request that will be queued. | |
| 307 | + MockRequest queuedRequest = MockRequest.send(pool, maxQueueSize); | |
| 308 | + | |
| 309 | + // Wait for connections to be borrowed before changing keyspace. | |
| 310 | + for (MockRequest request : requests) { | |
| 311 | + Uninterruptibles.getUninterruptibly(request.connectionFuture, 5, TimeUnit.SECONDS); | |
| 312 | + } | |
| 313 | + | |
| 314 | + // Respond to setting as slowks very slowly. | |
| 315 | + primingClient.prime(PrimingRequest.queryBuilder().withQuery("USE \"slowks\"").withThen(PrimingRequest.then().withFixedDelay(5000L))); | |
| 316 | + Connection connection = pool.connections.get(0); | |
| 317 | + connection.setKeyspaceAsync("slowks"); | |
| 318 | + | |
| 319 | + // Simulate change of keyspace on pool. | |
| 320 | + pool.manager.poolsState.setKeyspace("newkeyspace"); | |
| 321 | + | |
| 322 | + // Complete all requests, this should cause dequeue on connection. | |
| 323 | + MockRequest.completeAll(requests); | |
| 143 | 324 | |
| 144 | 325 | try { |
| 145 | - MockRequest.send(pool); | |
| 146 | - Assertions.fail("Expected a TimeoutException"); | |
| 147 | - } catch (TimeoutException e) { /*expected*/} | |
| 326 | + Uninterruptibles.getUninterruptibly(queuedRequest.connectionFuture, 5, TimeUnit.SECONDS); | |
| 327 | + fail("Should have thrown exception"); | |
| 328 | + } catch (ExecutionException e) { | |
| 329 | + assertThat(e.getCause()).isInstanceOf(DriverException.class); | |
| 330 | + assertThat(e.getCause().getMessage()).contains("Aborting attempt to set keyspace to 'newkeyspace' since there is already an in flight attempt to set keyspace to 'slowks'."); | |
| 331 | + } | |
| 332 | + | |
| 148 | 333 | } finally { |
| 149 | - completeRequests(requests); | |
| 334 | + MockRequest.completeAll(requests); | |
| 150 | 335 | cluster.close(); |
| 151 | 336 | } |
| 152 | 337 | } |
| 153 | 338 | |
| 154 | 339 | /** |
| 155 | 340 | * Ensures that if a variable-sized pool has filled up to its maximum connections that borrowConnection will |
| 156 | - * timeout instead of creating a new connection. | |
| 341 | + * return a failed future instead of creating a new connection. | |
| 157 | 342 | * |
| 158 | 343 | * @jira_ticket JAVA-419 |
| 159 | 344 | * @test_category connection:connection_pool |
| 160 | 345 | * @since 2.0.10, 2.1.6 |
| 161 | 346 | */ |
| 162 | 347 | @Test(groups = "short") |
| 163 | - public void variable_size_pool_should_fill_its_connections_and_then_timeout() throws Exception { | |
| 348 | + public void variable_size_pool_should_fill_its_connections_and_then_reject() throws Exception { | |
| 164 | 349 | Cluster cluster = createClusterBuilder().build(); |
| 165 | - List<MockRequest> requests = newArrayList(); | |
| 350 | + List<MockRequest> allRequests = newArrayList(); | |
| 166 | 351 | try { |
| 167 | 352 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 168 | 353 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 169 | 354 | cluster.manager.connectionFactory = factory; |
| 170 | 355 | |
| 171 | 356 | assertThat(pool.connections.size()).isEqualTo(1); |
| 172 | - List<Connection> coreConnections = newArrayList(pool.connections); | |
| 357 | + Connection coreConnection = pool.connections.get(0); | |
| 173 | 358 | |
| 174 | 359 | // Fill enough connections to hit the threshold. |
| 175 | - requests.addAll(fillConnectionToThreshold(pool, coreConnections)); | |
| 360 | + List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); | |
| 361 | + assertBorrowedConnection(requests, coreConnection); | |
| 362 | + allRequests.addAll(requests); | |
| 363 | + allRequests.add(MockRequest.send(pool)); | |
| 176 | 364 | |
| 177 | 365 | // Allow time for new connection to be spawned. |
| 178 | 366 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 179 | 367 | assertPoolSize(pool, 2); |
| 180 | 368 | |
| 181 | 369 | // Borrow more and ensure the connection returned is a non-core connection. |
| 182 | - for (int i = 0; i < 100; i++) { | |
| 370 | + for (int i = 0; i < NEW_CONNECTION_THRESHOLD; i++) { | |
| 183 | 371 | MockRequest request = MockRequest.send(pool); |
| 184 | - assertThat(coreConnections).doesNotContain(request.connection); | |
| 185 | - requests.add(request); | |
| 372 | + assertThat(request.getConnection()).isNotEqualTo(coreConnection); | |
| 373 | + allRequests.add(request); | |
| 186 | 374 | } |
| 187 | 375 | |
| 188 | 376 | // Fill remaining connections (28 + 28) - 1 |
| 189 | - requests.addAll(sendRequests(55, pool)); | |
| 377 | + allRequests.addAll(MockRequest.sendMany(55, pool)); | |
| 190 | 378 | |
| 191 | - boolean timedOut = false; | |
| 379 | + MockRequest failedBorrow = MockRequest.send(pool); | |
| 192 | 380 | try { |
| 193 | - MockRequest.send(pool); | |
| 194 | - } catch (TimeoutException e) { | |
| 195 | - timedOut = true; | |
| 196 | - } | |
| 197 | - assertThat(timedOut).isTrue(); | |
| 381 | + failedBorrow.getConnection(); | |
| 382 | + fail("Expected a BusyPoolException"); | |
| 383 | + } catch (BusyPoolException e) { /*expected*/} | |
| 198 | 384 | } finally { |
| 199 | - completeRequests(requests); | |
| 385 | + MockRequest.completeAll(allRequests); | |
| 200 | 386 | cluster.close(); |
| 201 | 387 | } |
| 202 | 388 | } |
| @@ -211,7 +397,7 @@ | ||
| 211 | 397 | @Test(groups = "short") |
| 212 | 398 | public void should_add_extra_connection_when_core_full() throws Exception { |
| 213 | 399 | Cluster cluster = createClusterBuilder().build(); |
| 214 | - List<MockRequest> requests = newArrayList(); | |
| 400 | + List<MockRequest> allRequests = newArrayList(); | |
| 215 | 401 | try { |
| 216 | 402 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 217 | 403 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| @@ -219,13 +405,16 @@ | ||
| 219 | 405 | Connection core = pool.connections.get(0); |
| 220 | 406 | |
| 221 | 407 | // Fill core connection + 1 |
| 222 | - requests.addAll(fillConnectionToThreshold(pool, singletonList(core))); | |
| 408 | + List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); | |
| 409 | + assertBorrowedConnection(requests, core); | |
| 410 | + allRequests.addAll(requests); | |
| 411 | + allRequests.add(MockRequest.send(pool)); | |
| 223 | 412 | |
| 224 | 413 | // Reaching the threshold should have triggered the creation of an extra one |
| 225 | 414 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 226 | 415 | assertPoolSize(pool, 2); |
| 227 | 416 | } finally { |
| 228 | - completeRequests(requests); | |
| 417 | + MockRequest.completeAll(allRequests); | |
| 229 | 418 | cluster.close(); |
| 230 | 419 | } |
| 231 | 420 | } |
| @@ -241,14 +430,17 @@ | ||
| 241 | 430 | @Test(groups = "long") |
| 242 | 431 | public void should_resurrect_trashed_connection_within_idle_timeout() throws Exception { |
| 243 | 432 | Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build(); |
| 244 | - List<MockRequest> requests = newArrayList(); | |
| 433 | + List<MockRequest> allRequests = newArrayList(); | |
| 245 | 434 | try { |
| 246 | 435 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 247 | 436 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 248 | 437 | cluster.manager.connectionFactory = factory; |
| 249 | 438 | Connection connection1 = pool.connections.get(0); |
| 250 | 439 | |
| 251 | - requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1))); | |
| 440 | + List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); | |
| 441 | + assertBorrowedConnections(requests, Collections.singletonList(connection1)); | |
| 442 | + allRequests.addAll(requests); | |
| 443 | + allRequests.add(MockRequest.send(pool)); | |
| 252 | 444 | |
| 253 | 445 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 254 | 446 | assertPoolSize(pool, 2); |
| @@ -258,7 +450,7 @@ | ||
| 258 | 450 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| 259 | 451 | |
| 260 | 452 | // Go back under the capacity of 1 connection |
| 261 | - completeRequests(51, requests); | |
| 453 | + MockRequest.completeMany(51, allRequests); | |
| 262 | 454 | |
| 263 | 455 | assertThat(connection1.inFlight.get()).isEqualTo(50); |
| 264 | 456 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| @@ -269,7 +461,7 @@ | ||
| 269 | 461 | assertThat(pool.trash).containsExactly(connection1); |
| 270 | 462 | |
| 271 | 463 | // Now borrow enough to go just under the 1 connection threshold |
| 272 | - requests.addAll(sendRequests(50, pool)); | |
| 464 | + allRequests.addAll(MockRequest.sendMany(50, pool)); | |
| 273 | 465 | |
| 274 | 466 | assertThat(pool.connections).containsExactly(connection2); |
| 275 | 467 | assertThat(pool.trash).containsExactly(connection1); |
| @@ -277,7 +469,7 @@ | ||
| 277 | 469 | assertThat(connection2.inFlight.get()).isEqualTo(50); |
| 278 | 470 | |
| 279 | 471 | // Borrowing one more time should resurrect the trashed connection |
| 280 | - requests.addAll(sendRequests(1, pool)); | |
| 472 | + allRequests.addAll(MockRequest.sendMany(1, pool)); | |
| 281 | 473 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 282 | 474 | assertPoolSize(pool, 2); |
| 283 | 475 | |
| @@ -286,7 +478,7 @@ | ||
| 286 | 478 | assertThat(connection1.inFlight.get()).isEqualTo(50); |
| 287 | 479 | assertThat(connection2.inFlight.get()).isEqualTo(51); |
| 288 | 480 | } finally { |
| 289 | - completeRequests(requests); | |
| 481 | + MockRequest.completeAll(allRequests); | |
| 290 | 482 | cluster.close(); |
| 291 | 483 | } |
| 292 | 484 | } |
| @@ -302,14 +494,17 @@ | ||
| 302 | 494 | @Test(groups = "long") |
| 303 | 495 | public void should_not_resurrect_trashed_connection_after_idle_timeout() throws Exception { |
| 304 | 496 | Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build(); |
| 305 | - List<MockRequest> requests = newArrayList(); | |
| 497 | + List<MockRequest> allRequests = newArrayList(); | |
| 306 | 498 | try { |
| 307 | 499 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 308 | 500 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 309 | 501 | cluster.manager.connectionFactory = factory; |
| 310 | 502 | Connection connection1 = pool.connections.get(0); |
| 311 | 503 | |
| 312 | - requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1))); | |
| 504 | + List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); | |
| 505 | + assertBorrowedConnection(requests, connection1); | |
| 506 | + allRequests.addAll(requests); | |
| 507 | + allRequests.add(MockRequest.send(pool)); | |
| 313 | 508 | |
| 314 | 509 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 315 | 510 | assertPoolSize(pool, 2); |
| @@ -320,7 +515,7 @@ | ||
| 320 | 515 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| 321 | 516 | |
| 322 | 517 | // Go back under the capacity of 1 connection |
| 323 | - completeRequests(51, requests); | |
| 518 | + MockRequest.completeMany(51, allRequests); | |
| 324 | 519 | |
| 325 | 520 | assertThat(connection1.inFlight.get()).isEqualTo(50); |
| 326 | 521 | assertThat(connection2.inFlight.get()).isEqualTo(0); |
| @@ -331,7 +526,7 @@ | ||
| 331 | 526 | assertThat(pool.trash).containsExactly(connection1); |
| 332 | 527 | |
| 333 | 528 | // Return trashed connection down to 0 inFlight |
| 334 | - completeRequests(50, requests); | |
| 529 | + MockRequest.completeMany(50, allRequests); | |
| 335 | 530 | assertThat(connection1.inFlight.get()).isEqualTo(0); |
| 336 | 531 | |
| 337 | 532 | // Give enough time for trashed connection to be cleaned up from the trash: |
| @@ -341,19 +536,22 @@ | ||
| 341 | 536 | assertThat(connection1.isClosed()).isTrue(); |
| 342 | 537 | |
| 343 | 538 | // Fill the live connection to go over the threshold where a second one is needed |
| 344 | - requests.addAll(fillConnectionToThreshold(pool, singletonList(connection2))); | |
| 539 | + requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); | |
| 540 | + assertBorrowedConnection(requests, connection2); | |
| 541 | + allRequests.addAll(requests); | |
| 542 | + allRequests.add(MockRequest.send(pool)); | |
| 345 | 543 | assertThat(connection2.inFlight.get()).isEqualTo(101); |
| 346 | 544 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 347 | 545 | assertPoolSize(pool, 2); |
| 348 | 546 | |
| 349 | 547 | // Borrow again to get the new connection |
| 350 | 548 | MockRequest request = MockRequest.send(pool); |
| 351 | - requests.add(request); | |
| 352 | - assertThat(request.connection) | |
| 549 | + allRequests.add(request); | |
| 550 | + assertThat(request.getConnection()) | |
| 353 | 551 | .isNotEqualTo(connection2) // should not be the full connection |
| 354 | 552 | .isNotEqualTo(connection1); // should not be the previously trashed one |
| 355 | 553 | } finally { |
| 356 | - completeRequests(requests); | |
| 554 | + MockRequest.completeAll(allRequests); | |
| 357 | 555 | cluster.close(); |
| 358 | 556 | } |
| 359 | 557 | } |
| @@ -368,7 +566,7 @@ | ||
| 368 | 566 | @Test(groups = "long") |
| 369 | 567 | public void should_not_close_trashed_connection_until_no_in_flight() throws Exception { |
| 370 | 568 | Cluster cluster = createClusterBuilder().withPoolingOptions(new PoolingOptions().setIdleTimeoutSeconds(20)).build(); |
| 371 | - List<MockRequest> requests = newArrayList(); | |
| 569 | + List<MockRequest> allRequests = newArrayList(); | |
| 372 | 570 | |
| 373 | 571 | try { |
| 374 | 572 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| @@ -377,13 +575,16 @@ | ||
| 377 | 575 | Connection connection1 = pool.connections.get(0); |
| 378 | 576 | |
| 379 | 577 | // Fill core connection enough to trigger creation of another one |
| 380 | - requests.addAll(fillConnectionToThreshold(pool, singletonList(connection1))); | |
| 578 | + List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); | |
| 579 | + assertBorrowedConnections(requests, Collections.singletonList(connection1)); | |
| 580 | + allRequests.addAll(requests); | |
| 581 | + allRequests.add(MockRequest.send(pool)); | |
| 381 | 582 | |
| 382 | 583 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 383 | 584 | assertThat(pool.connections).hasSize(2); |
| 384 | 585 | |
| 385 | 586 | // Return enough times to get back under the threshold where one connection is enough |
| 386 | - completeRequests(50, requests); | |
| 587 | + MockRequest.completeMany(50, allRequests); | |
| 387 | 588 | |
| 388 | 589 | // Give enough time for one connection to be trashed. Due to the implementation, this will be the first one. |
| 389 | 590 | // It still has in-flight requests so should not get closed. |
| @@ -393,7 +594,7 @@ | ||
| 393 | 594 | assertThat(connection1.isClosed()).isFalse(); |
| 394 | 595 | |
| 395 | 596 | // Consume all inFlight requests on the trashed connection. |
| 396 | - completeRequests(51, requests); | |
| 597 | + MockRequest.completeMany(51, allRequests); | |
| 397 | 598 | |
| 398 | 599 | // Sleep enough time for the connection to be consider idled and closed. |
| 399 | 600 | Uninterruptibles.sleepUninterruptibly(30, TimeUnit.SECONDS); |
| @@ -404,7 +605,7 @@ | ||
| 404 | 605 | assertThat(pool.connections).doesNotContain(connection1); |
| 405 | 606 | assertThat(pool.trash).doesNotContain(connection1); |
| 406 | 607 | } finally { |
| 407 | - completeRequests(requests); | |
| 608 | + MockRequest.completeAll(allRequests); | |
| 408 | 609 | cluster.close(); |
| 409 | 610 | } |
| 410 | 611 | } |
| @@ -420,14 +621,17 @@ | ||
| 420 | 621 | @Test(groups = "short") |
| 421 | 622 | public void should_trash_on_returning_connection_with_insufficient_streams() throws Exception { |
| 422 | 623 | Cluster cluster = createClusterBuilder().build(); |
| 423 | - List<MockRequest> requests = newArrayList(); | |
| 624 | + List<MockRequest> allRequests = newArrayList(); | |
| 424 | 625 | try { |
| 425 | 626 | HostConnectionPool pool = createPool(cluster, 1, 2); |
| 426 | 627 | Connection.Factory factory = spy(cluster.manager.connectionFactory); |
| 427 | 628 | cluster.manager.connectionFactory = factory; |
| 428 | 629 | Connection core = pool.connections.get(0); |
| 429 | 630 | |
| 430 | - requests.addAll(fillConnectionToThreshold(pool, singletonList(core))); | |
| 631 | + List<MockRequest> requests = MockRequest.sendMany(NEW_CONNECTION_THRESHOLD, pool); | |
| 632 | + assertBorrowedConnections(requests, Collections.singletonList(core)); | |
| 633 | + allRequests.addAll(requests); | |
| 634 | + allRequests.add(MockRequest.send(pool)); | |
| 431 | 635 | |
| 432 | 636 | verify(factory, after(2000).times(1)).open(any(HostConnectionPool.class)); |
| 433 | 637 | assertThat(pool.connections).hasSize(2); |
| @@ -437,7 +641,7 @@ | ||
| 437 | 641 | pool.connections.set(1, extra1); |
| 438 | 642 | |
| 439 | 643 | // Borrow 10 times to ensure pool is utilized. |
| 440 | - requests.addAll(sendRequests(10, pool)); | |
| 644 | + allRequests.addAll(MockRequest.sendMany(10, pool)); | |
| 441 | 645 | assertThat(pool.connections).hasSize(2); |
| 442 | 646 | |
| 443 | 647 | // stub the maxAvailableStreams method to return 0, indicating there are no remaining streams. |
| @@ -449,7 +653,7 @@ | ||
| 449 | 653 | pool.returnConnection(extra1); |
| 450 | 654 | assertThat(pool.trash).hasSize(1); |
| 451 | 655 | } finally { |
| 452 | - completeRequests(requests); | |
| 656 | + MockRequest.completeAll(allRequests); | |
| 453 | 657 | cluster.close(); |
| 454 | 658 | } |
| 455 | 659 | } |
| @@ -486,7 +690,6 @@ | ||
| 486 | 690 | } |
| 487 | 691 | } |
| 488 | 692 | |
| 489 | - | |
| 490 | 693 | /** |
| 491 | 694 | * Ensures that if all connections on a host are closed that the host is marked |
| 492 | 695 | * down and the control connection is notified of that fact and re-established |
| @@ -561,7 +764,6 @@ | ||
| 561 | 764 | } |
| 562 | 765 | } |
| 563 | 766 | |
| 564 | - | |
| 565 | 767 | /** |
| 566 | 768 | * Ensures that if a connection on a host is lost that brings the number of active connections in a pool |
| 567 | 769 | * under core connection count that up to core connections are re-established, but only after the |
| @@ -580,7 +782,7 @@ | ||
| 580 | 782 | .setConnectTimeoutMillis(readTimeout) |
| 581 | 783 | .setReadTimeoutMillis(reconnectInterval)) |
| 582 | 784 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); |
| 583 | - List<MockRequest> requests = newArrayList(); | |
| 785 | + List<MockRequest> allRequests = newArrayList(); | |
| 584 | 786 | try { |
| 585 | 787 | cluster.init(); |
| 586 | 788 | |
| @@ -608,8 +810,8 @@ | ||
| 608 | 810 | |
| 609 | 811 | // The borrowed connection should be the open one. |
| 610 | 812 | MockRequest request = MockRequest.send(pool); |
| 611 | - requests.add(request); | |
| 612 | - assertThat(request.connection).isEqualTo(core1); | |
| 813 | + allRequests.add(request); | |
| 814 | + assertThat(request.getConnection()).isEqualTo(core1); | |
| 613 | 815 | |
| 614 | 816 | // Should not have tried to create a new core connection since reconnection time had not elapsed. |
| 615 | 817 | verify(factory, never()).open(any(HostConnectionPool.class)); |
| @@ -620,8 +822,8 @@ | ||
| 620 | 822 | // Attempt to borrow connection, this should trigger ensureCoreConnections thus spawning a new connection. |
| 621 | 823 | blockingExecutor.reset(); |
| 622 | 824 | request = MockRequest.send(pool); |
| 623 | - requests.add(request); | |
| 624 | - assertThat(request.connection).isEqualTo(core1); | |
| 825 | + allRequests.add(request); | |
| 826 | + assertThat(request.getConnection()).isEqualTo(core1); | |
| 625 | 827 | |
| 626 | 828 | // Should have tried to open up to core connections as result of borrowing a connection past reconnect time and not being at core. |
| 627 | 829 | blockingExecutor.blockUntilNextTaskCompleted(); |
| @@ -638,23 +840,23 @@ | ||
| 638 | 840 | |
| 639 | 841 | // Try to borrow a connection, the pool should grow. |
| 640 | 842 | blockingExecutor.reset(); |
| 641 | - requests.add(MockRequest.send(pool)); | |
| 843 | + allRequests.add(MockRequest.send(pool)); | |
| 642 | 844 | blockingExecutor.blockUntilNextTaskCompleted(); |
| 643 | 845 | verify(factory).open(any(HostConnectionPool.class)); |
| 644 | 846 | reset(factory); |
| 645 | 847 | |
| 646 | 848 | // Another core connection should be opened as result of another request to get us up to core connections. |
| 647 | 849 | blockingExecutor.reset(); |
| 648 | - requests.add(MockRequest.send(pool)); | |
| 850 | + allRequests.add(MockRequest.send(pool)); | |
| 649 | 851 | blockingExecutor.blockUntilNextTaskCompleted(); |
| 650 | 852 | verify(factory).open(any(HostConnectionPool.class)); |
| 651 | 853 | reset(factory); |
| 652 | 854 | |
| 653 | 855 | // Sending another request should not grow the pool any more, since we are now at core connections. |
| 654 | - requests.add(MockRequest.send(pool)); | |
| 856 | + allRequests.add(MockRequest.send(pool)); | |
| 655 | 857 | verify(factory, after((reconnectInterval + readTimeout) * 2).never()).open(any(HostConnectionPool.class)); |
| 656 | 858 | } finally { |
| 657 | - completeRequests(requests); | |
| 859 | + MockRequest.completeAll(allRequests); | |
| 658 | 860 | cluster.close(); |
| 659 | 861 | } |
| 660 | 862 | } |
| @@ -677,7 +879,7 @@ | ||
| 677 | 879 | .setConnectTimeoutMillis(readTimeout) |
| 678 | 880 | .setReadTimeoutMillis(reconnectInterval)) |
| 679 | 881 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); |
| 680 | - List<MockRequest> requests = newArrayList(); | |
| 882 | + List<MockRequest> allRequests = newArrayList(); | |
| 681 | 883 | try { |
| 682 | 884 | cluster.init(); |
| 683 | 885 | |
| @@ -691,7 +893,7 @@ | ||
| 691 | 893 | List<MockRequest> core0requests = newArrayList(); |
| 692 | 894 | for (int i = 0; i < 101; i++) { |
| 693 | 895 | MockRequest request = MockRequest.send(pool); |
| 694 | - assertThat(request.connection).isEqualTo(core0); | |
| 896 | + assertThat(request.getConnection()).isEqualTo(core0); | |
| 695 | 897 | core0requests.add(request); |
| 696 | 898 | } |
| 697 | 899 | |
| @@ -712,13 +914,15 @@ | ||
| 712 | 914 | |
| 713 | 915 | // Since core0 was closed, all of it's requests should have errored. |
| 714 | 916 | for (MockRequest request : core0requests) { |
| 715 | - verify(request, times(1)).onException(any(Connection.class), any(Exception.class), anyLong(), anyInt()); | |
| 917 | + assertThat(request.state.get()).isEqualTo(MockRequest.State.FAILED); | |
| 716 | 918 | } |
| 717 | 919 | |
| 718 | 920 | assertThat(cluster).host(1).hasState(Host.State.UP); |
| 719 | 921 | |
| 720 | 922 | // Create enough inFlight requests to fill connection. |
| 721 | - requests.addAll(sendRequests(100, pool, singletonList(extra1))); | |
| 923 | + List<MockRequest> requests = MockRequest.sendMany(100, pool); | |
| 924 | + assertBorrowedConnections(requests, Collections.singletonList(extra1)); | |
| 925 | + allRequests.addAll(requests); | |
| 722 | 926 | assertThat(pool.connections).hasSize(1); |
| 723 | 927 | |
| 724 | 928 | // A new connection should never have been spawned since we didn't max out core. |
| @@ -726,8 +930,8 @@ | ||
| 726 | 930 | |
| 727 | 931 | // Borrow another connection, since we exceed max another connection should be opened. |
| 728 | 932 | MockRequest request = MockRequest.send(pool); |
| 729 | - requests.add(request); | |
| 730 | - assertThat(request.connection).isEqualTo(extra1); | |
| 933 | + allRequests.add(request); | |
| 934 | + assertThat(request.getConnection()).isEqualTo(extra1); | |
| 731 | 935 | |
| 732 | 936 | // After some time the a connection should attempt to be opened (but will fail). |
| 733 | 937 | verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class)); |
| @@ -745,8 +949,8 @@ | ||
| 745 | 949 | |
| 746 | 950 | // Borrow another connection, since we exceed max another connection should be opened. |
| 747 | 951 | request = MockRequest.send(pool); |
| 748 | - requests.add(request); | |
| 749 | - assertThat(request.connection).isEqualTo(extra1); | |
| 952 | + allRequests.add(request); | |
| 953 | + assertThat(request.getConnection()).isEqualTo(extra1); | |
| 750 | 954 | |
| 751 | 955 | // Wait some reasonable amount of time for connection to reestablish then check pool size. |
| 752 | 956 | Uninterruptibles.sleepUninterruptibly(readTimeout, TimeUnit.MILLISECONDS); |
| @@ -755,10 +959,10 @@ | ||
| 755 | 959 | |
| 756 | 960 | // Borrowed connection should be the newly spawned connection since the other one has some inflight requests. |
| 757 | 961 | request = MockRequest.send(pool); |
| 758 | - requests.add(request); | |
| 759 | - assertThat(request.connection).isNotEqualTo(core0).isNotEqualTo(extra1); | |
| 962 | + allRequests.add(request); | |
| 963 | + assertThat(request.getConnection()).isNotEqualTo(core0).isNotEqualTo(extra1); | |
| 760 | 964 | } finally { |
| 761 | - completeRequests(requests); | |
| 965 | + MockRequest.completeAll(allRequests); | |
| 762 | 966 | cluster.close(); |
| 763 | 967 | } |
| 764 | 968 | } |
| @@ -781,7 +985,7 @@ | ||
| 781 | 985 | .setConnectTimeoutMillis(readTimeout) |
| 782 | 986 | .setReadTimeoutMillis(reconnectInterval)) |
| 783 | 987 | .withReconnectionPolicy(new ConstantReconnectionPolicy(1000)).build(); |
| 784 | - List<MockRequest> requests = newArrayList(); | |
| 988 | + List<MockRequest> allRequests = newArrayList(); | |
| 785 | 989 | try { |
| 786 | 990 | cluster.init(); |
| 787 | 991 | |
| @@ -811,13 +1015,13 @@ | ||
| 811 | 1015 | // we need to wait for connections to be established between requests for the pool |
| 812 | 1016 | // to spawn new connections (since it only allows one simultaneous creation). |
| 813 | 1017 | for (int i = 5; i <= 8; i++) { |
| 814 | - requests.add(MockRequest.send(pool)); | |
| 1018 | + allRequests.add(MockRequest.send(pool)); | |
| 815 | 1019 | verify(factory, timeout(readTimeout)).open(any(HostConnectionPool.class)); |
| 816 | 1020 | reset(factory); |
| 817 | 1021 | assertPoolSize(pool, i); |
| 818 | 1022 | } |
| 819 | 1023 | } finally { |
| 820 | - completeRequests(requests); | |
| 1024 | + MockRequest.completeAll(allRequests); | |
| 821 | 1025 | cluster.close(); |
| 822 | 1026 | } |
| 823 | 1027 | } |
| @@ -825,15 +1029,15 @@ | ||
| 825 | 1029 | /** |
| 826 | 1030 | * Ensures that if all connections fail on pool init that the host and subsequently the |
| 827 | 1031 | * control connection is not marked down since the control connection is still active. |
| 828 | - * on the pool that a TimeoutException is yielded if we are still in the reconnection window | |
| 1032 | + * The test also ensures that borrow attempts on the pool fail if we are still in the reconnection window | |
| 829 | 1033 | * according to the ConvictionPolicy. |
| 830 | 1034 | * |
| 831 | 1035 | * @jira_ticket JAVA-544 |
| 832 | 1036 | * @test_category connection:connection_pool |
| 833 | 1037 | * @since 2.0.11 |
| 834 | 1038 | */ |
| 835 | - @Test(groups = "short", expectedExceptions = TimeoutException.class) | |
| 836 | - public void should_throw_exception_if_convicted_and_no_connections_available() throws Exception { | |
| 1039 | + @Test(groups = "short") | |
| 1040 | + public void should_throw_exception_if_convicted_and_no_connections_available() { | |
| 837 | 1041 | int readTimeout = 1000; |
| 838 | 1042 | int reconnectInterval = 1000; |
| 839 | 1043 | Cluster cluster = this.createClusterBuilder() |
| @@ -862,16 +1066,19 @@ | ||
| 862 | 1066 | assertThat(cluster).host(1).hasState(Host.State.UP); |
| 863 | 1067 | assertThat(cluster).hasOpenControlConnection(); |
| 864 | 1068 | |
| 865 | - MockRequest.send(pool); | |
| 1069 | + MockRequest failedBorrow = MockRequest.send(pool); | |
| 1070 | + try { | |
| 1071 | + failedBorrow.getConnection(); | |
| 1072 | + fail("Expected a BusyPoolException"); | |
| 1073 | + } catch (BusyPoolException e) { /*expected*/} | |
| 866 | 1074 | } finally { |
| 867 | 1075 | cluster.close(); |
| 868 | 1076 | } |
| 869 | 1077 | } |
| 870 | 1078 | |
| 871 | - | |
| 872 | 1079 | /** |
| 873 | 1080 | * Ensures that if all connections fail on pool init that the host and subsequently the |
| 874 | - * control connection is not marked down. The test also ensures that when making requests | |
| 1081 | + * control connection is not marked down. The test also ensures that when making requests | |
| 875 | 1082 | * on the pool after the conviction period that all core connections are created. |
| 876 | 1083 | * |
| 877 | 1084 | * @jira_ticket JAVA-544 |
| @@ -912,12 +1119,13 @@ | ||
| 912 | 1119 | Uninterruptibles.sleepUninterruptibly(reconnectInterval, TimeUnit.MILLISECONDS); |
| 913 | 1120 | |
| 914 | 1121 | reset(factory); |
| 915 | - MockRequest request = MockRequest.send(pool); | |
| 916 | - request.simulateSuccessResponse(); | |
| 1122 | + MockRequest request = MockRequest.send(pool, 1); | |
| 917 | 1123 | |
| 918 | 1124 | // Should create up to core connections. |
| 919 | 1125 | verify(factory, timeout(readTimeout * 8).times(8)).open(any(HostConnectionPool.class)); |
| 920 | 1126 | assertPoolSize(pool, 8); |
| 1127 | + | |
| 1128 | + request.simulateSuccessResponse(); | |
| 921 | 1129 | } finally { |
| 922 | 1130 | cluster.close(); |
| 923 | 1131 | } |
| @@ -946,6 +1154,9 @@ | ||
| 946 | 1154 | cluster.init(); |
| 947 | 1155 | assertThat(cluster).hasOpenControlConnection(); |
| 948 | 1156 | |
| 1157 | + Connection.Factory factory = spy(cluster.manager.connectionFactory); | |
| 1158 | + cluster.manager.connectionFactory = factory; | |
| 1159 | + | |
| 949 | 1160 | HostConnectionPool pool = createPool(cluster, 0, 2); |
| 950 | 1161 | |
| 951 | 1162 | // Pool should be empty. |
| @@ -955,12 +1166,14 @@ | ||
| 955 | 1166 | assertThat(cluster).host(1).hasState(Host.State.UP); |
| 956 | 1167 | assertThat(cluster).hasOpenControlConnection(); |
| 957 | 1168 | |
| 958 | - // Send a request, this should create a connection. | |
| 959 | - MockRequest request = MockRequest.send(pool); | |
| 960 | - request.simulateSuccessResponse(); | |
| 1169 | + reset(factory); | |
| 1170 | + MockRequest request = MockRequest.send(pool, 1); | |
| 961 | 1171 | |
| 962 | 1172 | // Should create up to core connections. |
| 1173 | + verify(factory, timeout(readTimeout).times(1)).open(any(HostConnectionPool.class)); | |
| 963 | 1174 | assertThat(pool.connections).hasSize(1); |
| 1175 | + | |
| 1176 | + request.simulateSuccessResponse(); | |
| 964 | 1177 | } finally { |
| 965 | 1178 | cluster.close(); |
| 966 | 1179 | } |
| @@ -979,10 +1192,10 @@ | ||
| 979 | 1192 | } |
| 980 | 1193 | |
| 981 | 1194 | /** |
| 982 | - * <p> | |
| 1195 | + * <p/> | |
| 983 | 1196 | * This test uses a table named "Java349" with 1000 column and performs asynchronously 100k insertions. While the |
| 984 | 1197 | * insertions are being executed, the number of opened connection is monitored. |
| 985 | - * <p> | |
| 1198 | + * <p/> | |
| 986 | 1199 | * If at anytime, the number of opened connections is negative, this test will fail. |
| 987 | 1200 | * |
| 988 | 1201 | * @jira_ticket JAVA-349 |
| @@ -1061,51 +1274,115 @@ | ||
| 1061 | 1274 | |
| 1062 | 1275 | enum State {START, COMPLETED, FAILED, TIMED_OUT} |
| 1063 | 1276 | |
| 1064 | - final Connection connection; | |
| 1065 | - private Connection.ResponseHandler responseHandler; | |
| 1277 | + final ListenableFuture<Connection> connectionFuture; | |
| 1278 | + private volatile Connection.ResponseHandler responseHandler; | |
| 1279 | + | |
| 1280 | + final AtomicReference<State> state = new AtomicReference<State>(State.START); | |
| 1281 | + | |
| 1282 | + static MockRequest send(HostConnectionPool pool) { | |
| 1283 | + return send(pool, 0); | |
| 1284 | + } | |
| 1285 | + | |
| 1286 | + static MockRequest send(HostConnectionPool pool, int maxQueueSize) throws ConnectionException, BusyConnectionException { | |
| 1287 | + return new MockRequest(pool, maxQueueSize); | |
| 1288 | + } | |
| 1289 | + | |
| 1290 | + private static List<MockRequest> sendMany(int count, HostConnectionPool pool) throws ConnectionException { | |
| 1291 | + return sendMany(count, pool, 0); | |
| 1292 | + } | |
| 1293 | + | |
| 1294 | + private static List<MockRequest> sendMany(int count, HostConnectionPool pool, int maxQueueSize) throws ConnectionException { | |
| 1295 | + List<MockRequest> requests = newArrayList(); | |
| 1296 | + for (int i = 0; i < count; i++) { | |
| 1297 | + MockRequest request = send(pool, maxQueueSize); | |
| 1298 | + requests.add(request); | |
| 1299 | + } | |
| 1300 | + return requests; | |
| 1301 | + } | |
| 1066 | 1302 | |
| 1067 | - private final AtomicReference<State> state = new AtomicReference<State>(State.START); | |
| 1303 | + /** | |
| 1304 | + * Completes count requests by simulating a successful response. | |
| 1305 | + */ | |
| 1306 | + private static void completeMany(int count, List<MockRequest> requests) { | |
| 1307 | + Iterator<MockRequest> requestIt = requests.iterator(); | |
| 1308 | + for (int i = 0; i < count; i++) { | |
| 1309 | + if (requestIt.hasNext()) { | |
| 1310 | + MockRequest request = requestIt.next(); | |
| 1311 | + request.simulateSuccessResponse(); | |
| 1312 | + requestIt.remove(); | |
| 1313 | + } else { | |
| 1314 | + break; | |
| 1315 | + } | |
| 1316 | + } | |
| 1317 | + } | |
| 1068 | 1318 | |
| 1069 | - static MockRequest send(HostConnectionPool pool) throws ConnectionException, BusyConnectionException, TimeoutException { | |
| 1070 | - // Create a MockRequest and spy on it. Create a response handler and add it to the connection's dispatcher. | |
| 1071 | - MockRequest request = spy(new MockRequest(pool)); | |
| 1072 | - request.responseHandler = new Connection.ResponseHandler(request.connection, -1, request); | |
| 1073 | - request.connection.dispatcher.add(request.responseHandler); | |
| 1074 | - return request; | |
| 1319 | + /** | |
| 1320 | + * Completes all requests by simulating a successful response. | |
| 1321 | + */ | |
| 1322 | + private static void completeAll(List<MockRequest> requests) { | |
| 1323 | + for (MockRequest request : requests) { | |
| 1324 | + request.simulateSuccessResponse(); | |
| 1325 | + } | |
| 1075 | 1326 | } |
| 1076 | 1327 | |
| 1077 | - private MockRequest(HostConnectionPool pool) throws ConnectionException, TimeoutException, BusyConnectionException { | |
| 1078 | - connection = pool.borrowConnection(500, TimeUnit.MILLISECONDS); | |
| 1328 | + private MockRequest(HostConnectionPool pool, int maxQueueSize) throws ConnectionException { | |
| 1329 | + this.connectionFuture = pool.borrowConnection(maxQueueSize); | |
| 1330 | + Futures.addCallback(this.connectionFuture, new MoreFutures.SuccessCallback<Connection>() { | |
| 1331 | + @Override | |
| 1332 | + public void onSuccess(Connection connection) { | |
| 1333 | + MockRequest thisRequest = MockRequest.this; | |
| 1334 | + thisRequest.responseHandler = new Connection.ResponseHandler(connection, -1, thisRequest); | |
| 1335 | + connection.dispatcher.add(thisRequest.responseHandler); | |
| 1336 | + } | |
| 1337 | + }); | |
| 1079 | 1338 | } |
| 1080 | 1339 | |
| 1081 | 1340 | void simulateSuccessResponse() { |
| 1082 | - onSet(connection, null, 0, 0); | |
| 1341 | + onSet(getConnection(), null, 0, 0); | |
| 1083 | 1342 | } |
| 1084 | 1343 | |
| 1085 | 1344 | @SuppressWarnings("unused") |
| 1086 | 1345 | void simulateErrorResponse() { |
| 1087 | - onException(connection, null, 0, 0); | |
| 1346 | + onException(getConnection(), null, 0, 0); | |
| 1088 | 1347 | } |
| 1089 | 1348 | |
| 1090 | 1349 | @SuppressWarnings("unused") |
| 1091 | 1350 | void simulateTimeout() { |
| 1092 | - if (onTimeout(connection, 0, 0)) | |
| 1351 | + if (onTimeout(getConnection(), 0, 0)) | |
| 1093 | 1352 | responseHandler.cancelHandler(); |
| 1094 | 1353 | } |
| 1095 | 1354 | |
| 1355 | + // Get the connection, assuming pool acquisition completed | |
| 1356 | + Connection getConnection() { | |
| 1357 | + try { | |
| 1358 | + if (!connectionFuture.isDone()) { | |
| 1359 | + throw new AssertionError("Borrow call did not complete"); | |
| 1360 | + } | |
| 1361 | + return Uninterruptibles.getUninterruptibly(connectionFuture); | |
| 1362 | + } catch (ExecutionException e) { | |
| 1363 | + throw Throwables.propagate(e.getCause()); | |
| 1364 | + } | |
| 1365 | + } | |
| 1366 | + | |
| 1096 | 1367 | @Override |
| 1097 | 1368 | public void onSet(Connection connection, Message.Response response, long latency, int retryCount) { |
| 1369 | + assertThat(connectionFuture.isDone()).isTrue(); | |
| 1370 | + try { | |
| 1371 | + assertThat(Uninterruptibles.getUninterruptibly(connectionFuture)).isNotNull(); | |
| 1372 | + } catch (ExecutionException e) { | |
| 1373 | + Throwables.propagate(e.getCause()); | |
| 1374 | + } | |
| 1098 | 1375 | if (state.compareAndSet(State.START, State.COMPLETED)) { |
| 1099 | - connection.release(); | |
| 1100 | 1376 | connection.dispatcher.removeHandler(responseHandler, true); |
| 1377 | + connection.release(); | |
| 1101 | 1378 | } |
| 1102 | 1379 | } |
| 1103 | 1380 | |
| 1104 | 1381 | @Override |
| 1105 | 1382 | public void onException(Connection connection, Exception exception, long latency, int retryCount) { |
| 1106 | 1383 | if (state.compareAndSet(State.START, State.FAILED)) { |
| 1107 | - connection.release(); | |
| 1108 | 1384 | connection.dispatcher.removeHandler(responseHandler, true); |
| 1385 | + connection.release(); | |
| 1109 | 1386 | } |
| 1110 | 1387 | } |
| 1111 | 1388 |
modified driver-core/src/test/java/com/datastax/driver/core/ParseUtilsTest.java +45 −0
| @@ -43,6 +43,9 @@ | ||
| 43 | 43 | assertThat(ParseUtils.unquote("'foo'")).isEqualTo("foo"); |
| 44 | 44 | assertThat(ParseUtils.unquote(" 'foo' ")).isEqualTo(" 'foo' "); // considered unquoted |
| 45 | 45 | assertThat(ParseUtils.unquote("'''foo'''")).isEqualTo("'foo'"); |
| 46 | + assertThat(ParseUtils.unquote("'''")).isEqualTo("'"); | |
| 47 | + assertThat(ParseUtils.unquote("''foo'")).isEqualTo("'foo"); | |
| 48 | + assertThat(ParseUtils.unquote("'foo''")).isEqualTo("foo'"); | |
| 46 | 49 | } |
| 47 | 50 | |
| 48 | 51 | @Test(groups = "unit") |
| @@ -60,4 +63,46 @@ | ||
| 60 | 63 | assertThat(ParseUtils.isQuoted("'''foo'''")).isTrue(); |
| 61 | 64 | } |
| 62 | 65 | |
| 66 | + @Test(groups = "unit") | |
| 67 | + public void testDoubleQuote() { | |
| 68 | + assertThat(ParseUtils.doubleQuote(null)).isEqualTo("\"\""); | |
| 69 | + assertThat(ParseUtils.doubleQuote("")).isEqualTo("\"\""); | |
| 70 | + assertThat(ParseUtils.doubleQuote(" ")).isEqualTo("\" \""); | |
| 71 | + assertThat(ParseUtils.doubleQuote("foo")).isEqualTo("\"foo\""); | |
| 72 | + assertThat(ParseUtils.doubleQuote(" \"foo\" ")).isEqualTo("\" \"\"foo\"\" \""); | |
| 73 | + } | |
| 74 | + | |
| 75 | + @Test(groups = "unit") | |
| 76 | + public void testDoubleUnquote() { | |
| 77 | + assertThat(ParseUtils.unDoubleQuote(null)).isNull(); | |
| 78 | + assertThat(ParseUtils.unDoubleQuote("")).isEqualTo(""); | |
| 79 | + assertThat(ParseUtils.unDoubleQuote(" ")).isEqualTo(" "); | |
| 80 | + assertThat(ParseUtils.unDoubleQuote("\"")).isEqualTo("\""); // malformed string left untouched | |
| 81 | + assertThat(ParseUtils.unDoubleQuote("foo")).isEqualTo("foo"); | |
| 82 | + assertThat(ParseUtils.unDoubleQuote("\"\"")).isEqualTo(""); | |
| 83 | + assertThat(ParseUtils.unDoubleQuote("\" \"")).isEqualTo(" "); | |
| 84 | + assertThat(ParseUtils.unDoubleQuote("\"foo")).isEqualTo("\"foo"); // malformed string left untouched | |
| 85 | + assertThat(ParseUtils.unDoubleQuote("\"foo\"")).isEqualTo("foo"); | |
| 86 | + assertThat(ParseUtils.unDoubleQuote(" \"foo\" ")).isEqualTo(" \"foo\" "); // considered unquoted | |
| 87 | + assertThat(ParseUtils.unDoubleQuote("\"\"\"foo\"\"\"")).isEqualTo("\"foo\""); | |
| 88 | + assertThat(ParseUtils.unDoubleQuote("\"\"\"")).isEqualTo("\""); | |
| 89 | + assertThat(ParseUtils.unDoubleQuote("\"\"foo\"")).isEqualTo("\"foo"); | |
| 90 | + assertThat(ParseUtils.unDoubleQuote("\"foo\"\"")).isEqualTo("foo\""); | |
| 91 | + } | |
| 92 | + | |
| 93 | + @Test(groups = "unit") | |
| 94 | + public void testIsDoubleQuoted() { | |
| 95 | + assertThat(ParseUtils.isDoubleQuoted(null)).isFalse(); | |
| 96 | + assertThat(ParseUtils.isDoubleQuoted("")).isFalse(); | |
| 97 | + assertThat(ParseUtils.isDoubleQuoted(" ")).isFalse(); | |
| 98 | + assertThat(ParseUtils.isDoubleQuoted("\"")).isFalse(); // malformed string considered unquoted | |
| 99 | + assertThat(ParseUtils.isDoubleQuoted("foo")).isFalse(); | |
| 100 | + assertThat(ParseUtils.isDoubleQuoted("\"\"")).isTrue(); | |
| 101 | + assertThat(ParseUtils.isDoubleQuoted("\" \"")).isTrue(); | |
| 102 | + assertThat(ParseUtils.isDoubleQuoted("\"foo")).isFalse(); // malformed string considered unquoted | |
| 103 | + assertThat(ParseUtils.isDoubleQuoted("\"foo\"")).isTrue(); | |
| 104 | + assertThat(ParseUtils.isDoubleQuoted(" \"foo\" ")).isFalse(); // considered unquoted | |
| 105 | + assertThat(ParseUtils.isDoubleQuoted("\"\"\"foo\"\"\"")).isTrue(); | |
| 106 | + } | |
| 107 | + | |
| 63 | 108 | } |
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +6 −2
| @@ -106,15 +106,19 @@ | ||
| 106 | 106 | ccm().start(1); |
| 107 | 107 | ccm().waitForUp(1); |
| 108 | 108 | |
| 109 | - // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least once | |
| 109 | + // Wait a few iterations to ensure that our authProvider has returned the wrong credentials at least twice | |
| 110 | 110 | // NB: authentication errors show up in the logs |
| 111 | 111 | int initialCount = authProvider.count.get(); |
| 112 | + long initialMetricCount = cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount(); | |
| 112 | 113 | int iterations = 0, maxIterations = 12; // make sure we don't wait indefinitely |
| 113 | 114 | do { |
| 114 | 115 | iterations += 1; |
| 115 | 116 | TimeUnit.SECONDS.sleep(5); |
| 116 | - } while (iterations < maxIterations && authProvider.count.get() <= initialCount); | |
| 117 | + } while (iterations < maxIterations && authProvider.count.get() <= initialCount + 1); | |
| 117 | 118 | assertThat(iterations).isLessThan(maxIterations); |
| 119 | + // Number of authentication errors should have increased. | |
| 120 | + assertThat(cluster.getMetrics().getErrorMetrics().getAuthenticationErrors().getCount()) | |
| 121 | + .isGreaterThan(initialMetricCount); | |
| 118 | 122 | |
| 119 | 123 | // Fix the credentials |
| 120 | 124 | authProvider.setPassword("cassandra"); |
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +1 −52
| @@ -16,7 +16,6 @@ | ||
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.exceptions.SyntaxError; |
| 19 | -import com.datastax.driver.core.utils.CassandraVersion; | |
| 20 | 19 | import com.google.common.util.concurrent.ListenableFuture; |
| 21 | 20 | import org.testng.annotations.Test; |
| 22 | 21 | |
| @@ -81,7 +80,7 @@ | ||
| 81 | 80 | checkExecuteResultSet(session().executeAsync(bs.setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key); |
| 82 | 81 | } |
| 83 | 82 | |
| 84 | - private static void checkExecuteResultSet(ResultSet rs, String key) { | |
| 83 | + static void checkExecuteResultSet(ResultSet rs, String key) { | |
| 85 | 84 | assertThat(rs.isExhausted()).isFalse(); |
| 86 | 85 | Row row = rs.one(); |
| 87 | 86 | assertThat(rs.isExhausted()).isTrue(); |
| @@ -104,56 +103,6 @@ | ||
| 104 | 103 | assertThat(rows.get(0).getLong("c")).isEqualTo(2L); |
| 105 | 104 | } |
| 106 | 105 | |
| 107 | - /** | |
| 108 | - * Validates that a session can be established using snappy compression and executes some queries that inserts and | |
| 109 | - * retrieves data using that session(). | |
| 110 | - * | |
| 111 | - * @test_category connection:compression | |
| 112 | - * @expected_result session established and queries made successfully using it. | |
| 113 | - */ | |
| 114 | - @Test(groups = "short") | |
| 115 | - public void should_function_with_snappy_compression() throws Exception { | |
| 116 | - compressionTest(ProtocolOptions.Compression.SNAPPY); | |
| 117 | - } | |
| 118 | - | |
| 119 | - /** | |
| 120 | - * Validates that a session can be established using lz4 compression and executes some queries that inserts and | |
| 121 | - * retrieves data using that session(). | |
| 122 | - * | |
| 123 | - * @test_category connection:compression | |
| 124 | - * @expected_result session established and queries made successfully using it. | |
| 125 | - */ | |
| 126 | - @Test(groups = "short") | |
| 127 | - @CassandraVersion(major = 2.0) | |
| 128 | - public void should_function_with_lz4_compression() throws Exception { | |
| 129 | - compressionTest(ProtocolOptions.Compression.LZ4); | |
| 130 | - } | |
| 131 | - | |
| 132 | - public void compressionTest(ProtocolOptions.Compression compression) { | |
| 133 | - cluster().getConfiguration().getProtocolOptions().setCompression(compression); | |
| 134 | - try { | |
| 135 | - Session compressedSession = cluster().connect(keyspace); | |
| 136 | - | |
| 137 | - // Simple calls to all versions of the execute/executeAsync methods | |
| 138 | - String key = "execute_compressed_test_" + compression; | |
| 139 | - ResultSet rs = compressedSession.execute(String.format(Locale.US, "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)", TABLE3, key, "foo", 42, 24.03f)); | |
| 140 | - assertThat(rs.isExhausted()).isTrue(); | |
| 141 | - | |
| 142 | - String SELECT_ALL = String.format(TestUtils.SELECT_ALL_FORMAT + " WHERE k = '%s'", TABLE3, key); | |
| 143 | - | |
| 144 | - // execute | |
| 145 | - checkExecuteResultSet(compressedSession.execute(SELECT_ALL), key); | |
| 146 | - checkExecuteResultSet(compressedSession.execute(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)), key); | |
| 147 | - | |
| 148 | - // executeAsync | |
| 149 | - checkExecuteResultSet(compressedSession.executeAsync(SELECT_ALL).getUninterruptibly(), key); | |
| 150 | - checkExecuteResultSet(compressedSession.executeAsync(new SimpleStatement(SELECT_ALL).setConsistencyLevel(ConsistencyLevel.ONE)).getUninterruptibly(), key); | |
| 151 | - | |
| 152 | - } finally { | |
| 153 | - cluster().getConfiguration().getProtocolOptions().setCompression(ProtocolOptions.Compression.NONE); | |
| 154 | - } | |
| 155 | - } | |
| 156 | - | |
| 157 | 106 | /** |
| 158 | 107 | * Checks for deadlocks when a session shutdown races with the initialization of the cluster (JAVA-418). |
| 159 | 108 | */ |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +1 −1
| @@ -729,7 +729,7 @@ | ||
| 729 | 729 | try { |
| 730 | 730 | socket.close(); |
| 731 | 731 | } catch (IOException e) { |
| 732 | - logger.warn("Error closing socket to " + address); | |
| 732 | + logger.warn("Error closing socket to " + address, e); | |
| 733 | 733 | } |
| 734 | 734 | } |
| 735 | 735 | return connectionSuccessful; |
added driver-core/src/test/java/com/datastax/driver/core/querybuilder/BatchIdempotencyTest.java +47 −0
| @@ -0,0 +1,47 @@ | ||
| 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.querybuilder; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.AbstractBatchIdempotencyTest; | |
| 19 | +import com.datastax.driver.core.RegularStatement; | |
| 20 | + | |
| 21 | +public class BatchIdempotencyTest extends AbstractBatchIdempotencyTest { | |
| 22 | + | |
| 23 | + @Override | |
| 24 | + protected AbstractBatchIdempotencyTest.TestBatch createBatch() { | |
| 25 | + return new TestBatchWrapper(); | |
| 26 | + } | |
| 27 | + | |
| 28 | + static class TestBatchWrapper implements TestBatch { | |
| 29 | + | |
| 30 | + private final Batch batch = QueryBuilder.batch(); | |
| 31 | + | |
| 32 | + @Override | |
| 33 | + public void add(RegularStatement statement) { | |
| 34 | + batch.add(statement); | |
| 35 | + } | |
| 36 | + | |
| 37 | + @Override | |
| 38 | + public Boolean isIdempotent() { | |
| 39 | + return batch.isIdempotent(); | |
| 40 | + } | |
| 41 | + | |
| 42 | + @Override | |
| 43 | + public void setIdempotent(boolean idempotent) { | |
| 44 | + batch.setIdempotent(idempotent); | |
| 45 | + } | |
| 46 | + } | |
| 47 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderRoutingKeyTest.java +64 −1
| @@ -23,17 +23,22 @@ | ||
| 23 | 23 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 24 | 24 | import static org.testng.Assert.assertEquals; |
| 25 | 25 | import static org.testng.Assert.assertNotNull; |
| 26 | +import static org.testng.Assert.assertNull; | |
| 26 | 27 | |
| 27 | 28 | @CCMConfig(clusterProvider = "createClusterBuilderNoDebouncing") |
| 28 | 29 | public class QueryBuilderRoutingKeyTest extends CCMTestsSupport { |
| 29 | 30 | |
| 30 | 31 | private static final String TABLE_TEXT = "test_text"; |
| 31 | 32 | private static final String TABLE_INT = "test_int"; |
| 33 | + private static final String TABLE_CASE = "test_case"; | |
| 34 | + private static final String TABLE_CASE_QUOTED = "test_case_quoted"; | |
| 32 | 35 | |
| 33 | 36 | @Override |
| 34 | 37 | public void onTestContextInitialized() { |
| 35 | 38 | execute(String.format("CREATE TABLE %s (k text PRIMARY KEY, a int, b int)", TABLE_TEXT), |
| 36 | - String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT)); | |
| 39 | + String.format("CREATE TABLE %s (k int PRIMARY KEY, a int, b int)", TABLE_INT), | |
| 40 | + String.format("CREATE TABLE %s (theKey int PRIMARY KEY, a int, b int)", TABLE_CASE), | |
| 41 | + String.format("CREATE TABLE %s (\"theKey\" int PRIMARY KEY, a int, b int, \"tHEkEY\" int)", TABLE_CASE_QUOTED)); | |
| 37 | 42 | } |
| 38 | 43 | |
| 39 | 44 | @Test(groups = "short") |
| @@ -58,6 +63,64 @@ | ||
| 58 | 63 | assertEquals(row.getInt("b"), 2); |
| 59 | 64 | } |
| 60 | 65 | |
| 66 | + @Test(groups = "short") | |
| 67 | + public void routingKeyColumnCaseSensitivityTest() throws Exception { | |
| 68 | + | |
| 69 | + BuiltStatement query; | |
| 70 | + TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_CASE); | |
| 71 | + assertNotNull(table); | |
| 72 | + ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion(); | |
| 73 | + CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE; | |
| 74 | + | |
| 75 | + query = insertInto(table).values(new String[]{"theKey", "a", "b"}, new Object[]{42, 1, 2}); | |
| 76 | + ByteBuffer bb = ByteBuffer.allocate(4); | |
| 77 | + bb.putInt(0, 42); | |
| 78 | + assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb); | |
| 79 | + session().execute(query); | |
| 80 | + | |
| 81 | + query = select().from(table).where(eq("theKey", 42)); | |
| 82 | + assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb); | |
| 83 | + Row row = session().execute(query).one(); | |
| 84 | + assertEquals(row.getInt("theKey"), 42); | |
| 85 | + assertEquals(row.getInt("a"), 1); | |
| 86 | + assertEquals(row.getInt("b"), 2); | |
| 87 | + | |
| 88 | + query = insertInto(table).values(new String[]{"ThEkEy", "a", "b"}, new Object[]{42, 1, 2}); | |
| 89 | + bb = ByteBuffer.allocate(4); | |
| 90 | + bb.putInt(0, 42); | |
| 91 | + assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb); | |
| 92 | + session().execute(query); | |
| 93 | + | |
| 94 | + query = select().from(table).where(eq("ThEkEy", 42)); | |
| 95 | + assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb); | |
| 96 | + row = session().execute(query).one(); | |
| 97 | + assertEquals(row.getInt("theKey"), 42); | |
| 98 | + assertEquals(row.getInt("a"), 1); | |
| 99 | + assertEquals(row.getInt("b"), 2); | |
| 100 | + } | |
| 101 | + | |
| 102 | + @Test(groups = "short") | |
| 103 | + public void routingKeyColumnCaseSensitivityForQuotedIdentifiersTest() throws Exception { | |
| 104 | + | |
| 105 | + BuiltStatement query; | |
| 106 | + TableMetadata table = cluster().getMetadata().getKeyspace(keyspace).getTable(TABLE_CASE_QUOTED); | |
| 107 | + assertNotNull(table); | |
| 108 | + ProtocolVersion protocolVersion = cluster().getConfiguration().getProtocolOptions().getProtocolVersion(); | |
| 109 | + CodecRegistry codecRegistry = CodecRegistry.DEFAULT_INSTANCE; | |
| 110 | + | |
| 111 | + query = insertInto(table).values(new String[]{"\"theKey\"", "a", "b", "\"tHEkEY\""}, new Object[]{42, 1, 2, 3}); | |
| 112 | + ByteBuffer bb = ByteBuffer.allocate(4); | |
| 113 | + bb.putInt(0, 42); | |
| 114 | + assertEquals(query.getRoutingKey(protocolVersion, codecRegistry), bb); | |
| 115 | + | |
| 116 | + query = insertInto(table).values(new String[]{"theKey", "a", "b", "\"tHEkEY\""}, new Object[]{42, 1, 2, 3}); | |
| 117 | + assertNull(query.getRoutingKey(protocolVersion, codecRegistry)); | |
| 118 | + | |
| 119 | + query = insertInto(table).values(new String[]{"theKey", "a", "b", "theKey"}, new Object[]{42, 1, 2, 3}); | |
| 120 | + assertNull(query.getRoutingKey(protocolVersion, codecRegistry)); | |
| 121 | + | |
| 122 | + } | |
| 123 | + | |
| 61 | 124 | @Test(groups = "short") |
| 62 | 125 | public void intRoutingKeyTest() throws Exception { |
| 63 | 126 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +62 −9
| @@ -726,16 +726,11 @@ | ||
| 726 | 726 | assertTrue(query.isTracing()); |
| 727 | 727 | } |
| 728 | 728 | |
| 729 | - @Test(groups = "unit") | |
| 729 | + @Test(groups = "unit", expectedExceptions = CodecNotFoundException.class) | |
| 730 | 730 | public void rejectUnknownValueTest() throws Exception { |
| 731 | - try { | |
| 732 | - RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2)) | |
| 733 | - .setForceNoValues(true); | |
| 734 | - s.getQueryString(); | |
| 735 | - fail("should have failed to inline a byte[]"); | |
| 736 | - } catch (CodecNotFoundException e) { | |
| 737 | - // Ok, that's what we expect | |
| 738 | - } | |
| 731 | + RegularStatement s = update("foo").with(set("a", new byte[13])).where(eq("k", 2)) | |
| 732 | + .setForceNoValues(true); | |
| 733 | + s.getQueryString(); | |
| 739 | 734 | } |
| 740 | 735 | |
| 741 | 736 | @Test(groups = "unit") |
| @@ -1102,5 +1097,63 @@ | ||
| 1102 | 1097 | .isEqualTo("INSERT INTO users (id) VALUES (fromJson(:id));"); |
| 1103 | 1098 | } |
| 1104 | 1099 | |
| 1100 | + static class Foo { | |
| 1101 | + int bar; | |
| 1102 | + | |
| 1103 | + public Foo(int bar) { | |
| 1104 | + this.bar = bar; | |
| 1105 | + } | |
| 1106 | + } | |
| 1107 | + | |
| 1108 | + static class FooCodec extends TypeCodec<Foo> { | |
| 1109 | + | |
| 1110 | + public FooCodec() { | |
| 1111 | + super(DataType.cint(), Foo.class); | |
| 1112 | + } | |
| 1113 | + | |
| 1114 | + @Override | |
| 1115 | + public ByteBuffer serialize(Foo value, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 1116 | + // not relevant for this test | |
| 1117 | + return null; | |
| 1118 | + } | |
| 1119 | + | |
| 1120 | + @Override | |
| 1121 | + public Foo deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException { | |
| 1122 | + // not relevant for this test | |
| 1123 | + return null; | |
| 1124 | + } | |
| 1125 | + | |
| 1126 | + @Override | |
| 1127 | + public Foo parse(String value) throws InvalidTypeException { | |
| 1128 | + // not relevant for this test | |
| 1129 | + return null; | |
| 1130 | + } | |
| 1131 | + | |
| 1132 | + @Override | |
| 1133 | + public String format(Foo foo) throws InvalidTypeException { | |
| 1134 | + return Integer.toString(foo.bar); | |
| 1135 | + } | |
| 1136 | + } | |
| 1137 | + | |
| 1138 | + /** | |
| 1139 | + * Ensures that a statement can be printed with and without | |
| 1140 | + * a required custom codec. | |
| 1141 | + * The expectation is that if the codec is not registered, | |
| 1142 | + * then the query string should contain bind markers for all variables; | |
| 1143 | + * if however all codecs are properly registered, then | |
| 1144 | + * the query string should contain all variables inlined and formatted properly. | |
| 1145 | + * | |
| 1146 | + * @jira_ticket JAVA-1272 | |
| 1147 | + */ | |
| 1148 | + @Test(groups = "unit") | |
| 1149 | + public void should_inline_custom_codec() throws Exception { | |
| 1150 | + assertThat( | |
| 1151 | + insertInto("users").value("id", new Foo(42)).toString()) | |
| 1152 | + .isEqualTo("INSERT INTO users (id) VALUES (?);"); | |
| 1153 | + CodecRegistry.DEFAULT_INSTANCE.register(new FooCodec()); | |
| 1154 | + assertThat( | |
| 1155 | + insertInto("users").value("id", new Foo(42)).toString()) | |
| 1156 | + .isEqualTo("INSERT INTO users (id) VALUES (42);"); | |
| 1157 | + } | |
| 1105 | 1158 | |
| 1106 | 1159 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/AnnotationParser.java +17 −10
| @@ -15,11 +15,7 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.mapping; |
| 17 | 17 | |
| 18 | -import com.datastax.driver.core.ConsistencyLevel; | |
| 19 | -import com.datastax.driver.core.Metadata; | |
| 20 | -import com.datastax.driver.core.TableMetadata; | |
| 21 | -import com.datastax.driver.core.TypeCodec; | |
| 22 | -import com.datastax.driver.core.UserType; | |
| 18 | +import com.datastax.driver.core.*; | |
| 23 | 19 | import com.datastax.driver.mapping.MethodMapper.ParamMapper; |
| 24 | 20 | import com.datastax.driver.mapping.annotations.*; |
| 25 | 21 | import com.google.common.base.Strings; |
| @@ -95,11 +91,18 @@ | ||
| 95 | 91 | ksName = Metadata.quote(loggedKeyspace); |
| 96 | 92 | } |
| 97 | 93 | |
| 98 | - EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency); | |
| 99 | - TableMetadata tableMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getTable(tableName); | |
| 94 | + KeyspaceMetadata keyspaceMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName); | |
| 95 | + if (keyspaceMetadata == null) | |
| 96 | + throw new IllegalArgumentException(String.format("Keyspace %s does not exist", ksName)); | |
| 97 | + | |
| 98 | + AbstractTableMetadata tableMetadata = keyspaceMetadata.getTable(tableName); | |
| 99 | + if (tableMetadata == null) { | |
| 100 | + tableMetadata = keyspaceMetadata.getMaterializedView(tableName); | |
| 101 | + if (tableMetadata == null) | |
| 102 | + throw new IllegalArgumentException(String.format("Table or materialized view %s does not exist in keyspace %s", tableName, ksName)); | |
| 103 | + } | |
| 100 | 104 | |
| 101 | - if (tableMetadata == null) | |
| 102 | - throw new IllegalArgumentException(String.format("Table %s does not exist in keyspace %s", tableName, ksName)); | |
| 105 | + EntityMapper<T> mapper = new EntityMapper<T>(entityClass, ksName, tableName, writeConsistency, readConsistency); | |
| 103 | 106 | |
| 104 | 107 | List<PropertyMapper> pks = new ArrayList<PropertyMapper>(); |
| 105 | 108 | List<PropertyMapper> ccs = new ArrayList<PropertyMapper>(); |
| @@ -169,7 +172,11 @@ | ||
| 169 | 172 | ksName = Metadata.quote(loggedKeyspace); |
| 170 | 173 | } |
| 171 | 174 | |
| 172 | - UserType userType = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName).getUserType(udtName); | |
| 175 | + KeyspaceMetadata keyspaceMetadata = mappingManager.getSession().getCluster().getMetadata().getKeyspace(ksName); | |
| 176 | + if (keyspaceMetadata == null) | |
| 177 | + throw new IllegalArgumentException(String.format("Keyspace %s does not exist", ksName)); | |
| 178 | + | |
| 179 | + UserType userType = keyspaceMetadata.getUserType(udtName); | |
| 173 | 180 | if (userType == null) |
| 174 | 181 | throw new IllegalArgumentException(String.format("User type %s does not exist in keyspace %s", udtName, ksName)); |
| 175 | 182 |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/MappedUDTCodec.java +16 −4
| @@ -79,13 +79,25 @@ | ||
| 79 | 79 | |
| 80 | 80 | @Override |
| 81 | 81 | protected String formatField(T source, String fieldName) { |
| 82 | - // This codec implementation is internal-use only, and its format method is never used | |
| 83 | - throw new UnsupportedOperationException(); | |
| 82 | + PropertyMapper propertyMapper = columnMappers.get(fieldName); | |
| 83 | + if (propertyMapper == null) | |
| 84 | + return null; | |
| 85 | + Object value = propertyMapper.getValue(source); | |
| 86 | + TypeCodec<Object> codec = propertyMapper.customCodec; | |
| 87 | + if (codec == null) | |
| 88 | + codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType); | |
| 89 | + return codec.format(value); | |
| 84 | 90 | } |
| 85 | 91 | |
| 86 | 92 | @Override |
| 87 | 93 | protected T parseAndSetField(String input, T target, String fieldName) { |
| 88 | - // This codec implementation is internal-use only, and its parse method is never used | |
| 89 | - throw new UnsupportedOperationException(); | |
| 94 | + PropertyMapper propertyMapper = columnMappers.get(fieldName); | |
| 95 | + if (propertyMapper != null) { | |
| 96 | + TypeCodec<Object> codec = propertyMapper.customCodec; | |
| 97 | + if (codec == null) | |
| 98 | + codec = codecRegistry.codecFor(cqlUserType.getFieldType(propertyMapper.columnName), propertyMapper.javaType); | |
| 99 | + propertyMapper.setValue(target, codec.parse(input)); | |
| 100 | + } | |
| 101 | + return target; | |
| 90 | 102 | } |
| 91 | 103 | } |
modified driver-mapping/src/main/java/com/datastax/driver/mapping/Mapper.java +4 −1
| @@ -113,7 +113,7 @@ | ||
| 113 | 113 | if (old != null) { |
| 114 | 114 | return old; |
| 115 | 115 | } else { |
| 116 | - String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values()); | |
| 116 | + final String queryString = type.makePreparedQueryString(tableMetadata, mapper, manager, columns, options.values()); | |
| 117 | 117 | logger.debug("Preparing query {}", queryString); |
| 118 | 118 | SimpleStatement s = new SimpleStatement(queryString); |
| 119 | 119 | // all queries generated by the mapper are idempotent |
| @@ -127,6 +127,9 @@ | ||
| 127 | 127 | @Override |
| 128 | 128 | public void onFailure(Throwable t) { |
| 129 | 129 | future.setException(t); |
| 130 | + // do not keep a failed future in the query cache | |
| 131 | + preparedQueries.remove(pqk, future); | |
| 132 | + logger.error("Query preparation failed: " + queryString, t); | |
| 130 | 133 | } |
| 131 | 134 | }); |
| 132 | 135 | return future; |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperMaterializedViewTest.java +158 −6
| @@ -17,10 +17,7 @@ | ||
| 17 | 17 | |
| 18 | 18 | import com.datastax.driver.core.CCMTestsSupport; |
| 19 | 19 | import com.datastax.driver.core.utils.CassandraVersion; |
| 20 | -import com.datastax.driver.mapping.annotations.Accessor; | |
| 21 | -import com.datastax.driver.mapping.annotations.Param; | |
| 22 | -import com.datastax.driver.mapping.annotations.Query; | |
| 23 | -import com.datastax.driver.mapping.annotations.Table; | |
| 20 | +import com.datastax.driver.mapping.annotations.*; | |
| 24 | 21 | import org.testng.annotations.BeforeMethod; |
| 25 | 22 | import org.testng.annotations.Test; |
| 26 | 23 | |
| @@ -32,7 +29,6 @@ | ||
| 32 | 29 | @CassandraVersion(major = 3.0) |
| 33 | 30 | public class MapperMaterializedViewTest extends CCMTestsSupport { |
| 34 | 31 | |
| 35 | - | |
| 36 | 32 | @Override |
| 37 | 33 | public void onTestContextInitialized() { |
| 38 | 34 | // Example schema taken from: http://www.datastax.com/dev/blog/new-in-cassandra-3-0-materialized-views |
| @@ -73,11 +69,28 @@ | ||
| 73 | 69 | ); |
| 74 | 70 | } |
| 75 | 71 | |
| 72 | + | |
| 73 | + private Mapper<AllTimeHigh> mapper; | |
| 74 | + | |
| 76 | 75 | private ScoreAccessor accessor; |
| 77 | 76 | |
| 78 | 77 | @BeforeMethod(groups = "short") |
| 79 | 78 | public void setUp() { |
| 80 | - accessor = new MappingManager(session()).createAccessor(ScoreAccessor.class); | |
| 79 | + MappingManager mappingManager = new MappingManager(session()); | |
| 80 | + mapper = mappingManager.mapper(AllTimeHigh.class); | |
| 81 | + accessor = mappingManager.createAccessor(ScoreAccessor.class); | |
| 82 | + } | |
| 83 | + | |
| 84 | + /** | |
| 85 | + * Validates that a materialized view can be mapped as a regular table. | |
| 86 | + * | |
| 87 | + * @test_category materialized_view, mapper | |
| 88 | + * @jira_ticket JAVA-1258 | |
| 89 | + */ | |
| 90 | + @Test(groups = "short") | |
| 91 | + public void should_access_mapped_materialized_view() { | |
| 92 | + AllTimeHigh allTimeHigh = mapper.get("Coup", 4000, "pcmanus", 2015, 5, 1); | |
| 93 | + assertThat(allTimeHigh).isNotNull(); | |
| 81 | 94 | } |
| 82 | 95 | |
| 83 | 96 | /** |
| @@ -159,14 +172,22 @@ | ||
| 159 | 172 | |
| 160 | 173 | @Table(name = "scores") |
| 161 | 174 | public static class Score { |
| 175 | + | |
| 176 | + //primary key: user, game, year, month, day | |
| 177 | + | |
| 178 | + @PartitionKey | |
| 162 | 179 | String user; |
| 163 | 180 | |
| 181 | + @ClusteringColumn(0) | |
| 164 | 182 | String game; |
| 165 | 183 | |
| 184 | + @ClusteringColumn(1) | |
| 166 | 185 | int year; |
| 167 | 186 | |
| 187 | + @ClusteringColumn(2) | |
| 168 | 188 | int month; |
| 169 | 189 | |
| 190 | + @ClusteringColumn(3) | |
| 170 | 191 | int day; |
| 171 | 192 | |
| 172 | 193 | int score; |
| @@ -277,4 +298,135 @@ | ||
| 277 | 298 | return result; |
| 278 | 299 | } |
| 279 | 300 | } |
| 301 | + | |
| 302 | + @Table(name = "alltimehigh") | |
| 303 | + public static class AllTimeHigh { | |
| 304 | + | |
| 305 | + //primary key: game, score, user, year, month, day | |
| 306 | + | |
| 307 | + @PartitionKey | |
| 308 | + String game; | |
| 309 | + | |
| 310 | + @ClusteringColumn(0) | |
| 311 | + int score; | |
| 312 | + | |
| 313 | + @ClusteringColumn(1) | |
| 314 | + String user; | |
| 315 | + | |
| 316 | + @ClusteringColumn(2) | |
| 317 | + int year; | |
| 318 | + | |
| 319 | + @ClusteringColumn(3) | |
| 320 | + int month; | |
| 321 | + | |
| 322 | + @ClusteringColumn(4) | |
| 323 | + int day; | |
| 324 | + | |
| 325 | + public AllTimeHigh() { | |
| 326 | + } | |
| 327 | + | |
| 328 | + public AllTimeHigh(String user, String game, int year, int month, int day, int score) { | |
| 329 | + this.user = user; | |
| 330 | + this.game = game; | |
| 331 | + this.year = year; | |
| 332 | + this.month = month; | |
| 333 | + this.day = day; | |
| 334 | + this.score = score; | |
| 335 | + } | |
| 336 | + | |
| 337 | + public String getUser() { | |
| 338 | + return user; | |
| 339 | + } | |
| 340 | + | |
| 341 | + public void setUser(String user) { | |
| 342 | + this.user = user; | |
| 343 | + } | |
| 344 | + | |
| 345 | + public String getGame() { | |
| 346 | + return game; | |
| 347 | + } | |
| 348 | + | |
| 349 | + public void setGame(String game) { | |
| 350 | + this.game = game; | |
| 351 | + } | |
| 352 | + | |
| 353 | + public int getYear() { | |
| 354 | + return year; | |
| 355 | + } | |
| 356 | + | |
| 357 | + public void setYear(int year) { | |
| 358 | + this.year = year; | |
| 359 | + } | |
| 360 | + | |
| 361 | + public int getMonth() { | |
| 362 | + return month; | |
| 363 | + } | |
| 364 | + | |
| 365 | + public void setMonth(int month) { | |
| 366 | + this.month = month; | |
| 367 | + } | |
| 368 | + | |
| 369 | + public int getDay() { | |
| 370 | + return day; | |
| 371 | + } | |
| 372 | + | |
| 373 | + public void setDay(int day) { | |
| 374 | + this.day = day; | |
| 375 | + } | |
| 376 | + | |
| 377 | + public int getScore() { | |
| 378 | + return score; | |
| 379 | + } | |
| 380 | + | |
| 381 | + public void setScore(int score) { | |
| 382 | + this.score = score; | |
| 383 | + } | |
| 384 | + | |
| 385 | + @Override | |
| 386 | + public String toString() { | |
| 387 | + return "AllTimeHigh{" + | |
| 388 | + "user='" + user + '\'' + | |
| 389 | + ", game='" + game + '\'' + | |
| 390 | + ", year=" + year + | |
| 391 | + ", month=" + month + | |
| 392 | + ", day=" + day + | |
| 393 | + ", score=" + score + | |
| 394 | + '}'; | |
| 395 | + } | |
| 396 | + | |
| 397 | + @SuppressWarnings("SimplifiableIfStatement") | |
| 398 | + @Override | |
| 399 | + public boolean equals(Object o) { | |
| 400 | + if (this == o) | |
| 401 | + return true; | |
| 402 | + if (!(o instanceof Score)) | |
| 403 | + return false; | |
| 404 | + | |
| 405 | + Score score1 = (Score) o; | |
| 406 | + | |
| 407 | + if (year != score1.year) | |
| 408 | + return false; | |
| 409 | + if (month != score1.month) | |
| 410 | + return false; | |
| 411 | + if (day != score1.day) | |
| 412 | + return false; | |
| 413 | + if (score != score1.score) | |
| 414 | + return false; | |
| 415 | + if (!user.equals(score1.user)) | |
| 416 | + return false; | |
| 417 | + return game.equals(score1.game); | |
| 418 | + } | |
| 419 | + | |
| 420 | + @Override | |
| 421 | + public int hashCode() { | |
| 422 | + int result = user.hashCode(); | |
| 423 | + result = 31 * result + game.hashCode(); | |
| 424 | + result = 31 * result + year; | |
| 425 | + result = 31 * result + month; | |
| 426 | + result = 31 * result + day; | |
| 427 | + result = 31 * result + score; | |
| 428 | + return result; | |
| 429 | + } | |
| 430 | + | |
| 431 | + } | |
| 280 | 432 | } |
added driver-mapping/src/test/java/com/datastax/driver/mapping/MapperReconnectionTest.java +80 −0
| @@ -0,0 +1,80 @@ | ||
| 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.mapping; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.CCMConfig; | |
| 19 | +import com.datastax.driver.core.CCMTestsSupport; | |
| 20 | +import com.datastax.driver.core.Cluster; | |
| 21 | +import com.datastax.driver.core.CreateCCM; | |
| 22 | +import com.datastax.driver.core.exceptions.NoHostAvailableException; | |
| 23 | +import com.datastax.driver.core.policies.ConstantReconnectionPolicy; | |
| 24 | +import org.testng.annotations.Test; | |
| 25 | + | |
| 26 | +import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; | |
| 27 | +import static com.datastax.driver.core.TestUtils.*; | |
| 28 | +import static com.datastax.driver.mapping.MapperTest.User; | |
| 29 | +import static org.testng.Assert.fail; | |
| 30 | + | |
| 31 | +@CreateCCM(PER_METHOD) | |
| 32 | +@CCMConfig(dirtiesContext = true) | |
| 33 | +public class MapperReconnectionTest extends CCMTestsSupport { | |
| 34 | + | |
| 35 | + @Override | |
| 36 | + public Cluster.Builder createClusterBuilder() { | |
| 37 | + return super.createClusterBuilder().withReconnectionPolicy(new ConstantReconnectionPolicy(1000)); | |
| 38 | + } | |
| 39 | + | |
| 40 | + @Override | |
| 41 | + public void onTestContextInitialized() { | |
| 42 | + execute("CREATE TABLE users (user_id uuid PRIMARY KEY, name text, email text, year int, gender text)"); | |
| 43 | + } | |
| 44 | + | |
| 45 | + /** | |
| 46 | + * Ensures that when the driver looses connectivity, | |
| 47 | + * if a mapper query preparation is attempted in the meanwhile, | |
| 48 | + * the failed future will not be kept in cache, so that when | |
| 49 | + * connectivity comes back again, | |
| 50 | + * the same query preparation can be reattempted. | |
| 51 | + * | |
| 52 | + * @jira_ticket JAVA-1283 | |
| 53 | + * @test_category object_mapper | |
| 54 | + */ | |
| 55 | + @Test(groups = "long") | |
| 56 | + public void should_not_keep_failed_future_in_query_cache() throws Exception { | |
| 57 | + MappingManager manager = new MappingManager(session()); | |
| 58 | + Mapper<User> m = manager.mapper(User.class); | |
| 59 | + User u1 = new User("Paul", "paul@gmail.com"); | |
| 60 | + m.save(u1); | |
| 61 | + ccm().stop(1); | |
| 62 | + ccm().waitForDown(1); | |
| 63 | + waitForDown(ipOfNode(1), cluster()); | |
| 64 | + try { | |
| 65 | + m.get(u1.getUserId()); | |
| 66 | + fail("Should have thrown NoHostAvailableException"); | |
| 67 | + } catch (NoHostAvailableException e) { | |
| 68 | + // ok | |
| 69 | + } | |
| 70 | + ccm().start(1); | |
| 71 | + ccm().waitForUp(1); | |
| 72 | + waitForUp(ipOfNode(1), cluster()); | |
| 73 | + try { | |
| 74 | + m.get(u1.getUserId()); | |
| 75 | + } catch (NoHostAvailableException e) { | |
| 76 | + fail("Should not have thrown NoHostAvailableException"); | |
| 77 | + } | |
| 78 | + } | |
| 79 | + | |
| 80 | +} |
modified driver-mapping/src/test/java/com/datastax/driver/mapping/MapperUDTTest.java +46 −1
| @@ -18,6 +18,7 @@ | ||
| 18 | 18 | import com.datastax.driver.core.*; |
| 19 | 19 | import com.datastax.driver.core.exceptions.CodecNotFoundException; |
| 20 | 20 | import com.datastax.driver.core.exceptions.InvalidQueryException; |
| 21 | +import com.datastax.driver.core.querybuilder.BuiltStatement; | |
| 21 | 22 | import com.datastax.driver.core.utils.CassandraVersion; |
| 22 | 23 | import com.datastax.driver.core.utils.UUIDs; |
| 23 | 24 | import com.datastax.driver.mapping.annotations.*; |
| @@ -31,6 +32,7 @@ | ||
| 31 | 32 | import java.util.*; |
| 32 | 33 | |
| 33 | 34 | import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD; |
| 35 | +import static com.datastax.driver.core.querybuilder.QueryBuilder.*; | |
| 34 | 36 | import static org.assertj.core.api.Assertions.assertThat; |
| 35 | 37 | import static org.assertj.core.api.Assertions.fail; |
| 36 | 38 | import static org.testng.Assert.*; |
| @@ -471,7 +473,7 @@ | ||
| 471 | 473 | manager.mapper(User.class); |
| 472 | 474 | fail("Expected IllegalArgumentException"); |
| 473 | 475 | } catch (IllegalArgumentException e) { |
| 474 | - assertThat(e.getMessage()).isEqualTo("Table users does not exist in keyspace \"" + keyspace + "\""); | |
| 476 | + assertThat(e.getMessage()).isEqualTo("Table or materialized view users does not exist in keyspace \"" + keyspace + "\""); | |
| 475 | 477 | } |
| 476 | 478 | } |
| 477 | 479 | |
| @@ -728,4 +730,47 @@ | ||
| 728 | 730 | manager.mapper(UserWithAddressUnknownField.class); |
| 729 | 731 | } |
| 730 | 732 | |
| 733 | + /** | |
| 734 | + * Ensures that MappedUDTCodec is able to properly format UDTs when printing the query string of a BuiltStatement. | |
| 735 | + * | |
| 736 | + * @jira_ticket JAVA-1272 | |
| 737 | + * @test_category object_mapper | |
| 738 | + */ | |
| 739 | + @Test(groups = "short") | |
| 740 | + public void should_format_mapped_udt() throws Exception { | |
| 741 | + MappingManager manager = new MappingManager(session()); | |
| 742 | + UUID uuid = UUIDs.random(); | |
| 743 | + BuiltStatement update = | |
| 744 | + update("users") | |
| 745 | + .with(set("mainaddress", new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245"))) | |
| 746 | + .where(eq("user_id", uuid)); | |
| 747 | + CodecRegistry codecRegistry = cluster().getConfiguration().getCodecRegistry(); | |
| 748 | + codecRegistry.register(manager.udtCodec(Address.class)); | |
| 749 | + String queryString = update.getQueryString(codecRegistry); | |
| 750 | + assertThat(queryString) | |
| 751 | + .isEqualTo("UPDATE users SET mainaddress=? WHERE user_id=?;"); | |
| 752 | + update.setForceNoValues(true); | |
| 753 | + queryString = update.getQueryString(codecRegistry); | |
| 754 | + assertThat(queryString).isEqualTo( | |
| 755 | + "UPDATE users " + | |
| 756 | + "SET mainaddress={street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}} " + | |
| 757 | + "WHERE user_id=" + uuid + ";"); | |
| 758 | + // check that the query string is valid | |
| 759 | + session().execute(queryString); | |
| 760 | + } | |
| 761 | + | |
| 762 | + /** | |
| 763 | + * Ensures that MappedUDTCodec is able to properly parse UDTs. | |
| 764 | + * | |
| 765 | + * @jira_ticket JAVA-1272 | |
| 766 | + * @test_category object_mapper | |
| 767 | + */ | |
| 768 | + @Test(groups = "short") | |
| 769 | + public void should_parse_mapped_udt() throws Exception { | |
| 770 | + MappingManager manager = new MappingManager(session()); | |
| 771 | + TypeCodec<Address> codec = manager.udtCodec(Address.class); | |
| 772 | + Address actual = codec.parse("{street:'12 4th Street',city:'Springfield',\"ZIP_code\":12345,phones:{'435423245','12341343'}}"); | |
| 773 | + assertThat(actual).isEqualTo(new Address("12 4th Street", "Springfield", 12345, "12341343", "435423245")); | |
| 774 | + } | |
| 775 | + | |
| 731 | 776 | } |
modified faq/README.md +58 −1
| @@ -157,9 +157,66 @@ | ||
| 157 | 157 | |
| 158 | 158 | See [Blobs.java] in the `driver-examples` module for some examples and explanations. |
| 159 | 159 | |
| 160 | -[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java | |
| 160 | +[Blobs.java]: https://github.com/datastax/java-driver/tree/3.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java | |
| 161 | 161 | |
| 162 | 162 | |
| 163 | 163 | ### How do I use the driver in an OSGi application? |
| 164 | 164 | |
| 165 | 165 | Read our [OSGi-specific FAQ section](osgi/) to find out. |
| 166 | + | |
| 167 | + | |
| 168 | +### Why am I seeing messages about `tombstone_warn_threshold` or `tombstone_fail_threshold` being exceeded in my Cassandra logs? | |
| 169 | + | |
| 170 | +Applications which use the object mapper or set `null` values in their | |
| 171 | +statements may observe that many tombstones are being stored in their tables | |
| 172 | +which subsequently may lead to poor query performance, failed queries, or | |
| 173 | +columns being mysteriously deleted. | |
| 174 | + | |
| 175 | +This is caused by INSERT/UPDATE statements containing `null` values for columns | |
| 176 | +that a user does not intend to change. Common circumstances around this come | |
| 177 | +from using the object mapper or writing your own persistence layer and | |
| 178 | +attempting to reuse the same `PreparedStatement` for inserting data, even with | |
| 179 | +partial updates. | |
| 180 | + | |
| 181 | +Prior to cassandra 2.2, there was no means of reusing the same | |
| 182 | +`PreparedStatement` for making partial updates to different columns. | |
| 183 | + | |
| 184 | +For example, given the following code: | |
| 185 | + | |
| 186 | +```java | |
| 187 | +PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)"); | |
| 188 | +BoundStatement bound = prepared.bind(); | |
| 189 | +bound.set("email", "clint.barton@hawkeye.com"); | |
| 190 | +bound.set("firstname", "Barney"); | |
| 191 | +// creates a tombstone!! | |
| 192 | +bound.set("lastname", null); | |
| 193 | +``` | |
| 194 | + | |
| 195 | +If one wanted to use this query to update only `firstname` this would not | |
| 196 | +be achievable without binding the `lastname` parameter to `null`. This would | |
| 197 | +have an undesired side effect of creating a tombstone for `lastname` and thus | |
| 198 | +to the user giving the impression that `lastname` was deleted. | |
| 199 | + | |
| 200 | +In cassandra 2.2 and later with protocol v4, bind parameters (`?`) can | |
| 201 | +optionally be left unset | |
| 202 | +([CASSANDRA-7304]): | |
| 203 | + | |
| 204 | + ```java | |
| 205 | + PreparedStatement prepared = session.prepare("INSERT INTO contacts (email, firstname, lastname) VALUES (?, ?, ?)"); | |
| 206 | + BoundStatement bound = prepared.bind(); | |
| 207 | + bound.set("email", "clint.barton@hawkeye.com"); | |
| 208 | + bound.set("firstname", "Barney"); | |
| 209 | + // lastname is left unset. | |
| 210 | + ``` | |
| 211 | + | |
| 212 | +See [Parameters and Binding] for more details about unset parameters. | |
| 213 | + | |
| 214 | +Another possible root cause for this is using the object mapper and leaving | |
| 215 | +fields set to `null`. This also causes tombstones to be inserted unless | |
| 216 | +setting `saveNullFields` option to false. See [Mapper options] for more | |
| 217 | +details. | |
| 218 | + | |
| 219 | +[Blobs.java]: https://github.com/datastax/java-driver/tree/3.0.x/driver-examples/src/main/java/com/datastax/driver/examples/datatypes/Blobs.java | |
| 220 | +[CASSANDRA-7304]: https://issues.apache.org/jira/browse/CASSANDRA-7304 | |
| 221 | +[Parameters and Binding]: ../manual/statements/prepared/#parameters-and-binding | |
| 222 | +[Mapper options]: ../manual/object_mapper/using/#mapper-options |
modified manual/async/README.md +0 −12
| @@ -130,21 +130,9 @@ | ||
| 130 | 130 | issues, you should create your `Cluster` instances while bootstrapping |
| 131 | 131 | your application, and call `init` immediately. If you need to create new |
| 132 | 132 | instances at runtime, make sure this does not happen on an I/O thread. |
| 133 | -* if a connection pool is busy, the driver will block until a connection | |
| 134 | - becomes available. To avoid this, set | |
| 135 | - [PoolingOptions.poolTimeoutMillis][setPoolTimeoutMillis] to 0; the | |
| 136 | - driver will not block, just move to the next host immediately. | |
| 137 | -* if the session is set to a specific keyspace (either at startup or by | |
| 138 | - issuing a `USE` statement on a running session), the keyspace needs to | |
| 139 | - be propagated to any newly created connection. This is done when the | |
| 140 | - connection is first borrowed from the connection pool, and currently | |
| 141 | - blocks. To avoid any issue, only use a session with no keyspace set | |
| 142 | - (i.e. created by `Cluster#connect()`). This will be addressed in | |
| 143 | - [JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893). | |
| 144 | 133 | * trying to read fields from a [query trace] will block if the trace |
| 145 | 134 | hasn't been fetched already. |
| 146 | 135 | |
| 147 | 136 | [ListenableFuture]: https://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained |
| 148 | 137 | [init]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Cluster.html#init-- |
| 149 | -[setPoolTimeoutMillis]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int- | |
| 150 | 138 | [query trace]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/QueryTrace.html |
modified manual/load_balancing/README.md +2 −2
| @@ -178,8 +178,8 @@ | ||
| 178 | 178 | // Set the routing key manually: serialize each partition key component to its target CQL type |
| 179 | 179 | ProtocolVersion protocolVersion = cluster.getConfiguration().getProtocolOptions().getProtocolVersionEnum(); |
| 180 | 180 | statement.setRoutingKey( |
| 181 | - DataType.cint().serialize(1, protocolVersion), | |
| 182 | - DataType.cint().serialize(2016, protocolVersion)); | |
| 181 | + TypeCodec.cint().serialize(1, protocolVersion), | |
| 182 | + TypeCodec.cint().serialize(2016, protocolVersion)); | |
| 183 | 183 | |
| 184 | 184 | session.execute(statement); |
| 185 | 185 | ``` |
modified manual/object_mapper/custom_codecs/README.md +1 −1
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | ```java |
| 59 | 59 | @Accessor |
| 60 | 60 | interface UserAccessor { |
| 61 | - @Query("update user set birth = :b where id = :i) | |
| 61 | + @Query("update user set birth = :b where id = :i") | |
| 62 | 62 | void updateBirth(@Param("i") int id, |
| 63 | 63 | @Param("b") MyCustomDate birth); |
| 64 | 64 | } |
modified manual/object_mapper/using/README.md +2 −2
| @@ -146,13 +146,13 @@ | ||
| 146 | 146 | - `Mapper.getQuery(userId)`: returns a statement to select a row in the |
| 147 | 147 | database, selected on the given `userId`, and matching the mapped |
| 148 | 148 | object structure. |
| 149 | -- `Mapper.deleteQuery(userID)`: returns a statement delete a row in the | |
| 149 | +- `Mapper.deleteQuery(userID)`: returns a statement to delete a row in the | |
| 150 | 150 | database given the `userId` provided. This method can also accept a |
| 151 | 151 | mapped object instance. |
| 152 | 152 | |
| 153 | 153 | #### Manual mapping |
| 154 | 154 | |
| 155 | -`Mapper#map` provides a way to converts the results of a regular query: | |
| 155 | +`Mapper#map` provides a way to convert the results of a regular query: | |
| 156 | 156 | |
| 157 | 157 | ```java |
| 158 | 158 | ResultSet results = session.execute("SELECT * FROM user"); |
modified manual/pooling/README.md +24 −23
| @@ -180,24 +180,24 @@ | ||
| 180 | 180 | message. |
| 181 | 181 | |
| 182 | 182 | |
| 183 | -#### Acquisition timeout | |
| 183 | +#### Acquisition queue | |
| 184 | 184 | |
| 185 | 185 | When the driver tries to send a request to a host, it will first try to |
| 186 | 186 | acquire a connection from this host's pool. If the pool is busy (i.e. |
| 187 | 187 | all connections are already handling their maximum number of in flight |
| 188 | -requests), the client thread will block for a while, until a connection | |
| 189 | -becomes available (note that this will block even if you're using the | |
| 190 | -asynchronous API, like [Session.executeAsync][exec_async]). | |
| 188 | +requests), the acquisition attempt gets enqueued until a connection becomes | |
| 189 | +available again. | |
| 191 | 190 | |
| 192 | -The time that the driver blocks is controlled by | |
| 193 | -[PoolingOptions.setPoolTimeoutMillis][ptm]. If there is still no connection | |
| 194 | -available after this timeout, the driver will try the next host. | |
| 191 | +The size of that queue is controlled by [PoolingOptions.setMaxQueueSize][smqs]. | |
| 192 | +If the queue has already reached its limit, further attempts to acquire a | |
| 193 | +connection will be rejected immediately: the driver will move on and try to | |
| 194 | +acquire a connection from the next host's pool. The limit can be set to 0 to | |
| 195 | +disable queueing entirely. | |
| 195 | 196 | |
| 196 | -For some applications, blocking is not acceptable, and it is preferable | |
| 197 | -to fail fast if the request cannot be fulfilled. If that's your case, | |
| 198 | -set the pool timeout to 0. If all hosts are busy, you will get a | |
| 199 | -[NoHostAvailableException][nhae] (if you look at the exception's details, you | |
| 200 | -will see a `java.util.concurrent.TimeoutException` for each host). | |
| 197 | +If all hosts are busy with a full queue, the request will fail with a | |
| 198 | +[NoHostAvailableException][nhae]. If you inspect the map returns by this | |
| 199 | +exception's [getErrors] method, you will see a [BusyPoolException] for | |
| 200 | +each host. | |
| 201 | 201 | |
| 202 | 202 | |
| 203 | 203 | ### Monitoring and tuning the pool |
| @@ -278,14 +278,15 @@ | ||
| 278 | 278 | [newConnectionThreshold][nct] so that enough connections are added by |
| 279 | 279 | the time you reach the bottleneck. |
| 280 | 280 | |
| 281 | -[result_set_future]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html | |
| 282 | -[pooling_options]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html | |
| 283 | -[lbp]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 284 | -[nct]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int- | |
| 285 | -[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int- | |
| 286 | -[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int- | |
| 287 | -[rtm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis-- | |
| 288 | -[exec_async]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#executeAsync-com.datastax.driver.core.Statement- | |
| 289 | -[ptm]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setPoolTimeoutMillis-int- | |
| 290 | -[nhae]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html | |
| 291 | -[get_state]:http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState-- | |
| 281 | +[result_set_future]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/ResultSetFuture.html | |
| 282 | +[pooling_options]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html | |
| 283 | +[lbp]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/policies/LoadBalancingPolicy.html | |
| 284 | +[nct]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setNewConnectionThreshold-com.datastax.driver.core.HostDistance-int- | |
| 285 | +[mrpc]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxRequestsPerConnection-com.datastax.driver.core.HostDistance-int- | |
| 286 | +[sits]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setIdleTimeoutSeconds-int- | |
| 287 | +[rtm]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/SocketOptions.html#getReadTimeoutMillis-- | |
| 288 | +[smqs]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/PoolingOptions.html#setMaxQueueSize-int- | |
| 289 | +[nhae]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html | |
| 290 | +[getErrors]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/NoHostAvailableException.html#getErrors-- | |
| 291 | +[get_state]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/Session.html#getState-- | |
| 292 | +[BusyPoolException]: http://docs.datastax.com/en/drivers/java/3.0/com/datastax/driver/core/exceptions/BusyPoolException.html |
modified manual/shaded_jar/README.md +7 −7
| @@ -56,16 +56,16 @@ | ||
| 56 | 56 | |
| 57 | 57 | ### Limitations |
| 58 | 58 | |
| 59 | -When using the shaded jar, it is not possible to configure the Netty layer. | |
| 59 | +When using the shaded jar, it is not possible to configure the Netty layer. | |
| 60 | 60 | |
| 61 | -Extending [NettyOptions] is not an option because `NettyOptions` API | |
| 62 | -exposes Netty classes, and as such it should only be extended | |
| 63 | -by clients using the non-shaded version of driver. | |
| 64 | -Attempting to extend `NettyOptions` with shaded Netty classes is not supported, | |
| 65 | -and in particular for OSGi applications, | |
| 61 | +Extending [NettyOptions] is not an option because `NettyOptions` API | |
| 62 | +exposes Netty classes, and as such it should only be extended | |
| 63 | +by clients using the non-shaded version of driver. | |
| 64 | +Attempting to extend `NettyOptions` with shaded Netty classes is not supported, | |
| 65 | +and in particular for OSGi applications, | |
| 66 | 66 | it is likely that such a configuration would lead to compile and/or runtime errors. |
| 67 | 67 | |
| 68 | -Also, with shaded Netty classes, it is not possible to benefit | |
| 68 | +Also, with shaded Netty classes, it is not possible to benefit | |
| 69 | 69 | from [Netty native transports]. |
| 70 | 70 | |
| 71 | 71 | It is therefore normal to see the following log line when the driver starts and |
modified pom.xml +8 −0
| @@ -140,6 +140,10 @@ | ||
| 140 | 140 | <artifactId>maven-surefire-plugin</artifactId> |
| 141 | 141 | <version>2.16</version> |
| 142 | 142 | <configuration> |
| 143 | + <property> | |
| 144 | + <name>usedefaultlisteners</name> | |
| 145 | + <value>false</value> <!-- disable default listeners as some of the html reports do a lot of File I/O --> | |
| 146 | + </property> | |
| 143 | 147 | <skip>true</skip> |
| 144 | 148 | <forkCount>1</forkCount> |
| 145 | 149 | <reuseForks>false</reuseForks> |
| @@ -377,6 +381,10 @@ | ||
| 377 | 381 | <classpathDependencyExcludes>io.netty:netty-transport-native-epoll</classpathDependencyExcludes> |
| 378 | 382 | </classpathDependencyExcludes> |
| 379 | 383 | <properties> |
| 384 | + <property> | |
| 385 | + <name>usedefaultlisteners</name> | |
| 386 | + <value>false</value> <!-- disable default listeners as some of the html reports do a lot of File I/O --> | |
| 387 | + </property> | |
| 380 | 388 | <property> |
| 381 | 389 | <!-- Don't skip tests after a @Before method throws a SkipException --> |
| 382 | 390 | <name>configfailurepolicy</name> |
modified upgrade_guide/README.md +16 −0
| @@ -35,6 +35,22 @@ | ||
| 35 | 35 | 3.2.0. |
| 36 | 36 | |
| 37 | 37 | |
| 38 | +### 3.0.4 | |
| 39 | + | |
| 40 | +The connection pool is now fully non-blocking ([JAVA-893](https://datastax-oss.atlassian.net/browse/JAVA-893)), | |
| 41 | +which greatly improves asynchronous programming: | |
| 42 | + | |
| 43 | +* `Session.executeAsync` won't ever block the user thread anymore; | |
| 44 | +* you can now safely run async queries on a session connected to a keyspace. | |
| 45 | + | |
| 46 | +This new implementation brings a couple of changes: | |
| 47 | + | |
| 48 | +* pool saturation is no longer handled by a timeout, but instead by a bounded queue. As a consequence, | |
| 49 | + `PoolingOptions.setPoolTimeoutMillis` has been deprecated, and replaced by `setMaxQueueSize`; | |
| 50 | +* a saturated pool will now throw `BusyPoolException` instead of `TimeoutException` (note that this exception is not | |
| 51 | + rethrown directly to the client, but wrapped in `NoHostAvailableException.getErrors()`). | |
| 52 | + | |
| 53 | + | |
| 38 | 54 | ### 3.0.0 |
| 39 | 55 | |
| 40 | 56 | This version brings parity with Cassandra 2.2 and 3.0. |
added upgrade_guide/migrating_from_astyanax/.nav +3 −0
| @@ -0,0 +1,3 @@ | ||
| 1 | +language_level_changes | |
| 2 | +configuration | |
| 3 | +queries_and_results | |
| No newline at the end of the file |
added upgrade_guide/migrating_from_astyanax/README.md +10 −0
| @@ -0,0 +1,10 @@ | ||
| 1 | +# Migrating from Astyanax | |
| 2 | + | |
| 3 | +This section is a guide for users previously using *Astyanax* and looking for | |
| 4 | +migrating to the *DataStax Java driver*. | |
| 5 | + | |
| 6 | +See the child pages for more information: | |
| 7 | + | |
| 8 | +* [Changes at the language level](language_level_changes/) | |
| 9 | +* [Migrating Astyanax configurations to DataStax Java driver configurations](configuration/) | |
| 10 | +* [Querying and retrieving results comparisons.](queries_and_results/) |
added upgrade_guide/migrating_from_astyanax/configuration/README.md +252 −0
| @@ -0,0 +1,252 @@ | ||
| 1 | +# Configuration | |
| 2 | + | |
| 3 | +## How Configuring the Java driver works | |
| 4 | + | |
| 5 | +The two basic components in the Java driver are the `Cluster` and the `Session`. | |
| 6 | +The `Cluster` is the object to create first, and on to which all global configurations | |
| 7 | +apply. Connecting to the `Cluster` creates a `Session`. Queries are executed | |
| 8 | +through the `Session`. | |
| 9 | + | |
| 10 | +The `Cluster` object then is to be viewed as the equivalent of the `AstyanaxContext` | |
| 11 | +object. "Starting" an `AstyanaxContext` object typically returns a `Keyspace` | |
| 12 | +object, the `Keyspace` object is the equivalent of the *Java driver*’s `Session`. | |
| 13 | + | |
| 14 | +Configuring a `Cluster` works with the *Builder* pattern. The `Builder` takes all | |
| 15 | +the configurations into account before building the `Cluster`. | |
| 16 | + | |
| 17 | +Following are some examples of the most important configurations that were | |
| 18 | +possible with *Astyanax* and how to translate them into *DataStax Java driver* | |
| 19 | +configurations. Please note that the Java driver has been optimized to handle most use | |
| 20 | +cases at best and even though the following sections show how to tune some various | |
| 21 | +options, the driver should provide the best performances with the default configurations | |
| 22 | +and these options should not be changed unless there is a good reason to. | |
| 23 | + | |
| 24 | +## Connection pools | |
| 25 | + | |
| 26 | +Configuration of connection pools in *Astyanax* are made through the | |
| 27 | +`ConnectionPoolConfigurationImpl`. This object gathers important configurations | |
| 28 | +that the *Java driver* has categorized in multiple *Option* and *Policy* kinds. | |
| 29 | + | |
| 30 | +### Connections pools internals | |
| 31 | +Everything concerning the internal pools of connections to the *Cassandra nodes* | |
| 32 | +will be gathered in the Java driver in the [`PoolingOptions`](../../../manual/pooling): | |
| 33 | + | |
| 34 | +*Astyanax*: | |
| 35 | + | |
| 36 | +```java | |
| 37 | +ConnectionPoolConfigurationImpl cpool = | |
| 38 | + new ConnectionPoolConfigurationImpl("myConnectionPool") | |
| 39 | + .setInitConnsPerHost(2) | |
| 40 | + .setMaxConnsPerHost(3) | |
| 41 | +``` | |
| 42 | + | |
| 43 | +*Java driver*: | |
| 44 | + | |
| 45 | +```java | |
| 46 | +PoolingOptions poolingOptions = | |
| 47 | + new PoolingOptions() | |
| 48 | + .setConnectionsPerHost(HostDistance.LOCAL, 2, 3) | |
| 49 | +``` | |
| 50 | +The first number is the initial number of connections, the second is the maximum number | |
| 51 | +of connections the driver is allowed to create for each host. | |
| 52 | + | |
| 53 | +Note that the *Java driver* allows multiple simultaneous requests on one single | |
| 54 | +connection, as it is based upon the [*Native protocol*](../../../manual/native_protocol), | |
| 55 | +an asynchronous binary protocol that can handle up to 32768 simultaneous requests on a | |
| 56 | +single connection. The Java driver is able to manage and distribute simultaneous requests | |
| 57 | +by itself even under high contention, and changing the default `PoolingOptions` is not | |
| 58 | +necessary most of the time except for very [specific use cases](../../../manual/pooling/#tuning-protocol-v3-for-very-high-throughputs). | |
| 59 | + | |
| 60 | +### Timeouts | |
| 61 | + | |
| 62 | +Timeouts concerning requests, or connections will be part of the `SocketOptions`. | |
| 63 | + | |
| 64 | +*Astyanax*: | |
| 65 | + | |
| 66 | +```java | |
| 67 | +ConnectionPoolConfigurationImpl cpool = | |
| 68 | + new ConnectionPoolConfigurationImpl("myConnectionPool") | |
| 69 | + .setSocketTimeout(3000) | |
| 70 | + .setConnectTimeout(3000) | |
| 71 | +``` | |
| 72 | + | |
| 73 | +*Java Driver:* | |
| 74 | + | |
| 75 | +```java | |
| 76 | +SocketOptions so = | |
| 77 | + new SocketOptions() | |
| 78 | + .setReadTimeoutMillis(3000) | |
| 79 | + .setConnectTimeoutMillis(3000); | |
| 80 | +``` | |
| 81 | + | |
| 82 | +Changing the client timeout options might have more impacts than expected, **please make | |
| 83 | +sure to properly document before changing these options.** | |
| 84 | + | |
| 85 | +## Load Balancing | |
| 86 | +Both *Astyanax* and the *Java driver* connect to multiple nodes of the *Cassandra* | |
| 87 | +cluster. Distributing requests through all the nodes plays an important role in | |
| 88 | +the good operation of the `Cluster` and for best performances. With *Astyanax*, | |
| 89 | +requests (or “operations”) can be sent directly to replicas that have a copy of | |
| 90 | +the data targeted by the *“Row key”* specified in the operation. Since the *Thrift* API is | |
| 91 | +low-level, it forces the user to provide *Row keys*, known as the `TokenAware` | |
| 92 | +connection pool type. This setting is also present in the *Java driver*, however | |
| 93 | +the configuration is different and provides more options to tweak. | |
| 94 | + | |
| 95 | +Load balancing in the *Java driver* is a *Policy*, it is a class that will be | |
| 96 | +plugged in the *Java driver*’s code and the Driver will call its methods when it | |
| 97 | +needs to. The *Java driver* comes with a preset of specific load balancing policies. | |
| 98 | +Here’s an equivalent code: | |
| 99 | + | |
| 100 | +*Astyanax*: | |
| 101 | + | |
| 102 | +```java | |
| 103 | +final ConnectionPoolType poolType = ConnectionPoolType.TOKEN_AWARE; | |
| 104 | +final NodeDiscoveryType discType = NodeDiscoveryType.RING_DESCRIBE; | |
| 105 | +ConnectionPoolConfigurationImpl cpool = | |
| 106 | + new ConnectionPoolConfigurationImpl("myConnectionPool") | |
| 107 | + .setLocalDatacenter("myDC") | |
| 108 | +AstyanaxConfigurationImpl aconf = | |
| 109 | + new AstyanaxConfigurationImpl() | |
| 110 | + .setConnectionPoolType(poolType) | |
| 111 | + .setDiscoveryType(discType) | |
| 112 | +``` | |
| 113 | + | |
| 114 | +*Java driver*: | |
| 115 | + | |
| 116 | +```java | |
| 117 | +LoadBalancingPolicy lbp = new TokenAwarePolicy( | |
| 118 | + DCAwareRoundRobinPolicy.builder() | |
| 119 | + .withLocalDc("myDC") | |
| 120 | + .build() | |
| 121 | +); | |
| 122 | +``` | |
| 123 | + | |
| 124 | +*By default* the *Java driver* will instantiate the exact Load balancing policy | |
| 125 | +shown above, with the `LocalDC` being the DC of the first host the driver connects | |
| 126 | +to. So to get the same behaviour than the *TokenAware* pool type of *Astyanax*, | |
| 127 | +users shouldn’t need to specify a load balancing policy since the default one | |
| 128 | +should cover it. | |
| 129 | + | |
| 130 | +Important: Note that since *CQL* is an abstraction of the Cassandra’s architecture, a simple | |
| 131 | +query needs to have the *Row key* specified explicitly on a `Statement` in order | |
| 132 | +to benefit from the *TokenAware* routing (the *Row key* in the *Java driver* is | |
| 133 | +referenced as *Routing Key*), unlike the *Astyanax* driver. | |
| 134 | +Some differences occur related to the different kinds of `Statements` the *Java | |
| 135 | +driver* provides. Please see [this link](../../../manual/load_balancing/#token-aware-policy) | |
| 136 | +for specific information. | |
| 137 | + | |
| 138 | +Custom load balancing policies can easily be implemented by users, and supplied to | |
| 139 | +the *Java driver* for specific use cases. All information necessary is available | |
| 140 | +in the [Load balaning policies docs](../../../manual/load_balancing). | |
| 141 | + | |
| 142 | +## Consistency levels | |
| 143 | +Consistency levels can be set per-statement, or globally through the `QueryOptions`. | |
| 144 | + | |
| 145 | +*Astyanax*: | |
| 146 | + | |
| 147 | +```java | |
| 148 | +AstyanaxConfigurationImpl aconf = | |
| 149 | + new AstyanaxConfigurationImpl() | |
| 150 | + .setDefaultReadConsistencyLevel(ConsistencyLevel.CL*ALL) | |
| 151 | + .setDefaultWriteConsistencyLevel(ConsistencyLevel.CL*ALL) | |
| 152 | +``` | |
| 153 | + | |
| 154 | +*Java driver*: | |
| 155 | + | |
| 156 | +```java | |
| 157 | +QueryOptions qo = new QueryOptions().setConsistencyLevel(ConsistencyLevel.ALL); | |
| 158 | +``` | |
| 159 | + | |
| 160 | +Since the *Java driver* only executes *CQL* statements, which can be either reads | |
| 161 | +or writes to *Cassandra*, it is not possible to globally configure the | |
| 162 | +Consistency Level for only reads or only writes. To do so, since the Consistency | |
| 163 | +Level can be set per-statement, you can either set it on every statement, or use | |
| 164 | +`PreparedStatements` (if queries are to be repeated with different values): in | |
| 165 | +this case, setting the CL on the `PreparedStatement`, causes the `BoundStatements` to | |
| 166 | +inherit the CL from the prepared statements they were prepared from. More | |
| 167 | +informations about how `Statement`s work in the *Java driver* are detailed | |
| 168 | +in the [“Queries and Results” section](../queries_and_results/). | |
| 169 | + | |
| 170 | + | |
| 171 | +## Authentication | |
| 172 | + | |
| 173 | +Authentication settings are managed by the `AuthProvider` class in the *Java driver*. | |
| 174 | +It can be highly customizable, but also comes with default simple implementations: | |
| 175 | + | |
| 176 | +*Astyanax*: | |
| 177 | + | |
| 178 | +```java | |
| 179 | +AuthenticationCredentials authCreds = new SimpleAuthenticationCredentials("username", "password"); | |
| 180 | +ConnectionPoolConfigurationImpl cpool = | |
| 181 | + new ConnectionPoolConfigurationImpl("myConnectionPool") | |
| 182 | + .setAuthenticationCredentials(authCreds) | |
| 183 | +``` | |
| 184 | + | |
| 185 | +*Java driver*: | |
| 186 | + | |
| 187 | +```java | |
| 188 | +AuthProvider authProvider = new PlainTextAuthProvider("username", "password"); | |
| 189 | +``` | |
| 190 | + | |
| 191 | +The class `AuthProvider` can be easily implemented to suit the user’s needs, | |
| 192 | +documentation about the classes needed is [available there](../../../manual/auth/). | |
| 193 | + | |
| 194 | +## Hosts and ports | |
| 195 | + | |
| 196 | +Setting the “seeds” or first hosts to connect to can be done directly on the | |
| 197 | +Cluster configuration Builder: | |
| 198 | + | |
| 199 | +*Astyanax*: | |
| 200 | + | |
| 201 | +```java | |
| 202 | +ConnectionPoolConfigurationImpl cpool = | |
| 203 | + new ConnectionPoolConfigurationImpl("myConnectionPool") | |
| 204 | + .setSeeds("127.0.0.1") | |
| 205 | + .setPort(9160) | |
| 206 | +``` | |
| 207 | + | |
| 208 | +*Java driver*: | |
| 209 | + | |
| 210 | +```java | |
| 211 | +Cluster cluster = Cluster.builder() | |
| 212 | + .addContactPoint("127.0.0.1") | |
| 213 | + .withPort(9042) | |
| 214 | +``` | |
| 215 | + | |
| 216 | +The *Java driver* by default connects to port *9042*, hence you can supply only | |
| 217 | +host names with the `addContactPoints(String...)` method. Note that the contact | |
| 218 | +points are only the entry points to the `Cluster` for the *Automatic discovery | |
| 219 | +phase*. | |
| 220 | + | |
| 221 | +## Building the Cluster | |
| 222 | +With all options previously presented, one may configure and create the | |
| 223 | +`Cluster` object this way: | |
| 224 | + | |
| 225 | +*Java driver*: | |
| 226 | + | |
| 227 | +```java | |
| 228 | +Cluster cluster = Cluster.builder() | |
| 229 | + .addContactPoint("127.0.0.1") | |
| 230 | + .withAuthProvider(authProvider) | |
| 231 | + .withLoadBalancingPolicy(lbp) | |
| 232 | + .withSocketOptions(so) | |
| 233 | + .withPoolingOptions(poolingOptions) | |
| 234 | + .withQueryOptions(qo) | |
| 235 | + .build(); | |
| 236 | +Session session = cluster.connect(); | |
| 237 | +``` | |
| 238 | + | |
| 239 | +## Best Practices | |
| 240 | + | |
| 241 | +A few best practices are summed up in [this blog post](http://www.datastax.com/dev/blog/4-simple-rules-when-using-the-datastax-drivers-for-cassandra). | |
| 242 | + | |
| 243 | +Concerning connection pools, the Java driver’s default settings should allow | |
| 244 | +most of the users to get the best out of the driver in terms of throughput, | |
| 245 | +they have been thoroughly tested and tweaked to accommodate the users’ needs. | |
| 246 | +If one still wishes to change those, first [Monitoring the pools](../../../manual/pooling/#monitoring-and-tuning-the-pool) is | |
| 247 | +advised, then a [deep dive in the Pools management mechanism](../../../manual/pooling/) should | |
| 248 | +provide enough insight. | |
| 249 | + | |
| 250 | +A lot more options are available in the different `XxxxOption`s classes, policies are | |
| 251 | +also highly customizable since the base Java driver's implementations can easily be | |
| 252 | +extended and implement user-specific actions. |
added upgrade_guide/migrating_from_astyanax/language_level_changes/README.md +75 −0
| @@ -0,0 +1,75 @@ | ||
| 1 | +# Language change : from Thrift to CQL | |
| 2 | +The data model changes when using *CQL* (Cassandra Query Language). | |
| 3 | +*CQL* is providing an abstraction of the low-level data stored in *Cassandra*, in | |
| 4 | +opposition to *Thrift* that aims to expose the low-level data structure directly. | |
| 5 | +[But note that this changes with Cassandra 3’s new storage engine.](http://www.datastax.com/2015/12/storage-engine-30) | |
| 6 | + | |
| 7 | +*Thrift* exposes *Keyspaces*, and these *Keyspaces* contain *Column Families*. A | |
| 8 | +*ColumnFamily* contains *Rows* in which each *Row* has a list of an arbitrary number | |
| 9 | +of column-values. With *CQL*, the data is **tabular**, *ColumnFamily* gets viewed | |
| 10 | +as a *Table*, the **Table Rows** get a **fixed and finite number of named columns**. | |
| 11 | +*Thrift*’s columns inside the *Rows* get distributed in a tabular way through the | |
| 12 | +_Table Rows_. See the following figure: | |
| 13 | + | |
| 14 | +```ditaa | |
| 15 | + Thrift | |
| 16 | + /- -\ | |
| 17 | + | | | |
| 18 | + | /------------\ /---------------+---------------+---------------+---------+ | | |
| 19 | + | | cRED | |cFA0 1 | 2 | 3 | | | | |
| 20 | + | | 1 | ----------> +---------------+---------------+---------------+ ... | +--> One Thrift | |
| 21 | + | | | |c1AB 'a' | 'b' | 'c' | | | ROW | |
| 22 | + | \------------/ \---------------+---------------+---------------+---------+ | | |
| 23 | + | | | |
| 24 | +One Thrift | -/ | |
| 25 | +COLUMNFAMILY | | |
| 26 | + | | |
| 27 | + | /------------\ /---------------+---------------+---------+ | |
| 28 | + | | | | 1 | 2 | | | |
| 29 | + | | 2 | ----------> +---------------+---------------+ ... | | |
| 30 | + | | | | 'a' | 'b' | | | |
| 31 | + | \------------/ \---------------+---------------+---------+ | |
| 32 | + | | |
| 33 | + \- | |
| 34 | + | |
| 35 | + | |
| 36 | + ----------------------------------------------------------------------- | |
| 37 | + | |
| 38 | + | |
| 39 | + CQL | |
| 40 | + | |
| 41 | + /- | |
| 42 | + | | |
| 43 | + | /--------------------+---------------------------------+-----------------------------\ | |
| 44 | + | | key | column1 | value | | |
| 45 | + | +--------------------+---------------------------------+-----------------------------+ | |
| 46 | + | | cRED 1 | cFA0 1 | c1AB 'a' | | |
| 47 | + | +--------------------+---------------------------------+-----------------------------+ -\ | |
| 48 | + | | cRED 1 | 2 | 'b' | +--> One CQL | |
| 49 | + One CQL | +--------------------+---------------------------------+-----------------------------+ -/ ROW | |
| 50 | + TABLE | | cRED 1 | 3 | 'c' | | |
| 51 | + | +--------------------+---------------------------------+-----------------------------+ | |
| 52 | + | | cRED ... | ... | ... | | |
| 53 | + | +--------------------+---------------------------------+-----------------------------+ | |
| 54 | + | | 2 | 1 | 'a' | | |
| 55 | + | +--------------------+---------------------------------+-----------------------------+ | |
| 56 | + | | 2 | 2 | 'b' | | |
| 57 | + | +--------------------+---------------------------------+-----------------------------+ | |
| 58 | + | | ... | ... | ... | | |
| 59 | + | +--------------------+---------------------------------+-----------------------------+ | |
| 60 | + \- | |
| 61 | +``` | |
| 62 | + | |
| 63 | +Some of the columns of a *CQL Table* have a special role that is specifically | |
| 64 | +related to the *Cassandra* architecture. Indeed, the *Row key* of the *Thrift Row*, | |
| 65 | +becomes the *Partition Key* in the *CQL Table*, and can be composed of 1 or multiple | |
| 66 | +*CQL columns* (the key column in Figure 1). The *“Column”* part of the Column-value | |
| 67 | +component in a *Thrift Row*, becomes the *Clustering Column* in *CQL*, and can | |
| 68 | +also be composed of multiple columns (in the figure, column1 is the only column | |
| 69 | +composing the *Clustering Column*, but there can be others if the Thrift's ColumnComparator | |
| 70 | +is a CompositeType). | |
| 71 | + | |
| 72 | +Here is the basic architectural concept of *CQL*, a detailed explanation and *CQL* | |
| 73 | +examples can be found in this article : [http://www.planetcassandra.org/making-the-change-from-thrift-to-cql/](http://www.planetcassandra.org/making-the-change-from-thrift-to-cql/). | |
| 74 | +Understanding the *CQL* abstraction plays a key role in developing performing | |
| 75 | +and scaling applications. |
added upgrade_guide/migrating_from_astyanax/queries_and_results/README.md +106 −0
| @@ -0,0 +1,106 @@ | ||
| 1 | +# Queries and Results | |
| 2 | +There are many resources such as [this post][planetCCqlLink] or [this post][dsBlogCqlLink] to learn | |
| 3 | +how to transform previous Thrift operations to CQL queries. | |
| 4 | + | |
| 5 | +The *Java driver* executes CQL queries through the `Session`. | |
| 6 | +The queries can either be simple *CQL* Strings or represented in the form of | |
| 7 | +`Statement`s. The driver offers 4 kinds of statements, `SimpleStatement`, | |
| 8 | +`Prepared/BoundStatement`, `BuiltStatement`, and `BatchStatement`. All necessary | |
| 9 | +information can be [found here](../../../manual/statements/) about the nature of the different | |
| 10 | +`Statement`s. | |
| 11 | + | |
| 12 | +As explained in [the running section](../../../manual/#running-queries), | |
| 13 | +results of a *CQL* query will be in the form of *Rows* from *Tables*, composed | |
| 14 | +of fixed set of columns, each with a type and a name. The driver exposes the | |
| 15 | +set of *Rows* returned from a query as a ResultSet, thus containing *Rows* on | |
| 16 | +which `getXXX()` can be called. Here are simple examples of translation from | |
| 17 | +*Astyanax* to *Java driver* in querying and retrieving query results. | |
| 18 | + | |
| 19 | +## Single column | |
| 20 | + | |
| 21 | +*Astyanax*: | |
| 22 | + | |
| 23 | +```java | |
| 24 | +ColumnFamily<String, String> CF_STANDARD1 = new ColumnFamily<String, String>("cf1", StringSerializer.get(), StringSerializer.get(). StringSerializer.get()); | |
| 25 | + | |
| 26 | +Column<String> result = keyspace.prepareQuery(CF_STANDARD1) | |
| 27 | + .getKey("1") | |
| 28 | + .getColumn("3") | |
| 29 | + .execute().getResult(); | |
| 30 | +String value = result.getStringValue(); | |
| 31 | +``` | |
| 32 | + | |
| 33 | +*Java driver*: | |
| 34 | + | |
| 35 | +``` | |
| 36 | +Row row = session.execute("SELECT value FROM table1 WHERE key = '1' AND column1 = '3'").one(); | |
| 37 | +String value = row.getString("value"); | |
| 38 | +``` | |
| 39 | + | |
| 40 | +## All columns | |
| 41 | + | |
| 42 | +*Astyanax*: | |
| 43 | + | |
| 44 | +```java | |
| 45 | +ColumnList<String> columns; | |
| 46 | +int pagesize = 10; | |
| 47 | +RowQuery<String, String> query = keyspace | |
| 48 | + .prepareQuery(CF_STANDARD1) | |
| 49 | + .getKey("1") | |
| 50 | + .autoPaginate(true) | |
| 51 | + .withColumnRange(new RangeBuilder().setLimit(pagesize).build()); | |
| 52 | + | |
| 53 | +while (!(columns = query.execute().getResult()).isEmpty()) { | |
| 54 | + for (Column<String> c : columns) { | |
| 55 | + String value = c.getStringValue(); | |
| 56 | + } | |
| 57 | +} | |
| 58 | +``` | |
| 59 | + | |
| 60 | +*Java driver*: | |
| 61 | + | |
| 62 | +```java | |
| 63 | +ResultSet rs = session.execute("SELECT value FROM table1 WHERE key = '1'"); | |
| 64 | +for (Row row : rs) { | |
| 65 | + String value = row.getString("value"); | |
| 66 | +} | |
| 67 | +``` | |
| 68 | + | |
| 69 | +## Column range | |
| 70 | + | |
| 71 | +*Astyanax*: | |
| 72 | + | |
| 73 | +```java | |
| 74 | +ColumnList<String> result; | |
| 75 | +result = keyspace.prepareQuery(CF_STANDARD1) | |
| 76 | + .getKey("1") | |
| 77 | + .withColumnRange(new RangeBuilder().setStart("3").setEnd("5").setMaxSize(100).build()) | |
| 78 | + .execute().getResult(); | |
| 79 | + | |
| 80 | +Iterator<Column<String>> it = result.iterator(); | |
| 81 | +while (it.hasNext()) { | |
| 82 | + Column<String> col = it.next(); | |
| 83 | + String value = col.getStringValue(); | |
| 84 | +} | |
| 85 | +``` | |
| 86 | + | |
| 87 | +*Java driver*: | |
| 88 | + | |
| 89 | +```java | |
| 90 | +ResultSet rs = session.execute("SELECT value FROM table1 WHERE key = '1'" + | |
| 91 | + " AND column1 > '3'" + | |
| 92 | + " AND column1 < '5'"); | |
| 93 | +for (Row row : rs) { | |
| 94 | + String value = row.getString("value"); | |
| 95 | +} | |
| 96 | +``` | |
| 97 | + | |
| 98 | +## Async | |
| 99 | +The *Java driver* provides native support for asynchronous programming since it | |
| 100 | +is built on top of an [asynchronous protocol](../../../manual/native_protocol/), | |
| 101 | +please see [this page](../../../manual/async/) for best practices regarding asynchronous programming | |
| 102 | +with the *Java driver*. | |
| 103 | + | |
| 104 | + | |
| 105 | +[planetCCqlLink]: http://www.planetcassandra.org/making-the-change-from-thrift-to-cql/ | |
| 106 | +[dsBlogCqlLink]: http://www.datastax.com/dev/blog/thrift-to-cql3 | |
| No newline at the end of the file |