Elffuss BraidHub

kikocis/java-driver public

Minor enhancements to CCM tests.

Highlights:
- Apply annotation-level configuration to CCM builders obtained via ccmProvider.
- Generic way to randomize ports in a CCMBridge.Builder instance.
- Generate CCM cluster names only when building CCMBridge instances.
- Improve algorithm to find available ports.
Changeset3b3b008455669d0ae88c2c138f41d4f943345133b1c424f1497d74e4575ac0e2
AuthorAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-02-03 11:35 +01:00
CommitterAndrew Tolbert <andrew.tolbert@datastax.com> · 2016-03-11 13:21 -06:00
Parents23c646c58e54

Browse the files at this changeset

6 files changed

modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +58 −35
@@ -31,6 +31,8 @@
3131 import java.net.InetSocketAddress;
3232 import java.util.*;
3333 import java.util.concurrent.TimeUnit;
34+import java.util.regex.Matcher;
35+import java.util.regex.Pattern;
3436
3537 import static com.datastax.driver.core.TestUtils.executeNoFail;
3638 import static com.datastax.driver.core.TestUtils.findAvailablePort;
@@ -659,22 +661,25 @@
659661 * use {@link #builder()} to get an instance
660662 */
661663 public static class Builder {
662- private final String clusterName = TestUtils.generateIdentifier("cluster_");
664+
665+ public static final String RANDOM_PORT = "__RANDOM_PORT__";
666+ private static final Pattern RANDOM_PORT_PATTERN = Pattern.compile(RANDOM_PORT);
667+
663668 int[] nodes = {1};
664669 private boolean start = true;
665670 private boolean isDSE = isDSE();
666671 private String version = getCassandraVersion();
667- private Set<String> createOptions = new HashSet<String>(getInstallArguments());
672+ private Set<String> createOptions = new LinkedHashSet<String>(getInstallArguments());
668673 private Set<String> jvmArgs = new LinkedHashSet<String>();
669- private final Map<String, Object> cassandraConfiguration = Maps.newHashMap();
670- private final Map<String, Object> dseConfiguration = Maps.newHashMap();
671- // -1 means random
672- private int thriftPort = -1;
673- private int binaryPort = -1;
674- private int storagePort = -1;
674+ private final Map<String, Object> cassandraConfiguration = Maps.newLinkedHashMap();
675+ private final Map<String, Object> dseConfiguration = Maps.newLinkedHashMap();
675676 private Map<Integer, Workload> workloads = new HashMap<Integer, Workload>();
676677
677678 private Builder() {
679+ cassandraConfiguration.put("start_rpc", false);
680+ cassandraConfiguration.put("storage_port", RANDOM_PORT);
681+ cassandraConfiguration.put("rpc_port", RANDOM_PORT);
682+ cassandraConfiguration.put("native_transport_port", RANDOM_PORT);
678683 }
679684
680685 /**
@@ -781,17 +786,17 @@
781786 }
782787
783788 public Builder withStoragePort(int port) {
784- storagePort = port;
789+ cassandraConfiguration.put("storage_port", port);
785790 return this;
786791 }
787792
788793 public Builder withThriftPort(int port) {
789- thriftPort = port;
794+ cassandraConfiguration.put("rpc_port", port);
790795 return this;
791796 }
792797
793798 public Builder withBinaryPort(int port) {
794- binaryPort = port;
799+ cassandraConfiguration.put("native_transport_port", port);
795800 return this;
796801 }
797802
@@ -809,10 +814,13 @@
809814
810815 public CCMBridge build() {
811816 // be careful NOT to alter internal state (hashCode/equals) during build!
812- int storagePort = this.storagePort == -1 ? findAvailablePort() : this.storagePort;
813- int thriftPort = this.thriftPort == -1 ? findAvailablePort() : this.thriftPort;
814- int binaryPort = this.binaryPort == -1 ? findAvailablePort() : this.binaryPort;
817+ String clusterName = TestUtils.generateIdentifier("ccm_");
818+ Map<String, Object> cassandraConfiguration = randomizePorts(this.cassandraConfiguration);
819+ Map<String, Object> dseConfiguration = randomizePorts(this.dseConfiguration);
815820 VersionNumber version = VersionNumber.parse(this.version);
821+ int storagePort = Integer.parseInt(cassandraConfiguration.get("storage_port").toString());
822+ int thriftPort = Integer.parseInt(cassandraConfiguration.get("rpc_port").toString());
823+ int binaryPort = Integer.parseInt(cassandraConfiguration.get("native_transport_port").toString());
816824 final CCMBridge ccm = new CCMBridge(clusterName, isDSE, version, storagePort, thriftPort, binaryPort, joinJvmArgs());
817825 Runtime.getRuntime().addShutdownHook(new Thread() {
818826 @Override
@@ -820,14 +828,9 @@
820828 ccm.close();
821829 }
822830 });
823- ccm.execute(buildCreateCommand());
831+ ccm.execute(buildCreateCommand(clusterName));
824832 updateNodeConf(ccm);
825- HashMap<String, Object> config = new HashMap<String, Object>(cassandraConfiguration);
826- config.put("start_rpc", false);
827- config.put("storage_port", storagePort);
828- config.put("rpc_port", thriftPort);
829- config.put("native_transport_port", binaryPort);
830- ccm.updateConfig(config);
833+ ccm.updateConfig(cassandraConfiguration);
831834 if (!dseConfiguration.isEmpty())
832835 ccm.updateDSEConfig(dseConfiguration);
833836 for (Map.Entry<Integer, Workload> entry : workloads.entrySet()) {
@@ -851,12 +854,12 @@
851854 StringBuilder allJvmArgs = new StringBuilder("");
852855 for (String jvmArg : jvmArgs) {
853856 allJvmArgs.append(" --jvm_arg=");
854- allJvmArgs.append(jvmArg);
857+ allJvmArgs.append(randomizePorts(jvmArg));
855858 }
856859 return allJvmArgs.toString();
857860 }
858861
859- private String buildCreateCommand() {
862+ private String buildCreateCommand(String clusterName) {
860863 StringBuilder result = new StringBuilder(CCM_COMMAND + " create");
861864 result.append(" ").append(clusterName);
862865 result.append(" -i ").append(TestUtils.IP_PREFIX);
@@ -870,7 +873,7 @@
870873 result.append(node);
871874 }
872875 }
873- result.append(" ").append(Joiner.on(" ").join(createOptions));
876+ result.append(" ").append(Joiner.on(" ").join(randomizePorts(createOptions)));
874877 return result.toString();
875878 }
876879
@@ -888,7 +891,7 @@
888891 for (int i = 0; i < nodesInDc; i++) {
889892 int jmxPort = findAvailablePort();
890893 int debugPort = findAvailablePort();
891- logger.trace("Node {} in cluster {} using JMX port {} and debug port {}", n, clusterName, jmxPort, debugPort);
894+ logger.trace("Node {} in cluster {} using JMX port {} and debug port {}", n, ccm.getClusterName(), jmxPort, debugPort);
892895 File nodeConf = new File(ccm.getNodeDir(n), "node.conf");
893896 File nodeConf2 = new File(ccm.getNodeDir(n), "node.conf.tmp");
894897 BufferedReader br = closer.register(new BufferedReader(new FileReader(nodeConf)));
@@ -923,6 +926,36 @@
923926 }
924927 }
925928
929+ private Set<String> randomizePorts(Set<String> set) {
930+ Set<String> randomized = new LinkedHashSet<String>();
931+ for (String value : set) {
932+ randomized.add(randomizePorts(value));
933+ }
934+ return randomized;
935+ }
936+
937+ private Map<String, Object> randomizePorts(Map<String, Object> map) {
938+ Map<String, Object> randomized = new HashMap<String, Object>();
939+ for (Map.Entry<String, Object> entry : map.entrySet()) {
940+ Object value = entry.getValue();
941+ if (value instanceof CharSequence) {
942+ value = randomizePorts((CharSequence) value);
943+ }
944+ randomized.put(entry.getKey(), value);
945+ }
946+ return randomized;
947+ }
948+
949+ private String randomizePorts(CharSequence str) {
950+ Matcher matcher = RANDOM_PORT_PATTERN.matcher(str);
951+ StringBuffer sb = new StringBuffer();
952+ while (matcher.find()) {
953+ matcher.appendReplacement(sb, Integer.toString(TestUtils.findAvailablePort()));
954+ }
955+ matcher.appendTail(sb);
956+ return sb.toString();
957+ }
958+
926959 @Override
927960 @SuppressWarnings("SimplifiableIfStatement")
928961 public boolean equals(Object o) {
@@ -932,9 +965,6 @@
932965 if (o == null || getClass() != o.getClass()) return false;
933966 Builder builder = (Builder) o;
934967 if (isDSE != builder.isDSE) return false;
935- if (thriftPort != builder.thriftPort) return false;
936- if (binaryPort != builder.binaryPort) return false;
937- if (storagePort != builder.storagePort) return false;
938968 if (!Arrays.equals(nodes, builder.nodes)) return false;
939969 if (!createOptions.equals(builder.createOptions)) return false;
940970 if (!jvmArgs.equals(builder.jvmArgs)) return false;
@@ -955,17 +985,10 @@
955985 result = 31 * result + cassandraConfiguration.hashCode();
956986 result = 31 * result + dseConfiguration.hashCode();
957987 result = 31 * result + workloads.hashCode();
958- result = 31 * result + thriftPort;
959- result = 31 * result + binaryPort;
960- result = 31 * result + storagePort;
961988 result = 31 * result + version.hashCode();
962989 return result;
963990 }
964991
965- @Override
966- public String toString() {
967- return String.format("%s (%s nodes)", clusterName, weight());
968- }
969992 }
970993
971994 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMCache.java +24 −5
@@ -22,6 +22,7 @@
2222
2323 import java.io.File;
2424 import java.net.InetSocketAddress;
25+import java.util.Iterator;
2526 import java.util.Map;
2627 import java.util.concurrent.ExecutionException;
2728 import java.util.concurrent.atomic.AtomicInteger;
@@ -247,20 +248,23 @@
247248 */
248249 private static final LoadingCache<CCMBridge.Builder, CachedCCMAccess> CACHE;
249250
251+ // The amount of memory one CCM node takes in MB.
252+ private static final int ONE_CCM_NODE_MB = 800;
253+
250254 static {
251255 long maximumWeight;
252256 String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes");
253257 if (numberOfNodes == null) {
254258 long freeMemoryMB = TestUtils.getFreeMemoryMB();
255- if (freeMemoryMB < 1000)
256- LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB);
259+ if (freeMemoryMB < ONE_CCM_NODE_MB)
260+ LOGGER.warn("Not enough available memory: {} MB, CCM clusters might fail to start", freeMemoryMB);
257261 // CCM nodes are started with -Xms500M -Xmx500M
258262 // and allocate up to 100MB non-heap memory in the general case,
259263 // to be conservative we treat 1 "slot" as 800Mb.
260264 // We leave 2 slots out to avoid starving system memory,
261265 // and we pick a value with a minimum of 1 slot and a maximum of 8 slots.
262266 // For example, an 8GB VM with ~6.5GB currently available heap will yield 6 slots ((6500/800) - 2 = 6).
263- long slotsAvailable = (freeMemoryMB / 800) - 2;
267+ long slotsAvailable = (freeMemoryMB / ONE_CCM_NODE_MB) - 2;
264268 maximumWeight = Math.min(8, Math.max(1, slotsAvailable));
265269 } else {
266270 maximumWeight = Integer.parseInt(numberOfNodes);
@@ -272,6 +276,7 @@
272276 .maximumWeight(maximumWeight)
273277 .weigher(new CCMAccessWeigher())
274278 .removalListener(new CCMAccessRemovalListener())
279+ .recordStats()
275280 .build(new CCMAccessLoader());
276281 }
277282
@@ -304,8 +309,22 @@
304309 }
305310
306311 private static void logCache() {
307- if (LOGGER.isDebugEnabled())
308- LOGGER.debug("Free memory: {}, Cache {}", TestUtils.getFreeMemoryMB(), CACHE.asMap().keySet());
312+ if (LOGGER.isDebugEnabled()) {
313+ LOGGER.debug("Free memory: {} MB", TestUtils.getFreeMemoryMB());
314+ StringBuilder sb = new StringBuilder();
315+ Iterator<Map.Entry<CCMBridge.Builder, CachedCCMAccess>> iterator = CACHE.asMap().entrySet().iterator();
316+ while (iterator.hasNext()) {
317+ Map.Entry<CCMBridge.Builder, CachedCCMAccess> entry = iterator.next();
318+ sb.append(entry.getValue().getClusterName())
319+ .append(" (")
320+ .append(entry.getKey().weight())
321+ .append(")");
322+ if (iterator.hasNext())
323+ sb.append(", ");
324+ }
325+ LOGGER.debug("Cache contents: {{}}", sb.toString());
326+ LOGGER.debug("Cache stats: {}", CACHE.stats());
327+ }
309328 }
310329
311330 }
modified driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +26 −26
@@ -417,32 +417,32 @@
417417 ccmBuilder = ccmProvider(testInstance);
418418 if (ccmBuilder == null) {
419419 ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes()).notStarted();
420- if (version() != null)
421- ccmBuilder.withVersion(version());
422- if (dse())
423- ccmBuilder.withDSE();
424- if (ssl())
425- ccmBuilder.withSSL();
426- if (auth())
427- ccmBuilder.withAuth();
428- for (Map.Entry<String, Object> entry : config().entrySet()) {
429- ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue());
430- }
431- for (Map.Entry<String, Object> entry : dseConfig().entrySet()) {
432- ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue());
433- }
434- for (String option : startOptions()) {
435- ccmBuilder.withCreateOptions(option);
436- }
437- for (String arg : jvmArgs()) {
438- ccmBuilder.withJvmArgs(arg);
439- }
440- List<Workload> workloads = workloads();
441- for (int i = 0; i < workloads.size(); i++) {
442- Workload workload = workloads.get(i);
443- if (workload != null)
444- ccmBuilder.withWorkload(i + 1, workload);
445- }
420+ }
421+ if (version() != null)
422+ ccmBuilder.withVersion(version());
423+ if (dse())
424+ ccmBuilder.withDSE();
425+ if (ssl())
426+ ccmBuilder.withSSL();
427+ if (auth())
428+ ccmBuilder.withAuth();
429+ for (Map.Entry<String, Object> entry : config().entrySet()) {
430+ ccmBuilder.withCassandraConfiguration(entry.getKey(), entry.getValue());
431+ }
432+ for (Map.Entry<String, Object> entry : dseConfig().entrySet()) {
433+ ccmBuilder.withDSEConfiguration(entry.getKey(), entry.getValue());
434+ }
435+ for (String option : startOptions()) {
436+ ccmBuilder.withCreateOptions(option);
437+ }
438+ for (String arg : jvmArgs()) {
439+ ccmBuilder.withJvmArgs(arg);
440+ }
441+ List<Workload> workloads = workloads();
442+ for (int i = 0; i < workloads.size(); i++) {
443+ Workload workload = workloads.get(i);
444+ if (workload != null)
445+ ccmBuilder.withWorkload(i + 1, workload);
446446 }
447447 }
448448 return ccmBuilder;
modified driver-core/src/test/java/com/datastax/driver/core/ConsistencyTest.java +8 −9
@@ -49,10 +49,9 @@
4949 createKeyspace = false,
5050 config = {
5151 // tests fail often with write or read timeouts
52- "hinted_handoff_enabled:true",
5352 "phi_convict_threshold:5",
54- "read_request_timeout_in_ms:100000",
55- "write_request_timeout_in_ms:100000"
53+ "read_request_timeout_in_ms:200000",
54+ "write_request_timeout_in_ms:200000"
5655 }
5756 )
5857 public class ConsistencyTest extends AbstractPoliciesTest {
@@ -61,40 +60,40 @@
6160
6261 private Cluster.Builder tokenAwareRoundRobin() {
6362 return Cluster.builder()
64- .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
63+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000))
6564 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()));
6665 }
6766
6867 private Cluster.Builder tokenAwareRoundRobinNoShuffle() {
6968 return Cluster.builder()
70- .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
69+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000))
7170 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false));
7271 }
7372
7473 private Cluster.Builder tokenAwareRoundRobinDowngrading() {
7574 return Cluster.builder()
76- .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
75+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000))
7776 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
7877 .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
7978 }
8079
8180 private Cluster.Builder tokenAwareRoundRobinNoShuffleDowngrading() {
8281 return Cluster.builder()
83- .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
82+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000))
8483 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy(), false))
8584 .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
8685 }
8786
8887 private Cluster.Builder roundRobinDowngrading() {
8988 return Cluster.builder()
90- .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
89+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000))
9190 .withLoadBalancingPolicy(new RoundRobinPolicy())
9291 .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
9392 }
9493
9594 private Cluster.Builder tokenAwareDCAwareRoundRobinNoShuffleDowngrading() {
9695 return Cluster.builder()
97- .withSocketOptions(new SocketOptions().setReadTimeoutMillis(120000))
96+ .withSocketOptions(new SocketOptions().setReadTimeoutMillis(300000))
9897 .withLoadBalancingPolicy(new TokenAwarePolicy(DCAwareRoundRobinPolicy.builder().withLocalDc("dc2").build(), false))
9998 .withRetryPolicy(DowngradingConsistencyRetryPolicy.INSTANCE);
10099 }
modified driver-core/src/test/java/com/datastax/driver/core/MissingRpcAddressTest.java +2 −2
@@ -20,7 +20,6 @@
2020 import com.google.common.collect.Lists;
2121 import org.testng.annotations.Test;
2222
23-import java.net.InetAddress;
2423 import java.net.InetSocketAddress;
2524
2625 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
@@ -64,9 +63,10 @@
6463 .build());
6564 Session session = cluster.connect();
6665 String deleteStmt = String.format("DELETE rpc_address FROM system.peers WHERE peer = '%s'",
67- InetAddress.getByName(TestUtils.IP_PREFIX + "2").getHostName());
66+ ccm().addressOfNode(2).getHostName());
6867 session.execute(deleteStmt);
6968 session.close();
69+ cluster.close();
7070 }
7171
7272 }
modified driver-core/src/test/java/com/datastax/driver/core/TestUtils.java +17 −35
@@ -18,6 +18,7 @@
1818 import com.datastax.driver.core.policies.RoundRobinPolicy;
1919 import com.datastax.driver.core.policies.WhiteListPolicy;
2020 import com.google.common.base.Predicate;
21+import com.google.common.base.Throwables;
2122 import com.google.common.util.concurrent.Futures;
2223 import com.google.common.util.concurrent.Uninterruptibles;
2324 import com.sun.management.OperatingSystemMXBean;
@@ -39,7 +40,6 @@
3940 import java.util.*;
4041 import java.util.concurrent.*;
4142 import java.util.concurrent.atomic.AtomicInteger;
42-import java.util.concurrent.locks.ReentrantLock;
4343
4444 import static com.datastax.driver.core.ConditionChecker.check;
4545 import static java.util.concurrent.TimeUnit.MINUTES;
@@ -489,47 +489,29 @@
489489 return prefix + seq.incrementAndGet();
490490 }
491491
492- // use ports in the ephemeral range
493- private static int nextPort = 50000;
494-
495- private static final ReentrantLock PORT_LOCK = new ReentrantLock();
496-
497492 /**
498- * Find an available port in the ephemeral range.
493+ * Finds an available port in the ephemeral range.
494+ * This is loosely inspired by Apache MINA's AvailablePortFinder.
499495 *
500496 * @return A local port that is currently unused.
501497 */
502- public static int findAvailablePort() {
503- PORT_LOCK.lock();
498+ public synchronized static int findAvailablePort() throws RuntimeException {
499+ ServerSocket ss = null;
504500 try {
505- for (int i = 0; i < 3; i++) {
506- int port = nextPort;
507- ServerSocket s = null;
508- for (int j = 0; j < 100; j++) {
509- try {
510- s = new ServerSocket(port);
511- s.close();
512- nextPort = port + 1;
513- return port;
514- } catch (IOException e) {
515- // ok
516- } finally {
517- port++;
518- if (s != null) {
519- try {
520- s.close();
521- } catch (IOException e) {
522- // ok
523- }
524- }
525- }
501+ // let the system pick an ephemeral port
502+ ss = new ServerSocket(0);
503+ ss.setReuseAddress(true);
504+ return ss.getLocalPort();
505+ } catch (IOException e) {
506+ throw Throwables.propagate(e);
507+ } finally {
508+ if (ss != null) {
509+ try {
510+ ss.close();
511+ } catch (IOException e) {
512+ Throwables.propagate(e);
526513 }
527- logger.warn("Could not acquire an available port after 100 attempts, sleeping for 1 minute");
528- Uninterruptibles.sleepUninterruptibly(1, TimeUnit.MINUTES);
529514 }
530- throw new RuntimeException(String.format("Could not acquire an available port within range: %s-%s", nextPort, nextPort + 100));
531- } finally {
532- PORT_LOCK.unlock();
533515 }
534516 }
535517