Elffuss BraidHub

kikocis/java-driver public

Merge branch '3.0.x' into 3.1.x
Changeset52d22fede0702a11968ef42139580f22ce1a63ec27ecd13eedd0c1ca5adf7f2d
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-12-29 12:31 +01:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-12-29 12:39 +01:00
Parentsdab837f5b945, a6c13e17062e

Browse the files at this changeset

15 files changed

modified build.yaml +8 −1
@@ -4,7 +4,12 @@
44 schedule: per_commit
55 matrix:
66 exclude:
7- - java: [openjdk6, oraclejdk7]
7+ # Exclude all java 7 builds
8+ - java: oraclejdk7
9+ # Exclude java6 with all versions except latest
10+ - java: openjdk6
11+ cassandra: ['1.2', '2.0', '2.1', '2.2', '3.0']
12+ # Exclude 2.2 and 3.0 always since 3.X provides latest protocol version
813 - cassandra: ['2.2', '3.0']
914 env_vars: |
1015 TEST_GROUP="short"
@@ -39,6 +44,7 @@
3944 cassandra.version=$CCM_CASSANDRA_VERSION
4045 ccm.java.home=$CCM_JAVA_HOME
4146 ccm.path=$CCM_JAVA_HOME/bin
47+ ccm.maxNumberOfNodes=3
4248 failIfNoTests=false
4349 maven.test.failure.ignore=true
4450 maven.javadoc.skip=true
@@ -51,6 +57,7 @@
5157 cassandra.version=$CCM_CASSANDRA_VERSION
5258 ccm.java.home=$CCM_JAVA_HOME
5359 ccm.path=$CCM_JAVA_HOME/bin
60+ ccm.maxNumberOfNodes=3
5461 failIfNoTests=false
5562 maven.test.failure.ignore=true
5663 maven.javadoc.skip=true
modified changelog/README.md +6 −2
@@ -2,15 +2,19 @@
22
33 ### 3.1.3 (in progress)
44
5+Merged from 3.0.x branch:
6+
57 - [bug] JAVA-1330: Add un/register for SchemaChangeListener in DelegatingCluster
68 - [bug] JAVA-1351: Include Custom Payload in Request.copy.
9+- [bug] JAVA-1346: Reset heartbeat only on client reads (not writes).
10+- [improvement] JAVA-866: Support tuple notation in QueryBuilder.eq/in.
711
812
913 ### 3.1.2
1014
1115 - [bug] JAVA-1321: Wrong OSGi dependency version for Guava.
1216
13-Merged from 3.0.x:
17+Merged from 3.0.x branch:
1418
1519 - [bug] JAVA-1312: QueryBuilder modifies selected columns when manually selected.
1620 - [improvement] JAVA-1303: Add missing BoundStatement.setRoutingKey(ByteBuffer...)
@@ -23,7 +27,7 @@
2327 - [bug] JAVA-1255: Allow nested UDTs to be used in Mapper.
2428 - [bug] JAVA-1279: Mapper should exclude Groovy's "metaClass" property when looking for mapped properties
2529
26-Merged from 3.0.x:
30+Merged from 3.0.x branch:
2731
2832 - [improvement] JAVA-1246: Driver swallows the real exception in a few cases
2933 - [improvement] JAVA-1261: Throw error when attempting to page in I/O thread.
modified driver-core/src/main/java/com/datastax/driver/core/Connection.java +3 −3
@@ -50,7 +50,7 @@
5050 import java.util.concurrent.atomic.AtomicReference;
5151
5252 import static com.datastax.driver.core.Message.Response.Type.ERROR;
53-import static io.netty.handler.timeout.IdleState.ALL_IDLE;
53+import static io.netty.handler.timeout.IdleState.READER_IDLE;
5454
5555 // For LoggingHandler
5656 //import org.jboss.netty.handler.logging.LoggingHandler;
@@ -1077,7 +1077,7 @@
10771077
10781078 @Override
10791079 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
1080- if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == ALL_IDLE) {
1080+ if (!isClosed() && evt instanceof IdleStateEvent && ((IdleStateEvent) evt).state() == READER_IDLE) {
10811081 logger.debug("{} was inactive for {} seconds, sending heartbeat", Connection.this, factory.configuration.getPoolingOptions().getHeartbeatIntervalSeconds());
10821082 write(HEARTBEAT_CALLBACK);
10831083 }
@@ -1406,7 +1406,7 @@
14061406 this.sslOptions = sslOptions;
14071407 this.nettyOptions = nettyOptions;
14081408 this.codecRegistry = codecRegistry;
1409- this.idleStateHandler = new IdleStateHandler(0, 0, heartBeatIntervalSeconds);
1409+ this.idleStateHandler = new IdleStateHandler(heartBeatIntervalSeconds, 0, 0);
14101410 }
14111411
14121412 @Override
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/Clause.java +28 −13
@@ -227,9 +227,23 @@
227227
228228 static class CompoundInClause extends Clause {
229229 private final List<String> names;
230- private final List<List<?>> valueLists;
230+ private final List<?> valueLists;
231231
232- public CompoundInClause(List<String> names, List<List<?>> valueLists) {
232+ public CompoundInClause(List<String> names, List<?> valueLists) {
233+ if (valueLists == null)
234+ throw new IllegalArgumentException("Missing values for IN clause");
235+ if (valueLists.size() > 65535)
236+ throw new IllegalArgumentException("Too many values for IN clause, the maximum allowed is 65535");
237+ for (Object value : valueLists) {
238+ if (value instanceof List) {
239+ List<?> tuple = (List<?>) value;
240+ if (tuple.size() != names.size()) {
241+ throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), tuple.size()));
242+ }
243+ } else if (!(value instanceof BindMarker)) {
244+ throw new IllegalArgumentException(String.format("Wrong element type for values list, expected List or BindMarker, got %s", value.getClass().getName()));
245+ }
246+ }
233247 this.names = names;
234248 this.valueLists = valueLists;
235249 }
@@ -250,11 +264,7 @@
250264
251265 @Override
252266 boolean containsBindMarker() {
253- for (List<?> values : valueLists)
254- for (Object value : values)
255- if (Utils.containsBindMarker(value))
256- return true;
257- return false;
267+ return Utils.containsBindMarker(valueLists);
258268 }
259269
260270 @Override
@@ -270,14 +280,19 @@
270280 if (i > 0)
271281 sb.append(",");
272282
273- List<?> values = valueLists.get(i);
283+ Object elt = valueLists.get(i);
274284
275- // Special case when there is only one bind marker: "IN ?" instead of "IN (?)"
276- if (values.size() == 1 && values.get(0) instanceof BindMarker) {
277- sb.append(values.get(0));
285+ if (elt instanceof BindMarker) {
286+ sb.append(elt);
278287 } else {
279- sb.append("(");
280- Utils.joinAndAppendValues(sb, codecRegistry, ",", values, variables).append(')');
288+ List<?> tuple = (List<?>) elt;
289+ if (tuple.size() == 1 && tuple.get(0) instanceof BindMarker) {
290+ // Special case when there is only one bind marker: "IN ?" instead of "IN (?)"
291+ sb.append(tuple.get(0));
292+ } else {
293+ sb.append("(");
294+ Utils.joinAndAppendValues(sb, codecRegistry, ",", (List<?>) tuple, variables).append(')');
295+ }
281296 }
282297 }
283298 sb.append(")");
modified driver-core/src/main/java/com/datastax/driver/core/querybuilder/QueryBuilder.java +11 −8
@@ -333,22 +333,25 @@
333333 }
334334
335335 /**
336- * Creates an "in" where clause for a group of clustering columns.
336+ * Creates an "in" where clause for a group of clustering columns (a.k.a. "multi-column IN restriction").
337337 * <p/>
338- * For instance, {@code in(Arrays.asList("a", "b"), Arrays.asList(Arrays.asList(1, 2), Arrays.asList("foo", "bar")))}
339- * will generate the CQL WHERE clause {@code (a, b) IN ((1, 2), ('foo', 'bar')) }.
338+ * For instance, {@code in(Arrays.asList("a", "b"), Arrays.asList(Arrays.asList(1, "foo"), Arrays.asList(2, "bar")))}
339+ * will generate the CQL WHERE clause {@code (a, b) IN ((1, 'foo'), (2, 'bar'))}.
340+ * <p/>
341+ * Each element in {@code values} must be either a {@link List list} containing exactly as many values
342+ * as there are columns to match in {@code names},
343+ * or a {@link #bindMarker() bind marker} – in which case, that marker is to be considered as
344+ * a placeholder for one whole tuple of values to match.
340345 * <p/>
341346 * Please note that this variant is only supported starting with Cassandra 2.0.9.
342347 *
343348 * @param names the column names
344349 * @param values the values
345350 * @return the corresponding where clause.
346- * @throws IllegalArgumentException if {@code names.size() != values.size()}.
351+ * @throws IllegalArgumentException if the size of any tuple in {@code values} is not equal to {@code names.size()},
352+ * or if {@code values} contains elements that are neither {@link List lists} nor {@link #bindMarker() bind markers}.
347353 */
348- public static Clause in(List<String> names, List<List<?>> values) {
349- if (names.size() != values.size())
350- throw new IllegalArgumentException(String.format("The number of names (%d) and values (%d) don't match", names.size(), values.size()));
351-
354+ public static Clause in(List<String> names, List<?> values) {
352355 return new Clause.CompoundInClause(names, values);
353356 }
354357
modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +101 −19
@@ -34,8 +34,7 @@
3434 import java.util.regex.Matcher;
3535 import java.util.regex.Pattern;
3636
37-import static com.datastax.driver.core.TestUtils.executeNoFail;
38-import static com.datastax.driver.core.TestUtils.findAvailablePort;
37+import static com.datastax.driver.core.TestUtils.*;
3938
4039 public class CCMBridge implements CCMAccess {
4140
@@ -86,11 +85,26 @@
8685 * {@link #getCassandraVersion()}. If C* version cannot be derived, the method makes a 'best guess'.
8786 */
8887 private static final Map<String, String> dseToCassandraVersions = ImmutableMap.<String, String>builder()
89- .put("5.0", "3.0")
88+ .put("5.0.4", "3.0.10")
89+ .put("5.0.3", "3.0.9")
90+ .put("5.0.2", "3.0.8")
91+ .put("5.0.1", "3.0.7")
92+ .put("5.0", "3.0.7")
93+ .put("4.8.11", "2.1.17")
94+ .put("4.8.10", "2.1.15")
95+ .put("4.8.9", "2.1.15")
96+ .put("4.8.8", "2.1.14")
97+ .put("4.8.7", "2.1.14")
98+ .put("4.8.6", "2.1.13")
99+ .put("4.8.5", "2.1.13")
100+ .put("4.8.4", "2.1.12")
90101 .put("4.8.3", "2.1.11")
91102 .put("4.8.2", "2.1.11")
92103 .put("4.8.1", "2.1.11")
93104 .put("4.8", "2.1.9")
105+ .put("4.7.9", "2.1.15")
106+ .put("4.7.8", "2.1.13")
107+ .put("4.7.7", "2.1.12")
94108 .put("4.7.6", "2.1.11")
95109 .put("4.7.5", "2.1.11")
96110 .put("4.7.4", "2.1.11")
@@ -221,7 +235,9 @@
221235
222236 private boolean closed = false;
223237
224- private CCMBridge(String clusterName, boolean isDSE, VersionNumber version, int storagePort, int thriftPort, int binaryPort, String jvmArgs) {
238+ private final int[] nodes;
239+
240+ private CCMBridge(String clusterName, boolean isDSE, VersionNumber version, int storagePort, int thriftPort, int binaryPort, String jvmArgs, int[] nodes) {
225241 this.clusterName = clusterName;
226242 this.version = version;
227243 this.storagePort = storagePort;
@@ -229,6 +245,7 @@
229245 this.binaryPort = binaryPort;
230246 this.isDSE = isDSE;
231247 this.jvmArgs = jvmArgs;
248+ this.nodes = nodes;
232249 this.ccmDir = Files.createTempDir();
233250 }
234251
@@ -379,6 +396,21 @@
379396 logger.debug("Closed: {}", this);
380397 }
381398
399+ /**
400+ * Based on C* version, return the wait arguments.
401+ *
402+ * @return For C* 1.x, --wait-other-notice otherwise --no-wait
403+ */
404+ private String getStartWaitArguments() {
405+ // make a small exception for C* 1.2 as it has a bug where it starts listening on the binary
406+ // interface slightly before it joins the cluster.
407+ if (getCassandraVersion().startsWith("1.")) {
408+ return " --wait-other-notice";
409+ } else {
410+ return " --no-wait";
411+ }
412+ }
413+
382414 @Override
383415 public synchronized void start() {
384416 if (started)
@@ -386,11 +418,23 @@
386418 if (logger.isDebugEnabled())
387419 logger.debug("Starting: {} - free memory: {} MB", this, TestUtils.getFreeMemoryMB());
388420 try {
389- String cmd = CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs;
421+ String cmd = CCM_COMMAND + " start " + jvmArgs + getStartWaitArguments();
390422 if (isWindows() && this.version.compareTo(VersionNumber.parse("2.2.4")) >= 0) {
391423 cmd += " --quiet-windows";
392424 }
393425 execute(cmd);
426+
427+ // Wait for binary interface on each node.
428+ int n = 1;
429+ for (int dc = 1; dc <= nodes.length; dc++) {
430+ int nodesInDc = nodes[dc - 1];
431+ for (int i = 0; i < nodesInDc; i++) {
432+ InetSocketAddress addr = new InetSocketAddress(ipOfNode(n), binaryPort);
433+ logger.debug("Waiting for binary protocol to show up for {}", addr);
434+ TestUtils.waitUntilPortIsUp(addr);
435+ n++;
436+ }
437+ }
394438 } catch (CCMException e) {
395439 logger.error("Could not start " + this, e);
396440 logger.error("CCM output:\n{}", e.getOut());
@@ -448,11 +492,15 @@
448492 public void start(int n) {
449493 logger.debug(String.format("Starting: node %s (%s%s:%s) in %s", n, TestUtils.IP_PREFIX, n, binaryPort, this));
450494 try {
451- String cmd = CCM_COMMAND + " node%d start --wait-other-notice --wait-for-binary-proto" + jvmArgs;
495+ String cmd = CCM_COMMAND + " node%d start " + jvmArgs + getStartWaitArguments();
452496 if (isWindows() && this.version.compareTo(VersionNumber.parse("2.2.4")) >= 0) {
453497 cmd += " --quiet-windows";
454498 }
455499 execute(cmd, n);
500+ // Wait for binary interface
501+ InetSocketAddress addr = new InetSocketAddress(ipOfNode(n), binaryPort);
502+ logger.debug("Waiting for binary protocol to show up for {}", addr);
503+ TestUtils.waitUntilPortIsUp(addr);
456504 } catch (CCMException e) {
457505 logger.error(String.format("Could not start node %s in %s", n, this), e);
458506 logger.error("CCM output:\n{}", e.getOut());
@@ -698,7 +746,7 @@
698746
699747 int[] nodes = {1};
700748 private boolean start = true;
701- private boolean isDSE = isDSE();
749+ private Boolean isDSE = null;
702750 private String version = getCassandraVersion();
703751 private Set<String> createOptions = new LinkedHashSet<String>(getInstallArguments());
704752 private Set<String> jvmArgs = new LinkedHashSet<String>();
@@ -759,11 +807,18 @@
759807 * Sets this cluster to be a DSE cluster (defaults to {@link #isDSE()} if this is never called).
760808 */
761809 public Builder withDSE() {
762- this.createOptions.add("--dse");
763810 this.isDSE = true;
764811 return this;
765812 }
766813
814+ /**
815+ * Sets this cluster to be a non-DSE cluster (defaults to {@link #isDSE()} if this is never called).
816+ */
817+ public Builder withoutDSE() {
818+ this.isDSE = false;
819+ return this;
820+ }
821+
767822 /**
768823 * The Cassandra or DSE version to use (defaults to {@link #getCassandraVersion()} if this is never called).
769824 */
@@ -846,24 +901,38 @@
846901 public CCMBridge build() {
847902 // be careful NOT to alter internal state (hashCode/equals) during build!
848903 String clusterName = TestUtils.generateIdentifier("ccm_");
904+ boolean dse = isDSE == null ? isDSE() : isDSE;
905+
849906 Map<String, Object> cassandraConfiguration = randomizePorts(this.cassandraConfiguration);
850- Map<String, Object> dseConfiguration = randomizePorts(this.dseConfiguration);
851907 VersionNumber version = VersionNumber.parse(this.version);
852908 int storagePort = Integer.parseInt(cassandraConfiguration.get("storage_port").toString());
853909 int thriftPort = Integer.parseInt(cassandraConfiguration.get("rpc_port").toString());
854910 int binaryPort = Integer.parseInt(cassandraConfiguration.get("native_transport_port").toString());
855- final CCMBridge ccm = new CCMBridge(clusterName, isDSE, version, storagePort, thriftPort, binaryPort, joinJvmArgs());
911+ final CCMBridge ccm = new CCMBridge(clusterName, dse, version, storagePort, thriftPort, binaryPort, joinJvmArgs(), nodes);
912+
856913 Runtime.getRuntime().addShutdownHook(new Thread() {
857914 @Override
858915 public void run() {
859916 ccm.close();
860917 }
861918 });
862- ccm.execute(buildCreateCommand(clusterName));
919+ ccm.execute(buildCreateCommand(clusterName, dse));
863920 updateNodeConf(ccm);
864921 ccm.updateConfig(cassandraConfiguration);
865- if (!dseConfiguration.isEmpty())
866- ccm.updateDSEConfig(dseConfiguration);
922+ if (dse) {
923+ Map<String, Object> dseConfiguration = Maps.newLinkedHashMap(this.dseConfiguration);
924+ /* TODO: Use version passed in if present, there is currently a conflation of C* and DSE versions
925+ * when it comes to this that don't want to disturb. No tests are currently using withVersion with
926+ * dse, so its not an issue at the moment. */
927+ if (VersionNumber.parse(CCMBridge.getDSEVersion()).getMajor() >= 5) {
928+ // randomize DSE specific ports if dse present and greater than 5.0
929+ dseConfiguration.put("lease_netty_server_port", RANDOM_PORT);
930+ dseConfiguration.put("internode_messaging_options.port", RANDOM_PORT);
931+ }
932+ dseConfiguration = randomizePorts(dseConfiguration);
933+ if (!dseConfiguration.isEmpty())
934+ ccm.updateDSEConfig(dseConfiguration);
935+ }
867936 for (Map.Entry<Integer, Workload[]> entry : workloads.entrySet()) {
868937 ccm.setWorkload(entry.getKey(), entry.getValue());
869938 }
@@ -895,7 +964,7 @@
895964 return allJvmArgs.toString();
896965 }
897966
898- private String buildCreateCommand(String clusterName) {
967+ private String buildCreateCommand(String clusterName, boolean dse) {
899968 StringBuilder result = new StringBuilder(CCM_COMMAND + " create");
900969 result.append(" ").append(clusterName);
901970 result.append(" -i ").append(TestUtils.IP_PREFIX);
@@ -909,7 +978,20 @@
909978 result.append(node);
910979 }
911980 }
912- result.append(" ").append(Joiner.on(" ").join(randomizePorts(createOptions)));
981+
982+ // If not DSE, remove --dse if in createOptions.
983+ Set<String> lCreateOptions = new LinkedHashSet<String>(createOptions);
984+ if (!dse) {
985+ Iterator<String> it = lCreateOptions.iterator();
986+ while (it.hasNext()) {
987+ String option = it.next();
988+ // remove any version previously set and
989+ // install-dir, which is incompatible
990+ if (option.equals("--dse"))
991+ it.remove();
992+ }
993+ }
994+ result.append(" ").append(Joiner.on(" ").join(randomizePorts(lCreateOptions)));
913995 return result.toString();
914996 }
915997
@@ -1000,14 +1082,14 @@
10001082 if (this == o) return true;
10011083 if (o == null || getClass() != o.getClass()) return false;
10021084 Builder builder = (Builder) o;
1003- if (isDSE != builder.isDSE) return false;
10041085 if (!Arrays.equals(nodes, builder.nodes)) return false;
1086+ if (isDSE != null ? !isDSE.equals(builder.isDSE) : builder.isDSE != null) return false;
1087+ if (!version.equals(builder.version)) return false;
10051088 if (!createOptions.equals(builder.createOptions)) return false;
10061089 if (!jvmArgs.equals(builder.jvmArgs)) return false;
10071090 if (!cassandraConfiguration.equals(builder.cassandraConfiguration)) return false;
10081091 if (!dseConfiguration.equals(builder.dseConfiguration)) return false;
1009- if (!workloads.equals(builder.workloads)) return false;
1010- return version.equals(builder.version);
1092+ return workloads.equals(builder.workloads);
10111093 }
10121094
10131095 @Override
@@ -1015,7 +1097,7 @@
10151097 // do not include cluster name and start, only
10161098 // properties relevant to the settings of the cluster
10171099 int result = Arrays.hashCode(nodes);
1018- result = 31 * result + (isDSE ? 1 : 0);
1100+ result = 31 * result + (isDSE != null ? isDSE.hashCode() : 0);
10191101 result = 31 * result + createOptions.hashCode();
10201102 result = 31 * result + jvmArgs.hashCode();
10211103 result = 31 * result + cassandraConfiguration.hashCode();
modified driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +10 −4
@@ -271,12 +271,12 @@
271271 }
272272
273273 @SuppressWarnings("SimplifiableIfStatement")
274- private boolean dse() {
274+ private Boolean dse() {
275275 for (CCMConfig ann : annotations) {
276276 if (ann != null && ann.dse().length > 0)
277277 return ann.dse()[0];
278278 }
279- return false;
279+ return null;
280280 }
281281
282282 @SuppressWarnings("SimplifiableIfStatement")
@@ -430,8 +430,14 @@
430430 }
431431 if (version() != null)
432432 ccmBuilder.withVersion(version());
433- if (dse())
434- ccmBuilder.withDSE();
433+ Boolean dse = dse();
434+ if (dse != null) {
435+ if (dse) {
436+ ccmBuilder.withDSE();
437+ } else {
438+ ccmBuilder.withoutDSE();
439+ }
440+ }
435441 if (ssl())
436442 ccmBuilder.withSSL();
437443 if (auth())
modified driver-core/src/test/java/com/datastax/driver/core/HeartbeatTest.java +202 −57
@@ -15,18 +15,26 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.google.common.util.concurrent.Uninterruptibles;
1819 import org.apache.log4j.Level;
1920 import org.apache.log4j.Logger;
21+import org.slf4j.LoggerFactory;
2022 import org.testng.annotations.AfterMethod;
2123 import org.testng.annotations.BeforeMethod;
2224 import org.testng.annotations.Test;
2325
26+import java.util.concurrent.TimeUnit;
27+import java.util.regex.Pattern;
28+
2429 import static com.datastax.driver.core.Assertions.assertThat;
2530 import static java.util.concurrent.TimeUnit.SECONDS;
31+import static org.assertj.core.api.Assertions.fail;
32+import static org.scassandra.http.client.PrimingRequest.queryBuilder;
33+import static org.scassandra.http.client.PrimingRequest.then;
2634
27-@CCMConfig(createCluster = false)
28-public class HeartbeatTest extends CCMTestsSupport {
35+public class HeartbeatTest extends ScassandraTestBase {
2936
37+ static org.slf4j.Logger logger = LoggerFactory.getLogger(HeartbeatTest.class);
3038 Logger connectionLogger = Logger.getLogger(Connection.class);
3139 MemoryAppender logs;
3240 Level originalLevel;
@@ -56,47 +64,179 @@
5664 */
5765 @Test(groups = "long")
5866 public void should_send_heartbeat_when_connection_is_inactive() throws InterruptedException {
59- Cluster cluster = register(Cluster.builder()
60- .addContactPoints(getContactPoints().get(0))
61- .withPort(ccm().getBinaryPort())
62- .withPoolingOptions(new PoolingOptions()
63- .setHeartbeatIntervalSeconds(3))
64- .build());
65-
66- // Don't create any session, only the control connection will be established
67- cluster.init();
68-
69- for (int i = 0; i < 5; i++) {
70- triggerRequestOnControlConnection(cluster);
71- SECONDS.sleep(1);
67+ Cluster cluster = Cluster.builder()
68+ .addContactPoints(hostAddress.getAddress())
69+ .withPort(scassandra.getBinaryPort())
70+ .withProtocolVersion(ProtocolVersion.V2)
71+ .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(3))
72+ .build();
73+
74+ try {
75+ // Don't create any session, only the control connection will be established
76+ cluster.init();
77+
78+ for (int i = 0; i < 5; i++) {
79+ triggerRequestOnControlConnection(cluster);
80+ SECONDS.sleep(1);
81+ }
82+ assertThat(logs.getNext()).doesNotContain("sending heartbeat");
83+
84+ // Ensure heartbeat is sent after no activity.
85+ SECONDS.sleep(4);
86+ assertThat(logs.getNext())
87+ .contains("sending heartbeat")
88+ .contains("heartbeat query succeeded");
89+
90+ // Ensure heartbeat is sent after continued inactivity.
91+ SECONDS.sleep(4);
92+ assertThat(logs.getNext())
93+ .contains("sending heartbeat")
94+ .contains("heartbeat query succeeded");
95+
96+ // Ensure heartbeat is not sent after activity.
97+ logs.getNext();
98+ for (int i = 0; i < 5; i++) {
99+ triggerRequestOnControlConnection(cluster);
100+ SECONDS.sleep(1);
101+ }
102+ assertThat(logs.getNext()).doesNotContain("sending heartbeat");
103+
104+ // Finally, ensure heartbeat is sent after inactivity.
105+ SECONDS.sleep(4);
106+ assertThat(logs.getNext())
107+ .contains("sending heartbeat")
108+ .contains("heartbeat query succeeded");
109+ } finally {
110+ cluster.close();
111+ }
112+ }
113+
114+ /**
115+ * Verifies that there exists a line in logs that matches pattern.
116+ *
117+ * @param logs Captured log entries.
118+ * @param pattern Pattern to match on individual lines.
119+ * @return
120+ */
121+ private void assertLineMatches(String logs, Pattern pattern) {
122+ String lines[] = logs.split("\\r?\\n");
123+ for (String line : lines) {
124+ if (pattern.matcher(line).matches()) {
125+ return;
126+ }
127+ }
128+ fail("Expecting: [" + logs + "] to contain " + pattern);
129+ }
130+
131+ /**
132+ * Verifies that no line in logs matches pattern.
133+ *
134+ * @param logs Captured log entries.
135+ * @param pattern Pattern to match on individual lines.
136+ */
137+ private void assertNoLineMatches(String logs, Pattern pattern) {
138+ String lines[] = logs.split("\\r?\\n");
139+ for (String line : lines) {
140+ if (pattern.matcher(line).matches()) {
141+ fail("Expecting: [" + logs + "] not to contain " + pattern);
142+ }
143+ }
144+ }
145+
146+ /**
147+ * Ensures that a heartbeat message is sent after the configured heartbeat interval of idle time when no data is
148+ * received on a connection even though are successful writes on the socket.
149+ *
150+ * @test_category connection:heartbeat
151+ * @expected_result heartbeat is sent after heartbeat interval (3) seconds of idle time.
152+ * @jira_ticket JAVA-1346
153+ * @since 3.0.6, 3.1.3
154+ */
155+ @Test(groups = "long")
156+ public void should_send_heartbeat_when_requests_being_written_but_nothing_received() throws Exception {
157+ Cluster cluster = Cluster.builder()
158+ .addContactPoints(hostAddress.getAddress())
159+ .withPort(scassandra.getBinaryPort())
160+ .withProtocolVersion(ProtocolVersion.V2)
161+ .withPoolingOptions(new PoolingOptions().setHeartbeatIntervalSeconds(3).setConnectionsPerHost(HostDistance.LOCAL, 1, 1))
162+ .build();
163+
164+ // Prime 'ping' to never return a response this is a way to create outgoing traffic
165+ // without receiving anything inbound.
166+ scassandra.primingClient()
167+ .prime(queryBuilder().withQuery("ping").withThen(then().withFixedDelay(8675309999L)));
168+
169+ // Thread that will submit queries that get no response repeatedly.
170+ Thread submitter = null;
171+ try {
172+ // Don't create any session, only the control connection will be established
173+ cluster.init();
174+
175+ // Find the connection in the connection pool.
176+ SessionManager session = (SessionManager) cluster.connect();
177+ Host host = TestUtils.findHost(cluster, 1);
178+ Connection connection = session.pools.get(host).connections.get(0);
179+
180+ // Extract connection name from toString implementation.
181+ String connectionName = connection.toString()
182+ .replaceAll("\\-", "\\\\-") // Replace - with \- so its properly escaped as a regex.
183+ .replaceAll("Connection\\[\\/", "") // Replace first part of toString (Connection[
184+ .replaceAll("\\, inFlight.*", ""); // Replace everything after ',inFlight'
185+
186+ // Define patterns that check for whether or not heartbeats are sent / received on a given connection.
187+ Pattern heartbeatSentPattern = Pattern.compile(".*" + connectionName + ".*sending heartbeat");
188+ Pattern heartbeatReceivedPattern = Pattern.compile(".*" + connectionName + ".*heartbeat query succeeded");
189+ logger.debug("Heartbeat pattern is {}", heartbeatSentPattern);
190+
191+ // Start query submission thread.
192+ submitter = new Thread(new QuerySubmitter(session));
193+ submitter.start();
194+
195+ for (int i = 0; i < 5; i++) {
196+ session.execute("bar");
197+ SECONDS.sleep(1);
198+ }
199+
200+ // Should be no heartbeats sent on pooled connection since we had successful requests.
201+ String log = logs.getNext();
202+ assertNoLineMatches(log, heartbeatSentPattern);
203+
204+ int inFlight = connection.inFlight.get();
205+ assertThat(inFlight).isGreaterThan(0);
206+
207+ // Ensure heartbeat is sent after no received data, even though we have inflight requests (JAVA-1346).
208+ SECONDS.sleep(4);
209+ // Verify more requests were sent over this time period.
210+ assertThat(connection.inFlight.get()).isGreaterThan(inFlight);
211+ log = logs.getNext();
212+ // Heartbeat should have been sent and received.
213+ assertLineMatches(log, heartbeatSentPattern);
214+ assertLineMatches(log, heartbeatReceivedPattern);
215+ } finally {
216+ // interrupt thread so it stops submitting queries.
217+ if (submitter != null) {
218+ submitter.interrupt();
219+ }
220+ cluster.close();
72221 }
73- assertThat(logs.getNext()).doesNotContain("sending heartbeat");
74-
75- // Ensure heartbeat is sent after no activity.
76- SECONDS.sleep(4);
77- assertThat(logs.getNext())
78- .contains("sending heartbeat")
79- .contains("heartbeat query succeeded");
80-
81- // Ensure heartbeat is sent after continued inactivity.
82- SECONDS.sleep(4);
83- assertThat(logs.getNext())
84- .contains("sending heartbeat")
85- .contains("heartbeat query succeeded");
86-
87- // Ensure heartbeat is not sent after activity.
88- logs.getNext();
89- for (int i = 0; i < 5; i++) {
90- triggerRequestOnControlConnection(cluster);
91- SECONDS.sleep(1);
222+ }
223+
224+ private static class QuerySubmitter implements Runnable {
225+
226+ private final Session session;
227+
228+ QuerySubmitter(Session session) {
229+ this.session = session;
230+ }
231+
232+ @Override
233+ public void run() {
234+ while (!Thread.currentThread().isInterrupted()) {
235+ logger.debug("Sending ping, for which we expect no response");
236+ session.executeAsync("ping");
237+ Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
238+ }
92239 }
93- assertThat(logs.getNext()).doesNotContain("sending heartbeat");
94-
95- // Finally, ensure heartbeat is sent after inactivity.
96- SECONDS.sleep(4);
97- assertThat(logs.getNext())
98- .contains("sending heartbeat")
99- .contains("heartbeat query succeeded");
100240 }
101241
102242 /**
@@ -112,25 +252,30 @@
112252 */
113253 @Test(groups = "long")
114254 public void should_not_send_heartbeat_when_disabled() throws InterruptedException {
115- Cluster cluster = register(Cluster.builder()
116- .addContactPoints(getContactPoints().get(0))
117- .withPort(ccm().getBinaryPort())
255+ Cluster cluster = Cluster.builder()
256+ .addContactPoints(hostAddress.getAddress())
257+ .withPort(scassandra.getBinaryPort())
118258 .withPoolingOptions(new PoolingOptions()
119259 .setHeartbeatIntervalSeconds(0))
120- .build());
121-
122- // Don't create any session, only the control connection will be established
123- cluster.init();
124-
125- for (int i = 0; i < 5; i++) {
126- triggerRequestOnControlConnection(cluster);
127- SECONDS.sleep(1);
260+ .withProtocolVersion(ProtocolVersion.V2)
261+ .build();
262+
263+ try {
264+ // Don't create any session, only the control connection will be established
265+ cluster.init();
266+
267+ for (int i = 0; i < 5; i++) {
268+ triggerRequestOnControlConnection(cluster);
269+ SECONDS.sleep(1);
270+ }
271+ assertThat(logs.get()).doesNotContain("sending heartbeat");
272+
273+ // Sleep for a while and ensure no heartbeat is sent.
274+ SECONDS.sleep(32);
275+ assertThat(logs.get()).doesNotContain("sending heartbeat");
276+ } finally {
277+ cluster.close();
128278 }
129- assertThat(logs.get()).doesNotContain("sending heartbeat");
130-
131- // Sleep for a while and ensure no heartbeat is sent.
132- SECONDS.sleep(32);
133- assertThat(logs.get()).doesNotContain("sending heartbeat");
134279 }
135280
136281 // Simulates activity on the control connection via the internal API
modified driver-core/src/test/java/com/datastax/driver/core/HostMetadataIntegrationTest.java +5 −6
@@ -15,6 +15,7 @@
1515 */
1616 package com.datastax.driver.core;
1717
18+import com.datastax.driver.core.utils.DseVersion;
1819 import org.apache.log4j.Level;
1920 import org.apache.log4j.Logger;
2021 import org.testng.annotations.Test;
@@ -35,24 +36,22 @@
3536 * This test is disabled as running DSE with workloads is intensive and has unreliable results
3637 * when running CCM with multiple workloads.
3738 * <p/>
38- * FIXME: this test is currently disabled because nodes with specific workload
39- * do not seem to come up within the allocated time.
4039 *
4140 * @test_category host:metadata
42- * @jira_ticket JAVA1042
41+ * @jira_ticket JAVA-1042
4342 * @see HostMetadataIntegrationTest#should_parse_dse_workload_and_version_if_available()
4443 */
45- @Test(groups = "long", enabled = false)
44+ @Test(groups = "long")
45+ @DseVersion(major = 5.0)
4646 public void test_mixed_dse_workload() {
4747 CCMBridge.Builder builder = CCMBridge.builder()
4848 .withNodes(3)
4949 .withDSE()
50- .withVersion("4.8.3")
5150 .withWorkload(2, solr)
5251 .withWorkload(3, spark);
5352 CCMAccess ccm = CCMCache.get(builder);
5453
55- VersionNumber version = VersionNumber.parse("4.8.3");
54+ VersionNumber version = VersionNumber.parse(CCMBridge.getDSEVersion());
5655
5756 Cluster cluster = Cluster.builder()
5857 .addContactPoints(ccm.addressOfNode(1).getAddress())
modified driver-core/src/test/java/com/datastax/driver/core/LoadBalancingPolicyBootstrapTest.java +34 −26
@@ -53,12 +53,16 @@
5353 .withLoadBalancingPolicy(policy)
5454 .build());
5555
56- cluster.init();
57-
58- assertThat(policy.history).containsOnly(
59- entry(INIT, TestUtils.findHost(cluster, 1)),
60- entry(INIT, TestUtils.findHost(cluster, 2))
61- );
56+ try {
57+ cluster.init();
58+
59+ assertThat(policy.history).containsOnly(
60+ entry(INIT, TestUtils.findHost(cluster, 1)),
61+ entry(INIT, TestUtils.findHost(cluster, 2))
62+ );
63+ } finally {
64+ cluster.close();
65+ }
6266 }
6367
6468 /**
@@ -95,27 +99,31 @@
9599 .withLoadBalancingPolicy(policy)
96100 .build());
97101
98- cluster.init();
99-
100- if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) {
101- // This is the situation we're testing, the control connection tried the stopped node first.
102- assertThat(policy.history).containsExactly(
103- entry(INIT, TestUtils.findHost(cluster, activeNode)),
104- entry(DOWN, TestUtils.findHost(cluster, nodeToStop))
105- );
106- break;
107- } else {
108- assertThat(policy.history).containsOnly(
109- entry(INIT, TestUtils.findHost(cluster, 1)),
110- entry(INIT, TestUtils.findHost(cluster, 2))
111- );
112-
113- logger.info("Could not get first contact point to fail, retrying");
114-
102+ try {
103+ cluster.init();
104+
105+ if (policy.history.contains(entry(DOWN, TestUtils.findHost(cluster, nodeToStop)))) {
106+ // This is the situation we're testing, the control connection tried the stopped node first.
107+ assertThat(policy.history).containsExactly(
108+ entry(INIT, TestUtils.findHost(cluster, activeNode)),
109+ entry(DOWN, TestUtils.findHost(cluster, nodeToStop))
110+ );
111+ break;
112+ } else {
113+ assertThat(policy.history).containsOnly(
114+ entry(INIT, TestUtils.findHost(cluster, 1)),
115+ entry(INIT, TestUtils.findHost(cluster, 2))
116+ );
117+
118+ logger.info("Could not get first contact point to fail, retrying");
119+
120+ cluster.close();
121+
122+ ccm().start(nodeToStop);
123+ ccm().waitForUp(nodeToStop);
124+ }
125+ } finally {
115126 cluster.close();
116-
117- ccm().start(nodeToStop);
118- ccm().waitForUp(nodeToStop);
119127 }
120128 }
121129
modified driver-core/src/test/java/com/datastax/driver/core/ProtocolV1Test.java +1 −1
@@ -25,7 +25,7 @@
2525 /**
2626 * Tests targeting protocol v1 specifically.
2727 */
28-@CCMConfig(version = "1.2.19")
28+@CCMConfig(version = "1.2.19", dse = false)
2929 public class ProtocolV1Test extends CCMTestsSupport {
3030
3131 @Override
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +1 −0
@@ -157,6 +157,7 @@
157157 .withStoragePort(mainCcm.getStoragePort())
158158 .withThriftPort(mainCcm.getThriftPort())
159159 .withBinaryPort(mainCcm.getBinaryPort())
160+ .withoutDSE()
160161 .withVersion("1.2.19");
161162 otherCcm = CCMCache.get(otherCcmBuilder);
162163 otherCcm.waitForUp(1);
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +1 −1
@@ -739,7 +739,7 @@
739739 * @return The desired target protocol version based on the 'cassandra.version' System property.
740740 */
741741 public static ProtocolVersion getDesiredProtocolVersion() {
742- String version = System.getProperty("cassandra.version");
742+ String version = CCMBridge.getCassandraVersion();
743743 String[] versionArray = version.split("\\.|-");
744744 double major = Double.parseDouble(versionArray[0] + "." + versionArray[1]);
745745 if (major < 2.0) {
modified driver-core/src/test/java/com/datastax/driver/core/WarningsTest.java +2 −1
@@ -23,6 +23,8 @@
2323
2424 import static org.assertj.core.api.Assertions.assertThat;
2525
26+@CCMConfig(config = {"batch_size_warn_threshold_in_kb:5"})
27+@CassandraVersion(major = 2.2)
2628 public class WarningsTest extends CCMTestsSupport {
2729
2830 @Override
@@ -30,7 +32,6 @@
3032 execute("CREATE TABLE foo(k int primary key, v text)");
3133 }
3234
33- @CassandraVersion(major = 2.2)
3435 @Test(groups = "short")
3536 public void should_expose_warnings_on_execution_info() {
3637 // the default batch size warn threshold is 5 * 1024 bytes, but after CASSANDRA-10876 there must be
modified driver-core/src/test/java/com/datastax/driver/core/querybuilder/QueryBuilderTest.java +48 −8
@@ -782,21 +782,61 @@
782782 select = select().all().from("foo").where(eq("k", 4)).and(lte(Arrays.asList("c1", "c2"), Arrays.<Object>asList("a", 2)));
783783 assertEquals(select.toString(), query);
784784
785- query = "SELECT * FROM foo WHERE k=4 AND (c1,c2) IN ((1,2),('foo','bar'));";
785+ query = "SELECT * FROM foo WHERE k=4 AND (c1,c2) IN ((1,'foo'),(2,'bar'),(3,'qix'));";
786786 List<String> names = ImmutableList.of("c1", "c2");
787- List<List<?>> values = ImmutableList.<List<?>>of(
788- ImmutableList.of(1, 2),
789- ImmutableList.of("foo", "bar"));
787+ List<?> values = ImmutableList.<List<?>>of(
788+ ImmutableList.of(1, "foo"),
789+ ImmutableList.of(2, "bar"),
790+ ImmutableList.of(3, "qix"));
790791 select = select().all().from("foo").where(eq("k", 4)).and(in(names, values));
791792 assertEquals(select.toString(), query);
792793
793- query = "SELECT * FROM foo WHERE k=4 AND (c1,c2) IN ((1,2),?);";
794+ query = "SELECT * FROM foo WHERE k=4 AND (c1,c2) IN ((1,'foo'),(2,?),?);";
794795 names = ImmutableList.of("c1", "c2");
795- values = ImmutableList.<List<?>>of(
796- ImmutableList.of(1, 2),
797- ImmutableList.of(bindMarker()));
796+ values = ImmutableList.of(
797+ ImmutableList.of(1, "foo"),
798+ ImmutableList.of(2, bindMarker()),
799+ bindMarker());
798800 select = select().all().from("foo").where(eq("k", 4)).and(in(names, values));
799801 assertEquals(select.toString(), query);
802+
803+ // special case, single element list with bind marker should be (?) instead of ((?))
804+ query = "SELECT * FROM foo WHERE k=4 AND (c1) IN (?);";
805+ names = ImmutableList.of("c1");
806+ values = ImmutableList.of(ImmutableList.of(bindMarker()));
807+ select = select().all().from("foo").where(eq("k", 4)).and(in(names, values));
808+ assertEquals(select.toString(), query);
809+ }
810+
811+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Too many values for IN clause, the maximum allowed is 65535")
812+ public void should_fail_if_compound_in_clause_has_too_many_values() {
813+ List<Object> values = Collections.<Object>nCopies(65536, "a");
814+ select().all().from("foo").where(eq("k", 4)).and(in(ImmutableList.of("name"), values));
815+ }
816+
817+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Missing values for IN clause")
818+ public void should_fail_if_compound_in_clause_given_null_values() {
819+ select().all().from("foo").where(eq("k", 4)).and(in(ImmutableList.of("name"), null));
820+ }
821+
822+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "The number of names \\(4\\) and values \\(3\\) don't match")
823+ public void should_fail_if_compound_in_clause_has_mismatch_of_names_and_values() {
824+ select().all().from("foo").where(eq("k", 4)).and(in(ImmutableList.of("a", "b", "c", "d"),
825+ ImmutableList.of(
826+ ImmutableList.of(1, 2, 3, 4), // Adequately sized (4)
827+ ImmutableList.of(1, 2, 3) // Inadequately sized (3)
828+ )));
829+ }
830+
831+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Wrong element type for values list, expected List or BindMarker, got java.lang.Integer")
832+ public void shoud_fail_if_compound_in_clause_has_value_pair_that_is_not_list_or_bind_marker() {
833+ select().all().from("foo").where(eq("k", 4)).and(in(ImmutableList.of("a", "b", "c", "d"),
834+ ImmutableList.of(1))); // Invalid value 1, must be list or bind marker.
835+ }
836+
837+ @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Missing values for IN clause")
838+ public void should_fail_if_in_clause_has_null_values() {
839+ select().all().from("foo").where(in("bar", (List<?>) null));
800840 }
801841
802842 @Test(groups = "unit", expectedExceptions = IllegalArgumentException.class)