Elffuss BraidHub

kikocis/java-driver public

Merge branch '2.0' into 2.1
Changeset8c8fb5365c18f6e6e3eb0449e9b7592102b514b9f581543bc8a7fdb94a30e47b
Authorolim7t <omichallat+github@gmail.com> · 2015-02-19 15:54 +01:00
Committerolim7t <omichallat+github@gmail.com> · 2015-02-19 16:09 +01:00
Parents8aa2f039d03f, b1ca3ae13f03

Browse the files at this changeset

39 files changed

modified driver-core/CHANGELOG.rst +32 −0
@@ -4,6 +4,20 @@
44 2.1.5:
55 ------
66
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+
721
822 2.1.4:
923 ------
@@ -153,6 +167,24 @@
153167 - [bug] Make metadata parsing more lenient (JAVA-377, JAVA-391)
154168
155169
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+
156188 2.0.9:
157189 ------
158190
modified driver-core/pom.xml +14 −0
@@ -89,6 +89,20 @@
8989 <scope>test</scope>
9090 </dependency>
9191
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+
92106 </dependencies>
93107
94108 <build>
modified driver-core/src/main/java/com/datastax/driver/core/Cluster.java +4 −0
@@ -1353,6 +1353,10 @@
13531353 if (loadBalancingPolicy instanceof CloseableLoadBalancingPolicy)
13541354 ((CloseableLoadBalancingPolicy)loadBalancingPolicy).close();
13551355
1356+ AddressTranslater translater = configuration.getPolicies().getAddressTranslater();
1357+ if (translater instanceof CloseableAddressTranslater)
1358+ ((CloseableAddressTranslater)translater).close();
1359+
13561360 // Then we shutdown all connections
13571361 List<CloseFuture> futures = new ArrayList<CloseFuture>(sessions.size() + 1);
13581362 futures.add(controlConnection.closeAsync());
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +115 −22
@@ -19,6 +19,7 @@
1919 import java.net.InetSocketAddress;
2020 import java.util.Iterator;
2121 import java.util.concurrent.*;
22+import java.util.concurrent.atomic.AtomicBoolean;
2223 import java.util.concurrent.atomic.AtomicInteger;
2324 import java.util.concurrent.atomic.AtomicReference;
2425
@@ -31,6 +32,9 @@
3132 import org.jboss.netty.channel.group.DefaultChannelGroup;
3233 import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
3334 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;
3438 import org.jboss.netty.util.HashedWheelTimer;
3539 import org.jboss.netty.util.Timeout;
3640 import org.jboss.netty.util.TimerTask;
@@ -89,7 +93,8 @@
8993 ClientBootstrap bootstrap = factory.newBootstrap();
9094 ProtocolOptions protocolOptions = factory.configuration.getProtocolOptions();
9195 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));
9398
9499 ChannelFuture future = bootstrap.connect(address);
95100
@@ -282,9 +287,19 @@
282287 // sure the "suspected" mechanism work as expected
283288 Host host = factory.manager.metadata.getHost(address);
284289 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+
285300 // This will trigger onDown, including when the defunct Connection is part of a reconnection attempt, which is redundant.
286301 // 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);
288303 notifyOwnerWhenDefunct(isDown);
289304 }
290305
@@ -310,11 +325,12 @@
310325 if (this.keyspace != null && this.keyspace.equals(keyspace))
311326 return;
312327
328+ Future future = null;
313329 try {
314330 logger.trace("{} Setting keyspace {}", this, keyspace);
315331 long timeout = factory.getConnectTimeoutMillis();
316332 // 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 + '"'));
318334 Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS);
319335 switch (response.type) {
320336 case RESULT:
@@ -332,9 +348,16 @@
332348 } catch (ConnectionException e) {
333349 throw defunct(e);
334350 } 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);
335355 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");
336358 } catch (BusyConnectionException e) {
337359 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");
338361 } catch (ExecutionException e) {
339362 throw defunct(new ConnectionException(address, "Error while setting keyspace", e));
340363 }
@@ -356,6 +379,10 @@
356379 }
357380
358381 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 {
359386
360387 Message.Request request = callback.request();
361388
@@ -370,18 +397,22 @@
370397 * never leave a handler that won't get an answer or be errored out.
371398 */
372399 if (isDefunct) {
373- dispatcher.removeHandler(handler.streamId, true);
400+ dispatcher.removeHandler(handler, true);
374401 throw new ConnectionException(address, "Write attempt on defunct connection");
375402 }
376403
377404 if (isClosed()) {
378- dispatcher.removeHandler(handler.streamId, true);
405+ dispatcher.removeHandler(handler, true);
379406 throw new ConnectionException(address, "Connection has been closed");
380407 }
381408
382409 logger.trace("{} writing request {}", this, request);
383410 writer.incrementAndGet();
384411 channel.write(request).addListener(writeHandler(request, handler));
412+
413+ if (startTimeout)
414+ handler.startTimeout();
415+
385416 return handler;
386417 }
387418
@@ -396,7 +427,7 @@
396427 logger.debug("{} Error writing request {}", Connection.this, request);
397428 // Remove this handler from the dispatcher so it don't get notified of the error
398429 // twice (we will fail that method already)
399- dispatcher.removeHandler(handler.streamId, true);
430+ dispatcher.removeHandler(handler, true);
400431
401432 final ConnectionException ce;
402433 if (writeFuture.getCause() instanceof java.nio.channels.ClosedChannelException) {
@@ -619,7 +650,7 @@
619650 }
620651 }
621652
622- private class Dispatcher extends SimpleChannelUpstreamHandler {
653+ private class Dispatcher extends IdleStateAwareChannelUpstreamHandler {
623654
624655 public final StreamIdGenerator streamIdHandler;
625656 private final ConcurrentMap<Integer, ResponseHandler> pending = new ConcurrentHashMap<Integer, ResponseHandler>();
@@ -640,19 +671,27 @@
640671 assert old == null;
641672 }
642673
643- public void removeHandler(int streamId, boolean releaseStreamId) {
674+ public void removeHandler(ResponseHandler handler, boolean releaseStreamId) {
644675
645676 // If we don't release the ID, mark first so that we can rely later on the fact that if
646677 // we receive a response for an ID with no handler, it's that this ID has been marked.
647678 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();
653692
654693 if (releaseStreamId)
655- streamIdHandler.release(streamId);
694+ streamIdHandler.release(handler.streamId);
656695
657696 if (isClosed())
658697 tryTerminate(false);
@@ -703,6 +742,12 @@
703742 }
704743 }
705744
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+
706751 // Make sure we don't print huge responses in debug/error logs.
707752 private String asDebugString(Object obj) {
708753 if (obj == null)
@@ -751,6 +796,45 @@
751796 }
752797 }
753798
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+
754838 private class ConnectionCloseFuture extends CloseFuture {
755839
756840 @Override
@@ -832,8 +916,7 @@
832916 public boolean onTimeout(Connection connection, long latency, int retryCount) {
833917 assert connection != null; // We always timeout on a specific connection, so this shouldn't be null
834918 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));
837920 }
838921
839922 public InetSocketAddress getAddress() {
@@ -856,8 +939,10 @@
856939 public final ResponseCallback callback;
857940 public final int retryCount;
858941
859- private final Timeout timeout;
860942 private final long startTime;
943+ private volatile Timeout timeout;
944+
945+ private final AtomicBoolean isCancelled = new AtomicBoolean();
861946
862947 public ResponseHandler(Connection connection, ResponseCallback callback) throws BusyConnectionException {
863948 this.connection = connection;
@@ -865,10 +950,12 @@
865950 this.callback = callback;
866951 this.retryCount = callback.retryCount();
867952
953+ this.startTime = System.nanoTime();
954+ }
955+
956+ void startTimeout() {
868957 long timeoutMs = connection.factory.getReadTimeoutMillis();
869958 this.timeout = timeoutMs <= 0 ? null : connection.factory.timer.newTimeout(onTimeoutTask(), timeoutMs, TimeUnit.MILLISECONDS);
870-
871- this.startTime = System.nanoTime();
872959 }
873960
874961 void cancelTimeout() {
@@ -877,11 +964,14 @@
877964 }
878965
879966 public void cancelHandler() {
967+ if (!isCancelled.compareAndSet(false, true))
968+ return;
969+
880970 // We haven't really received a response: we want to remove the handle because we gave up on that
881971 // request and there is no point in holding the handler, but we don't release the streamId. If we
882972 // were, a new request could reuse that ID but get the answer to the request we just gave up on instead
883973 // 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);
885975 if (connection instanceof PooledConnection)
886976 ((PooledConnection)connection).release();
887977 }
@@ -913,12 +1003,14 @@
9131003 private final Connection connection;
9141004 private final FrameCompressor compressor;
9151005 private final SSLOptions sslOptions;
1006+ private final ChannelHandler idleStateHandler;
9161007
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) {
9181009 this.connection = connection;
9191010 this.protocolVersion = protocolVersion;
9201011 this.compressor = compressor;
9211012 this.sslOptions = sslOptions;
1013+ this.idleStateHandler = new IdleStateHandler(timer, 0, 0, heartBeatIntervalSeconds);
9221014 }
9231015
9241016 @Override
@@ -945,9 +1037,10 @@
9451037 }
9461038
9471039 pipeline.addLast("messageDecoder", messageDecoder);
948-
9491040 pipeline.addLast("messageEncoder", messageEncoderFor(protocolVersion));
9501041
1042+ pipeline.addLast("idleStateHandler", idleStateHandler);
1043+
9511044 pipeline.addLast("dispatcher", connection.dispatcher);
9521045
9531046 return pipeline;
modified driver-core/src/main/java/com/datastax/driver/core/ControlConnection.java +11 −11
@@ -411,7 +411,7 @@
411411 return null;
412412 } else if (addr == null) {
413413 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);
415415 return null;
416416 } else if (addr.equals(bindAllAddress)) {
417417 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 @@
461461 // until the control connection is back up (which leads to a catch-22 if there is only one)
462462 return true;
463463 } 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());
465465 return false;
466466 }
467467 // Ignore hosts with a null rpc_address, as this is most likely a phantom row in system.peers (JAVA-428).
468468 // Don't test this for the control host since we're already connected to it anyway, and we read the info from system.local
469469 // which doesn't have an rpc_address column (JAVA-546).
470470 } 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());
472472 return false;
473473 }
474474
475- updateInfo(host, row, cluster);
475+ updateInfo(host, row, cluster, false);
476476 return true;
477477
478478 } catch (ConnectionException e) {
@@ -499,9 +499,9 @@
499499 }
500500
501501 // 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) {
503503 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);
505505
506506 String version = row.getString("release_version");
507507 // 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 @@
512512 host.setVersionAndListenAdress(version, listenAddress);
513513 }
514514
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) {
516516 if (Objects.equal(host.getDatacenter(), datacenter) && Objects.equal(host.getRack(), rack))
517517 return;
518518
519519 // If the dc/rack information changes for an existing node, we need to update the load balancing policy.
520520 // For that, we remove and re-add the node against the policy. Not the most elegant, and assumes
521521 // that the policy will update correctly, but in practice this should work.
522- if (!host.wasJustAdded())
522+ if (!isInitialConnection)
523523 cluster.loadBalancingPolicy().onDown(host);
524524 host.setLocationInfo(datacenter, rack);
525- if (!host.wasJustAdded())
525+ if (!isInitialConnection)
526526 cluster.loadBalancingPolicy().onAdd(host);
527527 }
528528
@@ -556,7 +556,7 @@
556556 if (host == null) {
557557 logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address);
558558 } else {
559- updateInfo(host, localRow, cluster);
559+ updateInfo(host, localRow, cluster, isInitialConnection);
560560 Set<String> tokens = localRow.getSet("tokens", String.class);
561561 if (partitioner != null && !tokens.isEmpty())
562562 tokenMap.put(host, tokens);
@@ -593,7 +593,7 @@
593593 isNew = true;
594594 }
595595 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);
597597 if (cassandraVersions.get(i) != null)
598598 host.setVersionAndListenAdress(cassandraVersions.get(i), listenAddresses.get(i));
599599
modified driver-core/src/main/java/com/datastax/driver/core/DefaultResultSetFuture.java +1 −1
@@ -167,7 +167,7 @@
167167 public boolean onTimeout(Connection connection, long latency, int retryCount) {
168168 // This is only called for internal calls (i.e, when the future is not wrapped in RequestHandler).
169169 // 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));
171171 return true;
172172 }
173173
modified driver-core/src/main/java/com/datastax/driver/core/DynamicConnectionPool.java +2 −2
@@ -250,6 +250,8 @@
250250
251251 @Override
252252 public void returnConnection(PooledConnection connection) {
253+ int inFlight = connection.inFlight.decrementAndGet();
254+
253255 if (isClosed()) {
254256 close(connection);
255257 return;
@@ -261,8 +263,6 @@
261263 return;
262264 }
263265
264- int inFlight = connection.inFlight.decrementAndGet();
265-
266266 if (trash.contains(connection)) {
267267 if (inFlight == 0 && trash.remove(connection))
268268 close(connection);
modified driver-core/src/main/java/com/datastax/driver/core/Host.java +9 −6
@@ -207,14 +207,17 @@
207207 }
208208
209209 /**
210- * Triggers an asynchronous one-time reconnection attempt to this host.
210+ * Triggers an asynchronous reconnection attempt to this host.
211211 * <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).
215214 * <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.
218221 */
219222 public void tryReconnectOnce() {
220223 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 @@
2323 */
2424 class PooledConnection extends Connection {
2525
26- private final HostConnectionPool pool;
26+ final HostConnectionPool pool;
2727
2828 /** Used in {@link HostConnectionPool} to handle races between two threads trying to trash the same connection */
2929 final AtomicBoolean markForTrash = new AtomicBoolean();
modified driver-core/src/main/java/com/datastax/driver/core/PoolingOptions.java +33 −0
@@ -65,6 +65,7 @@
6565 private static final int DEFAULT_MAX_REQUESTS_PER_HOST_REMOTE = 256;
6666
6767 private static final int DEFAULT_POOL_TIMEOUT_MILLIS = 5000;
68+ private static final int DEFAULT_HEARTBEAT_INTERVAL_SECONDS = 30;
6869
6970 private volatile Cluster.Manager manager;
7071
@@ -79,6 +80,7 @@
7980
8081
8182 private volatile int poolTimeoutMillis = DEFAULT_POOL_TIMEOUT_MILLIS;
83+ private volatile int heartbeatIntervalSeconds = DEFAULT_HEARTBEAT_INTERVAL_SECONDS;
8284
8385 public PoolingOptions() {}
8486
@@ -293,6 +295,37 @@
293295 return this;
294296 }
295297
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+
296329 /**
297330 * Returns the maximum number of requests per host.
298331 * <p>
modified driver-core/src/main/java/com/datastax/driver/core/RequestHandler.java +82 −35
@@ -67,7 +67,6 @@
6767
6868 private volatile Map<InetSocketAddress, Throwable> errors;
6969
70- private volatile boolean isCanceled;
7170 private volatile Connection.ResponseHandler connectionHandler;
7271
7372 private final Timer.Context timerContext;
@@ -99,7 +98,7 @@
9998
10099 public void sendRequest() {
101100 try {
102- while (queryPlan.hasNext() && !isCanceled) {
101+ while (queryPlan.hasNext() && !queryStateRef.get().isCancelled()) {
103102 Host host = queryPlan.next();
104103 logger.trace("Querying node {}", host);
105104 if (query(host))
@@ -126,7 +125,7 @@
126125 triedHosts.add(current);
127126 }
128127 current = host;
129- connectionHandler = connection.write(this);
128+ write(connection, this);
130129 return true;
131130 } catch (ConnectionException e) {
132131 // If we have any problem with the connection, move to the next node.
@@ -154,6 +153,38 @@
154153 }
155154 }
156155
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+
157188 private void logError(InetSocketAddress address, Throwable exception) {
158189 logger.debug("Error querying {}, trying next host (error is: {})", address, exception.toString());
159190 if (errors == null)
@@ -162,8 +193,6 @@
162193 }
163194
164195 private void retry(final boolean retryCurrent, ConsistencyLevel newConsistencyLevel) {
165- queryStateRef.set(queryStateRef.get().startNext());
166-
167196 final Host h = current;
168197 this.retryConsistencyLevel = newConsistencyLevel;
169198
@@ -171,6 +200,8 @@
171200 manager.executor().execute(new Runnable() {
172201 @Override
173202 public void run() {
203+ if (queryStateRef.get().isCancelled())
204+ return;
174205 try {
175206 if (retryCurrent) {
176207 if (query(h))
@@ -185,9 +216,22 @@
185216 }
186217
187218 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+ }
191235 }
192236
193237 @Override
@@ -272,10 +316,8 @@
272316 }
273317
274318 Host queriedHost = current;
319+ boolean releaseConnection = true;
275320 try {
276- if (connection instanceof PooledConnection)
277- ((PooledConnection)connection).release();
278-
279321 switch (response.type) {
280322 case RESULT:
281323 setFinalResult(connection, response);
@@ -384,31 +426,23 @@
384426 return;
385427 }
386428
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);
390429 String currentKeyspace = connection.keyspace();
391430 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()));
399438 }
400439
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()));
412446 // we're done for now, the prepareAndRetry callback will handle the rest
413447 return;
414448 default:
@@ -447,6 +481,9 @@
447481 } catch (Exception e) {
448482 setFinalException(connection, e);
449483 } finally {
484+ if (releaseConnection && connection instanceof PooledConnection)
485+ ((PooledConnection)connection).release();
486+
450487 if (queriedHost != null)
451488 manager.cluster.manager.reportLatency(queriedHost, latency);
452489 }
@@ -475,6 +512,9 @@
475512 return;
476513 }
477514
515+ if (connection instanceof PooledConnection)
516+ ((PooledConnection)connection).release();
517+
478518 // TODO should we check the response ?
479519 switch (response.type) {
480520 case RESULT:
@@ -593,10 +633,13 @@
593633 }
594634
595635 // 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).
597638 // The count increments on each retry.
598639 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);
600643
601644 final int retryCount;
602645 final boolean inProgress;
@@ -620,9 +663,13 @@
620663 return new QueryState(retryCount + 1, true);
621664 }
622665
666+ public boolean isCancelled() {
667+ return this == CANCELLED_WHILE_IN_PROGRESS || this == CANCELLED_WHILE_COMPLETE;
668+ }
669+
623670 @Override
624671 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());
626673 }
627674 }
628675 }
modified driver-core/src/main/java/com/datastax/driver/core/SessionManager.java +4 −1
@@ -538,6 +538,7 @@
538538 // Let's not wait too long if we can't get a connection. Things
539539 // will fix themselves once the user tries a query anyway.
540540 PooledConnection c = null;
541+ boolean timedOut = false;
541542 try {
542543 c = entry.getValue().borrowConnection(200, TimeUnit.MILLISECONDS);
543544 c.write(new Requests.Prepare(query)).get();
@@ -551,8 +552,10 @@
551552 // We shouldn't really get exception while preparing a
552553 // query, so log this (but ignore otherwise as it's not a big deal)
553554 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;
554557 } finally {
555- if (c != null)
558+ if (c != null && !timedOut)
556559 c.release();
557560 }
558561 }
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 @@
2020
2121 import org.testng.annotations.Test;
2222
23-import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
24-
25-import static com.datastax.driver.core.TestUtils.versionCheck;
2623 import static org.testng.Assert.assertEquals;
2724 import static org.testng.Assert.assertTrue;
2825
26+import com.datastax.driver.core.exceptions.UnsupportedFeatureException;
27+import com.datastax.driver.core.utils.CassandraVersion;
28+
2929 public class BatchStatementTest extends CCMBridge.PerClassSingleNodeCluster {
3030
3131 @Override
@@ -80,9 +80,8 @@
8080 }
8181
8282 @Test(groups = "short")
83+ @CassandraVersion(major=2.0, minor=9, description="This will only work with C* 2.0.9 (CASSANDRA-7337)")
8384 public void casBatchTest() throws Throwable {
84- versionCheck(2.0, 9, "This will only work with C* 2.0.9 (CASSANDRA-7337)");
85-
8685 try {
8786 PreparedStatement st = session.prepare("INSERT INTO test (k, v) VALUES (?, ?) IF NOT EXISTS");
8887
modified driver-core/src/test/java/com/datastax/driver/core/ClusterInitTest.java +19 −10
@@ -18,10 +18,13 @@
1818 import static org.mockito.Mockito.verify;
1919
2020 import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
21+import com.datastax.driver.core.querybuilder.Insert;
2122 import com.datastax.driver.core.utils.UUIDs;
2223
2324 import static com.datastax.driver.core.FakeHost.Behavior.THROWING_CONNECT_TIMEOUTS;
2425
26+import static com.datastax.driver.core.querybuilder.QueryBuilder.insertInto;
27+
2528 public class ClusterInitTest {
2629 private static final Logger logger = LoggerFactory.getLogger(ClusterInitTest.class);
2730
@@ -68,6 +71,7 @@
6871 CCMBridge.ipOfNode(4), CCMBridge.ipOfNode(5), CCMBridge.ipOfNode(6))
6972 .withSocketOptions(socketOptions)
7073 .withReconnectionPolicy(reconnectionPolicy)
74+ .withProtocolVersion(TestUtils.getDesiredProtocolVersion())
7175 .build();
7276 cluster.connect();
7377
@@ -77,7 +81,10 @@
7781
7882 // We have one live host so 2 successful connections (1 control connection and 1 core connection in the pool).
7983 // 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();
8188 } finally {
8289 if (cluster != null)
8390 cluster.close();
@@ -97,15 +104,17 @@
97104 String releaseVersion = session.execute("SELECT release_version FROM local")
98105 .one().getString("release_version");
99106
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+ }
109118 } catch (Exception e) {
110119 fail("Error while inserting fake peer rows", e);
111120 } finally {
modified driver-core/src/test/java/com/datastax/driver/core/ConditionalUpdateTest.java +3 −0
@@ -6,9 +6,12 @@
66 import org.testng.annotations.Test;
77 import static org.testng.Assert.*;
88
9+import com.datastax.driver.core.utils.CassandraVersion;
10+
911 /**
1012 * Test {@link ResultSet#wasApplied()} for conditional updates.
1113 */
14+@CassandraVersion(major=2.0, description="Conditional Updates requires 2.0+.")
1215 public class ConditionalUpdateTest extends CCMBridge.PerClassSingleNodeCluster {
1316
1417 @Override
modified driver-core/src/test/java/com/datastax/driver/core/DataTypeIntegrationTest.java +2 −2
@@ -30,6 +30,7 @@
3030 import static org.testng.Assert.assertEquals;
3131 import static org.testng.Assert.assertTrue;
3232
33+import com.datastax.driver.core.utils.CassandraVersion;
3334
3435 /**
3536 * Tests DataType class to ensure data sent in is the same as data received
@@ -431,9 +432,8 @@
431432 }
432433
433434 @Test(groups = "short")
435+ @CassandraVersion(major=2.0, minor=0, description="This feature requires protocol v2")
434436 public void primitiveInsertWithValueTest() throws Throwable {
435- TestUtils.versionCheck(2.0, 0, "This feature requires protocol v2");
436-
437437 for (DataType dt : DataType.allPrimitiveTypes()) {
438438 if (exclude(dt))
439439 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 @@
3535 public HostAssert comesUpWithin(long duration, TimeUnit unit) {
3636 final CountDownLatch upSignal = new CountDownLatch(1);
3737 StateListener upListener = new StateListenerBase() {
38+
39+ @Override
3840 public void onUp(Host host) {
3941 upSignal.countDown();
4042 }
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+ }
4150 };
4251 cluster.register(upListener);
4352 try {
modified driver-core/src/test/java/com/datastax/driver/core/LargeDataTest.java +13 −6
@@ -23,6 +23,8 @@
2323
2424 import com.datastax.driver.core.querybuilder.Batch;
2525 import com.datastax.driver.core.querybuilder.Insert;
26+import com.datastax.driver.core.utils.CassandraVersion;
27+
2628 import static com.datastax.driver.core.TestUtils.CREATE_KEYSPACE_SIMPLE_FORMAT;
2729 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2830
@@ -129,9 +131,12 @@
129131 * Converts an integer to an string of letters
130132 * @param i The integer that maps to letter
131133 * @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.
132137 */
133138 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"};
135140
136141 StringBuilder columnName;
137142 int currentI;
@@ -176,7 +181,8 @@
176181 * Test a wide row of size 1,000,000
177182 * @throws Throwable
178183 */
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.")
180186 public void wideRows() throws Throwable {
181187 Cluster.Builder builder = Cluster.builder();
182188 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -199,7 +205,8 @@
199205 * Test a batch that writes a row of size 10,000
200206 * @throws Throwable
201207 */
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.")
203210 public void wideBatchRows() throws Throwable {
204211 Cluster.Builder builder = Cluster.builder();
205212 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -222,7 +229,7 @@
222229 * Test a wide row of size 1,000,000 consisting of a ByteBuffer
223230 * @throws Throwable
224231 */
225- @Test(groups = "integration")
232+ @Test(groups = "long")
226233 public void wideByteRows() throws Throwable {
227234 Cluster.Builder builder = Cluster.builder();
228235 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -245,7 +252,7 @@
245252 * Test a row with a single extra large text value
246253 * @throws Throwable
247254 */
248- @Test(groups = "integration")
255+ @Test(groups = "short")
249256 public void largeText() throws Throwable {
250257 Cluster.Builder builder = Cluster.builder();
251258 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, builder);
@@ -268,7 +275,7 @@
268275 * Creates a table with 330 columns
269276 * @throws Throwable
270277 */
271- @Test(groups = "integration")
278+ @Test(groups = "short")
272279 public void wideTable() throws Throwable {
273280 Cluster.Builder builder = Cluster.builder();
274281 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 @@
1515 */
1616 package com.datastax.driver.core;
1717
18-import java.io.PrintWriter;
19-import java.io.StringWriter;
2018 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;
2425 import org.testng.annotations.Test;
2526
26-import static org.testng.Assert.assertEquals;
27+import static org.assertj.core.api.Assertions.assertThat;
2728
2829 import com.datastax.driver.core.policies.DelegatingLoadBalancingPolicy;
2930 import com.datastax.driver.core.policies.LoadBalancingPolicy;
3031 import com.datastax.driver.core.policies.RoundRobinPolicy;
3132
33+import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.Action.*;
34+import static com.datastax.driver.core.LoadBalancingPolicyBootstrapTest.HistoryPolicy.entry;
35+
3236 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- }
4237
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+ */
4347 @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+ }
5172 }
5273
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+ }
56144 }
57145
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+ }
59178
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+ }
66182
67- final StringWriter history = new StringWriter();
68- private final PrintWriter out = new PrintWriter(history);
183+ List<Entry> history = Lists.newArrayList();
69184
70- public CountingPolicy(LoadBalancingPolicy delegate) {
185+ public HistoryPolicy(LoadBalancingPolicy delegate) {
71186 super(delegate);
72187 }
73188
74189 @Override
75190 public void init(Cluster cluster, Collection<Host> hosts) {
76191 super.init(cluster, hosts);
77- inits += hosts.size();
192+ for (Host host : hosts) {
193+ history.add(entry(INIT, host));
194+ }
78195 }
79196
80197 public void onAdd(Host host) {
81- out.printf("add %s%n", host);
82- adds++;
198+ history.add(entry(ADD, host));
83199 super.onAdd(host);
84200 }
85201
86202 public void onSuspected(Host host) {
87- out.printf("suspect %s%n", host);
88- suspecteds++;
203+ history.add(entry(SUSPECT, host));
89204 super.onSuspected(host);
90205 }
91206
92207 public void onUp(Host host) {
93- out.printf("up %s%n", host);
94- ups++;
208+ history.add(entry(UP, host));
95209 super.onUp(host);
96210 }
97211
98212 public void onDown(Host host) {
99- out.printf("down %s%n", host);
100- downs++;
213+ history.add(entry(DOWN, host));
101214 super.onDown(host);
102215 }
103216
104217 public void onRemove(Host host) {
105- out.printf("remove %s%n", host);
106- removes++;
218+ history.add(entry(REMOVE, host));
107219 super.onRemove(host);
108220 }
109221 }
modified driver-core/src/test/java/com/datastax/driver/core/MemoryAppender.java +11 −0
@@ -14,6 +14,8 @@
1414 public class MemoryAppender extends WriterAppender {
1515 public final StringWriter writer = new StringWriter();
1616
17+ private int nextLogIdx = 0;
18+
1719 public MemoryAppender() {
1820 setWriter(writer);
1921 setLayout(new PatternLayout("%m%n"));
@@ -22,4 +24,13 @@
2224 public String get() {
2325 return writer.toString();
2426 }
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+ }
2536 }
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +4 −2
@@ -22,10 +22,10 @@
2222 @Test(groups = "short")
2323 public void testMissingRpcAddressAtStartup() throws Exception {
2424 CCMBridge ccm = CCMBridge.create("ccm", 2);
25- deleteNode2RpcAddressFromNode1();
2625
2726 Cluster cluster = null;
2827 try {
28+ deleteNode2RpcAddressFromNode1();
2929 // Use only one contact point to make sure that the control connection is on node1
3030 cluster = Cluster.builder()
3131 .addContactPoint(CCMBridge.IP_PREFIX + "1")
@@ -53,7 +53,9 @@
5353 Lists.newArrayList(socketAddress(1))))
5454 .build();
5555 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);
5759 session.close();
5860 } finally {
5961 if (cluster != null)
modified driver-core/src/test/java/com/datastax/driver/core/PoolingOptionsTest.java +4 −3
@@ -48,8 +48,9 @@
4848 .hasState(State.UP)
4949 .isAtDistance(HostDistance.LOCAL);
5050 // 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
5152 assertThat(cluster).host(2)
52- .comesUpWithin(120, SECONDS)
53+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
5354 .isAtDistance(HostDistance.LOCAL);
5455
5556 // Bring host 3 up, its presence should be acknowledged but it should be ignored
@@ -63,13 +64,13 @@
6364 .hasState(State.UP)
6465 .isAtDistance(HostDistance.LOCAL);
6566 assertThat(cluster).host(3)
66- .comesUpWithin(120, SECONDS)
67+ .comesUpWithin(Cluster.NEW_NODE_DELAY_SECONDS+1, SECONDS)
6768 .isAtDistance(HostDistance.IGNORED);
6869 assertThat(session).hasNoPoolFor(3);
6970
7071 // Kill host 2, host 3 should take its place
7172 ccm.stop(2);
72- TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster, 120);
73+ TestUtils.waitFor(CCMBridge.ipOfNode(3), cluster);
7374
7475 assertThat(cluster).host(1)
7576 .hasState(State.UP)
modified driver-core/src/test/java/com/datastax/driver/core/ReconnectionTest.java +42 −19
@@ -5,6 +5,8 @@
55 import java.util.Collections;
66 import java.util.Iterator;
77 import java.util.Map;
8+import java.util.concurrent.ConcurrentHashMap;
9+import java.util.concurrent.ConcurrentMap;
810 import java.util.concurrent.TimeUnit;
911 import java.util.concurrent.atomic.AtomicInteger;
1012
@@ -12,7 +14,9 @@
1214
1315 import com.google.common.base.Charsets;
1416 import com.google.common.collect.ImmutableMap;
17+import com.google.common.util.concurrent.ListenableFuture;
1518 import org.testng.annotations.Test;
19+
1620 import static org.assertj.core.api.Assertions.assertThat;
1721
1822 import com.datastax.driver.core.Host.State;
@@ -33,9 +37,9 @@
3337 ccm = CCMBridge.create("test", 2);
3438 int reconnectionDelay = 1000;
3539 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();
3943 cluster.connect();
4044
4145 assertThat(cluster).usesControlHost(1);
@@ -78,11 +82,11 @@
7882 CountingReconnectionPolicy reconnectionPolicy = new CountingReconnectionPolicy(new ConstantReconnectionPolicy(reconnectionDelayMs));
7983
8084 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();
8690
8791 cluster.init();
8892 assertThat(cluster).usesControlHost(1);
@@ -128,9 +132,9 @@
128132 try {
129133 ccm = CCMBridge.create("test", 2);
130134 cluster = Cluster.builder()
131- .addContactPoint(CCMBridge.ipOfNode(1))
132- .withReconnectionPolicy(reconnectionPolicy)
133- .build();
135+ .addContactPoint(CCMBridge.ipOfNode(1))
136+ .withReconnectionPolicy(reconnectionPolicy)
137+ .build();
134138 cluster.connect();
135139
136140 // Stop a node and cancel the reconnection attempts to it
@@ -169,22 +173,25 @@
169173 try {
170174 ccm = CCMBridge.create("test", 1);
171175 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();
176180 cluster.connect();
177181
178182 // Tweak the LBP so that the control connection never reconnects, otherwise
179183 // it would interfere with the rest of the test (this is a bit of a hack)
180184 loadBalancingPolicy.returnEmptyQueryPlan = true;
181185
182- // Stop the node and cancel the reconnection attempts to it
186+ // Stop the node, ignore it and cancel reconnection attempts to it
183187 ccm.stop(1);
184188 ccm.waitForDown(1);
185189 assertThat(cluster).host(1).goesDownWithin(20, SECONDS);
186190 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);
188195
189196 // Trigger a one-time reconnection attempt (this will fail)
190197 host1.tryReconnectOnce();
@@ -260,8 +267,9 @@
260267
261268 @Override
262269 Map<String, String> getCredentials() {
270+ count.incrementAndGet();
263271 return ImmutableMap.of("username", username,
264- "password", password);
272+ "password", password);
265273 }
266274 }
267275 }
@@ -298,16 +306,31 @@
298306 }
299307
300308 /**
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.
302312 */
303313 public static class TogglabePolicy extends DelegatingLoadBalancingPolicy {
304314
305315 volatile boolean returnEmptyQueryPlan;
316+ final ConcurrentMap<Host, HostDistance> distances = new ConcurrentHashMap<Host, HostDistance>();
306317
307318 public TogglabePolicy(LoadBalancingPolicy delegate) {
308319 super(delegate);
309320 }
310321
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+
311334 @Override
312335 public Iterator<Host> newQueryPlan(String loggedKeyspace, Statement statement) {
313336 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 @@
99 import org.testng.annotations.BeforeClass;
1010 import org.testng.annotations.Test;
1111
12+import com.datastax.driver.core.exceptions.InvalidQueryException;
1213 import com.datastax.driver.core.utils.Bytes;
1314
1415 import static com.datastax.driver.core.Assertions.assertThat;
@@ -130,9 +131,15 @@
130131
131132 @AfterMethod(groups = "short")
132133 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) {}
136143 }
137144
138145 @AfterClass(groups = "short")
modified driver-core/src/test/java/com/datastax/driver/core/SessionTest.java +5 −3
@@ -161,16 +161,18 @@
161161
162162 // create a new cluster object and ensure 0 sessions and connections
163163 Cluster cluster = Cluster.builder().addContactPoints(CCMBridge.IP_PREFIX + '1').build();
164+
164165 assertEquals(cluster.manager.sessions.size(), 0);
165166 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 0);
166167
168+ // ensure sessions.size() returns with 1 control connection + core pool size.
167169 Session session = cluster.connect();
168170 assertEquals(cluster.manager.sessions.size(), 1);
169171 int coreConnections = TestUtils.numberOfLocalCoreConnections(cluster);
170172 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
171173 1 + coreConnections);
172174
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)
174176 session.close();
175177 assertEquals(cluster.manager.sessions.size(), 0);
176178 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
@@ -183,8 +185,8 @@
183185 assertEquals(cluster.manager.sessions.size(), 0);
184186 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(), 1);
185187
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.
188190 thisSession = cluster.connect();
189191 assertEquals(cluster.manager.sessions.size(), 1);
190192 assertEquals((int) cluster.getMetrics().getOpenConnections().getValue(),
modified driver-core/src/test/java/com/datastax/driver/core/StateListenerTest.java +18 −23
@@ -15,7 +15,11 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.collect.Sets;
1819 import org.testng.annotations.Test;
20+
21+import java.util.Set;
22+
1923 import static org.testng.Assert.assertEquals;
2024
2125 import static com.datastax.driver.core.TestUtils.*;
@@ -25,7 +29,7 @@
2529 */
2630 public class StateListenerTest {
2731
28- @Test(groups = "short")
32+ @Test(groups = "long")
2933 public void listenerTest() throws Throwable {
3034
3135 CCMBridge.CCMCluster c = CCMBridge.buildCluster(1, Cluster.builder());
@@ -42,22 +46,22 @@
4246 // just before the listeners are called, and since waitFor is based on isUP,
4347 // it can return *just* before the listener are called.
4448 Thread.sleep(500);
45- assertEquals(listener.adds, 1);
49+ assertEquals(listener.adds.size(), 1);
4650
4751 c.cassandraCluster.forceStop(1);
4852 waitForDown(CCMBridge.IP_PREFIX + '1', cluster);
4953 Thread.sleep(500);
50- assertEquals(listener.downs, 1);
54+ assertEquals(listener.downs.size(), 1);
5155
5256 c.cassandraCluster.start(1);
5357 waitFor(CCMBridge.IP_PREFIX + '1', cluster);
5458 Thread.sleep(500);
55- assertEquals(listener.ups, 1);
59+ assertEquals(listener.ups.size(), 1);
5660
5761 c.cassandraCluster.decommissionNode(2);
5862 waitForDecommission(CCMBridge.IP_PREFIX + '2', cluster);
5963 Thread.sleep(500);
60- assertEquals(listener.removes, 1);
64+ assertEquals(listener.removes.size(), 1);
6165 } catch (Throwable e) {
6266 c.errorOut();
6367 throw e;
@@ -68,28 +72,19 @@
6872
6973 private static class CountingListener implements Host.StateListener {
7074
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();
7579
76- public void onAdd(Host host) {
77- adds++;
78- }
80+ public void onAdd(Host host) { adds.add(host); }
7981
80- public void onUp(Host host) {
81- ups++;
82- }
82+ public void onUp(Host host) { ups.add(host); }
8383
84- public void onSuspected(Host host) {
85- }
84+ public void onSuspected(Host host) {}
8685
87- public void onDown(Host host) {
88- downs++;
89- }
86+ public void onDown(Host host) { downs.add(host); }
9087
91- public void onRemove(Host host) {
92- removes++;
93- }
88+ public void onRemove(Host host) { removes.add(host); }
9489 }
9590 }
modified driver-core/src/test/java/com/datastax/driver/core/TestListener.java +32 −4
@@ -15,12 +15,16 @@
1515 */
1616 package com.datastax.driver.core;
1717
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;
2123 import java.util.concurrent.TimeUnit;
2224
23-public class TestListener extends TestListenerAdapter {
25+import com.datastax.driver.core.utils.CassandraVersion;
26+
27+public class TestListener extends TestListenerAdapter implements IInvokedMethodListener {
2428
2529 private long start_time = System.nanoTime();
2630 private int test_index = 0;
@@ -78,4 +82,28 @@
7882 + ':' + (minutes < 10 ? "0" : "") + minutes
7983 + ':' + (seconds< 10 ? "0" : "") + seconds);
8084 }
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+ }
81109 }
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +56 −6
@@ -15,14 +15,18 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import java.io.IOException;
1819 import java.math.BigDecimal;
1920 import java.math.BigInteger;
2021 import java.net.InetAddress;
22+import java.net.ServerSocket;
2123 import java.nio.ByteBuffer;
2224 import java.util.*;
2325
2426 import static org.testng.Assert.fail;
2527
28+import org.scassandra.Scassandra;
29+import org.scassandra.ScassandraFactory;
2630 import org.slf4j.Logger;
2731 import org.slf4j.LoggerFactory;
2832 import org.testng.SkipException;
@@ -45,6 +49,8 @@
4549 public static final String INSERT_FORMAT = "INSERT INTO %s (k, t, i, f) VALUES ('%s', '%s', %d, %f)";
4650 public static final String SELECT_ALL_FORMAT = "SELECT * FROM %s";
4751
52+ public static final int TEST_BASE_NODE_WAIT = SystemProperties.getInt("com.datastax.driver.TEST_BASE_NODE_WAIT", 60);
53+
4854 @SuppressWarnings({ "unchecked", "rawtypes" })
4955 public static BoundStatement setBoundValue(BoundStatement bs, String name, DataType type, Object value) {
5056 switch (type.getName()) {
@@ -177,7 +183,7 @@
177183 case FLOAT:
178184 return 3.142519f;
179185 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 });
181187 case INT:
182188 return 24;
183189 case TEXT:
@@ -263,7 +269,7 @@
263269 // This is used because there is some delay between when a node has been
264270 // added through ccm and when it's actually available for querying
265271 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);
267273 }
268274
269275 public static void waitFor(String node, Cluster cluster, int maxTry) {
@@ -271,11 +277,11 @@
271277 }
272278
273279 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);
275281 }
276282
277283 public static void waitForDownWithWait(String node, Cluster cluster, int waitTime) {
278- waitFor(node, cluster, 180, true, false);
284+ waitForDown(node, cluster);
279285
280286 // FIXME: Once stop() works, remove this line
281287 try {
@@ -295,7 +301,7 @@
295301 }
296302
297303 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);
299305 }
300306
301307 public static void waitForDecommission(String node, Cluster cluster, int maxTry) {
@@ -368,7 +374,7 @@
368374 int minor = Integer.parseInt(versionArray[2]);
369375
370376 if (major < majorCheck || (major == majorCheck && minor < minorCheck)) {
371- throw new SkipException(skipString);
377+ throw new SkipException("Version >= " + majorCheck + "." + minorCheck + " required. Description: " + skipString);
372378 }
373379 }
374380
@@ -390,4 +396,48 @@
390396 ? configuration.getPoolingOptions().getCoreConnectionsPerHost(HostDistance.LOCAL)
391397 : 1;
392398 }
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+ }
393443 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/DCAwareRoundRobinPolicyTest.java +4 −6
@@ -14,6 +14,7 @@
1414 import com.datastax.driver.core.*;
1515
1616 public class DCAwareRoundRobinPolicyTest {
17+ Logger policyLogger = Logger.getLogger(DCAwareRoundRobinPolicy.class);
1718 MemoryAppender logs;
1819 CCMBridge ccm;
1920
@@ -31,18 +32,15 @@
3132
3233 @BeforeMethod(groups = "short")
3334 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);
3936 logs = new MemoryAppender();
4037 policyLogger.addAppender(logs);
4138 }
4239
4340 @AfterMethod(groups = "short")
4441 public void stopRecordingLogs() {
45- Logger.getLogger(DCAwareRoundRobinPolicy.class).removeAppender(logs);
42+ policyLogger.setLevel(null);
43+ policyLogger.removeAppender(logs);
4644 }
4745
4846 @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 @@
9393
9494 @Test(groups = "short")
9595 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')");
9897 RegularStatement built = insertInto(TABLE1).value("k", "batchTest2").value("t", "val2");
9998 session.execute(batch().add(simple).add(built));
10099
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderITest.java +4 −1
@@ -25,6 +25,8 @@
2525
2626 import com.datastax.driver.core.*;
2727 import com.datastax.driver.core.exceptions.SyntaxError;
28+import com.datastax.driver.core.utils.CassandraVersion;
29+
2830 import static com.datastax.driver.core.querybuilder.QueryBuilder.*;
2931
3032 public class QueryBuilderITest extends CCMBridge.PerClassSingleNodeCluster {
@@ -206,7 +208,8 @@
206208 }
207209
208210 @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 {
210213 session.execute("INSERT INTO ks.test_int (k, a, b) VALUES (1, 1, 1)");
211214
212215 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 @@
11 # Set root logger level to DEBUG and its only appender to A1.
22 log4j.rootLogger=INFO, A1
33
4+# Scassandra's info log is a bit verbose
5+log4j.logger.org.scassandra=WARN
6+
47 # A1 is set to be a ConsoleAppender.
58 log4j.appender.A1=org.apache.log4j.ConsoleAppender
69