kikocis/java-driver public
Changesets · Branches · Tags · Compare
| Changeset | 8c8fb5365c18f6e6e3eb0449e9b7592102b514b9f581543bc8a7fdb94a30e47b |
|---|---|
| Author | olim7t <omichallat+github@gmail.com> · 2015-02-19 15:54 +01:00 |
| Committer | olim7t <omichallat+github@gmail.com> · 2015-02-19 16:09 +01:00 |
| Parents | 8aa2f039d03f, b1ca3ae13f03 |
39 files changed
modified driver-core/CHANGELOG.rst +32 −0
| @@ -4,6 +4,20 @@ | ||
| 4 | 4 | 2.1.5: |
| 5 | 5 | ------ |
| 6 | 6 | |
| 7 | +Merged from 2.0 branch: | |
| 8 | + | |
| 9 | +- [new feature] Add AddressTranslater for EC2 multi-region deployment (JAVA-518) | |
| 10 | +- [improvement] Add connection heartbeat (JAVA-533) | |
| 11 | +- [improvement] Reduce level of logs on missing rpc_address (JAVA-568) | |
| 12 | +- [bug] Prevent race between cancellation and query completion (JAVA-614) | |
| 13 | +- [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if | |
| 14 | + streamId was already released and reused (JAVA-632). | |
| 15 | +- [bug] Fix issue when newly opened pool fails before we could mark the node UP | |
| 16 | + (JAVA-642) | |
| 17 | +- [bug] Fix unwanted LBP notifications when a contact host is down (JAVA-613) | |
| 18 | +- [bug] Fix edge cases where a connection was released twice (JAVA-651). | |
| 19 | +- [bug] Fix edge cases in query cancellation (JAVA-653). | |
| 20 | + | |
| 7 | 21 | |
| 8 | 22 | 2.1.4: |
| 9 | 23 | ------ |
| @@ -153,6 +167,24 @@ | ||
| 153 | 167 | - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391) |
| 154 | 168 | |
| 155 | 169 | |
| 170 | +2.0.9.2: | |
| 171 | +-------- | |
| 172 | + | |
| 173 | +- [bug] Fix edge cases where a connection was released twice (JAVA-651). | |
| 174 | +- [bug] Fix edge cases in query cancellation (JAVA-653). | |
| 175 | + | |
| 176 | + | |
| 177 | +2.0.9.1: | |
| 178 | +-------- | |
| 179 | + | |
| 180 | +- [bug] Prevent race between cancellation and query completion (JAVA-614) | |
| 181 | +- [bug] Prevent cancel and timeout from cancelling unrelated ResponseHandler if | |
| 182 | + streamId was already released and reused (JAVA-632). | |
| 183 | +- [bug] Fix issue when newly opened pool fails before we could mark the node UP | |
| 184 | + (JAVA-642) | |
| 185 | +- [bug] Fix unwanted LBP notifications when a contact host is down (JAVA-613) | |
| 186 | + | |
| 187 | + | |
| 156 | 188 | 2.0.9: |
| 157 | 189 | ------ |
| 158 | 190 |
modified driver-core/pom.xml +14 −0
| @@ -89,6 +89,20 @@ | ||
| 89 | 89 | <scope>test</scope> |
| 90 | 90 | </dependency> |
| 91 | 91 | |
| 92 | + <dependency> | |
| 93 | + <groupId>org.scassandra</groupId> | |
| 94 | + <artifactId>java-client</artifactId> | |
| 95 | + <!-- N.B. later versions of scassandra require JDK 7 --> | |
| 96 | + <version>0.4.1</version> | |
| 97 | + <scope>test</scope> | |
| 98 | + <exclusions> | |
| 99 | + <exclusion> | |
| 100 | + <groupId>ch.qos.logback</groupId> | |
| 101 | + <artifactId>logback-classic</artifactId> | |
| 102 | + </exclusion> | |
| 103 | + </exclusions> | |
| 104 | + </dependency> | |
| 105 | + | |
| 92 | 106 | </dependencies> |
| 93 | 107 | |
| 94 | 108 | <build> |
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +4 −0
| @@ -1353,6 +1353,10 @@ | ||
| 1353 | 1353 | if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy) |
| 1354 | 1354 | ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close(); |
| 1355 | 1355 | |
| 1356 | + AddressTranslater translater = configuration.getPolicies().getAddressTranslater(); | |
| 1357 | + if (translater instanceof CloseableAddressTranslater) | |
| 1358 | + ((CloseableAddressTranslater)translater).close(); | |
| 1359 | + | |
| 1356 | 1360 | // Then we shutdown all connections |
| 1357 | 1361 | List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1); |
| 1358 | 1362 | futures.add(controlConnection.closeAsync()); |
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +115 −22
| @@ -19,6 +19,7 @@ | ||
| 19 | 19 | import java.net.InetSocketAddress; |
| 20 | 20 | import java.util.Iterator; |
| 21 | 21 | import java.util.concurrent.*; |
| 22 | +import java.util.concurrent.atomic.AtomicBoolean; | |
| 22 | 23 | import java.util.concurrent.atomic.AtomicInteger; |
| 23 | 24 | import java.util.concurrent.atomic.AtomicReference; |
| 24 | 25 | |
| @@ -31,6 +32,9 @@ | ||
| 31 | 32 | import org.jboss.netty.channel.group.DefaultChannelGroup; |
| 32 | 33 | import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; |
| 33 | 34 | import org.jboss.netty.handler.ssl.SslHandler; |
| 35 | +import org.jboss.netty.handler.timeout.IdleStateAwareChannelUpstreamHandler; | |
| 36 | +import org.jboss.netty.handler.timeout.IdleStateEvent; | |
| 37 | +import org.jboss.netty.handler.timeout.IdleStateHandler; | |
| 34 | 38 | import org.jboss.netty.util.HashedWheelTimer; |
| 35 | 39 | import org.jboss.netty.util.Timeout; |
| 36 | 40 | import org.jboss.netty.util.TimerTask; |
| @@ -89,7 +93,8 @@ | ||
| 89 | 93 | ClientBootstrap bootstrap = factory.newBootstrap(); |
| 90 | 94 | ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions(); |
| 91 | 95 | ProtocolVersion protocolVersion = factory.protocolVersion == null ? ProtocolVersion.NEWEST_SUPPORTED : factory.protocolVersion; |
| 92 | - bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions())); | |
| 96 | + bootstrap.setPipelineFactory(new PipelineFactory(this, protocolVersion, protocolOptions.getCompression().compressor, protocolOptions.getSSLOptions(), | |
| 97 | + factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds(), factory.timer)); | |
| 93 | 98 | |
| 94 | 99 | ChannelFuture future = bootstrap.connect(address); |
| 95 | 100 | |
| @@ -282,9 +287,19 @@ | ||
| 282 | 287 | // sure the "suspected" mechanism work as expected |
| 283 | 288 | Host host = factory.manager.metadata.getHost(address); |
| 284 | 289 | if (host != null) { |
| 290 | + | |
| 291 | + // If the host was reconnecting, and this error happens right after we opened a connection pool, but | |
| 292 | + // before we could mark the node UP, we don't want to go through the SUSPECTED state, because that can | |
| 293 | + // lead to a race condition that leaves the node UP with a closed pool. | |
| 294 | + boolean belongsToReconnectingPool = host.state != Host.State.UP && | |
| 295 | + this instanceof PooledConnection && | |
| 296 | + (((PooledConnection)this).pool == null || !((PooledConnection)this).pool.isClosed()); | |
| 297 | + | |
| 298 | + boolean markSuspected = isInitialized && !belongsToReconnectingPool; | |
| 299 | + | |
| 285 | 300 | // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant. |
| 286 | 301 | // This is not too much of a problem since calling onDown on a node that is already down has no effect. |
| 287 | - boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), isInitialized); | |
| 302 | + boolean isDown = factory.manager.signalConnectionFailure(host, ce, host.wasJustAdded(), markSuspected); | |
| 288 | 303 | notifyOwnerWhenDefunct(isDown); |
| 289 | 304 | } |
| 290 | 305 | |
| @@ -310,11 +325,12 @@ | ||
| 310 | 325 | if (this.keyspace != null && this.keyspace.equals(keyspace)) |
| 311 | 326 | return; |
| 312 | 327 | |
| 328 | + Future future = null; | |
| 313 | 329 | try { |
| 314 | 330 | logger.trace("{} Setting keyspace {}", this, keyspace); |
| 315 | 331 | long timeout = factory.getConnectTimeoutMillis(); |
| 316 | 332 | // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already |
| 317 | - Future future = write(new Requests.Query("USE \"" + keyspace + '"')); | |
| 333 | + future = write(new Requests.Query("USE \"" + keyspace + '"')); | |
| 318 | 334 | Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); |
| 319 | 335 | switch (response.type) { |
| 320 | 336 | case RESULT: |
| @@ -332,9 +348,16 @@ | ||
| 332 | 348 | } catch (ConnectionException e) { |
| 333 | 349 | throw defunct(e); |
| 334 | 350 | } catch (TimeoutException e) { |
| 351 | + // We've given up waiting on the future, but it's still running. Cancel to make sure that the request timeout logic | |
| 352 | + // (readTimeout) will not kick in, because that would release the connection. This will work since connectTimeout is | |
| 353 | + // generally lower than readTimeout (and if not, we'll get an ExecutionException and defunct below). | |
| 354 | + future.cancel(true); | |
| 335 | 355 | logger.warn(String.format("Timeout while setting keyspace on connection to %s. This should not happen but is not critical (it will retried)", address)); |
| 356 | + // Rethrow so that the caller will not try to use the connection, but do not defunct as we don't want to mark down | |
| 357 | + throw new ConnectionException(address, "Timeout while setting keyspace on connection"); | |
| 336 | 358 | } catch (BusyConnectionException e) { |
| 337 | 359 | logger.warn(String.format("Tried to set the keyspace on busy connection to %s. This should not happen but is not critical (it will retried)", address)); |
| 360 | + throw new ConnectionException(address, "Tried to set the keyspace on busy connection"); | |
| 338 | 361 | } catch (ExecutionException e) { |
| 339 | 362 | throw defunct(new ConnectionException(address, "Error while setting keyspace", e)); |
| 340 | 363 | } |
| @@ -356,6 +379,10 @@ | ||
| 356 | 379 | } |
| 357 | 380 | |
| 358 | 381 | public ResponseHandler write(ResponseCallback callback) throws ConnectionException, BusyConnectionException { |
| 382 | + return write(callback, true); | |
| 383 | + } | |
| 384 | + | |
| 385 | + public ResponseHandler write(ResponseCallback callback, boolean startTimeout) throws ConnectionException, BusyConnectionException { | |
| 359 | 386 | |
| 360 | 387 | Message.Request request = callback.request(); |
| 361 | 388 | |
| @@ -370,18 +397,22 @@ | ||
| 370 | 397 | * never leave a handler that won't get an answer or be errored out. |
| 371 | 398 | */ |
| 372 | 399 | if (isDefunct) { |
| 373 | - dispatcher.removeHandler(handler.streamId, true); | |
| 400 | + dispatcher.removeHandler(handler, true); | |
| 374 | 401 | throw new ConnectionException(address, "Write attempt on defunct connection"); |
| 375 | 402 | } |
| 376 | 403 | |
| 377 | 404 | if (isClosed()) { |
| 378 | - dispatcher.removeHandler(handler.streamId, true); | |
| 405 | + dispatcher.removeHandler(handler, true); | |
| 379 | 406 | throw new ConnectionException(address, "Connection has been closed"); |
| 380 | 407 | } |
| 381 | 408 | |
| 382 | 409 | logger.trace("{} writing request {}", this, request); |
| 383 | 410 | writer.incrementAndGet(); |
| 384 | 411 | channel.write(request).addListener(writeHandler(request, handler)); |
| 412 | + | |
| 413 | + if (startTimeout) | |
| 414 | + handler.startTimeout(); | |
| 415 | + | |
| 385 | 416 | return handler; |
| 386 | 417 | } |
| 387 | 418 | |
| @@ -396,7 +427,7 @@ | ||
| 396 | 427 | logger.debug("{} Error writing request {}", Connection.this, request); |
| 397 | 428 | // Remove this handler from the dispatcher so it don't get notified of the error |
| 398 | 429 | // twice (we will fail that method already) |
| 399 | - dispatcher.removeHandler(handler.streamId, true); | |
| 430 | + dispatcher.removeHandler(handler, true); | |
| 400 | 431 | |
| 401 | 432 | final ConnectionException ce; |
| 402 | 433 | if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) { |
| @@ -619,7 +650,7 @@ | ||
| 619 | 650 | } |
| 620 | 651 | } |
| 621 | 652 | |
| 622 | - private class Dispatcher extends SimpleChannelUpstreamHandler { | |
| 653 | + private class Dispatcher extends IdleStateAwareChannelUpstreamHandler { | |
| 623 | 654 | |
| 624 | 655 | public final StreamIdGenerator streamIdHandler; |
| 625 | 656 | private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>(); |
| @@ -640,19 +671,27 @@ | ||
| 640 | 671 | assert old == null; |
| 641 | 672 | } |
| 642 | 673 | |
| 643 | - public void removeHandler(int streamId, boolean releaseStreamId) { | |
| 674 | + public void removeHandler(ResponseHandler handler, boolean releaseStreamId) { | |
| 644 | 675 | |
| 645 | 676 | // If we don't release the ID, mark first so that we can rely later on the fact that if |
| 646 | 677 | // we receive a response for an ID with no handler, it's that this ID has been marked. |
| 647 | 678 | if (!releaseStreamId) |
| 648 | - streamIdHandler.mark(streamId); | |
| 649 | - | |
| 650 | - ResponseHandler handler = pending.remove(streamId); | |
| 651 | - if (handler != null) | |
| 652 | - handler.cancelTimeout(); | |
| 679 | + streamIdHandler.mark(handler.streamId); | |
| 680 | + | |
| 681 | + // If a RequestHandler is cancelled right when the response arrives, this method (called with releaseStreamId=false) will race with messageReceived. | |
| 682 | + // messageReceived could have already released the streamId, which could have already been reused by another request. We must not remove the handler | |
| 683 | + // if it's not ours, because that would cause the other request to hang forever. | |
| 684 | + boolean removed = pending.remove(handler.streamId, handler); | |
| 685 | + if (!removed) { | |
| 686 | + // We raced, so if we marked the streamId above, that was wrong. | |
| 687 | + if (!releaseStreamId) | |
| 688 | + streamIdHandler.unmark(handler.streamId); | |
| 689 | + return; | |
| 690 | + } | |
| 691 | + handler.cancelTimeout(); | |
| 653 | 692 | |
| 654 | 693 | if (releaseStreamId) |
| 655 | - streamIdHandler.release(streamId); | |
| 694 | + streamIdHandler.release(handler.streamId); | |
| 656 | 695 | |
| 657 | 696 | if (isClosed()) |
| 658 | 697 | tryTerminate(false); |
| @@ -703,6 +742,12 @@ | ||
| 703 | 742 | } |
| 704 | 743 | } |
| 705 | 744 | |
| 745 | + @Override | |
| 746 | + public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception { | |
| 747 | + logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds()); | |
| 748 | + write(HEARTBEAT_CALLBACK); | |
| 749 | + } | |
| 750 | + | |
| 706 | 751 | // Make sure we don't print huge responses in debug/error logs. |
| 707 | 752 | private String asDebugString(Object obj) { |
| 708 | 753 | if (obj == null) |
| @@ -751,6 +796,45 @@ | ||
| 751 | 796 | } |
| 752 | 797 | } |
| 753 | 798 | |
| 799 | + private static final ResponseCallback HEARTBEAT_CALLBACK = new ResponseCallback() { | |
| 800 | + | |
| 801 | + @Override | |
| 802 | + public Message.Request request() { | |
| 803 | + return new Requests.Options(); | |
| 804 | + } | |
| 805 | + | |
| 806 | + @Override | |
| 807 | + public int retryCount() { | |
| 808 | + return 0; // no retries here | |
| 809 | + } | |
| 810 | + | |
| 811 | + @Override | |
| 812 | + public void onSet(Connection connection, Message.Response response, long latency, int retryCount) { | |
| 813 | + switch (response.type) { | |
| 814 | + case SUPPORTED: | |
| 815 | + logger.debug("{} heartbeat query succeeded", connection); | |
| 816 | + break; | |
| 817 | + default: | |
| 818 | + fail(connection, new ConnectionException(connection.address, "Unexpected heartbeat response: " + response)); | |
| 819 | + } | |
| 820 | + } | |
| 821 | + | |
| 822 | + @Override | |
| 823 | + public void onException(Connection connection, Exception exception, long latency, int retryCount) { | |
| 824 | + // Nothing to do: the connection is already defunct if we arrive here | |
| 825 | + } | |
| 826 | + | |
| 827 | + @Override | |
| 828 | + public boolean onTimeout(Connection connection, long latency, int retryCount) { | |
| 829 | + fail(connection, new ConnectionException(connection.address, "Heartbeat query timed out")); | |
| 830 | + return true; | |
| 831 | + } | |
| 832 | + | |
| 833 | + private void fail(Connection connection, Exception e) { | |
| 834 | + connection.defunct(e); | |
| 835 | + } | |
| 836 | + }; | |
| 837 | + | |
| 754 | 838 | private class ConnectionCloseFuture extends CloseFuture { |
| 755 | 839 | |
| 756 | 840 | @Override |
| @@ -832,8 +916,7 @@ | ||
| 832 | 916 | public boolean onTimeout(Connection connection, long latency, int retryCount) { |
| 833 | 917 | assert connection != null; // We always timeout on a specific connection, so this shouldn't be null |
| 834 | 918 | this.address = connection.address; |
| 835 | - super.setException(new ConnectionException(connection.address, "Operation timed out")); | |
| 836 | - return true; | |
| 919 | + return super.setException(new OperationTimedOutException(connection.address)); | |
| 837 | 920 | } |
| 838 | 921 | |
| 839 | 922 | public InetSocketAddress getAddress() { |
| @@ -856,8 +939,10 @@ | ||
| 856 | 939 | public final ResponseCallback callback; |
| 857 | 940 | public final int retryCount; |
| 858 | 941 | |
| 859 | - private final Timeout timeout; | |
| 860 | 942 | private final long startTime; |
| 943 | + private volatile Timeout timeout; | |
| 944 | + | |
| 945 | + private final AtomicBoolean isCancelled = new AtomicBoolean(); | |
| 861 | 946 | |
| 862 | 947 | public ResponseHandler(Connection connection, ResponseCallback callback) throws BusyConnectionException { |
| 863 | 948 | this.connection = connection; |
| @@ -865,10 +950,12 @@ | ||
| 865 | 950 | this.callback = callback; |
| 866 | 951 | this.retryCount = callback.retryCount(); |
| 867 | 952 | |
| 953 | + this.startTime = System.nanoTime(); | |
| 954 | + } | |
| 955 | + | |
| 956 | + void startTimeout() { | |
| 868 | 957 | long timeoutMs = connection.factory.getReadTimeoutMillis(); |
| 869 | 958 | this.timeout = timeoutMs <= 0 ? null : connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS); |
| 870 | - | |
| 871 | - this.startTime = System.nanoTime(); | |
| 872 | 959 | } |
| 873 | 960 | |
| 874 | 961 | void cancelTimeout() { |
| @@ -877,11 +964,14 @@ | ||
| 877 | 964 | } |
| 878 | 965 | |
| 879 | 966 | public void cancelHandler() { |
| 967 | + if (!isCancelled.compareAndSet(false, true)) | |
| 968 | + return; | |
| 969 | + | |
| 880 | 970 | // We haven't really received a response: we want to remove the handle because we gave up on that |
| 881 | 971 | // request and there is no point in holding the handler, but we don't release the streamId. If we |
| 882 | 972 | // were, a new request could reuse that ID but get the answer to the request we just gave up on instead |
| 883 | 973 | // of its own answer, and we would have no way to detect that. |
| 884 | - connection.dispatcher.removeHandler(streamId, false); | |
| 974 | + connection.dispatcher.removeHandler(this, false); | |
| 885 | 975 | if (connection instanceof PooledConnection) |
| 886 | 976 | ((PooledConnection)connection).release(); |
| 887 | 977 | } |
| @@ -913,12 +1003,14 @@ | ||
| 913 | 1003 | private final Connection connection; |
| 914 | 1004 | private final FrameCompressor compressor; |
| 915 | 1005 | private final SSLOptions sslOptions; |
| 1006 | + private final ChannelHandler idleStateHandler; | |
| 916 | 1007 | |
| 917 | - public PipelineFactory(Connection connection, ProtocolVersion protocolVersion, FrameCompressor compressor, SSLOptions sslOptions) { | |
| 1008 | + public PipelineFactory(Connection connection, ProtocolVersion protocolVersion, FrameCompressor compressor, SSLOptions sslOptions, int heartBeatIntervalSeconds, HashedWheelTimer timer) { | |
| 918 | 1009 | this.connection = connection; |
| 919 | 1010 | this.protocolVersion = protocolVersion; |
| 920 | 1011 | this.compressor = compressor; |
| 921 | 1012 | this.sslOptions = sslOptions; |
| 1013 | + this.idleStateHandler = new IdleStateHandler(timer, 0, 0, heartBeatIntervalSeconds); | |
| 922 | 1014 | } |
| 923 | 1015 | |
| 924 | 1016 | @Override |
| @@ -945,9 +1037,10 @@ | ||
| 945 | 1037 | } |
| 946 | 1038 | |
| 947 | 1039 | pipeline.addLast("messageDecoder", messageDecoder); |
| 948 | - | |
| 949 | 1040 | pipeline.addLast("messageEncoder", messageEncoderFor(protocolVersion)); |
| 950 | 1041 | |
| 1042 | + pipeline.addLast("idleStateHandler", idleStateHandler); | |
| 1043 | + | |
| 951 | 1044 | pipeline.addLast("dispatcher", connection.dispatcher); |
| 952 | 1045 | |
| 953 | 1046 | return pipeline; |
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +11 −11
| @@ -411,7 +411,7 @@ | ||
| 411 | 411 | return null; |
| 412 | 412 | } else if (addr == null) { |
| 413 | 413 | if (logMissingRpcAddresses) |
| 414 | - logger.error("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", peer, connectedHost, peer); | |
| 414 | + logger.warn("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", peer, connectedHost, peer); | |
| 415 | 415 | return null; |
| 416 | 416 | } else if (addr.equals(bindAllAddress)) { |
| 417 | 417 | logger.warn("Found host with 0.0.0.0 as rpc_address, using listen_address ({}) to contact it instead. If this is incorrect you should avoid the use of 0.0.0.0 server side.", peer); |
| @@ -461,18 +461,18 @@ | ||
| 461 | 461 | // until the control connection is back up (which leads to a catch-22 if there is only one) |
| 462 | 462 | return true; |
| 463 | 463 | } else { |
| 464 | - logger.error("No row found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress()); | |
| 464 | + logger.warn("No row found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress()); | |
| 465 | 465 | return false; |
| 466 | 466 | } |
| 467 | 467 | // Ignore hosts with a null rpc_address, as this is most likely a phantom row in system.peers (JAVA-428). |
| 468 | 468 | // Don't test this for the control host since we're already connected to it anyway, and we read the info from system.local |
| 469 | 469 | // which doesn't have an rpc_address column (JAVA-546). |
| 470 | 470 | } else if (!c.address.equals(host.getSocketAddress()) && row.getInet("rpc_address") == null) { |
| 471 | - logger.error("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress()); | |
| 471 | + logger.warn("No rpc_address found for host {} in {}'s peers system table. {} will be ignored.", host.getAddress(), c.address, host.getAddress()); | |
| 472 | 472 | return false; |
| 473 | 473 | } |
| 474 | 474 | |
| 475 | - updateInfo(host, row, cluster); | |
| 475 | + updateInfo(host, row, cluster, false); | |
| 476 | 476 | return true; |
| 477 | 477 | |
| 478 | 478 | } catch (ConnectionException e) { |
| @@ -499,9 +499,9 @@ | ||
| 499 | 499 | } |
| 500 | 500 | |
| 501 | 501 | // row can come either from the 'local' table or the 'peers' one |
| 502 | - private static void updateInfo(Host host, Row row, Cluster.Manager cluster) { | |
| 502 | + private static void updateInfo(Host host, Row row, Cluster.Manager cluster, boolean isInitialConnection) { | |
| 503 | 503 | if (!row.isNull("data_center") || !row.isNull("rack")) |
| 504 | - updateLocationInfo(host, row.getString("data_center"), row.getString("rack"), cluster); | |
| 504 | + updateLocationInfo(host, row.getString("data_center"), row.getString("rack"), isInitialConnection, cluster); | |
| 505 | 505 | |
| 506 | 506 | String version = row.getString("release_version"); |
| 507 | 507 | // We don't know if it's a 'local' or a 'peers' row, and only 'peers' rows have the 'peer' field. |
| @@ -512,17 +512,17 @@ | ||
| 512 | 512 | host.setVersionAndListenAdress(version, listenAddress); |
| 513 | 513 | } |
| 514 | 514 | |
| 515 | - private static void updateLocationInfo(Host host, String datacenter, String rack, Cluster.Manager cluster) { | |
| 515 | + private static void updateLocationInfo(Host host, String datacenter, String rack, boolean isInitialConnection, Cluster.Manager cluster) { | |
| 516 | 516 | if (Objects.equal(host.getDatacenter(), datacenter) && Objects.equal(host.getRack(), rack)) |
| 517 | 517 | return; |
| 518 | 518 | |
| 519 | 519 | // If the dc/rack information changes for an existing node, we need to update the load balancing policy. |
| 520 | 520 | // For that, we remove and re-add the node against the policy. Not the most elegant, and assumes |
| 521 | 521 | // that the policy will update correctly, but in practice this should work. |
| 522 | - if (!host.wasJustAdded()) | |
| 522 | + if (!isInitialConnection) | |
| 523 | 523 | cluster.loadBalancingPolicy().onDown(host); |
| 524 | 524 | host.setLocationInfo(datacenter, rack); |
| 525 | - if (!host.wasJustAdded()) | |
| 525 | + if (!isInitialConnection) | |
| 526 | 526 | cluster.loadBalancingPolicy().onAdd(host); |
| 527 | 527 | } |
| 528 | 528 | |
| @@ -556,7 +556,7 @@ | ||
| 556 | 556 | if (host == null) { |
| 557 | 557 | logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address); |
| 558 | 558 | } else { |
| 559 | - updateInfo(host, localRow, cluster); | |
| 559 | + updateInfo(host, localRow, cluster, isInitialConnection); | |
| 560 | 560 | Set<String> tokens = localRow.getSet("tokens", String.class); |
| 561 | 561 | if (partitioner != null && !tokens.isEmpty()) |
| 562 | 562 | tokenMap.put(host, tokens); |
| @@ -593,7 +593,7 @@ | ||
| 593 | 593 | isNew = true; |
| 594 | 594 | } |
| 595 | 595 | if (dcs.get(i) != null || racks.get(i) != null) |
| 596 | - updateLocationInfo(host, dcs.get(i), racks.get(i), cluster); | |
| 596 | + updateLocationInfo(host, dcs.get(i), racks.get(i), isInitialConnection, cluster); | |
| 597 | 597 | if (cassandraVersions.get(i) != null) |
| 598 | 598 | host.setVersionAndListenAdress(cassandraVersions.get(i), listenAddresses.get(i)); |
| 599 | 599 |
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +1 −1
| @@ -167,7 +167,7 @@ | ||
| 167 | 167 | public boolean onTimeout(Connection connection, long latency, int retryCount) { |
| 168 | 168 | // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler). |
| 169 | 169 | // So just set an exception for the final result, which should be handled correctly by said internal call. |
| 170 | - setException(new ConnectionException(connection.address, "Operation timed out")); | |
| 170 | + setException(new OperationTimedOutException(connection.address)); | |
| 171 | 171 | return true; |
| 172 | 172 | } |
| 173 | 173 |
modified driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +2 −2
| @@ -250,6 +250,8 @@ | ||
| 250 | 250 | |
| 251 | 251 | @Override |
| 252 | 252 | public void returnConnection(PooledConnection connection) { |
| 253 | + int inFlight = connection.inFlight.decrementAndGet(); | |
| 254 | + | |
| 253 | 255 | if (isClosed()) { |
| 254 | 256 | close(connection); |
| 255 | 257 | return; |
| @@ -261,8 +263,6 @@ | ||
| 261 | 263 | return; |
| 262 | 264 | } |
| 263 | 265 | |
| 264 | - int inFlight = connection.inFlight.decrementAndGet(); | |
| 265 | - | |
| 266 | 266 | if (trash.contains(connection)) { |
| 267 | 267 | if (inFlight == 0 && trash.remove(connection)) |
| 268 | 268 | close(connection); |
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +9 −6
| @@ -207,14 +207,17 @@ | ||
| 207 | 207 | } |
| 208 | 208 | |
| 209 | 209 | /** |
| 210 | - * Triggers an asynchronous one-time reconnection attempt to this host. | |
| 210 | + * Triggers an asynchronous reconnection attempt to this host. | |
| 211 | 211 | * <p> |
| 212 | - * If reconnection succeeds, the host will be marked {@code UP} and its connection pool(s) | |
| 213 | - * will be initialized (unless the load balancing policy returns {@link HostDistance#IGNORED} | |
| 214 | - * for it). If reconnection fails, no further attempts will be scheduled. | |
| 212 | + * This method is intended for load balancing policies that mark hosts as {@link HostDistance#IGNORED IGNORED}, | |
| 213 | + * but still need a way to periodically check these hosts' states (UP / DOWN). | |
| 215 | 214 | * <p> |
| 216 | - * This method has no effect if the node is already {@code UP}, or if a reconnection attempt | |
| 217 | - * is already in progress. | |
| 215 | + * For a host that is at distance {@code IGNORED}, this method will try to reconnect exactly once: if | |
| 216 | + * reconnection succeeds, the host is marked {@code UP}; otherwise, no further attempts will be scheduled. | |
| 217 | + * It has no effect if the node is already {@code UP}, or if a reconnection attempt is already in progress. | |
| 218 | + * <p> | |
| 219 | + * Note that if the host is <em>not</em> a distance {@code IGNORED}, this method <em>will</em> trigger a periodic | |
| 220 | + * reconnection attempt if the reconnection fails. | |
| 218 | 221 | */ |
| 219 | 222 | public void tryReconnectOnce() { |
| 220 | 223 | this.manager.startSingleReconnectionAttempt(this); |
added driver-core/src/main/java/com/datastax/driver/core/OperationTimedOutException.java +13 −0
| @@ -0,0 +1,13 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.net.InetSocketAddress; | |
| 4 | + | |
| 5 | +/** | |
| 6 | + * Thrown on a client-side timeout, i.e. when the client didn't hear back from the server within | |
| 7 | + * {@link SocketOptions#getReadTimeoutMillis()}. | |
| 8 | + */ | |
| 9 | +class OperationTimedOutException extends ConnectionException { | |
| 10 | + public OperationTimedOutException(InetSocketAddress address) { | |
| 11 | + super(address, "Operation timed out"); | |
| 12 | + } | |
| 13 | +} |
modified driver-core/src/main/java/com/datastax/driver/core/PooledConnection.java +1 −1
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | */ |
| 24 | 24 | class PooledConnection extends Connection { |
| 25 | 25 | |
| 26 | - private final HostConnectionPool pool; | |
| 26 | + final HostConnectionPool pool; | |
| 27 | 27 | |
| 28 | 28 | /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */ |
| 29 | 29 | final AtomicBoolean markForTrash = new AtomicBoolean(); |
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +33 −0
| @@ -65,6 +65,7 @@ | ||
| 65 | 65 | private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256; |
| 66 | 66 | |
| 67 | 67 | private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000; |
| 68 | + private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30; | |
| 68 | 69 | |
| 69 | 70 | private volatile Cluster.Manager manager; |
| 70 | 71 | |
| @@ -79,6 +80,7 @@ | ||
| 79 | 80 | |
| 80 | 81 | |
| 81 | 82 | private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS; |
| 83 | + private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS; | |
| 82 | 84 | |
| 83 | 85 | public PoolingOptions() {} |
| 84 | 86 | |
| @@ -293,6 +295,37 @@ | ||
| 293 | 295 | return this; |
| 294 | 296 | } |
| 295 | 297 | |
| 298 | + /** | |
| 299 | + * Returns the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive. | |
| 300 | + * @return the interval. | |
| 301 | + */ | |
| 302 | + public int getHeartbeatIntervalSeconds() { | |
| 303 | + return heartbeatIntervalSeconds; | |
| 304 | + } | |
| 305 | + | |
| 306 | + /** | |
| 307 | + * Sets the heart beat interval, after which a message is sent on an idle connection to make sure it's still alive. | |
| 308 | + * <p> | |
| 309 | + * This is an application-level keep-alive, provided for convenience since adjusting the TCP keep-alive might not be | |
| 310 | + * practical in all environments. | |
| 311 | + * <p> | |
| 312 | + * This option should be set higher than {@link SocketOptions#getReadTimeoutMillis()}. | |
| 313 | + * <p> | |
| 314 | + * The default value for this option is 30 seconds. | |
| 315 | + * | |
| 316 | + * @param heartbeatIntervalSeconds the new value in seconds. If set to 0, it will disable the feature. | |
| 317 | + * @return this {@code PoolingOptions} | |
| 318 | + * | |
| 319 | + * @throws IllegalArgumentException if the interval is negative. | |
| 320 | + */ | |
| 321 | + public PoolingOptions setHeartbeatIntervalSeconds(int heartbeatIntervalSeconds) { | |
| 322 | + if (poolTimeoutMillis < 0) | |
| 323 | + throw new IllegalArgumentException("Heartbeat interval must be positive"); | |
| 324 | + | |
| 325 | + this.heartbeatIntervalSeconds = heartbeatIntervalSeconds; | |
| 326 | + return this; | |
| 327 | + } | |
| 328 | + | |
| 296 | 329 | /** |
| 297 | 330 | * Returns the maximum number of requests per host. |
| 298 | 331 | * <p> |
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +82 −35
| @@ -67,7 +67,6 @@ | ||
| 67 | 67 | |
| 68 | 68 | private volatile Map<InetSocketAddress, Throwable> errors; |
| 69 | 69 | |
| 70 | - private volatile boolean isCanceled; | |
| 71 | 70 | private volatile Connection.ResponseHandler connectionHandler; |
| 72 | 71 | |
| 73 | 72 | private final Timer.Context timerContext; |
| @@ -99,7 +98,7 @@ | ||
| 99 | 98 | |
| 100 | 99 | public void sendRequest() { |
| 101 | 100 | try { |
| 102 | - while (queryPlan.hasNext() && !isCanceled) { | |
| 101 | + while (queryPlan.hasNext() && !queryStateRef.get().isCancelled()) { | |
| 103 | 102 | Host host = queryPlan.next(); |
| 104 | 103 | logger.trace("Querying node {}", host); |
| 105 | 104 | if (query(host)) |
| @@ -126,7 +125,7 @@ | ||
| 126 | 125 | triedHosts.add(current); |
| 127 | 126 | } |
| 128 | 127 | current = host; |
| 129 | - connectionHandler = connection.write(this); | |
| 128 | + write(connection, this); | |
| 130 | 129 | return true; |
| 131 | 130 | } catch (ConnectionException e) { |
| 132 | 131 | // If we have any problem with the connection, move to the next node. |
| @@ -154,6 +153,38 @@ | ||
| 154 | 153 | } |
| 155 | 154 | } |
| 156 | 155 | |
| 156 | + private void write(Connection connection, Connection.ResponseCallback responseCallback) throws ConnectionException, BusyConnectionException { | |
| 157 | + // Make sure cancel() does not see a stale connectionHandler if it sees the new query state | |
| 158 | + // before connection.write has completed | |
| 159 | + connectionHandler = null; | |
| 160 | + | |
| 161 | + // Ensure query state is "in progress" (can be already if connection.write failed on a previous node and we're retrying) | |
| 162 | + while (true) { | |
| 163 | + QueryState previous = queryStateRef.get(); | |
| 164 | + if (previous.isCancelled()) { | |
| 165 | + if (connection instanceof PooledConnection) | |
| 166 | + ((PooledConnection)connection).release(); | |
| 167 | + return; | |
| 168 | + } | |
| 169 | + if (previous.inProgress || queryStateRef.compareAndSet(previous, previous.startNext())) | |
| 170 | + break; | |
| 171 | + } | |
| 172 | + | |
| 173 | + connectionHandler = connection.write(responseCallback, false); | |
| 174 | + // Only start the timeout when we're sure connectionHandler is set. This avoids an edge case where onTimeout() was triggered | |
| 175 | + // *before* the call to connection.write had returned. | |
| 176 | + connectionHandler.startTimeout(); | |
| 177 | + | |
| 178 | + // Note that we could have already received the response here (so onSet() / onException() would have been called). This is | |
| 179 | + // why we only test for CANCELLED_WHILE_IN_PROGRESS below. | |
| 180 | + | |
| 181 | + // If cancel() was called after we set the state to "in progress", but before connection.write had completed, it might have | |
| 182 | + // missed the new value of connectionHandler. So make sure that cancelHandler() gets called here (we might call it twice, | |
| 183 | + // but it knows how to deal with it). | |
| 184 | + if (queryStateRef.get() == QueryState.CANCELLED_WHILE_IN_PROGRESS) | |
| 185 | + connectionHandler.cancelHandler(); | |
| 186 | + } | |
| 187 | + | |
| 157 | 188 | private void logError(InetSocketAddress address, Throwable exception) { |
| 158 | 189 | logger.debug("Error querying {}, trying next host (error is: {})", address, exception.toString()); |
| 159 | 190 | if (errors == null) |
| @@ -162,8 +193,6 @@ | ||
| 162 | 193 | } |
| 163 | 194 | |
| 164 | 195 | private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) { |
| 165 | - queryStateRef.set(queryStateRef.get().startNext()); | |
| 166 | - | |
| 167 | 196 | final Host h = current; |
| 168 | 197 | this.retryConsistencyLevel = newConsistencyLevel; |
| 169 | 198 | |
| @@ -171,6 +200,8 @@ | ||
| 171 | 200 | manager.executor().execute(new Runnable() { |
| 172 | 201 | @Override |
| 173 | 202 | public void run() { |
| 203 | + if (queryStateRef.get().isCancelled()) | |
| 204 | + return; | |
| 174 | 205 | try { |
| 175 | 206 | if (retryCurrent) { |
| 176 | 207 | if (query(h)) |
| @@ -185,9 +216,22 @@ | ||
| 185 | 216 | } |
| 186 | 217 | |
| 187 | 218 | public void cancel() { |
| 188 | - isCanceled = true; | |
| 189 | - if (connectionHandler != null) | |
| 190 | - connectionHandler.cancelHandler(); | |
| 219 | + // Atomically set a special QueryState, that will cause any further operation to abort. | |
| 220 | + // We want to remember whether a request was in progress when we did this, so there are two cancel states. | |
| 221 | + while (true) { | |
| 222 | + QueryState previous = queryStateRef.get(); | |
| 223 | + if (previous.isCancelled()) { | |
| 224 | + return; | |
| 225 | + } else if (previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_IN_PROGRESS)) { | |
| 226 | + // The connectionHandler should be non-null, but we might miss the update if we're racing with write(). | |
| 227 | + // If it's still null, this will be handled by re-checking queryStateRef at the end of write(). | |
| 228 | + if (connectionHandler != null) | |
| 229 | + connectionHandler.cancelHandler(); | |
| 230 | + return; | |
| 231 | + } else if (!previous.inProgress && queryStateRef.compareAndSet(previous, QueryState.CANCELLED_WHILE_COMPLETE)) { | |
| 232 | + return; | |
| 233 | + } | |
| 234 | + } | |
| 191 | 235 | } |
| 192 | 236 | |
| 193 | 237 | @Override |
| @@ -272,10 +316,8 @@ | ||
| 272 | 316 | } |
| 273 | 317 | |
| 274 | 318 | Host queriedHost = current; |
| 319 | + boolean releaseConnection = true; | |
| 275 | 320 | try { |
| 276 | - if (connection instanceof PooledConnection) | |
| 277 | - ((PooledConnection)connection).release(); | |
| 278 | - | |
| 279 | 321 | switch (response.type) { |
| 280 | 322 | case RESULT: |
| 281 | 323 | setFinalResult(connection, response); |
| @@ -384,31 +426,23 @@ | ||
| 384 | 426 | return; |
| 385 | 427 | } |
| 386 | 428 | |
| 387 | - logger.info("Query {} is not prepared on {}, preparing before retrying executing. " | |
| 388 | - + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems", | |
| 389 | - toPrepare.getQueryString(), connection.address); | |
| 390 | 429 | String currentKeyspace = connection.keyspace(); |
| 391 | 430 | String prepareKeyspace = toPrepare.getQueryKeyspace(); |
| 392 | - // This shouldn't happen in normal use, because a user shouldn't try to execute | |
| 393 | - // a prepared statement with the wrong keyspace set. However, if it does, we'd rather | |
| 394 | - // prepare the query correctly and let the query executing return a meaningful error message | |
| 395 | - if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace))) | |
| 396 | - { | |
| 397 | - logger.debug("Setting keyspace for prepared query to {}", prepareKeyspace); | |
| 398 | - connection.setKeyspace(prepareKeyspace); | |
| 431 | + if (prepareKeyspace != null && (currentKeyspace == null || !currentKeyspace.equals(prepareKeyspace))) { | |
| 432 | + // This shouldn't happen in normal use, because a user shouldn't try to execute | |
| 433 | + // a prepared statement with the wrong keyspace set. | |
| 434 | + // Fail fast (we can't change the keyspace to reprepare, because we're using a pooled connection | |
| 435 | + // that's shared with other requests). | |
| 436 | + throw new IllegalStateException(String.format("Statement was prepared on keyspace %s, can't execute it on %s (%s)", | |
| 437 | + toPrepare.getQueryKeyspace(), connection.keyspace(), toPrepare.getQueryString())); | |
| 399 | 438 | } |
| 400 | 439 | |
| 401 | - queryStateRef.set(queryStateRef.get().startNext()); | |
| 402 | - try { | |
| 403 | - connection.write(prepareAndRetry(toPrepare.getQueryString())); | |
| 404 | - } finally { | |
| 405 | - // Always reset the previous keyspace if needed | |
| 406 | - if (connection.keyspace() == null || !connection.keyspace().equals(currentKeyspace)) | |
| 407 | - { | |
| 408 | - logger.debug("Setting back keyspace post query preparation to {}", currentKeyspace); | |
| 409 | - connection.setKeyspace(currentKeyspace); | |
| 410 | - } | |
| 411 | - } | |
| 440 | + logger.info("Query {} is not prepared on {}, preparing before retrying executing. " | |
| 441 | + + "Seeing this message a few times is fine, but seeing it a lot may be source of performance problems", | |
| 442 | + toPrepare.getQueryString(), connection.address); | |
| 443 | + | |
| 444 | + releaseConnection = false; // we're reusing it for the prepare call | |
| 445 | + write(connection, prepareAndRetry(toPrepare.getQueryString())); | |
| 412 | 446 | // we're done for now, the prepareAndRetry callback will handle the rest |
| 413 | 447 | return; |
| 414 | 448 | default: |
| @@ -447,6 +481,9 @@ | ||
| 447 | 481 | } catch (Exception e) { |
| 448 | 482 | setFinalException(connection, e); |
| 449 | 483 | } finally { |
| 484 | + if (releaseConnection && connection instanceof PooledConnection) | |
| 485 | + ((PooledConnection)connection).release(); | |
| 486 | + | |
| 450 | 487 | if (queriedHost != null) |
| 451 | 488 | manager.cluster.manager.reportLatency(queriedHost, latency); |
| 452 | 489 | } |
| @@ -475,6 +512,9 @@ | ||
| 475 | 512 | return; |
| 476 | 513 | } |
| 477 | 514 | |
| 515 | + if (connection instanceof PooledConnection) | |
| 516 | + ((PooledConnection)connection).release(); | |
| 517 | + | |
| 478 | 518 | // TODO should we check the response ? |
| 479 | 519 | switch (response.type) { |
| 480 | 520 | case RESULT: |
| @@ -593,10 +633,13 @@ | ||
| 593 | 633 | } |
| 594 | 634 | |
| 595 | 635 | // This is used to prevent races between request completion (either success or error) and timeout. |
| 596 | - // A retry is in progress once we have written the request to the connection and until we get back a response or a timeout. | |
| 636 | + // A retry is in progress once we have written the request to the connection and until we get back a response (see onSet | |
| 637 | + // or onException) or a timeout (see onTimeout). | |
| 597 | 638 | // The count increments on each retry. |
| 598 | 639 | static class QueryState { |
| 599 | - static QueryState INITIAL = new QueryState(0, true); | |
| 640 | + static final QueryState INITIAL = new QueryState(-1, false); | |
| 641 | + static final QueryState CANCELLED_WHILE_IN_PROGRESS = new QueryState(Integer.MIN_VALUE, false); | |
| 642 | + static final QueryState CANCELLED_WHILE_COMPLETE = new QueryState(Integer.MIN_VALUE + 1, false); | |
| 600 | 643 | |
| 601 | 644 | final int retryCount; |
| 602 | 645 | final boolean inProgress; |
| @@ -620,9 +663,13 @@ | ||
| 620 | 663 | return new QueryState(retryCount + 1, true); |
| 621 | 664 | } |
| 622 | 665 | |
| 666 | + public boolean isCancelled() { | |
| 667 | + return this == CANCELLED_WHILE_IN_PROGRESS || this == CANCELLED_WHILE_COMPLETE; | |
| 668 | + } | |
| 669 | + | |
| 623 | 670 | @Override |
| 624 | 671 | public String toString() { |
| 625 | - return String.format("QueryState(count=%d, inProgress=%s)", retryCount, inProgress); | |
| 672 | + return String.format("QueryState(count=%d, inProgress=%s, cancelled=%s)", retryCount, inProgress, isCancelled()); | |
| 626 | 673 | } |
| 627 | 674 | } |
| 628 | 675 | } |
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +4 −1
| @@ -538,6 +538,7 @@ | ||
| 538 | 538 | // Let's not wait too long if we can't get a connection. Things |
| 539 | 539 | // will fix themselves once the user tries a query anyway. |
| 540 | 540 | PooledConnection c = null; |
| 541 | + boolean timedOut = false; | |
| 541 | 542 | try { |
| 542 | 543 | c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS); |
| 543 | 544 | c.write(new Requests.Prepare(query)).get(); |
| @@ -551,8 +552,10 @@ | ||
| 551 | 552 | // We shouldn't really get exception while preparing a |
| 552 | 553 | // query, so log this (but ignore otherwise as it's not a big deal) |
| 553 | 554 | logger.error(String.format("Unexpected error while preparing query (%s) on %s", query, entry.getKey()), e); |
| 555 | + // If the query timed out, that already released the connection | |
| 556 | + timedOut = e.getCause() instanceof OperationTimedOutException; | |
| 554 | 557 | } finally { |
| 555 | - if (c != null) | |
| 558 | + if (c != null && !timedOut) | |
| 556 | 559 | c.release(); |
| 557 | 560 | } |
| 558 | 561 | } |
added driver-core/src/main/java/com/datastax/driver/core/policies/CloseableAddressTranslater.java +32 −0
| @@ -0,0 +1,32 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import com.datastax.driver.core.Cluster; | |
| 19 | + | |
| 20 | +/** | |
| 21 | + * Extends {@link AddressTranslater} for implementations that need to free some resources | |
| 22 | + * at {@link Cluster} shutdown. | |
| 23 | + * <p> | |
| 24 | + * Note: the only reason {@link #close()} was not added directly to {@code AddressTranslater} | |
| 25 | + * is backward-compatibility. | |
| 26 | + */ | |
| 27 | +public interface CloseableAddressTranslater extends AddressTranslater { | |
| 28 | + /** | |
| 29 | + * Called at {@link Cluster} shutdown. | |
| 30 | + */ | |
| 31 | + void close(); | |
| 32 | +} |
added driver-core/src/main/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslater.java +144 −0
| @@ -0,0 +1,144 @@ | ||
| 1 | +/* | |
| 2 | + * Copyright (C) 2012-2014 DataStax Inc. | |
| 3 | + * | |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); | |
| 5 | + * you may not use this file except in compliance with the License. | |
| 6 | + * You may obtain a copy of the License at | |
| 7 | + * | |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 | |
| 9 | + * | |
| 10 | + * Unless required by applicable law or agreed to in writing, software | |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, | |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| 13 | + * See the License for the specific language governing permissions and | |
| 14 | + * limitations under the License. | |
| 15 | + */ | |
| 16 | +package com.datastax.driver.core.policies; | |
| 17 | + | |
| 18 | +import java.net.InetAddress; | |
| 19 | +import java.net.InetSocketAddress; | |
| 20 | +import java.util.Enumeration; | |
| 21 | +import java.util.Hashtable; | |
| 22 | + | |
| 23 | +import com.google.common.annotations.VisibleForTesting; | |
| 24 | +import javax.naming.Context; | |
| 25 | +import javax.naming.NamingEnumeration; | |
| 26 | +import javax.naming.NamingException; | |
| 27 | +import javax.naming.directory.Attribute; | |
| 28 | +import javax.naming.directory.Attributes; | |
| 29 | +import javax.naming.directory.DirContext; | |
| 30 | +import javax.naming.directory.InitialDirContext; | |
| 31 | +import org.slf4j.Logger; | |
| 32 | +import org.slf4j.LoggerFactory; | |
| 33 | + | |
| 34 | +import com.datastax.driver.core.exceptions.DriverException; | |
| 35 | + | |
| 36 | +/** | |
| 37 | + * {@link AddressTranslater} implementation for a multi-region EC2 deployment <b>where clients are also deployed in EC2</b>. | |
| 38 | + * <p> | |
| 39 | + * Its distinctive feature is that it translates addresses according to the location of the Cassandra host: | |
| 40 | + * <ul> | |
| 41 | + * <li>addresses in different EC2 regions (than the client) are unchanged;</li> | |
| 42 | + * <li>addresses in the same EC2 region are <b>translated to private IPs</b>.</li> | |
| 43 | + * </ul> | |
| 44 | + * This optimizes network costs, because Amazon charges more for communication over public IPs. | |
| 45 | + * | |
| 46 | + * <p> | |
| 47 | + * Implementation note: this class performs a reverse DNS lookup of the origin address, to find the domain name of the target | |
| 48 | + * instance. Then it performs a forward DNS lookup of the domain name; the EC2 DNS does the private/public switch automatically | |
| 49 | + * based on location. | |
| 50 | + */ | |
| 51 | +public class EC2MultiRegionAddressTranslater implements CloseableAddressTranslater { | |
| 52 | + | |
| 53 | + private static final Logger logger = LoggerFactory.getLogger(EC2MultiRegionAddressTranslater.class); | |
| 54 | + | |
| 55 | + // TODO when we switch to Netty 4.1, we can replace this with the Netty built-in DNS client | |
| 56 | + private final DirContext ctx; | |
| 57 | + | |
| 58 | + public EC2MultiRegionAddressTranslater() { | |
| 59 | + Hashtable<Object, Object> env = new Hashtable<Object, Object>(); | |
| 60 | + env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory"); | |
| 61 | + try { | |
| 62 | + ctx = new InitialDirContext(env); | |
| 63 | + } catch (NamingException e) { | |
| 64 | + throw new DriverException("Could not create translater", e); | |
| 65 | + } | |
| 66 | + } | |
| 67 | + | |
| 68 | + @VisibleForTesting | |
| 69 | + EC2MultiRegionAddressTranslater(DirContext ctx) { | |
| 70 | + this.ctx = ctx; | |
| 71 | + } | |
| 72 | + | |
| 73 | + @Override | |
| 74 | + public InetSocketAddress translate(InetSocketAddress socketAddress) { | |
| 75 | + InetAddress address = socketAddress.getAddress(); | |
| 76 | + try { | |
| 77 | + // InetAddress#getHostName() is supposed to perform a reverse DNS lookup, but for some reason it doesn't work | |
| 78 | + // within the same EC2 region (it returns the IP address itself). | |
| 79 | + // We use an alternate implementation: | |
| 80 | + String domainName = lookupPtrRecord(reverse(address)); | |
| 81 | + if (domainName == null) { | |
| 82 | + logger.warn("Found no domain name for {}, returning it as-is", address); | |
| 83 | + return socketAddress; | |
| 84 | + } | |
| 85 | + | |
| 86 | + InetAddress translatedAddress = InetAddress.getByName(domainName); | |
| 87 | + logger.debug("Resolved {} to {}", address, translatedAddress); | |
| 88 | + return new InetSocketAddress(translatedAddress, socketAddress.getPort()); | |
| 89 | + } catch (Exception e) { | |
| 90 | + logger.warn("Error resolving " + address + ", returning it as-is", e); | |
| 91 | + return socketAddress; | |
| 92 | + } | |
| 93 | + } | |
| 94 | + | |
| 95 | + private String lookupPtrRecord(String reversedDomain) throws Exception { | |
| 96 | + Attributes attrs = ctx.getAttributes(reversedDomain, new String[]{ "PTR" }); | |
| 97 | + for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements(); ) { | |
| 98 | + Attribute attr = (Attribute)ae.next(); | |
| 99 | + for (Enumeration<?> vals = attr.getAll(); vals.hasMoreElements(); ) | |
| 100 | + return vals.nextElement().toString(); | |
| 101 | + } | |
| 102 | + return null; | |
| 103 | + } | |
| 104 | + | |
| 105 | + public void close() { | |
| 106 | + try { | |
| 107 | + ctx.close(); | |
| 108 | + } catch (NamingException e) { | |
| 109 | + logger.warn("Error closing translater", e); | |
| 110 | + } | |
| 111 | + } | |
| 112 | + | |
| 113 | + // Builds the "reversed" domain name in the ARPA domain to perform the reverse lookup | |
| 114 | + @VisibleForTesting | |
| 115 | + static String reverse(InetAddress address) { | |
| 116 | + byte[] bytes = address.getAddress(); | |
| 117 | + if (bytes.length == 4) | |
| 118 | + return reverseIpv4(bytes); | |
| 119 | + else | |
| 120 | + return reverseIpv6(bytes); | |
| 121 | + } | |
| 122 | + | |
| 123 | + private static String reverseIpv4(byte[] bytes) { | |
| 124 | + StringBuilder builder = new StringBuilder(); | |
| 125 | + for (int i = bytes.length - 1; i >= 0; i--) { | |
| 126 | + builder.append(bytes[i] & 0xFF).append('.'); | |
| 127 | + } | |
| 128 | + builder.append("in-addr.arpa"); | |
| 129 | + return builder.toString(); | |
| 130 | + } | |
| 131 | + | |
| 132 | + private static String reverseIpv6(byte[] bytes) { | |
| 133 | + StringBuilder builder = new StringBuilder(); | |
| 134 | + for (int i = bytes.length - 1; i >= 0; i--) { | |
| 135 | + byte b = bytes[i]; | |
| 136 | + int lowNibble = b & 0x0F; | |
| 137 | + int highNibble = b >> 4 & 0x0F; | |
| 138 | + builder.append(Integer.toHexString(lowNibble)).append('.') | |
| 139 | + .append(Integer.toHexString(highNibble)).append('.'); | |
| 140 | + } | |
| 141 | + builder.append("ip6.arpa"); | |
| 142 | + return builder.toString(); | |
| 143 | + } | |
| 144 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/BatchStatementTest.java +4 −5
| @@ -20,12 +20,12 @@ | ||
| 20 | 20 | |
| 21 | 21 | import org.testng.annotations.Test; |
| 22 | 22 | |
| 23 | -import com.datastax.driver.core.exceptions.UnsupportedFeatureException; | |
| 24 | - | |
| 25 | -import static com.datastax.driver.core.TestUtils.versionCheck; | |
| 26 | 23 | import static org.testng.Assert.assertEquals; |
| 27 | 24 | import static org.testng.Assert.assertTrue; |
| 28 | 25 | |
| 26 | +import com.datastax.driver.core.exceptions.UnsupportedFeatureException; | |
| 27 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 28 | + | |
| 29 | 29 | public class BatchStatementTest extends CCMBridge.PerClassSingleNodeCluster { |
| 30 | 30 | |
| 31 | 31 | @Override |
| @@ -80,9 +80,8 @@ | ||
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 82 | @Test(groups = "short") |
| 83 | + @CassandraVersion(major=2.0, minor=9, description="This will only work with C* 2.0.9 (CASSANDRA-7337)") | |
| 83 | 84 | public void casBatchTest() throws Throwable { |
| 84 | - versionCheck(2.0, 9, "This will only work with C* 2.0.9 (CASSANDRA-7337)"); | |
| 85 | - | |
| 86 | 85 | try { |
| 87 | 86 | PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS"); |
| 88 | 87 |
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +19 −10
| @@ -18,10 +18,13 @@ | ||
| 18 | 18 | import static org.mockito.Mockito.verify; |
| 19 | 19 | |
| 20 | 20 | import com.datastax.driver.core.policies.ConstantReconnectionPolicy; |
| 21 | +import com.datastax.driver.core.querybuilder.Insert; | |
| 21 | 22 | import com.datastax.driver.core.utils.UUIDs; |
| 22 | 23 | |
| 23 | 24 | import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS; |
| 24 | 25 | |
| 26 | +import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto; | |
| 27 | + | |
| 25 | 28 | public class ClusterInitTest { |
| 26 | 29 | private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class); |
| 27 | 30 | |
| @@ -68,6 +71,7 @@ | ||
| 68 | 71 | CCMBridge.ipOfNode(4), CCMBridge.ipOfNode(5), CCMBridge.ipOfNode(6)) |
| 69 | 72 | .withSocketOptions(socketOptions) |
| 70 | 73 | .withReconnectionPolicy(reconnectionPolicy) |
| 74 | + .withProtocolVersion(TestUtils.getDesiredProtocolVersion()) | |
| 71 | 75 | .build(); |
| 72 | 76 | cluster.connect(); |
| 73 | 77 | |
| @@ -77,7 +81,10 @@ | ||
| 77 | 81 | |
| 78 | 82 | // We have one live host so 2 successful connections (1 control connection and 1 core connection in the pool). |
| 79 | 83 | // The other 5 hosts are unreachable, we should attempt to connect to each of them only once. |
| 80 | - verify(socketOptions, times(2 + 5)).getKeepAlive(); | |
| 84 | + int coreConnections = cluster.getConfiguration() | |
| 85 | + .getPoolingOptions() | |
| 86 | + .getCoreConnectionsPerHost(HostDistance.LOCAL); | |
| 87 | + verify(socketOptions, times(1 + coreConnections + 5)).getKeepAlive(); | |
| 81 | 88 | } finally { |
| 82 | 89 | if (cluster != null) |
| 83 | 90 | cluster.close(); |
| @@ -97,15 +104,17 @@ | ||
| 97 | 104 | String releaseVersion = session.execute("SELECT release_version FROM local") |
| 98 | 105 | .one().getString("release_version"); |
| 99 | 106 | |
| 100 | - for (int i = 2; i <= 6; i++) | |
| 101 | - session.execute("INSERT INTO peers (peer, data_center, host_id, rack, release_version, rpc_address, schema_version) " + | |
| 102 | - "VALUES (?, 'datacenter1', ?, 'rack1', ?, ?, ?)", | |
| 103 | - InetAddress.getByName(CCMBridge.ipOfNode(i)), | |
| 104 | - UUIDs.random(), | |
| 105 | - releaseVersion, | |
| 106 | - InetAddress.getByName(CCMBridge.ipOfNode(i)), | |
| 107 | - UUIDs.random() | |
| 108 | - ); | |
| 107 | + for (int i = 2; i <= 6; i++) { | |
| 108 | + Insert insertStmt = insertInto("peers") | |
| 109 | + .value("peer", InetAddress.getByName(CCMBridge.ipOfNode(i))) | |
| 110 | + .value("data_center", "datacenter1") | |
| 111 | + .value("host_id", UUIDs.random()) | |
| 112 | + .value("rack", "rack1") | |
| 113 | + .value("release_version", releaseVersion) | |
| 114 | + .value("rpc_address", InetAddress.getByName(CCMBridge.ipOfNode(i))) | |
| 115 | + .value("schema_version", UUIDs.random()); | |
| 116 | + session.execute(insertStmt); | |
| 117 | + } | |
| 109 | 118 | } catch (Exception e) { |
| 110 | 119 | fail("Error while inserting fake peer rows", e); |
| 111 | 120 | } finally { |
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +3 −0
| @@ -6,9 +6,12 @@ | ||
| 6 | 6 | import org.testng.annotations.Test; |
| 7 | 7 | import static org.testng.Assert.*; |
| 8 | 8 | |
| 9 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 10 | + | |
| 9 | 11 | /** |
| 10 | 12 | * Test {@link ResultSet#wasApplied()} for conditional updates. |
| 11 | 13 | */ |
| 14 | +@CassandraVersion(major=2.0, description="Conditional Updates requires 2.0+.") | |
| 12 | 15 | public class ConditionalUpdateTest extends CCMBridge.PerClassSingleNodeCluster { |
| 13 | 16 | |
| 14 | 17 | @Override |
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +2 −2
| @@ -30,6 +30,7 @@ | ||
| 30 | 30 | import static org.testng.Assert.assertEquals; |
| 31 | 31 | import static org.testng.Assert.assertTrue; |
| 32 | 32 | |
| 33 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 33 | 34 | |
| 34 | 35 | /** |
| 35 | 36 | * Tests DataType class to ensure data sent in is the same as data received |
| @@ -431,9 +432,8 @@ | ||
| 431 | 432 | } |
| 432 | 433 | |
| 433 | 434 | @Test(groups = "short") |
| 435 | + @CassandraVersion(major=2.0, minor=0, description="This feature requires protocol v2") | |
| 434 | 436 | public void primitiveInsertWithValueTest() throws Throwable { |
| 435 | - TestUtils.versionCheck(2.0, 0, "This feature requires protocol v2"); | |
| 436 | - | |
| 437 | 437 | for (DataType dt : DataType.allPrimitiveTypes()) { |
| 438 | 438 | if (exclude(dt)) |
| 439 | 439 | continue; |
added driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +139 −0
| @@ -0,0 +1,139 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import static java.util.concurrent.TimeUnit.SECONDS; | |
| 4 | + | |
| 5 | +import org.apache.log4j.Level; | |
| 6 | +import org.apache.log4j.Logger; | |
| 7 | +import org.testng.annotations.AfterMethod; | |
| 8 | +import org.testng.annotations.BeforeMethod; | |
| 9 | +import org.testng.annotations.Test; | |
| 10 | + | |
| 11 | +import static com.datastax.driver.core.Assertions.assertThat; | |
| 12 | + | |
| 13 | +public class HeartbeatTest { | |
| 14 | + | |
| 15 | + Logger connectionLogger = Logger.getLogger(Connection.class); | |
| 16 | + MemoryAppender logs; | |
| 17 | + | |
| 18 | + @BeforeMethod(groups = "long") | |
| 19 | + public void startCapturingLogs() { | |
| 20 | + connectionLogger.setLevel(Level.DEBUG); | |
| 21 | + logs = new MemoryAppender(); | |
| 22 | + connectionLogger.addAppender(logs); | |
| 23 | + } | |
| 24 | + | |
| 25 | + @AfterMethod(groups="long") | |
| 26 | + public void stopCapturingLogs() { | |
| 27 | + connectionLogger.setLevel(null); | |
| 28 | + connectionLogger.removeAppender(logs); | |
| 29 | + } | |
| 30 | + | |
| 31 | + /** | |
| 32 | + * Ensures that a heartbeat message is sent after the configured heartbeat interval of idle time and succeeds and | |
| 33 | + * continues to be sent as long as the connection remains idle. | |
| 34 | + * | |
| 35 | + * @test_category connection:heartbeat | |
| 36 | + * @expected_result heartbeat is sent after heartbeat interval (3) seconds of idle time. | |
| 37 | + * @jira_ticket JAVA-533 | |
| 38 | + * @since 2.0.10, 2.1.5 | |
| 39 | + */ | |
| 40 | + @Test(groups = "long") | |
| 41 | + public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException { | |
| 42 | + CCMBridge ccm = null; | |
| 43 | + Cluster cluster = null; | |
| 44 | + try { | |
| 45 | + ccm = CCMBridge.create("test", 1); | |
| 46 | + cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)) | |
| 47 | + .withPoolingOptions(new PoolingOptions() | |
| 48 | + .setHeartbeatIntervalSeconds(3)) | |
| 49 | + .build(); | |
| 50 | + | |
| 51 | + // Don't create any session, only the control connection will be established | |
| 52 | + cluster.init(); | |
| 53 | + | |
| 54 | + for (int i = 0; i < 5; i++) { | |
| 55 | + triggerRequestOnControlConnection(cluster); | |
| 56 | + SECONDS.sleep(1); | |
| 57 | + } | |
| 58 | + assertThat(logs.getNext()).doesNotContain("sending heartbeat"); | |
| 59 | + | |
| 60 | + // Ensure heartbeat is sent after no activity. | |
| 61 | + SECONDS.sleep(4); | |
| 62 | + assertThat(logs.getNext()) | |
| 63 | + .contains("sending heartbeat") | |
| 64 | + .contains("heartbeat query succeeded"); | |
| 65 | + | |
| 66 | + // Ensure heartbeat is sent after continued inactivity. | |
| 67 | + SECONDS.sleep(4); | |
| 68 | + assertThat(logs.getNext()) | |
| 69 | + .contains("sending heartbeat") | |
| 70 | + .contains("heartbeat query succeeded"); | |
| 71 | + | |
| 72 | + // Ensure heartbeat is not sent after activity. | |
| 73 | + logs.getNext(); | |
| 74 | + for (int i = 0; i < 5; i++) { | |
| 75 | + triggerRequestOnControlConnection(cluster); | |
| 76 | + SECONDS.sleep(1); | |
| 77 | + } | |
| 78 | + assertThat(logs.getNext()).doesNotContain("sending heartbeat"); | |
| 79 | + | |
| 80 | + // Finally, ensure heartbeat is sent after inactivity. | |
| 81 | + SECONDS.sleep(4); | |
| 82 | + assertThat(logs.getNext()) | |
| 83 | + .contains("sending heartbeat") | |
| 84 | + .contains("heartbeat query succeeded"); | |
| 85 | + } finally { | |
| 86 | + if (cluster != null) | |
| 87 | + cluster.close(); | |
| 88 | + if (ccm != null) | |
| 89 | + ccm.remove(); | |
| 90 | + } | |
| 91 | + } | |
| 92 | + | |
| 93 | + /** | |
| 94 | + * Ensures that a heartbeat message is not sent if the configured heartbeat interval is 0. | |
| 95 | + * | |
| 96 | + * While difficult to prove the absence of evidence, the test will wait up to the default heartbeat interval | |
| 97 | + * (30 seconds + 1) and check to see if the heartbeat was sent. | |
| 98 | + * | |
| 99 | + * @test_category connection:heartbeat | |
| 100 | + * @expected_result heartbeat is not sent after default heartbeat interval (60) seconds of idle time. | |
| 101 | + * @jira_ticket JAVA-533 | |
| 102 | + * @since 2.0.10, 2.1.5 | |
| 103 | + */ | |
| 104 | + @Test(groups = "long") | |
| 105 | + public void should_not_send_heartbeat_when_disabled() throws InterruptedException { | |
| 106 | + CCMBridge ccm = null; | |
| 107 | + Cluster cluster = null; | |
| 108 | + try { | |
| 109 | + ccm = CCMBridge.create("test", 1); | |
| 110 | + cluster = Cluster.builder().addContactPoint(CCMBridge.ipOfNode(1)) | |
| 111 | + .withPoolingOptions(new PoolingOptions() | |
| 112 | + .setHeartbeatIntervalSeconds(0)) | |
| 113 | + .build(); | |
| 114 | + | |
| 115 | + // Don't create any session, only the control connection will be established | |
| 116 | + cluster.init(); | |
| 117 | + | |
| 118 | + for (int i = 0; i < 5; i++) { | |
| 119 | + triggerRequestOnControlConnection(cluster); | |
| 120 | + SECONDS.sleep(1); | |
| 121 | + } | |
| 122 | + assertThat(logs.get()).doesNotContain("sending heartbeat"); | |
| 123 | + | |
| 124 | + // Sleep for a while and ensure no heartbeat is sent. | |
| 125 | + SECONDS.sleep(32); | |
| 126 | + assertThat(logs.get()).doesNotContain("sending heartbeat"); | |
| 127 | + } finally { | |
| 128 | + if (cluster != null) | |
| 129 | + cluster.close(); | |
| 130 | + if (ccm != null) | |
| 131 | + ccm.remove(); | |
| 132 | + } | |
| 133 | + } | |
| 134 | + | |
| 135 | + // Simulates activity on the control connection via the internal API | |
| 136 | + private void triggerRequestOnControlConnection(Cluster cluster) { | |
| 137 | + cluster.manager.controlConnection.refreshNodeInfo(TestUtils.findHost(cluster, 1)); | |
| 138 | + } | |
| 139 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/HostAssert.java +9 −0
| @@ -35,9 +35,18 @@ | ||
| 35 | 35 | public HostAssert comesUpWithin(long duration, TimeUnit unit) { |
| 36 | 36 | final CountDownLatch upSignal = new CountDownLatch(1); |
| 37 | 37 | StateListener upListener = new StateListenerBase() { |
| 38 | + | |
| 39 | + @Override | |
| 38 | 40 | public void onUp(Host host) { |
| 39 | 41 | upSignal.countDown(); |
| 40 | 42 | } |
| 43 | + | |
| 44 | + @Override | |
| 45 | + public void onAdd(Host host) { | |
| 46 | + // Special case, cassandra will sometimes not send an 'UP' topology change event | |
| 47 | + // for a new node, because of this we also listen for add events. | |
| 48 | + upSignal.countDown(); | |
| 49 | + } | |
| 41 | 50 | }; |
| 42 | 51 | cluster.register(upListener); |
| 43 | 52 | try { |
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +13 −6
| @@ -23,6 +23,8 @@ | ||
| 23 | 23 | |
| 24 | 24 | import com.datastax.driver.core.querybuilder.Batch; |
| 25 | 25 | import com.datastax.driver.core.querybuilder.Insert; |
| 26 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 27 | + | |
| 26 | 28 | import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT; |
| 27 | 29 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 28 | 30 | |
| @@ -129,9 +131,12 @@ | ||
| 129 | 131 | * Converts an integer to an string of letters |
| 130 | 132 | * @param i The integer that maps to letter |
| 131 | 133 | * @return |
| 134 | + * | |
| 135 | + * TODO This doesn't offer protection from generating column names that are reserved keywords. This does | |
| 136 | + * work with CQL 3.0, but may break in future specifications. Should fix this to ensure it does not. | |
| 132 | 137 | */ |
| 133 | 138 | private static String createColumnName(int i) { |
| 134 | - String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}; | |
| 139 | + String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "j", "l"}; | |
| 135 | 140 | |
| 136 | 141 | StringBuilder columnName; |
| 137 | 142 | int currentI; |
| @@ -176,7 +181,8 @@ | ||
| 176 | 181 | * Test a wide row of size 1,000,000 |
| 177 | 182 | * @throws Throwable |
| 178 | 183 | */ |
| 179 | - @Test(groups = "integration") | |
| 184 | + @Test(groups = "long") | |
| 185 | + @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle reading wide rows well.") | |
| 180 | 186 | public void wideRows() throws Throwable { |
| 181 | 187 | Cluster.Builder builder = Cluster.builder(); |
| 182 | 188 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); |
| @@ -199,7 +205,8 @@ | ||
| 199 | 205 | * Test a batch that writes a row of size 10,000 |
| 200 | 206 | * @throws Throwable |
| 201 | 207 | */ |
| 202 | - @Test(groups = "integration") | |
| 208 | + @Test(groups = "short") | |
| 209 | + @CassandraVersion(major=2.0, minor=0, description="< 2.0 is skipped as 1.2 does not handle large batches well.") | |
| 203 | 210 | public void wideBatchRows() throws Throwable { |
| 204 | 211 | Cluster.Builder builder = Cluster.builder(); |
| 205 | 212 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); |
| @@ -222,7 +229,7 @@ | ||
| 222 | 229 | * Test a wide row of size 1,000,000 consisting of a ByteBuffer |
| 223 | 230 | * @throws Throwable |
| 224 | 231 | */ |
| 225 | - @Test(groups = "integration") | |
| 232 | + @Test(groups = "long") | |
| 226 | 233 | public void wideByteRows() throws Throwable { |
| 227 | 234 | Cluster.Builder builder = Cluster.builder(); |
| 228 | 235 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); |
| @@ -245,7 +252,7 @@ | ||
| 245 | 252 | * Test a row with a single extra large text value |
| 246 | 253 | * @throws Throwable |
| 247 | 254 | */ |
| 248 | - @Test(groups = "integration") | |
| 255 | + @Test(groups = "short") | |
| 249 | 256 | public void largeText() throws Throwable { |
| 250 | 257 | Cluster.Builder builder = Cluster.builder(); |
| 251 | 258 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); |
| @@ -268,7 +275,7 @@ | ||
| 268 | 275 | * Creates a table with 330 columns |
| 269 | 276 | * @throws Throwable |
| 270 | 277 | */ |
| 271 | - @Test(groups = "integration") | |
| 278 | + @Test(groups = "short") | |
| 272 | 279 | public void wideTable() throws Throwable { |
| 273 | 280 | Cluster.Builder builder = Cluster.builder(); |
| 274 | 281 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder); |
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +158 −46
| @@ -15,95 +15,207 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import java.io.PrintWriter; | |
| 19 | -import java.io.StringWriter; | |
| 20 | 18 | import java.util.Collection; |
| 21 | - | |
| 22 | -import org.testng.annotations.AfterClass; | |
| 23 | -import org.testng.annotations.BeforeClass; | |
| 19 | +import java.util.List; | |
| 20 | + | |
| 21 | +import com.google.common.base.Objects; | |
| 22 | +import com.google.common.collect.Lists; | |
| 23 | +import org.slf4j.Logger; | |
| 24 | +import org.slf4j.LoggerFactory; | |
| 24 | 25 | import org.testng.annotations.Test; |
| 25 | 26 | |
| 26 | -import static org.testng.Assert.assertEquals; | |
| 27 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 27 | 28 | |
| 28 | 29 | import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy; |
| 29 | 30 | import com.datastax.driver.core.policies.LoadBalancingPolicy; |
| 30 | 31 | import com.datastax.driver.core.policies.RoundRobinPolicy; |
| 31 | 32 | |
| 33 | +import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.Action.*; | |
| 34 | +import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.entry; | |
| 35 | + | |
| 32 | 36 | public class LoadBalancingPolicyBootstrapTest { |
| 33 | - CountingPolicy policy; | |
| 34 | - CCMBridge.CCMCluster c; | |
| 35 | - | |
| 36 | - @BeforeClass(groups = "short") | |
| 37 | - private void setup() { | |
| 38 | - policy = new CountingPolicy(new RoundRobinPolicy()); | |
| 39 | - Cluster.Builder builder = Cluster.builder().withLoadBalancingPolicy(policy); | |
| 40 | - c = CCMBridge.buildCluster(2, builder); | |
| 41 | - } | |
| 42 | 37 | |
| 38 | + private static final Logger logger = LoggerFactory.getLogger(LoadBalancingPolicyBootstrapTest.class); | |
| 39 | + | |
| 40 | + /** | |
| 41 | + * Ensures that when a cluster is initialized that {@link LoadBalancingPolicy#init(Cluster, Collection)} is called | |
| 42 | + * with each reachable contact point. | |
| 43 | + * | |
| 44 | + * @test_category load_balancing:notification | |
| 45 | + * @expected_result init() is called for each of two contact points. | |
| 46 | + */ | |
| 43 | 47 | @Test(groups = "short") |
| 44 | - public void notificationsTest() throws Exception { | |
| 45 | - assertEquals(policy.inits, 2, "inits\n" + policy.history); | |
| 46 | - assertEquals(policy.adds, 0, "adds\n" + policy.history); | |
| 47 | - assertEquals(policy.suspecteds, 0, "suspecteds\n" + policy.history); | |
| 48 | - assertEquals(policy.removes, 0, "removes\n" + policy.history); | |
| 49 | - assertEquals(policy.ups, 0, "ups\n" + policy.history); | |
| 50 | - assertEquals(policy.downs, 0, "downs\n" + policy.history); | |
| 48 | + public void should_init_policy_with_up_contact_points() throws Exception { | |
| 49 | + HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy()); | |
| 50 | + | |
| 51 | + CCMBridge ccm = null; | |
| 52 | + Cluster cluster = null; | |
| 53 | + try { | |
| 54 | + ccm = CCMBridge.create("test", 2); | |
| 55 | + cluster = Cluster.builder() | |
| 56 | + .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2)) | |
| 57 | + .withLoadBalancingPolicy(policy) | |
| 58 | + .build(); | |
| 59 | + | |
| 60 | + cluster.init(); | |
| 61 | + | |
| 62 | + assertThat(policy.history).containsOnly( | |
| 63 | + entry(INIT, TestUtils.findHost(cluster, 1)), | |
| 64 | + entry(INIT, TestUtils.findHost(cluster, 2)) | |
| 65 | + ); | |
| 66 | + } finally { | |
| 67 | + if (cluster != null) | |
| 68 | + cluster.close(); | |
| 69 | + if (ccm != null) | |
| 70 | + ccm.remove(); | |
| 71 | + } | |
| 51 | 72 | } |
| 52 | 73 | |
| 53 | - @AfterClass(groups = "short") | |
| 54 | - private void tearDown() { | |
| 55 | - c.discard(); | |
| 74 | + /** | |
| 75 | + * Ensures that {@link LoadBalancingPolicy#onDown(Host)} is called for a contact point that couldn't | |
| 76 | + * be reached while initializing the control connection, but only after | |
| 77 | + * {@link LoadBalancingPolicy#init(Cluster, Collection)} has been called. | |
| 78 | + * | |
| 79 | + * @test_category load_balancing:notification | |
| 80 | + * @expected_result init() is called with the up host, followed by onDown() for the downed host. | |
| 81 | + * @jira_ticket JAVA-613 | |
| 82 | + * @since 2.0.10, 2.1.5 | |
| 83 | + */ | |
| 84 | + @Test(groups = "short") | |
| 85 | + public void should_send_down_notifications_after_init_when_contact_points_are_down() throws Exception { | |
| 86 | + CCMBridge ccm = null; | |
| 87 | + Cluster cluster = null; | |
| 88 | + try { | |
| 89 | + ccm = CCMBridge.create("test", 2); | |
| 90 | + | |
| 91 | + // In order to validate this behavior, we need to stop the first node that would be attempted to be | |
| 92 | + // established as the control connection. | |
| 93 | + // This depends on the internal behavior and will even be made totally random by JAVA-618, therefore | |
| 94 | + // we retry the scenario until we get the desired preconditions. | |
| 95 | + | |
| 96 | + int nodeToStop = 1; | |
| 97 | + int tries = 1, maxTries = 10; | |
| 98 | + for (; tries <= maxTries; tries++) { | |
| 99 | + nodeToStop = (nodeToStop == 1) ? 2 : 1; // switch nodes at each try | |
| 100 | + int activeNode = nodeToStop == 2 ? 1 : 2; | |
| 101 | + | |
| 102 | + ccm.stop(nodeToStop); | |
| 103 | + ccm.waitForDown(nodeToStop); | |
| 104 | + | |
| 105 | + HistoryPolicy policy = new HistoryPolicy(new RoundRobinPolicy()); | |
| 106 | + cluster = Cluster.builder() | |
| 107 | + .addContactPoints(CCMBridge.ipOfNode(1), CCMBridge.ipOfNode(2)) | |
| 108 | + .withLoadBalancingPolicy(policy) | |
| 109 | + .build(); | |
| 110 | + | |
| 111 | + cluster.init(); | |
| 112 | + | |
| 113 | + if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) { | |
| 114 | + // This is the situation we're testing, the control connection tried the stopped node first. | |
| 115 | + assertThat(policy.history).containsExactly( | |
| 116 | + entry(INIT, TestUtils.findHost(cluster, activeNode)), | |
| 117 | + entry(DOWN, TestUtils.findHost(cluster, nodeToStop)) | |
| 118 | + ); | |
| 119 | + break; | |
| 120 | + } else { | |
| 121 | + assertThat(policy.history).containsOnly( | |
| 122 | + entry(INIT, TestUtils.findHost(cluster, 1)), | |
| 123 | + entry(INIT, TestUtils.findHost(cluster, 2)) | |
| 124 | + ); | |
| 125 | + | |
| 126 | + logger.info("Could not get first contact point to fail, retrying"); | |
| 127 | + | |
| 128 | + cluster.close(); | |
| 129 | + | |
| 130 | + ccm.start(nodeToStop); | |
| 131 | + ccm.waitForUp(nodeToStop); | |
| 132 | + } | |
| 133 | + } | |
| 134 | + | |
| 135 | + if (tries == maxTries + 1) | |
| 136 | + logger.warn("Could not get first contact point to fail after {} tries", maxTries); | |
| 137 | + | |
| 138 | + } finally { | |
| 139 | + if (cluster != null) | |
| 140 | + cluster.close(); | |
| 141 | + if (ccm != null) | |
| 142 | + ccm.remove(); | |
| 143 | + } | |
| 56 | 144 | } |
| 57 | 145 | |
| 58 | - static class CountingPolicy extends DelegatingLoadBalancingPolicy { | |
| 146 | + static class HistoryPolicy extends DelegatingLoadBalancingPolicy { | |
| 147 | + enum Action {INIT, UP, DOWN, ADD, REMOVE, SUSPECT} | |
| 148 | + | |
| 149 | + static class Entry { | |
| 150 | + final Action action; | |
| 151 | + final Host host; | |
| 152 | + | |
| 153 | + public Entry(Action action, Host host) { | |
| 154 | + this.action = action; | |
| 155 | + this.host = host; | |
| 156 | + } | |
| 157 | + | |
| 158 | + @Override | |
| 159 | + public boolean equals(Object other) { | |
| 160 | + if (other == this) | |
| 161 | + return true; | |
| 162 | + if (other instanceof Entry) { | |
| 163 | + Entry that = (Entry)other; | |
| 164 | + return this.action == that.action && this.host.equals(that.host); | |
| 165 | + } | |
| 166 | + return false; | |
| 167 | + } | |
| 168 | + | |
| 169 | + @Override | |
| 170 | + public int hashCode() { | |
| 171 | + return Objects.hashCode(action, host); | |
| 172 | + } | |
| 173 | + | |
| 174 | + @Override public String toString() { | |
| 175 | + return Objects.toStringHelper(this).add("action", action).add("host", host).toString(); | |
| 176 | + } | |
| 177 | + } | |
| 59 | 178 | |
| 60 | - int inits; | |
| 61 | - int adds; | |
| 62 | - int suspecteds; | |
| 63 | - int removes; | |
| 64 | - int ups; | |
| 65 | - int downs; | |
| 179 | + static Entry entry(Action action, Host host) { | |
| 180 | + return new Entry(action, host); | |
| 181 | + } | |
| 66 | 182 | |
| 67 | - final StringWriter history = new StringWriter(); | |
| 68 | - private final PrintWriter out = new PrintWriter(history); | |
| 183 | + List<Entry> history = Lists.newArrayList(); | |
| 69 | 184 | |
| 70 | - public CountingPolicy(LoadBalancingPolicy delegate) { | |
| 185 | + public HistoryPolicy(LoadBalancingPolicy delegate) { | |
| 71 | 186 | super(delegate); |
| 72 | 187 | } |
| 73 | 188 | |
| 74 | 189 | @Override |
| 75 | 190 | public void init(Cluster cluster, Collection<Host> hosts) { |
| 76 | 191 | super.init(cluster, hosts); |
| 77 | - inits += hosts.size(); | |
| 192 | + for (Host host : hosts) { | |
| 193 | + history.add(entry(INIT, host)); | |
| 194 | + } | |
| 78 | 195 | } |
| 79 | 196 | |
| 80 | 197 | public void onAdd(Host host) { |
| 81 | - out.printf("add %s%n", host); | |
| 82 | - adds++; | |
| 198 | + history.add(entry(ADD, host)); | |
| 83 | 199 | super.onAdd(host); |
| 84 | 200 | } |
| 85 | 201 | |
| 86 | 202 | public void onSuspected(Host host) { |
| 87 | - out.printf("suspect %s%n", host); | |
| 88 | - suspecteds++; | |
| 203 | + history.add(entry(SUSPECT, host)); | |
| 89 | 204 | super.onSuspected(host); |
| 90 | 205 | } |
| 91 | 206 | |
| 92 | 207 | public void onUp(Host host) { |
| 93 | - out.printf("up %s%n", host); | |
| 94 | - ups++; | |
| 208 | + history.add(entry(UP, host)); | |
| 95 | 209 | super.onUp(host); |
| 96 | 210 | } |
| 97 | 211 | |
| 98 | 212 | public void onDown(Host host) { |
| 99 | - out.printf("down %s%n", host); | |
| 100 | - downs++; | |
| 213 | + history.add(entry(DOWN, host)); | |
| 101 | 214 | super.onDown(host); |
| 102 | 215 | } |
| 103 | 216 | |
| 104 | 217 | public void onRemove(Host host) { |
| 105 | - out.printf("remove %s%n", host); | |
| 106 | - removes++; | |
| 218 | + history.add(entry(REMOVE, host)); | |
| 107 | 219 | super.onRemove(host); |
| 108 | 220 | } |
| 109 | 221 | } |
modified driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +11 −0
| @@ -14,6 +14,8 @@ | ||
| 14 | 14 | public class MemoryAppender extends WriterAppender { |
| 15 | 15 | public final StringWriter writer = new StringWriter(); |
| 16 | 16 | |
| 17 | + private int nextLogIdx = 0; | |
| 18 | + | |
| 17 | 19 | public MemoryAppender() { |
| 18 | 20 | setWriter(writer); |
| 19 | 21 | setLayout(new PatternLayout("%m%n")); |
| @@ -22,4 +24,13 @@ | ||
| 22 | 24 | public String get() { |
| 23 | 25 | return writer.toString(); |
| 24 | 26 | } |
| 27 | + | |
| 28 | + /** | |
| 29 | + * @return The next set of logs after getNext was last called. Not thread safe. | |
| 30 | + */ | |
| 31 | + public String getNext() { | |
| 32 | + String next = get().substring(nextLogIdx); | |
| 33 | + nextLogIdx += next.length(); | |
| 34 | + return next; | |
| 35 | + } | |
| 25 | 36 | } |
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +4 −2
| @@ -22,10 +22,10 @@ | ||
| 22 | 22 | @Test(groups = "short") |
| 23 | 23 | public void testMissingRpcAddressAtStartup() throws Exception { |
| 24 | 24 | CCMBridge ccm = CCMBridge.create("ccm", 2); |
| 25 | - deleteNode2RpcAddressFromNode1(); | |
| 26 | 25 | |
| 27 | 26 | Cluster cluster = null; |
| 28 | 27 | try { |
| 28 | + deleteNode2RpcAddressFromNode1(); | |
| 29 | 29 | // Use only one contact point to make sure that the control connection is on node1 |
| 30 | 30 | cluster = Cluster.builder() |
| 31 | 31 | .addContactPoint(CCMBridge.IP_PREFIX + "1") |
| @@ -53,7 +53,9 @@ | ||
| 53 | 53 | Lists.newArrayList(socketAddress(1)))) |
| 54 | 54 | .build(); |
| 55 | 55 | Session session = cluster.connect(); |
| 56 | - session.execute("DELETE rpc_address FROM system.peers WHERE peer = ?", InetAddress.getByName(CCMBridge.IP_PREFIX + "2")); | |
| 56 | + String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'", | |
| 57 | + InetAddress.getByName(CCMBridge.IP_PREFIX + "2").getHostName()); | |
| 58 | + session.execute(deleteStmt); | |
| 57 | 59 | session.close(); |
| 58 | 60 | } finally { |
| 59 | 61 | if (cluster != null) |
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +4 −3
| @@ -48,8 +48,9 @@ | ||
| 48 | 48 | .hasState(State.UP) |
| 49 | 49 | .isAtDistance(HostDistance.LOCAL); |
| 50 | 50 | // Wait for the node to be up, because apparently on Jenkins it's still only ADDED when we reach this line |
| 51 | + // Waiting for NEW_NODE_DELAY_SECONDS+1 allows the driver to create a connection pool and mark the node up | |
| 51 | 52 | assertThat(cluster).host(2) |
| 52 | - .comesUpWithin(120, SECONDS) | |
| 53 | + .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS) | |
| 53 | 54 | .isAtDistance(HostDistance.LOCAL); |
| 54 | 55 | |
| 55 | 56 | // Bring host 3 up, its presence should be acknowledged but it should be ignored |
| @@ -63,13 +64,13 @@ | ||
| 63 | 64 | .hasState(State.UP) |
| 64 | 65 | .isAtDistance(HostDistance.LOCAL); |
| 65 | 66 | assertThat(cluster).host(3) |
| 66 | - .comesUpWithin(120, SECONDS) | |
| 67 | + .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS) | |
| 67 | 68 | .isAtDistance(HostDistance.IGNORED); |
| 68 | 69 | assertThat(session).hasNoPoolFor(3); |
| 69 | 70 | |
| 70 | 71 | // Kill host 2, host 3 should take its place |
| 71 | 72 | ccm.stop(2); |
| 72 | - TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster, 120); | |
| 73 | + TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster); | |
| 73 | 74 | |
| 74 | 75 | assertThat(cluster).host(1) |
| 75 | 76 | .hasState(State.UP) |
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +42 −19
| @@ -5,6 +5,8 @@ | ||
| 5 | 5 | import java.util.Collections; |
| 6 | 6 | import java.util.Iterator; |
| 7 | 7 | import java.util.Map; |
| 8 | +import java.util.concurrent.ConcurrentHashMap; | |
| 9 | +import java.util.concurrent.ConcurrentMap; | |
| 8 | 10 | import java.util.concurrent.TimeUnit; |
| 9 | 11 | import java.util.concurrent.atomic.AtomicInteger; |
| 10 | 12 | |
| @@ -12,7 +14,9 @@ | ||
| 12 | 14 | |
| 13 | 15 | import com.google.common.base.Charsets; |
| 14 | 16 | import com.google.common.collect.ImmutableMap; |
| 17 | +import com.google.common.util.concurrent.ListenableFuture; | |
| 15 | 18 | import org.testng.annotations.Test; |
| 19 | + | |
| 16 | 20 | import static org.assertj.core.api.Assertions.assertThat; |
| 17 | 21 | |
| 18 | 22 | import com.datastax.driver.core.Host.State; |
| @@ -33,9 +37,9 @@ | ||
| 33 | 37 | ccm = CCMBridge.create("test", 2); |
| 34 | 38 | int reconnectionDelay = 1000; |
| 35 | 39 | cluster = Cluster.builder() |
| 36 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 37 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay)) | |
| 38 | - .build(); | |
| 40 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 41 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelay)) | |
| 42 | + .build(); | |
| 39 | 43 | cluster.connect(); |
| 40 | 44 | |
| 41 | 45 | assertThat(cluster).usesControlHost(1); |
| @@ -78,11 +82,11 @@ | ||
| 78 | 82 | CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs)); |
| 79 | 83 | |
| 80 | 84 | cluster = Cluster.builder() |
| 81 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 82 | - // Start with the correct auth so that we can initialize the server | |
| 83 | - .withAuthProvider(authProvider) | |
| 84 | - .withReconnectionPolicy(reconnectionPolicy) | |
| 85 | - .build(); | |
| 85 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 86 | + // Start with the correct auth so that we can initialize the server | |
| 87 | + .withAuthProvider(authProvider) | |
| 88 | + .withReconnectionPolicy(reconnectionPolicy) | |
| 89 | + .build(); | |
| 86 | 90 | |
| 87 | 91 | cluster.init(); |
| 88 | 92 | assertThat(cluster).usesControlHost(1); |
| @@ -128,9 +132,9 @@ | ||
| 128 | 132 | try { |
| 129 | 133 | ccm = CCMBridge.create("test", 2); |
| 130 | 134 | cluster = Cluster.builder() |
| 131 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 132 | - .withReconnectionPolicy(reconnectionPolicy) | |
| 133 | - .build(); | |
| 135 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 136 | + .withReconnectionPolicy(reconnectionPolicy) | |
| 137 | + .build(); | |
| 134 | 138 | cluster.connect(); |
| 135 | 139 | |
| 136 | 140 | // Stop a node and cancel the reconnection attempts to it |
| @@ -169,22 +173,25 @@ | ||
| 169 | 173 | try { |
| 170 | 174 | ccm = CCMBridge.create("test", 1); |
| 171 | 175 | cluster = Cluster.builder() |
| 172 | - .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 173 | - .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 174 | - .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)) | |
| 175 | - .build(); | |
| 176 | + .addContactPoint(CCMBridge.ipOfNode(1)) | |
| 177 | + .withLoadBalancingPolicy(loadBalancingPolicy) | |
| 178 | + .withReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMillis)) | |
| 179 | + .build(); | |
| 176 | 180 | cluster.connect(); |
| 177 | 181 | |
| 178 | 182 | // Tweak the LBP so that the control connection never reconnects, otherwise |
| 179 | 183 | // it would interfere with the rest of the test (this is a bit of a hack) |
| 180 | 184 | loadBalancingPolicy.returnEmptyQueryPlan = true; |
| 181 | 185 | |
| 182 | - // Stop the node and cancel the reconnection attempts to it | |
| 186 | + // Stop the node, ignore it and cancel reconnection attempts to it | |
| 183 | 187 | ccm.stop(1); |
| 184 | 188 | ccm.waitForDown(1); |
| 185 | 189 | assertThat(cluster).host(1).goesDownWithin(20, SECONDS); |
| 186 | 190 | Host host1 = TestUtils.findHost(cluster, 1); |
| 187 | - host1.getReconnectionAttemptFuture().cancel(false); | |
| 191 | + loadBalancingPolicy.setDistance(TestUtils.findHost(cluster, 1), HostDistance.IGNORED); | |
| 192 | + ListenableFuture<?> reconnectionAttemptFuture = host1.getReconnectionAttemptFuture(); | |
| 193 | + if (reconnectionAttemptFuture != null) | |
| 194 | + reconnectionAttemptFuture.cancel(false); | |
| 188 | 195 | |
| 189 | 196 | // Trigger a one-time reconnection attempt (this will fail) |
| 190 | 197 | host1.tryReconnectOnce(); |
| @@ -260,8 +267,9 @@ | ||
| 260 | 267 | |
| 261 | 268 | @Override |
| 262 | 269 | Map<String, String> getCredentials() { |
| 270 | + count.incrementAndGet(); | |
| 263 | 271 | return ImmutableMap.of("username", username, |
| 264 | - "password", password); | |
| 272 | + "password", password); | |
| 265 | 273 | } |
| 266 | 274 | } |
| 267 | 275 | } |
| @@ -298,16 +306,31 @@ | ||
| 298 | 306 | } |
| 299 | 307 | |
| 300 | 308 | /** |
| 301 | - * A load balancing policy that can be "disabled" by having its query plan return no hosts. | |
| 309 | + * A load balancing policy that: | |
| 310 | + * - can be "disabled" by having its query plan return no hosts. | |
| 311 | + * - can be instructed to return a specific distance for some hosts. | |
| 302 | 312 | */ |
| 303 | 313 | public static class TogglabePolicy extends DelegatingLoadBalancingPolicy { |
| 304 | 314 | |
| 305 | 315 | volatile boolean returnEmptyQueryPlan; |
| 316 | + final ConcurrentMap<Host, HostDistance> distances = new ConcurrentHashMap<Host, HostDistance>(); | |
| 306 | 317 | |
| 307 | 318 | public TogglabePolicy(LoadBalancingPolicy delegate) { |
| 308 | 319 | super(delegate); |
| 309 | 320 | } |
| 310 | 321 | |
| 322 | + @Override | |
| 323 | + public HostDistance distance(Host host) { | |
| 324 | + HostDistance distance = distances.get(host); | |
| 325 | + return (distance != null) | |
| 326 | + ? distance | |
| 327 | + : super.distance(host); | |
| 328 | + } | |
| 329 | + | |
| 330 | + public void setDistance(Host host, HostDistance distance) { | |
| 331 | + distances.put(host, distance); | |
| 332 | + } | |
| 333 | + | |
| 311 | 334 | @Override |
| 312 | 335 | public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) { |
| 313 | 336 | if (returnEmptyQueryPlan) |
added driver-core/src/test/java/com/datastax/driver/core/RequestHandlerTest.java +75 −0
| @@ -0,0 +1,75 @@ | ||
| 1 | +package com.datastax.driver.core; | |
| 2 | + | |
| 3 | +import java.util.concurrent.TimeUnit; | |
| 4 | +import java.util.concurrent.TimeoutException; | |
| 5 | + | |
| 6 | +import com.google.common.collect.ImmutableMap; | |
| 7 | +import org.scassandra.Scassandra; | |
| 8 | +import org.scassandra.http.client.PrimingRequest; | |
| 9 | +import org.testng.annotations.Test; | |
| 10 | + | |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 12 | + | |
| 13 | +public class RequestHandlerTest { | |
| 14 | + | |
| 15 | + @Test(groups = "long") | |
| 16 | + public void should_handle_race_between_response_and_cancellation() { | |
| 17 | + Scassandra scassandra = TestUtils.createScassandraServer(); | |
| 18 | + Cluster cluster = null; | |
| 19 | + | |
| 20 | + try { | |
| 21 | + // Use a mock server that takes a constant time to reply | |
| 22 | + scassandra.start(); | |
| 23 | + scassandra.primingClient().prime( | |
| 24 | + PrimingRequest.queryBuilder() | |
| 25 | + .withQuery("mock query") | |
| 26 | + .withRows(ImmutableMap.of("key", 1)) | |
| 27 | + .withFixedDelay(10) | |
| 28 | + .build() | |
| 29 | + ); | |
| 30 | + | |
| 31 | + cluster = Cluster.builder().addContactPoint("127.0.0.1").withPort(scassandra.getBinaryPort()) | |
| 32 | + .withPoolingOptions(new PoolingOptions() | |
| 33 | + .setCoreConnectionsPerHost(HostDistance.LOCAL, 1) | |
| 34 | + .setMaxConnectionsPerHost(HostDistance.LOCAL, 1)) | |
| 35 | + .build(); | |
| 36 | + | |
| 37 | + Session session = cluster.connect(); | |
| 38 | + | |
| 39 | + // To reproduce, we need to cancel the query exactly when the reply arrives. | |
| 40 | + // Run a few queries to estimate how much that will take. | |
| 41 | + int samples = 100; | |
| 42 | + long start = System.currentTimeMillis(); | |
| 43 | + for (int i = 0; i < samples; i++) { | |
| 44 | + session.execute("mock query"); | |
| 45 | + } | |
| 46 | + long elapsed = System.currentTimeMillis() - start; | |
| 47 | + long queryDuration = elapsed / samples; | |
| 48 | + | |
| 49 | + // Now run queries and cancel them after that estimated time | |
| 50 | + for (int i = 0; i < 2000; i++) { | |
| 51 | + ResultSetFuture future = session.executeAsync("mock query"); | |
| 52 | + try { | |
| 53 | + future.getUninterruptibly(queryDuration, TimeUnit.MILLISECONDS); | |
| 54 | + } catch (TimeoutException e) { | |
| 55 | + future.cancel(true); | |
| 56 | + } | |
| 57 | + } | |
| 58 | + | |
| 59 | + PooledConnection connection = getSingleConnection(session); | |
| 60 | + assertThat(connection.inFlight.get()).isEqualTo(0); | |
| 61 | + } finally { | |
| 62 | + if (cluster != null) | |
| 63 | + cluster.close(); | |
| 64 | + scassandra.stop(); | |
| 65 | + } | |
| 66 | + } | |
| 67 | + | |
| 68 | + private PooledConnection getSingleConnection(Session session) { | |
| 69 | + HostConnectionPool pool = ((SessionManager)session).pools.values().iterator().next(); | |
| 70 | + if (pool instanceof DynamicConnectionPool) | |
| 71 | + return ((DynamicConnectionPool)pool).connections.get(0); | |
| 72 | + else | |
| 73 | + return ((SingleConnectionPool)pool).connectionRef.get(); | |
| 74 | + } | |
| 75 | +} |
modified driver-core/src/test/java/com/datastax/driver/core/SchemaChangesTest.java +10 −3
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | import org.testng.annotations.BeforeClass; |
| 10 | 10 | import org.testng.annotations.Test; |
| 11 | 11 | |
| 12 | +import com.datastax.driver.core.exceptions.InvalidQueryException; | |
| 12 | 13 | import com.datastax.driver.core.utils.Bytes; |
| 13 | 14 | |
| 14 | 15 | import static com.datastax.driver.core.Assertions.assertThat; |
| @@ -130,9 +131,15 @@ | ||
| 130 | 131 | |
| 131 | 132 | @AfterMethod(groups = "short") |
| 132 | 133 | public void cleanup() { |
| 133 | - session.execute("DROP TABLE IF EXISTS ks.table1"); | |
| 134 | - session.execute("DROP TYPE IF EXISTS ks.type1"); | |
| 135 | - session.execute("DROP KEYSPACE IF EXISTS ks2"); | |
| 134 | + try { | |
| 135 | + session.execute("DROP TABLE IF EXISTS ks.table1"); | |
| 136 | + } catch(InvalidQueryException ex) {} | |
| 137 | + try { | |
| 138 | + session.execute("DROP TYPE IF EXISTS ks.type1"); | |
| 139 | + } catch(InvalidQueryException ex) {} | |
| 140 | + try { | |
| 141 | + session.execute("DROP KEYSPACE IF EXISTS ks2"); | |
| 142 | + } catch(InvalidQueryException ex) {} | |
| 136 | 143 | } |
| 137 | 144 | |
| 138 | 145 | @AfterClass(groups = "short") |
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +5 −3
| @@ -161,16 +161,18 @@ | ||
| 161 | 161 | |
| 162 | 162 | // create a new cluster object and ensure 0 sessions and connections |
| 163 | 163 | Cluster cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build(); |
| 164 | + | |
| 164 | 165 | assertEquals(cluster.manager.sessions.size(), 0); |
| 165 | 166 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 0); |
| 166 | 167 | |
| 168 | + // ensure sessions.size() returns with 1 control connection + core pool size. | |
| 167 | 169 | Session session = cluster.connect(); |
| 168 | 170 | assertEquals(cluster.manager.sessions.size(), 1); |
| 169 | 171 | int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster); |
| 170 | 172 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), |
| 171 | 173 | 1 + coreConnections); |
| 172 | 174 | |
| 173 | - // ensure sessions.size() returns to 0 with only 1 active connection | |
| 175 | + // ensure sessions.size() returns to 0 with only 1 active connection (the control connection) | |
| 174 | 176 | session.close(); |
| 175 | 177 | assertEquals(cluster.manager.sessions.size(), 0); |
| 176 | 178 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| @@ -183,8 +185,8 @@ | ||
| 183 | 185 | assertEquals(cluster.manager.sessions.size(), 0); |
| 184 | 186 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1); |
| 185 | 187 | |
| 186 | - // ensure a new session gets registered and control connections are established | |
| 187 | - // an additional 2 control connections should be seen for node2 | |
| 188 | + // ensure a new session gets registered and core connections are established | |
| 189 | + // there should be corePoolSize more connections to accommodate for the new host. | |
| 188 | 190 | thisSession = cluster.connect(); |
| 189 | 191 | assertEquals(cluster.manager.sessions.size(), 1); |
| 190 | 192 | assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), |
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +18 −23
| @@ -15,7 +15,11 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import com.google.common.collect.Sets; | |
| 18 | 19 | import org.testng.annotations.Test; |
| 20 | + | |
| 21 | +import java.util.Set; | |
| 22 | + | |
| 19 | 23 | import static org.testng.Assert.assertEquals; |
| 20 | 24 | |
| 21 | 25 | import static com.datastax.driver.core.TestUtils.*; |
| @@ -25,7 +29,7 @@ | ||
| 25 | 29 | */ |
| 26 | 30 | public class StateListenerTest { |
| 27 | 31 | |
| 28 | - @Test(groups = "short") | |
| 32 | + @Test(groups = "long") | |
| 29 | 33 | public void listenerTest() throws Throwable { |
| 30 | 34 | |
| 31 | 35 | CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder()); |
| @@ -42,22 +46,22 @@ | ||
| 42 | 46 | // just before the listeners are called, and since waitFor is based on isUP, |
| 43 | 47 | // it can return *just* before the listener are called. |
| 44 | 48 | Thread.sleep(500); |
| 45 | - assertEquals(listener.adds, 1); | |
| 49 | + assertEquals(listener.adds.size(), 1); | |
| 46 | 50 | |
| 47 | 51 | c.cassandraCluster.forceStop(1); |
| 48 | 52 | waitForDown(CCMBridge.IP_PREFIX + '1', cluster); |
| 49 | 53 | Thread.sleep(500); |
| 50 | - assertEquals(listener.downs, 1); | |
| 54 | + assertEquals(listener.downs.size(), 1); | |
| 51 | 55 | |
| 52 | 56 | c.cassandraCluster.start(1); |
| 53 | 57 | waitFor(CCMBridge.IP_PREFIX + '1', cluster); |
| 54 | 58 | Thread.sleep(500); |
| 55 | - assertEquals(listener.ups, 1); | |
| 59 | + assertEquals(listener.ups.size(), 1); | |
| 56 | 60 | |
| 57 | 61 | c.cassandraCluster.decommissionNode(2); |
| 58 | 62 | waitForDecommission(CCMBridge.IP_PREFIX + '2', cluster); |
| 59 | 63 | Thread.sleep(500); |
| 60 | - assertEquals(listener.removes, 1); | |
| 64 | + assertEquals(listener.removes.size(), 1); | |
| 61 | 65 | } catch (Throwable e) { |
| 62 | 66 | c.errorOut(); |
| 63 | 67 | throw e; |
| @@ -68,28 +72,19 @@ | ||
| 68 | 72 | |
| 69 | 73 | private static class CountingListener implements Host.StateListener { |
| 70 | 74 | |
| 71 | - public int adds; | |
| 72 | - public int removes; | |
| 73 | - public int ups; | |
| 74 | - public int downs; | |
| 75 | + public Set<Host> adds = Sets.newHashSet(); | |
| 76 | + public Set<Host> removes = Sets.newHashSet(); | |
| 77 | + public Set<Host> ups = Sets.newHashSet(); | |
| 78 | + public Set<Host> downs = Sets.newHashSet(); | |
| 75 | 79 | |
| 76 | - public void onAdd(Host host) { | |
| 77 | - adds++; | |
| 78 | - } | |
| 80 | + public void onAdd(Host host) { adds.add(host); } | |
| 79 | 81 | |
| 80 | - public void onUp(Host host) { | |
| 81 | - ups++; | |
| 82 | - } | |
| 82 | + public void onUp(Host host) { ups.add(host); } | |
| 83 | 83 | |
| 84 | - public void onSuspected(Host host) { | |
| 85 | - } | |
| 84 | + public void onSuspected(Host host) {} | |
| 86 | 85 | |
| 87 | - public void onDown(Host host) { | |
| 88 | - downs++; | |
| 89 | - } | |
| 86 | + public void onDown(Host host) { downs.add(host); } | |
| 90 | 87 | |
| 91 | - public void onRemove(Host host) { | |
| 92 | - removes++; | |
| 93 | - } | |
| 88 | + public void onRemove(Host host) { removes.add(host); } | |
| 94 | 89 | } |
| 95 | 90 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +32 −4
| @@ -15,12 +15,16 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | -import org.testng.ITestResult; | |
| 19 | -import org.testng.TestListenerAdapter; | |
| 20 | - | |
| 18 | +import org.testng.*; | |
| 19 | +import org.testng.internal.ConstructorOrMethod; | |
| 20 | + | |
| 21 | +import java.lang.annotation.Annotation; | |
| 22 | +import java.lang.reflect.Method; | |
| 21 | 23 | import java.util.concurrent.TimeUnit; |
| 22 | 24 | |
| 23 | -public class TestListener extends TestListenerAdapter { | |
| 25 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 26 | + | |
| 27 | +public class TestListener extends TestListenerAdapter implements IInvokedMethodListener { | |
| 24 | 28 | |
| 25 | 29 | private long start_time = System.nanoTime(); |
| 26 | 30 | private int test_index = 0; |
| @@ -78,4 +82,28 @@ | ||
| 78 | 82 | + ':' + (minutes < 10 ? "0" : "") + minutes |
| 79 | 83 | + ':' + (seconds< 10 ? "0" : "") + seconds); |
| 80 | 84 | } |
| 85 | + | |
| 86 | + @Override public void beforeInvocation(IInvokedMethod testMethod, ITestResult testResult) { | |
| 87 | + // Check to see if the class or method is annotated with 'CassandraVersion', if so ensure the | |
| 88 | + // version we are testing with meets the requirement, if not a SkipException is thrown | |
| 89 | + // and this test is skipped. | |
| 90 | + ITestNGMethod testNgMethod = testResult.getMethod(); | |
| 91 | + ConstructorOrMethod constructorOrMethod = testNgMethod.getConstructorOrMethod(); | |
| 92 | + | |
| 93 | + Class<?> clazz = testNgMethod.getInstance().getClass(); | |
| 94 | + if(clazz != null && clazz.isAnnotationPresent(CassandraVersion.class)) { | |
| 95 | + CassandraVersion cassandraVersion = clazz.getAnnotation(CassandraVersion.class); | |
| 96 | + TestUtils.versionCheck(cassandraVersion.major(), cassandraVersion.minor(), cassandraVersion.description()); | |
| 97 | + } | |
| 98 | + | |
| 99 | + Method method = constructorOrMethod.getMethod(); | |
| 100 | + if(method != null && method.isAnnotationPresent(CassandraVersion.class)) { | |
| 101 | + CassandraVersion cassandraVersion = method.getAnnotation(CassandraVersion.class); | |
| 102 | + TestUtils.versionCheck(cassandraVersion.major(), cassandraVersion.minor(), cassandraVersion.description()); | |
| 103 | + } | |
| 104 | + } | |
| 105 | + | |
| 106 | + @Override public void afterInvocation(IInvokedMethod testMethod, ITestResult testResult) { | |
| 107 | + // Do nothing | |
| 108 | + } | |
| 81 | 109 | } |
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +56 −6
| @@ -15,14 +15,18 @@ | ||
| 15 | 15 | */ |
| 16 | 16 | package com.datastax.driver.core; |
| 17 | 17 | |
| 18 | +import java.io.IOException; | |
| 18 | 19 | import java.math.BigDecimal; |
| 19 | 20 | import java.math.BigInteger; |
| 20 | 21 | import java.net.InetAddress; |
| 22 | +import java.net.ServerSocket; | |
| 21 | 23 | import java.nio.ByteBuffer; |
| 22 | 24 | import java.util.*; |
| 23 | 25 | |
| 24 | 26 | import static org.testng.Assert.fail; |
| 25 | 27 | |
| 28 | +import org.scassandra.Scassandra; | |
| 29 | +import org.scassandra.ScassandraFactory; | |
| 26 | 30 | import org.slf4j.Logger; |
| 27 | 31 | import org.slf4j.LoggerFactory; |
| 28 | 32 | import org.testng.SkipException; |
| @@ -45,6 +49,8 @@ | ||
| 45 | 49 | public static final String INSERT_FORMAT = "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)"; |
| 46 | 50 | public static final String SELECT_ALL_FORMAT = "SELECT * FROM %s"; |
| 47 | 51 | |
| 52 | + public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60); | |
| 53 | + | |
| 48 | 54 | @SuppressWarnings({ "unchecked", "rawtypes" }) |
| 49 | 55 | public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) { |
| 50 | 56 | switch (type.getName()) { |
| @@ -177,7 +183,7 @@ | ||
| 177 | 183 | case FLOAT: |
| 178 | 184 | return 3.142519f; |
| 179 | 185 | case INET: |
| 180 | - return InetAddress.getByAddress(new byte[]{(byte)127, (byte)0, (byte)0, (byte)1}); | |
| 186 | + return InetAddress.getByAddress(new byte[]{ (byte)127, (byte)0, (byte)0, (byte)1 }); | |
| 181 | 187 | case INT: |
| 182 | 188 | return 24; |
| 183 | 189 | case TEXT: |
| @@ -263,7 +269,7 @@ | ||
| 263 | 269 | // This is used because there is some delay between when a node has been |
| 264 | 270 | // added through ccm and when it's actually available for querying |
| 265 | 271 | public static void waitFor(String node, Cluster cluster) { |
| 266 | - waitFor(node, cluster, 60, false, false); | |
| 272 | + waitFor(node, cluster, TEST_BASE_NODE_WAIT, false, false); | |
| 267 | 273 | } |
| 268 | 274 | |
| 269 | 275 | public static void waitFor(String node, Cluster cluster, int maxTry) { |
| @@ -271,11 +277,11 @@ | ||
| 271 | 277 | } |
| 272 | 278 | |
| 273 | 279 | public static void waitForDown(String node, Cluster cluster) { |
| 274 | - waitFor(node, cluster, 180, true, false); | |
| 280 | + waitFor(node, cluster, TEST_BASE_NODE_WAIT * 3, true, false); | |
| 275 | 281 | } |
| 276 | 282 | |
| 277 | 283 | public static void waitForDownWithWait(String node, Cluster cluster, int waitTime) { |
| 278 | - waitFor(node, cluster, 180, true, false); | |
| 284 | + waitForDown(node, cluster); | |
| 279 | 285 | |
| 280 | 286 | // FIXME: Once stop() works, remove this line |
| 281 | 287 | try { |
| @@ -295,7 +301,7 @@ | ||
| 295 | 301 | } |
| 296 | 302 | |
| 297 | 303 | public static void waitForDecommission(String node, Cluster cluster) { |
| 298 | - waitFor(node, cluster, 30, true, true); | |
| 304 | + waitFor(node, cluster, TEST_BASE_NODE_WAIT / 2, true, true); | |
| 299 | 305 | } |
| 300 | 306 | |
| 301 | 307 | public static void waitForDecommission(String node, Cluster cluster, int maxTry) { |
| @@ -368,7 +374,7 @@ | ||
| 368 | 374 | int minor = Integer.parseInt(versionArray[2]); |
| 369 | 375 | |
| 370 | 376 | if (major < majorCheck || (major == majorCheck && minor < minorCheck)) { |
| 371 | - throw new SkipException(skipString); | |
| 377 | + throw new SkipException("Version >= " + majorCheck + "." + minorCheck + " required. Description: " + skipString); | |
| 372 | 378 | } |
| 373 | 379 | } |
| 374 | 380 | |
| @@ -390,4 +396,48 @@ | ||
| 390 | 396 | ? configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL) |
| 391 | 397 | : 1; |
| 392 | 398 | } |
| 399 | + | |
| 400 | + /** | |
| 401 | + * @return A Scassandra instance with an arbitrarily chosen binary port from 8042-8142 and admin port from | |
| 402 | + * 8052-8152. | |
| 403 | + */ | |
| 404 | + public static Scassandra createScassandraServer() { | |
| 405 | + int binaryPort = findAvailablePort(8042); | |
| 406 | + int adminPort = findAvailablePort(8052); | |
| 407 | + return ScassandraFactory.createServer(binaryPort, adminPort); | |
| 408 | + } | |
| 409 | + | |
| 410 | + /** | |
| 411 | + * @param startingWith The first port to try, if unused will keep trying the next port until one is found up to | |
| 412 | + * 100 subsequent ports. | |
| 413 | + * @return A local port that is currently unused. | |
| 414 | + */ | |
| 415 | + public static int findAvailablePort(int startingWith) { | |
| 416 | + IOException last = null; | |
| 417 | + for (int port = startingWith; port < startingWith + 100; port++) { | |
| 418 | + try { | |
| 419 | + ServerSocket s = new ServerSocket(port); | |
| 420 | + s.close(); | |
| 421 | + return port; | |
| 422 | + } catch (IOException e) { | |
| 423 | + last = e; | |
| 424 | + } | |
| 425 | + } | |
| 426 | + // If for whatever reason a port could not be acquired throw the last encountered exception. | |
| 427 | + throw new RuntimeException("Could not acquire an available port", last); | |
| 428 | + } | |
| 429 | + | |
| 430 | + /** | |
| 431 | + * @return The desired target protocol version based on the 'cassandra.version' System property. | |
| 432 | + */ | |
| 433 | + public static int getDesiredProtocolVersion() { | |
| 434 | + String version = System.getProperty("cassandra.version"); | |
| 435 | + String[] versionArray = version.split("\\.|-"); | |
| 436 | + double major = Double.parseDouble(versionArray[0] + "." + versionArray[1]); | |
| 437 | + if(major < 2.0) { | |
| 438 | + return 1; | |
| 439 | + } else { | |
| 440 | + return 2; | |
| 441 | + } | |
| 442 | + } | |
| 393 | 443 | } |
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +4 −6
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | import com.datastax.driver.core.*; |
| 15 | 15 | |
| 16 | 16 | public class DCAwareRoundRobinPolicyTest { |
| 17 | + Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class); | |
| 17 | 18 | MemoryAppender logs; |
| 18 | 19 | CCMBridge ccm; |
| 19 | 20 | |
| @@ -31,18 +32,15 @@ | ||
| 31 | 32 | |
| 32 | 33 | @BeforeMethod(groups = "short") |
| 33 | 34 | public void startRecordingLogs() { |
| 34 | - Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class); | |
| 35 | - assertThat(Level.WARN.isGreaterOrEqual(policyLogger.getEffectiveLevel())) | |
| 36 | - .isTrue() | |
| 37 | - .as("Log level must be at least WARN for this test to work"); | |
| 38 | - | |
| 35 | + policyLogger.setLevel(Level.WARN); | |
| 39 | 36 | logs = new MemoryAppender(); |
| 40 | 37 | policyLogger.addAppender(logs); |
| 41 | 38 | } |
| 42 | 39 | |
| 43 | 40 | @AfterMethod(groups = "short") |
| 44 | 41 | public void stopRecordingLogs() { |
| 45 | - Logger.getLogger(DCAwareRoundRobinPolicy.class).removeAppender(logs); | |
| 42 | + policyLogger.setLevel(null); | |
| 43 | + policyLogger.removeAppender(logs); | |
| 46 | 44 | } |
| 47 | 45 | |
| 48 | 46 | @Test(groups = "short") |
added driver-core/src/test/java/com/datastax/driver/core/policies/EC2MultiRegionAddressTranslaterTest.java +82 −0
| @@ -0,0 +1,82 @@ | ||
| 1 | +package com.datastax.driver.core.policies; | |
| 2 | + | |
| 3 | +import org.testng.annotations.Test; | |
| 4 | + | |
| 5 | +import javax.naming.NamingException; | |
| 6 | +import javax.naming.directory.BasicAttributes; | |
| 7 | +import javax.naming.directory.InitialDirContext; | |
| 8 | +import java.net.InetAddress; | |
| 9 | +import java.net.InetSocketAddress; | |
| 10 | + | |
| 11 | +import static org.assertj.core.api.Assertions.assertThat; | |
| 12 | +import static org.mockito.Mockito.*; | |
| 13 | + | |
| 14 | +public class EC2MultiRegionAddressTranslaterTest { | |
| 15 | + | |
| 16 | + @Test(groups = "unit") | |
| 17 | + public void should_return_same_address_when_no_entry_found() throws Exception { | |
| 18 | + InitialDirContext mock = mock(InitialDirContext.class); | |
| 19 | + when(mock.getAttributes(anyString(), any(String[].class))) | |
| 20 | + .thenReturn(new BasicAttributes()); | |
| 21 | + EC2MultiRegionAddressTranslater translater = new EC2MultiRegionAddressTranslater(mock); | |
| 22 | + | |
| 23 | + InetSocketAddress address = new InetSocketAddress("192.0.2.5", 9042); | |
| 24 | + assertThat(translater.translate(address)).isEqualTo(address); | |
| 25 | + } | |
| 26 | + | |
| 27 | + @Test(groups = "unit") | |
| 28 | + public void should_return_same_address_when_exception_encountered() throws Exception { | |
| 29 | + InitialDirContext mock = mock(InitialDirContext.class); | |
| 30 | + when(mock.getAttributes(anyString(), any(String[].class))) | |
| 31 | + .thenThrow(new NamingException("Problem resolving address (not really).")); | |
| 32 | + EC2MultiRegionAddressTranslater translater = new EC2MultiRegionAddressTranslater(mock); | |
| 33 | + | |
| 34 | + InetSocketAddress address = new InetSocketAddress("192.0.2.5", 9042); | |
| 35 | + assertThat(translater.translate(address)).isEqualTo(address); | |
| 36 | + } | |
| 37 | + | |
| 38 | + @Test(groups = "unit") | |
| 39 | + public void should_return_new_address_when_match_found() throws Exception { | |
| 40 | + InetSocketAddress expectedAddress = new InetSocketAddress("54.32.55.66", 9042); | |
| 41 | + | |
| 42 | + InitialDirContext mock = mock(InitialDirContext.class); | |
| 43 | + when(mock.getAttributes("5.2.0.192.in-addr.arpa", new String[] { "PTR" })) | |
| 44 | + .thenReturn(new BasicAttributes("PTR", expectedAddress.getHostName())); | |
| 45 | + EC2MultiRegionAddressTranslater translater = new EC2MultiRegionAddressTranslater(mock); | |
| 46 | + | |
| 47 | + InetSocketAddress address = new InetSocketAddress("192.0.2.5", 9042); | |
| 48 | + assertThat(translater.translate(address)).isEqualTo(expectedAddress); | |
| 49 | + } | |
| 50 | + | |
| 51 | + @Test(groups = "unit") | |
| 52 | + public void should_close_context_when_closed() throws Exception { | |
| 53 | + InitialDirContext mock = mock(InitialDirContext.class); | |
| 54 | + EC2MultiRegionAddressTranslater translater = new EC2MultiRegionAddressTranslater(mock); | |
| 55 | + | |
| 56 | + // ensure close has not been called to this point. | |
| 57 | + verify(mock, times(0)).close(); | |
| 58 | + translater.close(); | |
| 59 | + // ensure close is closed. | |
| 60 | + verify(mock).close(); | |
| 61 | + } | |
| 62 | + | |
| 63 | + @Test(groups = "unit") | |
| 64 | + public void should_build_reversed_domain_name_for_ip_v4() throws Exception { | |
| 65 | + InetAddress address = InetAddress.getByName("192.0.2.5"); | |
| 66 | + assertThat( | |
| 67 | + EC2MultiRegionAddressTranslater.reverse(address) | |
| 68 | + ).isEqualTo( | |
| 69 | + "5.2.0.192.in-addr.arpa" | |
| 70 | + ); | |
| 71 | + } | |
| 72 | + | |
| 73 | + @Test(groups = "unit") | |
| 74 | + public void should_build_reversed_domain_name_for_ip_v6() throws Exception { | |
| 75 | + InetAddress address = InetAddress.getByName("2001:db8::567:89ab"); | |
| 76 | + assertThat( | |
| 77 | + EC2MultiRegionAddressTranslater.reverse(address) | |
| 78 | + ).isEqualTo( | |
| 79 | + "b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa" | |
| 80 | + ); | |
| 81 | + } | |
| 82 | +} | |
| No newline at the end of the file |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderExecutionTest.java +1 −2
| @@ -93,8 +93,7 @@ | ||
| 93 | 93 | |
| 94 | 94 | @Test(groups = "short") |
| 95 | 95 | public void batchNonBuiltStatementTest() throws Exception { |
| 96 | - | |
| 97 | - SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES (?, ?)", "batchTest1", "val1"); | |
| 96 | + SimpleStatement simple = new SimpleStatement("INSERT INTO " + TABLE1 + " (k, t) VALUES ('batchTest1', 'val1')"); | |
| 98 | 97 | RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2"); |
| 99 | 98 | session.execute(batch().add(simple).add(built)); |
| 100 | 99 |
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +4 −1
| @@ -25,6 +25,8 @@ | ||
| 25 | 25 | |
| 26 | 26 | import com.datastax.driver.core.*; |
| 27 | 27 | import com.datastax.driver.core.exceptions.SyntaxError; |
| 28 | +import com.datastax.driver.core.utils.CassandraVersion; | |
| 29 | + | |
| 28 | 30 | import static com.datastax.driver.core.querybuilder.QueryBuilder.*; |
| 29 | 31 | |
| 30 | 32 | public class QueryBuilderITest extends CCMBridge.PerClassSingleNodeCluster { |
| @@ -206,7 +208,8 @@ | ||
| 206 | 208 | } |
| 207 | 209 | |
| 208 | 210 | @Test(groups = "short") |
| 209 | - public void conditionalDeletesTest() throws Exception { | |
| 211 | + @CassandraVersion(major=2.0, minor=7, description="DELETE..IF EXISTS only supported in 2.0.7+ (CASSANDRA-5708)") | |
| 212 | + public void conditionalDeletesTest() throws Exception { | |
| 210 | 213 | session.execute("INSERT INTO ks.test_int (k, a, b) VALUES (1, 1, 1)"); |
| 211 | 214 | |
| 212 | 215 | Statement delete; |
added driver-core/src/test/java/com/datastax/driver/core/utils/CassandraVersion.java +28 −0
| @@ -0,0 +1,28 @@ | ||
| 1 | +package com.datastax.driver.core.utils; | |
| 2 | + | |
| 3 | +import java.lang.annotation.Retention; | |
| 4 | +import java.lang.annotation.RetentionPolicy; | |
| 5 | + | |
| 6 | +/** | |
| 7 | + * <p>Annotation for a Class or Method that defines a Cassandra Version requirement. If the cassandra verison in used | |
| 8 | + * does not meet the version requirement, the test is skipped.</p> | |
| 9 | + * | |
| 10 | + * @see {@link com.datastax.driver.core.TestListener#beforeInvocation(org.testng.IInvokedMethod, org.testng.ITestResult)} for usage. | |
| 11 | + */ | |
| 12 | +@Retention(RetentionPolicy.RUNTIME) | |
| 13 | +public @interface CassandraVersion { | |
| 14 | + /** | |
| 15 | + * @return The major version required to execute this test, i.e. "2.0" | |
| 16 | + */ | |
| 17 | + public double major(); | |
| 18 | + | |
| 19 | + /** | |
| 20 | + * @return The minor version required to execute this test, i.e. "0" | |
| 21 | + */ | |
| 22 | + public int minor() default 0; | |
| 23 | + | |
| 24 | + /** | |
| 25 | + * @return The description returned if this version requirement is not met. | |
| 26 | + */ | |
| 27 | + public String description() default "Does not meet minimum version requirement."; | |
| 28 | +} |
modified driver-core/src/test/resources/log4j.properties +3 −0
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | # Set root logger level to DEBUG and its only appender to A1. |
| 2 | 2 | log4j.rootLogger=INFO, A1 |
| 3 | 3 | |
| 4 | +# Scassandra's info log is a bit verbose | |
| 5 | +log4j.logger.org.scassandra=WARN | |
| 6 | + | |
| 4 | 7 | # A1 is set to be a ConsoleAppender. |
| 5 | 8 | log4j.appender.A1=org.apache.log4j.ConsoleAppender |
| 6 | 9 |