Elffuss BraidHub

kikocis/java-driver public

Fix algorithm for weighing cached CCM instances.
Changesetc5a41f8457e01fc98cddfcf6234912619adc858b68206726785a2058b1717161
AuthorAndrew Tolbert <andrew.tolbert@datastax.com> · 2016-01-16 14:52 -06:00
CommitterAlexandre Dutra <alexandre.dutra@datastax.com> · 2016-01-17 23:20 +01:00
Parents446aa287b841

Browse the files at this changeset

10 files changed

modified driver-core/src/test/java/com/datastax/driver/core/CCMBridge.java +38 −11
@@ -211,6 +211,8 @@
211211
212212 private boolean keepLogs = false;
213213
214+ private boolean started = false;
215+
214216 private boolean closed = false;
215217
216218 private CCMBridge(String clusterName, boolean isDSE, VersionNumber version, int storagePort, int thriftPort, int binaryPort, String jvmArgs) {
@@ -344,7 +346,7 @@
344346 public synchronized void close() {
345347 if (closed)
346348 return;
347- logger.debug("Closing: " + this);
349+ logger.debug("Closing: {}", this);
348350 if (keepLogs) {
349351 executeNoFail(new Runnable() {
350352 @Override
@@ -368,21 +370,31 @@
368370 }, false);
369371 }
370372 closed = true;
371- logger.debug("Closed: " + this);
373+ logger.debug("Closed: {}", this);
372374 }
373375
374376 @Override
375- public void start() {
376- logger.debug("Starting: " + this);
377+ public synchronized void start() {
378+ if (started)
379+ return;
380+ if (logger.isDebugEnabled())
381+ logger.debug("Starting: {} - free memory: {}", this, TestUtils.getFreeMemoryMB());
377382 execute(CCM_COMMAND + " start --wait-other-notice --wait-for-binary-proto" + jvmArgs);
383+ if (logger.isDebugEnabled())
384+ logger.debug("Started: {} - Free memory: {}", this, TestUtils.getFreeMemoryMB());
385+ started = true;
378386 }
379387
380388 @Override
381389 public synchronized void stop() {
382390 if (closed)
383391 return;
384- logger.debug("Stopping: " + this);
392+ if (logger.isDebugEnabled())
393+ logger.debug("Stopping: {} - free memory: {}", this, TestUtils.getFreeMemoryMB());
385394 execute(CCM_COMMAND + " stop");
395+ System.gc();
396+ if (logger.isDebugEnabled())
397+ logger.debug("Stopped: {} - free memory: {}", this, TestUtils.getFreeMemoryMB());
386398 closed = true;
387399 }
388400
@@ -390,7 +402,7 @@
390402 public synchronized void forceStop() {
391403 if (closed)
392404 return;
393- logger.debug("Force stopping: " + this);
405+ logger.debug("Force stopping: {}", this);
394406 execute(CCM_COMMAND + " stop --not-gently");
395407 closed = true;
396408 }
@@ -416,7 +428,7 @@
416428 @Override
417429 public synchronized void remove() {
418430 stop();
419- logger.debug("Removing: " + this);
431+ logger.debug("Removing: {}", this);
420432 execute(CCM_COMMAND + " remove");
421433 }
422434
@@ -601,6 +613,7 @@
601613
602614 @Override
603615 protected void finalize() throws Throwable {
616+ logger.debug("GC'ing {}", this);
604617 close();
605618 super.finalize();
606619 }
@@ -679,9 +692,7 @@
679692 }
680693
681694 /**
682- * The Cassandra or DSE version to use.
683- *
684- * Defaults to {@link #getCassandraVersion()}.
695+ * The Cassandra or DSE version to use (defaults to {@link #getCassandraVersion()} if this is never called).
685696 */
686697 public Builder withVersion(String version) {
687698 Iterator<String> it = createOptions.iterator();
@@ -698,7 +709,8 @@
698709 }
699710
700711 /**
701- * Free-form options that will be added at the end of the {@code ccm create} command.
712+ * Free-form options that will be added at the end of the {@code ccm create} command
713+ * (defaults to {@link #getInstallArguments()} if this is never called).
702714 */
703715 public Builder withCreateOptions(String... createOptions) {
704716 Collections.addAll(this.createOptions, createOptions);
@@ -762,6 +774,7 @@
762774 ccm.execute(buildCreateCommand());
763775 updateNodeConf(ccm);
764776 HashMap<String, Object> config = new HashMap<String, Object>(cassandraConfiguration);
777+ config.put("start_rpc", false);
765778 config.put("storage_port", storagePort);
766779 config.put("rpc_port", thriftPort);
767780 config.put("native_transport_port", binaryPort);
@@ -773,6 +786,15 @@
773786 return ccm;
774787 }
775788
789+ public int weight() {
790+ // the weight is simply function of the number of nodes
791+ int totalNodes = 0;
792+ for (int nodesPerDc : this.nodes) {
793+ totalNodes += nodesPerDc;
794+ }
795+ return totalNodes;
796+ }
797+
776798 private String joinJvmArgs() {
777799 StringBuilder allJvmArgs = new StringBuilder("");
778800 for (String jvmArg : jvmArgs) {
@@ -885,6 +907,11 @@
885907 result = 31 * result + version.hashCode();
886908 return result;
887909 }
910+
911+ @Override
912+ public String toString() {
913+ return String.format("%s (weight %s)", clusterName, weight());
914+ }
888915 }
889916
890917 }
added driver-core/src/test/java/com/datastax/driver/core/CCMCache.java +306 −0
@@ -0,0 +1,306 @@
1+/*
2+ * Copyright (C) 2012-2015 DataStax Inc.
3+ *
4+ * Licensed under the Apache License, Version 2.0 (the "License");
5+ * you may not use this file except in compliance with the License.
6+ * You may obtain a copy of the License at
7+ *
8+ * http://www.apache.org/licenses/LICENSE-2.0
9+ *
10+ * Unless required by applicable law or agreed to in writing, software
11+ * distributed under the License is distributed on an "AS IS" BASIS,
12+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+ * See the License for the specific language governing permissions and
14+ * limitations under the License.
15+ */
16+package com.datastax.driver.core;
17+
18+import com.google.common.base.Throwables;
19+import com.google.common.cache.*;
20+import org.slf4j.Logger;
21+import org.slf4j.LoggerFactory;
22+
23+import java.io.File;
24+import java.net.InetSocketAddress;
25+import java.util.Map;
26+import java.util.concurrent.ExecutionException;
27+import java.util.concurrent.atomic.AtomicInteger;
28+
29+public class CCMCache {
30+
31+ private static final Logger LOGGER = LoggerFactory.getLogger(CCMCache.class);
32+
33+ private static class CachedCCMAccess implements CCMAccess {
34+
35+ private final CCMAccess ccm;
36+
37+ private final AtomicInteger refCount = new AtomicInteger(1);
38+
39+ private volatile boolean evicted = false;
40+
41+ private CachedCCMAccess(CCMAccess ccm) {
42+ this.ccm = ccm;
43+ }
44+
45+ @Override
46+ public String getClusterName() {
47+ return ccm.getClusterName();
48+ }
49+
50+ @Override
51+ public VersionNumber getVersion() {
52+ return ccm.getVersion();
53+ }
54+
55+ @Override
56+ public File getCcmDir() {
57+ return ccm.getCcmDir();
58+ }
59+
60+ @Override
61+ public File getClusterDir() {
62+ return ccm.getClusterDir();
63+ }
64+
65+ @Override
66+ public File getNodeDir(int n) {
67+ return ccm.getNodeDir(n);
68+ }
69+
70+ @Override
71+ public File getNodeConfDir(int n) {
72+ return ccm.getNodeConfDir(n);
73+ }
74+
75+ @Override
76+ public int getStoragePort() {
77+ return ccm.getStoragePort();
78+ }
79+
80+ @Override
81+ public int getThriftPort() {
82+ return ccm.getThriftPort();
83+ }
84+
85+ @Override
86+ public int getBinaryPort() {
87+ return ccm.getBinaryPort();
88+ }
89+
90+ @Override
91+ public void setKeepLogs(boolean keepLogs) {
92+ ccm.setKeepLogs(keepLogs);
93+ }
94+
95+ @Override
96+ public InetSocketAddress addressOfNode(int n) {
97+ return ccm.addressOfNode(n);
98+ }
99+
100+ @Override
101+ public void start() {
102+ ccm.start();
103+ }
104+
105+ @Override
106+ public void stop() {
107+ ccm.stop();
108+ }
109+
110+ @Override
111+ public void forceStop() {
112+ ccm.forceStop();
113+ }
114+
115+ @Override
116+ public void close() {
117+ refCount.decrementAndGet();
118+ maybeClose();
119+ }
120+
121+ private void maybeClose() {
122+ if (refCount.get() <= 0 && evicted) {
123+ ccm.close();
124+ }
125+ }
126+
127+ @Override
128+ public void remove() {
129+ ccm.remove();
130+ }
131+
132+ @Override
133+ public void updateConfig(Map<String, Object> configs) {
134+ ccm.updateConfig(configs);
135+ }
136+
137+ @Override
138+ public void updateDSEConfig(Map<String, Object> configs) {
139+ ccm.updateDSEConfig(configs);
140+ }
141+
142+ @Override
143+ public void start(int n) {
144+ ccm.start(n);
145+ }
146+
147+ @Override
148+ public void stop(int n) {
149+ ccm.stop(n);
150+ }
151+
152+ @Override
153+ public void forceStop(int n) {
154+ ccm.forceStop(n);
155+ }
156+
157+ @Override
158+ public void remove(int n) {
159+ ccm.remove(n);
160+ }
161+
162+ @Override
163+ public void add(int n) {
164+ ccm.add(n);
165+ }
166+
167+ @Override
168+ public void add(int dc, int n) {
169+ ccm.add(dc, n);
170+ }
171+
172+ @Override
173+ public void decommision(int n) {
174+ ccm.decommision(n);
175+ }
176+
177+ @Override
178+ public void updateNodeConfig(int n, String key, Object value) {
179+ ccm.updateNodeConfig(n, key, value);
180+ }
181+
182+ @Override
183+ public void updateNodeConfig(int n, Map<String, Object> configs) {
184+ ccm.updateNodeConfig(n, configs);
185+ }
186+
187+ @Override
188+ public void setWorkload(int n, String workload) {
189+ ccm.setWorkload(n, workload);
190+ }
191+
192+ @Override
193+ public void waitForUp(int node) {
194+ ccm.waitForUp(node);
195+ }
196+
197+ @Override
198+ public void waitForDown(int node) {
199+ ccm.waitForDown(node);
200+ }
201+
202+ @Override
203+ public String toString() {
204+ return ccm.toString();
205+ }
206+ }
207+
208+ private static class CCMAccessLoader extends CacheLoader<CCMBridge.Builder, CachedCCMAccess> {
209+
210+ @Override
211+ public CachedCCMAccess load(CCMBridge.Builder key) {
212+ return new CachedCCMAccess(key.build());
213+ }
214+
215+ }
216+
217+ private static class CCMAccessWeigher implements Weigher<CCMBridge.Builder, CachedCCMAccess> {
218+
219+ @Override
220+ public int weigh(CCMBridge.Builder key, CachedCCMAccess value) {
221+ return key.weight();
222+ }
223+
224+ }
225+
226+ private static class CCMAccessRemovalListener implements RemovalListener<CCMBridge.Builder, CachedCCMAccess> {
227+
228+ @Override
229+ public void onRemoval(RemovalNotification<CCMBridge.Builder, CachedCCMAccess> notification) {
230+ CachedCCMAccess cached = notification.getValue();
231+ if (cached != null && cached.ccm != null) {
232+ LOGGER.debug("Evicting: {} because of {}", cached.ccm, notification.getCause());
233+ cached.evicted = true;
234+ cached.maybeClose();
235+ }
236+ }
237+
238+ }
239+
240+ /**
241+ * A LoadingCache that stores running CCM clusters.
242+ */
243+ private static final LoadingCache<CCMBridge.Builder, CachedCCMAccess> CACHE;
244+
245+ static {
246+ long maximumWeight;
247+ String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes");
248+ if (numberOfNodes == null) {
249+ long freeMemoryMB = TestUtils.getFreeMemoryMB();
250+ if (freeMemoryMB < 1000)
251+ LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB);
252+ // CCM nodes are started with -Xms500M -Xmx500M
253+ // and allocate up to 100MB non-heap memory in the general case,
254+ // to be conservative we treat 1 "slot" as 800Mb.
255+ // We leave 2 slots out to avoid starving system memory,
256+ // and we pick a value with a minimum of 1 slot and a maximum of 8 slots.
257+ // For example, an 8GB VM with ~6.5GB currently available heap will yield 6 slots ((6500/800) - 2 = 6).
258+ long slotsAvailable = (freeMemoryMB / 800) - 2;
259+ maximumWeight = Math.min(8, Math.max(1, slotsAvailable));
260+ } else {
261+ maximumWeight = Integer.parseInt(numberOfNodes);
262+ }
263+ LOGGER.info("Maximum number of running CCM nodes: {}", maximumWeight);
264+ CACHE = CacheBuilder.newBuilder()
265+ .initialCapacity(3)
266+ .softValues()
267+ .maximumWeight(maximumWeight)
268+ .weigher(new CCMAccessWeigher())
269+ .removalListener(new CCMAccessRemovalListener())
270+ .build(new CCMAccessLoader());
271+ }
272+
273+ /**
274+ * Creates or recycles a {@link CCMAccess} instance and returns it.
275+ * <p/>
276+ * Caller MUST call {@link CCMAccess#close()} when done with the cluster,
277+ * to ensure that resources will be properly freed.
278+ */
279+ public static CCMAccess get(CCMBridge.Builder key) {
280+ CachedCCMAccess ccm = CACHE.getIfPresent(key);
281+ if (ccm != null) {
282+ ccm.refCount.incrementAndGet();
283+ } else {
284+ try {
285+ ccm = CACHE.get(key);
286+ } catch (ExecutionException e) {
287+ throw Throwables.propagate(e);
288+ }
289+ }
290+ logCache();
291+ return ccm;
292+ }
293+
294+ /**
295+ * Removes the given key from the cache.
296+ */
297+ public static void remove(CCMBridge.Builder key) {
298+ CACHE.invalidate(key);
299+ }
300+
301+ private static void logCache() {
302+ if (LOGGER.isDebugEnabled())
303+ LOGGER.debug("Free memory: {}, Cache {}", TestUtils.getFreeMemoryMB(), CACHE.asMap().keySet());
304+ }
305+
306+}
modified driver-core/src/test/java/com/datastax/driver/core/CCMTestsSupport.java +45 −181
@@ -17,11 +17,9 @@
1717
1818 import com.datastax.driver.core.CreateCCM.TestMode;
1919 import com.google.common.base.Throwables;
20-import com.google.common.cache.*;
20+import com.google.common.collect.ImmutableMap;
2121 import com.google.common.collect.Lists;
2222 import com.google.common.io.Closer;
23-import com.google.common.util.concurrent.MoreExecutors;
24-import com.google.common.util.concurrent.ThreadFactoryBuilder;
2523 import org.slf4j.Logger;
2624 import org.slf4j.LoggerFactory;
2725 import org.testng.ITestResult;
@@ -37,12 +35,13 @@
3735 import java.lang.reflect.ParameterizedType;
3836 import java.net.InetSocketAddress;
3937 import java.util.*;
40-import java.util.concurrent.*;
38+import java.util.concurrent.Callable;
4139 import java.util.concurrent.atomic.AtomicInteger;
4240
4341 import static com.datastax.driver.core.CreateCCM.TestMode.PER_CLASS;
4442 import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
4543 import static com.datastax.driver.core.TestUtils.*;
44+import static org.assertj.core.api.Assertions.fail;
4645
4746 @SuppressWarnings("unused")
4847 public class CCMTestsSupport {
@@ -53,6 +52,13 @@
5352
5453 private static final List<String> TEST_GROUPS = Lists.newArrayList("isolated", "short", "long", "stress", "duration");
5554
55+ // A mapping of cassandra.yaml config options to their version requirements.
56+ // If a config is passed containing one of these options and the version requirement cannot be met
57+ // the option is simply filtered.
58+ private static final Map<String, VersionNumber> configVersionRequirements = ImmutableMap.<String, VersionNumber>builder()
59+ .put("enable_user_defined_functions", VersionNumber.parse("2.2.0"))
60+ .build();
61+
5662
5763 private static class ReadOnlyCCMBridge implements CCMAccess {
5864
@@ -211,6 +217,11 @@
211217 public void waitForDown(int node) {
212218 throw new UnsupportedOperationException("This CCM cluster is read-only");
213219 }
220+
221+ @Override
222+ public String toString() {
223+ return delegate.toString();
224+ }
214225 }
215226
216227 private static class CCMTestConfig {
@@ -270,7 +281,6 @@
270281 @SuppressWarnings("SimplifiableIfStatement")
271282 private Map<String, Object> config() {
272283 Map<String, Object> config = new HashMap<String, Object>();
273- config.put("start_rpc", false);
274284 for (int i = annotations.size() - 1; i == 0; i--) {
275285 CCMConfig ann = annotations.get(i);
276286 addConfigOptions(ann.config(), config);
@@ -289,10 +299,25 @@
289299 }
290300
291301 private void addConfigOptions(String[] conf, Map<String, Object> config) {
302+ String versionStr = version();
303+ VersionNumber version = VersionNumber.parse(versionStr != null ?
304+ versionStr : CCMBridge.getCassandraVersion());
292305 for (String aConf : conf) {
293306 String[] tokens = aConf.split(":");
307+ if (tokens.length != 2)
308+ fail("Wrong configuration option: " + aConf);
294309 String key = tokens[0];
295310 String value = tokens[1];
311+ // If we've detected a property with a version requirement, skip it if the version requirement
312+ // cannot be met.
313+ if (configVersionRequirements.containsKey(key)) {
314+ VersionNumber requirement = configVersionRequirements.get(key);
315+ if (version.compareTo(requirement) < 0) {
316+ LOGGER.debug("Skipping inclusion of '{}' in cassandra.yaml since it requires >= C* {} and {} " +
317+ "was detected.", aConf, requirement, version);
318+ continue;
319+ }
320+ }
296321 config.put(key, value);
297322 }
298323 }
@@ -364,7 +389,7 @@
364389
365390 private CCMBridge.Builder ccmBuilder() {
366391 if (ccmBuilder == null) {
367- ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes());
392+ ccmBuilder = CCMBridge.builder().withNodes(numberOfNodes()).notStarted();
368393 if (version() != null)
369394 ccmBuilder.withVersion(version());
370395 if (dse())
@@ -444,159 +469,12 @@
444469 }
445470 }
446471
447- private int weight() {
448- int weight = 0;
449- weight += totalNodes() - 1;
450- weight += config().size() - 1;
451- weight += dseConfig().size();
452- weight += dse() ? 1 : 0;
453- weight += jvmArgs().size();
454- weight += startOptions().size();
455- weight += ssl() ? 1 : 0;
456- weight += auth() ? 1 : 0;
457- weight += version() != null ? 1 : 0;
458- return weight;
459- }
460-
461- private int totalNodes() {
462- int nodes = 0;
463- for (int nodesPerDc : numberOfNodes()) {
464- nodes += nodesPerDc;
465- }
466- return nodes;
467- }
468- }
469-
470- private static class CCMTestContextKey {
471-
472- private final CCMBridge.Builder builder;
473-
474- private final int weight;
475-
476- private CCMTestContextKey(CCMBridge.Builder builder, int weight) {
477- this.builder = builder;
478- this.weight = weight;
479- }
480-
481- @Override
482- public boolean equals(Object o) {
483- if (this == o) return true;
484- if (o == null || getClass() != o.getClass()) return false;
485- CCMTestContextKey that = (CCMTestContextKey) o;
486- return builder.equals(that.builder);
487- }
488-
489- @Override
490- public int hashCode() {
491- return builder.hashCode();
492- }
493- }
494-
495- private static class CCMTestContext implements Runnable {
496-
497- private CCMAccess ccm;
498-
499- private final AtomicInteger refCount = new AtomicInteger(1);
500-
501- private volatile boolean evicted = false;
502-
503- private CCMTestContext(CCMAccess ccm) {
504- this(ccm, false);
505- }
506-
507- public CCMTestContext(CCMAccess ccm, boolean evicted) {
508- this.ccm = ccm;
509- this.evicted = evicted;
510- }
511-
512- @Override
513- public void run() {
514- if (ccm != null)
515- ccm.close();
516- ccm = null;
517- }
518-
519- private void markEvicted() {
520- evicted = true;
521- }
522-
523- private void maybeClose() {
524- if (refCount.get() <= 0 && evicted)
525- POOL.execute(this);
526- }
527- }
528-
529- private static class CCMTestContextLoader extends CacheLoader<CCMTestContextKey, CCMTestContext> {
530-
531- @Override
532- public CCMTestContext load(CCMTestContextKey key) {
533- return new CCMTestContext(key.builder.build());
534- }
535-
536- }
537-
538- private static class CCMTestContextWeigher implements Weigher<CCMTestContextKey, CCMTestContext> {
539-
540- @Override
541- public int weigh(CCMTestContextKey key, CCMTestContext value) {
542- return key.weight;
543- }
544-
545- }
546-
547- private static class CCMTestContextRemovalListener implements RemovalListener<CCMTestContextKey, CCMTestContext> {
548-
549- @Override
550- public void onRemoval(RemovalNotification<CCMTestContextKey, CCMTestContext> notification) {
551- CCMTestContext context = notification.getValue();
552- if (context != null && context.ccm != null) {
553- LOGGER.debug("Evicting: {} because of {}", context.ccm, notification.getCause());
554- context.markEvicted();
555- context.maybeClose();
556- }
557- }
558-
559- }
560-
561- /**
562- * A LoadingCache that stores running CCM clusters.
563- */
564- private static final LoadingCache<CCMTestContextKey, CCMTestContext> CACHE;
565-
566- private static final ExecutorService POOL = MoreExecutors.getExitingExecutorService(
567- (ThreadPoolExecutor) Executors.newFixedThreadPool(2,
568- new ThreadFactoryBuilder().setNameFormat("ccm-removal-%d").build()));
569-
570- static {
571- long maximumWeight;
572- String numberOfNodes = System.getProperty("ccm.maxNumberOfNodes");
573- if (numberOfNodes == null) {
574- long freeMemoryMB = TestUtils.getFreeMemoryMB();
575- if (freeMemoryMB < 1000)
576- LOGGER.warn("Available memory below 1GB: {}MB, CCM clusters might fail to start", freeMemoryMB);
577- // CCM nodes are started with -Xms500M -Xmx500M
578- // so 1 "slot" is roughly 500MB
579- // leave at least 2 slots out, with a minimum of 1 slot and a maximum of 6 slots
580- long slotsAvailable = (freeMemoryMB / 500) - 2;
581- maximumWeight = Math.min(6, Math.max(1, slotsAvailable));
582- } else {
583- maximumWeight = Integer.parseInt(numberOfNodes);
584- }
585- LOGGER.info("Maximum number of running CCM nodes: {}", maximumWeight);
586- CACHE = CacheBuilder.newBuilder()
587- .initialCapacity(3)
588- .maximumWeight(maximumWeight)
589- .weigher(new CCMTestContextWeigher())
590- .removalListener(new CCMTestContextRemovalListener())
591- .build(new CCMTestContextLoader());
592472 }
593473
594474 private TestMode testMode;
595475
596476 private CCMTestConfig ccmTestConfig;
597477
598- private CCMTestContext ccmTestContext;
599-
600478 protected CCMAccess ccm;
601479
602480 protected Cluster cluster;
@@ -688,6 +566,7 @@
688566 closeTestContext();
689567 }
690568 }
569+
691570 /**
692571 * Hook executed after each test class.
693572 */
@@ -805,34 +684,15 @@
805684 ccmTestConfig = createCCMTestConfig(testInstance, testMethod);
806685 assert ccmTestConfig != null;
807686 if (ccmTestConfig.createCcm()) {
687+ CCMAccess ccm = CCMCache.get(ccmTestConfig.ccmBuilder());
688+ assert ccm != null;
808689 if (ccmTestConfig.dirtiesContext()) {
809- ccm = ccmTestConfig.ccmBuilder().build();
810- ccmTestContext = new CCMTestContext(ccm, true);
811- LOGGER.debug("Using dedicated {}", ccm);
690+ this.ccm = ccm;
812691 } else {
813- CCMBridge.Builder builder = ccmTestConfig.ccmBuilder();
814- int weight = ccmTestConfig.weight();
815- CCMTestContextKey key = new CCMTestContextKey(builder, weight);
816- CCMAccess ccm;
817- ccmTestContext = CACHE.getIfPresent(key);
818- if (ccmTestContext != null) {
819- ccmTestContext.refCount.incrementAndGet();
820- ccm = ccmTestContext.ccm;
821- LOGGER.debug("Reusing {}", ccm);
822- } else {
823- try {
824- ccmTestContext = CACHE.get(key);
825- ccm = ccmTestContext.ccm;
826- LOGGER.debug("Using newly-created {}", ccm);
827- } catch (ExecutionException e) {
828- throw Throwables.propagate(e);
829- }
830- }
831692 this.ccm = new ReadOnlyCCMBridge(ccm);
832693 }
833- assert ccmTestContext != null;
834- assert ccm != null;
835-
694+ ccm.start();
695+ LOGGER.debug("Using {}", ccm);
836696 }
837697 }
838698
@@ -883,12 +743,16 @@
883743 }
884744
885745 private void closeTestContext() {
886- if (ccmTestContext != null) {
887- ccmTestContext.refCount.decrementAndGet();
888- ccmTestContext.maybeClose();
746+ if (ccmTestConfig != null && ccm != null) {
747+ CCMBridge.Builder key = ccmTestConfig.ccmBuilder();
748+ if (ccmTestConfig.dirtiesContext()) {
749+ CCMCache.remove(key);
750+ ccm.close();
751+ } else {
752+ ((ReadOnlyCCMBridge) ccm).delegate.close();
753+ }
889754 }
890755 ccmTestConfig = null;
891- ccmTestContext = null;
892756 ccm = null;
893757 }
894758
modified driver-core/src/test/java/com/datastax/driver/core/ClusterStressTest.java +16 −9
@@ -70,6 +70,9 @@
7070 fail("executor ran for longer than expected");
7171 } catch (InterruptedException e) {
7272 fail("Interrupted while waiting for executor to shutdown");
73+ } finally {
74+ executorService = null;
75+ System.gc();
7376 }
7477 }
7578
@@ -164,7 +167,7 @@
164167
165168 private class CreateClusterAndCheckConnections implements Callable<CreateClusterAndCheckConnections> {
166169 private final CountDownLatch startSignal;
167- private final Cluster cluster;
170+ private Cluster cluster;
168171 private final SocketChannelMonitor channelMonitor = new SocketChannelMonitor();
169172
170173 CreateClusterAndCheckConnections(CountDownLatch startSignal) {
@@ -202,6 +205,7 @@
202205 // If an assertion fails, close the cluster now, because it's the last time we
203206 // have a reference to it.
204207 cluster.close();
208+ cluster = null;
205209 throw e;
206210 } finally {
207211 channelMonitor.stop();
@@ -210,8 +214,8 @@
210214 }
211215
212216 private class CloseCluster implements Callable<Void> {
213- private final Cluster cluster;
214- private final SocketChannelMonitor channelMonitor;
217+ private Cluster cluster;
218+ private SocketChannelMonitor channelMonitor;
215219 private final CountDownLatch startSignal;
216220
217221 CloseCluster(Cluster cluster, SocketChannelMonitor channelMonitor, CountDownLatch startSignal) {
@@ -223,12 +227,15 @@
223227 @Override
224228 public Void call() throws Exception {
225229 startSignal.await();
226-
227- cluster.close();
228- assertEquals(cluster.manager.sessions.size(), 0);
229- assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
230- channelMonitor.stop();
231-
230+ try {
231+ cluster.close();
232+ assertEquals(cluster.manager.sessions.size(), 0);
233+ assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
234+ } finally {
235+ channelMonitor.stop();
236+ cluster = null;
237+ channelMonitor = null;
238+ }
232239 return null;
233240 }
234241 }
modified driver-core/src/test/java/com/datastax/driver/core/NettyOptionsTest.java +58 −62
@@ -25,79 +25,75 @@
2525 import io.netty.util.Timer;
2626 import org.mockito.invocation.InvocationOnMock;
2727 import org.mockito.stubbing.Answer;
28-import org.testng.annotations.DataProvider;
2928 import org.testng.annotations.Test;
3029
3130 import java.util.concurrent.ThreadFactory;
3231
32+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
3333 import static org.mockito.Answers.CALLS_REAL_METHODS;
3434 import static org.mockito.Matchers.any;
3535 import static org.mockito.Mockito.*;
3636
37-public class NettyOptionsTest {
37+@CreateCCM(PER_METHOD)
38+@CCMConfig(createCluster = false)
39+public class NettyOptionsTest extends CCMTestsSupport {
3840
39- @DataProvider(name = "NettyOptionsTest")
40- public static Object[][] parameters() {
41- Object[][] params = new Object[][]{{1, 1}, {3, 4}};
42- return params;
41+ @Test(groups = "short")
42+ public void should_invoke_netty_options_hooks_single_node() throws Exception {
43+ should_invoke_netty_options_hooks(1, 1);
4344 }
4445
45- @Test(groups = "long", dataProvider = "NettyOptionsTest")
46- public void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
47- //given
48- CCMBridge ccm = CCMBridge.builder().withNodes(hosts).build();
49- Cluster cluster = null;
50- try {
51- NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
52- EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
53- Timer timer = new HashedWheelTimer();
54- doReturn(eventLoopGroup).when(nettyOptions).eventLoopGroup(any(ThreadFactory.class));
55- doReturn(timer).when(nettyOptions).timer(any(ThreadFactory.class));
56- final ChannelHandler handler = mock(ChannelHandler.class);
57- doAnswer(new Answer() {
58- @Override
59- public Object answer(InvocationOnMock invocation) throws Throwable {
60- SocketChannel channel = (SocketChannel) invocation.getArguments()[0];
61- channel.pipeline().addLast("test-handler", handler);
62- return null;
63- }
64- }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
65- cluster = Cluster.builder()
66- .addContactPointsWithPorts(ccm.addressOfNode(1))
67- .withPort(ccm.getBinaryPort())
68- .withPoolingOptions(new PoolingOptions()
69- .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
70- )
71- .withNettyOptions(nettyOptions)
72- .build();
73- // when
74- cluster.connect();// force session creation to populate pools
75-
76- int expectedNumberOfCalls = TestUtils.numberOfLocalCoreConnections(cluster) * hosts + 1;
77- // If the driver supports a more recent protocol version than C*, the negotiation at startup
78- // will open 1 extra connection.
79- if (!ProtocolVersion.NEWEST_SUPPORTED.isSupportedBy(TestUtils.findHost(cluster, 1)))
80- expectedNumberOfCalls += 1;
81-
82- cluster.close();
83- // then
84- verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
85- verify(nettyOptions, times(1)).channelClass();
86- verify(nettyOptions, times(1)).timer(any(ThreadFactory.class));
87- // per-connection hooks will be called coreConnections * hosts + 1 times:
88- // the extra call is for the control connection
89- verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
90- verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
91- verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
92- verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
93- verify(nettyOptions, times(1)).onClusterClose(eventLoopGroup);
94- verify(nettyOptions, times(1)).onClusterClose(timer);
95- verifyNoMoreInteractions(nettyOptions);
96- } finally {
97- if (cluster != null)
98- cluster.close();
99- ccm.remove();
100- }
46+ @CCMConfig(numberOfNodes = 3)
47+ @Test(groups = "short")
48+ public void should_invoke_netty_options_hooks_multi_node() throws Exception {
49+ should_invoke_netty_options_hooks(3, 4);
10150 }
10251
52+ private void should_invoke_netty_options_hooks(int hosts, int coreConnections) throws Exception {
53+ NettyOptions nettyOptions = mock(NettyOptions.class, CALLS_REAL_METHODS.get());
54+ EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
55+ Timer timer = new HashedWheelTimer();
56+ doReturn(eventLoopGroup).when(nettyOptions).eventLoopGroup(any(ThreadFactory.class));
57+ doReturn(timer).when(nettyOptions).timer(any(ThreadFactory.class));
58+ final ChannelHandler handler = mock(ChannelHandler.class);
59+ doAnswer(new Answer() {
60+ @Override
61+ public Object answer(InvocationOnMock invocation) throws Throwable {
62+ SocketChannel channel = (SocketChannel) invocation.getArguments()[0];
63+ channel.pipeline().addLast("test-handler", handler);
64+ return null;
65+ }
66+ }).when(nettyOptions).afterChannelInitialized(any(SocketChannel.class));
67+ Cluster cluster = register(Cluster.builder()
68+ .addContactPointsWithPorts(ccm.addressOfNode(1))
69+ .withPort(ccm.getBinaryPort())
70+ .withPoolingOptions(new PoolingOptions()
71+ .setConnectionsPerHost(HostDistance.LOCAL, coreConnections, coreConnections)
72+ )
73+ .withNettyOptions(nettyOptions)
74+ .build());
75+ // when
76+ cluster.connect();// force session creation to populate pools
77+
78+ int expectedNumberOfCalls = TestUtils.numberOfLocalCoreConnections(cluster) * hosts + 1;
79+ // If the driver supports a more recent protocol version than C*, the negotiation at startup
80+ // will open 1 extra connection.
81+ if (!ProtocolVersion.NEWEST_SUPPORTED.isSupportedBy(TestUtils.findHost(cluster, 1)))
82+ expectedNumberOfCalls += 1;
83+
84+ cluster.close();
85+ // then
86+ verify(nettyOptions, times(1)).eventLoopGroup(any(ThreadFactory.class));
87+ verify(nettyOptions, times(1)).channelClass();
88+ verify(nettyOptions, times(1)).timer(any(ThreadFactory.class));
89+ // per-connection hooks will be called coreConnections * hosts + 1 times:
90+ // the extra call is for the control connection
91+ verify(nettyOptions, times(expectedNumberOfCalls)).afterBootstrapInitialized(any(Bootstrap.class));
92+ verify(nettyOptions, times(expectedNumberOfCalls)).afterChannelInitialized(any(SocketChannel.class));
93+ verify(handler, times(expectedNumberOfCalls)).handlerAdded(any(ChannelHandlerContext.class));
94+ verify(handler, times(expectedNumberOfCalls)).handlerRemoved(any(ChannelHandlerContext.class));
95+ verify(nettyOptions, times(1)).onClusterClose(eventLoopGroup);
96+ verify(nettyOptions, times(1)).onClusterClose(timer);
97+ verifyNoMoreInteractions(nettyOptions);
98+ }
10399 }
modified driver-core/src/test/java/com/datastax/driver/core/RecommissionedNodeTest.java +39 −17
@@ -39,12 +39,16 @@
3939 public class RecommissionedNodeTest {
4040 private static final Logger logger = LoggerFactory.getLogger(RecommissionedNodeTest.class);
4141
42- CCMBridge mainCcm, otherCcm;
42+ CCMBridge.Builder mainCcmBuilder, otherCcmBuilder;
43+ CCMAccess mainCcm, otherCcm;
4344 Cluster mainCluster;
4445
4546 @Test(groups = "long")
4647 public void should_ignore_recommissioned_node_on_reconnection_attempt() throws Exception {
47- mainCcm = CCMBridge.builder().withNodes(3).build();
48+ mainCcmBuilder = CCMBridge.builder().withNodes(3).notStarted();
49+ mainCcm = CCMCache.get(mainCcmBuilder);
50+ mainCcm.start();
51+
4852 // node1 will be our "recommissioned" node, for now we just stop it so that it stays in the peers table.
4953 mainCcm.stop(1);
5054 mainCcm.waitForDown(1);
@@ -59,11 +63,13 @@
5963 // From that point, reconnections to node1 have been scheduled.
6064
6165 // Start another ccm that will reuse node1's address
62- otherCcm = CCMBridge.builder()
66+ otherCcmBuilder = CCMBridge.builder()
6367 .withStoragePort(mainCcm.getStoragePort())
6468 .withThriftPort(mainCcm.getThriftPort())
6569 .withBinaryPort(mainCcm.getBinaryPort())
66- .withNodes(1).build();
70+ .withNodes(1).notStarted();
71+ otherCcm = CCMCache.get(otherCcmBuilder);
72+ otherCcm.start();
6773 otherCcm.waitForUp(1);
6874
6975 // Give the driver the time to notice the node is back up and try to connect to it.
@@ -74,7 +80,9 @@
7480
7581 @Test(groups = "long")
7682 public void should_ignore_recommissioned_node_on_control_connection_reconnect() throws Exception {
77- mainCcm = CCMBridge.builder().withNodes(2).build();
83+ mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
84+ mainCcm = CCMCache.get(mainCcmBuilder);
85+ mainCcm.start();
7886 mainCcm.stop(1);
7987 mainCcm.waitForDown(1);
8088
@@ -87,11 +95,13 @@
8795 waitForCountUpHosts(mainCluster, 1);
8896
8997 // Start another ccm that will reuse node1's address
90- otherCcm = CCMBridge.builder()
98+ otherCcmBuilder = CCMBridge.builder()
9199 .withStoragePort(mainCcm.getStoragePort())
92100 .withThriftPort(mainCcm.getThriftPort())
93101 .withBinaryPort(mainCcm.getBinaryPort())
94- .withNodes(1).build();
102+ .withNodes(1).notStarted();
103+ otherCcm = CCMCache.get(otherCcmBuilder);
104+ otherCcm.start();
95105 otherCcm.waitForUp(1);
96106
97107 // Stop node2, the control connection gets defunct
@@ -105,15 +115,19 @@
105115 @Test(groups = "long")
106116 public void should_ignore_recommissioned_node_on_session_init() throws Exception {
107117 // Simulate the bug before starting the cluster
108- mainCcm = CCMBridge.builder().withNodes(2).build();
118+ mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
119+ mainCcm = CCMCache.get(mainCcmBuilder);
120+ mainCcm.start();
109121 mainCcm.stop(1);
110122 mainCcm.waitForDown(1);
111123
112- otherCcm = CCMBridge.builder()
124+ otherCcmBuilder = CCMBridge.builder()
113125 .withStoragePort(mainCcm.getStoragePort())
114126 .withThriftPort(mainCcm.getThriftPort())
115127 .withBinaryPort(mainCcm.getBinaryPort())
116- .withNodes(1).build();
128+ .withNodes(1).notStarted();
129+ otherCcm = CCMCache.get(otherCcmBuilder);
130+ otherCcm.start();
117131 otherCcm.waitForUp(1);
118132
119133 // Start the driver, it should only connect to node 2
@@ -140,16 +154,19 @@
140154 @CassandraVersion(major = 2.0)
141155 public void should_ignore_node_that_does_not_support_protocol_version_on_session_init() throws Exception {
142156 // Simulate the bug before starting the cluster
143- mainCcm = CCMBridge.builder().withNodes(2).build();
157+ mainCcmBuilder = CCMBridge.builder().withNodes(2).notStarted();
158+ mainCcm = CCMCache.get(mainCcmBuilder);
159+ mainCcm.start();
144160 mainCcm.stop(1);
145161 mainCcm.waitForDown(1);
146162
147- otherCcm = CCMBridge.builder().withNodes(1)
163+ otherCcmBuilder = CCMBridge.builder().withNodes(1)
148164 .withStoragePort(mainCcm.getStoragePort())
149165 .withThriftPort(mainCcm.getThriftPort())
150166 .withBinaryPort(mainCcm.getBinaryPort())
151- .withVersion("1.2.19")
152- .build();
167+ .withVersion("1.2.19").notStarted();
168+ otherCcm = CCMCache.get(otherCcmBuilder);
169+ otherCcm.start();
153170 otherCcm.waitForUp(1);
154171
155172 // Start the driver, it should only connect to node 2
@@ -172,6 +189,8 @@
172189 public void clearFields() {
173190 // Clear cluster and ccm instances between tests.
174191 mainCluster = null;
192+ mainCcmBuilder = null;
193+ otherCcmBuilder = null;
175194 mainCcm = null;
176195 otherCcm = null;
177196 }
@@ -180,11 +199,14 @@
180199 public void teardown() {
181200 if (mainCluster != null)
182201 mainCluster.close();
183-
202+ if (mainCcmBuilder != null)
203+ CCMCache.remove(mainCcmBuilder);
204+ if (otherCcmBuilder != null)
205+ CCMCache.remove(otherCcmBuilder);
184206 if (mainCcm != null)
185- mainCcm.remove();
207+ mainCcm.close();
186208 if (otherCcm != null)
187- otherCcm.remove();
209+ otherCcm.close();
188210 }
189211
190212 private static int countUpHosts(Cluster cluster) {
modified driver-core/src/test/java/com/datastax/driver/core/SessionStressTest.java +10 −2
@@ -59,6 +59,9 @@
5959 fail("executor ran for longer than expected");
6060 } catch (InterruptedException e) {
6161 fail("Interrupted while waiting for executor to shutdown");
62+ } finally {
63+ executorService = null;
64+ System.gc();
6265 }
6366 }
6467
@@ -175,6 +178,7 @@
175178 }
176179 } finally {
177180 stressCluster.close();
181+ stressCluster = null;
178182
179183 // Ensure no channels remain open.
180184 assertEquals(channelMonitor.openChannels(getInitialContactPoints()).size(), 0);
@@ -263,7 +267,7 @@
263267 }
264268
265269 private static class CloseSession implements Callable<CloseFuture> {
266- private final Session session;
270+ private Session session;
267271 private final CountDownLatch startSignal;
268272
269273 CloseSession(Session session, CountDownLatch startSignal) {
@@ -274,7 +278,11 @@
274278 @Override
275279 public CloseFuture call() throws Exception {
276280 startSignal.await();
277- return session.closeAsync();
281+ try {
282+ return session.closeAsync();
283+ } finally {
284+ session = null;
285+ }
278286 }
279287 }
280288 }
modified driver-core/src/test/java/com/datastax/driver/core/policies/TokenAwarePolicyTest.java +35 −40
@@ -26,9 +26,12 @@
2626 import java.util.List;
2727
2828 import static com.datastax.driver.core.Assertions.assertThat;
29+import static com.datastax.driver.core.CreateCCM.TestMode.PER_METHOD;
2930 import static com.datastax.driver.core.TestUtils.*;
3031
31-public class TokenAwarePolicyTest {
32+@CreateCCM(PER_METHOD)
33+@CCMConfig(createCcm = false)
34+public class TokenAwarePolicyTest extends CCMTestsSupport {
3235
3336 QueryTracker queryTracker;
3437
@@ -314,51 +317,43 @@
314317 * @test_category load_balancing:token_aware
315318 * @jira_ticket JAVA-123 (to ensure routing key buffers are not destroyed).
316319 */
320+ @CCMConfig(createCcm = true, numberOfNodes = 3, createCluster = false)
317321 @Test(groups = "long")
318322 public void should_properly_generate_and_use_routing_key_for_composite_partition_key() {
319323 // given: a 3 node cluster with a keyspace with RF 1.
320- CCMBridge ccm = CCMBridge.builder().withNodes(3).notStarted().build();
321-
322- Cluster cluster = Cluster.builder()
324+ Cluster cluster = register(Cluster.builder()
323325 .withLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
324326 .addContactPointsWithPorts(ccm.addressOfNode(1))
325327 .withPort(ccm.getBinaryPort())
326- .build();
327-
328- try {
329- ccm.start();
330- Session session = cluster.connect();
331-
332- String table = "composite";
333- session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, SIMPLE_KEYSPACE, 1));
334- session.execute("USE " + SIMPLE_KEYSPACE);
335- session.execute(String.format("CREATE TABLE %s (k1 int, k2 int, i int, PRIMARY KEY ((k1, k2)))", table));
336-
337- // (1,2) resolves to token '4881097376275569167' which belongs to node 1 so all queries should go to that node.
338- PreparedStatement insertPs = session.prepare("INSERT INTO " + table + "(k1, k2, i) VALUES (?, ?, ?)");
339- BoundStatement insertBs = insertPs.bind(1, 2, 3);
340-
341- PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
342- BoundStatement selectBs = selectPs.bind(1, 2);
343-
344- // when: executing a prepared statement with a composite partition key.
345- // then: should query the correct node (1) in for both insert and select queries.
346- for (int i = 0; i < 10; i++) {
347- ResultSet rs = session.execute(insertBs);
348- assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
349-
350- rs = session.execute(selectBs);
351- assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
352- assertThat(rs.isExhausted()).isFalse();
353- Row r = rs.one();
354- assertThat(rs.isExhausted()).isTrue();
355-
356- assertThat(r.getInt("i")).isEqualTo(3);
357- }
358-
359- } finally {
360- cluster.close();
361- ccm.remove();
328+ .build());
329+ Session session = cluster.connect();
330+
331+ String table = "composite";
332+ String ks = TestUtils.getAvailableKeyspaceName();
333+ session.execute(String.format(CREATE_KEYSPACE_SIMPLE_FORMAT, ks, 1));
334+ session.execute("USE " + ks);
335+ session.execute(String.format("CREATE TABLE %s (k1 int, k2 int, i int, PRIMARY KEY ((k1, k2)))", table));
336+
337+ // (1,2) resolves to token '4881097376275569167' which belongs to node 1 so all queries should go to that node.
338+ PreparedStatement insertPs = session.prepare("INSERT INTO " + table + "(k1, k2, i) VALUES (?, ?, ?)");
339+ BoundStatement insertBs = insertPs.bind(1, 2, 3);
340+
341+ PreparedStatement selectPs = session.prepare("SELECT * FROM " + table + " WHERE k1=? and k2=?");
342+ BoundStatement selectBs = selectPs.bind(1, 2);
343+
344+ // when: executing a prepared statement with a composite partition key.
345+ // then: should query the correct node (1) in for both insert and select queries.
346+ for (int i = 0; i < 10; i++) {
347+ ResultSet rs = session.execute(insertBs);
348+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
349+
350+ rs = session.execute(selectBs);
351+ assertThat(rs.getExecutionInfo().getQueriedHost()).isEqualTo(TestUtils.findHost(cluster, 1));
352+ assertThat(rs.isExhausted()).isFalse();
353+ Row r = rs.one();
354+ assertThat(rs.isExhausted()).isTrue();
355+
356+ assertThat(r.getInt("i")).isEqualTo(3);
362357 }
363358 }
364359 }
modified driver-core/src/test/resources/log4j.properties +1 −0
@@ -41,6 +41,7 @@
4141
4242 # Adjust log levels for CCM tests
4343 #log4j.logger.com.datastax.driver.core.CCMTestsSupport=DEBUG
44+#log4j.logger.com.datastax.driver.core.CCMCache=DEBUG
4445 #log4j.logger.com.datastax.driver.core.CCMBridge=DEBUG
4546
4647 # A1 is set to be a ConsoleAppender.
modified driver-mapping/src/test/java/com/datastax/driver/mapping/UDTFieldMapperTest.java +82 −103
@@ -15,7 +15,8 @@
1515 */
1616 package com.datastax.driver.mapping;
1717
18-import com.datastax.driver.core.CCMBridge;
18+import com.datastax.driver.core.CCMConfig;
19+import com.datastax.driver.core.CCMTestsSupport;
1920 import com.datastax.driver.core.Cluster;
2021 import com.datastax.driver.core.Session;
2122 import com.datastax.driver.core.utils.CassandraVersion;
@@ -27,116 +28,94 @@
2728 import java.util.Map;
2829
2930 @CassandraVersion(major = 2.1)
31+@CCMConfig(createCluster = false)
3032 @SuppressWarnings("unused")
31-public class UDTFieldMapperTest {
33+public class UDTFieldMapperTest extends CCMTestsSupport {
3234
3335 @Test(groups = "short")
3436 public void udt_and_tables_with_ks_created_in_another_session_should_be_mapped() {
35- CCMBridge ccm = null;
36- Cluster cluster = null;
37-
38- try {
39- // Create type and table
40- ccm = CCMBridge.builder().build();
41- cluster = Cluster.builder()
42- .addContactPointsWithPorts(ccm.addressOfNode(1))
43- .withPort(ccm.getBinaryPort())
44- .build();
45- Session session1 = cluster.connect();
46- session1.execute("create schema if not exists java_509 " +
47- "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
48- session1.execute("create type java_509.my_tuple (" +
49- "type text, " +
50- "value text);");
51- session1.execute("create table java_509.my_hash (" +
52- "key int primary key, " +
53- "properties map<text, frozen<java_509.my_tuple>>);");
54- cluster.close();
55-
56- // Create entities with another connection
57- cluster = Cluster.builder()
58- .addContactPointsWithPorts(ccm.addressOfNode(1))
59- .withPort(ccm.getBinaryPort())
60- .build();
61- Session session2 = cluster.newSession();
62- Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class);
63- hashMapper.save(new MyHashWithKeyspace(
64- 1,
65- ImmutableMap.of("key-1", new MyTupleWithKeyspace("first-half-1", "second-half-1"))));
66- hashMapper.save(new MyHashWithKeyspace(
67- 2,
68- ImmutableMap.of("key-2", new MyTupleWithKeyspace("first-half-2", null))));
69- hashMapper.save(new MyHashWithKeyspace(
70- 3,
71- ImmutableMap.of("key-3", new MyTupleWithKeyspace(null, "second-half-3"))));
72- hashMapper.save(new MyHashWithKeyspace(
73- 4,
74- new HashMap<String, MyTupleWithKeyspace>()));
75- hashMapper.save(new MyHashWithKeyspace(
76- 5,
77- null));
78- } finally {
79- if (cluster != null)
80- cluster.close();
81- if (ccm != null)
82- ccm.remove();
83- }
37+ Cluster cluster = register(Cluster.builder()
38+ .addContactPointsWithPorts(ccm.addressOfNode(1))
39+ .withPort(ccm.getBinaryPort())
40+ .build());
41+ Session session1 = cluster.connect();
42+ // Create type and table
43+ session1.execute("create schema if not exists java_509 " +
44+ "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
45+ session1.execute("create type java_509.my_tuple (" +
46+ "type text, " +
47+ "value text);");
48+ session1.execute("create table java_509.my_hash (" +
49+ "key int primary key, " +
50+ "properties map<text, frozen<java_509.my_tuple>>);");
51+ cluster.close();
52+
53+ // Create entities with another connection
54+ cluster = register(Cluster.builder()
55+ .addContactPointsWithPorts(ccm.addressOfNode(1))
56+ .withPort(ccm.getBinaryPort())
57+ .build());
58+ Session session2 = cluster.newSession();
59+ Mapper<MyHashWithKeyspace> hashMapper = new MappingManager(session2).mapper(MyHashWithKeyspace.class);
60+ hashMapper.save(new MyHashWithKeyspace(
61+ 1,
62+ ImmutableMap.of("key-1", new MyTupleWithKeyspace("first-half-1", "second-half-1"))));
63+ hashMapper.save(new MyHashWithKeyspace(
64+ 2,
65+ ImmutableMap.of("key-2", new MyTupleWithKeyspace("first-half-2", null))));
66+ hashMapper.save(new MyHashWithKeyspace(
67+ 3,
68+ ImmutableMap.of("key-3", new MyTupleWithKeyspace(null, "second-half-3"))));
69+ hashMapper.save(new MyHashWithKeyspace(
70+ 4,
71+ new HashMap<String, MyTupleWithKeyspace>()));
72+ hashMapper.save(new MyHashWithKeyspace(
73+ 5,
74+ null));
8475 }
8576
8677 @Test(groups = "short")
8778 public void udt_and_tables_without_ks_created_in_another_session_should_be_mapped() {
88- CCMBridge ccm = null;
89- Cluster cluster = null;
90-
91- try {
92- // Create type and table
93- ccm = CCMBridge.builder().build();
94- cluster = Cluster.builder()
95- .addContactPointsWithPorts(ccm.addressOfNode(1))
96- .withPort(ccm.getBinaryPort())
97- .build();
98- Session session1 = cluster.connect();
99- session1.execute("create schema if not exists java_509 " +
100- "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
101- session1.execute("use java_509");
102- session1.execute("create type my_tuple (" +
103- "type text, " +
104- "value text);");
105- session1.execute("create table my_hash (" +
106- "key int primary key, " +
107- "properties map<text, frozen<my_tuple>>);");
108- cluster.close();
109-
110- // Create entities with another connection
111- cluster = Cluster.builder()
112- .addContactPointsWithPorts(ccm.addressOfNode(1))
113- .withPort(ccm.getBinaryPort())
114- .build();
115- Session session2 = cluster.newSession();
116-
117- session2.execute("use java_509");
118- Mapper<MyHash> hashMapper = new MappingManager(session2).mapper(MyHash.class);
119- hashMapper.save(new MyHash(
120- 1,
121- ImmutableMap.of("key-1", new MyTuple("first-half-1", "second-half-1"))));
122- hashMapper.save(new MyHash(
123- 2,
124- ImmutableMap.of("key-2", new MyTuple("first-half-2", null))));
125- hashMapper.save(new MyHash(
126- 3,
127- ImmutableMap.of("key-3", new MyTuple(null, "second-half-3"))));
128- hashMapper.save(new MyHash(
129- 4,
130- new HashMap<String, MyTuple>()));
131- hashMapper.save(new MyHash(
132- 5,
133- null));
134- } finally {
135- if (cluster != null)
136- cluster.close();
137- if (ccm != null)
138- ccm.remove();
139- }
79+ Cluster cluster = register(Cluster.builder()
80+ .addContactPointsWithPorts(ccm.addressOfNode(1))
81+ .withPort(ccm.getBinaryPort())
82+ .build());
83+ Session session1 = cluster.connect();
84+ session1.execute("create schema if not exists java_509b " +
85+ "with replication = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };");
86+ session1.execute("use java_509b");
87+ session1.execute("create type my_tuple (" +
88+ "type text, " +
89+ "value text);");
90+ session1.execute("create table my_hash (" +
91+ "key int primary key, " +
92+ "properties map<text, frozen<my_tuple>>);");
93+ cluster.close();
94+
95+ // Create entities with another connection
96+ cluster = Cluster.builder()
97+ .addContactPointsWithPorts(ccm.addressOfNode(1))
98+ .withPort(ccm.getBinaryPort())
99+ .build();
100+ Session session2 = cluster.newSession();
101+
102+ session2.execute("use java_509b");
103+ Mapper<MyHash> hashMapper = new MappingManager(session2).mapper(MyHash.class);
104+ hashMapper.save(new MyHash(
105+ 1,
106+ ImmutableMap.of("key-1", new MyTuple("first-half-1", "second-half-1"))));
107+ hashMapper.save(new MyHash(
108+ 2,
109+ ImmutableMap.of("key-2", new MyTuple("first-half-2", null))));
110+ hashMapper.save(new MyHash(
111+ 3,
112+ ImmutableMap.of("key-3", new MyTuple(null, "second-half-3"))));
113+ hashMapper.save(new MyHash(
114+ 4,
115+ new HashMap<String, MyTuple>()));
116+ hashMapper.save(new MyHash(
117+ 5,
118+ null));
140119 }
141120
142121 @UDT(name = "my_tuple")